car-server-core 0.14.0

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

use crate::session::{A2aRouteAuth, ServerState, WsChannel};
use car_proto::*;
use car_verify;
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::atomic::AtomicU64;
use std::sync::Arc;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio_tungstenite::{accept_async, tungstenite::Message};
use tracing::{info, instrument};

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
pub struct JsonRpcMessage {
    #[serde(default)]
    pub jsonrpc: String,
    #[serde(default)]
    pub method: Option<String>,
    #[serde(default)]
    pub params: Value,
    #[serde(default)]
    pub id: Value,
    // Response fields
    #[serde(default)]
    pub result: Option<Value>,
    #[serde(default)]
    pub error: Option<Value>,
}

#[derive(Debug, Serialize)]
pub struct JsonRpcResponse {
    pub jsonrpc: &'static str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<JsonRpcError>,
    pub id: Value,
}

#[derive(Debug, Serialize)]
pub struct JsonRpcError {
    pub code: i32,
    pub message: String,
}

impl JsonRpcResponse {
    pub fn success(id: Value, result: Value) -> Self {
        Self {
            jsonrpc: "2.0",
            result: Some(result),
            error: None,
            id,
        }
    }
    pub fn error(id: Value, code: i32, message: &str) -> Self {
        Self {
            jsonrpc: "2.0",
            result: None,
            error: Some(JsonRpcError {
                code,
                message: message.to_string(),
            }),
            id,
        }
    }
}

/// Convenience wrapper for the standalone `car-server` binary: accepts
/// the WebSocket handshake on a raw [`TcpStream`] then delegates to
/// [`run_dispatch`]. Embedders that already have a handshake-completed
/// `WebSocketStream` skip this and call `run_dispatch` directly.
#[instrument(
    name = "ws.connection",
    skip_all,
    fields(peer = %peer),
)]
pub async fn handle_connection(
    stream: TcpStream,
    peer: SocketAddr,
    state: Arc<ServerState>,
) -> Result<(), Box<dyn std::error::Error>> {
    let ws_stream = accept_async(stream).await?;
    let (write, read) = ws_stream.split();
    run_dispatch(read, Box::pin(write), peer.to_string(), state).await
}

/// Convenience wrapper for the daemon-as-default Unix-socket
/// listener. Same shape as [`handle_connection`] but accepts a
/// `UnixStream` — used by the per-user UDS listener in
/// `car-server::main` (default transport for FFI thin clients,
/// since UDS is faster + permission-scoped vs localhost TCP).
///
/// Unix-only — `tokio::net::UnixStream` is gated on
/// `cfg(all(unix, feature = "net"))`. On Windows the daemon binds
/// only the TCP listener (loopback) and this entry point is
/// compiled out; consumers must use `handle_connection` instead.
#[cfg(unix)]
#[instrument(
    name = "ws.connection",
    skip_all,
    fields(peer = %peer),
)]
pub async fn handle_connection_unix(
    stream: tokio::net::UnixStream,
    peer: String,
    state: Arc<ServerState>,
) -> Result<(), Box<dyn std::error::Error>> {
    let ws_stream = tokio_tungstenite::accept_async(stream).await?;
    let (write, read) = ws_stream.split();
    run_dispatch(read, Box::pin(write), peer, state).await
}

/// Transport-neutral entry point: drives the JSON-RPC dispatch loop
/// against an already-handshake-completed split WebSocket. Generic
/// over the read half (any `Stream<Item = Result<Message, WsError>>`)
/// and the write half (a [`WsSink`] — type-erased so this function
/// doesn't templatize every downstream consumer of `WsChannel`).
///
/// `peer` is a free-form string ("127.0.0.1:1234" for TCP,
/// "uds:/path/sock" for UDS, "axum:..." for embedders) — used only
/// for tracing fields, never for dispatch logic.
#[instrument(
    name = "ws.dispatch",
    skip_all,
    fields(client_id = tracing::field::Empty, peer = %peer),
)]
pub async fn run_dispatch<R>(
    mut read: R,
    write: crate::session::WsSink,
    peer: String,
    state: Arc<ServerState>,
) -> Result<(), Box<dyn std::error::Error>>
where
    R: futures::Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>>
        + Unpin
        + Send,
{
    let client_id = uuid::Uuid::new_v4().simple().to_string()[..12].to_string();
    tracing::Span::current().record("client_id", &client_id.as_str());

    info!("New connection from {}", peer);

    let channel = Arc::new(WsChannel {
        write: Mutex::new(write),
        pending: Mutex::new(HashMap::new()),
        next_id: AtomicU64::new(1),
    });

    let session = state.create_session(&client_id, channel.clone()).await;

    // car#209: per-request handlers are spawned detached (below) and
    // each clones `Arc<ClientSession>` → `Arc<WsChannel>`. A bare
    // `tokio::spawn` outlives the connection, so a slow/hung handler
    // pins the split sink and the inbound socket lingers in CLOSED
    // until the daemon hits EMFILE. Own them in a per-connection
    // `JoinSet` so every in-flight handler is aborted the instant the
    // WS drops (`abort_all` in the cleanup block; `JoinSet`'s Drop
    // also aborts on any early return), releasing the FD immediately.
    let mut conn_tasks: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();

    while let Some(msg) = read.next().await {
        // Reap finished handlers so a long-lived connection doesn't
        // retain their `JoinHandle`s unbounded (memory, not FDs).
        while conn_tasks.try_join_next().is_some() {}

        // car#209: on an abrupt transport error (peer reset / network
        // drop — the trader crash-loop case) `read.next()` yields
        // `Some(Err(_))`. The old `let msg = msg?;` propagated that
        // out of the function, *skipping the cleanup block below*, so
        // `state.sessions` (+ the host/a2ui/chat registries) kept the
        // session + channel — and thus the socket FD — forever. Break
        // instead: every disconnect, clean or not, runs the single
        // cleanup path.
        let msg = match msg {
            Ok(m) => m,
            Err(e) => {
                info!("read error from {}: {}; closing", client_id, e);
                break;
            }
        };
        if msg.is_text() {
            let text = match msg.to_text() {
                Ok(t) => t,
                Err(e) => {
                    info!("non-text frame from {}: {}; closing", client_id, e);
                    break;
                }
            };
            let parsed: JsonRpcMessage = match serde_json::from_str(text) {
                Ok(m) => m,
                Err(e) => {
                    send_response(
                        &session.channel,
                        JsonRpcResponse::error(Value::Null, -32700, &format!("Parse error: {}", e)),
                    )
                    .await
                    .ok();
                    continue;
                }
            };

            // Is this a response to a pending tool callback?
            if parsed.method.is_none() && (parsed.result.is_some() || parsed.error.is_some()) {
                if let Some(id_str) = parsed.id.as_str() {
                    let mut pending = session.channel.pending.lock().await;
                    if let Some(tx) = pending.remove(id_str) {
                        let tool_resp = if let Some(result) = parsed.result {
                            ToolExecuteResponse {
                                action_id: id_str.to_string(),
                                output: Some(result),
                                error: None,
                            }
                        } else {
                            let err_msg = parsed
                                .error
                                .as_ref()
                                .and_then(|e| e.get("message"))
                                .and_then(|m| m.as_str())
                                .unwrap_or("unknown error")
                                .to_string();
                            ToolExecuteResponse {
                                action_id: id_str.to_string(),
                                output: None,
                                error: Some(err_msg),
                            }
                        };
                        let _ = tx.send(tool_resp);
                        continue;
                    }
                }
            }

            // Agent → host chat-event interceptor. `agent.chat.event`
            // notifications coming up the WS from a connected agent
            // are forwarded to the originating host's channel as
            // `agents.chat.event`. Lives ahead of the regular method
            // dispatch so the dispatcher doesn't reply with
            // "method-not-found" on what is a fire-and-forget
            // notification (no id). See
            // `docs/proposals/agent-chat-surface.md`.
            if try_forward_agent_chat_event(&parsed, &state).await {
                continue;
            }

            // Otherwise it's a client request
            if let Some(method) = &parsed.method {
                info!(method = %method, "dispatching JSON-RPC method");

                // Auth gate (Parslee-ai/car-releases#32). When the
                // server has an auth token installed, every method
                // other than `session.auth` is rejected on
                // unauthenticated sessions and the connection is
                // closed after the error response goes out. When no
                // token is installed (default), this branch never
                // fires — preserves pre-#32 behaviour.
                if state.auth_token.get().is_some()
                    && !session
                        .authenticated
                        .load(std::sync::atomic::Ordering::Acquire)
                    && method != "session.auth"
                {
                    let resp = JsonRpcResponse::error(
                        parsed.id.clone(),
                        -32001,
                        "auth required: send `session.auth` with the per-launch token \
                         from ~/Library/Application Support/ai.parslee.car/auth-token \
                         (macOS) or $XDG_RUNTIME_DIR/ai.parslee.car/auth-token (Linux) \
                         as the first frame on this connection",
                    );
                    let _ = send_response(&session.channel, resp).await;
                    info!(client = %client_id, method = %method,
                        "rejecting non-auth method on unauthenticated session; closing");
                    break;
                }

                // Approval gate (audit 2026-05). High-risk methods —
                // anything that drives macOS automation or sends
                // messages on the user's behalf — must be acked by
                // the user via `host.resolve_approval` before they
                // dispatch. The gate raises an `approval.requested`
                // host event the local UI can render approve/deny on,
                // then parks until resolved or the configured
                // timeout fires. Returns a JSON-RPC error and
                // continues the dispatch loop on deny / timeout —
                // no connection close, since the caller may want to
                // retry with revised parameters.
                if state.approval_gate.requires_approval(method.as_str()) {
                    match gate_high_risk_method(method.as_str(), &parsed.params, &state).await {
                        Ok(()) => {}
                        Err(reason) => {
                            let resp = JsonRpcResponse::error(parsed.id.clone(), -32003, &reason);
                            let _ = send_response(&session.channel, resp).await;
                            info!(
                                client = %client_id,
                                method = %method,
                                reason = %reason,
                                "approval gate blocked dispatch"
                            );
                            continue;
                        }
                    }
                }

                // Spawn the per-method dispatch in a task so the read
                // loop keeps reading frames. Without this, methods
                // that trigger server-initiated `tools.execute`
                // callbacks (`proposal.submit`, `workflow.run`,
                // `multi.*` paths that fire a registered tool)
                // deadlock the connection: the handler awaits the
                // callback response on a oneshot, but the response is
                // another frame on this same read half — which the
                // synchronous `.await` here would prevent the loop
                // from ever picking up. Surfaced by the
                // `executeProposal: echo tool via JS callback` smoke
                // (#173). Response ordering becomes id-keyed (the
                // JSON-RPC demuxing contract) rather than
                // arrival-ordered.
                let session_task = session.clone();
                let state_task = state.clone();
                let method_owned = method.clone();
                let parsed_task = parsed;
                // car#209: owned by the per-connection JoinSet so it's
                // aborted on disconnect instead of leaking the channel.
                conn_tasks.spawn(async move {
                    let session = session_task;
                    let state = state_task;
                    let parsed = parsed_task;
                    let result = match method_owned.as_str() {
                        "session.auth" => handle_session_auth(&parsed, &session, &state).await,
                        "parslee.auth" => handle_parslee_auth().await,
                        "auth.start" => handle_auth_start(&parsed).await,
                        "auth.complete" => handle_auth_complete(&parsed).await,
                        "auth.status" => handle_auth_status().await,
                        "auth.logout" => handle_auth_logout().await,
                        "session.init" => handle_session_init(&parsed, &session).await,
                        "host.subscribe" => handle_host_subscribe(&session, &state).await,
                        "host.agents" => handle_host_agents(&session).await,
                        "host.events" => handle_host_events(&parsed, &session).await,
                        "host.approvals" => handle_host_approvals(&session).await,
                        "host.register_agent" => {
                            handle_host_register_agent(&parsed, &session).await
                        }
                        "host.unregister_agent" => {
                            handle_host_unregister_agent(&parsed, &session).await
                        }
                        "host.set_status" => handle_host_set_status(&parsed, &session).await,
                        "host.notify" => handle_host_notify(&parsed, &session).await,
                        "host.request_approval" => {
                            handle_host_request_approval(&parsed, &session).await
                        }
                        "host.resolve_approval" => {
                            handle_host_resolve_approval(&parsed, &session).await
                        }
                        "tools.register" => handle_tools_register(&parsed, &session).await,
                        "proposal.submit" => handle_proposal_submit(&parsed, &session).await,
                        "policy.register" => handle_policy_register(&parsed, &session).await,
                        "session.policy.open" => handle_session_policy_open(&session).await,
                        "session.policy.close" => {
                            handle_session_policy_close(&parsed, &session).await
                        }
                        "verify" => handle_verify(&parsed, &session).await,
                        "state.get" => handle_state_get(&parsed, &session).await,
                        "state.set" => handle_state_set(&parsed, &session).await,
                        "state.exists" => handle_state_exists(&parsed, &session).await,
                        "state.keys" => handle_state_keys(&parsed, &session).await,
                        "state.snapshot" => handle_state_snapshot(&parsed, &session).await,
                        "memory.add_fact" => handle_memory_add_fact(&parsed, &session).await,
                        "memory.query" => handle_memory_query(&parsed, &session).await,
                        "memory.build_context" => {
                            handle_memory_build_context(&parsed, &session).await
                        }
                        "memory.build_context_fast" => {
                            handle_memory_build_context_fast(&parsed, &session).await
                        }
                        "memory.consolidate" => handle_memory_consolidate(&session).await,
                        "memory.fact_count" => handle_memory_fact_count(&session).await,
                        "memory.persist" => handle_memory_persist(&parsed, &session).await,
                        "memory.load" => handle_memory_load(&parsed, &session).await,
                        "skill.ingest" => handle_skill_ingest(&parsed, &session).await,
                        "skill.find" => handle_skill_find(&parsed, &session).await,
                        "skill.report" => handle_skill_report(&parsed, &session).await,
                        "skill.repair" => handle_skill_repair(&parsed, &session).await,
                        "skills.ingest_distilled" => {
                            handle_skills_ingest_distilled(&parsed, &session).await
                        }
                        "skills.evolve" => handle_skills_evolve(&parsed, &session).await,
                        "skills.domains_needing_evolution" => {
                            handle_skills_domains_needing_evolution(&parsed, &session).await
                        }
                        "multi.swarm" => handle_multi_swarm(&parsed, &session).await,
                        "multi.pipeline" => handle_multi_pipeline(&parsed, &session).await,
                        "multi.supervisor" => handle_multi_supervisor(&parsed, &session).await,
                        "multi.map_reduce" => handle_multi_map_reduce(&parsed, &session).await,
                        "multi.vote" => handle_multi_vote(&parsed, &session).await,
                        "scheduler.create" => handle_scheduler_create(&parsed),
                        "scheduler.run" => handle_scheduler_run(&parsed, &session).await,
                        "scheduler.run_loop" => handle_scheduler_run_loop(&parsed, &session).await,
                        "infer" => handle_infer(&parsed, &state, &session).await,
                        "image.generate" => handle_image_generate(&parsed, &state).await,
                        "video.generate" => handle_video_generate(&parsed, &state).await,
                        "embed" => handle_embed(&parsed, &state).await,
                        "classify" => handle_classify(&parsed, &state).await,
                        "tokenize" => handle_tokenize(&parsed, &state).await,
                        "detokenize" => handle_detokenize(&parsed, &state).await,
                        "rerank" => handle_rerank(&parsed, &state).await,
                        "transcribe" => handle_transcribe(&parsed, &state).await,
                        "synthesize" => handle_synthesize(&parsed, &state).await,
                        "infer_stream" => handle_infer_stream(&parsed, &session, &state).await,
                        "speech.prepare" => handle_speech_prepare(&state).await,
                        "models.route" => handle_models_route(&parsed, &state).await,
                        "models.stats" => handle_models_stats(&state).await,
                        "outcomes.resolve_pending" => {
                            handle_outcomes_resolve_pending(&parsed, &state).await
                        }
                        "events.count" => handle_events_count(&session).await,
                        "events.stats" => handle_events_stats(&session).await,
                        "events.truncate" => handle_events_truncate(&parsed, &session).await,
                        "events.clear" => handle_events_clear(&session).await,
                        "replan.set_config" => handle_replan_set_config(&parsed, &session).await,
                        "models.list" => handle_models_list(&state),
                        "models.register" => handle_models_register(&parsed, &state).await,
                        "models.unregister" => handle_models_unregister(&parsed, &state).await,
                        "models.list_unified" => handle_models_list_unified(&state),
                        "models.search" => handle_models_search(&parsed, &state),
                        "models.upgrades" => handle_models_upgrades(&state),
                        "models.pull" => handle_models_pull(&parsed, &state).await,
                        "models.install" => handle_models_pull(&parsed, &state).await,
                        "skills.distill" => handle_skills_distill(&parsed, &state).await,
                        "skills.list" => handle_skills_list(&parsed, &session).await,
                        "browser.run" => handle_browser_run(&parsed, &session).await,
                        "browser.close" => handle_browser_close(&session).await,
                        "secret.put" => handle_secret_put(&parsed),
                        "secret.get" => handle_secret_get(&parsed),
                        "secret.delete" => handle_secret_delete(&parsed),
                        "secret.status" => handle_secret_status(&parsed),
                        "secret.available" => Ok(car_ffi_common::secrets::is_available()),
                        "permissions.status" => handle_perm_status(&parsed),
                        "permissions.request" => handle_perm_request(&parsed),
                        "permissions.explain" => handle_perm_explain(&parsed),
                        "permissions.domains" => Ok(car_ffi_common::permissions::domains()),
                        "accounts.list" => car_ffi_common::accounts::list(),
                        "accounts.open" => {
                            #[derive(serde::Deserialize, Default)]
                            struct OpenParams {
                                #[serde(default)]
                                account_id: Option<String>,
                            }
                            let p: OpenParams =
                                serde_json::from_value(parsed.params.clone()).unwrap_or_default();
                            car_ffi_common::accounts::open_settings(p.account_id.as_deref())
                        }
                        "calendar.list" => car_ffi_common::integrations::calendar_list(),
                        "calendar.events" => handle_calendar_events(&parsed),
                        "contacts.containers" => {
                            car_ffi_common::integrations::contacts_containers()
                        }
                        "contacts.find" => handle_contacts_find(&parsed),
                        "mail.accounts" => car_ffi_common::integrations::mail_accounts(),
                        "mail.inbox" => handle_mail_inbox(&parsed),
                        "mail.send" => handle_mail_send(&parsed),
                        "messages.services" => car_ffi_common::integrations::messages_services(),
                        "messages.chats" => handle_messages_chats(&parsed),
                        "messages.send" => handle_messages_send(&parsed),
                        "notes.accounts" => car_ffi_common::integrations::notes_accounts(),
                        "notes.find" => handle_notes_find(&parsed),
                        "reminders.lists" => car_ffi_common::integrations::reminders_lists(),
                        "reminders.items" => handle_reminders_items(&parsed),
                        "photos.albums" => car_ffi_common::integrations::photos_albums(),
                        "bookmarks.list" => handle_bookmarks_list(&parsed),
                        "files.locations" => car_ffi_common::integrations::files_locations(),
                        "keychain.status" => car_ffi_common::integrations::keychain_status(),
                        "health.status" => car_ffi_common::health::status(),
                        "health.sleep" => handle_health_sleep(&parsed),
                        "health.workouts" => handle_health_workouts(&parsed),
                        "health.activity" => handle_health_activity(&parsed),
                        "voice.transcribe_stream.start" => {
                            handle_voice_transcribe_stream_start(&parsed, &state, &session).await
                        }
                        "voice.transcribe_stream.stop" => {
                            handle_voice_transcribe_stream_stop(&parsed, &state).await
                        }
                        "voice.transcribe_stream.push" => {
                            handle_voice_transcribe_stream_push(&parsed, &state).await
                        }
                        "voice.sessions.list" => Ok(handle_voice_sessions_list(&state)),
                        "voice.dispatch_turn" => {
                            handle_voice_dispatch_turn(&parsed, &state, &session).await
                        }
                        "voice.cancel_turn" => handle_voice_cancel_turn().await,
                        "voice.prewarm_turn" => handle_voice_prewarm_turn(&state).await,
                        "inference.register_runner" => {
                            handle_inference_register_runner(&session).await
                        }
                        "inference.runner.event" => handle_inference_runner_event(&parsed).await,
                        "inference.runner.complete" => {
                            handle_inference_runner_complete(&parsed).await
                        }
                        "inference.runner.fail" => handle_inference_runner_fail(&parsed).await,
                        "voice.providers.list" => {
                            // Stateless: enumerates STT/TTS providers compiled into
                            // this build. Runtime readiness (API key, permission,
                            // model download) is reported via per-provider errors.
                            serde_json::from_str::<serde_json::Value>(
                                &car_voice::list_voice_providers_json(),
                            )
                            .map_err(|e| e.to_string())
                        }
                        "voice.prepare_parakeet" => car_ffi_common::voice::prepare_parakeet()
                            .await
                            .and_then(|j| serde_json::from_str(&j).map_err(|e| e.to_string())),
                        "voice.prepare_diarizer" => car_ffi_common::voice::prepare_diarizer()
                            .await
                            .and_then(|j| serde_json::from_str(&j).map_err(|e| e.to_string())),
                        "voice.enroll_speaker" => handle_enroll_speaker(&parsed).await,
                        "voice.list_enrollments" => car_ffi_common::voice::list_enrollments()
                            .and_then(|j| serde_json::from_str(&j).map_err(|e| e.to_string())),
                        "voice.remove_enrollment" => handle_remove_enrollment(&parsed),
                        "workflow.run" => handle_workflow_run(&parsed, &session).await,
                        "workflow.verify" => handle_workflow_verify(&parsed),
                        "meeting.start" => handle_meeting_start(&parsed, &state, &session).await,
                        "meeting.stop" => handle_meeting_stop(&parsed, &state, &session).await,
                        "meeting.list" => handle_meeting_list(&parsed),
                        "meeting.get" => handle_meeting_get(&parsed),
                        "registry.register" => handle_registry_register(&parsed),
                        "registry.heartbeat" => handle_registry_heartbeat(&parsed),
                        "registry.unregister" => handle_registry_unregister(&parsed),
                        "registry.list" => handle_registry_list(&parsed),
                        "registry.reap" => handle_registry_reap(&parsed),
                        "admission.status" => handle_admission_status(&state),
                        "a2a.start" => handle_a2a_start(&parsed, &session).await,
                        "a2a.stop" => handle_a2a_stop(),
                        "a2a.status" => handle_a2a_status(),
                        "a2a.send" => handle_a2a_send(&parsed, &state).await,
                        "a2ui.apply" => handle_a2ui_apply(&parsed, &state).await,
                        "a2ui.ingest" => handle_a2ui_ingest(&parsed, &state).await,
                        "a2ui.capabilities" => handle_a2ui_capabilities(&state),
                        "a2ui.reap" => handle_a2ui_reap(&state).await,
                        "a2ui.surfaces" => handle_a2ui_surfaces(&state).await,
                        "a2ui.get" => handle_a2ui_get(&parsed, &state).await,
                        "a2ui.action" => handle_a2ui_action(&parsed, &state).await,
                        "a2ui.render_report" => handle_a2ui_render_report(&parsed, &state).await,
                        "a2ui/subscribe" => handle_a2ui_subscribe(&session, &state).await,
                        "a2ui/unsubscribe" => handle_a2ui_unsubscribe(&session, &state).await,
                        "a2ui/replay" => handle_a2ui_replay(&parsed, &state).await,
                        "automation.run_applescript" => handle_run_applescript(&parsed).await,
                        "automation.shortcuts.list" => handle_list_shortcuts(&parsed).await,
                        "automation.shortcuts.run" => handle_run_shortcut(&parsed).await,
                        "notifications.local" => handle_local_notification(&parsed).await,
                        "vision.ocr" => handle_vision_ocr(&parsed).await,
                        "agents.list" => handle_agents_list(&state).await,
                        "agents.health" => handle_agents_health(&state).await,
                        "agents.upsert" => handle_agents_upsert(&parsed, &state).await,
                        "agents.install" => handle_agents_install(&parsed, &state).await,
                        "agents.remove" => handle_agents_remove(&parsed, &state).await,
                        "agents.start" => handle_agents_start(&parsed, &state).await,
                        "agents.stop" => handle_agents_stop(&parsed, &state).await,
                        "agents.restart" => handle_agents_restart(&parsed, &state).await,
                        "agents.tail_log" => handle_agents_tail_log(&parsed, &state).await,
                        "agents.list_external" => handle_agents_list_external(&parsed).await,
                        "agents.detect_external" => handle_agents_detect_external(&parsed).await,
                        "agents.health_external" => handle_agents_health_external(&parsed).await,
                        "agents.invoke_external" => {
                            handle_agents_invoke_external(&parsed, &state, &session).await
                        }
                        "agents.chat" => handle_agents_chat(&parsed, &state, &session).await,
                        "agents.chat.cancel" => handle_agents_chat_cancel(&parsed, &state).await,
                        // A2A v1.0 (PascalCase) + v0.3 (slash form) — both
                        // alias to the same in-core dispatcher per
                        // Parslee-ai/car-releases#28. Embedders that need a
                        // custom AgentCardSource / TaskStore plug them in
                        // via ServerStateConfig::with_a2a_card_source /
                        // with_a2a_store before any handler runs.
                        "message/send"
                        | "SendMessage"
                        | "message/stream"
                        | "SendStreamingMessage"
                        | "tasks/get"
                        | "GetTask"
                        | "tasks/list"
                        | "ListTasks"
                        | "tasks/cancel"
                        | "CancelTask"
                        | "tasks/resubscribe"
                        | "SubscribeToTask"
                        | "tasks/pushNotificationConfig/set"
                        | "CreateTaskPushNotificationConfig"
                        | "tasks/pushNotificationConfig/get"
                        | "GetTaskPushNotificationConfig"
                        | "tasks/pushNotificationConfig/list"
                        | "ListTaskPushNotificationConfigs"
                        | "tasks/pushNotificationConfig/delete"
                        | "DeleteTaskPushNotificationConfig"
                        | "agent/getAuthenticatedExtendedCard"
                        | "GetExtendedAgentCard" => {
                            handle_a2a_dispatch(method_owned.as_str(), &parsed, &state).await
                        }
                        _ => Err(format!("unknown method: {}", method_owned)),
                    };

                    let resp = match result {
                        Ok(value) => JsonRpcResponse::success(parsed.id, value),
                        Err(e) => JsonRpcResponse::error(parsed.id, -32603, &e),
                    };
                    let _ = send_response(&session.channel, resp).await;
                });
            }
        } else if msg.is_close() {
            info!("Client {} disconnected", client_id);
            break;
        }
    }

    // car#209: abort every in-flight handler for this connection
    // *first* — they each hold an `Arc<ClientSession>` → `Arc<WsChannel>`
    // clone; until they're gone the split sink (and the inbound socket
    // FD) can't drop, even after the registries below are cleared.
    conn_tasks.abort_all();

    session.host.unsubscribe(&client_id).await;
    // Auto-cancel this session's pending approvals so the queue stays
    // in sync with what's actually decidable — covers graceful
    // unregister+close, hard crash (TCP reset), and ping timeout in
    // one place. System-level gate approvals (client_id None) are not
    // touched. car-releases#48.
    session.host.reap_session_approvals(&client_id).await;
    state.a2ui_subscribers.lock().await.remove(&client_id);

    // Fix for MULTI-4 / WS-3: drop the session from the registry and
    // drain any pending tool callbacks. Without this, every connection
    // we ever accepted keeps an `Arc<ClientSession>` alive in
    // `state.sessions`, and outstanding `oneshot::Sender`s in
    // `session.channel.pending` outlive the closed connection until
    // their per-call timeout (60s). Dropping the senders here causes any
    // awaiting `recv()` in `WsToolExecutor::execute` to return
    // `RecvError` immediately, which the existing error-handler path
    // already maps to "callback channel closed" — same shape as the
    // timeout path, just faster.
    let _removed = state.remove_session(&client_id).await;
    {
        let mut pending = session.channel.pending.lock().await;
        pending.clear();
    }

    Ok(())
}

