brokk-mj-core 2.6.2

Session control plane for ACP coding agents
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
//! ACP runtime and normalized session controls used by a Hel session worker.
//!
//! The worker owns exactly one harness process and one foreground session.  It
//! deliberately does not know about orchestration, review lanes, or subagents;
//! [`surface`] projects protocol capabilities for the chat control surface.

mod dialect;
mod kimi_tasks;
#[cfg(test)]
mod plan_tests;
#[cfg(test)]
mod session_config_tests;
pub mod step_clock;
pub mod surface;
mod terminal_compat;
pub use kimi_tasks::{
    KimiBackgroundTask, KimiTaskSnapshot, KimiWireFollower, KimiWireRefresh,
    resolve_session_dir as resolve_kimi_session_dir,
};
pub use step_clock::StepClock;
pub use surface::PlanControl;
pub use terminal_compat::fallback_terminal_tool_call;
pub(crate) use terminal_compat::fallback_terminal_tool_call_id;
pub use terminal_compat::is_fallback_terminal_tool_call;

use dialect::grok;

use std::collections::{BTreeMap, BTreeSet};
use std::future::Future;
use std::path::PathBuf;
use std::pin::Pin;
use std::process::Stdio;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;

use agent_client_protocol::schema::ProtocolVersion;
use agent_client_protocol::schema::v1::TextContent;
use agent_client_protocol::schema::v1::{
    AgentCapabilities, CancelNotification, ClientCapabilities, CloseSessionRequest, ContentBlock,
    CreateTerminalRequest, CreateTerminalResponse, ElicitationCapabilities,
    ElicitationFormCapabilities, Implementation, InitializeRequest, KillTerminalRequest,
    KillTerminalResponse, LoadSessionRequest, McpServer, McpServerStdio, NewSessionRequest,
    PermissionOptionKind, PromptRequest, PromptResponse, ReleaseTerminalRequest,
    ReleaseTerminalResponse, RequestPermissionOutcome, RequestPermissionRequest,
    RequestPermissionResponse, ResumeSessionRequest, SelectedPermissionOutcome, SessionConfigKind,
    SessionConfigOption, SessionConfigOptionCategory, SessionConfigSelectOptions,
    SessionConfigValueId, SessionId, SessionModeState, SessionUpdate,
    SetSessionConfigOptionRequest, SetSessionModeRequest, StopReason, TerminalExitStatus,
    TerminalId, TerminalOutputRequest, TerminalOutputResponse, ToolCallUpdateFields,
    WaitForTerminalExitRequest, WaitForTerminalExitResponse,
};
use agent_client_protocol::{Agent, ByteStreams, Client, ConnectTo, ConnectionTo, UntypedMessage};
use anyhow::{Context, Result, anyhow, bail, ensure};
use serde::{Deserialize, Serialize};
use tokio::io::AsyncReadExt;
use tokio::process::Command;
use tokio::sync::{mpsc, oneshot};
use tokio_util::compat::{TokioAsyncReadCompatExt, TokioAsyncWriteCompatExt};

use crate::hel_config::{ExecutionEnforcement, ExecutionPolicy, HarnessKind};
use crate::hel_elicitation::{
    ElicitationField, ElicitationFieldKind, ElicitationOption, ElicitationRequest,
    ElicitationResponse, ElicitationValue,
};
use crate::hel_terminal::{
    DEFAULT_TERMINAL_OUTPUT_BYTES, TerminalExit, TerminalRegistry, TerminalSpawn,
};
use crate::hel_worker::{AcpActivityClock, ClaimedSteeringPrompt};
use crate::hel_worker_launch::{ProjectMemoryLaunchConfig, ProjectMemoryMcpDelivery};

pub fn plan_review_carries_native_feedback(id: &str) -> bool {
    grok::is_plan_review_id(id)
}

/// Identity prefix every normalized plan decision shares, whatever harness
/// dialect produced it.
pub const PLAN_REVIEW_ID_PREFIX: &str = "plan-review-";

/// Header [`normalized_plan_review`] puts in front of the harness's proposal
/// text. Reading the proposal back out is the inverse, so both live here.
const PLAN_REVIEW_MESSAGE_PREFIX: &str = "Review the agent's plan:\n\n";

/// Whether this elicitation id belongs to one of Hel's normalized plan
/// decisions.
#[must_use]
pub fn is_plan_review_id(id: &str) -> bool {
    id.starts_with(PLAN_REVIEW_ID_PREFIX)
}

/// The exact proposal text a normalized plan decision carries.
///
/// Returns `None` for any other elicitation, and for a plan decision whose
/// message was not built by [`normalized_plan_review`].
#[must_use]
pub fn plan_review_proposal(request: &ElicitationRequest) -> Option<&str> {
    if !is_plan_review_id(&request.id) {
        return None;
    }
    request.message.strip_prefix(PLAN_REVIEW_MESSAGE_PREFIX)
}

/// The plan decision Hel answers itself instead of forwarding to the harness.
/// Every other decision maps to a native option through the dialect bridge.
pub const PLAN_REVIEW_SECOND_OPINION: &str = "second_opinion";

/// The proposal to review when this answer asked for a second opinion.
///
/// A second opinion is local: the harness's decision stays pending while Hel
/// sets the reviewer up, so this answer must never reach ACP. Callers use the
/// returned proposal as the captured text they hand to the reviewer.
#[must_use]
pub fn plan_review_second_opinion<'a>(
    request: &'a ElicitationRequest,
    response: &ElicitationResponse,
) -> Option<&'a str> {
    let proposal = plan_review_proposal(request)?;
    let ElicitationResponse::Accept { content } = response else {
        return None;
    };
    match content.get(PLAN_REVIEW_ACTION) {
        Some(ElicitationValue::String(action)) if action == PLAN_REVIEW_SECOND_OPINION => {
            Some(proposal)
        }
        _ => None,
    }
}

/// The answer Hel gives the harness once a second opinion has been set up.
///
/// Gathering context needs an idle planning session, so the pending decision
/// has to be resolved first. Declining keeps plan mode active, which is why
/// the captured proposal is the only copy of the plan that survives and why
/// cancelling a review owes the user a Hel-owned decision in its place.
#[must_use]
pub fn plan_review_keep_planning() -> ElicitationResponse {
    ElicitationResponse::Accept {
        content: std::collections::BTreeMap::from([(
            PLAN_REVIEW_ACTION.to_owned(),
            ElicitationValue::String("keep_planning".to_owned()),
        )]),
    }
}

/// Private ACP metadata is provider-local and has no Hel projection. In
/// particular, Codex can replay terminal-output metadata for old tool calls on
/// every `session/load`; journaling those invisible deltas grows the relay and
/// makes every later recovery replay them again.
fn session_update_is_relay_visible(
    update: &SessionUpdate,
    live_tool_calls: &Mutex<BTreeSet<String>>,
    session_id: &str,
) -> bool {
    match update {
        // The accepted command is the authoritative user message. Agent echoes
        // have no projection and must not put image bytes back into the journal.
        SessionUpdate::UserMessageChunk(_) => false,
        SessionUpdate::ToolCall(call) => {
            live_tool_calls
                .lock()
                .expect("live ACP tool-call set lock poisoned")
                .insert(call.tool_call_id.to_string());
            true
        }
        SessionUpdate::ToolCallUpdate(update)
            if update.fields == ToolCallUpdateFields::default() =>
        {
            false
        }
        SessionUpdate::ToolCallUpdate(update) => {
            let created_live = live_tool_calls
                .lock()
                .expect("live ACP tool-call set lock poisoned")
                .contains(&update.tool_call_id.to_string());
            if !created_live {
                tracing::warn!(
                    %session_id,
                    tool_call_id = %update.tool_call_id,
                    "ignored delayed ACP update for a tool call not created on this live connection"
                );
            }
            created_live
        }
        _ => true,
    }
}

#[derive(Debug, Clone)]
pub struct LaunchSpec {
    pub command: PathBuf,
    pub args: Vec<String>,
    pub environment: BTreeMap<String, String>,
    pub cwd: PathBuf,
    pub additional_directories: Vec<PathBuf>,
    pub project_memory: Option<ProjectMemoryLaunchConfig>,
    /// Extra stdio MCP servers this session gets, beyond project memory. A
    /// turn review's reviewing agents get Bifrost this way; the primary
    /// session gets none.
    pub extra_mcp_servers: Vec<crate::hel_worker_launch::ReviewMcpServer>,
    pub resume_session: Option<String>,
    /// Accepted selectors for this logical session, shared across native
    /// bridge replacements. Workers seed this from their durable relay.
    pub accepted_config: Arc<Mutex<AcceptedSessionConfig>>,
    pub harness: HarnessKind,
    pub execution_policy: ExecutionPolicy,
    pub acp_activity: AcpActivityClock,
    /// When the step the agent is on began. Marked from the same handlers as
    /// `acp_activity`, but only where a new step actually starts.
    pub step_clock: StepClock,
}

/// Only model and reasoning effort survive a bridge replacement. Restoring
/// plan/permission modes here could override the current execution policy.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AcceptedSessionConfig {
    model: Option<String>,
    effort: Option<String>,
}

impl AcceptedSessionConfig {
    pub fn from_configuration(
        values: &BTreeMap<String, String>,
        options: &[SessionConfigOption],
    ) -> Self {
        let accepted = |key: &str| {
            let option = find_session_config_option(options, key);
            let recorded = values
                .get(key)
                .or_else(|| option.and_then(|option| values.get(&option.id.to_string())))?;
            Some(recorded.clone())
        };
        Self {
            model: accepted("model"),
            effort: accepted("effort"),
        }
    }

    fn remember(&mut self, key: &str, value: &str, options: &[SessionConfigOption]) -> bool {
        let is_selector = |canonical: &str| {
            key == canonical
                || find_session_config_option(options, canonical)
                    .is_some_and(|option| option.id.to_string() == key)
        };
        let current = |canonical| {
            let option = find_session_config_option(options, canonical)?;
            let SessionConfigKind::Select(select) = &option.kind else {
                return None;
            };
            Some(select.current_value.to_string())
        };
        if is_selector("model") {
            self.model = Some(value.to_owned());
            // A model change can reset effort or remove that selector.
            self.effort = current("effort");
        } else if is_selector("effort") {
            self.effort = Some(value.to_owned());
            if let Some(model) = current("model") {
                self.model = Some(model);
            }
        } else {
            return false;
        }
        true
    }

    /// Fold a completed selector command into the durable configuration using
    /// the same accepted pair as the live bridge. Startup advertisements alone
    /// must never replace it with the provider's defaults.
    pub(crate) fn record_completed(
        values: &mut BTreeMap<String, String>,
        key: &str,
        value: &str,
        options: &[SessionConfigOption],
    ) {
        let mut accepted = Self::from_configuration(values, options);
        if !accepted.remember(key, value, options) {
            return;
        }
        for canonical in ["model", "effort"] {
            values.remove(canonical);
            if let Some(option) = find_session_config_option(options, canonical) {
                values.remove(&option.id.to_string());
            }
        }
        if let Some(model) = accepted.model {
            values.insert("model".into(), model);
        }
        if let Some(effort) = accepted.effort {
            values.insert("effort".into(), effort);
        }
    }
}

fn project_memory_mcp(spec: &LaunchSpec) -> Vec<McpServer> {
    if spec.harness == HarnessKind::Claude
        || spec
            .project_memory
            .as_ref()
            .is_some_and(|memory| memory.mcp_delivery == ProjectMemoryMcpDelivery::HarnessProfile)
    {
        return Vec::new();
    }
    let Some(memory) = &spec.project_memory else {
        return Vec::new();
    };
    vec![McpServer::Stdio(
        McpServerStdio::new("mj-project-memory", spec.command.clone()).args(vec![
            "worker".into(),
            "memory-mcp".into(),
            "--root".into(),
            memory.root.to_string_lossy().into_owned(),
        ]),
    )]
}

fn session_request_meta(spec: &LaunchSpec) -> Option<serde_json::Map<String, serde_json::Value>> {
    if spec.harness != HarnessKind::Claude {
        return None;
    }
    let mut claude_code = serde_json::Map::from_iter([(
        "emitRawSDKMessages".to_owned(),
        serde_json::json!([{
            "type": "system",
            "subtype": CLAUDE_BACKGROUND_TASKS_CHANGED_SUBTYPE,
        }]),
    )]);
    let mut options = serde_json::Map::from_iter([(
        "perTaskStopAffordance".to_owned(),
        serde_json::Value::Bool(true),
    )]);
    if spec.execution_policy.is_unconstrained() {
        options.insert(
            "sandbox".to_owned(),
            serde_json::json!({ "enabled": false }),
        );
    }
    claude_code.insert("options".to_owned(), serde_json::Value::Object(options));
    Some(serde_json::Map::from_iter([(
        "claudeCode".to_owned(),
        serde_json::Value::Object(claude_code),
    )]))
}

const CLAUDE_BACKGROUND_TASKS_CHANGED_SUBTYPE: &str = "background_tasks_changed";

/// A task in Claude Code's process-local background-task level signal.
///
/// The adapter also sends `task_type` and an optional `ambient` marker. Hel
/// only needs the stable id and user-facing description, and filters ambient
/// housekeeping tasks before publishing the replacement level to the relay.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ClaudeBackgroundTask {
    pub task_id: String,
    pub description: String,
}

#[derive(Debug, Clone, Deserialize)]
struct ClaudeBackgroundTaskPayload {
    task_id: String,
    description: String,
    #[serde(default)]
    ambient: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize, agent_client_protocol::JsonRpcNotification)]
#[notification(method = "_claude/sdkMessage")]
struct ClaudeSdkMessageNotification {
    #[serde(rename = "sessionId")]
    session_id: SessionId,
    message: serde_json::Value,
}