async fn send_response(
    channel: &WsChannel,
    resp: JsonRpcResponse,
) -> Result<(), Box<dyn std::error::Error>> {
    use futures::SinkExt;
    let json = serde_json::to_string(&resp)?;
    channel
        .write
        .lock()
        .await
        .send(Message::Text(json.into()))
        .await?;
    Ok(())
}

// --- Request handlers ---

async fn handle_host_subscribe(
    session: &crate::session::ClientSession,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    session
        .host
        .subscribe(&session.client_id, session.channel.clone())
        .await;
    serde_json::to_value(HostSnapshot {
        subscribed: true,
        agents: session.host.agents().await,
        approvals: session.host.approvals().await,
        events: session.host.events(50).await,
        identity: Some(daemon_identity(state)),
    })
    .map_err(|e| e.to_string())
}

/// Snapshot the daemon-identity facts for a fresh subscriber.
/// Cheap: non-acquiring reads on `OnceLock`s + a single
/// `to_string_lossy` on the manifest path. Critically uses
/// [`ServerState::supervisor_if_installed`] — not the lazy-init
/// `supervisor()` — so a Heisenberg subscribe can't *cause* the
/// daemon to acquire the manifest lock just by asking whether it
/// owns one.
fn daemon_identity(state: &Arc<ServerState>) -> car_proto::HostIdentity {
    // Observer takes precedence: when both supervisor and observer
    // markers are set (currently unreachable through the standalone
    // binary, but an embedder could install both racily), the
    // observer marker is the authoritative role since the
    // supervisor handle is only installed when this daemon owns
    // the lock.
    let (manifest_path, manifest_role) = if let Some(p) = state.observer_manifest_path() {
        (
            Some(p.to_string_lossy().into_owned()),
            car_proto::HostManifestRole::Observer,
        )
    } else if let Some(s) = state.supervisor_if_installed() {
        (
            Some(s.manifest_path().to_string_lossy().into_owned()),
            car_proto::HostManifestRole::Owner,
        )
    } else {
        (None, car_proto::HostManifestRole::None)
    };
    car_proto::HostIdentity {
        version: env!("CARGO_PKG_VERSION").to_string(),
        pid: std::process::id(),
        manifest_path,
        manifest_role,
        parslee: state
            .parslee_session
            .get()
            .map(|session| session.identity.clone()),
    }
}

/// Return the Parslee cloud credential for an authenticated CAR
/// connection. Managed agents already receive `CAR_AUTH_TOKEN` and
/// authenticate to the local daemon with `session.auth`; this method is
/// their supported bridge from local CAR auth to the user's Parslee
/// backend auth.
///
/// The bearer token is intentionally not injected into every managed
/// child process environment. Agents ask for it only when they need it,
/// through the same local auth gate that protects the rest of the
/// daemon.
async fn handle_parslee_auth() -> Result<Value, String> {
    let session = crate::parslee_auth::load_or_refresh()
        .await?
        .ok_or_else(|| "Parslee account not authenticated; run `car auth login`".to_string())?;
    Ok(serde_json::json!({
        "authenticated": true,
        "token_type": "Bearer",
        "access_token": session.access_token,
        "authorization_header": format!("Bearer {}", session.access_token),
        "identity": session.identity,
    }))
}

// --- auth.* : GUI-driven Parslee sign-in (CAR Host.app).
// Shares one implementation with `car auth login` via the car-auth
// crate. Stateless: the trusted in-process GUI holds the PKCE
// verifier + state between auth.start and auth.complete (same trust
// boundary as the keychain it ultimately writes).
async fn handle_auth_start(req: &JsonRpcMessage) -> Result<Value, String> {
    let api_base = car_auth::api_base(req.params.get("api_base").and_then(|v| v.as_str()));
    let client_id = req
        .params
        .get("client_id")
        .and_then(|v| v.as_str())
        .unwrap_or("parslee-car");
    let redirect_uri = req
        .params
        .get("redirect_uri")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "redirect_uri is required".to_string())?;
    let provider = req.params.get("provider").and_then(|v| v.as_str());
    let state = car_auth::new_state();
    let verifier = car_auth::pkce_verifier();
    let challenge = car_auth::pkce_challenge(&verifier);
    let url =
        car_auth::authorize_url(&api_base, client_id, redirect_uri, &state, &challenge, provider)?;
    Ok(serde_json::json!({
        "authorize_url": url,
        "state": state,
        "verifier": verifier,
    }))
}

async fn handle_auth_complete(req: &JsonRpcMessage) -> Result<Value, String> {
    let api_base = car_auth::api_base(req.params.get("api_base").and_then(|v| v.as_str()));
    let client_id = req
        .params
        .get("client_id")
        .and_then(|v| v.as_str())
        .unwrap_or("parslee-car");
    let redirect_uri = req
        .params
        .get("redirect_uri")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "redirect_uri is required".to_string())?;
    let code = req
        .params
        .get("code")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "code is required".to_string())?;
    let verifier = req
        .params
        .get("verifier")
        .and_then(|v| v.as_str())
        .ok_or_else(|| "verifier is required".to_string())?;
    let token =
        car_auth::exchange_code(&api_base, client_id, redirect_uri, code, verifier).await?;
    car_auth::store_tokens(&api_base, &token)?;
    Ok(serde_json::json!({ "ok": true }))
}

async fn handle_auth_status() -> Result<Value, String> {
    match car_auth::fetch_status(None).await? {
        Some(session_json) => {
            let session: Value = serde_json::from_str(&session_json).unwrap_or(Value::Null);
            Ok(serde_json::json!({ "authenticated": true, "session": session }))
        }
        None => Ok(serde_json::json!({ "authenticated": false })),
    }
}

async fn handle_auth_logout() -> Result<Value, String> {
    car_auth::clear_tokens()?;
    Ok(serde_json::json!({ "ok": true }))
}

async fn handle_host_agents(session: &crate::session::ClientSession) -> Result<Value, String> {
    serde_json::to_value(session.host.agents().await).map_err(|e| e.to_string())
}

async fn handle_host_events(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let limit = req
        .params
        .get("limit")
        .and_then(|v| v.as_u64())
        .unwrap_or(100) as usize;
    serde_json::to_value(session.host.events(limit).await).map_err(|e| e.to_string())
}

async fn handle_host_approvals(session: &crate::session::ClientSession) -> Result<Value, String> {
    serde_json::to_value(session.host.approvals().await).map_err(|e| e.to_string())
}

async fn handle_a2ui_apply(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    #[derive(Deserialize)]
    struct Params {
        #[serde(default)]
        envelope: Option<car_a2ui::A2uiEnvelope>,
        #[serde(default)]
        message: Option<car_a2ui::A2uiEnvelope>,
    }

    let envelope = if req.params.get("createSurface").is_some()
        || req.params.get("updateComponents").is_some()
        || req.params.get("updateDataModel").is_some()
        || req.params.get("deleteSurface").is_some()
    {
        serde_json::from_value::<car_a2ui::A2uiEnvelope>(req.params.clone())
            .map_err(|e| e.to_string())?
    } else {
        match serde_json::from_value::<Params>(req.params.clone()) {
            Ok(params) => params
                .envelope
                .or(params.message)
                .ok_or_else(|| "`a2ui.apply` requires an A2UI envelope".to_string())?,
            Err(_) => serde_json::from_value::<car_a2ui::A2uiEnvelope>(req.params.clone())
                .map_err(|e| e.to_string())?,
        }
    };

    apply_a2ui_envelope(state, envelope, None, None).await
}

async fn handle_a2ui_ingest(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct Params {
        #[serde(default)]
        endpoint: Option<String>,
        #[serde(default)]
        a2a_endpoint: Option<String>,
        #[serde(default)]
        owner: Option<car_a2ui::A2uiSurfaceOwner>,
        #[serde(default)]
        route_auth: Option<A2aRouteAuth>,
        #[serde(default)]
        allow_untrusted_endpoint: bool,
    }

    let params = serde_json::from_value::<Params>(req.params.clone()).unwrap_or(Params {
        endpoint: None,
        a2a_endpoint: None,
        owner: None,
        route_auth: None,
        allow_untrusted_endpoint: false,
    });
    let payload = req.params.get("payload").unwrap_or(&req.params);
    state
        .a2ui
        .validate_payload(payload)
        .map_err(|e| e.to_string())?;
    let envelopes = car_a2ui::envelopes_from_value(payload).map_err(|e| e.to_string())?;
    if envelopes.is_empty() {
        return Err("no A2UI envelopes found in payload".into());
    }
    let endpoint = params.endpoint.or(params.a2a_endpoint);
    let endpoint = trusted_route_endpoint(endpoint, params.allow_untrusted_endpoint);
    let owner = params
        .owner
        .or_else(|| car_a2ui::owner_from_value(payload))
        .map(|owner| match endpoint.clone() {
            Some(endpoint) => owner.with_endpoint(Some(endpoint)),
            None => owner,
        });

    let mut results = Vec::new();
    for envelope in envelopes {
        let value =
            apply_a2ui_envelope(state, envelope, owner.clone(), params.route_auth.clone()).await?;
        results.push(value);
    }
    Ok(serde_json::json!({ "applied": results }))
}

async fn apply_a2ui_envelope(
    state: &Arc<ServerState>,
    envelope: car_a2ui::A2uiEnvelope,
    owner: Option<car_a2ui::A2uiSurfaceOwner>,
    route_auth: Option<A2aRouteAuth>,
) -> Result<Value, String> {
    let result = state
        .a2ui
        .apply_with_owner(envelope, owner)
        .await
        .map_err(|e| e.to_string())?;
    update_a2ui_route_auth(state, &result, route_auth).await;
    let kind = if result.deleted {
        "a2ui.surface_deleted"
    } else {
        "a2ui.surface_updated"
    };
    let message = if result.deleted {
        format!("A2UI surface {} deleted", result.surface_id)
    } else {
        format!("A2UI surface {} updated", result.surface_id)
    };
    let payload = serde_json::to_value(&result).map_err(|e| e.to_string())?;
    state
        .host
        .record_event(kind, None, message, payload.clone())
        .await;
    // Push the envelope result to every WS subscriber as an
    // `a2ui.event` notification — Parslee-ai/car-releases#29. Late
    // joiners catch up via `a2ui/replay` (or `a2ui.surfaces`).
    broadcast_a2ui_event(state, kind, &payload).await;
    serde_json::to_value(result).map_err(|e| e.to_string())
}

async fn broadcast_a2ui_event(state: &Arc<ServerState>, kind: &str, result: &Value) {
    use futures::SinkExt;
    use tokio_tungstenite::tungstenite::Message;
    let subscribers: Vec<Arc<crate::session::WsChannel>> = state
        .a2ui_subscribers
        .lock()
        .await
        .values()
        .cloned()
        .collect();
    if subscribers.is_empty() {
        return;
    }
    let Ok(json) = serde_json::to_string(&serde_json::json!({
        "jsonrpc": "2.0",
        "method": "a2ui.event",
        "params": {
            "kind": kind,
            "result": result,
        },
    })) else {
        return;
    };
    for channel in subscribers {
        let _ = channel
            .write
            .lock()
            .await
            .send(Message::Text(json.clone().into()))
            .await;
    }
}

async fn update_a2ui_route_auth(
    state: &Arc<ServerState>,
    result: &car_a2ui::A2uiApplyResult,
    route_auth: Option<A2aRouteAuth>,
) {
    let mut auth = state.a2ui_route_auth.lock().await;
    if result.deleted {
        auth.remove(&result.surface_id);
        return;
    }

    let has_route_endpoint = result
        .surface
        .as_ref()
        .and_then(|surface| surface.owner.as_ref())
        .and_then(|owner| owner.endpoint.as_ref())
        .is_some();
    match (has_route_endpoint, route_auth) {
        (true, Some(route_auth)) => {
            auth.insert(result.surface_id.clone(), route_auth);
        }
        _ => {
            auth.remove(&result.surface_id);
        }
    }
}

fn handle_a2ui_capabilities(state: &Arc<ServerState>) -> Result<Value, String> {
    serde_json::to_value(state.a2ui.capabilities()).map_err(|e| e.to_string())
}

async fn handle_a2ui_reap(state: &Arc<ServerState>) -> Result<Value, String> {
    let removed = state.a2ui.reap_expired(chrono::Utc::now()).await;
    if !removed.is_empty() {
        let mut auth = state.a2ui_route_auth.lock().await;
        for surface_id in &removed {
            auth.remove(surface_id);
        }
    }
    Ok(serde_json::json!({ "removed": removed }))
}

async fn handle_a2ui_surfaces(state: &Arc<ServerState>) -> Result<Value, String> {
    serde_json::to_value(state.a2ui.list().await).map_err(|e| e.to_string())
}

async fn handle_a2ui_get(req: &JsonRpcMessage, state: &Arc<ServerState>) -> Result<Value, String> {
    let surface_id = req
        .params
        .get("surface_id")
        .or_else(|| req.params.get("surfaceId"))
        .and_then(Value::as_str)
        .ok_or_else(|| "`a2ui.get` requires surface_id".to_string())?;
    serde_json::to_value(state.a2ui.get(surface_id).await).map_err(|e| e.to_string())
}

/// `a2ui/subscribe` — opt this WS connection into `a2ui.event`
/// notifications. Subscribers receive every `apply_a2ui_envelope`
/// result for as long as they're connected; the cleanup hook in
/// `run_dispatch` removes them on disconnect. Closes
/// Parslee-ai/car-releases#29.
async fn handle_a2ui_subscribe(
    session: &crate::session::ClientSession,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    state
        .a2ui_subscribers
        .lock()
        .await
        .insert(session.client_id.clone(), session.channel.clone());
    Ok(serde_json::json!({ "subscribed": true }))
}

/// `a2ui/unsubscribe` — opt out of `a2ui.event` notifications.
/// Idempotent: returns `{ subscribed: false }` regardless of prior
/// state.
async fn handle_a2ui_unsubscribe(
    session: &crate::session::ClientSession,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    state
        .a2ui_subscribers
        .lock()
        .await
        .remove(&session.client_id);
    Ok(serde_json::json!({ "subscribed": false }))
}

/// `a2ui/replay` — fetch the current state of one surface. Intended
/// for late joiners and reconnect: a client calls `subscribe`, then
/// `replay` once per surface it's tracking, and from then on
/// notifications keep it in sync. Equivalent to `a2ui.get` on the
/// surface store; lives in the subscribe namespace for
/// discoverability.
async fn handle_a2ui_replay(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let surface_id = req
        .params
        .get("surface_id")
        .or_else(|| req.params.get("surfaceId"))
        .and_then(Value::as_str)
        .ok_or_else(|| "`a2ui/replay` requires surface_id".to_string())?;
    serde_json::to_value(state.a2ui.get(surface_id).await).map_err(|e| e.to_string())
}

async fn handle_a2ui_action(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let action: car_a2ui::ClientAction =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let owner = state.a2ui.owner(&action.surface_id).await;
    let route = route_a2ui_action(state, &action, owner.clone()).await;
    let payload = serde_json::json!({
        "action": action,
        "owner": owner,
        "route": route,
    });
    let event = state
        .host
        .record_event(
            "a2ui.action",
            None,
            format!(
                "A2UI action {} from {}",
                action.name, action.source_component_id
            ),
            payload,
        )
        .await;
    Ok(serde_json::json!({
        "event": event,
        "route": route,
    }))
}

/// `a2ui.render_report` — renderer-emitted telemetry envelope
/// (Parslee-ai/car#180). Fire-and-forget; we record an event in
/// the host log (so dev tools and the conversation log see it) and
/// broadcast as `a2ui.event { kind: "a2ui.render_report", result }`
/// to every WS subscriber. The improvement agent reads the report
/// and decides whether to issue a follow-up `patchComponents`.
async fn handle_a2ui_render_report(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    // Parse into the typed struct to enforce the schema; we
    // re-serialize for the event/broadcast payload so downstream
    // consumers don't have to defensively re-validate.
    let report: car_a2ui::RenderReport =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let payload = serde_json::to_value(&report).map_err(|e| e.to_string())?;
    let kind = "a2ui.render_report";
    let message = format!("A2UI render report for surface {}", report.surface_id);
    let event = state
        .host
        .record_event(kind, None, message, payload.clone())
        .await;
    broadcast_a2ui_event(state, kind, &payload).await;

    // Hand the report to the in-process UI-improvement agent. The
    // agent is sync but cheap; we await the surface lookup before
    // calling it so the strategies see the same surface state the
    // renderer saw at report-emit time. Best-effort: surface lookup
    // misses (the surface might have been deleted between
    // report-emit and report-receive) are logged and skipped, never
    // surfaced as JSON-RPC errors — render_report is fire-and-forget.
    if let Some(surface) = state.a2ui.get(&report.surface_id).await {
        // Iteration budget — runaway-loop backstop. try_consume
        // claims the slot atomically; if the surface is already at
        // the cap, we short-circuit before consulting the agent.
        // The slot stays consumed only if the patch actually
        // applies — failure paths refund.
        if !state.ui_agent_budget.try_consume(&report.surface_id) {
            tracing::warn!(
                surface_id = %report.surface_id,
                count = state.ui_agent_budget.count(&report.surface_id),
                max = state.ui_agent_budget.max(),
                "ui-agent iteration budget exhausted; skipping agent invocation"
            );
            return Ok(serde_json::json!({ "event": event }));
        }
        // From here on, every non-applied branch must `refund` the
        // slot we just claimed. Only the successful-apply branch
        // keeps it consumed.
        match state.ui_agent.on_render_report(&report, &surface) {
            car_ui_agent::Decision::Patch {
                envelope,
                strategy_id,
                patch_hash,
                elapsed_ns,
            } => {
                // Runtime-side convergence monitor — neo's deferred
                // ask. The agent's no-double-patch guard catches
                // same-sequence repeats; this catches A→B→A across
                // sequences by tracking recent patch hashes per
                // surface. When a proposal would repeat one in the
                // window, drop it; the loop waits for the next
                // signature change.
                if !state
                    .ui_agent_oscillation
                    .check_and_record(&report.surface_id, patch_hash)
                {
                    tracing::warn!(
                        surface_id = %report.surface_id,
                        strategy = %strategy_id,
                        patch_hash,
                        "ui-agent oscillation detected; suppressing patch"
                    );
                    // Suppressed patch never applied → release the
                    // budget slot we claimed above.
                    state.ui_agent_budget.refund(&report.surface_id);
                    return Ok(serde_json::json!({ "event": event }));
                }
                let a2ui_envelope = car_a2ui::A2uiEnvelope {
                    patch_components: Some(envelope),
                    ..Default::default()
                };
                if let Err(e) = apply_a2ui_envelope(state, a2ui_envelope, None, None).await {
                    tracing::warn!(
                        surface_id = %report.surface_id,
                        strategy = %strategy_id,
                        patch_hash,
                        elapsed_ns,
                        error = %e,
                        "ui-agent patch apply failed",
                    );
                    // Apply failed → release the budget slot.
                    state.ui_agent_budget.refund(&report.surface_id);
                } else {
                    tracing::debug!(
                        surface_id = %report.surface_id,
                        strategy = %strategy_id,
                        patch_hash,
                        elapsed_ns,
                        iteration = state.ui_agent_budget.count(&report.surface_id),
                        "ui-agent patch applied",
                    );
                    // Memgine trace: one Conversation node per
                    // successful patch, tagged "ui-agent/<surface>".
                    // Spreading activation can surface these on
                    // future renders of related surfaces. Spawned
                    // off the render-report hot path — ingest walks
                    // the graph for spreading activation and can
                    // take real time; we don't want two surfaces
                    // churning patches to serialize through the
                    // memgine mutex behind the WS handler.
                    if let Some(memgine) = state.shared_memgine.clone() {
                        let speaker = format!("ui-agent/{}", report.surface_id);
                        let text = format!("strategy applied: {}", strategy_id);
                        tokio::spawn(async move {
                            let mut guard = memgine.lock().await;
                            guard.ingest_conversation(&speaker, &text, chrono::Utc::now());
                        });
                    }
                }
            }
            car_ui_agent::Decision::StableNoChange => {
                // No patch this round → release the slot.
                state.ui_agent_budget.refund(&report.surface_id);
            }
            car_ui_agent::Decision::HardStop { reason } => {
                state.ui_agent_budget.refund(&report.surface_id);
                // Renderer painted unknown components — contract
                // violation between server and renderer. Per
                // types.rs docs: "loud failure" + "MUST pause."
                // `error!` not `warn!` so it surfaces in production
                // logs at the right severity.
                tracing::error!(
                    surface_id = %report.surface_id,
                    reason = %reason,
                    "ui-agent hard-stopped improvement loop",
                );
            }
        }
    } else {
        tracing::debug!(
            surface_id = %report.surface_id,
            "ui-agent skipped — surface not found in store",
        );
    }

    Ok(serde_json::json!({ "event": event }))
}

async fn route_a2ui_action(
    state: &Arc<ServerState>,
    action: &car_a2ui::ClientAction,
    owner: Option<car_a2ui::A2uiSurfaceOwner>,
) -> Value {
    let Some(owner) = owner else {
        return serde_json::json!({ "delivered": false, "reason": "surface has no owner" });
    };
    if owner.kind != "a2a" {
        return serde_json::json!({ "delivered": false, "reason": "unsupported owner kind", "owner": owner });
    }
    let Some(endpoint) = owner.endpoint.clone() else {
        return serde_json::json!({
            "delivered": false,
            "reason": "surface owner has no endpoint",
            "owner": owner
        });
    };

    let message = car_a2a::Message {
        message_id: format!("a2ui-action-{}", uuid::Uuid::new_v4().simple()),
        role: car_a2a::MessageRole::User,
        parts: vec![car_a2a::Part::Data(car_a2a::types::DataPart {
            data: serde_json::json!({
                "a2uiAction": action,
            }),
            metadata: Default::default(),
        })],
        task_id: owner.task_id.clone(),
        context_id: owner.context_id.clone(),
        metadata: Default::default(),
    };

    let auth = state
        .a2ui_route_auth
        .lock()
        .await
        .get(&action.surface_id)
        .cloned()
        .map(client_auth_from_route_auth)
        .unwrap_or(car_a2a::ClientAuth::None);

    match car_a2a::A2aClient::new(endpoint.clone())
        .with_auth(auth)
        .send_message(message, false)
        .await
    {
        Ok(result) => serde_json::json!({
            "delivered": true,
            "owner": owner,
            "endpoint": endpoint,
            "result": result,
        }),
        Err(error) => serde_json::json!({
            "delivered": false,
            "owner": owner,
            "endpoint": endpoint,
            "error": error.to_string(),
        }),
    }
}

fn client_auth_from_route_auth(auth: A2aRouteAuth) -> car_a2a::ClientAuth {
    match auth {
        A2aRouteAuth::None => car_a2a::ClientAuth::None,
        A2aRouteAuth::Bearer { token } => car_a2a::ClientAuth::Bearer(token),
        A2aRouteAuth::Header { name, value } => car_a2a::ClientAuth::Header { name, value },
    }
}

fn trusted_route_endpoint(endpoint: Option<String>, allow_untrusted: bool) -> Option<String> {
    let endpoint = endpoint?;
    if allow_untrusted || is_loopback_http_endpoint(&endpoint) {
        Some(endpoint)
    } else {
        None
    }
}

fn is_loopback_http_endpoint(endpoint: &str) -> bool {
    endpoint == "http://localhost"
        || endpoint.starts_with("http://localhost:")
        || endpoint.starts_with("http://localhost/")
        || endpoint == "http://127.0.0.1"
        || endpoint.starts_with("http://127.0.0.1:")
        || endpoint.starts_with("http://127.0.0.1/")
        || endpoint == "http://[::1]"
        || endpoint.starts_with("http://[::1]:")
        || endpoint.starts_with("http://[::1]/")
}

async fn handle_host_register_agent(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let request: RegisterHostAgentRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    serde_json::to_value(
        session
            .host
            .register_agent(&session.client_id, request)
            .await?,
    )
    .map_err(|e| e.to_string())
}

async fn handle_host_unregister_agent(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let agent_id = req
        .params
        .get("agent_id")
        .and_then(|v| v.as_str())
        .ok_or("missing agent_id")?;
    session
        .host
        .unregister_agent(&session.client_id, agent_id)
        .await?;
    Ok(serde_json::json!({"ok": true}))
}

async fn handle_host_set_status(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let request: SetHostAgentStatusRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    serde_json::to_value(session.host.set_status(&session.client_id, request).await?)
        .map_err(|e| e.to_string())
}

async fn handle_host_notify(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let kind = req
        .params
        .get("kind")
        .and_then(|v| v.as_str())
        .unwrap_or("host.notification");
    let agent_id = req
        .params
        .get("agent_id")
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let message = req
        .params
        .get("message")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let payload = req.params.get("payload").cloned().unwrap_or(Value::Null);
    serde_json::to_value(
        session
            .host
            .record_event(kind, agent_id, message, payload)
            .await,
    )
    .map_err(|e| e.to_string())
}

async fn handle_host_request_approval(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let request: CreateHostApprovalRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    if let Some(agent_id) = &request.agent_id {
        // Best-effort. If the caller doesn't own this agent the
        // ACL added 2026-05 will refuse the status update — that
        // is the correct semantics; we still want the approval row
        // itself to land so the UI can render the request.
        let _ = session
            .host
            .set_status(
                &session.client_id,
                SetHostAgentStatusRequest {
                    agent_id: agent_id.clone(),
                    status: HostAgentStatus::WaitingForApproval,
                    current_task: None,
                    message: Some("Waiting for approval".to_string()),
                    payload: Value::Null,
                },
            )
            .await;
    }
    // `system_level: true` opts the approval out of per-session
    // ownership. The host-side ACL then allows any authenticated
    // session (typically CarHost or `car-host approve`) to resolve.
    // Agents requesting user approval should always set this — the
    // session-owned mode is only correct when the requesting session
    // is also the resolving session, which approval-via-UI never is.
    let owner_client_id = if request.system_level {
        None
    } else {
        Some(session.client_id.as_str())
    };
    serde_json::to_value(session.host.create_approval(owner_client_id, request).await?)
        .map_err(|e| e.to_string())
}

async fn handle_host_resolve_approval(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let request: ResolveHostApprovalRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    serde_json::to_value(
        session
            .host
            .resolve_approval(&session.client_id, request)
            .await?,
    )
    .map_err(|e| e.to_string())
}

/// `session.auth` — present the per-launch token to unlock the
/// connection. When `state.auth_token` is unset, this method is a
/// no-op success (auth is disabled). When set, the supplied token
/// must equal it (constant-time comparison) — a successful auth
/// flips `session.authenticated` to `true` so subsequent methods
/// pass the gate. Wrong token returns an error AND leaves the
/// session unauthenticated; the dispatcher loop's gate then closes
/// the connection on the next non-auth method.
///
/// Closes Parslee-ai/car-releases#32.
async fn handle_session_auth(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let supplied = req
        .params
        .get("token")
        .and_then(Value::as_str)
        .ok_or_else(|| "session.auth requires { token: string }".to_string())?;
    // #169: optional `agent_id` binds the WS connection to a
    // supervised lifecycle agent. When present, the supplied token
    // must equal the per-agent token the supervisor minted at upsert
    // (NOT the daemon-wide auth token). When absent, fall back to
    // the daemon-wide token — preserves the legacy unbound-token
    // path for browser/host/CLI clients.
    let agent_id = req
        .params
        .get("agent_id")
        .and_then(Value::as_str)
        .map(str::to_string);

    if let Some(id) = agent_id {
        let supervisor = state.supervisor()?;
        if !supervisor.validate_agent_token(&id, supplied).await {
            return Err(format!(
                "auth failed: agent_id `{id}` is not supervised, or token mismatch"
            ));
        }
        // Single-claim: only one connection at a time per
        // agent_id. A second claim is rejected so the daemon-side
        // per-agent state stays unambiguous.
        {
            let mut attached = state.attached_agents.lock().await;
            if let Some(prior) = attached.get(&id) {
                if prior != &session.client_id {
                    return Err(format!(
                        "auth failed: agent_id `{id}` is already attached on \
                         another connection (client_id={prior})"
                    ));
                }
            }
            attached.insert(id.clone(), session.client_id.clone());
        }
        // #170: attach the daemon-owned persistent memgine for
        // this agent. Lazy-loaded on first connection per id from
        // `~/.car/memory/agents/<id>.jsonl`; retained across
        // disconnect so the next session sees the same state.
        let agent_eng = get_or_load_agent_memgine(state, &id).await?;
        *session.bound_memgine.lock().await = Some(agent_eng);
        *session.agent_id.lock().await = Some(id.clone());
        session
            .authenticated
            .store(true, std::sync::atomic::Ordering::Release);
        return Ok(serde_json::json!({
            "ok": true,
            "auth_enabled": true,
            "agent_id": id,
        }));
    }

    let expected = match state.auth_token.get() {
        Some(t) => t,
        None => {
            // Auth disabled — accept any token politely so callers
            // that always include a session.auth handshake (e.g. the
            // FFI proxy) don't fail when the daemon happens to be
            // unauthed. Mark the session authenticated anyway so the
            // gate is a no-op below.
            session
                .authenticated
                .store(true, std::sync::atomic::Ordering::Release);
            return Ok(serde_json::json!({ "ok": true, "auth_enabled": false }));
        }
    };
    if !constant_time_eq(supplied.as_bytes(), expected.as_bytes()) {
        return Err("auth failed: token mismatch".to_string());
    }
    session
        .authenticated
        .store(true, std::sync::atomic::Ordering::Release);
    Ok(serde_json::json!({
        "ok": true,
        "auth_enabled": true,
        "parslee": state.parslee_session.get().map(|session| session.identity.clone()),
    }))
}

/// Length-checked constant-time byte comparison. Returns false when
/// lengths differ (so length itself is the only timing leak — fine
/// for our 43-char fixed-length tokens).
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
    if a.len() != b.len() {
        return false;
    }
    let mut diff: u8 = 0;
    for (x, y) in a.iter().zip(b.iter()) {
        diff |= x ^ y;
    }
    diff == 0
}

/// Block dispatch of `method` until the user resolves the approval
/// raised on [`HostState`].
///
/// Called from the dispatcher loop only when
/// [`crate::session::ApprovalGate::requires_approval`] returns true.
/// `Ok(())` means the user picked "approve"; `Err(reason)` is sent
/// to the caller as JSON-RPC error code `-32003` with the supplied
/// reason. On timeout, the approval row stays in `Pending` so the
/// UI keeps a record of the unanswered request.
async fn gate_high_risk_method(
    method: &str,
    params: &Value,
    state: &Arc<ServerState>,
) -> Result<(), String> {
    let timeout = state.approval_gate.timeout;
    let req = CreateHostApprovalRequest {
        agent_id: None,
        action: format!("ws.method:{method}"),
        details: serde_json::json!({
            "method": method,
            // Truncate params for the UI — full payload is recoverable
            // via the request-time host event log if needed. The cap
            // keeps a malicious caller from drowning the UI in JSON.
            "params_preview": preview_params(params, 2_000),
        }),
        options: vec!["approve".to_string(), "deny".to_string()],
        // The high-risk-method gate is already system-level (it
        // passes None as the owner via request_and_wait_approval's
        // internal call). This field is informational here.
        system_level: true,
    };
    match state
        .host
        .request_and_wait_approval(req, "approve", timeout)
        .await
    {
        Ok(crate::host::ApprovalOutcome::Approved) => Ok(()),
        Ok(crate::host::ApprovalOutcome::Denied) => Err(format!(
            "{method} denied by user (approval gate, audit 2026-05). \
             To call this method without an interactive prompt, start \
             car-server with --no-approvals on a trusted machine."
        )),
        Ok(crate::host::ApprovalOutcome::TimedOut) => Err(format!(
            "{method} approval timed out after {}s with no resolution. \
             The approval is still visible in `host.approvals` for \
             forensics; resubmit the request to retry.",
            timeout.as_secs()
        )),
        Err(e) => Err(format!("approval gate error: {e}")),
    }
}

fn preview_params(value: &Value, max_chars: usize) -> Value {
    let s = value.to_string();
    if s.len() <= max_chars {
        value.clone()
    } else {
        Value::String(format!("{}… (truncated)", &s[..max_chars]))
    }
}

async fn handle_session_init(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let init: SessionInitRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;

    for tool in &init.tools {
        register_from_definition(&session.runtime, tool).await;
    }

    let mut policy_count = 0;
    {
        let mut policies = session.runtime.policies.write().await;
        for policy_def in &init.policies {
            if let Some(check) = build_policy_check(policy_def) {
                policies.register(&policy_def.name, check, "");
                policy_count += 1;
            }
        }
    }

    serde_json::to_value(SessionInitResponse {
        session_id: session.client_id.clone(),
        tools_registered: init.tools.len(),
        policies_registered: policy_count,
    })
    .map_err(|e| e.to_string())
}

fn build_policy_check(def: &PolicyDefinition) -> Option<car_policy::PolicyCheck> {
    match def.rule.as_str() {
        "deny_tool" => {
            let target = def.target.clone();
            Some(Box::new(
                move |action: &car_ir::Action, _: &car_state::StateStore| {
                    if action.tool.as_deref() == Some(&target) {
                        Some(format!("tool '{}' denied", target))
                    } else {
                        None
                    }
                },
            ))
        }
        "require_state" => {
            let key = def.key.clone();
            let value = def.value.clone();
            Some(Box::new(
                move |_: &car_ir::Action, state: &car_state::StateStore| {
                    if state.get(&key).as_ref() != Some(&value) {
                        Some(format!("state['{}'] must be {:?}", key, value))
                    } else {
                        None
                    }
                },
            ))
        }
        "deny_tool_param" => {
            let target = def.target.clone();
            let param = def.key.clone();
            let pattern = def.pattern.clone();
            Some(Box::new(
                move |action: &car_ir::Action, _: &car_state::StateStore| {
                    if action.tool.as_deref() != Some(&target) {
                        return None;
                    }
                    if let Some(val) = action.parameters.get(&param) {
                        let s = val.as_str().unwrap_or(&val.to_string()).to_string();
                        if s.contains(&pattern) {
                            return Some(format!("param '{}' matches '{}'", param, pattern));
                        }
                    }
                    None
                },
            ))
        }
        _ => None,
    }
}

async fn handle_tools_register(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let tools: Vec<ToolDefinition> =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    for tool in &tools {
        register_from_definition(&session.runtime, tool).await;
    }
    Ok(Value::from(tools.len()))
}

/// Bridge a wire-protocol `ToolDefinition` to the engine's
/// schema-aware registration. Carries the full ToolSchema shape
/// (description, parameters, returns, idempotency, caching, rate
/// limit) through to the validator. An empty `parameters` object is
/// the legacy schemaless registration — the validator no-ops for
/// those, so pre-v0.5.x callers see no change.
async fn register_from_definition(runtime: &car_engine::Runtime, def: &ToolDefinition) {
    runtime
        .register_tool_schema(car_ir::ToolSchema {
            name: def.name.clone(),
            description: def.description.clone(),
            parameters: def.parameters.clone(),
            returns: def.returns.clone(),
            idempotent: def.idempotent,
            cache_ttl_secs: def.cache_ttl_secs,
            rate_limit: def.rate_limit.as_ref().map(|rl| car_ir::ToolRateLimit {
                max_calls: rl.max_calls,
                interval_secs: rl.interval_secs,
            }),
        })
        .await;
}

async fn handle_proposal_submit(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let submit: ProposalSubmitRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    // `session_id` is sibling to `proposal` in the params object —
    // not part of `ProposalSubmitRequest` (kept proto-compatible). When
    // present, executes the proposal under the named session so any
    // session-scoped policies layer on top of global ones.
    // See docs/proposals/per-session-policy-scoping.md.
    let session_id = req
        .params
        .get("session_id")
        .and_then(|v| v.as_str())
        .map(str::to_string);

    // `scope` is the optional per-execution caller / tenant surface
    // added in Parslee-ai/car#187 phase 3. Shape mirrors
    // `car_engine::RuntimeScope` ({ callerId, tenantId, claims });
    // serde's camelCase rename keeps the wire form consistent with
    // the rest of the JSON-RPC surface. When present, the proposal
    // routes through `execute_scoped*` so the runtime records the
    // identity on the event log and state R/W ops apply the tenant
    // prefix (#187 phase 3-B).
    let scope: Option<car_engine::RuntimeScope> = match req.params.get("scope") {
        Some(v) if !v.is_null() => {
            Some(serde_json::from_value(v.clone()).map_err(|e| format!("invalid scope: {e}"))?)
        }
        _ => None,
    };

    let result = match (session_id, scope) {
        // session_id + scope: no single combined entry point on
        // Runtime today. Scope takes precedence because it's the
        // tenant-isolation surface; per-session policies layer in
        // a follow-up when there's a real caller asking for both.
        (Some(_sid), Some(s)) => session.runtime.execute_scoped(&submit.proposal, &s).await,
        (Some(sid), None) => {
            session
                .runtime
                .execute_with_session(&submit.proposal, &sid)
                .await
        }
        (None, Some(s)) => session.runtime.execute_scoped(&submit.proposal, &s).await,
        (None, None) => session.runtime.execute(&submit.proposal).await,
    };
    serde_json::to_value(result).map_err(|e| e.to_string())
}

async fn handle_session_policy_open(
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let id = session.runtime.open_session().await;
    Ok(serde_json::json!({ "session_id": id }))
}

async fn handle_session_policy_close(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let sid = req
        .params
        .get("session_id")
        .and_then(|v| v.as_str())
        .ok_or("missing 'session_id'")?;
    let closed = session.runtime.close_session(sid).await;
    Ok(serde_json::json!({ "closed": closed }))
}

/// `policy.register` — register one policy against this WebSocket
/// session's runtime. Mirrors the `PolicyDefinition` shape used by
/// `session.init`. When `session_id` is present, the policy is scoped
/// to the named in-runtime session opened via `session.policy.open`;
/// otherwise it is global.
async fn handle_policy_register(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let def: PolicyDefinition = serde_json::from_value(req.params.clone())
        .map_err(|e| format!("invalid policy params: {e}"))?;
    let session_id = req
        .params
        .get("session_id")
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let check = build_policy_check(&def)
        .ok_or_else(|| format!("unsupported policy rule '{}'", def.rule))?;
    match session_id {
        Some(sid) => session
            .runtime
            .register_policy_in_session(&sid, &def.name, check, "")
            .await
            .map(|_| serde_json::json!({ "registered": def.name, "scope": { "session_id": sid } })),
        None => {
            let mut policies = session.runtime.policies.write().await;
            policies.register(&def.name, check, "");
            Ok(serde_json::json!({ "registered": def.name, "scope": "global" }))
        }
    }
}

async fn handle_verify(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let vr: VerifyRequest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let tools: std::collections::HashSet<String> =
        session.runtime.tools.read().await.keys().cloned().collect();
    let result = car_verify::verify(&vr.proposal, Some(&vr.initial_state), Some(&tools), 30);
    serde_json::to_value(VerifyResponse {
        valid: result.valid,
        issues: result
            .issues
            .iter()
            .map(|i| VerifyIssueProto {
                action_id: i.action_id.clone(),
                severity: i.severity.clone(),
                message: i.message.clone(),
            })
            .collect(),
        simulated_state: result.simulated_state,
    })
    .map_err(|e| e.to_string())
}

/// Parse the optional `tenant_id` sibling field from JSON-RPC
/// params (Parslee-ai/car#187 phase 3-E). When set and non-empty,
/// state R/W routes through `StateStore::scoped(tenant_id)` so
/// distinct tenants can't see each other's keys over the WS
/// surface — symmetric to the proposal.submit scope plumbing.
/// When absent / empty, the legacy unscoped namespace applies.
fn tenant_from_params(req: &JsonRpcMessage) -> Option<String> {
    req.params
        .get("tenant_id")
        .and_then(|v| v.as_str())
        .filter(|s| !s.is_empty())
        .map(str::to_string)
}

async fn handle_state_get(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let key = req
        .params
        .get("key")
        .and_then(|v| v.as_str())
        .ok_or("missing 'key'")?;
    let tenant = tenant_from_params(req);
    Ok(session
        .runtime
        .state
        .scoped(tenant.as_deref())
        .get(key)
        .unwrap_or(Value::Null))
}

async fn handle_state_set(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let key = req
        .params
        .get("key")
        .and_then(|v| v.as_str())
        .ok_or("missing 'key'")?;
    let value = req.params.get("value").cloned().unwrap_or(Value::Null);
    let tenant = tenant_from_params(req);
    session
        .runtime
        .state
        .scoped(tenant.as_deref())
        .set(key, value, "client");
    Ok(Value::from("ok"))
}

/// `state.exists` — true if the key is set in this session's state
/// store, false otherwise. Cheaper than `state.get` + null-check on
/// the client side because it doesn't serialize the value.
async fn handle_state_exists(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let key = req
        .params
        .get("key")
        .and_then(|v| v.as_str())
        .ok_or("missing 'key'")?;
    let tenant = tenant_from_params(req);
    Ok(Value::Bool(
        session.runtime.state.scoped(tenant.as_deref()).exists(key),
    ))
}

/// `state.keys` — list every key currently set in this session's
/// state store. Returns a JSON array of strings.
async fn handle_state_keys(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let tenant = tenant_from_params(req);
    Ok(Value::Array(
        session
            .runtime
            .state
            .scoped(tenant.as_deref())
            .keys()
            .into_iter()
            .map(Value::String)
            .collect(),
    ))
}

/// `state.snapshot` — return the entire session state store as a
/// JSON object (`{ key: value, ... }`). Equivalent to iterating
/// `state.keys` + `state.get` but in a single round-trip; for
/// inspectors/dashboards.
///
/// Tenant-scoped variant: when `tenant_id` is set, only that
/// tenant's keys are returned (prefix stripped on the way out).
/// `state.snapshot` with no `tenant_id` returns only unscoped
/// keys; consistent with `state.keys`'s filter behaviour and the
/// strict-isolation contract from phase 3-B.
async fn handle_state_snapshot(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let tenant = tenant_from_params(req);
    let view = session.runtime.state.scoped(tenant.as_deref());
    let mut map = serde_json::Map::new();
    for key in view.keys() {
        if let Some(value) = view.get(&key) {
            map.insert(key, value);
        }
    }
    Ok(Value::Object(map))
}

// --- Per-agent persistent memgine (#170) ---

/// `~/.car/memory/agents/<id>.json` — the per-agent snapshot file.
/// Mirrors the existing `memory.persist` shape (flat JSON array of
/// fact objects) so the same loader path works.
fn agent_memgine_snapshot_path(agent_id: &str) -> Result<std::path::PathBuf, String> {
    let base = car_ffi_common::memory_path::ensure_base()
        .map_err(|e| format!("memory base unavailable: {e}"))?;
    let dir = base.join("agents");
    std::fs::create_dir_all(&dir).map_err(|e| format!("create agents dir: {e}"))?;
    Ok(dir.join(format!("{agent_id}.json")))
}

/// Acquire (or lazy-create + load from disk) the daemon-owned
/// persistent memgine for `agent_id`. First call per id reads
/// `~/.car/memory/agents/<id>.json` if it exists; subsequent calls
/// share the in-memory engine across sessions. Caller stores the
/// returned `Arc` on `ClientSession.bound_memgine` so memory.*
/// handlers route through it via [`ClientSession::effective_memgine`].
async fn get_or_load_agent_memgine(
    state: &Arc<ServerState>,
    agent_id: &str,
) -> Result<Arc<tokio::sync::Mutex<car_memgine::MemgineEngine>>, String> {
    {
        let map = state.agent_memgines.lock().await;
        if let Some(eng) = map.get(agent_id) {
            return Ok(eng.clone());
        }
    }
    // Build a fresh engine and try to load from disk.
    let engine = Arc::new(tokio::sync::Mutex::new(car_memgine::MemgineEngine::new(
        None,
    )));
    let path = agent_memgine_snapshot_path(agent_id)?;
    if path.exists() {
        let content = std::fs::read_to_string(&path)
            .map_err(|e| format!("read {}: {}", path.display(), e))?;
        let facts: Vec<Value> = serde_json::from_str(&content).unwrap_or_default();
        let mut g = engine.lock().await;
        let mut loaded: u32 = 0;
        for fact in &facts {
            let subject = fact.get("subject").and_then(|v| v.as_str()).unwrap_or("");
            let body = fact.get("body").and_then(|v| v.as_str()).unwrap_or("");
            let kind = fact
                .get("kind")
                .and_then(|v| v.as_str())
                .unwrap_or("pattern");
            let fid = format!("loaded-{loaded}");
            g.ingest_fact(
                &fid,
                subject,
                body,
                "user",
                "peer",
                chrono::Utc::now(),
                "global",
                None,
                vec![],
                kind == "constraint",
            );
            loaded += 1;
        }
    }
    let mut map = state.agent_memgines.lock().await;
    let stored = map.entry(agent_id.to_string()).or_insert(engine).clone();
    Ok(stored)
}