#[derive(Debug, Clone, Serialize, Deserialize, agent_client_protocol::JsonRpcNotification)]
#[notification(method = "session/update")]
struct RawSessionNotification {
    #[serde(rename = "sessionId")]
    session_id: SessionId,
    update: serde_json::Value,
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum ClaudeAsyncTaskControlUpdate {
    Set { task_id: String, can_stop: bool },
    Ignore,
}

fn claude_async_task_control_update(
    update: &serde_json::Value,
) -> std::result::Result<Option<ClaudeAsyncTaskControlUpdate>, String> {
    let Some(kind) = update
        .get("sessionUpdate")
        .and_then(serde_json::Value::as_str)
    else {
        return Ok(None);
    };
    if !kind.starts_with("async_task_") {
        return Ok(None);
    }
    let task_id = || {
        update
            .get("asyncTaskId")
            .and_then(serde_json::Value::as_str)
            .filter(|id| !id.trim().is_empty())
            .map(str::to_owned)
            .ok_or_else(|| format!("{kind} requires a non-empty asyncTaskId"))
    };
    match kind {
        "async_task_spawned" => Ok(Some(ClaudeAsyncTaskControlUpdate::Set {
            task_id: task_id()?,
            can_stop: update
                .get("canStop")
                .and_then(serde_json::Value::as_bool)
                .ok_or_else(|| "async_task_spawned requires canStop".to_owned())?,
        })),
        "async_task_state_update" => {
            let state = update
                .get("state")
                .and_then(serde_json::Value::as_str)
                .ok_or_else(|| "async_task_state_update requires state".to_owned())?;
            if matches!(state, "completed" | "failed" | "stopped") {
                Ok(Some(ClaudeAsyncTaskControlUpdate::Set {
                    task_id: task_id()?,
                    can_stop: false,
                }))
            } else if matches!(state, "running" | "paused") {
                Ok(Some(ClaudeAsyncTaskControlUpdate::Ignore))
            } else {
                Err(format!("unknown Claude async task state {state:?}"))
            }
        }
        "async_task_progress" => {
            task_id()?;
            Ok(Some(ClaudeAsyncTaskControlUpdate::Ignore))
        }
        _ => Err(format!("unknown Claude async task update {kind:?}")),
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, agent_client_protocol::JsonRpcRequest)]
#[request(method = "_session/async_task/stop", response = ClaudeAsyncTaskStopResponse)]
struct ClaudeAsyncTaskStopRequest {
    #[serde(rename = "sessionId")]
    session_id: SessionId,
    #[serde(rename = "asyncTaskId")]
    async_task_id: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, agent_client_protocol::JsonRpcResponse)]
struct ClaudeAsyncTaskStopResponse {
    stopped: bool,
}

/// Extract the one Claude SDK level signal Hel subscribes to. Edge lifecycle
/// messages and foreground activity are deliberately ignored: their ordering
/// is unspecified and task starts include foreground work.
fn claude_background_tasks(
    message: &serde_json::Value,
) -> std::result::Result<Option<Vec<ClaudeBackgroundTask>>, serde_json::Error> {
    if message.get("type").and_then(serde_json::Value::as_str) != Some("system")
        || message.get("subtype").and_then(serde_json::Value::as_str)
            != Some(CLAUDE_BACKGROUND_TASKS_CHANGED_SUBTYPE)
    {
        return Ok(None);
    }
    let payload = serde_json::from_value::<Vec<ClaudeBackgroundTaskPayload>>(
        message
            .get("tasks")
            .cloned()
            .unwrap_or(serde_json::Value::Null),
    )?;
    Ok(Some(
        payload
            .into_iter()
            .filter(|task| !task.ambient)
            .map(|task| ClaudeBackgroundTask {
                task_id: task.task_id,
                description: task.description,
            })
            .collect(),
    ))
}

/// The reviewing agents' analyzer servers, for harnesses that accept a server
/// over ACP. Claude and Kimi read their staged profile instead, which the
/// controller writes while staging the reviewer.
fn extra_mcp(spec: &LaunchSpec) -> Vec<McpServer> {
    if crate::hel_worker_launch::ReviewMcpDelivery::for_harness(spec.harness)
        != crate::hel_worker_launch::ReviewMcpDelivery::Acp
    {
        return Vec::new();
    }
    spec.extra_mcp_servers
        .iter()
        .map(|server| {
            McpServer::Stdio(
                McpServerStdio::new(server.name.clone(), server.command.clone())
                    .args(server.args.clone()),
            )
        })
        .collect()
}

fn new_session_request(spec: &LaunchSpec, include_project_memory: bool) -> NewSessionRequest {
    let request = NewSessionRequest::new(spec.cwd.clone())
        .additional_directories(spec.additional_directories.clone())
        .meta(session_request_meta(spec));
    let mut servers = extra_mcp(spec);
    if include_project_memory {
        servers.extend(project_memory_mcp(spec));
    }
    // DSH's bundled ACP v1 server requires this field, including an empty
    // array. Other bridges distinguish omission from an explicit MCP set.
    if servers.is_empty() && spec.harness != HarnessKind::Deepseek {
        request
    } else {
        request.mcp_servers(servers)
    }
}

fn load_session_request(spec: &LaunchSpec, session_id: SessionId) -> LoadSessionRequest {
    LoadSessionRequest::new(session_id, spec.cwd.clone())
        .additional_directories(spec.additional_directories.clone())
        // Loading must preserve the native session's original MCP set. Adding
        // Hel's current project-memory server here mutates an existing Codex
        // session and can make its history replay emit updates for tools whose
        // creation was never part of this relay stream. New sessions receive
        // the server above; resumed sessions keep whatever they began with.
        .meta(session_request_meta(spec))
}

fn resume_session_request(spec: &LaunchSpec, session_id: SessionId) -> ResumeSessionRequest {
    ResumeSessionRequest::new(session_id, spec.cwd.clone())
        .additional_directories(spec.additional_directories.clone())
        // Resuming must preserve the native session's original MCP set, just
        // like loading it. The adapter only needs the session context here;
        // future live updates are delivered on this connection.
        .meta(session_request_meta(spec))
}

#[derive(Debug)]
pub enum CommandRequest {
    PromptAttachments {
        request_id: String,
        prompt: Vec<ContentBlock>,
        root: PathBuf,
    },
    Prompt {
        request_id: String,
        prompt: Vec<ContentBlock>,
    },
    SetConfig {
        request_id: String,
        key: String,
        value: String,
    },
    /// Select an ACP session mode through `session/set_mode`.
    SetSessionMode {
        request_id: String,
        mode_id: String,
    },
    /// Connection-only answer to an in-flight ACP elicitation. The content is
    /// deliberately never put in the durable relay command ledger.
    ResolveElicitation {
        elicitation_id: String,
        response: ElicitationResponse,
        resolved: oneshot::Sender<std::result::Result<(), String>>,
    },
    StopBackgroundTask {
        target: crate::hel_worker::BackgroundTaskStopTarget,
        resolved: oneshot::Sender<std::result::Result<(), String>>,
    },
    Cancel {
        request_id: String,
        steering_prompt: Option<ClaimedSteeringPrompt>,
    },
    Close {
        request_id: String,
    },
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum RuntimeEvent {
    Connected {
        agent_name: Option<String>,
        agent_version: Option<String>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        protocol_version: Option<ProtocolVersion>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        capabilities: Option<Box<AgentCapabilities>>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        agent_info: Option<Implementation>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        steering_supported: Option<bool>,
    },
    SessionStarted {
        native_session_id: String,
        resumed: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        execution_mode: Option<String>,
    },
    SessionConfigured {
        config_options: Vec<SessionConfigOption>,
    },
    SessionModesConfigured {
        modes: Option<SessionModeState>,
    },
    SessionUpdate {
        update: serde_json::Value,
    },
    /// Replacement level for Claude Code's live non-ambient background tasks.
    /// This provider signal does not represent transcript or foreground work.
    ClaudeBackgroundTasksChanged {
        tasks: Vec<ClaudeBackgroundTask>,
    },
    ClaudeAsyncTaskControlChanged {
        task_id: String,
        can_stop: bool,
    },
    ElicitationRequested {
        request: ElicitationRequest,
    },
    ElicitationResolved {
        elicitation_id: String,
        action: String,
    },
    PromptFinished {
        #[serde(default, skip_serializing_if = "String::is_empty")]
        request_id: String,
        stop_reason: String,
    },
    Warning {
        message: String,
    },
    /// A client terminal started successfully. The worker records an interim
    /// tool call so agents that omit the ACP association do not strand its
    /// eventual result as a standalone transcript item.
    TerminalStarted {
        terminal_id: String,
        command: String,
        started_at_ms: i64,
    },
    /// A client-run terminal was reaped. Exactly one of these is emitted per
    /// terminal, by the supervisor that waits on the child, so kill and
    /// release flow through the same report.
    TerminalClosed {
        terminal_id: String,
        output: String,
        #[serde(default)]
        truncated: bool,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        exit_code: Option<u32>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        signal: Option<String>,
    },
    UserShellOutput {
        request_id: String,
        command: String,
        stdout: String,
        stderr: String,
        stdout_truncated: bool,
        stderr_truncated: bool,
    },
    UserShellFinished {
        request_id: String,
        result: crate::hel_worker::UserShellResult,
    },
    ConfigApplied {
        #[serde(default, skip_serializing_if = "String::is_empty")]
        request_id: String,
        key: String,
        value: String,
        /// The complete configuration returned by ACP for this change. Keep
        /// it in the same runtime event as command completion so the relay
        /// cannot publish a checkpoint between the two durable observations.
        #[serde(default)]
        config_options: Vec<SessionConfigOption>,
    },
    SessionModeApplied {
        #[serde(default, skip_serializing_if = "String::is_empty")]
        request_id: String,
        mode_id: String,
        #[serde(default)]
        config_options: Vec<SessionConfigOption>,
        #[serde(default, skip_serializing_if = "Option::is_none")]
        modes: Option<SessionModeState>,
    },
    CommandRejected {
        request_id: String,
        message: String,
    },
    CommandInterrupted {
        request_id: String,
        message: String,
    },
    CancelApplied {
        request_id: String,
    },
    SteerApplied {
        request_id: String,
        queued_command_id: String,
    },
    CloseApplied {
        request_id: String,
    },
    /// The ACP child died or the protocol broke after a session was open.
    /// The coordinator interrupts in-flight commands; the runtime reloads the
    /// native session on a new bridge instead of stopping the worker.
    HarnessRestarting {
        message: String,
    },
    Stopped,
}

type PendingElicitations = Arc<Mutex<BTreeMap<String, oneshot::Sender<ElicitationResponse>>>>;

/// A permission callback captures the current command's sender, so a late
/// answer cannot attach an implementation to a subsequent prompt or bridge.
type PlanImplementationSlot = Arc<Mutex<Option<mpsc::UnboundedSender<PlanImplementation>>>>;

struct PlanImplementation {
    plan: String,
    permission_sent: oneshot::Receiver<bool>,
}

struct ActivePlanImplementation(PlanImplementationSlot);

type ActivePrompt = Pin<
    Box<
        dyn Future<Output = std::result::Result<PromptResponse, agent_client_protocol::Error>>
            + Send,
    >,
>;

struct RestoredPlanMode {
    config_options: Vec<SessionConfigOption>,
    modes: Option<SessionModeState>,
    plan: String,
}

type PlanModeRestoration<'a> = Pin<Box<dyn Future<Output = Result<RestoredPlanMode>> + Send + 'a>>;

async fn restore_plan_execution_mode(
    connection: &ConnectionTo<Agent>,
    session_id: SessionId,
    mut state: RestoredPlanMode,
    permission_sent: oneshot::Receiver<bool>,
) -> Result<RestoredPlanMode> {
    ensure!(
        permission_sent.await.unwrap_or(false),
        "Claude's plan permission response could not be delivered"
    );
    enforce_execution_mode(
        connection,
        &session_id,
        "bypassPermissions",
        &mut state.config_options,
        &mut state.modes,
    )
    .await?;
    for option in &state.config_options {
        if option.category == Some(SessionConfigOptionCategory::Mode)
            && let SessionConfigKind::Select(select) = &option.kind
        {
            ensure!(
                select.current_value.to_string() == "bypassPermissions",
                "Claude did not apply the required bypassPermissions mode"
            );
        }
    }
    Ok(state)
}

impl Drop for ActivePlanImplementation {
    fn drop(&mut self) {
        self.0
            .lock()
            .expect("plan implementation lock poisoned")
            .take();
    }
}

enum PlanPermissionAnswer {
    Native(RequestPermissionResponse),
    ContinueInBypass,
}

fn policy_plan_permission_answer(
    request: &RequestPermissionRequest,
    response: ElicitationResponse,
    harness: HarnessKind,
    policy: ExecutionPolicy,
) -> Result<PlanPermissionAnswer> {
    if harness != HarnessKind::Claude || plan_review_answer(response.clone()).0 != "implement" {
        return Ok(PlanPermissionAnswer::Native(permission_plan_response(
            request, response,
        )));
    }
    let (mode, ids) = if policy.is_unconstrained() {
        (
            "bypassPermissions",
            ["bypassPermissions", "exit-plan-bypass"],
        )
    } else {
        ("auto", ["auto", "exit-plan-auto"])
    };
    if let Some(option) = request.options.iter().find(|option| {
        ids.contains(&option.option_id.to_string().as_str())
            && matches!(
                option.kind,
                PermissionOptionKind::AllowOnce | PermissionOptionKind::AllowAlways
            )
    }) {
        return Ok(PlanPermissionAnswer::Native(
            RequestPermissionResponse::new(RequestPermissionOutcome::Selected(
                SelectedPermissionOutcome::new(option.option_id.clone()),
            )),
        ));
    }
    if policy.is_unconstrained() {
        Ok(PlanPermissionAnswer::ContinueInBypass)
    } else {
        bail!(
            "Cannot implement the approved plan: Claude did not offer the required {mode} mode. Update the Claude bridge or use a model supporting Auto mode."
        )
    }
}

pub async fn run(
    spec: LaunchSpec,
    requests: mpsc::Receiver<CommandRequest>,
    events: mpsc::Sender<RuntimeEvent>,
) -> Result<()> {
    let result = run_inner(spec, requests, events.clone()).await;
    if let Err(error) = &result {
        emit_runtime_event(
            &events,
            RuntimeEvent::Warning {
                message: format!("ACP runtime failed: {error:#}"),
            },
        )
        .await
        .with_context(|| format!("report ACP runtime failure: {error:#}"))?;
    }
    emit_runtime_event(&events, RuntimeEvent::Stopped).await?;
    result
}

#[derive(Clone)]
struct OpenedSession {
    native_session_id: String,
    started_at: tokio::time::Instant,
    resume_required: Arc<AtomicBool>,
}

struct BridgeRestart {
    resume_session: Option<String>,
    unexpected: bool,
    session_age: Duration,
    message: &'static str,
}

async fn run_inner(
    mut spec: LaunchSpec,
    mut requests: mpsc::Receiver<CommandRequest>,
    events: mpsc::Sender<RuntimeEvent>,
) -> Result<()> {
    let mut rapid_deaths = 0_u32;
    let mut replacing_previous_bridge = false;
    loop {
        let opened = Arc::new(Mutex::new(None));
        match run_bridge(
            &spec,
            &mut requests,
            &events,
            opened.clone(),
            replacing_previous_bridge,
        )
        .await?
        {
            None => return Ok(()),
            Some(restart) => {
                if restart.unexpected {
                    if restart.session_age < RAPID_BRIDGE_WINDOW {
                        rapid_deaths += 1;
                        ensure!(
                            rapid_deaths < RAPID_BRIDGE_RESTART_LIMIT,
                            "ACP bridge exited repeatedly during startup; giving up"
                        );
                    } else {
                        rapid_deaths = 0;
                    }
                }
                emit_runtime_event(
                    &events,
                    RuntimeEvent::HarnessRestarting {
                        message: restart.message.to_owned(),
                    },
                )
                .await?;
                spec.resume_session = restart.resume_session;
                replacing_previous_bridge = true;
            }
        }
    }
}

/// Run one ACP bridge process. `Some` means reload the native session on a
/// fresh bridge: a cancel that never acked, or a dead ACP child.
async fn run_bridge(
    spec: &LaunchSpec,
    requests: &mut mpsc::Receiver<CommandRequest>,
    events: &mpsc::Sender<RuntimeEvent>,
    opened: Arc<Mutex<Option<OpenedSession>>>,
    replacing_previous_bridge: bool,
) -> Result<Option<BridgeRestart>> {
    let mut child = Command::new(&spec.command)
        .args(&spec.args)
        .envs(&spec.environment)
        .current_dir(&spec.cwd)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .spawn()
        .with_context(|| {
            format!(
                "launch ACP bridge {} in working directory {}",
                spec.command.display(),
                spec.cwd.display()
            )
        })?;
    let stdin = child.stdin.take().context("ACP bridge stdin unavailable")?;
    let stdout = child
        .stdout
        .take()
        .context("ACP bridge stdout unavailable")?;
    let stderr = child
        .stderr
        .take()
        .context("ACP bridge stderr unavailable")?;
    let stderr_task = tokio::spawn(read_stderr_tail(stderr));
    let transport = ByteStreams::new(stdin.compat_write(), stdout.compat());

    let (mut result, child_reaped) = {
        let drive = drive(
            transport,
            spec.clone(),
            requests,
            events.clone(),
            opened.clone(),
            replacing_previous_bridge,
        );
        tokio::pin!(drive);
        tokio::select! {
            biased;
            result = &mut drive => (result, false),
            waited = child.wait() => {
                let result = match waited {
                    Ok(status) => Err(anyhow!(
                        "ACP bridge exited before the protocol runtime completed with {status}; \
                         bridge stdout must contain only JSON-RPC frames and login-shell startup must be silent"
                    )),
                    Err(error) => Err(error).context("wait for ACP bridge"),
                };
                (result, true)
            }
        }
    };
    let opened_now = opened.lock().expect("opened session lock poisoned").clone();
    let restarting = matches!(&result, Ok(Some(_))) || (result.is_err() && opened_now.is_some());
    // Dropping the transport closes the supervisor's stdin. Give it time to
    // terminate and reap the complete bridge process group before killing the
    // supervisor itself as a last resort. A planned restart already decided
    // to kill the child, so a non-zero exit is the expected outcome.
    if !child_reaped {
        if restarting {
            if let Err(error) = child.kill().await {
                tracing::warn!(
                    operation = "acp_bridge_restart",
                    %error,
                    "could not kill ACP bridge during planned restart"
                );
            }
            if let Err(error) = child.wait().await {
                tracing::warn!(
                    operation = "acp_bridge_restart",
                    %error,
                    "could not reap ACP bridge during planned restart"
                );
            }
        } else {
            let cleanup =
                match tokio::time::timeout(std::time::Duration::from_secs(3), child.wait()).await {
                    Ok(Ok(status)) if status.success() => Ok(()),
                    Ok(Ok(status)) => Err(anyhow!(
                        "ACP bridge exited with {status} after the protocol runtime completed"
                    )),
                    Ok(Err(error)) => Err(error).context("wait for ACP bridge shutdown"),
                    Err(_) => {
                        let killed = child.kill().await.context("kill unresponsive ACP bridge");
                        let waited = child
                            .wait()
                            .await
                            .context("reap killed ACP bridge")
                            .map(|_| ());
                        match (killed, waited) {
                            (Ok(()), Ok(())) => Ok(()),
                            (Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
                            (Err(error), Err(wait_error)) => Err(error.context(format!(
                                "also failed to reap killed ACP bridge: {wait_error:#}"
                            ))),
                        }
                    }
                };
            if let Err(error) = cleanup {
                merge_drive_error(&mut result, error);
            }
        }
    }
    let stderr_tail = match stderr_task.await {
        Ok(Ok(tail)) => tail,
        Ok(Err(error)) => {
            merge_drive_error(&mut result, error);
            String::new()
        }
        Err(error) => {
            merge_drive_error(
                &mut result,
                anyhow!("ACP stderr collector task failed: {error}"),
            );
            String::new()
        }
    };
    if !restarting && let Some(stderr_tail) = actionable_stderr_tail(&stderr_tail) {
        result =
            result.map_err(|error| error.context(format!("ACP bridge stderr:\n{stderr_tail}")));
    }
    match result {
        Ok(None) => Ok(None),
        Ok(Some(native_session_id)) => Ok(Some(BridgeRestart {
            resume_session: Some(native_session_id),
            unexpected: false,
            session_age: opened_now
                .map(|opened| opened.started_at.elapsed())
                .unwrap_or(Duration::ZERO),
            message: ACP_BRIDGE_RESTART_WARNING,
        })),
        Err(error) => match opened_now {
            None => Err(error),
            Some(opened) => Ok(Some(BridgeRestart {
                resume_session: opened
                    .resume_required
                    .load(Ordering::Acquire)
                    .then_some(opened.native_session_id),
                unexpected: true,
                session_age: opened.started_at.elapsed(),
                message: if opened.resume_required.load(Ordering::Acquire) {
                    ACP_BRIDGE_LOST_WARNING
                } else {
                    "The agent stopped before its first prompt; restarting with a new empty thread."
                },
            })),
        },
    }
}

const ACP_STDERR_TAIL_BYTES: usize = 16 * 1024;
const UNEXPECTED_PERMISSION_REQUEST_WARNING: &str = "The agent made a permission request while configured to run unconstrained; its execution policy is misconfigured.";
/// Chatter the Claude bridge logs for SDK events it does not model, for example
/// `Unexpected case: {"type":"vcs_state_changed"}`. It arrives often enough to
/// fill the whole stderr tail and bury the real failure in worker exit records.
const ADAPTER_CHATTER_PREFIX: &str = "Unexpected case: ";
/// Kimi 0.37.x logs this for response-shaped startup frames with a null id.
/// It is adapter routing noise and commonly precedes a useful ACP error.
const KIMI_NULL_RESPONSE_CHATTER: &str = "Got response to unknown request null";

const PLAN_REVIEW_ACTION: &str = "action";
const PLAN_REVIEW_FEEDBACK: &str = "feedback";

fn nested_string<'a>(value: &'a serde_json::Value, keys: &[&str]) -> Option<&'a str> {
    match value {
        serde_json::Value::Object(object) => {
            for key in keys {
                if let Some(value) = object.get(*key).and_then(serde_json::Value::as_str) {
                    return Some(value);
                }
            }
            object.values().find_map(|value| nested_string(value, keys))
        }
        serde_json::Value::Array(values) => {
            values.iter().find_map(|value| nested_string(value, keys))
        }
        _ => None,
    }
}

fn nested_string_matches(
    value: &serde_json::Value,
    keys: &[&str],
    predicate: &impl Fn(&str) -> bool,
) -> bool {
    match value {
        serde_json::Value::Object(object) => object.iter().any(|(key, value)| {
            (keys.contains(&key.as_str()) && value.as_str().is_some_and(predicate))
                || nested_string_matches(value, keys, predicate)
        }),
        serde_json::Value::Array(values) => values
            .iter()
            .any(|value| nested_string_matches(value, keys, predicate)),
        _ => false,
    }
}

fn is_plan_permission(request: &RequestPermissionRequest) -> bool {
    let Ok(value) = serde_json::to_value(request) else {
        return false;
    };
    // Claude Code's ExitPlanMode approval arrives as a `switch_mode` tool call
    // whose rawInput carries the plan text and a `planFilePath`; its title is
    // "Ready to code?" and its options are generic permission-mode ids
    // (`default`, `acceptEdits`, `plan`, ...). None of those match a title or
    // option-id heuristic, so key on the tool kind and the plan payload.
    nested_string_matches(&value, &["kind"], &|kind| {
        kind == "plan_review" || kind == "switch_mode"
    }) || nested_string(&value, &["planFilePath", "plan_file_path"]).is_some()
        || nested_string_matches(&value, &["title", "name"], &|name| {
            let normalized = name.to_ascii_lowercase().replace([' ', '_'], "");
            normalized.contains("implementthisplan") || normalized.contains("exitplanmode")
        })
        || request.options.iter().any(|option| {
            let id = option.option_id.to_string().to_ascii_lowercase();
            id.contains("plan_approve")
                || id.contains("implement_plan")
                || id.contains("plan_revise")
                || id.contains("reject_and_exit")
        })
}

pub fn normalized_plan_review(id: String, value: &serde_json::Value) -> ElicitationRequest {
    let plan = nested_string(value, &["plan", "plan_content", "planContent"])
        .unwrap_or("The agent did not provide plan text in its review request.");
    ElicitationRequest {
        id,
        title: Some("Plan review".into()),
        message: format!("{PLAN_REVIEW_MESSAGE_PREFIX}{plan}"),
        description: Some("Choose what Mjolnir should tell the planning harness.".into()),
        fields: vec![
            ElicitationField {
                id: PLAN_REVIEW_ACTION.into(),
                title: "Decision".into(),
                description: Some(
                    "Implement approves the plan; revise sends the feedback below.".into(),
                ),
                required: true,
                secret: false,
                custom_answer_for: None,
                custom_answer_option: None,
                kind: ElicitationFieldKind::SingleSelect {
                    options: vec![
                        ElicitationOption {
                            value: "implement".into(),
                            title: "Implement".into(),
                            description: Some("Approve and continue with implementation".into()),
                            preview: None,
                        },
                        ElicitationOption {
                            value: "revise".into(),
                            title: "Revise".into(),
                            description: Some("Keep planning and incorporate feedback".into()),
                            preview: None,
                        },
                        ElicitationOption {
                            value: PLAN_REVIEW_SECOND_OPINION.into(),
                            title: "Get a second opinion".into(),
                            description: Some(
                                "Ask another agent to review this plan before you decide".into(),
                            ),
                            preview: None,
                        },
                        ElicitationOption {
                            value: "keep_planning".into(),
                            title: "Keep planning".into(),
                            description: Some("Decline this plan without leaving plan mode".into()),
                            preview: None,
                        },
                        ElicitationOption {
                            value: "exit".into(),
                            title: "Exit plan mode".into(),
                            description: Some(
                                "Abandon this review and return to normal mode".into(),
                            ),
                            preview: None,
                        },
                    ],
                    default: Some("keep_planning".into()),
                },
            },
            ElicitationField {
                id: PLAN_REVIEW_FEEDBACK.into(),
                title: "Revision feedback".into(),
                description: Some("Describe what the agent should change.".into()),
                required: false,
                secret: false,
                custom_answer_for: Some(PLAN_REVIEW_ACTION.into()),
                custom_answer_option: Some("revise".into()),
                kind: ElicitationFieldKind::Text {
                    default: None,
                    min_length: None,
                    max_length: Some(16 * 1024),
                    pattern: None,
                    format: None,
                },
            },
        ],
    }
}

fn plan_review_answer(response: ElicitationResponse) -> (String, Option<String>) {
    let ElicitationResponse::Accept { content } = response else {
        return ("keep_planning".into(), None);
    };
    let action = match content.get(PLAN_REVIEW_ACTION) {
        Some(ElicitationValue::String(action)) => action.clone(),
        _ => "keep_planning".into(),
    };
    let feedback = match content.get(PLAN_REVIEW_FEEDBACK) {
        Some(ElicitationValue::String(feedback)) if !feedback.trim().is_empty() => {
            Some(feedback.clone())
        }
        _ => None,
    };
    (action, feedback)
}

fn permission_plan_response(
    request: &RequestPermissionRequest,
    response: ElicitationResponse,
) -> RequestPermissionResponse {
    let (action, _) = plan_review_answer(response);
    let needles: &[&str] = match action.as_str() {
        "implement" => &["implement_plan", "plan_approve", "default", "approve"],
        "revise" => &["plan_revise", "revise"],
        "exit" => &["reject_and_exit", "exit"],
        // A second opinion is answered locally and never reaches here. If one
        // ever did, it must not approve the plan, so it declines like every
        // other non-approval and leaves the session in plan mode.
        _ => &[],
    };
    let selected = request
        .options
        .iter()
        .find(|option| {
            let id = option.option_id.to_string().to_ascii_lowercase();
            let name = option.name.to_ascii_lowercase();
            needles
                .iter()
                .any(|needle| id.contains(needle) || name.contains(needle))
        })
        .or_else(|| {
            // No harness-specific option id matched. Claude's "Ready to code?"
            // exposes only generic kinds, so fall back by intent: implement
            // takes an allow option; every decline (revise, keep_planning,
            // exit) takes a reject option to stay in plan mode rather than
            // cancelling the turn.
            if action == "implement" {
                // Prefer the least-privileged approval so an unmatched harness
                // never silently escalates to a bypass-permissions option.
                request
                    .options
                    .iter()
                    .find(|option| option.kind == PermissionOptionKind::AllowOnce)
                    .or_else(|| {
                        request
                            .options
                            .iter()
                            .find(|option| option.kind == PermissionOptionKind::AllowAlways)
                    })
            } else {
                request
                    .options
                    .iter()
                    .find(|option| option.kind == PermissionOptionKind::RejectOnce)
                    .or_else(|| {
                        request
                            .options
                            .iter()
                            .find(|option| option.kind == PermissionOptionKind::RejectAlways)
                    })
            }
        });
    selected.map_or_else(
        || RequestPermissionResponse::new(RequestPermissionOutcome::Cancelled),
        |option| {
            RequestPermissionResponse::new(RequestPermissionOutcome::Selected(
                SelectedPermissionOutcome::new(option.option_id.clone()),
            ))
        },
    )
}

fn unsupported_client_request_report(method: &str) -> String {
    format!(
        "The agent sent the client request {method}, which Hel does not implement. \
         Hel answered with a method-not-found error rather than leaving the agent waiting."
    )
}

/// The part of a bridge stderr tail worth attaching to a failing result.
/// Returns `None` when only adapter chatter was captured, so a failure keeps
/// its own error text instead of gaining misleading context.
fn actionable_stderr_tail(tail: &str) -> Option<String> {
    let kept = tail
        .lines()
        .filter(|line| {
            let line = line.trim();
            !line.starts_with(ADAPTER_CHATTER_PREFIX) && line != KIMI_NULL_RESPONSE_CHATTER
        })
        .collect::<Vec<_>>()
        .join("\n");
    let kept = kept.trim();
    (!kept.is_empty()).then(|| kept.to_owned())
}