/// Snapshot the agent's memgine to its disk file. Same on-wire shape
/// as `memory.persist` so manual snapshots and the daemon-owned
/// persistence stay interoperable.
async fn persist_agent_memgine(
    agent_id: &str,
    engine: &Arc<tokio::sync::Mutex<car_memgine::MemgineEngine>>,
) -> Result<(), String> {
    let path = agent_memgine_snapshot_path(agent_id)?;
    let g = engine.lock().await;
    let facts: Vec<Value> = g
        .graph
        .inner
        .node_indices()
        .filter_map(|nix| {
            let node = g.graph.inner.node_weight(nix)?;
            if !node.is_valid() {
                return None;
            }
            if node.kind == car_memgine::MemKind::Identity
                || node.kind == car_memgine::MemKind::Environment
            {
                return None;
            }
            Some(serde_json::json!({
                "subject": node.key,
                "body": node.value,
                "kind": match node.kind {
                    car_memgine::MemKind::Fact => if node.is_constraint { "constraint" } else { "pattern" },
                    car_memgine::MemKind::Conversation => "outcome",
                    _ => "pattern",
                },
                "confidence": 0.5,
                "content_type": node.content_type.as_label(),
            }))
        })
        .collect();
    let json = serde_json::to_string(&facts).map_err(|e| e.to_string())?;
    std::fs::write(&path, json).map_err(|e| format!("write {}: {}", path.display(), e))?;
    Ok(())
}

// --- Memory handlers ---

/// `memory.fact_count` — return `valid_fact_count()` of the
/// session's memgine. Used by FFI bindings to mirror their
/// embedded `fact_count()` accessor without round-tripping a full
/// query. No params.
async fn handle_memory_fact_count(
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let engine_arc = session.effective_memgine().await;
    let engine = engine_arc.lock().await;
    Ok(Value::from(engine.valid_fact_count()))
}

async fn handle_memory_add_fact(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let subject = req
        .params
        .get("subject")
        .and_then(|v| v.as_str())
        .ok_or("missing subject")?;
    let body = req
        .params
        .get("body")
        .and_then(|v| v.as_str())
        .ok_or("missing body")?;
    let kind = req
        .params
        .get("kind")
        .and_then(|v| v.as_str())
        .unwrap_or("pattern");
    // Route through `effective_memgine` so connections bound to a
    // lifecycle agent (#169) write into the daemon-owned per-agent
    // memgine instead of the per-WS ephemeral one (#170).
    let engine_arc = session.effective_memgine().await;
    let count = {
        let mut engine = engine_arc.lock().await;
        let fid = format!("ws-{}", engine.valid_fact_count());
        engine.ingest_fact(
            &fid,
            subject,
            body,
            "user",
            "peer",
            chrono::Utc::now(),
            "global",
            None,
            vec![],
            kind == "constraint",
        );
        engine.valid_fact_count()
    };
    // Persist after every add when the session is bound to a
    // supervised agent. Synchronous write — small JSON snapshot.
    if let Some(id) = session.agent_id.lock().await.clone() {
        if let Err(e) = persist_agent_memgine(&id, &engine_arc).await {
            tracing::warn!(agent_id = %id, error = %e,
                "agent memgine persist failed; in-memory state is canonical");
        }
    }
    Ok(Value::from(count))
}

async fn handle_memory_query(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let query = req
        .params
        .get("query")
        .and_then(|v| v.as_str())
        .ok_or("missing query")?;
    let k = req.params.get("k").and_then(|v| v.as_u64()).unwrap_or(5) as usize;
    let engine_arc = session.effective_memgine().await;
    let engine = engine_arc.lock().await;
    let seeds = engine.graph.find_seeds(query, 5);
    // FFI parity with NAPI `query_facts` (car-ffi-napi/src/lib.rs:577) —
    // both use Personalized PageRank so transport choice doesn't shift
    // ranking semantics. Result shape (subject/body/kind/confidence)
    // also mirrors NAPI for the same reason.
    let hits = if !seeds.is_empty() {
        engine.graph.retrieve_ppr(&seeds, None, 0.5, k)
    } else {
        vec![]
    };
    let results: Vec<Value> = hits
        .iter()
        .filter_map(|hit| {
            let node = engine.graph.inner.node_weight(hit.node_ix)?;
            Some(serde_json::json!({
                "subject": node.key,
                "body": node.value,
                "kind": format!("{:?}", node.kind).to_lowercase(),
                "confidence": hit.activation,
            }))
        })
        .collect();
    serde_json::to_value(results).map_err(|e| e.to_string())
}

async fn handle_memory_build_context(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let query = req
        .params
        .get("query")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    // FFI parity with NAPI `build_context(query, model_context_window)`.
    // When supplied, sizes the assembly budget against the model's window
    // instead of the fixed 8K default.
    let model_context_window = req
        .params
        .get("model_context_window")
        .and_then(|v| v.as_u64())
        .map(|w| w as usize);
    let mut engine = session.memgine.lock().await;
    Ok(Value::from(
        engine.build_context_for_model(query, model_context_window),
    ))
}

/// `memory.build_context_fast` — Fast-mode context assembly for
/// latency-sensitive paths (voice, real-time). Skips embedding flush,
/// skill lookup, PPR-based scoring, inline repairs, known-unknowns
/// extraction. Keeps identity, constraints, facts (creation order),
/// conversation, environment.
async fn handle_memory_build_context_fast(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let query = req
        .params
        .get("query")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let model_context_window = req
        .params
        .get("model_context_window")
        .and_then(|v| v.as_u64())
        .map(|w| w as usize);
    let mut engine = session.memgine.lock().await;
    Ok(Value::from(engine.build_context_with_options(
        query,
        model_context_window,
        car_memgine::ContextMode::Fast,
        None,
    )))
}

/// `memory.persist` — write the session's memgine to a JSON file
/// at `path`. Mirrors NAPI `persist_memory` (car-ffi-napi/src/lib.rs:797)
/// so daemon-mode clients can drive checkpoint/restore symmetrically
/// with embedded mode. Returns the number of facts written.
///
/// Filesystem caveat: `path` is interpreted on the daemon's filesystem,
/// not the caller's. Since the 2026-05 audit, `path` is also
/// sandboxed under `~/.car/memory/` via
/// [`car_ffi_common::memory_path::resolve`] — relative paths land
/// under the base, absolute paths must already be under the base,
/// `..` segments are rejected, symlinks pointing out are rejected.
/// Pre-2026-05 the path was passed straight to `std::fs::write` and
/// became an arbitrary file-write primitive. The base64-blob escape
/// hatch tracked in `Parslee-ai/car-releases#31` will plug into the
/// same resolver when it lands.
async fn handle_memory_persist(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let path = req
        .params
        .get("path")
        .and_then(|v| v.as_str())
        .ok_or("missing path")?;
    let resolved = car_ffi_common::memory_path::resolve(path)
        .map_err(|e| format!("memory.persist rejected path {path:?}: {e}"))?;
    let engine = session.memgine.lock().await;
    let facts: Vec<Value> = engine
        .graph
        .inner
        .node_indices()
        .filter_map(|nix| {
            let node = engine.graph.inner.node_weight(nix)?;
            if !node.is_valid() {
                return None;
            }
            if node.kind == car_memgine::MemKind::Identity
                || node.kind == car_memgine::MemKind::Environment
            {
                return None;
            }
            Some(serde_json::json!({
                "subject": node.key,
                "body": node.value,
                "kind": match node.kind {
                    car_memgine::MemKind::Fact => if node.is_constraint { "constraint" } else { "pattern" },
                    car_memgine::MemKind::Conversation => "outcome",
                    _ => "pattern",
                },
                "confidence": 0.5,
                "content_type": node.content_type.as_label(),
            }))
        })
        .collect();
    let count = facts.len();
    let json = serde_json::to_string(&facts).map_err(|e| e.to_string())?;
    std::fs::write(&resolved, json)
        .map_err(|e| format!("failed to write {}: {}", resolved.display(), e))?;
    Ok(Value::from(count as u64))
}

/// `memory.load` — replace the session's memgine with facts from the
/// JSON file at `path`. Mirrors NAPI `load_memory`
/// (car-ffi-napi/src/lib.rs:121). Same `~/.car/memory/` sandboxing
/// as `memory.persist` since the 2026-05 audit — relative paths
/// land under the base, anything that escapes is rejected.
async fn handle_memory_load(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let path = req
        .params
        .get("path")
        .and_then(|v| v.as_str())
        .ok_or("missing path")?;
    let resolved = car_ffi_common::memory_path::resolve(path)
        .map_err(|e| format!("memory.load rejected path {path:?}: {e}"))?;
    let content = std::fs::read_to_string(&resolved)
        .map_err(|e| format!("failed to read {}: {}", resolved.display(), e))?;
    let facts: Vec<Value> =
        serde_json::from_str(&content).map_err(|e| format!("invalid JSON: {}", e))?;
    let mut engine = session.memgine.lock().await;
    engine.reset();
    let mut count: u32 = 0;
    for fact in &facts {
        let subject = fact.get("subject").and_then(|v| v.as_str()).unwrap_or("");
        let body = fact.get("body").and_then(|v| v.as_str()).unwrap_or("");
        let kind = fact
            .get("kind")
            .and_then(|v| v.as_str())
            .unwrap_or("pattern");
        let fid = format!("loaded-{}", count);
        engine.ingest_fact(
            &fid,
            subject,
            body,
            "user",
            "peer",
            chrono::Utc::now(),
            "global",
            None,
            vec![],
            kind == "constraint",
        );
        count += 1;
    }
    Ok(Value::from(count))
}

// --- Skill handlers ---

async fn handle_skill_ingest(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let name = req
        .params
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or("missing name")?;
    let code = req
        .params
        .get("code")
        .and_then(|v| v.as_str())
        .ok_or("missing code")?;
    let platform = req
        .params
        .get("platform")
        .and_then(|v| v.as_str())
        .unwrap_or("unknown");
    let persona = req
        .params
        .get("persona")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let url_pattern = req
        .params
        .get("url_pattern")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let description = req
        .params
        .get("description")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let supersedes = req.params.get("supersedes").and_then(|v| v.as_str());
    let keywords: Vec<String> = req
        .params
        .get("task_keywords")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    let trigger = car_memgine::SkillTrigger {
        persona: persona.into(),
        url_pattern: url_pattern.into(),
        task_keywords: keywords,
        structured: None,
    };
    let mut engine = session.memgine.lock().await;
    let node = engine.ingest_skill(
        name,
        code,
        platform,
        trigger,
        description,
        supersedes,
        vec![],
        vec![],
    );
    Ok(Value::from(node.index() as u64))
}

async fn handle_skill_find(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let persona = req
        .params
        .get("persona")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let url = req.params.get("url").and_then(|v| v.as_str()).unwrap_or("");
    let task = req
        .params
        .get("task")
        .and_then(|v| v.as_str())
        .unwrap_or("");
    let max = req
        .params
        .get("max_results")
        .and_then(|v| v.as_u64())
        .unwrap_or(1) as usize;
    let engine = session.memgine.lock().await;
    let results = engine.find_skill(persona, url, task, max);
    let json: Vec<Value> = results
        .iter()
        .map(|(m, s)| {
            serde_json::json!({
                "name": m.name, "code": m.code, "platform": m.platform,
                "description": m.description, "stats": m.stats, "match_score": s,
            })
        })
        .collect();
    serde_json::to_value(json).map_err(|e| e.to_string())
}

async fn handle_skill_report(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let name = req
        .params
        .get("skill_name")
        .and_then(|v| v.as_str())
        .ok_or("missing skill_name")?;
    let outcome_str = req
        .params
        .get("outcome")
        .and_then(|v| v.as_str())
        .ok_or("missing outcome")?;
    let outcome = match outcome_str {
        "success" => car_memgine::SkillOutcome::Success,
        _ => car_memgine::SkillOutcome::Fail,
    };
    let mut engine = session.memgine.lock().await;
    let stats = engine
        .report_outcome(name, outcome)
        .ok_or(format!("skill '{}' not found", name))?;
    serde_json::to_value(stats).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Multi-agent coordination handlers
//
// The WsAgentRunner sends a `multi.run_agent` JSON-RPC request to the client.
// The client runs the model loop and responds with AgentOutput JSON.
// ---------------------------------------------------------------------------

/// AgentRunner backed by WebSocket callback to the client.
struct WsAgentRunner {
    channel: Arc<WsChannel>,
    host: Arc<crate::host::HostState>,
    client_id: String,
}

#[async_trait::async_trait]
impl car_multi::AgentRunner for WsAgentRunner {
    async fn run(
        &self,
        spec: &car_multi::AgentSpec,
        task: &str,
        _runtime: &car_engine::Runtime,
        _mailbox: &car_multi::Mailbox,
    ) -> std::result::Result<car_multi::AgentOutput, car_multi::MultiError> {
        use futures::SinkExt;

        let request_id = self.channel.next_request_id();
        let agent_id = agent_id_for_run(&self.client_id, &spec.name, &request_id);
        let agent = self
            .host
            .register_agent(
                &self.client_id,
                RegisterHostAgentRequest {
                    id: Some(agent_id.clone()),
                    name: spec.name.clone(),
                    kind: "callback".to_string(),
                    capabilities: spec.tools.clone(),
                    project: spec
                        .metadata
                        .get("project")
                        .and_then(|v| v.as_str())
                        .map(str::to_string),
                    pid: None,
                    display: serde_json::from_value(
                        spec.metadata
                            .get("display")
                            .cloned()
                            .unwrap_or(serde_json::Value::Null),
                    )
                    .unwrap_or_default(),
                    metadata: serde_json::to_value(&spec.metadata).unwrap_or(Value::Null),
                },
            )
            .await
            .map_err(|e| car_multi::MultiError::AgentFailed(spec.name.clone(), e))?;
        let _ = self
            .host
            .set_status(
                &self.client_id,
                SetHostAgentStatusRequest {
                    agent_id: agent.id.clone(),
                    status: HostAgentStatus::Running,
                    current_task: Some(task.to_string()),
                    message: Some(format!("{} started", spec.name)),
                    payload: serde_json::json!({ "task": task }),
                },
            )
            .await;

        let rpc_request = serde_json::json!({
            "jsonrpc": "2.0",
            "method": "multi.run_agent",
            "params": {
                "spec": spec,
                "task": task,
            },
            "id": request_id,
        });

        // Create oneshot channel for the response
        let (tx, rx) = tokio::sync::oneshot::channel();
        self.channel
            .pending
            .lock()
            .await
            .insert(request_id.clone(), tx);

        let msg = Message::Text(
            serde_json::to_string(&rpc_request)
                .map_err(|e| car_multi::MultiError::AgentFailed(spec.name.clone(), e.to_string()))?
                .into(),
        );
        if let Err(e) = self.channel.write.lock().await.send(msg).await {
            let _ = self
                .host
                .set_status(
                    &self.client_id,
                    SetHostAgentStatusRequest {
                        agent_id: agent_id.clone(),
                        status: HostAgentStatus::Errored,
                        current_task: None,
                        message: Some(format!("{} failed to start", spec.name)),
                        payload: serde_json::json!({ "error": e.to_string() }),
                    },
                )
                .await;
            return Err(car_multi::MultiError::AgentFailed(
                spec.name.clone(),
                format!("ws send error: {}", e),
            ));
        }

        // Wait for client response (5 min timeout for model loops)
        let response = match tokio::time::timeout(std::time::Duration::from_secs(300), rx).await {
            Ok(Ok(response)) => response,
            Ok(Err(_)) => {
                let _ = self
                    .host
                    .set_status(
                        &self.client_id,
                        SetHostAgentStatusRequest {
                            agent_id: agent_id.clone(),
                            status: HostAgentStatus::Errored,
                            current_task: None,
                            message: Some(format!("{} callback channel closed", spec.name)),
                            payload: Value::Null,
                        },
                    )
                    .await;
                return Err(car_multi::MultiError::AgentFailed(
                    spec.name.clone(),
                    "agent callback channel closed".into(),
                ));
            }
            Err(_) => {
                let _ = self
                    .host
                    .set_status(
                        &self.client_id,
                        SetHostAgentStatusRequest {
                            agent_id: agent_id.clone(),
                            status: HostAgentStatus::Errored,
                            current_task: None,
                            message: Some(format!("{} timed out", spec.name)),
                            payload: Value::Null,
                        },
                    )
                    .await;
                return Err(car_multi::MultiError::AgentFailed(
                    spec.name.clone(),
                    "agent callback timed out (300s)".into(),
                ));
            }
        };

        if let Some(err) = response.error {
            let _ = self
                .host
                .set_status(
                    &self.client_id,
                    SetHostAgentStatusRequest {
                        agent_id: agent_id.clone(),
                        status: HostAgentStatus::Errored,
                        current_task: None,
                        message: Some(format!("{} errored", spec.name)),
                        payload: serde_json::json!({ "error": err }),
                    },
                )
                .await;
            return Err(car_multi::MultiError::AgentFailed(spec.name.clone(), err));
        }

        let output_value = response.output.unwrap_or(Value::Null);
        let output: car_multi::AgentOutput = serde_json::from_value(output_value).map_err(|e| {
            car_multi::MultiError::AgentFailed(
                spec.name.clone(),
                format!("invalid AgentOutput: {}", e),
            )
        })?;
        let status = if output.error.is_some() {
            HostAgentStatus::Errored
        } else {
            HostAgentStatus::Completed
        };
        let message = if output.error.is_some() {
            format!("{} errored", spec.name)
        } else {
            format!("{} completed", spec.name)
        };
        let _ = self
            .host
            .set_status(
                &self.client_id,
                SetHostAgentStatusRequest {
                    agent_id,
                    status,
                    current_task: None,
                    message: Some(message),
                    payload: serde_json::to_value(&output).unwrap_or(Value::Null),
                },
            )
            .await;

        Ok(output)
    }
}

fn agent_id_for_run(client_id: &str, name: &str, request_id: &str) -> String {
    let safe_name: String = name
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    format!("{}:{}:{}", client_id, safe_name, request_id)
}

async fn handle_multi_swarm(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let mode_str = req
        .params
        .get("mode")
        .and_then(|v| v.as_str())
        .ok_or("missing 'mode'")?;
    let agents_val = req.params.get("agents").ok_or("missing 'agents'")?;
    let task = req
        .params
        .get("task")
        .and_then(|v| v.as_str())
        .ok_or("missing 'task'")?;

    let swarm_mode: car_multi::SwarmMode = serde_json::from_str(&format!("\"{}\"", mode_str))
        .map_err(|e| format!("invalid mode '{}': {}", mode_str, e))?;
    let agent_specs: Vec<car_multi::AgentSpec> =
        serde_json::from_value(agents_val.clone()).map_err(|e| format!("invalid agents: {}", e))?;
    let synth: Option<car_multi::AgentSpec> = req
        .params
        .get("synthesizer")
        .map(|v| serde_json::from_value(v.clone()))
        .transpose()
        .map_err(|e| format!("invalid synthesizer: {}", e))?;

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let infra = car_multi::SharedInfra::new();

    let mut swarm = car_multi::Swarm::new(agent_specs, swarm_mode);
    if let Some(s) = synth {
        swarm = swarm.with_synthesizer(s);
    }

    let result = swarm
        .run(task, &runner, &infra)
        .await
        .map_err(|e| format!("swarm error: {}", e))?;
    serde_json::to_value(result).map_err(|e| e.to_string())
}

async fn handle_multi_pipeline(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let stages_val = req.params.get("stages").ok_or("missing 'stages'")?;
    let task = req
        .params
        .get("task")
        .and_then(|v| v.as_str())
        .ok_or("missing 'task'")?;

    let stage_specs: Vec<car_multi::AgentSpec> =
        serde_json::from_value(stages_val.clone()).map_err(|e| format!("invalid stages: {}", e))?;

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let infra = car_multi::SharedInfra::new();

    let result = car_multi::Pipeline::new(stage_specs)
        .run(task, &runner, &infra)
        .await
        .map_err(|e| format!("pipeline error: {}", e))?;
    serde_json::to_value(result).map_err(|e| e.to_string())
}

async fn handle_multi_supervisor(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let workers_val = req.params.get("workers").ok_or("missing 'workers'")?;
    let supervisor_val = req.params.get("supervisor").ok_or("missing 'supervisor'")?;
    let task = req
        .params
        .get("task")
        .and_then(|v| v.as_str())
        .ok_or("missing 'task'")?;
    let max_rounds = req
        .params
        .get("max_rounds")
        .and_then(|v| v.as_u64())
        .unwrap_or(3) as u32;

    let worker_specs: Vec<car_multi::AgentSpec> = serde_json::from_value(workers_val.clone())
        .map_err(|e| format!("invalid workers: {}", e))?;
    let supervisor_spec: car_multi::AgentSpec = serde_json::from_value(supervisor_val.clone())
        .map_err(|e| format!("invalid supervisor: {}", e))?;

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let infra = car_multi::SharedInfra::new();

    let result = car_multi::Supervisor::new(worker_specs, supervisor_spec)
        .with_max_rounds(max_rounds)
        .run(task, &runner, &infra)
        .await
        .map_err(|e| format!("supervisor error: {}", e))?;
    serde_json::to_value(result).map_err(|e| e.to_string())
}

async fn handle_multi_map_reduce(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let mapper_val = req.params.get("mapper").ok_or("missing 'mapper'")?;
    let reducer_val = req.params.get("reducer").ok_or("missing 'reducer'")?;
    let task = req
        .params
        .get("task")
        .and_then(|v| v.as_str())
        .ok_or("missing 'task'")?;
    let items_val = req.params.get("items").ok_or("missing 'items'")?;

    let mapper_spec: car_multi::AgentSpec =
        serde_json::from_value(mapper_val.clone()).map_err(|e| format!("invalid mapper: {}", e))?;
    let reducer_spec: car_multi::AgentSpec = serde_json::from_value(reducer_val.clone())
        .map_err(|e| format!("invalid reducer: {}", e))?;
    let items: Vec<String> =
        serde_json::from_value(items_val.clone()).map_err(|e| format!("invalid items: {}", e))?;

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let infra = car_multi::SharedInfra::new();

    let result = car_multi::MapReduce::new(mapper_spec, reducer_spec)
        .run(task, &items, &runner, &infra)
        .await
        .map_err(|e| format!("map_reduce error: {}", e))?;
    serde_json::to_value(result).map_err(|e| e.to_string())
}

async fn handle_multi_vote(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let agents_val = req.params.get("agents").ok_or("missing 'agents'")?;
    let task = req
        .params
        .get("task")
        .and_then(|v| v.as_str())
        .ok_or("missing 'task'")?;

    let agent_specs: Vec<car_multi::AgentSpec> =
        serde_json::from_value(agents_val.clone()).map_err(|e| format!("invalid agents: {}", e))?;
    let synth: Option<car_multi::AgentSpec> = req
        .params
        .get("synthesizer")
        .map(|v| serde_json::from_value(v.clone()))
        .transpose()
        .map_err(|e| format!("invalid synthesizer: {}", e))?;

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let infra = car_multi::SharedInfra::new();

    let mut vote = car_multi::Vote::new(agent_specs);
    if let Some(s) = synth {
        vote = vote.with_synthesizer(s);
    }

    let result = vote
        .run(task, &runner, &infra)
        .await
        .map_err(|e| format!("vote error: {}", e))?;
    serde_json::to_value(result).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Scheduler handlers
// ---------------------------------------------------------------------------

fn handle_scheduler_create(req: &JsonRpcMessage) -> Result<Value, String> {
    let name = req
        .params
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or("scheduler.create requires 'name'")?;
    let prompt = req
        .params
        .get("prompt")
        .and_then(|v| v.as_str())
        .ok_or("scheduler.create requires 'prompt'")?;

    let mut task = car_scheduler::Task::new(name, prompt);

    if let Some(t) = req.params.get("trigger").and_then(|v| v.as_str()) {
        let trigger = match t {
            "once" => car_scheduler::TaskTrigger::Once,
            "cron" => car_scheduler::TaskTrigger::Cron,
            "interval" => car_scheduler::TaskTrigger::Interval,
            "file_watch" => car_scheduler::TaskTrigger::FileWatch,
            _ => car_scheduler::TaskTrigger::Manual,
        };
        let schedule = req
            .params
            .get("schedule")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        task = task.with_trigger(trigger, schedule);
    }

    if let Some(sp) = req.params.get("system_prompt").and_then(|v| v.as_str()) {
        task = task.with_system_prompt(sp);
    }

    serde_json::to_value(&task).map_err(|e| e.to_string())
}

async fn handle_scheduler_run(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let task_val = req
        .params
        .get("task")
        .ok_or("scheduler.run requires 'task'")?;
    let mut task: car_scheduler::Task =
        serde_json::from_value(task_val.clone()).map_err(|e| format!("invalid task: {}", e))?;

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let executor = car_scheduler::Executor::new(runner);
    let execution = executor.run_once(&mut task).await;

    serde_json::to_value(&execution).map_err(|e| e.to_string())
}

async fn handle_scheduler_run_loop(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let task_val = req
        .params
        .get("task")
        .ok_or("scheduler.run_loop requires 'task'")?;
    let mut task: car_scheduler::Task =
        serde_json::from_value(task_val.clone()).map_err(|e| format!("invalid task: {}", e))?;
    let max_iterations = req
        .params
        .get("max_iterations")
        .and_then(|v| v.as_u64())
        .map(|v| v as u32);

    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let executor = car_scheduler::Executor::new(runner);
    let (_cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);
    let executions = executor
        .run_loop(&mut task, max_iterations, cancel_rx)
        .await;

    serde_json::to_value(&executions).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Inference handlers
// ---------------------------------------------------------------------------

fn get_inference_engine(state: &ServerState) -> &Arc<car_inference::InferenceEngine> {
    state.inference.get_or_init(|| {
        Arc::new(car_inference::InferenceEngine::new(
            car_inference::InferenceConfig::default(),
        ))
    })
}

async fn handle_infer(
    msg: &JsonRpcMessage,
    state: &ServerState,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let mut req: car_inference::GenerateRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;

    // If context_query is provided, build context from memgine and inject it
    if let Some(cq) = msg.params.get("context_query").and_then(|v| v.as_str()) {
        let mut memgine = session.memgine.lock().await;
        let ctx = memgine.build_context(cq);
        if !ctx.is_empty() {
            req.context = Some(ctx);
        }
    }

    // Process-wide admission gate. Held for the duration of the
    // generation so a burst of concurrent infer RPCs can't multiply
    // KV-cache + activation memory and take the host out. The
    // `_permit` binding is intentional — its `Drop` releases the slot
    // when this future returns.
    let _permit = state.admission.acquire().await;

    // Use generate_tracked() so tool_calls, usage, model_used, trace_id, and
    // latency_ms are preserved in the response. Plain `generate()` discards
    // everything except `.text`, which silently breaks tool-use over the
    // WebSocket protocol (issue #43).
    //
    // NOTE: This directly serializes `InferenceResult`. Any field added to
    // that struct in `car-inference` becomes part of the public WebSocket
    // protocol. The shape is locked by `inference_result_serializes_*` tests
    // in car-inference; updating those tests is part of intentionally
    // changing the wire contract.
    let result = engine
        .generate_tracked(req)
        .await
        .map_err(|e| e.to_string())?;
    serde_json::to_value(&result).map_err(|e| format!("serialize result: {}", e))
}

/// Streaming inference — mirrors NAPI `inferStream`. Closes
/// Parslee-ai/car-releases#30. Same `GenerateRequest` shape as
/// `infer`; emits `inference.stream.event` JSON-RPC notifications
/// during the run, and returns the final `InferenceResult` as the
/// JSON-RPC response when the stream completes.
///
/// Notification shape (server → client):
/// ```jsonc
/// {
///   "jsonrpc": "2.0",
///   "method": "inference.stream.event",
///   "params": {
///     "request_id": "<original RPC id>",
///     "event": { "type": "text" | "tool_start" | "tool_delta" | "usage", ... }
///   }
/// }
/// ```
///
/// The final `done` event is not pushed as a notification — it's
/// the JSON-RPC response with the accumulated `InferenceResult`.
/// `video.generate` — daemon-side wrapper for
/// `InferenceEngine::generate_video`. Mirrors `handle_infer`'s
/// admission gate + JSON request shape (Parslee-ai/car#185).
///
/// Previously the CLI's `cmd_video` constructed an in-process
/// engine and called `generate_video` directly — a v0.7 holdover
/// that bypassed the daemon. With this handler the CLI proxies
/// here, so the engine-level audio_passthrough gate fires
/// inside the daemon process where all FFI surfaces converge.
async fn handle_image_generate(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let req: car_inference::GenerateImageRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;
    // Share the same admission gate as text/video generation — a burst
    // of image requests shouldn't smuggle around the concurrency cap.
    let _permit = state.admission.acquire().await;
    let result = engine
        .generate_image(req)
        .await
        .map_err(|e| e.to_string())?;
    serde_json::to_value(&result).map_err(|e| format!("serialize result: {}", e))
}

async fn handle_video_generate(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let req: car_inference::GenerateVideoRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;
    let _permit = state.admission.acquire().await;
    let result = engine
        .generate_video(req)
        .await
        .map_err(|e| e.to_string())?;
    serde_json::to_value(&result).map_err(|e| format!("serialize result: {}", e))
}

async fn handle_infer_stream(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
    state: &ServerState,
) -> Result<Value, String> {
    use futures::SinkExt;
    use tokio_tungstenite::tungstenite::Message;

    let engine = get_inference_engine(state);
    let mut req: car_inference::GenerateRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;

    // Same context-injection convenience as non-streaming `infer` so
    // the two methods have parity on the call shape.
    if let Some(cq) = msg.params.get("context_query").and_then(|v| v.as_str()) {
        let mut memgine = session.memgine.lock().await;
        let ctx = memgine.build_context(cq);
        if !ctx.is_empty() {
            req.context = Some(ctx);
        }
    }

    let _permit = state.admission.acquire().await;
    let mut rx = engine
        .generate_tracked_stream(req)
        .await
        .map_err(|e| e.to_string())?;

    let mut accumulator = car_inference::StreamAccumulator::default();
    let request_id = msg.id.clone();

    while let Some(event) = rx.recv().await {
        let event_payload = match &event {
            car_inference::StreamEvent::TextDelta(text) => {
                serde_json::json!({"type": "text", "data": text})
            }
            car_inference::StreamEvent::ToolCallStart { name, index, .. } => {
                serde_json::json!({"type": "tool_start", "name": name, "index": index})
            }
            car_inference::StreamEvent::ToolCallDelta {
                index,
                arguments_delta,
            } => serde_json::json!({
                "type": "tool_delta",
                "index": index,
                "data": arguments_delta,
            }),
            car_inference::StreamEvent::Usage {
                input_tokens,
                output_tokens,
            } => serde_json::json!({
                "type": "usage",
                "input_tokens": input_tokens,
                "output_tokens": output_tokens,
            }),
            // Done is delivered as the JSON-RPC response, not a
            // notification — matches the NAPI contract where the
            // standalone function's return value is the accumulated
            // result and the callback only sees in-progress events.
            car_inference::StreamEvent::Done { .. } => {
                accumulator.push(&event);
                continue;
            }
        };

        let notif = serde_json::json!({
            "jsonrpc": "2.0",
            "method": "inference.stream.event",
            "params": {
                "request_id": request_id,
                "event": event_payload,
            },
        });
        if let Ok(text) = serde_json::to_string(&notif) {
            let _ = session
                .channel
                .write
                .lock()
                .await
                .send(Message::Text(text.into()))
                .await;
        }
        accumulator.push(&event);
    }

    let (text, tool_calls, usage) = accumulator.finish_with_usage();
    Ok(serde_json::json!({
        "text": text,
        "tool_calls": tool_calls,
        "usage": usage,
    }))
}

async fn handle_embed(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let req: car_inference::EmbedRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;
    // Embeds load their own model weights; share the same admission
    // gate as generations so a burst of embed requests can't smuggle
    // around the concurrency cap.
    let _permit = state.admission.acquire().await;
    let result = engine.embed(req).await.map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"embeddings": result}))
}

async fn handle_classify(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let req: car_inference::ClassifyRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;
    let _permit = state.admission.acquire().await;
    let result = engine.classify(req).await.map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"classifications": result}))
}

/// Surface the current admission state so the menubar tray and
/// `car daemon status` can show "queued: N" / "permits: P/T". Read-only
/// snapshot — racy by definition but correct enough for status panels.
fn handle_admission_status(state: &ServerState) -> Result<Value, String> {
    let total = state.admission.permits();
    let available = state.admission.permits_available();
    let in_use = total.saturating_sub(available);
    Ok(serde_json::json!({
        "permits_total": total,
        "permits_available": available,
        "permits_in_use": in_use,
        "env_override": crate::admission::ENV_MAX_CONCURRENT,
    }))
}

async fn handle_tokenize(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let model = msg
        .params
        .get("model")
        .and_then(|v| v.as_str())
        .ok_or("missing 'model' parameter")?;
    let text = msg
        .params
        .get("text")
        .and_then(|v| v.as_str())
        .ok_or("missing 'text' parameter")?;
    let engine = get_inference_engine(state);
    let ids = engine
        .tokenize(model, text)
        .await
        .map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"tokens": ids}))
}

async fn handle_detokenize(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let model = msg
        .params
        .get("model")
        .and_then(|v| v.as_str())
        .ok_or("missing 'model' parameter")?;
    let tokens: Vec<u32> = msg
        .params
        .get("tokens")
        .and_then(|v| v.as_array())
        .ok_or("missing 'tokens' parameter")?
        .iter()
        .map(|t| {
            t.as_u64()
                .and_then(|n| u32::try_from(n).ok())
                .ok_or_else(|| "tokens[] must be u32 values".to_string())
        })
        .collect::<Result<Vec<_>, _>>()?;
    let engine = get_inference_engine(state);
    let text = engine
        .detokenize(model, &tokens)
        .await
        .map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"text": text}))
}

/// `models.register` — persist a user-supplied `ModelSchema` to
/// `~/.car/models.json` (Parslee-ai/car-releases#39). Replaces any
/// existing entry with the same `id`. Returns `{id, registered}`.
///
/// **Phase 1 limitation**: the daemon's live `UnifiedRegistry` is
/// not updated in-process — the new model becomes visible to
/// `models.list`, `infer`, `infer_stream` on the **next daemon
/// boot** when `load_user_config` re-reads the file. This is
/// enough to unblock opencode's setup flow (register ahead of
/// time, then start the daemon). Hot-update requires either an
/// `RwLock<InferenceEngine>` on `ServerState` or an
/// interior-mutable `UnifiedRegistry`; both touch 20+ call sites
/// and are tracked as a follow-up.
///
/// Until hot-update lands, callers SHOULD register their models
/// before issuing `infer` calls against them, and operators
/// SHOULD restart the daemon after batches of model
/// registrations.
async fn handle_models_register(
    req: &JsonRpcMessage,
    _state: &Arc<ServerState>,
) -> Result<Value, String> {
    // The params shape mirrors v0.7's FFI `rt.registerModel(schemaJson)`:
    // either the bare `ModelSchema` value, OR `{ schema: ModelSchema }`.
    // Honor both so existing in-process callers don't have to reshape.
    let schema_value = match req.params.get("schema") {
        Some(v) => v.clone(),
        None => req.params.clone(),
    };
    let schema: car_inference::ModelSchema =
        serde_json::from_value(schema_value).map_err(|e| format!("invalid ModelSchema: {e}"))?;
    let id = schema.id.clone();

    // Resolve the models.json path the same way UnifiedRegistry does:
    // `<models_dir>/../models.json` where models_dir defaults to
    // `~/.car/models/`. We read whatever's there, swap in the new
    // entry, and write back atomically.
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .ok_or_else(|| "no HOME / USERPROFILE in env".to_string())?;
    let car_dir = std::path::PathBuf::from(home).join(".car");
    std::fs::create_dir_all(&car_dir).map_err(|e| format!("create {}: {e}", car_dir.display()))?;
    let path = car_dir.join("models.json");

    let mut models: Vec<car_inference::ModelSchema> = if path.exists() {
        let text =
            std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
        if text.trim().is_empty() {
            Vec::new()
        } else {
            serde_json::from_str(&text).map_err(|e| format!("parse {}: {e}", path.display()))?
        }
    } else {
        Vec::new()
    };
    // Replace existing entry with the same id, else append.
    if let Some(slot) = models.iter_mut().find(|m| m.id == id) {
        *slot = schema;
    } else {
        models.push(schema);
    }
    let json =
        serde_json::to_string_pretty(&models).map_err(|e| format!("serialize models.json: {e}"))?;
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, json).map_err(|e| format!("write {}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, &path)
        .map_err(|e| format!("rename {} -> {}: {e}", tmp.display(), path.display()))?;
    Ok(serde_json::json!({
        "id": id,
        "registered": true,
        "path": path.to_string_lossy(),
        "note": "Daemon restart required for live UnifiedRegistry visibility \
                 (Parslee-ai/car-releases#39 phase 1). The model is persisted; \
                 next car-server boot loads it via UnifiedRegistry::load_user_config.",
    }))
}

/// `models.unregister` — remove an entry from `~/.car/models.json`
/// by id (Parslee-ai/car#186 — symmetric to `models.register`).
/// Returns `{ id, unregistered, path }` on success. Returns an error
/// when the model isn't present.
///
/// **Phase 1 limitation** (same as `models.register`): the daemon's
/// live `UnifiedRegistry` is not rebuilt — the removal takes effect
/// on the next daemon boot. Callers SHOULD restart the daemon after
/// a batch of unregistrations if they expect `models.list_unified`
/// to reflect the change immediately.
async fn handle_models_unregister(
    req: &JsonRpcMessage,
    _state: &Arc<ServerState>,
) -> Result<Value, String> {
    // Params shape mirrors the CLI flag: `{ id: string }`. Bare-string
    // params are honored for symmetry with the register handler's
    // tolerant shape (`{schema: ...}` OR bare schema).
    let id = match req.params.get("id") {
        Some(v) => v
            .as_str()
            .ok_or_else(|| "`id` must be a string".to_string())?
            .to_string(),
        None => match req.params.as_str() {
            Some(s) => s.to_string(),
            None => return Err("missing `id` parameter".to_string()),
        },
    };

    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .ok_or_else(|| "no HOME / USERPROFILE in env".to_string())?;
    let car_dir = std::path::PathBuf::from(home).join(".car");
    let path = car_dir.join("models.json");

    if !path.exists() {
        return Err(format!(
            "no models.json at {} — nothing to unregister",
            path.display()
        ));
    }
    let text =
        std::fs::read_to_string(&path).map_err(|e| format!("read {}: {e}", path.display()))?;
    let mut models: Vec<car_inference::ModelSchema> = if text.trim().is_empty() {
        Vec::new()
    } else {
        serde_json::from_str(&text).map_err(|e| format!("parse {}: {e}", path.display()))?
    };
    let before = models.len();
    models.retain(|m| m.id != id);
    if models.len() == before {
        return Err(format!("model {} not found in {}", id, path.display()));
    }
    let json =
        serde_json::to_string_pretty(&models).map_err(|e| format!("serialize models.json: {e}"))?;
    let tmp = path.with_extension("json.tmp");
    std::fs::write(&tmp, json).map_err(|e| format!("write {}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, &path)
        .map_err(|e| format!("rename {} -> {}: {e}", tmp.display(), path.display()))?;
    Ok(serde_json::json!({
        "id": id,
        "unregistered": true,
        "path": path.to_string_lossy(),
        "note": "Daemon restart required for live UnifiedRegistry visibility \
                 (phase 1, matching models.register).",
    }))
}

fn handle_models_list(state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let models = engine.list_models();
    serde_json::to_value(&models).map_err(|e| e.to_string())
}

fn handle_models_list_unified(state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let models = engine.list_models_unified();
    serde_json::to_value(&models).map_err(|e| e.to_string())
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ModelSearchParams {
    #[serde(default)]
    query: Option<String>,
    #[serde(default)]
    capability: Option<car_inference::ModelCapability>,
    #[serde(default)]
    provider: Option<String>,
    #[serde(default)]
    local_only: bool,
    #[serde(default)]
    available_only: bool,
    #[serde(default)]
    limit: Option<usize>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ModelSearchEntry {
    #[serde(flatten)]
    info: car_inference::ModelInfo,
    family: String,
    version: String,
    tags: Vec<String>,
    pullable: bool,
    upgrade: Option<car_inference::ModelUpgrade>,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
struct ModelSearchResponse {
    models: Vec<ModelSearchEntry>,
    upgrades: Vec<car_inference::ModelUpgrade>,
    total: usize,
    available: usize,
    local: usize,
    remote: usize,
}

fn handle_models_search(req: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let params: ModelSearchParams =
        serde_json::from_value(req.params.clone()).unwrap_or(ModelSearchParams {
            query: None,
            capability: None,
            provider: None,
            local_only: false,
            available_only: false,
            limit: None,
        });
    let engine = get_inference_engine(state);
    let upgrades = engine.available_model_upgrades();
    let upgrades_by_from: HashMap<String, car_inference::ModelUpgrade> = upgrades
        .iter()
        .cloned()
        .map(|upgrade| (upgrade.from_id.clone(), upgrade))
        .collect();
    let query = params
        .query
        .as_deref()
        .map(str::trim)
        .filter(|q| !q.is_empty())
        .map(|q| q.to_ascii_lowercase());
    let provider = params
        .provider
        .as_deref()
        .map(str::trim)
        .filter(|p| !p.is_empty())
        .map(|p| p.to_ascii_lowercase());

    let mut entries: Vec<ModelSearchEntry> = engine
        .list_schemas()
        .into_iter()
        .filter(|schema| {
            if let Some(capability) = params.capability {
                if !schema.has_capability(capability) {
                    return false;
                }
            }
            if let Some(provider) = provider.as_deref() {
                if schema.provider.to_ascii_lowercase() != provider {
                    return false;
                }
            }
            if params.local_only && !schema.is_local() {
                return false;
            }
            if params.available_only && !schema.available {
                return false;
            }
            if let Some(query) = query.as_deref() {
                let capability_text = schema
                    .capabilities
                    .iter()
                    .map(|cap| format!("{cap:?}").to_ascii_lowercase())
                    .collect::<Vec<_>>()
                    .join(" ");
                let haystack = format!(
                    "{} {} {} {} {} {}",
                    schema.id,
                    schema.name,
                    schema.provider,
                    schema.family,
                    schema.tags.join(" "),
                    capability_text
                )
                .to_ascii_lowercase();
                if !haystack.contains(query) {
                    return false;
                }
            }
            true
        })
        .map(|schema| {
            let pullable = !schema.available
                && matches!(
                    schema.source,
                    car_inference::ModelSource::Local { .. }
                        | car_inference::ModelSource::Mlx { .. }
                );
            let info = car_inference::ModelInfo::from(&schema);
            let upgrade = upgrades_by_from.get(&schema.id).cloned();
            ModelSearchEntry {
                info,
                family: schema.family,
                version: schema.version,
                tags: schema.tags,
                pullable,
                upgrade,
            }
        })
        .collect();
    entries.sort_by(|a, b| {
        b.info
            .available
            .cmp(&a.info.available)
            .then(b.info.is_local.cmp(&a.info.is_local))
            .then(a.info.name.cmp(&b.info.name))
    });
    if let Some(limit) = params.limit {
        entries.truncate(limit);
    }

    let total = entries.len();
    let available = entries.iter().filter(|entry| entry.info.available).count();
    let local = entries.iter().filter(|entry| entry.info.is_local).count();
    let response = ModelSearchResponse {
        models: entries,
        upgrades,
        total,
        available,
        local,
        remote: total.saturating_sub(local),
    };
    serde_json::to_value(response).map_err(|e| e.to_string())
}

fn handle_models_upgrades(state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    serde_json::to_value(serde_json::json!({
        "upgrades": engine.available_model_upgrades()
    }))
    .map_err(|e| e.to_string())
}

async fn handle_models_pull(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let name = msg
        .params
        .get("name")
        .or_else(|| msg.params.get("id"))
        .or_else(|| msg.params.get("model"))
        .and_then(|v| v.as_str())
        .ok_or("missing 'name' parameter")?;
    let engine = get_inference_engine(state);
    let path = engine.pull_model(name).await.map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"path": path.display().to_string()}))
}

async fn handle_skills_distill(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let events: Vec<car_memgine::TraceEvent> = serde_json::from_value(
        msg.params
            .get("events")
            .cloned()
            .unwrap_or(msg.params.clone()),
    )
    .map_err(|e| format!("invalid events: {}", e))?;

    let inference = get_inference_engine(state).clone();
    let engine = car_memgine::MemgineEngine::new(None).with_inference(inference);

    let skills = engine.distill_skills(&events).await;
    serde_json::to_value(&skills).map_err(|e| e.to_string())
}

/// Run memory consolidation against this client's session memgine
/// (or the daemon-owned per-agent memgine when bound — #170).
/// Returns the JSON `ConsolidationReport`.
async fn handle_memory_consolidate(
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let engine_arc = session.effective_memgine().await;
    let report = {
        let mut engine = engine_arc.lock().await;
        engine.consolidate().await
    };
    if let Some(id) = session.agent_id.lock().await.clone() {
        if let Err(e) = persist_agent_memgine(&id, &engine_arc).await {
            tracing::warn!(agent_id = %id, error = %e,
                "agent memgine persist after consolidate failed");
        }
    }
    serde_json::to_value(&report).map_err(|e| e.to_string())
}

/// Repair a degraded skill on this client's session memgine.
/// Returns `{ code: "..." }` on success, `null` if the skill
/// isn't broken or repair failed.
async fn handle_skill_repair(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let name = msg
        .params
        .get("skill_name")
        .and_then(|v| v.as_str())
        .ok_or("missing 'skill_name' parameter")?;
    let mut engine = session.memgine.lock().await;
    let code = engine.repair_skill(name).await;
    Ok(match code {
        Some(c) => serde_json::json!({ "code": c }),
        None => Value::Null,
    })
}

/// Ingest distilled skills into this client's session memgine.
/// Returns the number of nodes inserted.
async fn handle_skills_ingest_distilled(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let skills: Vec<car_memgine::DistilledSkill> = serde_json::from_value(
        msg.params
            .get("skills")
            .cloned()
            .unwrap_or(msg.params.clone()),
    )
    .map_err(|e| format!("invalid skills: {}", e))?;
    let mut engine = session.memgine.lock().await;
    let nodes = engine.ingest_distilled_skills(&skills);
    Ok(serde_json::json!({ "ingested": nodes.len() }))
}

/// Run skill evolution against this session's memgine for a
/// specified domain.  Returns the resulting `DistilledSkill` array.
async fn handle_skills_evolve(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let domain = msg
        .params
        .get("domain")
        .and_then(|v| v.as_str())
        .ok_or("missing 'domain' parameter")?
        .to_string();
    let events: Vec<car_memgine::TraceEvent> = serde_json::from_value(
        msg.params
            .get("events")
            .cloned()
            .unwrap_or(Value::Array(vec![])),
    )
    .map_err(|e| format!("invalid events: {}", e))?;
    let mut engine = session.memgine.lock().await;
    let skills = engine.evolve_skills(&events, &domain).await;
    serde_json::to_value(&skills).map_err(|e| e.to_string())
}

/// List domains whose skills are underperforming on this session.
async fn handle_skills_domains_needing_evolution(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let threshold = msg
        .params
        .get("threshold")
        .and_then(|v| v.as_f64())
        .unwrap_or(0.6);
    let engine = session.memgine.lock().await;
    let domains = engine.domains_needing_evolution(threshold);
    serde_json::to_value(&domains).map_err(|e| e.to_string())
}

/// Rerank documents against a query using a cross-encoder model.
async fn handle_rerank(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let req: car_inference::RerankRequest =
        serde_json::from_value(msg.params.clone()).map_err(|e| format!("invalid params: {}", e))?;
    let _permit = state.admission.acquire().await;
    let result = engine.rerank(req).await.map_err(|e| e.to_string())?;
    serde_json::to_value(&result).map_err(|e| e.to_string())
}

/// Transcribe audio at the given path. The path is interpreted on
/// the daemon's filesystem, not the FFI caller's — Daemon-mode
/// callers must pass a path the daemon can read (typically a
/// shared `~/.car/...` location or stdin push via the streaming
/// API).
async fn handle_transcribe(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    use base64::Engine as _;
    let engine = get_inference_engine(state);

    // Sandbox-crossing escape hatch (Parslee-ai/car-releases#31): when
    // the caller can't share a filesystem view with the daemon (e.g.
    // unsandboxed Milo talking to a sandboxed car-host), they pass
    // `audio_b64` instead of `audio_path`. We decode to a tempfile,
    // run transcribe against the path the engine expects, and clean up
    // on drop. Accepts either form; `audio_b64` wins if both are set.
    let mut params = msg.params.clone();
    let audio_b64 = params
        .as_object_mut()
        .and_then(|m| m.remove("audio_b64"))
        .and_then(|v| v.as_str().map(str::to_string));
    let _tmp_audio = if let Some(b64) = audio_b64 {
        let bytes = base64::engine::general_purpose::STANDARD
            .decode(b64.as_bytes())
            .map_err(|e| format!("audio_b64 decode failed: {e}"))?;
        let tmp = tempfile::NamedTempFile::new().map_err(|e| e.to_string())?;
        std::fs::write(tmp.path(), &bytes).map_err(|e| e.to_string())?;
        let path = tmp.path().to_string_lossy().into_owned();
        if let Some(obj) = params.as_object_mut() {
            obj.insert("audio_path".to_string(), Value::String(path));
        }
        Some(tmp)
    } else {
        None
    };

    let req: car_inference::TranscribeRequest =
        serde_json::from_value(params).map_err(|e| format!("invalid params: {}", e))?;
    let _permit = state.admission.acquire().await;
    let result = engine.transcribe(req).await.map_err(|e| e.to_string())?;
    serde_json::to_value(&result).map_err(|e| e.to_string())
}

/// Synthesize speech. By default writes to `output_path` on the
/// daemon's filesystem; when `return_b64: true` (or no `output_path`
/// was supplied) the result also includes an `audio_b64` field with
/// the rendered bytes inline so cross-sandbox callers can avoid
/// filesystem coordination. Closes Parslee-ai/car-releases#31.
async fn handle_synthesize(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    use base64::Engine as _;
    let engine = get_inference_engine(state);

    let mut params = msg.params.clone();
    let return_b64 = params
        .as_object_mut()
        .and_then(|m| m.remove("return_b64"))
        .and_then(|v| v.as_bool())
        .unwrap_or(false);
    let no_output_path = params
        .as_object()
        .map(|m| !m.contains_key("output_path"))
        .unwrap_or(true);

    let req: car_inference::SynthesizeRequest =
        serde_json::from_value(params).map_err(|e| format!("invalid params: {}", e))?;
    let _permit = state.admission.acquire().await;
    let result = engine.synthesize(req).await.map_err(|e| e.to_string())?;
    let mut value = serde_json::to_value(&result).map_err(|e| e.to_string())?;

    // Inline the bytes when the caller asked for them OR when no
    // output_path was specified (typical sandbox-crossing case —
    // they didn't pick a path because they have no shared one).
    if return_b64 || no_output_path {
        let bytes = std::fs::read(&result.audio_path).map_err(|e| {
            format!(
                "synthesize: failed to read rendered audio at {}: {e}",
                result.audio_path
            )
        })?;
        let encoded = base64::engine::general_purpose::STANDARD.encode(&bytes);
        if let Some(obj) = value.as_object_mut() {
            obj.insert("audio_b64".to_string(), Value::String(encoded));
        }
    }
    Ok(value)
}

/// Prepare the speech runtime (downloads / warmup). Returns a
/// JSON status string, mirroring the embedded
/// `prepare_speech_runtime` shape.
async fn handle_speech_prepare(state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let status = engine
        .prepare_speech_runtime()
        .await
        .map_err(|e| e.to_string())?;
    serde_json::to_value(&status).map_err(|e| e.to_string())
}

/// Adaptive route decision for a prompt — returns the routing
/// JSON the FFI's `route_model` returns.
async fn handle_models_route(msg: &JsonRpcMessage, state: &ServerState) -> Result<Value, String> {
    let prompt = msg
        .params
        .get("prompt")
        .and_then(|v| v.as_str())
        .ok_or("missing 'prompt' parameter")?;
    let engine = get_inference_engine(state);
    let decision = engine.route_adaptive(prompt).await;
    serde_json::to_value(&decision).map_err(|e| e.to_string())
}

/// Model performance profiles snapshot.
async fn handle_models_stats(state: &ServerState) -> Result<Value, String> {
    let engine = get_inference_engine(state);
    let profiles = engine.export_profiles().await;
    serde_json::to_value(&profiles).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct OutcomesResolvePendingParams {
    /// Flat `(trace_id, success, confidence, output)` tuples from the
    /// caller. Same shape `car-reason`'s session produces from its
    /// `ActionOutcome` vector. Daemon side runs the inference rules
    /// and writes resolved outcomes back to the shared tracker.
    action_results: Vec<(String, bool, f64, String)>,
}

/// `outcomes.resolve_pending` — write inferred outcomes back to the
/// shared engine's `OutcomeTracker` (Parslee-ai/car#189 follow-up).
///
/// Symmetric to the in-process path
/// `ReasoningInferenceHandle::record_inferred_outcomes` on
/// `InferenceEngine`: takes the per-action result tuples the
/// reasoning session produces, runs
/// `OutcomeTracker::infer_outcomes_from_action_sequence` to convert
/// them into `InferredOutcome` records, and calls
/// `resolve_pending_from_signals` under the tracker write lock. The
/// learning loop that adjusts routing decisions therefore survives
/// daemon-routed reasoning runs (previously a best-effort no-op on
/// the daemon side).
///
/// Returns `{ recorded: N }` where N is the number of action results
/// the caller passed. The tracker doesn't surface how many of those
/// actually had pending entries to resolve; that count would require
/// expanding the tracker API and isn't load-bearing for any caller
/// yet.
async fn handle_outcomes_resolve_pending(
    req: &JsonRpcMessage,
    state: &ServerState,
) -> Result<Value, String> {
    let params: OutcomesResolvePendingParams =
        serde_json::from_value(req.params.clone()).map_err(|e| format!("invalid params: {e}"))?;
    let engine = get_inference_engine(state);
    let mut tracker = engine.outcome_tracker.write().await;
    let inferred = tracker.infer_outcomes_from_action_sequence(&params.action_results);
    tracker.resolve_pending_from_signals(inferred);
    Ok(serde_json::json!({ "recorded": params.action_results.len() }))
}

/// Per-session event log size.
async fn handle_events_count(session: &crate::session::ClientSession) -> Result<Value, String> {
    let n = session.runtime.log.lock().await.len();
    Ok(Value::from(n as u64))
}

async fn handle_events_stats(session: &crate::session::ClientSession) -> Result<Value, String> {
    let stats = session.runtime.log.lock().await.stats();
    serde_json::to_value(stats).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct EventsTruncateParams {
    #[serde(default)]
    max_events: Option<usize>,
    #[serde(default)]
    max_spans: Option<usize>,
}

async fn handle_events_truncate(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let params: EventsTruncateParams =
        serde_json::from_value(msg.params.clone()).unwrap_or(EventsTruncateParams {
            max_events: None,
            max_spans: None,
        });
    let mut log = session.runtime.log.lock().await;
    let removed_events = params
        .max_events
        .map(|max| log.truncate_events_keep_last(max))
        .unwrap_or(0);
    let removed_spans = params
        .max_spans
        .map(|max| log.truncate_spans_keep_last(max))
        .unwrap_or(0);
    let stats = log.stats();
    Ok(serde_json::json!({
        "removedEvents": removed_events,
        "removedSpans": removed_spans,
        "stats": stats,
    }))
}

async fn handle_events_clear(session: &crate::session::ClientSession) -> Result<Value, String> {
    let mut log = session.runtime.log.lock().await;
    let removed = log.clear();
    Ok(serde_json::json!({ "removed": removed, "stats": log.stats() }))
}

/// Update the per-session replan config. Wire shape mirrors the
/// FFI's positional `set_replan_config` arguments — the engine
/// crate's `ReplanConfig` struct doesn't derive Serialize, so we
/// reconstruct it from a flat object here.
async fn handle_replan_set_config(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let max_replans = msg
        .params
        .get("max_replans")
        .and_then(|v| v.as_u64())
        .unwrap_or(0) as u32;
    let delay_ms = msg
        .params
        .get("delay_ms")
        .and_then(|v| v.as_u64())
        .unwrap_or(0);
    let verify_before_execute = msg
        .params
        .get("verify_before_execute")
        .and_then(|v| v.as_bool())
        .unwrap_or(true);
    let cfg = car_engine::ReplanConfig {
        max_replans,
        delay_ms,
        verify_before_execute,
    };
    session.runtime.set_replan_config(cfg).await;
    Ok(Value::Null)
}

async fn handle_skills_list(
    msg: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let domain = msg.params.get("domain").and_then(|v| v.as_str());
    let engine = session.memgine.lock().await;
    let skills: Vec<serde_json::Value> = engine
        .graph
        .inner
        .node_indices()
        .filter_map(|nix| {
            let node = engine.graph.inner.node_weight(nix)?;
            if node.kind != car_memgine::MemKind::Skill {
                return None;
            }
            let meta = car_memgine::SkillMeta::from_node(node)?;
            if let Some(d) = domain {
                match &meta.scope {
                    car_memgine::SkillScope::Global => {}
                    car_memgine::SkillScope::Domain(sd) if sd == d => {}
                    _ => return None,
                }
            }
            Some(serde_json::to_value(&meta).unwrap_or_default())
        })
        .collect();
    serde_json::to_value(&skills).map_err(|e| e.to_string())
}

#[derive(serde::Deserialize)]
struct SecretParams {
    #[serde(default)]
    service: Option<String>,
    key: String,
    #[serde(default)]
    value: Option<String>,
}

fn handle_secret_put(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: SecretParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let value = p.value.ok_or_else(|| "missing 'value'".to_string())?;
    car_ffi_common::secrets::put(p.service.as_deref(), &p.key, &value)
}

fn handle_secret_get(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: SecretParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::secrets::get(p.service.as_deref(), &p.key)
}

fn handle_secret_delete(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: SecretParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::secrets::delete(p.service.as_deref(), &p.key)
}

fn handle_secret_status(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: SecretParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::secrets::status(p.service.as_deref(), &p.key)
}

#[derive(serde::Deserialize)]
struct PermParams {
    domain: String,
    #[serde(default)]
    target_bundle_id: Option<String>,
}

fn handle_perm_status(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: PermParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::permissions::status(&p.domain, p.target_bundle_id.as_deref())
}

fn handle_perm_request(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: PermParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::permissions::request(&p.domain, p.target_bundle_id.as_deref())
}

fn handle_perm_explain(req: &JsonRpcMessage) -> Result<Value, String> {
    let p: PermParams = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::permissions::explain(&p.domain, p.target_bundle_id.as_deref())
}

fn handle_calendar_events(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        start: String,
        end: String,
        #[serde(default)]
        calendar_ids: Vec<String>,
    }
    let p: P = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let start = chrono::DateTime::parse_from_rfc3339(&p.start)
        .map_err(|e| format!("parse start: {}", e))?
        .with_timezone(&chrono::Utc);
    let end = chrono::DateTime::parse_from_rfc3339(&p.end)
        .map_err(|e| format!("parse end: {}", e))?
        .with_timezone(&chrono::Utc);
    car_ffi_common::integrations::calendar_events(start, end, &p.calendar_ids)
}

fn handle_contacts_find(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        query: String,
        #[serde(default = "default_limit")]
        limit: usize,
        #[serde(default)]
        container_ids: Vec<String>,
    }
    fn default_limit() -> usize {
        50
    }
    let p: P = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::integrations::contacts_list(&p.query, &p.container_ids, p.limit)
}

fn handle_mail_inbox(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize, Default)]
    struct P {
        #[serde(default)]
        account_ids: Vec<String>,
    }
    let p: P = serde_json::from_value(req.params.clone()).unwrap_or_default();
    car_ffi_common::integrations::mail_inbox(&p.account_ids)
}

fn handle_mail_send(req: &JsonRpcMessage) -> Result<Value, String> {
    let raw = req.params.to_string();
    car_ffi_common::integrations::mail_send(&raw)
}

fn handle_messages_chats(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        #[serde(default = "default_limit")]
        limit: usize,
    }
    fn default_limit() -> usize {
        50
    }
    let p: P = serde_json::from_value(req.params.clone()).unwrap_or(P { limit: 50 });
    car_ffi_common::integrations::messages_chats(p.limit)
}