async fn emit_runtime_event(
    events: &mpsc::Sender<RuntimeEvent>,
    event: RuntimeEvent,
) -> Result<()> {
    events
        .send(event)
        .await
        .map_err(|_| anyhow!("relay event coordinator stopped"))
}

/// Answer for a `terminal/*` request naming a terminal this connection does
/// not have, most often one the agent already released.
fn unknown_terminal_error(terminal_id: &str) -> agent_client_protocol::Error {
    agent_client_protocol::Error::invalid_params().data(serde_json::Value::String(format!(
        "unknown terminal {terminal_id}"
    )))
}

fn terminal_exit_status(exit: &TerminalExit) -> TerminalExitStatus {
    TerminalExitStatus::new()
        .exit_code(exit.exit_code)
        .signal(exit.signal.clone())
}

fn relay_event_channel_error() -> agent_client_protocol::Error {
    agent_client_protocol::Error::internal_error().data(serde_json::Value::String(
        "relay event coordinator stopped".into(),
    ))
}

fn merge_drive_error(result: &mut Result<Option<String>>, additional: anyhow::Error) {
    let previous = std::mem::replace(result, Ok(None));
    *result = match previous {
        Ok(_) => Err(additional),
        Err(error) => Err(error.context(format!("additional ACP runtime error: {additional:#}"))),
    };
}

async fn read_stderr_tail(mut stderr: tokio::process::ChildStderr) -> Result<String> {
    let mut tail = Vec::new();
    let mut buffer = [0_u8; 4096];
    loop {
        match stderr.read(&mut buffer).await {
            Ok(0) => break,
            Ok(read) => {
                tail.extend_from_slice(&buffer[..read]);
                if tail.len() > ACP_STDERR_TAIL_BYTES {
                    tail.drain(..tail.len() - ACP_STDERR_TAIL_BYTES);
                }
            }
            Err(error) => {
                return Err(error).context("read ACP bridge stderr");
            }
        }
    }
    Ok(String::from_utf8_lossy(&tail).trim().to_owned())
}

/// How long a `session/cancel` may take to settle `session/prompt` before Hel
/// kills the bridge and reloads the native session. A cooperative cancel can
/// flush thinking; this bound is for the case that never acks.
const CANCEL_ACK_TIMEOUT: Duration = Duration::from_secs(60);

const CANCEL_UNACKED_WARNING: &str =
    "cancel was not acknowledged within 60s; restarting the harness";

const ACP_BRIDGE_LOST_WARNING: &str = "ACP bridge exited; reloading the native session";
const ACP_BRIDGE_RESTART_WARNING: &str = "ACP bridge restarting; reloading the native session";

/// Give up if a freshly opened session dies this many times in a row before it
/// has lived for [`RAPID_BRIDGE_WINDOW`]. A later crash of a healthy session
/// resets the count.
const RAPID_BRIDGE_RESTART_LIMIT: u32 = 3;
const RAPID_BRIDGE_WINDOW: Duration = Duration::from_secs(5);