fn handle_messages_send(req: &JsonRpcMessage) -> Result<Value, String> {
    let raw = req.params.to_string();
    car_ffi_common::integrations::messages_send(&raw)
}

fn handle_notes_find(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        query: String,
        #[serde(default = "default_limit")]
        limit: usize,
    }
    fn default_limit() -> usize {
        50
    }
    let p: P = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::integrations::notes_find(&p.query, p.limit)
}

fn handle_reminders_items(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        #[serde(default = "default_limit")]
        limit: usize,
    }
    fn default_limit() -> usize {
        50
    }
    let p: P = serde_json::from_value(req.params.clone()).unwrap_or(P { limit: 50 });
    car_ffi_common::integrations::reminders_items(p.limit)
}

fn handle_bookmarks_list(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        #[serde(default = "default_limit")]
        limit: usize,
    }
    fn default_limit() -> usize {
        100
    }
    let p: P = serde_json::from_value(req.params.clone()).unwrap_or(P { limit: 100 });
    car_ffi_common::integrations::bookmarks_list(p.limit)
}

fn handle_health_sleep(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        start: String,
        end: String,
    }
    let p: P = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let s = chrono::DateTime::parse_from_rfc3339(&p.start)
        .map_err(|e| format!("parse start: {}", e))?
        .with_timezone(&chrono::Utc);
    let e = chrono::DateTime::parse_from_rfc3339(&p.end)
        .map_err(|e| format!("parse end: {}", e))?
        .with_timezone(&chrono::Utc);
    car_ffi_common::health::sleep_windows(s, e)
}

fn handle_health_workouts(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        start: String,
        end: String,
    }
    let p: P = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let s = chrono::DateTime::parse_from_rfc3339(&p.start)
        .map_err(|e| format!("parse start: {}", e))?
        .with_timezone(&chrono::Utc);
    let e = chrono::DateTime::parse_from_rfc3339(&p.end)
        .map_err(|e| format!("parse end: {}", e))?
        .with_timezone(&chrono::Utc);
    car_ffi_common::health::workouts(s, e)
}

fn handle_health_activity(req: &JsonRpcMessage) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct P {
        start: String,
        end: String,
    }
    let p: P = serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let s = chrono::NaiveDate::parse_from_str(&p.start, "%Y-%m-%d")
        .map_err(|e| format!("parse start: {}", e))?;
    let e = chrono::NaiveDate::parse_from_str(&p.end, "%Y-%m-%d")
        .map_err(|e| format!("parse end: {}", e))?;
    car_ffi_common::health::activity(s, e)
}

async fn handle_browser_close(session: &crate::session::ClientSession) -> Result<Value, String> {
    let closed = session.browser.close().await?;
    Ok(serde_json::json!({"closed": closed}))
}