async fn drive<T>(
    transport: T,
    spec: LaunchSpec,
    requests: &mut mpsc::Receiver<CommandRequest>,
    events: mpsc::Sender<RuntimeEvent>,
    opened: Arc<Mutex<Option<OpenedSession>>>,
    replacing_previous_bridge: bool,
) -> Result<Option<String>>
where
    T: ConnectTo<Client>,
{
    let notification_events = events.clone();
    let notification_activity = spec.acp_activity.clone();
    let notification_step_clock = spec.step_clock.clone();
    let session_update_count = Arc::new(AtomicU64::new(0));
    let notification_session_update_count = session_update_count.clone();
    let resume_required = Arc::new(AtomicBool::new(
        spec.resume_session.is_some() || spec.harness != HarnessKind::Codex,
    ));
    let notification_resume_required = resume_required.clone();
    // A provider may replay the native transcript as `session/update`
    // notifications while answering `session/load`. Hel already owns that
    // history in its durable relay, so accepting the replay would duplicate
    // every old turn on every restart. New sessions have no old history.
    let session_updates_enabled = Arc::new(AtomicBool::new(spec.resume_session.is_none()));
    let notification_session_updates_enabled = session_updates_enabled.clone();
    // Codex can finish dispatching old tool updates after `session/load` has
    // already returned. Track only creations observed after the load boundary,
    // so those delayed updates cannot reintroduce historical tool state into
    // the durable relay. A live tool always announces its creation before its
    // updates on the same ACP connection.
    let live_tool_calls = Arc::new(Mutex::new(BTreeSet::<String>::new()));
    let notification_live_tool_calls = live_tool_calls.clone();
    let notification_harness = spec.harness;
    let claude_sdk_events = events.clone();
    let claude_sdk_harness = spec.harness;
    let permission_events = events.clone();
    let permission_activity = spec.acp_activity.clone();
    let permission_step_clock = spec.step_clock.clone();
    let ext_events = events.clone();
    let ext_activity = spec.acp_activity.clone();
    let ext_step_clock = spec.step_clock.clone();
    let ext_harness = spec.harness;
    let elicitation_events = events.clone();
    let pending_elicitations = PendingElicitations::default();
    let handler_elicitations = pending_elicitations.clone();
    let permission_elicitations = pending_elicitations.clone();
    let permission_review_ids = Arc::new(AtomicU64::new(1));
    let ext_review_ids = Arc::new(AtomicU64::new(1));
    let session_elicitations = pending_elicitations.clone();
    let next_elicitation_id = Arc::new(AtomicU64::new(1));
    let permission_policy = spec.execution_policy;
    let permission_harness = spec.harness;
    let plan_implementation_slot = PlanImplementationSlot::default();
    let permission_implementation_slot = plan_implementation_slot.clone();
    let terminals = TerminalRegistry::new();
    let create_terminals = terminals.clone();
    let output_terminals = terminals.clone();
    let wait_terminals = terminals.clone();
    let kill_terminals = terminals.clone();
    let release_terminals = terminals.clone();
    let create_events = events.clone();
    let create_activity = spec.acp_activity.clone();
    let create_step_clock = spec.step_clock.clone();
    let output_activity = spec.acp_activity.clone();
    let wait_activity = spec.acp_activity.clone();
    let kill_activity = spec.acp_activity.clone();
    let release_activity = spec.acp_activity.clone();
    // A terminal runs where the session runs unless the agent names a
    // directory of its own.
    let session_cwd = spec.cwd.clone();
    let restart = Arc::new(Mutex::new(None));
    let restart_slot = restart.clone();
    Client
        .builder()
        .on_receive_notification(
            async move |notification: RawSessionNotification, _cx| {
                notification_activity.mark();
                if notification_harness == HarnessKind::Claude {
                    match claude_async_task_control_update(&notification.update) {
                        Ok(Some(ClaudeAsyncTaskControlUpdate::Set { task_id, can_stop })) => {
                            notification_events
                                .send(RuntimeEvent::ClaudeAsyncTaskControlChanged {
                                    task_id,
                                    can_stop,
                                })
                                .await
                                .map_err(|_| relay_event_channel_error())?;
                            return Ok(());
                        }
                        Ok(Some(ClaudeAsyncTaskControlUpdate::Ignore)) => return Ok(()),
                        Ok(None) => {}
                        Err(message) => {
                            notification_events
                                .send(RuntimeEvent::Warning {
                                    message: format!(
                                        "ignored malformed Claude async task update: {message}"
                                    ),
                                })
                                .await
                                .map_err(|_| relay_event_channel_error())?;
                            return Ok(());
                        }
                    }
                }
                let update = serde_json::from_value::<SessionUpdate>(notification.update)
                    .map_err(|error| {
                        agent_client_protocol::Error::invalid_params().data(
                            serde_json::Value::String(format!(
                                "decode ACP session update: {error}"
                            )),
                        )
                    })?;
                notification_step_clock.observe(&update);
                if !notification_session_updates_enabled.load(Ordering::Acquire) {
                    return Ok(());
                }
                if session_update_has_native_history(&update) {
                    notification_resume_required.store(true, Ordering::Release);
                }
                if !session_update_is_relay_visible(
                    &update,
                    &notification_live_tool_calls,
                    &notification.session_id.to_string(),
                ) {
                    return Ok(());
                }
                let update = serde_json::to_value(update).map_err(|error| {
                    agent_client_protocol::Error::internal_error().data(serde_json::Value::String(
                        format!("serialize ACP session update for relay: {error}"),
                    ))
                })?;
                notification_session_update_count.fetch_add(1, Ordering::Release);
                notification_events
                    .send(RuntimeEvent::SessionUpdate { update })
                    .await
                    .map_err(|_| relay_event_channel_error())?;
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .on_receive_notification(
            async move |notification: ClaudeSdkMessageNotification, _cx| {
                if claude_sdk_harness != HarnessKind::Claude {
                    return Ok(());
                }
                let tasks = match claude_background_tasks(&notification.message) {
                    Ok(Some(tasks)) => tasks,
                    Ok(None) => return Ok(()),
                    Err(error) => {
                        claude_sdk_events
                            .send(RuntimeEvent::Warning {
                                message: format!(
                                    "ignored malformed Claude background task level: {error}"
                                ),
                            })
                            .await
                            .map_err(|_| relay_event_channel_error())?;
                        // A malformed level cannot establish which provider
                        // tasks are still live, so keep the last known level
                        // until a valid replacement arrives.
                        return Ok(());
                    }
                };
                claude_sdk_events
                    .send(RuntimeEvent::ClaudeBackgroundTasksChanged { tasks })
                    .await
                    .map_err(|_| relay_event_channel_error())?;
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .on_receive_request(
            async move |request: RequestPermissionRequest, responder, _cx| {
                permission_activity.mark();
                permission_step_clock.begin_client_work();
                if permission_harness == HarnessKind::Muse && !permission_policy.is_unconstrained() {
                    let id = format!("tool-permission-{}", permission_review_ids.fetch_add(1, Ordering::Relaxed));
                    let options: Vec<_> = request.options.iter().map(|option| serde_json::json!({
                        "const": option.option_id.to_string(), "title": option.name,
                    })).collect();
                    let message = serde_json::to_string_pretty(&request.tool_call)
                        .map_err(|_| agent_client_protocol::Error::internal_error())?;
                    let form = ElicitationRequest::from_acp_params(id.clone(), serde_json::json!({
                        "mode": "form", "sessionId": request.session_id.to_string(),
                        "message": format!("Muse Code requests permission:\n{message}"),
                        "requestedSchema": {"type":"object", "required":["choice"], "properties":{
                            "choice":{"type":"string", "title":"Permission", "oneOf":options}
                        }}
                    })).map_err(|_| agent_client_protocol::Error::invalid_params())?;
                    let (answer, answer_rx) = oneshot::channel();
                    permission_elicitations.lock().expect("pending elicitation lock poisoned").insert(id.clone(), answer);
                    let pending = permission_elicitations.clone();
                    let events = permission_events.clone();
                    let cancellation = responder.cancellation();
                    tokio::spawn(async move {
                        let response = if events.send(RuntimeEvent::ElicitationRequested { request: form }).await.is_ok() {
                            tokio::select! { response = answer_rx => response.ok(), () = cancellation.cancelled() => None }
                        } else { None };
                        pending.lock().expect("pending elicitation lock poisoned").remove(&id);
                        let selected = match &response {
                            Some(ElicitationResponse::Accept { content }) if !cancellation.is_cancelled() => {
                                match content.get("choice") {
                                    Some(ElicitationValue::String(value)) => request.options.iter().find(|option| option.option_id.to_string() == *value),
                                    _ => None,
                                }
                            }
                            _ => None,
                        };
                        let outcome = selected.map_or(RequestPermissionOutcome::Cancelled, |option|
                            RequestPermissionOutcome::Selected(SelectedPermissionOutcome::new(option.option_id.clone())));
                        if let Err(error) = responder.respond(RequestPermissionResponse::new(outcome)) {
                            tracing::debug!(%error, "Muse permission responder closed");
                        }
                        if let Err(error) = events.send(RuntimeEvent::ElicitationResolved {
                            elicitation_id: id,
                            action: response.as_ref().map_or("cancel", ElicitationResponse::action_name).into(),
                        }).await {
                            tracing::debug!(%error, "Muse permission result receiver closed");
                        }
                    });
                    return Ok(());
                }
                if is_plan_permission(&request) {
                    let id = format!(
                        "plan-review-{}",
                        permission_review_ids.fetch_add(1, Ordering::Relaxed)
                    );
                    let value = serde_json::to_value(&request)
                        .map_err(|_| agent_client_protocol::Error::internal_error())?;
                    let review = normalized_plan_review(id.clone(), &value);
                    let approved_plan = plan_review_proposal(&review).unwrap_or_default().to_owned();
                    let implementation = permission_implementation_slot
                        .lock().expect("plan implementation lock poisoned").clone();
                    let (answer, answer_rx) = oneshot::channel();
                    permission_elicitations
                        .lock()
                        .expect("pending elicitation lock poisoned")
                        .insert(id.clone(), answer);
                    let pending = permission_elicitations.clone();
                    let events = permission_events.clone();
                    let cancellation = responder.cancellation();
                    tokio::spawn(async move {
                        if events
                            .send(RuntimeEvent::ElicitationRequested { request: review })
                            .await
                            .is_err()
                        {
                            pending
                                .lock()
                                .expect("pending elicitation lock poisoned")
                                .remove(&id);
                            if let Err(error) =
                                responder.respond_with_error(relay_event_channel_error())
                            {
                                tracing::debug!(
                                    %id,
                                    operation = "permission_request",
                                    %error,
                                    "could not report a stopped relay coordinator to ACP"
                                );
                            }
                            return;
                        }
                        let response = tokio::select! {
                            response = answer_rx => response.ok(),
                            () = cancellation.cancelled() => None,
                        };
                        pending
                            .lock()
                            .expect("pending elicitation lock poisoned")
                            .remove(&id);
                        let action = response
                            .as_ref()
                            .map_or("cancel", ElicitationResponse::action_name)
                            .to_owned();
                        if let Err(error) = events
                            .send(RuntimeEvent::ElicitationResolved {
                                elicitation_id: id.clone(),
                                action,
                            })
                            .await
                        {
                            tracing::debug!(
                                %id,
                                operation = "elicitation_resolved",
                                %error,
                                "could not report permission response to relay coordinator"
                            );
                        }
                        let response = if cancellation.is_cancelled() { None } else { response };
                        let mut handoff_completion = None;
                        let selection = response.map_or_else(
                            || Ok(PlanPermissionAnswer::Native(RequestPermissionResponse::new(RequestPermissionOutcome::Cancelled))),
                            |response| policy_plan_permission_answer(&request, response, permission_harness, permission_policy),
                        ).and_then(|selection| match selection {
                            PlanPermissionAnswer::Native(answer) => Ok(answer),
                            PlanPermissionAnswer::ContinueInBypass => {
                                let (completion, permission_sent) = oneshot::channel();
                                implementation.as_ref()
                                    .ok_or_else(|| anyhow!("Cannot resume the approved plan without an active prompt; select bypassPermissions and submit the implementation instruction."))?
                                    .send(PlanImplementation { plan: approved_plan, permission_sent })
                                    .map_err(|_| anyhow!("Plan implementation was cancelled because its prompt is no longer active."))?;
                                handoff_completion = Some(completion);
                                Ok(RequestPermissionResponse::new(RequestPermissionOutcome::Cancelled))
                            }
                        });
                        let answer = match selection {
                            Ok(answer) => answer,
                            Err(error) => {
                                if events.send(RuntimeEvent::Warning { message: format!("{error:#}") }).await.is_err() {
                                    tracing::debug!(%error, "could not report failed plan implementation");
                                }
                                RequestPermissionResponse::new(RequestPermissionOutcome::Cancelled)
                            }
                        };
                        let result = responder.respond(answer);
                        if let Some(completion) = handoff_completion
                            && completion.send(result.is_ok()).is_err()
                        {
                            tracing::debug!(%id, "plan implementation stopped before the permission response was delivered");
                        }
                        if let Err(error) = result {
                            tracing::debug!(
                                %id,
                                operation = "permission_response",
                                %error,
                                "ACP permission responder was already closed"
                            );
                        }
                    });
                    return Ok(());
                }
                // A permission request that is_plan_permission() did not classify
                // reaches the deny path below. Log its raw shape so an agent whose
                // request form we do not yet recognize is diagnosable from
                // worker.log instead of only surfacing as a silent denial.
                match serde_json::to_value(&request) {
                    Ok(raw) => tracing::debug!(
                        target: "hel_acp::plan_diag",
                        operation = "unclassified_permission_request",
                        request = %raw,
                        "permission request not classified as a plan review; raw payload follows"
                    ),
                    Err(error) => tracing::debug!(
                        target: "hel_acp::plan_diag",
                        operation = "unclassified_permission_request",
                        %error,
                        "permission request not classified as a plan review and could not be serialized"
                    ),
                }
                if permission_policy.is_unconstrained() {
                    permission_events
                        .send(RuntimeEvent::Warning {
                            message: UNEXPECTED_PERMISSION_REQUEST_WARNING.to_owned(),
                        })
                        .await
                        .map_err(|_| relay_event_channel_error())?;
                }
                // Permission escalations are denied safely because Hel has no
                // per-action human approval surface. An unconstrained harness
                // must never ask; denying instead of auto-approving makes a
                // broken mode selection visible rather than masking it.
                responder.respond(RequestPermissionResponse::new(
                    RequestPermissionOutcome::Cancelled,
                ))
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: CreateTerminalRequest, responder, _cx| {
                create_activity.mark();
                create_step_clock.begin_client_work();
                let started_at_ms = crate::clock::epoch_millis();
                let spawn = TerminalSpawn {
                    command: request.command.clone(),
                    args: request.args.clone(),
                    // Additions, not a replacement: the child inherits the
                    // daemon environment it needs to reach the toolchain.
                    env: request
                        .env
                        .iter()
                        .map(|variable| (variable.name.clone(), variable.value.clone()))
                        .collect(),
                    cwd: request.cwd.clone().unwrap_or_else(|| session_cwd.clone()),
                    output_byte_limit: request
                        .output_byte_limit
                        .and_then(|limit| usize::try_from(limit).ok())
                        .unwrap_or(DEFAULT_TERMINAL_OUTPUT_BYTES),
                };
                let command = spawn.display_command();
                match create_terminals.create(spawn, create_events.clone()) {
                    Ok(terminal_id) => {
                        create_events
                            .send(RuntimeEvent::TerminalStarted {
                                terminal_id: terminal_id.clone(),
                                command,
                                started_at_ms,
                            })
                            .await
                            .map_err(|_| relay_event_channel_error())?;
                        responder
                            .respond(CreateTerminalResponse::new(TerminalId::from(terminal_id)))
                    }
                    Err(error) => {
                        create_events
                            .send(RuntimeEvent::Warning {
                                message: format!("a client terminal failed to start: {error:#}"),
                            })
                            .await
                            .map_err(|_| relay_event_channel_error())?;
                        responder.respond_with_error(
                            agent_client_protocol::Error::internal_error()
                                .data(serde_json::Value::String(format!("{error:#}"))),
                        )
                    }
                }
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: TerminalOutputRequest, responder, _cx| {
                output_activity.mark();
                let terminal_id = request.terminal_id.to_string();
                let Some(snapshot) = output_terminals.output(&terminal_id) else {
                    return responder.respond_with_error(unknown_terminal_error(&terminal_id));
                };
                let mut response = TerminalOutputResponse::new(snapshot.output, snapshot.truncated);
                if let Some(exit) = &snapshot.exit {
                    response = response.exit_status(terminal_exit_status(exit));
                }
                responder.respond(response)
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: WaitForTerminalExitRequest, responder, _cx| {
                wait_activity.mark();
                let terminal_id = request.terminal_id.to_string();
                let Some(exit) = wait_terminals.exit_receiver(&terminal_id) else {
                    return responder.respond_with_error(unknown_terminal_error(&terminal_id));
                };
                // Handlers run on the dispatch loop, so awaiting the child here
                // would stop every other message until it exits.
                tokio::spawn(async move {
                    let exit = crate::hel_terminal::wait_for_exit(exit).await;
                    if let Err(error) = responder.respond(WaitForTerminalExitResponse::new(
                        terminal_exit_status(&exit),
                    )) {
                        // A closed channel means the relay already stopped, so
                        // this warning has nowhere left to go.
                        tracing::debug!(
                            %terminal_id,
                            operation = "terminal_wait_response",
                            %error,
                            "ACP terminal wait responder was already closed"
                        );
                    }
                });
                Ok(())
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: KillTerminalRequest, responder, _cx| {
                kill_activity.mark();
                let terminal_id = request.terminal_id.to_string();
                // The terminal stays valid: output and wait_for_exit still
                // answer for it until the agent releases it.
                if !kill_terminals.kill(&terminal_id) {
                    return responder.respond_with_error(unknown_terminal_error(&terminal_id));
                }
                responder.respond(KillTerminalResponse::new())
            },
            agent_client_protocol::on_receive_request!(),
        )
        .on_receive_request(
            async move |request: ReleaseTerminalRequest, responder, _cx| {
                release_activity.mark();
                let terminal_id = request.terminal_id.to_string();
                let Some(supervisor) = release_terminals.release(&terminal_id) else {
                    return responder.respond_with_error(unknown_terminal_error(&terminal_id));
                };
                // Reap off the dispatch loop: the supervisor still has to watch
                // the killed child exit before it reports the terminal closed.
                tokio::spawn(async move {
                    if let Err(error) = supervisor.await {
                        tracing::warn!(
                            %terminal_id,
                            operation = "terminal_release_reap",
                            %error,
                            "released terminal supervisor failed"
                        );
                    }
                });
                responder.respond(ReleaseTerminalResponse::new())
            },
            agent_client_protocol::on_receive_request!(),
        )
        // Catch-all, registered last so the typed handlers above win. The ACP
        // crate parks an unhandled request that carries a session id instead of
        // rejecting it, so without this an agent that sends an ext request Hel
        // does not know waits for a reply that never comes, and its turn never
        // ends. Hel answers every incoming request, always.
        .on_receive_request(
            async move |request: agent_client_protocol::UntypedMessage, responder, _cx| {
                ext_activity.mark();
                ext_step_clock.begin_client_work();
                let method = request.method().to_owned();
                if method == "elicitation/create" {
                    let id = format!(
                        "elicitation-{}",
                        next_elicitation_id.fetch_add(1, Ordering::Relaxed)
                    );
                    let request = match ElicitationRequest::from_acp_params(
                        id.clone(),
                        request.params().clone(),
                    ) {
                        Ok(request) => request,
                        Err(error) => {
                            return responder.respond_with_error(
                                agent_client_protocol::Error::invalid_params().data(
                                    serde_json::Value::String(format!(
                                        "invalid ACP form elicitation: {error:#}"
                                    )),
                                ),
                            );
                        }
                    };
                    let (answer, answer_rx) = oneshot::channel();
                    handler_elicitations
                        .lock()
                        .expect("pending elicitation lock poisoned")
                        .insert(id.clone(), answer);
                    let pending = handler_elicitations.clone();
                    let events = elicitation_events.clone();
                    let cancellation = responder.cancellation();
                    tokio::spawn(async move {
                        if events
                            .send(RuntimeEvent::ElicitationRequested { request })
                            .await
                            .is_err()
                        {
                            pending
                                .lock()
                                .expect("pending elicitation lock poisoned")
                                .remove(&id);
                            if let Err(error) =
                                responder.respond_with_error(relay_event_channel_error())
                            {
                                tracing::debug!(
                                    %id,
                                    operation = "elicitation_request",
                                    %error,
                                    "could not report a stopped relay coordinator to ACP"
                                );
                            }
                            return;
                        }
                        let response = tokio::select! {
                            response = answer_rx => response.ok(),
                            () = cancellation.cancelled() => None,
                        };
                        pending
                            .lock()
                            .expect("pending elicitation lock poisoned")
                            .remove(&id);
                        let action = response
                            .as_ref()
                            .map_or("cancel", ElicitationResponse::action_name)
                            .to_owned();
                        if let Err(error) = events
                            .send(RuntimeEvent::ElicitationResolved {
                                elicitation_id: id.clone(),
                                action,
                            })
                            .await
                        {
                            tracing::debug!(
                                %id,
                                operation = "elicitation_resolved",
                                %error,
                                "could not report elicitation response to relay coordinator"
                            );
                        }
                        match response {
                            Some(response) => match serde_json::to_value(response) {
                                Ok(response) => {
                                    if let Err(error) = responder.respond(response) {
                                        tracing::debug!(
                                            %id,
                                            operation = "elicitation_response",
                                            %error,
                                            "ACP elicitation responder was already closed"
                                        );
                                    }
                                }
                                Err(error) => {
                                    if let Err(error) = responder.respond_with_error(
                                        agent_client_protocol::Error::internal_error().data(
                                            serde_json::Value::String(format!(
                                                "serialize elicitation response: {error}"
                                            )),
                                        ),
                                    ) {
                                        tracing::debug!(
                                            %id,
                                            operation = "elicitation_response",
                                            %error,
                                            "ACP elicitation error responder was already closed"
                                        );
                                    }
                                }
                            },
                            None => {
                                if let Err(error) = responder.respond_with_error(
                                    agent_client_protocol::Error::request_cancelled(),
                                ) {
                                    tracing::debug!(
                                        %id,
                                        operation = "elicitation_cancel",
                                        %error,
                                        "ACP cancellation responder was already closed"
                                    );
                                }
                            }
                        }
                    });
                    return Ok(());
                }
                if grok::handles_exit_plan_mode(ext_harness, &method) {
                    let id = grok::plan_review_id(ext_review_ids.fetch_add(1, Ordering::Relaxed));
                    let review = normalized_plan_review(id.clone(), request.params());
                    let (answer, answer_rx) = oneshot::channel();
                    handler_elicitations
                        .lock()
                        .expect("pending elicitation lock poisoned")
                        .insert(id.clone(), answer);
                    let pending = handler_elicitations.clone();
                    let events = ext_events.clone();
                    let cancellation = responder.cancellation();
                    tokio::spawn(async move {
                        if events
                            .send(RuntimeEvent::ElicitationRequested { request: review })
                            .await
                            .is_err()
                        {
                            pending
                                .lock()
                                .expect("pending elicitation lock poisoned")
                                .remove(&id);
                            if let Err(error) =
                                responder.respond_with_error(relay_event_channel_error())
                            {
                                tracing::debug!(
                                    %id,
                                    operation = "plan_review_request",
                                    %error,
                                    "could not report a stopped relay coordinator to ACP"
                                );
                            }
                            return;
                        }
                        let response = tokio::select! {
                            response = answer_rx => response.ok(),
                            () = cancellation.cancelled() => None,
                        };
                        pending
                            .lock()
                            .expect("pending elicitation lock poisoned")
                            .remove(&id);
                        let action = response
                            .as_ref()
                            .map_or("cancel", ElicitationResponse::action_name)
                            .to_owned();
                        if let Err(error) = events
                            .send(RuntimeEvent::ElicitationResolved {
                                elicitation_id: id.clone(),
                                action,
                            })
                            .await
                        {
                            tracing::debug!(
                                %id,
                                operation = "plan_review_resolved",
                                %error,
                                "could not report plan review response to relay coordinator"
                            );
                        }
                        if let Err(error) = responder.respond(response.map_or_else(
                            || serde_json::json!({ "outcome": "cancelled" }),
                            grok::plan_response,
                        )) {
                            tracing::debug!(
                                %id,
                                operation = "plan_review_response",
                                %error,
                                "ACP plan review responder was already closed"
                            );
                        }
                    });
                    return Ok(());
                }
                ext_events
                    .send(RuntimeEvent::Warning {
                        message: unsupported_client_request_report(&method),
                    })
                    .await
                    .map_err(|_| relay_event_channel_error())?;
                responder.respond_with_error(
                    agent_client_protocol::Error::method_not_found()
                        .data(serde_json::Value::String(method)),
                )
            },
            agent_client_protocol::on_receive_request!(),
        )
        .connect_with(transport, |connection: ConnectionTo<Agent>| async move {
            match drive_connection(
                connection,
                &spec,
                requests,
                &events,
                terminals,
                session_elicitations,
                plan_implementation_slot,
                opened,
                session_update_count,
                session_updates_enabled,
                resume_required,
                replacing_previous_bridge,
            )
            .await
            {
                Ok(native_session_id) => {
                    *restart_slot.lock().expect("ACP restart slot lock poisoned") =
                        native_session_id;
                    Ok(())
                }
                Err(error) => Err(agent_client_protocol::Error::internal_error()
                    .data(serde_json::Value::String(format!("{error:#}")))),
            }
        })
        .await
        .map_err(|error| {
            anyhow!(
                "ACP protocol failed: {error}; bridge stdout must contain only JSON-RPC frames \
                 and login-shell startup must be silent"
            )
        })?;
    Ok(restart
        .lock()
        .expect("ACP restart slot lock poisoned")
        .take())
}

/// Stop reason reported for a turn the bridge rejected instead of finishing.
const PROMPT_ERROR_STOP_REASON: &str = "error";

/// Marker Hel adds to the warning for a prompt the bridge failed with ACP's
/// `auth_required`. The wire message is a bare "Authentication required", too
/// generic for `hel_credentials` to match on text alone, so the error code —
/// not the bridge's wording — decides whether the credential heuristic fires.
pub const PROMPT_AUTH_REQUIRED_MARKER: &str = "ACP auth_required";

/// Marker on a successful ACP response that carried no session updates. Some
/// bridges use this shape when their underlying turn failed, so completing it
/// silently would leave a user line with no answer or explanation.
pub const PROMPT_EMPTY_RESPONSE_MARKER: &str = "ACP prompt returned no session updates";

fn prompt_failure_warning(error: &agent_client_protocol::Error) -> String {
    if error.code == agent_client_protocol::ErrorCode::AuthRequired {
        format!("prompt failed ({PROMPT_AUTH_REQUIRED_MARKER}): {error}")
    } else {
        format!("prompt failed: {error}")
    }
}

fn prompt_returned_without_updates(
    stop_reason: &StopReason,
    updates_before: u64,
    updates_after: u64,
) -> bool {
    *stop_reason != StopReason::Cancelled && updates_before == updates_after
}

/// Only catalogue and selector announcements can prove a thread is unused.
/// Treat all other updates, including future ACP variants, as native history.
pub(crate) fn session_update_has_native_history(update: &SessionUpdate) -> bool {
    !matches!(
        update,
        SessionUpdate::AvailableCommandsUpdate(_)
            | SessionUpdate::ConfigOptionUpdate(_)
            | SessionUpdate::CurrentModeUpdate(_)
    )
}

#[allow(clippy::too_many_arguments)]
async fn drive_connection(
    connection: ConnectionTo<Agent>,
    spec: &LaunchSpec,
    requests: &mut mpsc::Receiver<CommandRequest>,
    events: &mpsc::Sender<RuntimeEvent>,
    terminals: TerminalRegistry,
    pending_elicitations: PendingElicitations,
    plan_implementation_slot: PlanImplementationSlot,
    opened: Arc<Mutex<Option<OpenedSession>>>,
    session_update_count: Arc<AtomicU64>,
    session_updates_enabled: Arc<AtomicBool>,
    resume_required: Arc<AtomicBool>,
    replacing_previous_bridge: bool,
) -> Result<Option<String>> {
    // Terminals belong to the connection. However the session ends — closed,
    // failed, or with its command channel dropped — their process groups must
    // not outlive it.
    let result = serve_session(
        &connection,
        spec,
        requests,
        events,
        &terminals,
        &pending_elicitations,
        &plan_implementation_slot,
        opened,
        &session_update_count,
        &session_updates_enabled,
        resume_required,
        replacing_previous_bridge,
    )
    .await;
    pending_elicitations
        .lock()
        .expect("pending elicitation lock poisoned")
        .clear();
    terminals.shutdown(events).await;
    result
}

async fn apply_cancel(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    cancel_id: String,
    events: &mpsc::Sender<RuntimeEvent>,
    terminals: &TerminalRegistry,
) -> Result<()> {
    terminals.kill_live();
    match connection.send_notification(CancelNotification::new(session_id.clone())) {
        Ok(()) => {
            emit_runtime_event(
                events,
                RuntimeEvent::CancelApplied {
                    request_id: cancel_id,
                },
            )
            .await
        }
        Err(error) => {
            emit_runtime_event(
                events,
                RuntimeEvent::CommandRejected {
                    request_id: cancel_id,
                    message: format!("cancel ACP prompt: {error}"),
                },
            )
            .await
        }
    }
}

const BACKGROUND_TASK_STOP_TIMEOUT: Duration = Duration::from_secs(5);

async fn stop_background_task(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    terminals: &TerminalRegistry,
    target: crate::hel_worker::BackgroundTaskStopTarget,
) -> std::result::Result<(), String> {
    match target {
        crate::hel_worker::BackgroundTaskStopTarget::HostedTerminal { terminal_id } => {
            if terminals.kill(&terminal_id) {
                Ok(())
            } else {
                Err("background task is no longer running".into())
            }
        }
        crate::hel_worker::BackgroundTaskStopTarget::ClaudeAsyncTask { task_id } => {
            let request = ClaudeAsyncTaskStopRequest {
                session_id: session_id.clone(),
                async_task_id: task_id,
            };
            match tokio::time::timeout(
                BACKGROUND_TASK_STOP_TIMEOUT,
                connection.send_request(request).block_task(),
            )
            .await
            {
                Ok(Ok(response)) if response.stopped => Ok(()),
                Ok(Ok(_)) => Err("background task is no longer stoppable".into()),
                Ok(Err(error)) => Err(format!("stop Claude background task: {error}")),
                Err(_) => Err("timed out stopping Claude background task".into()),
            }
        }
    }
}

async fn resolve_background_task_stop(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    terminals: &TerminalRegistry,
    target: crate::hel_worker::BackgroundTaskStopTarget,
    resolved: oneshot::Sender<std::result::Result<(), String>>,
) {
    let result = stop_background_task(connection, session_id, terminals, target).await;
    if resolved.send(result).is_err() {
        tracing::debug!(
            session_id = %session_id,
            operation = "stop_background_task",
            "background task stop receiver was already closed"
        );
    }
}

const SESSION_STEERING_METHOD: &str = "_session/steering";

fn steering_supported_from_meta(meta: Option<&agent_client_protocol::schema::v1::Meta>) -> bool {
    meta.and_then(|meta| meta.get("steering"))
        .and_then(|steering| steering.get("supported"))
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
}

struct PendingSteer {
    request_id: String,
    queued_command_id: String,
    response: Pin<
        Box<
            dyn Future<
                    Output = std::result::Result<serde_json::Value, agent_client_protocol::Error>,
                > + Send,
        >,
    >,
}

fn start_steer(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    request_id: String,
    steering_prompt: ClaimedSteeringPrompt,
) -> PendingSteer {
    let connection = connection.clone();
    let session_id = session_id.clone();
    let queued_command_id = steering_prompt.queued_command_id.clone();
    let response = Box::pin(async move {
        let mut prompt = steering_prompt.prompt;
        if let Some(root) = steering_prompt.attachment_root {
            prompt = tokio::task::spawn_blocking(move || -> Result<Vec<ContentBlock>> {
                crate::hel_attachment::AttachmentStore::worker(&root).resolve(&mut prompt)?;
                Ok(prompt)
            })
            .await
            .map_err(|error| {
                agent_client_protocol::Error::internal_error()
                    .data(serde_json::Value::String(error.to_string()))
            })?
            .map_err(|error| {
                agent_client_protocol::Error::internal_error()
                    .data(serde_json::Value::String(error.to_string()))
            })?;
        }
        let request = UntypedMessage {
            method: SESSION_STEERING_METHOD.to_owned(),
            params: serde_json::json!({ "sessionId": session_id, "prompt": prompt, "_meta": { "steering": { "idleBehavior": "promptRequired" } } }),
        };
        connection.send_request(request).block_task().await
    });
    PendingSteer {
        request_id,
        queued_command_id,
        response,
    }
}

async fn settle_steer(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    events: &mpsc::Sender<RuntimeEvent>,
    terminals: &TerminalRegistry,
    pending: PendingSteer,
    outcome: std::result::Result<serde_json::Value, agent_client_protocol::Error>,
    turn_running: bool,
) -> Result<bool> {
    match outcome
        .as_ref()
        .ok()
        .and_then(|value| value.get("outcome"))
        .and_then(serde_json::Value::as_str)
    {
        Some("injected") => {
            emit_runtime_event(
                events,
                RuntimeEvent::SteerApplied {
                    request_id: pending.request_id,
                    queued_command_id: pending.queued_command_id,
                },
            )
            .await?;
            Ok(false)
        }
        outcome => {
            let detached_turn = outcome == Some("startedNewTurn");
            if turn_running || detached_turn {
                apply_cancel(
                    connection,
                    session_id,
                    pending.request_id,
                    events,
                    terminals,
                )
                .await?;
                Ok(true)
            } else {
                emit_runtime_event(
                    events,
                    RuntimeEvent::CancelApplied {
                        request_id: pending.request_id,
                    },
                )
                .await?;
                Ok(false)
            }
        }
    }
}

/// Discard requests left in the channel by the bridge that just restarted. See
/// the call site in [`serve_session`] for why nothing is reported back.
fn drain_requests_from_the_previous_bridge(requests: &mut mpsc::Receiver<CommandRequest>) {
    while let Ok(request) = requests.try_recv() {
        let (variant, request_id) = match request {
            CommandRequest::Prompt { request_id, .. }
            | CommandRequest::PromptAttachments { request_id, .. } => ("Prompt", Some(request_id)),
            CommandRequest::SetConfig { request_id, .. } => ("SetConfig", Some(request_id)),
            CommandRequest::SetSessionMode { request_id, .. } => {
                ("SetSessionMode", Some(request_id))
            }
            CommandRequest::Cancel { request_id, .. } => ("Cancel", Some(request_id)),
            CommandRequest::Close { request_id } => ("Close", Some(request_id)),
            CommandRequest::ResolveElicitation { .. } => ("ResolveElicitation", None),
            CommandRequest::StopBackgroundTask { resolved, .. } => {
                let _ = resolved.send(Err("ACP bridge restarted before stopping task".into()));
                ("StopBackgroundTask", None)
            }
        };
        tracing::debug!(
            operation = "acp_bridge_restart",
            variant,
            request_id = request_id.as_deref().unwrap_or("-"),
            "dropping a request queued for the previous ACP bridge"
        );
    }
}

#[allow(clippy::too_many_arguments)]
async fn serve_session(
    connection: &ConnectionTo<Agent>,
    spec: &LaunchSpec,
    requests: &mut mpsc::Receiver<CommandRequest>,
    events: &mpsc::Sender<RuntimeEvent>,
    terminals: &TerminalRegistry,
    pending_elicitations: &PendingElicitations,
    plan_implementation_slot: &PlanImplementationSlot,
    opened: Arc<Mutex<Option<OpenedSession>>>,
    session_update_count: &AtomicU64,
    session_updates_enabled: &AtomicBool,
    resume_required: Arc<AtomicBool>,
    replacing_previous_bridge: bool,
) -> Result<Option<String>> {
    let mut meta = serde_json::Map::new();
    meta.insert("terminal_output".into(), serde_json::Value::Bool(true));
    if spec.harness == HarnessKind::Claude {
        meta.insert(
            "jetbrains".into(),
            serde_json::json!({
                "air": {
                    "version": 1,
                    "capabilities": ["asyncTasks"]
                }
            }),
        );
    }
    // Kimi routes every shell call through the client's terminal surface and
    // has no local fallback, so this capability is what makes Bash work.
    let capabilities = ClientCapabilities::new()
        .terminal(true)
        .elicitation(ElicitationCapabilities::new().form(ElicitationFormCapabilities::new()))
        .meta(meta);
    let initialized = connection
        .send_request(
            InitializeRequest::new(ProtocolVersion::V1)
                .client_info(
                    Implementation::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
                        .title("Mjolnir"),
                )
                .client_capabilities(capabilities),
        )
        .block_task()
        .await;
    spec.acp_activity.mark();
    let initialized = initialized.context("initialize ACP bridge")?;
    if initialized.protocol_version != ProtocolVersion::V1 {
        bail!(
            "ACP bridge negotiated unsupported protocol {:?}",
            initialized.protocol_version
        );
    }
    let steering_supported = steering_supported_from_meta(initialized.meta.as_ref());
    // Grok Build publishes its catalogue here rather than as `configOptions`.
    let mut grok_models = (spec.harness == HarnessKind::Grok)
        .then(|| grok::model_state(initialized.meta.as_ref()))
        .flatten();
    emit_runtime_event(
        events,
        RuntimeEvent::Connected {
            agent_name: initialized
                .agent_info
                .as_ref()
                .map(|info| info.name.clone()),
            agent_version: initialized
                .agent_info
                .as_ref()
                .map(|info| info.version.clone()),
            protocol_version: Some(initialized.protocol_version),
            capabilities: Some(Box::new(initialized.agent_capabilities.clone())),
            agent_info: initialized.agent_info.clone(),
            steering_supported: Some(steering_supported),
        },
    )
    .await?;

    let loaded_session = if let Some(existing) = &spec.resume_session {
        let session_id = SessionId::from(existing.clone());
        // The relay already owns the transcript. Prefer resuming without
        // replay so a large native history cannot delay worker readiness.
        let (loaded_meta, config_options, modes) = if initialized
            .agent_capabilities
            .session_capabilities
            .resume
            .is_some()
        {
            let resumed = connection
                .send_request(resume_session_request(spec, session_id.clone()))
                .block_task()
                .await;
            spec.acp_activity.mark();
            let resumed = resumed.with_context(|| format!("resume ACP session {existing}"))?;
            (resumed.meta, resumed.config_options, resumed.modes)
        } else {
            let loaded = connection
                .send_request(load_session_request(spec, session_id.clone()))
                .block_task()
                .await;
            spec.acp_activity.mark();
            let loaded = loaded.with_context(|| format!("load ACP session {existing}"))?;
            (loaded.meta, loaded.config_options, loaded.modes)
        };
        if let Some(state) = grok_models.as_mut()
            && let Some(fresh) = grok::model_state(loaded_meta.as_ref())
        {
            *state = fresh;
        }
        // The response is the boundary between provider replay and future
        // live updates for this connection.
        session_updates_enabled.store(true, Ordering::Release);
        Some((session_id, config_options, modes))
    } else {
        None
    };
    let (session_id, config_options, modes, resumed) =
        if let Some((id, options, modes)) = loaded_session {
            (id, options, modes, true)
        } else {
            let created = connection
                .send_request(new_session_request(spec, true))
                .block_task()
                .await;
            spec.acp_activity.mark();
            let created = created.context("create ACP session")?;
            // A session may open on a different model than the agent-wide
            // default, so a fresher catalogue on the session wins.
            if let Some(state) = grok_models.as_mut()
                && let Some(fresh) = grok::model_state(created.meta.as_ref())
            {
                *state = fresh;
            }
            (
                created.session_id,
                created.config_options,
                created.modes,
                false,
            )
        };

    // Launch flags and environment are applied before the bridge starts. ACP
    // modes are selected after the session exists, before any prompt can run.
    let enforcement = spec.harness.execution_enforcement(spec.execution_policy);
    let mut config_options = config_options.unwrap_or_default();
    let mut modes = modes;
    if let Some(desired_mode) = enforcement.and_then(ExecutionEnforcement::acp_mode) {
        enforce_execution_mode(
            connection,
            &session_id,
            desired_mode,
            &mut config_options,
            &mut modes,
        )
        .await?;
    }
    // Grok Build publishes model selection through its legacy catalogue. Keep
    // any standard selectors it also returns while projecting model/effort
    // into the shape the rest of Hel reads.
    if let Some(state) = &grok_models {
        grok::merge_config_options(&mut config_options, state);
    }
    let accepted = spec
        .accepted_config
        .lock()
        .map_err(|_| anyhow!("accepted session configuration lock was poisoned"))?
        .clone();
    // Model selection can replace the effort catalogue. Both must be
    // restored before SessionConfigured releases queued prompts.
    for (key, value) in [("model", accepted.model), ("effort", accepted.effort)] {
        let Some(value) = value else { continue };
        apply_session_selector(
            connection,
            &session_id,
            &mut config_options,
            &mut grok_models,
            key,
            &value,
        )
        .await
        .with_context(|| format!("restore this session's accepted {key} {value:?}"))?;
    }
    // Startup failures must retain their cause rather than being classified
    // as a dead running bridge and retried with the same invalid settings.
    *opened.lock().expect("opened session lock poisoned") = Some(OpenedSession {
        native_session_id: session_id.to_string(),
        started_at: tokio::time::Instant::now(),
        resume_required,
    });
    // Drop anything the worker queued for the bridge this one replaced. The
    // worker dispatches only while it believes the session is configured; it
    // clears that flag on `HarnessRestarting` and sets it again only after this
    // bridge's `SessionConfigured`, which has not been sent yet. So every
    // request still in the channel was dispatched before the worker saw the
    // restart and is already in the set the worker interrupted. Emitting a
    // runtime event for one would interrupt it twice and fail the coordinator's
    // `require_in_flight`; delivering it would run it untracked on the fresh
    // session. A first start drains nothing: out-of-band senders such as
    // compaction are not gated on the session being configured, so a request
    // that arrives while the very first bridge is still handshaking is a live
    // request for this session, not a leftover.
    if replacing_previous_bridge {
        drain_requests_from_the_previous_bridge(requests);
    }

    emit_runtime_event(
        events,
        RuntimeEvent::SessionStarted {
            native_session_id: session_id.to_string(),
            resumed,
            execution_mode: enforcement.map(|enforcement| enforcement.label().to_owned()),
        },
    )
    .await?;
    emit_runtime_event(
        events,
        RuntimeEvent::SessionConfigured {
            config_options: config_options.clone(),
        },
    )
    .await?;
    emit_runtime_event(
        events,
        RuntimeEvent::SessionModesConfigured {
            modes: modes.clone(),
        },
    )
    .await?;

    while let Some(request) = requests.recv().await {
        let request = match request {
            CommandRequest::PromptAttachments {
                request_id,
                mut prompt,
                root,
            } => {
                match tokio::task::spawn_blocking(move || -> Result<Vec<ContentBlock>> {
                    crate::hel_attachment::AttachmentStore::worker(&root).resolve(&mut prompt)?;
                    Ok(prompt)
                })
                .await
                {
                    Ok(Ok(prompt)) => CommandRequest::Prompt { request_id, prompt },
                    result => {
                        let message = match result {
                            Ok(Err(error)) => format!("could not load attached images: {error:#}"),
                            Err(error) => format!("image loading task failed: {error}"),
                            Ok(Ok(_)) => unreachable!(),
                        };
                        emit_runtime_event(
                            events,
                            RuntimeEvent::CommandRejected {
                                request_id,
                                message,
                            },
                        )
                        .await?;
                        continue;
                    }
                }
            }
            request => request,
        };
        match request {
            CommandRequest::PromptAttachments { .. } => {
                unreachable!("resolved before ACP dispatch")
            }
            CommandRequest::Prompt { request_id, prompt } => {
                if prompt.is_empty() {
                    emit_runtime_event(
                        events,
                        RuntimeEvent::CommandRejected {
                            request_id,
                            message: "ACP prompt has no content blocks".into(),
                        },
                    )
                    .await?;
                    continue;
                }
                let mut updates_before = session_update_count.load(Ordering::Acquire);
                // Mark before sending: even a failed reply cannot prove the
                // agent did not receive and persist this prompt.
                if let Some(opened) = opened
                    .lock()
                    .expect("opened session lock poisoned")
                    .as_mut()
                {
                    opened.resume_required.store(true, Ordering::Release);
                }
                spec.step_clock.begin_turn();
                let mut prompt: ActivePrompt = Box::pin(
                    connection
                        .send_request(PromptRequest::new(session_id.clone(), prompt))
                        .block_task(),
                );
                let (implementation_tx, mut implementation_rx) = mpsc::unbounded_channel();
                *plan_implementation_slot
                    .lock()
                    .expect("plan implementation lock poisoned") = Some(implementation_tx);
                let _active_implementation =
                    ActivePlanImplementation(plan_implementation_slot.clone());
                let mut approved_plan = None;
                let mut implementation_deadline = None;
                let mut mode_restoration: Option<PlanModeRestoration<'_>> = None;
                let mut prompt_running = true;
                let mut cancel_deadline = None;
                let mut pending_steer: Option<PendingSteer> = None;
                loop {
                    tokio::select! {
                        biased;
                        Some(plan) = implementation_rx.recv(), if cancel_deadline.is_none() && approved_plan.is_none() && mode_restoration.is_none() => {
                            approved_plan = Some(plan);
                            implementation_deadline = Some(tokio::time::Instant::now() + CANCEL_ACK_TIMEOUT);
                            emit_runtime_event(events, RuntimeEvent::Warning {
                                message: "Plan approved; waiting for Claude to finish planning before restoring bypassPermissions.".into(),
                            }).await?;
                        }
                        response = &mut prompt, if prompt_running => {
                            spec.acp_activity.mark();
                            spec.step_clock.end_turn();
                            if approved_plan.is_some() && cancel_deadline.is_none() {
                                if matches!(&response, Ok(response) if matches!(response.stop_reason, StopReason::EndTurn | StopReason::Cancelled)) {
                                    prompt_running = false;
                                    let implementation = approved_plan.take().expect("approved plan is present");
                                    mode_restoration = Some(Box::pin(restore_plan_execution_mode(connection, session_id.clone(), RestoredPlanMode {
                                        config_options: config_options.clone(), modes: modes.clone(), plan: implementation.plan,
                                    }, implementation.permission_sent)));
                                    continue;
                                }
                                emit_runtime_event(events, RuntimeEvent::Warning {
                                    message: "Plan implementation stopped because Claude did not finish the planning turn successfully.".into(),
                                }).await?;
                            }
                            if let Some(mut pending) = pending_steer.take() {
                                match tokio::time::timeout(
                                    Duration::from_secs(2),
                                    pending.response.as_mut(),
                                )
                                .await
                                {
                                    Ok(outcome) => {
                                        settle_steer(
                                            connection,
                                            &session_id,
                                            events,
                                            terminals,
                                            pending,
                                            outcome,
                                            false,
                                        )
                                        .await?;
                                    }
                                    Err(_) => {
                                        emit_runtime_event(
                                            events,
                                            RuntimeEvent::CancelApplied {
                                                request_id: pending.request_id,
                                            },
                                        )
                                        .await?;
                                    }
                                }
                            }
                            // A rejected prompt fails the turn, not the worker: the
                            // bridge can still serve later prompts. A JSON-RPC
                            // error stays on this connection; a dead transport
                            // is recovered by `run_bridge` via child exit or a
                            // protocol error after the session is open.
                            let stop_reason = match response {
                                Ok(response) => {
                                    if prompt_returned_without_updates(
                                        &response.stop_reason,
                                        updates_before,
                                        session_update_count.load(Ordering::Acquire),
                                    ) {
                                        emit_runtime_event(
                                            events,
                                            RuntimeEvent::Warning {
                                                message: PROMPT_EMPTY_RESPONSE_MARKER.to_owned(),
                                            },
                                        )
                                        .await?;
                                    }
                                    format!("{:?}", response.stop_reason)
                                }
                                Err(error) => {
                                    emit_runtime_event(
                                        events,
                                        RuntimeEvent::Warning {
                                            message: prompt_failure_warning(&error),
                                        },
                                    )
                                    .await?;
                                    if spec.harness == HarnessKind::Codex && crate::hel_worker::capacity_error(&error) {
                                        crate::hel_worker::CAPACITY_STOP_REASON.to_owned()
                                    } else {
                                        PROMPT_ERROR_STOP_REASON.to_owned()
                                    }
                                }
                            };
                            emit_runtime_event(
                                events,
                                RuntimeEvent::PromptFinished {
                                    request_id,
                                    stop_reason,
                                },
                            )
                            .await?;
                            // An acknowledged cancel leaves the bridge in
                            // place; the next prompt goes to the same session.
                            break;
                        }
                        _ = async {
                            tokio::time::sleep_until(implementation_deadline.expect("implementation deadline branch is guarded")).await;
                        }, if implementation_deadline.is_some() => {
                            let message = "Plan implementation timed out while finishing planning or restoring bypassPermissions; restarting the harness without submitting the continuation.";
                            emit_runtime_event(events, RuntimeEvent::Warning { message: message.into() }).await?;
                            emit_runtime_event(events, RuntimeEvent::CommandInterrupted { request_id, message: message.into() }).await?;
                            return Ok(Some(session_id.to_string()));
                        }
                        _ = async {
                            tokio::time::sleep_until(
                                cancel_deadline.expect("cancel deadline branch is guarded"),
                            )
                            .await;
                        }, if cancel_deadline.is_some() => {
                            emit_runtime_event(
                                events,
                                RuntimeEvent::Warning {
                                    message: CANCEL_UNACKED_WARNING.to_owned(),
                                },
                            )
                            .await?;
                            emit_runtime_event(
                                events,
                                RuntimeEvent::CommandInterrupted {
                                    request_id,
                                    message: CANCEL_UNACKED_WARNING.to_owned(),
                                },
                            )
                            .await?;
                            return Ok(Some(session_id.to_string()));
                        }
                        steer_outcome = async {
                            pending_steer
                                .as_mut()
                                .expect("steering branch is guarded")
                                .response
                                .as_mut()
                                .await
                        }, if pending_steer.is_some() => {
                            let pending = pending_steer
                                .take()
                                .expect("steering branch is guarded");
                            if settle_steer(
                                connection,
                                &session_id,
                                events,
                                terminals,
                                pending,
                                steer_outcome,
                                true,
                            )
                            .await?
                                && cancel_deadline.is_none()
                            {
                                cancel_deadline =
                                    Some(tokio::time::Instant::now() + CANCEL_ACK_TIMEOUT);
                            }
                        }
                        command = requests.recv() => match command {
                            Some(CommandRequest::Cancel {
                                request_id: cancel_id,
                                steering_prompt,
                            }) => {
                                implementation_rx.close();
                                approved_plan = None;
                                implementation_deadline = None;
                                if !prompt_running {
                                    apply_cancel(connection, &session_id, cancel_id, events, terminals).await?;
                                    emit_runtime_event(events, RuntimeEvent::PromptFinished {
                                        request_id, stop_reason: "Cancelled".into(),
                                    }).await?;
                                    break;
                                }
                                if steering_supported
                                    && pending_steer.is_none()
                                    && cancel_deadline.is_none()
                                    && let Some(steering_prompt) = steering_prompt
                                {
                                    pending_steer = Some(start_steer(
                                        connection,
                                        &session_id,
                                        cancel_id,
                                        steering_prompt,
                                    ));
                                } else {
                                    apply_cancel(
                                        connection,
                                        &session_id,
                                        cancel_id,
                                        events,
                                        terminals,
                                    )
                                    .await?;
                                    if cancel_deadline.is_none() {
                                        cancel_deadline = Some(
                                            tokio::time::Instant::now() + CANCEL_ACK_TIMEOUT,
                                        );
                                    }
                                }
                            }
                            Some(CommandRequest::Close { request_id: close_id }) => {
                                if let Err(error) = connection.send_notification(CancelNotification::new(session_id.clone())) {
                                    emit_runtime_event(
                                        events,
                                        RuntimeEvent::Warning {
                                            message: format!("cancel ACP prompt before close: {error}"),
                                        },
                                    )
                                    .await?;
                                }
                                emit_runtime_event(
                                    events,
                                    RuntimeEvent::CommandInterrupted {
                                        request_id: request_id.clone(),
                                        message: "prompt interrupted because the session was closed".into(),
                                    },
                                )
                                .await?;
                                match connection
                                    .send_request(CloseSessionRequest::new(session_id.clone()))
                                    .block_task()
                                    .await
                                {
                                    Ok(_) => {
                                        emit_runtime_event(
                                            events,
                                            RuntimeEvent::CloseApplied {
                                                request_id: close_id,
                                            },
                                        )
                                        .await?;
                                    }
                                    Err(error) => {
                                        emit_runtime_event(
                                            events,
                                            RuntimeEvent::CommandRejected {
                                                request_id: close_id,
                                                message: format!("close ACP session: {error}"),
                                            },
                                        )
                                        .await?;
                                    }
                                }
                                return Ok(None);
                            }
                            None => {
                                let cancellation = connection
                                    .send_notification(CancelNotification::new(session_id.clone()));
                                emit_runtime_event(
                                    events,
                                    RuntimeEvent::CommandInterrupted {
                                        request_id: request_id.clone(),
                                        message: "ACP command channel closed while the prompt was running".into(),
                                    },
                                )
                                .await?;
                                cancellation.context("cancel ACP prompt during runtime shutdown")?;
                                return Ok(None);
                            }
                            Some(CommandRequest::Prompt { request_id, .. } | CommandRequest::PromptAttachments { request_id, .. }) => {
                                emit_runtime_event(
                                    events,
                                    RuntimeEvent::CommandRejected {
                                        request_id,
                                        message: "a prompt is already running".into(),
                                    },
                                )
                                .await?;
                            }
                            Some(CommandRequest::SetConfig { request_id, .. }) => {
                                emit_runtime_event(
                                    events,
                                    RuntimeEvent::CommandRejected {
                                        request_id,
                                        message: "configuration can only be changed while the agent is idle".into(),
                                    },
                                )
                                .await?;
                            }
                            Some(CommandRequest::SetSessionMode { request_id, .. }) => {
                                emit_runtime_event(
                                    events,
                                    RuntimeEvent::CommandRejected {
                                        request_id,
                                        message: "the session mode can only be changed while the agent is idle".into(),
                                    },
                                )
                                .await?;
                            }
                            Some(CommandRequest::ResolveElicitation {
                                elicitation_id,
                                response,
                                resolved,
                            }) => {
                                if resolved
                                    .send(resolve_pending_elicitation(
                                        pending_elicitations,
                                        &elicitation_id,
                                        response,
                                    ))
                                    .is_err()
                                {
                                    tracing::debug!(
                                        session_id = %session_id,
                                        operation = "resolve_elicitation",
                                        %elicitation_id,
                                        "elicitation resolution receiver was already closed"
                                    );
                                }
                            }
                            Some(CommandRequest::StopBackgroundTask { target, resolved }) => {
                                resolve_background_task_stop(
                                    connection,
                                    &session_id,
                                    terminals,
                                    target,
                                    resolved,
                                )
                                .await;
                            }
                        },
                        restored = async {
                            mode_restoration.as_mut().expect("mode restoration branch is guarded").await
                        }, if mode_restoration.is_some() && requests.is_empty() => {
                            mode_restoration = None;
                            implementation_deadline = None;
                            match restored {
                                Ok(state) => {
                                    config_options = state.config_options;
                                    modes = state.modes;
                                    emit_runtime_event(events, RuntimeEvent::SessionConfigured { config_options: config_options.clone() }).await?;
                                    emit_runtime_event(events, RuntimeEvent::SessionModesConfigured { modes: modes.clone() }).await?;
                                    let plan = state.plan;
                                    let continuation = format!("The user approved the following plan. Implement it now; the preceding permission cancellation was mj's mode-transition handling.\n\n{plan}");
                                    updates_before = session_update_count.load(Ordering::Acquire);
                                    spec.step_clock.begin_turn();
                                    prompt = Box::pin(connection.send_request(PromptRequest::new(session_id.clone(), vec![ContentBlock::Text(TextContent::new(continuation))])).block_task());
                                    prompt_running = true;
                                }
                                Err(error) => {
                                    emit_runtime_event(events, RuntimeEvent::Warning { message: format!("Plan implementation stopped: could not restore bypassPermissions: {error:#}") }).await?;
                                    emit_runtime_event(events, RuntimeEvent::PromptFinished { request_id, stop_reason: PROMPT_ERROR_STOP_REASON.into() }).await?;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            CommandRequest::SetConfig {
                request_id,
                key,
                value,
            } => {
                let grok_model_change = grok_models.is_some() && grok::handles_config_key(&key);
                let applied = apply_session_selector(
                    connection,
                    &session_id,
                    &mut config_options,
                    &mut grok_models,
                    &key,
                    &value,
                )
                .await;
                match applied {
                    Ok(()) => {
                        spec.accepted_config
                            .lock()
                            .map_err(|_| {
                                anyhow!("accepted session configuration lock was poisoned")
                            })?
                            .remember(&key, &value, &config_options);
                        emit_runtime_event(
                            events,
                            RuntimeEvent::ConfigApplied {
                                request_id,
                                key,
                                value,
                                config_options: config_options.clone(),
                            },
                        )
                        .await?;
                    }
                    Err(error) => {
                        if grok_model_change && grok::response_was_lost(&error) {
                            return Err(error.context(
                                "Grok model change response was lost; reload the session to reconcile its model state",
                            ));
                        }
                        emit_runtime_event(
                            events,
                            RuntimeEvent::CommandRejected {
                                request_id,
                                message: format!("{error:#}"),
                            },
                        )
                        .await?;
                    }
                }
            }
            CommandRequest::SetSessionMode {
                request_id,
                mode_id,
            } => {
                let advertised = modes.as_ref().is_some_and(|state| {
                    state
                        .available_modes
                        .iter()
                        .any(|mode| mode.id.to_string() == mode_id)
                });
                let grok_plan_fallback =
                    grok::permits_unadvertised_plan_mode(spec.harness, &mode_id);
                let applied = if advertised || grok_plan_fallback {
                    connection
                        .send_request(SetSessionModeRequest::new(
                            session_id.clone(),
                            mode_id.clone(),
                        ))
                        .block_task()
                        .await
                        .map(|_| ())
                        .with_context(|| format!("set session mode to {mode_id}"))
                } else {
                    Err(anyhow!("{mode_id:?} is not an available session mode"))
                };
                match applied {
                    Ok(()) => {
                        if let Some(state) = modes.as_mut() {
                            state.current_mode_id = mode_id.clone().into();
                        }
                        emit_runtime_event(
                            events,
                            RuntimeEvent::SessionModeApplied {
                                request_id,
                                mode_id,
                                config_options: config_options.clone(),
                                modes: modes.clone(),
                            },
                        )
                        .await?;
                    }
                    Err(error) => {
                        emit_runtime_event(
                            events,
                            RuntimeEvent::CommandRejected {
                                request_id,
                                message: format!("{error:#}"),
                            },
                        )
                        .await?;
                    }
                }
            }
            CommandRequest::Cancel { request_id, .. } => {
                apply_cancel(connection, &session_id, request_id, events, terminals).await?;
            }
            CommandRequest::ResolveElicitation {
                elicitation_id,
                response,
                resolved,
            } => {
                if resolved
                    .send(resolve_pending_elicitation(
                        pending_elicitations,
                        &elicitation_id,
                        response,
                    ))
                    .is_err()
                {
                    tracing::debug!(
                        session_id = %session_id,
                        operation = "resolve_elicitation",
                        %elicitation_id,
                        "elicitation resolution receiver was already closed"
                    );
                }
            }
            CommandRequest::StopBackgroundTask { target, resolved } => {
                resolve_background_task_stop(connection, &session_id, terminals, target, resolved)
                    .await;
            }
            CommandRequest::Close { request_id } => {
                match connection
                    .send_request(CloseSessionRequest::new(session_id.clone()))
                    .block_task()
                    .await
                {
                    Ok(_) => {
                        emit_runtime_event(events, RuntimeEvent::CloseApplied { request_id })
                            .await?;
                    }
                    Err(error) => {
                        emit_runtime_event(
                            events,
                            RuntimeEvent::CommandRejected {
                                request_id,
                                message: format!("close ACP session: {error}"),
                            },
                        )
                        .await?;
                    }
                }
                break;
            }
        }
    }
    Ok(None)
}

fn resolve_pending_elicitation(
    pending: &PendingElicitations,
    elicitation_id: &str,
    response: ElicitationResponse,
) -> std::result::Result<(), String> {
    let Some(answer) = pending
        .lock()
        .expect("pending elicitation lock poisoned")
        .remove(elicitation_id)
    else {
        return Err(format!(
            "elicitation {elicitation_id:?} is no longer pending"
        ));
    };
    answer
        .send(response)
        .map_err(|_| format!("elicitation {elicitation_id:?} was cancelled before it was answered"))
}

async fn apply_session_selector(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    options: &mut Vec<SessionConfigOption>,
    grok_models: &mut Option<grok::GrokModelState>,
    key: &str,
    value: &str,
) -> Result<()> {
    match grok_models.as_mut() {
        Some(state) if grok::handles_config_key(key) => {
            grok::apply_model_change(connection, session_id, state, key, value)
                .await
                .inspect(|()| grok::merge_config_options(options, state))
        }
        _ => set_session_config(connection, session_id, options, key, value).await,
    }
}

async fn set_session_config(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    options: &mut Vec<SessionConfigOption>,
    key: &str,
    value: &str,
) -> Result<()> {
    let option = find_session_config_option(options, key)
        .with_context(|| format!("ACP bridge does not expose a {key} selector"))?;
    ensure!(
        select_contains(&option.kind, value),
        "{value:?} is not an available {key} value"
    );
    let response = connection
        .send_request(SetSessionConfigOptionRequest::new(
            session_id.clone(),
            option.id.clone(),
            SessionConfigValueId::new(value.to_owned()),
        ))
        .block_task()
        .await
        .with_context(|| format!("set session {key} to {value}"))?;
    *options = response.config_options;
    Ok(())
}

/// One selectable value of a session configuration option, flattened out of
/// the harness's ACP select shape.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionConfigChoice {
    pub value: String,
    pub name: String,
    pub description: Option<String>,
}

/// Every value the harness currently advertises for `key`, in advertised
/// order and with option groups flattened.
///
/// Empty when the harness advertises no such option or exposes it as
/// something other than a select, which callers read as "not configurable".
#[must_use]
/// What one live session's ACP surface offers, for callers outside the chat.
///
/// The phone server and the terminal must agree on which harness drives plan
/// mode through a session mode and which drives it through a configuration
/// key, on whether fast mode is available, and on which values a setting
/// accepts. Those are facts about the harness rather than about the client, so
/// they are answered here once instead of being decided again in each surface.
pub struct AcpSessionFacts(crate::hel_acp::surface::AcpSessionSurface);

impl AcpSessionFacts {
    /// Read the facts out of one relay operational snapshot.
    pub fn from_operational(
        harness_kind: HarnessKind,
        configuration: &std::collections::BTreeMap<String, String>,
        config_options: &[SessionConfigOption],
        modes: Option<&agent_client_protocol::schema::v1::SessionModeState>,
    ) -> Self {
        let values = configuration
            .iter()
            .map(|(key, value)| (key.clone(), serde_json::Value::String(value.clone())))
            .collect();
        let mut surface = crate::hel_acp::surface::AcpSessionSurface::from_configuration(&values);
        surface.set_harness_kind(harness_kind);
        surface.set_config_options(config_options);
        surface.set_session_modes(modes.cloned());
        Self(surface)
    }

    pub fn supports_plan_mode(&self) -> bool {
        self.0.supports_plan_mode()
    }

    pub fn plan_mode_active(&self) -> bool {
        self.0.plan_mode_active()
    }

    pub fn supports_fast_mode(&self) -> bool {
        self.0.supports_fast_mode()
    }

    pub fn fast_mode_active(&self) -> bool {
        self.0.fast_mode_active()
    }

    pub fn current_model(&self) -> Option<&str> {
        self.0.current_model()
    }

    pub fn current_effort(&self) -> Option<&str> {
        self.0.current_effort()
    }

    /// The ACP call that turns plan mode on or off, or a sentence saying why
    /// this harness cannot.
    pub fn plan_control(&self, active: bool) -> Result<PlanControl, &'static str> {
        self.0.plan_control(active).map_err(|error| match error {
            crate::hel_acp::surface::PlanControlError::DeepseekUnsupported => {
                "Plan mode is unsupported in DSH."
            }
            crate::hel_acp::surface::PlanControlError::CodexIncompatible => {
                "This Codex ACP version does not expose collaboration_mode with plan/default values."
            }
            crate::hel_acp::surface::PlanControlError::GrokIncompatible => {
                "This Grok Build version does not expose compatible plan/default modes."
            }
            crate::hel_acp::surface::PlanControlError::Incompatible => {
                "This ACP harness does not expose compatible plan/default modes."
            }
        })
    }
}

pub fn session_config_choices(
    options: &[SessionConfigOption],
    key: &str,
) -> Vec<SessionConfigChoice> {
    let Some(option) = find_session_config_option(options, key) else {
        return Vec::new();
    };
    let SessionConfigKind::Select(select) = &option.kind else {
        return Vec::new();
    };
    let choices = match &select.options {
        SessionConfigSelectOptions::Ungrouped(options) => options.iter().collect::<Vec<_>>(),
        SessionConfigSelectOptions::Grouped(groups) => {
            groups.iter().flat_map(|group| &group.options).collect()
        }
        _ => Vec::new(),
    };
    choices
        .into_iter()
        .map(|choice| SessionConfigChoice {
            value: choice.value.to_string(),
            name: choice.name.clone(),
            description: choice.description.clone(),
        })
        .collect()
}

pub(crate) fn find_session_config_option<'a>(
    options: &'a [SessionConfigOption],
    key: &str,
) -> Option<&'a SessionConfigOption> {
    if let Some(option) = options.iter().find(|option| option.id.to_string() == key) {
        return Some(option);
    }
    match key {
        "model" => options.iter().find(|option| {
            option.category == Some(SessionConfigOptionCategory::Model)
                && !matches!(
                    option.id.to_string().as_str(),
                    "effort" | "reasoning_effort"
                )
        }),
        "effort" => options
            .iter()
            .find(|option| option.category == Some(SessionConfigOptionCategory::ThoughtLevel))
            .or_else(|| {
                options.iter().find(|option| {
                    matches!(
                        option.id.to_string().as_str(),
                        "effort" | "reasoning_effort"
                    )
                })
            }),
        "mode" => options
            .iter()
            .find(|option| option.category == Some(SessionConfigOptionCategory::Mode)),
        _ => None,
    }
}

async fn enforce_execution_mode(
    connection: &ConnectionTo<Agent>,
    session_id: &SessionId,
    desired: &str,
    config_options: &mut Vec<SessionConfigOption>,
    legacy_modes: &mut Option<agent_client_protocol::schema::v1::SessionModeState>,
) -> Result<()> {
    if let Some(option) = config_options.iter().find(|option| {
        option.category == Some(SessionConfigOptionCategory::Mode)
            && select_contains(&option.kind, desired)
    }) {
        let response = connection
            .send_request(SetSessionConfigOptionRequest::new(
                session_id.clone(),
                option.id.clone(),
                SessionConfigValueId::new(desired.to_string()),
            ))
            .block_task()
            .await
            .with_context(|| format!("select required ACP execution mode {desired}"))?;
        *config_options = response.config_options;
        if let Some(modes) = legacy_modes.as_mut() {
            modes.current_mode_id = desired.to_owned().into();
        }
        return Ok(());
    }
    if legacy_modes.as_ref().is_some_and(|modes| {
        modes
            .available_modes
            .iter()
            .any(|mode| mode.id.to_string() == desired)
    }) {
        connection
            .send_request(SetSessionModeRequest::new(
                session_id.clone(),
                desired.to_string(),
            ))
            .block_task()
            .await
            .with_context(|| format!("select required ACP execution mode {desired}"))?;
        if let Some(modes) = legacy_modes.as_mut() {
            modes.current_mode_id = desired.to_owned().into();
        }
        return Ok(());
    }
    bail!("ACP bridge does not expose required execution mode {desired}")
}

pub(crate) fn select_contains(kind: &SessionConfigKind, desired: &str) -> bool {
    let SessionConfigKind::Select(select) = kind else {
        return false;
    };
    match &select.options {
        agent_client_protocol::schema::v1::SessionConfigSelectOptions::Ungrouped(options) => {
            options
                .iter()
                .any(|option| option.value.to_string() == desired)
        }
        agent_client_protocol::schema::v1::SessionConfigSelectOptions::Grouped(groups) => groups
            .iter()
            .flat_map(|group| &group.options)
            .any(|option| option.value.to_string() == desired),
        _ => false,
    }
}

#[cfg(all(test, unix))]
pub(crate) mod muse_tests;
#[cfg(test)]
mod tests;