async fn handle_browser_run(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    #[derive(serde::Deserialize)]
    struct BrowserRunParams {
        /// Inline JSON string (CLI-compatible), OR the structured object.
        script: Value,
        #[serde(default)]
        width: Option<u32>,
        #[serde(default)]
        height: Option<u32>,
        /// When true, launches a visible Chromium window for interactive
        /// flows (first-time auth, 2FA, supervised runs). Only honored on
        /// the call that first launches the browser session — subsequent
        /// calls reuse the existing browser regardless.
        #[serde(default)]
        headed: Option<bool>,
        /// Extra Chromium command-line flags appended verbatim at
        /// launch (#112). Honoured only on the launch call.
        #[serde(default)]
        extra_args: Option<Vec<String>>,
    }
    let params: BrowserRunParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;

    // Accept either a JSON string OR a structured object under `script`.
    let script_json = match params.script {
        Value::String(s) => s,
        other => other.to_string(),
    };

    let browser_session = session
        .browser
        .get_or_launch(car_ffi_common::browser::BrowserLaunchOptions {
            width: params.width.unwrap_or(1280),
            height: params.height.unwrap_or(720),
            headless: !params.headed.unwrap_or(false),
            extra_args: params.extra_args.unwrap_or_default(),
        })
        .await?;

    let trace_json = browser_session.run(&script_json).await?;
    serde_json::from_str(&trace_json).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Voice streaming JSON-RPC methods
//
// Events are pushed back to the originating client as JSON-RPC notifications:
//   { "jsonrpc": "2.0", "method": "voice.event",
//     "params": { "session_id": "...", "event": {...} } }
//
// The session registry is process-wide (ServerState.voice_sessions); per-call
// WsVoiceEventSink instances bind each session to its originating WS so a
// client only ever sees events for sessions it started.
// ---------------------------------------------------------------------------

#[derive(Deserialize)]
struct VoiceStartParams {
    session_id: String,
    audio_source: Value,
    #[serde(default)]
    options: Option<Value>,
}

async fn handle_voice_transcribe_stream_start(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
    session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    let params: VoiceStartParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let audio_source_json =
        serde_json::to_string(&params.audio_source).map_err(|e| e.to_string())?;
    let options_json = params
        .options
        .as_ref()
        .map(|v| serde_json::to_string(v).map_err(|e| e.to_string()))
        .transpose()?;
    let sink: Arc<dyn car_voice::VoiceEventSink> = Arc::new(crate::session::WsVoiceEventSink {
        channel: session.channel.clone(),
    });
    let json = car_ffi_common::voice::transcribe_stream_start(
        &params.session_id,
        &audio_source_json,
        options_json.as_deref(),
        state.voice_sessions.clone(),
        sink,
    )
    .await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct VoiceStopParams {
    session_id: String,
}

async fn handle_voice_transcribe_stream_stop(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let params: VoiceStopParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let json = car_ffi_common::voice::transcribe_stream_stop(
        &params.session_id,
        state.voice_sessions.clone(),
    )
    .await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct VoicePushParams {
    session_id: String,
    /// Base64-encoded 16-bit signed PCM frame. JSON-RPC is text, so binary
    /// audio frames have to be encoded; clients in WS-binary contexts that
    /// want to skip the round trip can call the FFI directly.
    pcm_b64: String,
}

async fn handle_voice_transcribe_stream_push(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    use base64::Engine;
    let params: VoicePushParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let pcm = base64::engine::general_purpose::STANDARD
        .decode(&params.pcm_b64)
        .map_err(|e| format!("invalid pcm_b64: {}", e))?;
    let json = car_ffi_common::voice::transcribe_stream_push(
        &params.session_id,
        &pcm,
        state.voice_sessions.clone(),
    )
    .await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

fn handle_voice_sessions_list(state: &Arc<ServerState>) -> Value {
    let json = car_ffi_common::voice::list_voice_sessions(state.voice_sessions.clone());
    serde_json::from_str(&json).unwrap_or(Value::Null)
}

async fn handle_voice_dispatch_turn(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
    session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    let req_value = req.params.clone();
    let request: crate::voice_turn::DispatchVoiceTurnRequest =
        serde_json::from_value(req_value).map_err(|e| e.to_string())?;
    let engine = get_inference_engine(state).clone();
    let sink: Arc<dyn car_voice::VoiceEventSink> = Arc::new(crate::session::WsVoiceEventSink {
        channel: session.channel.clone(),
    });
    let resp = crate::voice_turn::dispatch(engine, request, sink).await?;
    serde_json::to_value(resp).map_err(|e| e.to_string())
}

async fn handle_voice_cancel_turn() -> Result<Value, String> {
    crate::voice_turn::cancel().await;
    Ok(serde_json::json!({"cancelled": true}))
}

async fn handle_voice_prewarm_turn(state: &Arc<ServerState>) -> Result<Value, String> {
    let engine = get_inference_engine(state).clone();
    crate::voice_turn::prewarm(engine).await;
    Ok(serde_json::json!({"prewarmed": true}))
}

// ---------------------------------------------------------------------------
// Inference runner over WebSocket — closes Parslee-ai/car-releases#24
//
// Bidirectional protocol shape:
//   1. Client → server: `inference.register_runner` (no params). The
//      session that calls this becomes the host for delegated models.
//   2. Server → client: `inference.runner.invoke` notification with
//      {call_id, request} when CAR needs to dispatch a delegated turn.
//   3. Client → server: `inference.runner.event` with {call_id, event}
//      for each chunk; `inference.runner.complete` with {call_id, result}
//      on success; `inference.runner.fail` with {call_id, error} on
//      failure.
//
// The server-side data is process-wide because only one inference
// runner can be registered at a time (matches the FFI bindings'
// constraint). The per-call mailboxes live in dedicated DashMaps.
// ---------------------------------------------------------------------------

fn ws_runner_session() -> &'static std::sync::RwLock<Option<Arc<crate::session::WsChannel>>> {
    static SLOT: std::sync::OnceLock<std::sync::RwLock<Option<Arc<crate::session::WsChannel>>>> =
        std::sync::OnceLock::new();
    SLOT.get_or_init(|| std::sync::RwLock::new(None))
}

fn ws_runner_calls() -> &'static dashmap::DashMap<String, car_inference::EventEmitter> {
    static MAP: std::sync::OnceLock<dashmap::DashMap<String, car_inference::EventEmitter>> =
        std::sync::OnceLock::new();
    MAP.get_or_init(dashmap::DashMap::new)
}

fn ws_runner_completions() -> &'static dashmap::DashMap<
    String,
    tokio::sync::oneshot::Sender<std::result::Result<car_inference::RunnerResult, String>>,
> {
    static MAP: std::sync::OnceLock<
        dashmap::DashMap<
            String,
            tokio::sync::oneshot::Sender<std::result::Result<car_inference::RunnerResult, String>>,
        >,
    > = std::sync::OnceLock::new();
    MAP.get_or_init(dashmap::DashMap::new)
}

struct WsInferenceRunner;

#[async_trait::async_trait]
impl car_inference::InferenceRunner for WsInferenceRunner {
    async fn run(
        &self,
        request: car_inference::tasks::generate::GenerateRequest,
        emitter: car_inference::EventEmitter,
    ) -> std::result::Result<car_inference::RunnerResult, car_inference::RunnerError> {
        let channel = ws_runner_session()
            .read()
            .map_err(|e| {
                car_inference::RunnerError::Failed(format!("ws runner slot poisoned: {e}"))
            })?
            .clone()
            .ok_or_else(|| {
                car_inference::RunnerError::Declined(
                    "no WebSocket inference runner registered — call inference.register_runner first"
                        .into(),
                )
            })?;

        let call_id = uuid::Uuid::new_v4().to_string();
        let request_json = serde_json::to_value(&request)
            .map_err(|e| car_inference::RunnerError::Failed(e.to_string()))?;
        let (tx, rx) = tokio::sync::oneshot::channel();
        ws_runner_calls().insert(call_id.clone(), emitter);
        ws_runner_completions().insert(call_id.clone(), tx);

        // Fire the invoke notification.
        use futures::SinkExt;
        let notification = serde_json::json!({
            "jsonrpc": "2.0",
            "method": "inference.runner.invoke",
            "params": {
                "call_id": call_id,
                "request": request_json,
            },
        });
        let text = serde_json::to_string(&notification)
            .map_err(|e| car_inference::RunnerError::Failed(e.to_string()))?;
        let _ = channel
            .write
            .lock()
            .await
            .send(tokio_tungstenite::tungstenite::Message::Text(text.into()))
            .await;

        let result = rx.await.map_err(|_| {
            car_inference::RunnerError::Failed("runner completion channel dropped".into())
        })?;
        ws_runner_calls().remove(&call_id);
        result.map_err(car_inference::RunnerError::Failed)
    }
}

async fn handle_inference_register_runner(
    session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    let mut guard = ws_runner_session()
        .write()
        .map_err(|e| format!("ws runner slot poisoned: {e}"))?;
    *guard = Some(session.channel.clone());
    drop(guard);
    car_inference::set_inference_runner(Some(Arc::new(WsInferenceRunner)));
    Ok(serde_json::json!({"registered": true}))
}

#[derive(serde::Deserialize)]
struct InferenceRunnerEventParams {
    call_id: String,
    event: Value,
}

async fn handle_inference_runner_event(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: InferenceRunnerEventParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let stream_event = match parse_runner_event_value(&params.event) {
        Some(e) => e,
        None => return Err("unrecognised runner event shape".into()),
    };
    if let Some(entry) = ws_runner_calls().get(&params.call_id) {
        let emitter = entry.value().clone();
        tokio::spawn(async move { emitter.emit(stream_event).await });
    }
    Ok(serde_json::json!({"emitted": true}))
}

#[derive(serde::Deserialize)]
struct InferenceRunnerCompleteParams {
    call_id: String,
    result: Value,
}

async fn handle_inference_runner_complete(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: InferenceRunnerCompleteParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let result: std::result::Result<car_inference::RunnerResult, String> =
        serde_json::from_value(params.result)
            .map_err(|e| format!("invalid RunnerResult JSON: {e}"));
    if let Some((_, tx)) = ws_runner_completions().remove(&params.call_id) {
        let _ = tx.send(result);
    }
    Ok(serde_json::json!({"completed": true}))
}

#[derive(serde::Deserialize)]
struct InferenceRunnerFailParams {
    call_id: String,
    error: String,
}

async fn handle_inference_runner_fail(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: InferenceRunnerFailParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    if let Some((_, tx)) = ws_runner_completions().remove(&params.call_id) {
        let _ = tx.send(Err(params.error));
    }
    Ok(serde_json::json!({"failed": true}))
}

fn parse_runner_event_value(v: &Value) -> Option<car_inference::StreamEvent> {
    let ty = v.get("type").and_then(|t| t.as_str())?;
    match ty {
        "text" => Some(car_inference::StreamEvent::TextDelta(
            v.get("data")?.as_str()?.to_string(),
        )),
        "tool_start" => Some(car_inference::StreamEvent::ToolCallStart {
            name: v.get("name")?.as_str()?.to_string(),
            index: v.get("index")?.as_u64()? as usize,
            id: v.get("id").and_then(|i| i.as_str()).map(str::to_string),
        }),
        "tool_delta" => Some(car_inference::StreamEvent::ToolCallDelta {
            index: v.get("index")?.as_u64()? as usize,
            arguments_delta: v.get("data")?.as_str()?.to_string(),
        }),
        "usage" => Some(car_inference::StreamEvent::Usage {
            input_tokens: v.get("input_tokens")?.as_u64()?,
            output_tokens: v.get("output_tokens")?.as_u64()?,
        }),
        "done" => Some(car_inference::StreamEvent::Done {
            text: v.get("text")?.as_str()?.to_string(),
            tool_calls: v
                .get("tool_calls")
                .and_then(|tc| serde_json::from_value(tc.clone()).ok())
                .unwrap_or_default(),
        }),
        _ => None,
    }
}

#[derive(Deserialize)]
struct EnrollSpeakerParams {
    label: String,
    audio: Value,
}

async fn handle_enroll_speaker(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: EnrollSpeakerParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let audio_json = serde_json::to_string(&params.audio).map_err(|e| e.to_string())?;
    let json = car_ffi_common::voice::enroll_speaker(&params.label, &audio_json).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct RemoveEnrollmentParams {
    label: String,
}

fn handle_remove_enrollment(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: RemoveEnrollmentParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let json = car_ffi_common::voice::remove_enrollment(&params.label)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct WorkflowRunParams {
    workflow: Value,
}

async fn handle_workflow_run(
    req: &JsonRpcMessage,
    session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    let params: WorkflowRunParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let workflow_json = serde_json::to_string(&params.workflow).map_err(|e| e.to_string())?;
    let runner: Arc<dyn car_multi::AgentRunner> = Arc::new(WsAgentRunner {
        channel: session.channel.clone(),
        host: session.host.clone(),
        client_id: session.client_id.clone(),
    });
    let json = car_ffi_common::workflow::run_workflow(&workflow_json, runner).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct WorkflowVerifyParams {
    workflow: Value,
}

fn handle_workflow_verify(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: WorkflowVerifyParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let workflow_json = serde_json::to_string(&params.workflow).map_err(|e| e.to_string())?;
    let json = car_ffi_common::workflow::verify_workflow(&workflow_json)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Meeting JSON-RPC methods
// ---------------------------------------------------------------------------

async fn handle_meeting_start(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
    session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    // We need the meeting id BEFORE handing the upstream sink to
    // start_meeting so the WsMemgineIngestSink stamps transcripts with
    // the correct `meeting/<id>/<source>` speaker. Parse the request
    // here, mint an id if none was provided, and pass the same id
    // through to start_meeting via the request JSON.
    let mut req_value = req.params.clone();
    let meeting_id = req_value
        .get("id")
        .and_then(|v| v.as_str())
        .map(str::to_string)
        .unwrap_or_else(|| uuid::Uuid::new_v4().simple().to_string());
    if let Some(map) = req_value.as_object_mut() {
        map.insert("id".into(), Value::String(meeting_id.clone()));
    }
    let request_json = serde_json::to_string(&req_value).map_err(|e| e.to_string())?;

    let ws_upstream: Arc<dyn car_voice::VoiceEventSink> =
        Arc::new(crate::session::WsVoiceEventSink {
            channel: session.channel.clone(),
        });

    // Wrap the WS upstream with a memgine-ingest fanout that uses the
    // tokio::sync::Mutex-wrapped session memgine. We pass `None` for
    // the FFI-common `start_meeting` memgine arg to avoid the
    // sync-mutex contract there — ingest happens here instead.
    let upstream: Arc<dyn car_voice::VoiceEventSink> =
        Arc::new(crate::session::WsMemgineIngestSink {
            meeting_id,
            engine: session.memgine.clone(),
            upstream: ws_upstream,
        });

    let cwd = std::env::current_dir().ok();
    let json = crate::meeting::start_meeting(
        &request_json,
        state.meetings.clone(),
        state.voice_sessions.clone(),
        upstream,
        None,
        cwd,
    )
    .await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct MeetingStopParams {
    meeting_id: String,
    #[serde(default = "default_summarize")]
    summarize: bool,
}

fn default_summarize() -> bool {
    true
}

async fn handle_meeting_stop(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
    _session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    let params: MeetingStopParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let inference = if params.summarize {
        Some(state.inference.get().cloned()).flatten()
    } else {
        None
    };
    let json = crate::meeting::stop_meeting(
        &params.meeting_id,
        params.summarize,
        state.meetings.clone(),
        state.voice_sessions.clone(),
        inference,
    )
    .await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize, Default)]
struct MeetingListParams {
    #[serde(default)]
    root: Option<std::path::PathBuf>,
}

fn handle_meeting_list(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: MeetingListParams = serde_json::from_value(req.params.clone()).unwrap_or_default();
    let cwd = std::env::current_dir().ok();
    let json = crate::meeting::list_meetings(params.root, cwd)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
struct MeetingGetParams {
    meeting_id: String,
    #[serde(default)]
    root: Option<std::path::PathBuf>,
}

fn handle_meeting_get(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: MeetingGetParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let cwd = std::env::current_dir().ok();
    let json = crate::meeting::get_meeting(&params.meeting_id, params.root, cwd)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Agent registry — file-based cross-process discovery (#111)
// ---------------------------------------------------------------------------

#[derive(Deserialize, Default)]
struct RegistryRegisterParams {
    /// Caller serializes their AgentEntry as a JSON value; we
    /// re-serialize it so the ffi-common helper can validate the
    /// shape with the same parser used by the bindings.
    entry: Value,
    #[serde(default)]
    registry_path: Option<std::path::PathBuf>,
}

fn handle_registry_register(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: RegistryRegisterParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let entry_json = serde_json::to_string(&params.entry).map_err(|e| e.to_string())?;
    car_ffi_common::registry::register_agent(&entry_json, params.registry_path)?;
    Ok(Value::Null)
}

#[derive(Deserialize, Default)]
struct RegistryNameParams {
    name: String,
    #[serde(default)]
    registry_path: Option<std::path::PathBuf>,
}

fn handle_registry_heartbeat(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: RegistryNameParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let json = car_ffi_common::registry::agent_heartbeat(&params.name, params.registry_path)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

fn handle_registry_unregister(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: RegistryNameParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    car_ffi_common::registry::unregister_agent(&params.name, params.registry_path)?;
    Ok(Value::Null)
}

#[derive(Deserialize, Default)]
struct RegistryListParams {
    #[serde(default)]
    registry_path: Option<std::path::PathBuf>,
}

fn handle_registry_list(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: RegistryListParams = serde_json::from_value(req.params.clone()).unwrap_or_default();
    let json = car_ffi_common::registry::list_agents(params.registry_path)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize, Default)]
struct RegistryReapParams {
    /// Heartbeats older than this many seconds are reaped. Default
    /// 60 — two missed 20s heartbeats trigger removal.
    #[serde(default = "default_reap_age")]
    max_age_secs: u64,
    #[serde(default)]
    registry_path: Option<std::path::PathBuf>,
}

fn default_reap_age() -> u64 {
    60
}

fn handle_registry_reap(req: &JsonRpcMessage) -> Result<Value, String> {
    let params: RegistryReapParams = serde_json::from_value(req.params.clone()).unwrap_or_default();
    let json =
        car_ffi_common::registry::reap_stale_agents(params.max_age_secs, params.registry_path)?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// car-a2a server lifecycle (mirrors NAPI startA2aServer / stopA2aServer /
// a2aServerStatus and PyO3 start_a2a_server / stop_a2a_server /
// a2a_server_status — closes the binding gap noted in #126).
// ---------------------------------------------------------------------------

async fn handle_a2a_start(
    req: &JsonRpcMessage,
    session: &crate::session::ClientSession,
) -> Result<Value, String> {
    let params_json = serde_json::to_string(&req.params).map_err(|e| e.to_string())?;
    // Always hand the session's runtime through. start_a2a uses it
    // only when `share_session_runtime: true` is set in params;
    // otherwise it falls back to the legacy fresh-Runtime + agent_basics
    // path. Passing it unconditionally keeps the FFI layer ignorant of
    // the flag's plumbing.
    let json = crate::a2a::start_a2a(&params_json, Some(session.runtime.clone())).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

fn handle_a2a_stop() -> Result<Value, String> {
    let json = crate::a2a::stop_a2a()?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

fn handle_a2a_status() -> Result<Value, String> {
    let json = crate::a2a::a2a_status()?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct A2aSendParams {
    endpoint: String,
    message: car_a2a::Message,
    #[serde(default)]
    blocking: bool,
    #[serde(default = "default_true")]
    ingest_a2ui: bool,
    #[serde(default)]
    route_auth: Option<A2aRouteAuth>,
    #[serde(default)]
    allow_untrusted_endpoint: bool,
}

fn default_true() -> bool {
    true
}

/// In-core A2A dispatcher entry point. Forwards the JSON-RPC method
/// + params to the lazy-initialized [`car_a2a::A2aDispatcher`] held
/// on `ServerState`. Closes Parslee-ai/car-releases#28.
///
/// Streaming methods (`message/stream`, `tasks/resubscribe` and their
/// PascalCase aliases) return `MethodNotFound` from the dispatcher's
/// transport-neutral surface — the standalone `start_a2a_listener`
/// HTTP path serves SSE for those, but the in-core WS surface is
/// JSON-RPC only. Same trade as the dispatcher itself.
async fn handle_a2a_dispatch(
    method: &str,
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let dispatcher = state.a2a_dispatcher().await;
    dispatcher
        .dispatch(method, req.params.clone())
        .await
        .map_err(|e| e.to_string())
}

async fn handle_a2a_send(req: &JsonRpcMessage, state: &Arc<ServerState>) -> Result<Value, String> {
    let params: A2aSendParams =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let endpoint = trusted_route_endpoint(
        Some(params.endpoint.clone()),
        params.allow_untrusted_endpoint,
    )
    .ok_or_else(|| {
        "`a2a.send` endpoint must be loopback unless allowUntrustedEndpoint is true".to_string()
    })?;
    let client = match params.route_auth.clone() {
        Some(auth) => {
            car_a2a::A2aClient::new(endpoint.clone()).with_auth(client_auth_from_route_auth(auth))
        }
        None => car_a2a::A2aClient::new(endpoint.clone()),
    };
    let result = client
        .send_message(params.message, params.blocking)
        .await
        .map_err(|e| e.to_string())?;
    let result_value = serde_json::to_value(&result).map_err(|e| e.to_string())?;
    let mut applied = Vec::new();
    if params.ingest_a2ui {
        state
            .a2ui
            .validate_payload(&result_value)
            .map_err(|e| e.to_string())?;
        let routed_endpoint = Some(endpoint.clone());
        for envelope in car_a2ui::envelopes_from_value(&result_value).map_err(|e| e.to_string())? {
            let owner = car_a2ui::owner_from_value(&result_value).map(|owner| {
                if owner.endpoint.is_none() {
                    owner.with_endpoint(routed_endpoint.clone())
                } else {
                    owner
                }
            });
            applied.push(
                apply_a2ui_envelope(state, envelope, owner, params.route_auth.clone()).await?,
            );
        }
    }
    Ok(serde_json::json!({
        "result": result,
        "a2ui": {
            "applied": applied,
        }
    }))
}

// ---------------------------------------------------------------------------
// macOS automation — AppleScript + Shortcuts (car-automation), Vision OCR
// (car-vision). Mirrors NAPI runApplescript / listShortcuts / runShortcut /
// visionOcr and PyO3 run_applescript / list_shortcuts / run_shortcut /
// vision_ocr.
// ---------------------------------------------------------------------------

async fn handle_run_applescript(req: &JsonRpcMessage) -> Result<Value, String> {
    let args_json = serde_json::to_string(&req.params).map_err(|e| e.to_string())?;
    let json = car_ffi_common::automation::run_applescript(&args_json).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

async fn handle_list_shortcuts(req: &JsonRpcMessage) -> Result<Value, String> {
    let args_json = serde_json::to_string(&req.params).map_err(|e| e.to_string())?;
    let json = car_ffi_common::automation::list_shortcuts(&args_json).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

async fn handle_run_shortcut(req: &JsonRpcMessage) -> Result<Value, String> {
    let args_json = serde_json::to_string(&req.params).map_err(|e| e.to_string())?;
    let json = car_ffi_common::automation::run_shortcut(&args_json).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

async fn handle_local_notification(req: &JsonRpcMessage) -> Result<Value, String> {
    let args_json = serde_json::to_string(&req.params).map_err(|e| e.to_string())?;
    let json = car_ffi_common::notifications::local(&args_json).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

async fn handle_vision_ocr(req: &JsonRpcMessage) -> Result<Value, String> {
    let args_json = serde_json::to_string(&req.params).map_err(|e| e.to_string())?;
    let json = car_ffi_common::vision::ocr(&args_json).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

// ---------------------------------------------------------------------------
// Lifecycle-managed agents (car_registry::supervisor) — Parslee-ai/car-releases#27
// ---------------------------------------------------------------------------

async fn handle_agents_list(state: &Arc<ServerState>) -> Result<Value, String> {
    // Observe-only mode (Parslee-ai/car-releases#44): a second
    // car-server on the host can't take the supervisor lock, so it
    // can't drive `Supervisor::list` — but it can still answer
    // `agents.list` by reading the on-disk manifest directly. The
    // `attached` decoration is local to whichever daemon the caller
    // is talking to, so observer-mode entries return `attached:
    // false` (this daemon hasn't received `session.auth` from those
    // children; the primary one has).
    let agents = match state.observer_manifest_path() {
        Some(p) => car_registry::supervisor::Supervisor::list_from_manifest(p)
            .map_err(|e| e.to_string())?,
        None => {
            let supervisor = state.supervisor()?;
            supervisor.list().await
        }
    };
    // Decorate each entry with `attached` + `session_id` so operators
    // see whether the supervised process has actually called
    // `session.auth { agent_id }` and bound a WS connection (#169) —
    // the lifecycle status (`Running`, etc.) only reports the
    // process-level view, which can't tell "alive but never
    // attached" from "alive and attached".
    let attached = state.attached_agents.lock().await.clone();
    let mut decorated: Vec<Value> = Vec::with_capacity(agents.len());
    for a in agents {
        let mut v = serde_json::to_value(&a).map_err(|e| e.to_string())?;
        let session_id = attached.get(&a.spec.id).cloned();
        if let Some(map) = v.as_object_mut() {
            map.insert("attached".to_string(), Value::Bool(session_id.is_some()));
            if let Some(sid) = session_id {
                map.insert("session_id".to_string(), Value::String(sid));
            }
        }
        decorated.push(v);
    }
    Ok(Value::Array(decorated))
}

async fn handle_agents_upsert(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let mut params = req.params.clone();
    // Optional `interpreter` sugar (#171). When present, the
    // supervisor resolves the bare program name (`"node"`,
    // `"python"`, …) against `$PATH` and writes the absolute path
    // into `command` *before* validation. This keeps the strict
    // no-PATH-lookup rule at upsert time while letting callers
    // stop hand-coding `/opt/homebrew/bin/node` into every
    // agents.json entry. Resolution happens once; subsequent PATH
    // changes do not silently rewire the binding.
    if let Some(name) = params
        .get("interpreter")
        .and_then(|v| v.as_str())
        .map(str::to_string)
    {
        let resolved =
            car_registry::supervisor::resolve_interpreter(&name).map_err(|e| e.to_string())?;
        params["command"] = Value::String(resolved.to_string_lossy().into_owned());
    }
    let spec: car_registry::supervisor::AgentSpec =
        serde_json::from_value(params).map_err(|e| e.to_string())?;
    let supervisor = state.supervisor()?;
    let agent = supervisor.upsert(spec).await.map_err(|e| e.to_string())?;
    serde_json::to_value(agent).map_err(|e| e.to_string())
}

/// `agents.install` — install a contributed-agent manifest
/// (Parslee-ai/car#182 phase 3). Caller passes the parsed
/// `AgentManifest` JSON; the daemon runs install-time validation
/// (`car_min_version`, capability negotiation against the daemon's
/// own advertisement) and adopts the manifest. Returns
/// `{ report, agent? }` where `agent` is the spawnable
/// `ManagedAgent` for `external_process` transports and absent for
/// `pure_data` / health_url-only manifests.
///
/// The host capability advertisement comes from
/// `HostCapabilities::daemon_default(car_version)` — operators that
/// want a tighter advertisement go through a future config phase;
/// this MVP uses the runtime's natural surface.
async fn handle_agents_install(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let manifest: car_registry::manifest::AgentManifest =
        serde_json::from_value(req.params.clone()).map_err(|e| e.to_string())?;
    let host = car_registry::install::HostCapabilities::daemon_default(env!("CARGO_PKG_VERSION"));
    let supervisor = state.supervisor()?;
    let (report, managed) = supervisor
        .install_manifest(manifest, &host)
        .await
        .map_err(|e| e.to_string())?;
    Ok(serde_json::json!({
        "report": {
            "missingOptional": report
                .missing_optional
                .iter()
                .map(|(ns, feat)| serde_json::json!({ "namespace": ns, "feature": feat }))
                .collect::<Vec<_>>(),
        },
        "agent": managed,
    }))
}

async fn handle_agents_health(state: &Arc<ServerState>) -> Result<Value, String> {
    // Observe-only mode (Parslee-ai/car-releases#44) — see
    // `handle_agents_list` for the rationale. The health view is a
    // pure function of each entry's `command` plus the on-disk
    // sandbox rules, so reading from the manifest is equivalent to
    // calling the live supervisor's `health()`.
    let entries = match state.observer_manifest_path() {
        Some(p) => car_registry::supervisor::Supervisor::health_from_manifest(p)
            .map_err(|e| e.to_string())?,
        None => {
            let supervisor = state.supervisor()?;
            supervisor.health().await
        }
    };
    serde_json::to_value(entries).map_err(|e| e.to_string())
}

fn extract_agent_id(req: &JsonRpcMessage) -> Result<String, String> {
    req.params
        .get("id")
        .and_then(Value::as_str)
        .map(str::to_string)
        .ok_or_else(|| "missing required `id` parameter".to_string())
}

async fn handle_agents_remove(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let id = extract_agent_id(req)?;
    let supervisor = state.supervisor()?;
    let removed = supervisor.remove(&id).await.map_err(|e| e.to_string())?;
    Ok(serde_json::json!({ "removed": removed }))
}

async fn handle_agents_start(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let id = extract_agent_id(req)?;
    let supervisor = state.supervisor()?;
    let agent = supervisor.start(&id).await.map_err(|e| e.to_string())?;
    serde_json::to_value(agent).map_err(|e| e.to_string())
}

async fn handle_agents_stop(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let id = extract_agent_id(req)?;
    let signal: car_registry::supervisor::StopSignal = req
        .params
        .get("signal")
        .map(|v| serde_json::from_value(v.clone()))
        .transpose()
        .map_err(|e| e.to_string())?
        .unwrap_or_default();
    let supervisor = state.supervisor()?;
    let agent = supervisor
        .stop(&id, signal)
        .await
        .map_err(|e| e.to_string())?;
    serde_json::to_value(agent).map_err(|e| e.to_string())
}

async fn handle_agents_restart(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let id = extract_agent_id(req)?;
    let supervisor = state.supervisor()?;
    let agent = supervisor.restart(&id).await.map_err(|e| e.to_string())?;
    serde_json::to_value(agent).map_err(|e| e.to_string())
}

async fn handle_agents_tail_log(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    let id = extract_agent_id(req)?;
    let n = req.params.get("n").and_then(Value::as_u64).unwrap_or(100) as usize;
    let supervisor = state.supervisor()?;
    let lines = supervisor
        .tail_log(&id, n)
        .await
        .map_err(|e| e.to_string())?;
    Ok(serde_json::json!({ "lines": lines }))
}

// ---------------------------------------------------------------------------
// External-agent detection (Phase 1 of docs/proposals/external-agent-detection.md)
//
// Discovery surface for agentic CLIs the user has already installed and
// authenticated (Claude Code, Codex, Gemini). Read-only — no invocation
// path yet; agents.invoke_external lands in Phase 2 alongside the JSON
// stdio adapter. The cache lives in car_ffi_common::external_agents so
// the in-process FFI singletons share the same snapshot.
// ---------------------------------------------------------------------------

async fn handle_agents_list_external(req: &JsonRpcMessage) -> Result<Value, String> {
    let include_health = req
        .params
        .get("include_health")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let json = car_ffi_common::external_agents::list(include_health).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

async fn handle_agents_detect_external(req: &JsonRpcMessage) -> Result<Value, String> {
    let include_health = req
        .params
        .get("include_health")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let json = car_ffi_common::external_agents::detect(include_health).await?;
    serde_json::from_str(&json).map_err(|e| e.to_string())
}

/// Per-task invocation of an external CLI agent. Required params:
/// `id` (adapter, e.g. `"claude-code"`) and `task` (the prompt).
/// Optional: `cwd`, `allowed_tools`, `max_turns`, `timeout_secs`.
///
/// Phase 2 stage 3 ships with `claude-code` only. Other adapter
/// ids return `is_error: true` with a structured `error` so hosts
/// can surface the gap without a separate error code.
///
/// Phase 2 stage 4a (governance): every invocation appends a
/// structured audit record to `~/.car/external-agents.jsonl`. The
/// record captures id, task, options, result, and the full
/// `tool_uses` list the assistant emitted — so even though the
/// agent executes its built-in tools in-process (which we can't
/// gate via stream-json), there's a complete after-the-fact audit
/// trail. Full policy gating (proposing each tool_use to CAR's
/// validator + getting a yes/no) requires the MCP server route in
/// stage 4b.
async fn handle_agents_invoke_external(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
    host_session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    let id = req
        .params
        .get("id")
        .and_then(Value::as_str)
        .ok_or_else(|| "missing required `id` parameter".to_string())?
        .to_string();
    let task = req
        .params
        .get("task")
        .and_then(Value::as_str)
        .ok_or_else(|| "missing required `task` parameter".to_string())?
        .to_string();
    let stream = req
        .params
        .get("stream")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    let session_id = req
        .params
        .get("session_id")
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| format!("ext-{}", uuid::Uuid::new_v4().simple()));

    // Build the options sub-object directly from req.params so
    // hosts can pass `cwd` / `allowed_tools` / `max_turns` /
    // `timeout_secs` as siblings of `id`/`task`. Strip the
    // dispatch + streaming fields so they don't pollute the
    // options serde.
    let mut options_value = req.params.clone();
    if let Some(obj) = options_value.as_object_mut() {
        obj.remove("id");
        obj.remove("task");
        obj.remove("stream");
        obj.remove("session_id");
        // Auto-fill `mcp_endpoint` from the bound MCP URL when the
        // caller didn't supply one. This is the load-bearing
        // wiring of MCP-4: external agents get CAR's tools (memory,
        // skills, verify) routed through the daemon's policy +
        // shared memgine without any per-call host configuration.
        // Callers who want to opt out can pass `"mcp_endpoint": ""`
        // (empty string) — the runner skips the temp-file write
        // when the value isn't a non-empty URL.
        let has_explicit_mcp = obj.contains_key("mcp_endpoint");
        if !has_explicit_mcp {
            if let Some(url) = state.mcp_url.get() {
                obj.insert("mcp_endpoint".to_string(), Value::String(url.clone()));
            }
        }
    }

    if !stream {
        // Legacy one-shot path. Unchanged shape for FFI consumers
        // and any caller that hasn't opted into streaming.
        let options_json = options_value.to_string();
        let json = car_ffi_common::external_agents::invoke(&id, &task, &options_json).await?;
        let result: Value = serde_json::from_str(&json).map_err(|e| e.to_string())?;
        append_external_agent_audit(&id, &task, &options_value, &result);
        return Ok(result);
    }

    // Streaming path. Returns an ack ({accepted, session_id})
    // immediately and streams `agents.chat.event` notifications
    // to the host's WS as the runner emits StreamEvents. Reuses
    // the chat_sessions routing infrastructure supervised agents
    // use — host UIs render both kinds through the same path.
    let opts: car_external_agents::InvokeOptions = serde_json::from_value(options_value.clone())
        .map_err(|e| format!("invalid options: {e}"))?;

    // Register the chat session BEFORE spawning so the host's
    // subscriber is correctly bound to this session_id by the
    // time the first event arrives. Reusing the supervised
    // agent chat infrastructure means `agents.chat.cancel`
    // routes to chat_sessions[session_id] and can find this
    // entry — though we don't currently honor cancel for
    // external invocations (the child process is killed only
    // on timeout or task drop; a future iteration can plumb a
    // CancellationToken through invoke_with_emitter).
    {
        // If a chat session is already registered for this id (the
        // typical proxy shape: host → agents.chat → supervised agent
        // → agents.invoke_external with the same session_id), DO NOT
        // overwrite it. The existing entry owns the routing to the
        // original host; clobbering it with our caller's client_id
        // would send streaming events to the proxying agent instead
        // of back to the host that issued agents.chat. Only register
        // a fresh entry when the slot is empty (a direct
        // host-to-invoke_external call without a prior agents.chat).
        let mut chats = state.chat_sessions.lock().await;
        chats.entry(session_id.clone()).or_insert_with(|| {
            let created_at = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            crate::session::ChatSession {
                agent_id: id.clone(),
                host_client_id: host_session.client_id.clone(),
                created_at,
            }
        });
    }

    // Single drain task pulls StreamEvents off an unbounded
    // channel and serializes WS sends to the host. Per-event
    // tokio::spawn would let sends race (which token arrives
    // first depends on lock acquisition order). The channel
    // is unbounded because claude's event volume is bounded
    // by user turn count — typically <50 events per invocation.
    use tokio::sync::mpsc;
    let (tx, mut rx) = mpsc::unbounded_channel::<car_external_agents::StreamEvent>();

    let drain_state = state.clone();
    let drain_session_id = session_id.clone();
    let drain_agent_id = id.clone();
    tokio::spawn(async move {
        while let Some(event) = rx.recv().await {
            emit_external_chat_event(&drain_state, &drain_session_id, &drain_agent_id, event).await;
        }
    });

    let emitter_tx = tx.clone();
    let emitter: car_external_agents::StreamEventEmitter = Arc::new(move |event| {
        // Send failure (rx dropped) means the drain task has
        // exited — usually because the host disconnected. The
        // runner will keep going; let it finish so the audit
        // log captures the full result.
        let _ = emitter_tx.send(event);
    });

    // Run the invocation in a separate task so this handler
    // can return the ack right away. The runner's child-process
    // future owns the spawn lifetime; if the host disconnects
    // mid-stream, the runner still completes (its events fall
    // on the floor at the drain layer) so the audit log lands.
    let spawn_state = state.clone();
    let spawn_session_id = session_id.clone();
    let spawn_id = id.clone();
    let spawn_task = task.clone();
    let spawn_options = options_value.clone();
    tokio::spawn(async move {
        let outcome =
            car_external_agents::invoke_with_emitter(&spawn_id, &spawn_task, opts, Some(emitter))
                .await;
        drop(tx); // signal drain task to exit after queue empties

        // Synthesize a terminal agents.chat.event so the host's
        // bubble finalizes. The runner doesn't emit a "done" event
        // itself — the result is the aggregate InvokeResult. We
        // translate it here.
        let terminal_params: Value;
        let result_value: Value;
        match outcome {
            Ok(res) => {
                // Pack the metadata into `finish_reason` as a
                // human-readable summary so the host's existing
                // ChatEvent decoder surfaces it without a schema
                // change. Hosts that want structured data can
                // re-issue `agents.invoke_external` with
                // `stream: false` and read the InvokeResult.
                let mut parts: Vec<String> = Vec::new();
                if res.turns > 0 {
                    parts.push(format!(
                        "{} turn{}",
                        res.turns,
                        if res.turns == 1 { "" } else { "s" }
                    ));
                }
                if res.tool_calls > 0 {
                    parts.push(format!(
                        "{} tool{}",
                        res.tool_calls,
                        if res.tool_calls == 1 { "" } else { "s" }
                    ));
                }
                if res.duration_ms > 0 {
                    parts.push(format!("{:.1}s", res.duration_ms as f64 / 1000.0));
                }
                let summary = if parts.is_empty() {
                    "stop".to_string()
                } else {
                    parts.join(" · ")
                };
                if res.is_error {
                    terminal_params = serde_json::json!({
                        "session_id": spawn_session_id,
                        "agent_id": spawn_id,
                        "kind": "error",
                        "error": res.error.clone().unwrap_or_else(|| "external agent reported error".to_string()),
                    });
                } else {
                    terminal_params = serde_json::json!({
                        "session_id": spawn_session_id,
                        "agent_id": spawn_id,
                        "kind": "done",
                        "finish_reason": summary,
                    });
                }
                result_value = serde_json::to_value(&res).unwrap_or(Value::Null);
            }
            Err(e) => {
                let message = format!("{e}");
                terminal_params = serde_json::json!({
                    "session_id": spawn_session_id,
                    "agent_id": spawn_id,
                    "kind": "error",
                    "error": message.clone(),
                });
                result_value = serde_json::json!({ "is_error": true, "error": message });
            }
        }
        send_external_chat_frame(&spawn_state, &spawn_session_id, terminal_params).await;
        spawn_state
            .chat_sessions
            .lock()
            .await
            .remove(&spawn_session_id);
        append_external_agent_audit(&spawn_id, &spawn_task, &spawn_options, &result_value);
    });

    Ok(serde_json::json!({
        "accepted": true,
        "session_id": session_id,
    }))
}

/// Translate one [`StreamEvent`] from the running external CLI
/// into an `agents.chat.event` notification on the originating
/// host's WS. Same wire shape supervised agents emit, so host
/// UIs render both kinds with one decoder.
///
/// Mapping:
/// - `Assistant` events with `text` content blocks → `kind: "token"`
///   per text block. Each block carries the full text the
///   assistant emitted in that turn (claude doesn't expose
///   word-level deltas via stream-json — it emits per-turn or
///   per-content-block chunks).
/// - `Assistant` events with `tool_use` blocks → `kind: "tool_call"`
///   per block (tool name in `detail`).
/// - `System` / `User` / `Result` / others → dropped (Result's
///   metadata is folded into the terminal `done` event the
///   outer task emits when the invocation finishes).
async fn emit_external_chat_event(
    state: &Arc<ServerState>,
    session_id: &str,
    agent_id: &str,
    event: car_external_agents::StreamEvent,
) {
    use car_external_agents::StreamEvent;
    match event {
        StreamEvent::Assistant(a) => {
            if let Some(content) = a.message.get("content").and_then(|v| v.as_array()) {
                for block in content {
                    let block_type = block.get("type").and_then(|v| v.as_str()).unwrap_or("");
                    match block_type {
                        "text" => {
                            if let Some(text) = block.get("text").and_then(|v| v.as_str()) {
                                if !text.is_empty() {
                                    let params = serde_json::json!({
                                        "session_id": session_id,
                                        "agent_id": agent_id,
                                        "kind": "token",
                                        "delta": text,
                                    });
                                    send_external_chat_frame(state, session_id, params).await;
                                }
                            }
                        }
                        "tool_use" => {
                            let name = block
                                .get("name")
                                .and_then(|v| v.as_str())
                                .unwrap_or("(unknown tool)");
                            let params = serde_json::json!({
                                "session_id": session_id,
                                "agent_id": agent_id,
                                "kind": "tool_call",
                                "detail": name,
                            });
                            send_external_chat_frame(state, session_id, params).await;
                        }
                        _ => {}
                    }
                }
            }
        }
        _ => {
            // System (session id init), User (tool result echo),
            // Result (final aggregate — folded into terminal
            // `done` event by the outer task), RateLimitEvent,
            // Other: not surfaced to host.
        }
    }
}

/// Send a single `agents.chat.event` notification to the host
/// session bound by `session_id`. Best-effort: a missing route
/// or a closed WS is silently dropped, the runner continues so
/// the audit log lands.
async fn send_external_chat_frame(state: &Arc<ServerState>, session_id: &str, params: Value) {
    use futures::SinkExt;
    use tokio_tungstenite::tungstenite::Message;

    let host_client_id = state
        .chat_sessions
        .lock()
        .await
        .get(session_id)
        .map(|s| s.host_client_id.clone());
    let Some(host_client_id) = host_client_id else {
        return;
    };
    let host_channel = {
        let sessions = state.sessions.lock().await;
        sessions.get(&host_client_id).map(|s| s.channel.clone())
    };
    let Some(channel) = host_channel else {
        return;
    };
    let frame = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "agents.chat.event",
        "params": params,
    });
    if let Ok(text) = serde_json::to_string(&frame) {
        let _ = channel
            .write
            .lock()
            .await
            .send(Message::Text(text.into()))
            .await;
    }
}

/// Append one JSONL audit record to `~/.car/external-agents.jsonl`.
/// Best-effort: a failure to open the journal must NOT fail the
/// invocation; the in-memory result already returned is the
/// authoritative answer. Logs at warn level when the write fails so
/// operators notice repeated failures.
fn append_external_agent_audit(id: &str, task: &str, options: &Value, result: &Value) {
    use std::io::Write;
    let car_dir = match std::env::var_os("HOME").map(std::path::PathBuf::from) {
        Some(home) => home.join(".car"),
        None => return,
    };
    if std::fs::create_dir_all(&car_dir).is_err() {
        return;
    }
    let path = car_dir.join("external-agents.jsonl");
    let record = serde_json::json!({
        "ts": chrono::Utc::now().to_rfc3339(),
        "adapter_id": id,
        "task": task,
        "options": options,
        "result": result,
    });
    let line = match serde_json::to_string(&record) {
        Ok(s) => s,
        Err(_) => return,
    };
    if let Ok(mut f) = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(&path)
    {
        let _ = writeln!(f, "{}", line);
    } else {
        tracing::warn!(
            path = %path.display(),
            "failed to append external-agent audit record"
        );
    }
}

/// Ground-truth health check. Optional `id` param picks one tool;
/// without it, every detected adapter is checked. `force: true`
/// bypasses the 30s per-tool TTL cache. Replaces the Phase 1
/// credential-file shape heuristic as the load-bearing signal for
/// "is this tool ready to invoke."
async fn handle_agents_health_external(req: &JsonRpcMessage) -> Result<Value, String> {
    let force = req
        .params
        .get("force")
        .and_then(Value::as_bool)
        .unwrap_or(false);
    if let Some(id) = req.params.get("id").and_then(Value::as_str) {
        let json = car_ffi_common::external_agents::health_one(id, force).await?;
        serde_json::from_str(&json).map_err(|e| e.to_string())
    } else {
        let json = car_ffi_common::external_agents::health(force).await?;
        serde_json::from_str(&json).map_err(|e| e.to_string())
    }
}

// ---------------------------------------------------------------------------
// agents.chat — unified chat surface (docs/proposals/agent-chat-surface.md)
// ---------------------------------------------------------------------------
//
// Host calls `agents.chat { agent_id, prompt, session_id?, stream? }`.
// The server looks up the target agent's attached WS connection,
// reverse-calls `agent.chat { session_id, prompt, context }` on it
// (same pattern as `tools.execute`), and returns once the agent acks.
// The agent then streams `agent.chat.event` notifications back, which
// the dispatcher intercepts (see `try_forward_agent_chat_event`) and
// rewrites as `agents.chat.event` notifications on the originating
// host's channel.

/// Timeout the server waits for the agent to ack `agent.chat`. The
/// streamed tokens come later as separate notifications and have no
/// bearing on this — this is just "did the agent receive the prompt
/// and accept it." Five seconds is generous for a local IPC ack.
const AGENT_CHAT_ACK_TIMEOUT_SECS: u64 = 5;

/// `agents.chat` — host issues a chat turn to a named agent. Returns
/// `{ accepted: true, session_id }` once the agent acks; streamed
/// tokens arrive on the host's channel as `agents.chat.event`
/// notifications keyed by the same `session_id`.
async fn handle_agents_chat(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
    host_session: &Arc<crate::session::ClientSession>,
) -> Result<Value, String> {
    use futures::SinkExt;
    use tokio::sync::oneshot;
    use tokio_tungstenite::tungstenite::Message;

    let agent_id = req
        .params
        .get("agent_id")
        .and_then(Value::as_str)
        .ok_or_else(|| "`agents.chat` requires `agent_id`".to_string())?
        .to_string();
    let prompt = req
        .params
        .get("prompt")
        .and_then(Value::as_str)
        .ok_or_else(|| "`agents.chat` requires `prompt`".to_string())?
        .to_string();
    let session_id = req
        .params
        .get("session_id")
        .and_then(Value::as_str)
        .map(str::to_string)
        .unwrap_or_else(|| format!("chat-{}", uuid::Uuid::new_v4().simple()));
    let stream = req
        .params
        .get("stream")
        .and_then(Value::as_bool)
        .unwrap_or(true);
    let voice_input = req
        .params
        .get("voice_input")
        .and_then(Value::as_bool)
        .unwrap_or(false);

    // Resolve the agent's attached WS channel via `attached_agents` →
    // `sessions` → `channel`. Both lookups must hit; a missing entry on
    // either side means the agent is registered in `agents.json` but
    // hasn't `session.auth`'d (or has disconnected), so refuse with a
    // structured error rather than silently parking the chat.
    let agent_client_id = state
        .attached_agents
        .lock()
        .await
        .get(&agent_id)
        .cloned()
        .ok_or_else(|| {
            format!(
                "agent `{}` is not attached to this daemon — supervisor may have it stopped, or it hasn't called session.auth yet",
                agent_id
            )
        })?;
    let agent_channel = {
        let sessions = state.sessions.lock().await;
        sessions
            .get(&agent_client_id)
            .map(|s| s.channel.clone())
            .ok_or_else(|| {
                format!(
                    "agent `{}` client_id `{}` not found in session registry (raced with disconnect)",
                    agent_id, agent_client_id
                )
            })?
    };

    // Register the chat session BEFORE sending the reverse call so any
    // `agent.chat.event` notifications the agent sends as part of
    // accepting the chat (e.g. an immediate `token` delta) route
    // correctly. Indexed by session_id so the notification interceptor
    // can locate the originating host without scanning.
    {
        let created_at = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        state.chat_sessions.lock().await.insert(
            session_id.clone(),
            crate::session::ChatSession {
                agent_id: agent_id.clone(),
                host_client_id: host_session.client_id.clone(),
                created_at,
            },
        );
    }

    // Reverse-callback: register a oneshot for the ack, send the
    // `agent.chat` JSON-RPC request on the agent's channel, await up
    // to AGENT_CHAT_ACK_TIMEOUT_SECS. Uses the same `pending` map the
    // tool-callback path uses (`WsToolExecutor`) — the dispatcher's
    // response demuxer at the top of `run_dispatch` already routes
    // `result` / `error` frames keyed by request id back through it.
    let request_id = agent_channel.next_request_id();
    let (tx, rx) = oneshot::channel();
    agent_channel
        .pending
        .lock()
        .await
        .insert(request_id.clone(), tx);

    let rpc_request = serde_json::json!({
        "jsonrpc": "2.0",
        "method": "agent.chat",
        "params": {
            "session_id": session_id,
            "prompt": prompt,
            "stream": stream,
            "context": {
                "host_client_id": host_session.client_id,
                "voice_input": voice_input,
            },
        },
        "id": request_id,
    });
    let msg = Message::Text(
        serde_json::to_string(&rpc_request)
            .map_err(|e| e.to_string())?
            .into(),
    );
    if let Err(e) = agent_channel.write.lock().await.send(msg).await {
        // Send failed — drop the pending waiter and the chat session
        // entry so a retry can take a fresh session_id without
        // colliding.
        agent_channel.pending.lock().await.remove(&request_id);
        state.chat_sessions.lock().await.remove(&session_id);
        return Err(format!(
            "failed to deliver agent.chat to `{}`: {}",
            agent_id, e
        ));
    }

    // Await the agent's ack. The dispatcher's response demuxer routes
    // the result/error back via the oneshot. Timeout means the agent
    // is alive but unresponsive — clean up routing state and surface a
    // structured error so the host UI doesn't hang.
    let ack = match tokio::time::timeout(
        std::time::Duration::from_secs(AGENT_CHAT_ACK_TIMEOUT_SECS),
        rx,
    )
    .await
    {
        Ok(Ok(resp)) => resp,
        Ok(Err(_)) => {
            // Channel closed — agent disconnected mid-call.
            state.chat_sessions.lock().await.remove(&session_id);
            return Err(format!(
                "agent `{}` disconnected before acking agents.chat",
                agent_id
            ));
        }
        Err(_) => {
            // Timeout — agent didn't respond in time. Don't keep the
            // chat session around: any later events from the agent
            // would route to a host that already returned an error.
            agent_channel.pending.lock().await.remove(&request_id);
            state.chat_sessions.lock().await.remove(&session_id);
            return Err(format!(
                "agent `{}` did not ack agents.chat within {}s",
                agent_id, AGENT_CHAT_ACK_TIMEOUT_SECS
            ));
        }
    };

    if let Some(err) = ack.error {
        // Agent explicitly rejected — drop the session and propagate.
        state.chat_sessions.lock().await.remove(&session_id);
        return Err(format!("agent `{}` rejected chat: {}", agent_id, err));
    }

    Ok(serde_json::json!({
        "accepted": true,
        "session_id": session_id,
    }))
}

/// `agents.chat.cancel` — host aborts an in-flight chat. Forwards
/// `agent.chat.cancel` to the bound agent so the agent can short-
/// circuit its inference stream + free upstream resources
/// (`inference.stream.cancel`). The chat session is dropped from
/// routing state immediately whether or not the agent acks the cancel
/// — further `agent.chat.event` notifications for this session_id
/// fall on the floor by design.
async fn handle_agents_chat_cancel(
    req: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> Result<Value, String> {
    use futures::SinkExt;
    use tokio_tungstenite::tungstenite::Message;

    let session_id = req
        .params
        .get("session_id")
        .and_then(Value::as_str)
        .ok_or_else(|| "`agents.chat.cancel` requires `session_id`".to_string())?
        .to_string();

    let chat = state.chat_sessions.lock().await.remove(&session_id);
    let chat = match chat {
        Some(c) => c,
        None => {
            // Already cancelled or never existed — idempotent.
            return Ok(serde_json::json!({ "cancelled": false, "reason": "unknown session_id" }));
        }
    };

    // Best-effort fire-and-forget to the agent. We've already removed
    // the routing entry, so no need to await any agent response.
    let agent_client_id = state
        .attached_agents
        .lock()
        .await
        .get(&chat.agent_id)
        .cloned();
    if let Some(client_id) = agent_client_id {
        let channel_opt = {
            let sessions = state.sessions.lock().await;
            sessions.get(&client_id).map(|s| s.channel.clone())
        };
        if let Some(channel) = channel_opt {
            let notification = serde_json::json!({
                "jsonrpc": "2.0",
                "method": "agent.chat.cancel",
                "params": { "session_id": session_id },
            });
            if let Ok(text) = serde_json::to_string(&notification) {
                let _ = channel
                    .write
                    .lock()
                    .await
                    .send(Message::Text(text.into()))
                    .await;
            }
        }
    }

    Ok(serde_json::json!({ "cancelled": true, "session_id": session_id }))
}

/// Forward an `agent.chat.event` notification from an agent's
/// connection to the originating host's connection, rewritten as an
/// `agents.chat.event` notification. Returns `true` if the inbound
/// frame was a chat-event we routed (so the dispatcher can `continue`
/// past the normal method dispatch and skip the wasted "unknown
/// method" response), `false` otherwise.
///
/// Terminal events (`kind: "done"` / `"error"`) also drop the routing
/// entry from `state.chat_sessions` so a later stray notification can
/// be rejected as orphaned without leaking memory.
pub(crate) async fn try_forward_agent_chat_event(
    parsed: &JsonRpcMessage,
    state: &Arc<ServerState>,
) -> bool {
    use futures::SinkExt;
    use tokio_tungstenite::tungstenite::Message;

    // Notification predicate: method is `agent.chat.event`, id is
    // missing/null (per JSON-RPC, notifications have no id), and
    // params carry a session_id.
    let Some(method) = parsed.method.as_deref() else {
        return false;
    };
    if method != "agent.chat.event" {
        return false;
    }
    if !parsed.id.is_null() {
        // Has an id → it's a request, not a notification. Let the
        // normal dispatcher handle it (and reply with method-not-found).
        return false;
    }
    let Some(session_id) = parsed.params.get("session_id").and_then(Value::as_str) else {
        return false;
    };
    let session_id = session_id.to_string();

    // Look up the routing entry. If gone (cancelled, agent dropped,
    // disconnect cleanup), drop the event silently — late frames from
    // a respawned agent for a stale session are not the host's
    // problem.
    let chat = state.chat_sessions.lock().await.get(&session_id).cloned();
    let Some(chat) = chat else {
        return true; // recognized the method, but routing has dropped — consumed.
    };

    // Pull the kind early so terminal-event cleanup runs even if the
    // host's send fails.
    let kind = parsed
        .params
        .get("kind")
        .and_then(Value::as_str)
        .unwrap_or("token")
        .to_string();

    // Forward to the host. Rewrites the method name to the host-facing
    // form and attaches `agent_id` so the host doesn't have to remember
    // which agent owns each session.
    let host_channel = {
        let sessions = state.sessions.lock().await;
        sessions
            .get(&chat.host_client_id)
            .map(|s| s.channel.clone())
    };
    if let Some(channel) = host_channel {
        let mut params = parsed.params.clone();
        if let Some(obj) = params.as_object_mut() {
            obj.insert("agent_id".to_string(), Value::String(chat.agent_id.clone()));
        }
        let forward = serde_json::json!({
            "jsonrpc": "2.0",
            "method": "agents.chat.event",
            "params": params,
        });
        if let Ok(text) = serde_json::to_string(&forward) {
            let _ = channel
                .write
                .lock()
                .await
                .send(Message::Text(text.into()))
                .await;
        }
    }
    // Else: host disconnected mid-stream. Drop the event silently +
    // cancel the session so the agent isn't streaming into the void.

    // Terminal-kind cleanup. The host_channel branch above already
    // forwarded the terminal event; we just remove the routing entry
    // here so subsequent stray frames are no-ops.
    if matches!(kind.as_str(), "done" | "error") {
        state.chat_sessions.lock().await.remove(&session_id);
    }

    true
}

#[cfg(test)]
mod fd_leak_regression {
    //! car#209 regression: an abrupt transport error must still run
    //! the connection cleanup. Before the fix, `let msg = msg?;`
    //! propagated the read error out of `run_dispatch`, skipping
    //! `remove_session`, so `state.sessions` (holding the
    //! `Arc<ClientSession>` -> `Arc<WsChannel>` -> socket FD) leaked
    //! forever on every peer reset / crash-loop disconnect.
    use super::run_dispatch;
    use futures::SinkExt;
    use std::sync::Arc;
    use tokio_tungstenite::tungstenite::{Error as WsError, Message};

    #[tokio::test]
    async fn abrupt_read_error_still_runs_session_cleanup() {
        let tmp = tempfile::TempDir::new().unwrap();
        let state = Arc::new(crate::session::ServerState::standalone(
            tmp.path().to_path_buf(),
        ));

        // Read stream that immediately yields a transport error (peer
        // reset), then ends -- the exact shape of an ungraceful
        // client disconnect.
        let read = futures::stream::iter(vec![Err::<Message, WsError>(
            WsError::ConnectionClosed,
        )]);
        let write: crate::session::WsSink = Box::pin(
            futures::sink::drain().sink_map_err(|_| WsError::ConnectionClosed),
        );

        let result =
            run_dispatch(read, write, "test-peer".to_string(), state.clone()).await;
        assert!(
            result.is_ok(),
            "run_dispatch must return Ok after cleanup, got {result:?}"
        );

        // The session (and its channel/FD) must be gone -- cleanup
        // ran despite the abrupt error.
        assert!(
            state.sessions.lock().await.is_empty(),
            "state.sessions must be empty after an abrupt disconnect (car#209)"
        );
    }
}