attini 0.0.1

CLI coding agent that aims to be as autonomous as it can be, without ever leaving your control
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
//! Sans I/O agent core.
//!
//! [`AgentCore`] owns the conversation, the in-flight request, and the
//! transient display state; the surrounding I/O shell feeds it
//! [`Event`]s and executes the returned [`Action`]s. No transport,
//! terminal, filesystem, or subprocess is touched here.
//!
//! At most one model request is active at a time. Any events tagged
//! with a [`RequestId`] that is not the current one are silently
//! dropped, which lets the shell forward late arrivals from a
//! cancelled or completed request without corrupting state.
//!
//! Read-only tool calls are supported through an explicit tool loop
//! (see [`ReadOnlyTool`], `ToolRunning` phase,
//! [`Event::ToolCallDelta`], [`Event::ToolResult`]). File-editing and
//! command-execution tools, automatic retry, and side-effect approvals
//! remain out of scope.

use std::collections::BTreeMap;

use nojson::{Json, RawJsonValue};

use crate::metrics::Counter;
use crate::sansio::deepseek::{ChatMessage, ToolCall, ToolDef};

/// Maximum bytes of tool-call arguments (accumulated across streaming
/// fragments) the core will accept for a single tool call. Fragments
/// past this limit are dropped and the call is resolved to
/// `Err(ArgumentsTooLarge)` instead of being executed.
pub const ARGUMENTS_MAX_BYTES: usize = 64 * 1024;

/// Maximum number of tool calls the core will emit per user turn.
/// A "turn" spans [`Event::UserMessage`] acceptance to a return to
/// [`Status::Idle`], across any number of tool-loop iterations.
pub const TURN_TOOL_CALL_LIMIT: usize = 20;

/// Default upper bound on entries returned by [`ReadOnlyTool::List`].
pub const DEFAULT_LIST_MAX_ENTRIES: usize = 200;

/// Default upper bound on results returned by [`ReadOnlyTool::Search`].
pub const DEFAULT_SEARCH_MAX_RESULTS: usize = 50;

/// Maximum bytes read from a single file by [`ReadOnlyTool::Read`].
pub const READ_MAX_BYTES: usize = 1024 * 1024;

/// Maximum edits allowed in a single [`PatchInvocation`]. The 2-phase
/// applier assumes each edit maps to a unique target path, so the
/// upper bound doubles as an implicit cap on distinct target files
/// per call.
pub const PATCH_MAX_EDITS: usize = 20;

/// Maximum bytes for either the `content` of a [`PatchTool::Add`] or
/// the file targeted by a [`PatchTool::Update`]. Aligned with
/// [`READ_MAX_BYTES`] so the model cannot patch a file it cannot
/// read.
pub const PATCH_MAX_FILE_BYTES: usize = READ_MAX_BYTES;

/// A read-only tool the model can invoke while the agent is running.
///
/// Semantics and per-tool limits are defined in `src/tools.rs`; this
/// enum is only the Sans I/O contract that pairs a serialised
/// invocation (from the model) with an executor-supplied outcome.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReadOnlyTool {
    List {
        path: String,
        recursive: bool,
        max_entries: usize,
        include_hidden: bool,
    },
    Read {
        path: String,
        line_range: Option<(usize, usize)>,
    },
    Search {
        pattern: String,
        path_prefix: Option<String>,
        case_sensitive: bool,
        max_results: usize,
    },
}

impl ReadOnlyTool {
    /// OpenAI-compatible tool schemas advertised to the model as part
    /// of every [`crate::sansio::deepseek::ChatRequest`]. The enum is
    /// the source of truth; these definitions describe the wire shape
    /// the model must produce for a valid [`ToolCall`].
    pub fn definitions() -> Vec<ToolDef> {
        vec![
            ToolDef {
                name: "list".to_string(),
                description: "List files and directories under a workspace-relative path. \
                     Returns a JSON array of {path, kind, size} entries; the \
                     result includes truncated:true when max_entries is hit. \
                     A path outside the workspace requires one-shot human \
                     approval before it can be listed."
                    .to_string(),
                parameters_json: LIST_PARAMS_SCHEMA.to_string(),
            },
            ToolDef {
                name: "read".to_string(),
                description: "Read a UTF-8 text file at a workspace-relative path. \
                     Optionally restrict to a 1-indexed inclusive [start, end] \
                     line range. Content is truncated to the first 1 MiB. \
                     A path outside the workspace requires one-shot human \
                     approval before it can be read."
                    .to_string(),
                parameters_json: READ_PARAMS_SCHEMA.to_string(),
            },
            ToolDef {
                name: "search".to_string(),
                description: "Literal substring search across text files under an \
                     optional workspace-relative prefix. Returns \
                     {path, line, snippet} hits; binary or non-UTF-8 files \
                     are silently skipped. A path_prefix outside the \
                     workspace requires one-shot human approval."
                    .to_string(),
                parameters_json: SEARCH_PARAMS_SCHEMA.to_string(),
            },
        ]
    }

    /// Deserialise a model-supplied `function_name` + `arguments_json`
    /// pair into a concrete invocation.
    pub fn parse(function_name: &str, arguments_json: &str) -> Result<Self, ToolExecutionError> {
        match function_name {
            "list" => parse_list(arguments_json),
            "read" => parse_read(arguments_json),
            "search" => parse_search(arguments_json),
            _ => Err(ToolExecutionError::UnknownTool),
        }
    }
}

const LIST_PARAMS_SCHEMA: &str = r#"{
"type":"object",
"properties":{
"path":{"type":"string","description":"Workspace-relative directory path (e.g. \".\" or \"src\")."},
"recursive":{"type":"boolean","default":false},
"max_entries":{"type":"integer","default":200,"minimum":1},
"include_hidden":{"type":"boolean","default":false}
},
"required":["path"]
}"#;

const READ_PARAMS_SCHEMA: &str = r#"{
"type":"object",
"properties":{
"path":{"type":"string","description":"Workspace-relative file path."},
"line_range":{"type":"array","items":{"type":"integer","minimum":1},"minItems":2,"maxItems":2,"description":"1-indexed inclusive [start, end] range."}
},
"required":["path"]
}"#;

const SEARCH_PARAMS_SCHEMA: &str = r#"{
"type":"object",
"properties":{
"pattern":{"type":"string","description":"Literal substring to match (no regex)."},
"path_prefix":{"type":"string","description":"Restrict to a workspace-relative subtree."},
"case_sensitive":{"type":"boolean","default":false},
"max_results":{"type":"integer","default":50,"minimum":1}
},
"required":["pattern"]
}"#;

fn parse_list(arguments_json: &str) -> Result<ReadOnlyTool, ToolExecutionError> {
    let json = nojson::RawJson::parse(arguments_json).map_err(map_parse_err)?;
    let root = json.value();
    let path = required_string(root, "path")?;
    let recursive = optional_bool(root, "recursive")?.unwrap_or(false);
    let max_entries = optional_usize(root, "max_entries")?.unwrap_or(DEFAULT_LIST_MAX_ENTRIES);
    let include_hidden = optional_bool(root, "include_hidden")?.unwrap_or(false);
    Ok(ReadOnlyTool::List {
        path,
        recursive,
        max_entries,
        include_hidden,
    })
}

fn parse_read(arguments_json: &str) -> Result<ReadOnlyTool, ToolExecutionError> {
    let json = nojson::RawJson::parse(arguments_json).map_err(map_parse_err)?;
    let root = json.value();
    let path = required_string(root, "path")?;
    let line_range = match root
        .to_member("line_range")
        .map_err(map_parse_err)?
        .optional()
    {
        None => None,
        Some(value) => {
            let mut iter = value.to_array().map_err(map_parse_err)?;
            let start = next_usize(&mut iter, "line_range")?;
            let end = next_usize(&mut iter, "line_range")?;
            if iter.next().is_some() {
                return Err(ToolExecutionError::ArgumentsParseFailed(
                    "line_range must have exactly 2 elements".to_string(),
                ));
            }
            Some((start, end))
        }
    };
    Ok(ReadOnlyTool::Read { path, line_range })
}

fn parse_search(arguments_json: &str) -> Result<ReadOnlyTool, ToolExecutionError> {
    let json = nojson::RawJson::parse(arguments_json).map_err(map_parse_err)?;
    let root = json.value();
    let pattern = required_string(root, "pattern")?;
    let path_prefix = optional_string(root, "path_prefix")?;
    let case_sensitive = optional_bool(root, "case_sensitive")?.unwrap_or(false);
    let max_results = optional_usize(root, "max_results")?.unwrap_or(DEFAULT_SEARCH_MAX_RESULTS);
    Ok(ReadOnlyTool::Search {
        pattern,
        path_prefix,
        case_sensitive,
        max_results,
    })
}

fn map_parse_err(err: nojson::JsonParseError) -> ToolExecutionError {
    ToolExecutionError::ArgumentsParseFailed(err.to_string())
}

fn next_usize<'text, 'raw, I>(iter: &mut I, field: &str) -> Result<usize, ToolExecutionError>
where
    I: Iterator<Item = RawJsonValue<'text, 'raw>>,
{
    iter.next()
        .ok_or_else(|| {
            ToolExecutionError::ArgumentsParseFailed(format!(
                "{field} must have exactly 2 elements"
            ))
        })?
        .try_into()
        .map_err(map_parse_err)
}

/// A single edit within a [`PatchInvocation`]. The 2-phase applier
/// requires each edit's target `path` to be unique inside the
/// containing invocation (see [`PatchInvocation::parse`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatchTool {
    /// Create a new file. Rejected if the target path already exists
    /// at apply time.
    Add { path: String, content: String },
    /// Replace the unique byte-for-byte occurrence of `before` inside
    /// the target file with `after`. Rejected if `before` matches
    /// zero times or more than once.
    Update {
        path: String,
        before: String,
        after: String,
    },
}

impl PatchTool {
    pub fn path(&self) -> &str {
        match self {
            Self::Add { path, .. } | Self::Update { path, .. } => path,
        }
    }

    pub fn kind_label(&self) -> &'static str {
        match self {
            Self::Add { .. } => "add",
            Self::Update { .. } => "update",
        }
    }
}

/// A batch of [`PatchTool`] edits produced from a single `patch`
/// tool call. Parsed from the model-supplied JSON `arguments`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PatchInvocation {
    pub edits: Vec<PatchTool>,
}

impl PatchInvocation {
    /// Wire-format definition advertised to the model as one of the
    /// tools available to it in every [`crate::sansio::deepseek::ChatRequest`].
    pub fn definition() -> ToolDef {
        ToolDef {
            name: "patch".to_string(),
            description: "Apply a batch of file edits to the workspace. \
                          Each edit is either an add (create a new file) or \
                          an update (replace a unique substring). All edits \
                          in one call must target distinct paths. Patches \
                          that only update git-tracked files are applied \
                          immediately; any add, non-tracked edit, or target \
                          outside the workspace requires user approval before \
                          it touches the filesystem. A path outside the \
                          workspace is given either as an absolute path or as \
                          a relative path that escapes with `..`."
                .to_string(),
            parameters_json: PATCH_PARAMS_SCHEMA.to_string(),
        }
    }

    /// Parse the JSON `arguments` supplied by the model. Enforces the
    /// per-call limits declared in [`PATCH_MAX_EDITS`] /
    /// [`PATCH_MAX_FILE_BYTES`] and the unique-target-path invariant
    /// that the 2-phase applier depends on.
    pub fn parse(arguments_json: &str) -> Result<Self, ToolExecutionError> {
        let json = nojson::RawJson::parse(arguments_json).map_err(map_parse_err)?;
        let root = json.value();
        let edits_value = root
            .to_member("edits")
            .map_err(map_parse_err)?
            .required()
            .map_err(map_parse_err)?;

        let mut edits: Vec<PatchTool> = Vec::new();
        let mut seen_paths: std::collections::HashSet<String> = std::collections::HashSet::new();
        for item in edits_value.to_array().map_err(map_parse_err)? {
            let kind = required_string(item, "kind")?;
            let path = required_string(item, "path")?;
            if !seen_paths.insert(path.clone()) {
                return Err(ToolExecutionError::Patch(
                    PatchError::MultipleEditsSamePath { path },
                ));
            }
            let tool = match kind.as_str() {
                "add" => {
                    let content = required_string(item, "content")?;
                    if content.len() > PATCH_MAX_FILE_BYTES {
                        return Err(ToolExecutionError::Patch(PatchError::FileTooLarge { path }));
                    }
                    PatchTool::Add { path, content }
                }
                "update" => {
                    let before = required_string(item, "before")?;
                    let after = required_string(item, "after")?;
                    if after.len() > PATCH_MAX_FILE_BYTES {
                        return Err(ToolExecutionError::Patch(PatchError::FileTooLarge { path }));
                    }
                    PatchTool::Update {
                        path,
                        before,
                        after,
                    }
                }
                other => {
                    return Err(ToolExecutionError::ArgumentsParseFailed(format!(
                        "unknown edit kind: {other}"
                    )));
                }
            };
            edits.push(tool);
        }

        if edits.is_empty() {
            return Err(ToolExecutionError::ArgumentsParseFailed(
                "edits must not be empty".to_string(),
            ));
        }
        if edits.len() > PATCH_MAX_EDITS {
            return Err(ToolExecutionError::Patch(PatchError::TooManyEdits {
                count: edits.len() as u64,
            }));
        }
        Ok(Self { edits })
    }
}

const PATCH_PARAMS_SCHEMA: &str = r#"{
"type":"object",
"properties":{
"edits":{"type":"array","minItems":1,"items":{
"type":"object",
"properties":{
"kind":{"type":"string","enum":["add","update"]},
"path":{"type":"string","description":"Workspace-relative target path. Must be unique across edits in one call."},
"content":{"type":"string","description":"Full contents for add."},
"before":{"type":"string","description":"For update: byte-exact substring to replace. Must match exactly once."},
"after":{"type":"string","description":"For update: replacement text."}
},
"required":["kind","path"]
}}
},
"required":["edits"]
}"#;

/// A single command the model wants to run. Parsed from the
/// `command` tool call's arguments and dispatched only after user
/// approval. `argv[0]` is exec'd directly (no shell); pipes /
/// redirects / globs must be handled by each program's native
/// flags or by explicitly invoking `["bash", "-c", "..."]` as
/// argv, which stays approval-gated unless a matching `bash -c`
/// rule pre-approves it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandInvocation {
    /// Command and arguments, exec'd directly without a shell. The
    /// first element names the program (PATH-resolved by
    /// `Command::new`); the rest are argv[1..].
    pub argv: Vec<String>,
}

impl CommandInvocation {
    /// Wire definition advertised to the model alongside
    /// [`ReadOnlyTool::definitions`] and [`PatchInvocation::definition`].
    pub fn definition() -> ToolDef {
        ToolDef {
            name: "command".to_string(),
            description: "Run a command in the workspace by executing argv[0] with argv[1..] \
                 directly (no shell). Every call requires user approval unless a matching \
                 argv_prefix rule pre-approves it. Output is capped at 256 KiB per stream; if \
                 a stream is truncated the result sets `truncated: true`. Non-zero exit status \
                 is returned as a normal result (not an error). Runtime is capped (default 180 \
                 seconds); a command killed on timeout reports `termination_reason: \"timeout\"`."
                .to_string(),
            parameters_json: COMMAND_PARAMS_SCHEMA.to_string(),
        }
    }

    /// Parse the JSON `arguments` supplied by the model.
    pub fn parse(arguments_json: &str) -> Result<Self, ToolExecutionError> {
        let json = nojson::RawJson::parse(arguments_json).map_err(map_parse_err)?;
        let root = json.value();
        let argv = required_string_array(root, "argv")?;
        if argv.is_empty() {
            return Err(ToolExecutionError::Command(CommandError::EmptyArgv));
        }
        Ok(Self { argv })
    }
}

const COMMAND_PARAMS_SCHEMA: &str = r#"{
"type":"object",
"properties":{
"argv":{"type":"array","items":{"type":"string"},"minItems":1,"description":"Command and arguments to exec directly (no shell interpretation). Use each program's own flags for pipe / redirect / glob equivalents (for example --max-count instead of piping to head). For a shell pipe or chain, invoke it explicitly as [\"bash\", \"-c\", \"...\"]; that will still require user approval unless a matching argv_prefix rule pre-approves it."}
},
"required":["argv"]
}"#;

fn required_string(root: RawJsonValue<'_, '_>, name: &str) -> Result<String, ToolExecutionError> {
    let value = root
        .to_member(name)
        .map_err(map_parse_err)?
        .required()
        .map_err(map_parse_err)?;
    value.try_into().map_err(map_parse_err)
}

fn required_string_array(
    root: RawJsonValue<'_, '_>,
    name: &str,
) -> Result<Vec<String>, ToolExecutionError> {
    let value = root
        .to_member(name)
        .map_err(map_parse_err)?
        .required()
        .map_err(map_parse_err)?;
    let array = value.to_array().map_err(map_parse_err)?;
    let mut out = Vec::new();
    for item in array {
        let s: String = item.try_into().map_err(map_parse_err)?;
        out.push(s);
    }
    Ok(out)
}

fn optional_string(
    root: RawJsonValue<'_, '_>,
    name: &str,
) -> Result<Option<String>, ToolExecutionError> {
    match root.to_member(name).map_err(map_parse_err)?.optional() {
        None => Ok(None),
        Some(value) => value.try_into().map_err(map_parse_err),
    }
}

fn optional_bool(
    root: RawJsonValue<'_, '_>,
    name: &str,
) -> Result<Option<bool>, ToolExecutionError> {
    match root.to_member(name).map_err(map_parse_err)?.optional() {
        None => Ok(None),
        Some(value) => Ok(Some(value.try_into().map_err(map_parse_err)?)),
    }
}

fn optional_usize(
    root: RawJsonValue<'_, '_>,
    name: &str,
) -> Result<Option<usize>, ToolExecutionError> {
    match root.to_member(name).map_err(map_parse_err)?.optional() {
        None => Ok(None),
        Some(value) => Ok(Some(value.try_into().map_err(map_parse_err)?)),
    }
}

/// Result of executing a [`ReadOnlyTool`] on behalf of the model.
///
/// Partial-success outcomes (truncated output, silently-skipped
/// binary files) are `Ok` with a JSON payload that includes
/// `truncated: true` or `skipped_binary: N` so the model can see what
/// happened. Only impossible-to-proceed situations become
/// [`Err`](ToolExecutionError).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolOutcome {
    Ok(String),
    Err(ToolExecutionError),
}

/// Reasons a tool invocation could not succeed. Rendered into `Tool`
/// role message content for the model to reason about.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolExecutionError {
    OutsideWorkspace,
    NotUtf8,
    Binary,
    IoError(String),
    ArgumentsParseFailed(String),
    ArgumentsTooLarge,
    UnknownTool,
    TurnToolCallLimitExceeded,
    /// Failure of a [`PatchTool`] invocation. Isolated in its own
    /// enum to keep the read-only error variants intact while
    /// letting patch introduce approval- and filesystem-write-
    /// specific failure modes.
    Patch(PatchError),
    /// Failure of a [`CommandInvocation`] before the child process
    /// produced meaningful output (rejected, spawn failed, arguments
    /// out of range). In-run terminations (cancel, output limit)
    /// are surfaced as `Ok` with a `termination_reason` instead.
    Command(CommandError),
}

/// Failure modes specific to [`PatchTool`] invocations. See the
/// polished `0007` design for the discipline: any failure that
/// prevents the workspace from being updated is surfaced here so
/// the model can decide whether to retry, split the batch, or
/// abandon the edit.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PatchError {
    /// The user actively rejected the preview.
    Rejected,
    /// The target file's SHA-256 changed between preview and apply.
    Conflict { path: String },
    /// `Update.before` matched zero times in the target file.
    NoMatch { path: String },
    /// `Update.before` matched more than once in the target file.
    AmbiguousMatch { path: String, match_count: u64 },
    /// `Add` target already exists at apply time.
    AddOnExistingFile { path: String },
    /// The parent directory of an `Add` target does not exist and is
    /// not auto-created.
    ParentDirMissing { path: String },
    /// `Update` target does not exist at apply time.
    UpdateOnMissingFile { path: String },
    /// Layer 1 hardcoded reject: the target is a runtime-critical file
    /// (`.git/**`, `.attini/*/{LOCK,conversation.jsonl,...}`,
    /// `.attini/permissions.jsonl`) regardless of git
    /// tracking status. `reason` is a short human-readable classifier
    /// (`"git metadata"`, `"session runtime state"`, etc.) embedded in
    /// the message; it is not exposed as a separate JSON field.
    ExcludedPath { path: String, reason: String },
    /// Layer 3 Add reject: the parent directory of the new file is
    /// under a gitignored region, indicating an area the user has
    /// declared out-of-scope for the repo. Unlike an untracked Update
    /// (which the shell surfaces for approval), a gitignored parent is
    /// a hard refusal: the user has explicitly excluded the region.
    IgnoredParent { path: String },
    /// `edits.len()` exceeded [`PATCH_MAX_EDITS`].
    TooManyEdits { count: u64 },
    /// Two edits within the same call named the same target path.
    MultipleEditsSamePath { path: String },
    /// The affected file (either new `content` on add, existing
    /// target on update, or the produced `after` on update) exceeds
    /// [`PATCH_MAX_FILE_BYTES`].
    FileTooLarge { path: String },
    /// Underlying filesystem I/O failed during preview or apply.
    IoError { path: String, message: String },
    /// `rename(2)` returned `EXDEV`. Not handled by fallback in the
    /// prototype scope.
    CrossDeviceRename { path: String },
}

impl PatchError {
    /// Machine-readable code paired with a human-readable message.
    /// The code is stable enough for the model to key on retry logic.
    pub fn to_code_and_message(&self) -> (&'static str, String) {
        match self {
            Self::Rejected => (
                "patch_rejected",
                "user rejected the patch preview".to_string(),
            ),
            Self::Conflict { path } => (
                "patch_conflict",
                format!("target file changed between preview and apply: {path}"),
            ),
            Self::NoMatch { path } => (
                "patch_no_match",
                format!("`before` did not match any content in {path}"),
            ),
            Self::AmbiguousMatch { path, match_count } => (
                "patch_ambiguous_match",
                format!("`before` matched {match_count} places in {path}; expected exactly 1"),
            ),
            Self::AddOnExistingFile { path } => (
                "patch_add_on_existing_file",
                format!("cannot add: file already exists at {path}"),
            ),
            Self::ParentDirMissing { path } => (
                "patch_parent_dir_missing",
                format!("parent directory does not exist for {path}"),
            ),
            Self::UpdateOnMissingFile { path } => (
                "patch_update_on_missing_file",
                format!("cannot update: file does not exist at {path}"),
            ),
            Self::ExcludedPath { path, reason } => (
                "patch_excluded_path",
                format!("path is runtime-critical ({reason}): {path}"),
            ),
            Self::IgnoredParent { path } => (
                "patch_ignored_parent",
                format!("cannot add into git-ignored directory: {path}"),
            ),
            Self::TooManyEdits { count } => (
                "patch_too_many_edits",
                format!("edits count {count} exceeded the {PATCH_MAX_EDITS} limit"),
            ),
            Self::MultipleEditsSamePath { path } => (
                "patch_multiple_edits_same_path",
                format!("more than one edit targets {path} within the same patch call"),
            ),
            Self::FileTooLarge { path } => (
                "patch_file_too_large",
                format!(
                    "target or new content for {path} exceeded the {PATCH_MAX_FILE_BYTES} byte limit"
                ),
            ),
            Self::IoError { path, message } => (
                "patch_io_error",
                format!("filesystem I/O failed for {path}: {message}"),
            ),
            Self::CrossDeviceRename { path } => (
                "patch_cross_device_rename",
                format!("cross-device rename not supported for {path}"),
            ),
        }
    }

    /// Actionable remediation advice for the model, surfaced as the
    /// `hint` member of the tool error JSON (`null` when absent).
    /// Returns `None` for policy/permission rejections where the only
    /// correct move is to choose a different target (or ask the user).
    pub fn to_hint(&self) -> Option<&'static str> {
        match self {
            Self::MultipleEditsSamePath { .. } => Some(
                "each path may appear in only one edit per call; split the edits into \
                 separate patch calls (one per target path) or merge this path's changes \
                 into a single update with one before/after pair",
            ),
            Self::NoMatch { .. } => Some(
                "`before` is not present verbatim in the file; read the file first, then \
                 copy an exact existing substring into `before`",
            ),
            Self::AmbiguousMatch { .. } => Some(
                "`before` matched more than one place; extend `before` with surrounding \
                 lines so it matches exactly once",
            ),
            Self::AddOnExistingFile { .. } => Some(
                "path already exists; use update with a before/after pair instead of add, \
                 or choose a different path",
            ),
            Self::UpdateOnMissingFile { .. } => {
                Some("path does not exist; use add to create it, or fix the path")
            }
            Self::ParentDirMissing { .. } => Some(
                "the parent directory does not exist; create it first (e.g. mkdir -p), \
                 then retry",
            ),
            Self::TooManyEdits { .. } => {
                Some("too many edits in one call; split across multiple patch calls")
            }
            Self::FileTooLarge { .. } => {
                Some("content is too large; reduce it or split across multiple patch calls")
            }
            Self::Conflict { .. } => {
                Some("target changed between preview and apply; re-read the file and retry")
            }
            _ => None,
        }
    }
}

/// Failure modes specific to [`CommandInvocation`]. In-run
/// terminations (cancel, output limit) do not appear here; they
/// surface as `Ok` with a `termination_reason` in the tool result
/// JSON so the model can still see the partial output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CommandError {
    /// User rejected the approval preview.
    Rejected,
    /// `exec` failed (`argv[0]` not on PATH, ENOMEM, EPERM, ...).
    SpawnFailed { message: String },
    /// `argv` was an empty array.
    EmptyArgv,
}

impl CommandError {
    pub fn to_code_and_message(&self) -> (&'static str, String) {
        match self {
            Self::Rejected => (
                "command_rejected",
                "user rejected the command preview".to_string(),
            ),
            Self::SpawnFailed { message } => (
                "command_spawn_failed",
                format!("failed to spawn command: {message}"),
            ),
            Self::EmptyArgv => ("command_empty_argv", "argv must not be empty".to_string()),
        }
    }
}

/// Snapshot of a file's bytes captured at [`PatchTool::Update`]
/// preview time. `content` is `None` for [`PatchTool::Add`] paths
/// (whose apply-time check is "the file must NOT exist" rather than
/// a content match).
///
/// The apply-time check compares these bytes for exact equality, so
/// there is no hash-collision surface; `content` is a plain byte
/// snapshot, not a digest.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreviewContent {
    pub path: String,
    pub content: Option<Vec<u8>>,
}

/// TUI-facing summary of an incoming patch, computed on the shell
/// side from the `PatchInvocation` and delivered to the core with
/// [`Event::PatchPreviewReady`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PatchPreview {
    /// Sorted, deduplicated list of target paths.
    pub target_paths: Vec<String>,
    /// Number of `+` lines across all edits (unified-diff style).
    pub added_lines: u64,
    /// Number of `-` lines across all edits.
    pub removed_lines: u64,
    /// `invocation.edits.len()`.
    pub edit_count: u64,
    /// True when every edit is an `Update` on a file tracked by the
    /// workspace's git repository, so the shell may apply the patch
    /// without an approval prompt (git makes the change revertible).
    pub auto_approve: bool,
    /// When set, at least one target is not safe to auto-apply and the
    /// human should see it first: the path is untracked (so not
    /// revertible with `git checkout`), the workspace is not a git
    /// repository, or the target is outside the workspace. Holds a
    /// short human reason rendered as a `NOTE:` line in the approval
    /// preview. `None` when every target is either git-tracked or
    /// covered by an explicit `write` rule.
    pub not_revertible: Option<String>,
}

/// Approval status of a tool call. Read-only tools always report
/// [`ApprovalState::NotRequired`]; patch and command tool calls flow
/// through `Pending` → (`Approved` or `Rejected`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalState {
    NotRequired,
    Pending,
    Approved,
    Rejected,
}

/// TUI-facing summary of an incoming command call, populated at
/// `on_finish` so the approval prompt has the full command text to
/// display.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommandPreview {
    pub argv: Vec<String>,
    /// Directory the shell will spawn the child in. Copied from
    /// [`AgentCore::set_workspace_display`] so the pure Sans I/O core
    /// does not have to know the filesystem.
    pub working_directory: String,
}

/// Rolling tail of a running command's output plus running byte
/// totals. Updated on every [`Event::CommandOutputChunk`].
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CommandOutputTail {
    pub stdout_tail: String,
    pub stderr_tail: String,
    pub stdout_bytes_total: u64,
    pub stderr_bytes_total: u64,
}

/// Which pipe an [`Event::CommandOutputChunk`] belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandOutputStream {
    Stdout,
    Stderr,
}

/// Maximum characters retained in [`CommandOutputTail::stdout_tail`]
/// / `stderr_tail` for TUI display. New chunks push the tail
/// forward; older content is dropped so the tail stays small.
const COMMAND_TAIL_CHARS: usize = 4 * 1024;

impl ToolExecutionError {
    /// Human-readable message describing the failure, without the
    /// JSON envelope. The same string is embedded as the `message`
    /// field of [`ToolExecutionError::to_json_string`]; the shell also
    /// prints it directly to stderr so a human sees the same wording
    /// the model does.
    pub fn message(&self) -> String {
        let (_code, message) = self.code_and_message();
        message
    }

    /// Compact JSON representation suitable for a `Tool` role message
    /// body: `{"error":"CODE","message":"...","hint":"..."}`. `hint`
    /// is `null` unless there is actionable remediation, and is meant
    /// to guide the model's retry. Fields are stable enough for the
    /// model to key on.
    pub fn to_json_string(&self) -> String {
        let (code, message) = self.code_and_message();
        let hint: Option<&'static str> = match self {
            Self::Patch(err) => err.to_hint(),
            _ => None,
        };
        Json(ToolErrorJson {
            code,
            message: &message,
            hint,
        })
        .to_string()
    }

    /// Shared source of the `(code, message)` pair used by both
    /// [`ToolExecutionError::message`] and
    /// [`ToolExecutionError::to_json_string`].
    fn code_and_message(&self) -> (&'static str, String) {
        match self {
            Self::OutsideWorkspace => (
                "outside_workspace",
                "path escapes the workspace root".to_string(),
            ),
            Self::NotUtf8 => ("not_utf8", "file is not valid UTF-8".to_string()),
            Self::Binary => (
                "binary",
                "file contains binary data and cannot be read as text".to_string(),
            ),
            Self::IoError(msg) => ("io_error", msg.clone()),
            Self::ArgumentsParseFailed(msg) => ("arguments_parse_failed", msg.clone()),
            Self::ArgumentsTooLarge => (
                "arguments_too_large",
                format!(
                    "tool call arguments exceeded the {} byte limit",
                    ARGUMENTS_MAX_BYTES
                ),
            ),
            Self::UnknownTool => (
                "unknown_tool",
                "function_name does not match a known tool".to_string(),
            ),
            Self::TurnToolCallLimitExceeded => (
                "turn_tool_call_limit_exceeded",
                format!(
                    "this user turn exceeded the {} tool call limit",
                    TURN_TOOL_CALL_LIMIT
                ),
            ),
            Self::Patch(err) => err.to_code_and_message(),
            Self::Command(err) => err.to_code_and_message(),
        }
    }
}

struct ToolErrorJson<'a> {
    code: &'a str,
    message: &'a str,
    hint: Option<&'a str>,
}

impl nojson::DisplayJson for ToolErrorJson<'_> {
    fn fmt(&self, f: &mut nojson::JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("error", self.code)?;
            f.member("message", self.message)?;
            f.member("hint", self.hint)?;
            Ok(())
        })
    }
}

/// Opaque identifier for a model request tracked by the core.
///
/// The core assigns IDs internally; the surrounding shell receives
/// them via [`Action::StartRequest`] and tags subsequent events with
/// the same value. Tests and stubs can mint synthetic IDs with
/// [`Self::new`] to exercise stale-event handling.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct RequestId(u64);

impl RequestId {
    pub const fn new(raw: u64) -> Self {
        Self(raw)
    }

    pub const fn as_u64(self) -> u64 {
        self.0
    }
}

/// Coarse-grained runtime status of the core.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Status {
    /// No request is in flight and the shell can accept a new prompt.
    #[default]
    Idle,
    /// A request has been issued but no delta has been received yet.
    AwaitingModel,
    /// The current request has begun streaming content.
    Streaming,
    /// The model finished with `finish_reason == "tool_calls"` and the
    /// shell is executing the requested tools; the core is awaiting
    /// [`Event::ToolResult`] for every outstanding call before
    /// auto-emitting the follow-up [`Action::StartRequest`].
    ToolRunning,
    /// At least one patch call is waiting for user approval. Coexists
    /// with in-flight read-only tool execution — the shell keeps
    /// running those in the background while the UI focus is on the
    /// approval prompt.
    AwaitingApproval,
}

/// Buffered pieces of the assistant response for the in-flight request.
///
/// `content` is the user-visible answer accumulated so far;
/// `finish_reason` becomes `Some` after the final chunk has been
/// observed but before the response is committed to the conversation.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PendingResponse {
    pub content: String,
    pub finish_reason: Option<String>,
}

/// Input event fed to the core by the surrounding I/O shell.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Event {
    /// The user submitted a new prompt. Ignored while a request is
    /// already in flight.
    UserMessage(String),
    /// The user requested to abort the current request.
    Cancel,
    /// A content delta arrived from the transport.
    ContentDelta { request: RequestId, text: String },
    /// A tool-call streaming fragment arrived. The core assembles
    /// fragments across chunks by matching on `index`; the first
    /// non-null `id` / `function_name` win, and `arguments_fragment`
    /// is concatenated in arrival order.
    ToolCallDelta {
        request: RequestId,
        index: u64,
        id: Option<String>,
        function_name: Option<String>,
        arguments_fragment: Option<String>,
    },
    /// The transport observed the terminating `[DONE]` or finish reason.
    Finish {
        request: RequestId,
        reason: Option<String>,
    },
    /// A tool execution completed (successfully or with an error).
    /// Accepted while the core is in either the [`Status::ToolRunning`]
    /// or [`Status::AwaitingApproval`] phase for the matching request.
    ToolResult {
        request: RequestId,
        call_id: String,
        outcome: ToolOutcome,
    },
    /// Shell has computed the target file snapshots and diff summary
    /// for a patch call and is waiting for user approval. Transitions
    /// the core to [`Status::AwaitingApproval`].
    PatchPreviewReady {
        request: RequestId,
        call_id: String,
        preview_content: Vec<PreviewContent>,
        preview: PatchPreview,
    },
    /// User approved the approval-mode preview for `call_id`. The
    /// core dispatches the tool-specific action ([`Action::ApplyPatch`]
    /// for patch, [`Action::ExecuteCommand`] for command).
    ApproveToolCall { call_id: String },
    /// User rejected the approval-mode preview for `call_id`. The
    /// core synthesises an `Err(Rejected)` outcome for the call and
    /// continues the tool loop.
    RejectToolCall { call_id: String },
    /// Shell delivered a chunk of stdout or stderr from a running
    /// command. Only accepted while the corresponding pending tool
    /// result has `ApprovalState::Approved` and `outcome.is_none()`.
    CommandOutputChunk {
        request: RequestId,
        call_id: String,
        stream: CommandOutputStream,
        bytes: Vec<u8>,
    },
    /// The transport reported an unrecoverable error for this request.
    TransportError { request: RequestId, message: String },
    /// The request exceeded its allotted time.
    Timeout { request: RequestId },
}

/// Output action produced by the core for the surrounding I/O shell.
///
/// The shell renders the state after every batch that contains
/// [`Action::Redraw`]; other variants direct the transport or surface
/// a diagnostic to the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Action {
    /// Hand `messages` to the transport and forward returned events
    /// back to the core tagged with `id`.
    StartRequest {
        id: RequestId,
        messages: Vec<ChatMessage>,
    },
    /// Ask the transport to abort the request identified by `id`. The
    /// shell may still receive late events for this ID; they will be
    /// dropped when forwarded back to the core.
    CancelRequest { id: RequestId },
    /// Run `invocation` on behalf of the model in the surrounding
    /// shell (typically on a blocking thread) and deliver the
    /// outcome back as [`Event::ToolResult`] tagged with the same
    /// `request` and `call_id`.
    ExecuteTool {
        request: RequestId,
        call_id: String,
        invocation: ReadOnlyTool,
    },
    /// Compute the target file snapshots and diff summary for
    /// `invocation` and deliver them back as
    /// [`Event::PatchPreviewReady`] so the core can enter approval
    /// mode. The shell must not touch the filesystem yet.
    PreviewPatch {
        request: RequestId,
        call_id: String,
        invocation: PatchInvocation,
    },
    /// User approved the patch preview; apply the 2-phase writeback
    /// using `preview_content` to detect concurrent modifications
    /// between preview and apply. `invocation` is re-parsed from the
    /// tool call arguments so the shell does not need to cache it
    /// between preview and approval.
    ApplyPatch {
        request: RequestId,
        call_id: String,
        invocation: PatchInvocation,
        preview_content: Vec<PreviewContent>,
    },
    /// User approved the command preview; run the shell command,
    /// stream stdout/stderr back via [`Event::CommandOutputChunk`],
    /// and finish with an [`Event::ToolResult`] carrying the JSON
    /// result described in the polished `0008` design.
    ExecuteCommand {
        request: RequestId,
        call_id: String,
        invocation: CommandInvocation,
    },
    /// Abort any tool executions that were dispatched for `request`
    /// but have not yet reported an outcome. Emitted when the user
    /// cancels or the request times out while in
    /// [`Status::ToolRunning`] or [`Status::AwaitingApproval`].
    CancelToolExecution { request: RequestId },
    /// A diagnostic message the shell should surface to the user
    /// (transport failure, timeout, etc.). The core does not retain
    /// it; the shell owns any "sticky until dismissed" behaviour.
    ReportError { message: String },
    /// Something visible to the user changed; the shell should redraw.
    Redraw,
}

/// The Sans I/O agent core.
#[derive(Debug, Clone, Default)]
pub struct AgentCore {
    conversation: Vec<ChatMessage>,
    pending: Option<Pending>,
    status: Status,
    next_id: u64,
    /// Number of [`Action::ExecuteTool`] emitted since the current
    /// user turn began. Reset to 0 on every transition to
    /// [`Status::Idle`], including cancels, errors, and timeouts.
    tool_calls_this_turn: usize,
    /// Human-readable workspace root, copied into
    /// [`CommandPreview::working_directory`] so the approval prompt
    /// can show it. Set by the shell during startup via
    /// [`AgentCore::set_workspace_display`]; empty when unset.
    workspace_display: String,
    metrics: AgentMetrics,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct Pending {
    id: RequestId,
    phase: PendingPhase,
    response: PendingResponse,
    /// Partial tool calls being assembled from streaming fragments.
    /// The `u64` key is the `choices[0].delta.tool_calls[].index`.
    tool_call_slots: BTreeMap<u64, ToolCallSlot>,
    /// Tool results awaited before advancing to the next request.
    /// Populated on transition to `ToolRunning` phase; some
    /// entries may already carry a synthetic `Err` outcome for calls
    /// that hit the arguments-size or turn-tool-count limit.
    tool_results: Vec<PendingToolResult>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum PendingPhase {
    /// Receiving deltas from the model's SSE stream.
    Streaming,
    /// Model finished with `finish_reason == "tool_calls"`; waiting on
    /// the shell to deliver [`Event::ToolResult`] for every call.
    ToolRunning,
    /// At least one patch call is waiting for user approval. Read-only
    /// tool results still land in this phase; `on_tool_result`'s gate
    /// accepts both `ToolRunning` and `AwaitingApproval`.
    AwaitingApproval,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ToolCallSlot {
    id: Option<String>,
    function_name: Option<String>,
    arguments: String,
    /// Set once `arguments.len()` (after appending the current
    /// fragment) would exceed [`ARGUMENTS_MAX_BYTES`]; subsequent
    /// fragments for this index are dropped and the finalised call is
    /// resolved to `Err(ArgumentsTooLarge)` instead of being executed.
    over_limit: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct PendingToolResult {
    call_id: String,
    function_name: String,
    arguments_json: String,
    /// Approval state. Read-only tools are always
    /// [`ApprovalState::NotRequired`]. Patch tools stay in
    /// `NotRequired` until [`Event::PatchPreviewReady`] bumps them to
    /// `Pending`; command tools are `Pending` from `on_finish`.
    approval: ApprovalState,
    /// Populated when [`Event::PatchPreviewReady`] arrives so the TUI
    /// can render the diff summary. `None` for non-patch tools and
    /// for patch tools before the shell has produced a preview.
    patch_preview: Option<PatchPreview>,
    /// Populated together with `patch_preview`. Retained here so
    /// [`Event::ApproveToolCall`] can hand the same snapshots back to
    /// the shell as [`Action::ApplyPatch`] without a round trip.
    preview_content: Vec<PreviewContent>,
    /// Populated at `on_finish` for command tool calls. Drives the
    /// approval-mode label content in the TUI.
    command_preview: Option<CommandPreview>,
    /// Populated on the first [`Event::CommandOutputChunk`] and
    /// updated on every subsequent one until the tool result lands.
    command_output_tail: Option<CommandOutputTail>,
    /// `None` while the shell is still executing the tool; `Some` once
    /// it has reported (or the core has synthesised) an outcome.
    outcome: Option<ToolOutcome>,
}

/// Read-only projection of a single tool call for TUI rendering.
///
/// Built from [`AgentCore::active_tool_calls`]; `is_streaming` is
/// `true` while the model is still emitting fragments and `false`
/// once the assistant turn has been committed and the shell is
/// executing (or has already resolved) the call.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActiveToolCall {
    pub call_id: String,
    pub function_name: String,
    pub arguments_json: String,
    pub outcome: Option<ToolOutcome>,
    pub is_streaming: bool,
    /// Approval status. [`ApprovalState::NotRequired`] for read-only
    /// tools; otherwise reflects the approval flow state.
    pub approval: ApprovalState,
    /// Diff summary from [`Event::PatchPreviewReady`]. `None` for
    /// non-patch tools or patch tools whose preview has not yet
    /// arrived.
    pub patch_preview: Option<PatchPreview>,
    /// File-content snapshots captured at preview time. Empty for
    /// non-patch tools; the TUI does not display them (they exist only
    /// so the core can hand them to [`Action::ApplyPatch`] on
    /// approval).
    pub preview_content: Vec<PreviewContent>,
    /// Approval-mode label content for command tool calls. `None`
    /// for other tool kinds.
    pub command_preview: Option<CommandPreview>,
    /// Rolling output tail while a command is running. `None` before
    /// the first chunk arrives, or for non-command tool kinds.
    pub command_output_tail: Option<CommandOutputTail>,
}

/// Cumulative counters for the branches taken by
/// [`AgentCore::handle_event`].
///
/// Each field increases exactly once per event that lands in the
/// corresponding branch; drop paths (stale event id, event received
/// while idle, etc.) also increment their own counter so the sum of a
/// pair (`*_accepted` + `*_rejected` / `*_appended` + `*_dropped_as_stale`)
/// tells you how many events of a given kind the core has seen.
///
/// Read via [`AgentCore::metrics`]. Fields use the shared
/// [`Counter`] wrapper so `let a = agent.metrics().clone();`
/// captures an independent snapshot for before/after diffs.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct AgentMetrics {
    /// [`Event::UserMessage`] received while idle: the message was
    /// appended to the conversation and an [`Action::StartRequest`]
    /// was emitted.
    pub user_messages_accepted: Counter,
    /// [`Event::UserMessage`] received while another request was
    /// still in flight; the message was dropped.
    pub user_messages_rejected_while_active: Counter,
    /// [`Event::Cancel`] received while a request was in flight; the
    /// pending response was dropped and [`Action::CancelRequest`] was
    /// emitted.
    pub cancels_applied: Counter,
    /// [`Event::Cancel`] received while idle; no state changed.
    pub cancels_ignored_when_idle: Counter,
    /// [`Event::ContentDelta`] whose `request` matched the active
    /// [`RequestId`]; the text was appended to the pending response.
    pub content_deltas_appended: Counter,
    /// [`Event::ContentDelta`] dropped because no request was active
    /// or the `request` id did not match the active one.
    pub content_deltas_dropped_as_stale: Counter,
    /// [`Event::Finish`] whose `request` matched the active
    /// [`RequestId`]; the assistant message was committed to the
    /// conversation.
    pub finishes_committed: Counter,
    /// [`Event::Finish`] dropped because no request was active or the
    /// `request` id did not match the active one.
    pub finishes_dropped_as_stale: Counter,
    /// [`Event::TransportError`] whose `request` matched the active
    /// [`RequestId`]; an [`Action::ReportError`] was emitted.
    pub transport_errors_recorded: Counter,
    /// [`Event::TransportError`] dropped because no request was
    /// active or the `request` id did not match the active one.
    pub transport_errors_dropped_as_stale: Counter,
    /// [`Event::Timeout`] whose `request` matched the active
    /// [`RequestId`]; the request was cancelled and an
    /// [`Action::ReportError`] was emitted.
    pub timeouts_applied: Counter,
    /// [`Event::Timeout`] dropped because no request was active or
    /// the `request` id did not match the active one.
    pub timeouts_dropped_as_stale: Counter,
    /// [`Event::ToolCallDelta`] whose `request` matched the active
    /// [`RequestId`] and phase; the fragment was merged into the
    /// per-index tool-call slot.
    pub tool_call_deltas_appended: Counter,
    /// [`Event::ToolCallDelta`] dropped because no request was
    /// active, the id did not match, or the phase was not
    /// `Streaming` phase.
    pub tool_call_deltas_dropped_as_stale: Counter,
    /// A fragment was dropped because appending it would push the
    /// slot's accumulated `arguments` past [`ARGUMENTS_MAX_BYTES`].
    /// Counts every dropped fragment, not just the first one that
    /// tripped the limit.
    pub tool_call_arguments_fragments_dropped_over_limit: Counter,
    /// [`Event::ToolResult`] whose `request` matched the active
    /// [`RequestId`], phase was `ToolRunning` phase, and
    /// `call_id` matched an outstanding slot; the outcome was
    /// recorded.
    pub tool_results_committed: Counter,
    /// [`Event::ToolResult`] dropped because no request was active,
    /// the id did not match, the phase was not
    /// `ToolRunning` phase, or no outstanding call had the
    /// matching `call_id`.
    pub tool_results_dropped_as_stale: Counter,
    /// [`Action::ExecuteTool`] was emitted for a tool call (parsed
    /// invocation, within both the arguments-size and turn-count
    /// limits).
    pub tool_calls_executed: Counter,
    /// A tool call was resolved to a synthetic
    /// `Err(TurnToolCallLimitExceeded)` because the current user turn
    /// had already emitted [`TURN_TOOL_CALL_LIMIT`] executions.
    pub tool_calls_rejected_by_turn_limit: Counter,
    /// A tool call was resolved to a synthetic
    /// `Err(ArgumentsTooLarge)` because its accumulated arguments
    /// exceeded [`ARGUMENTS_MAX_BYTES`].
    pub tool_calls_rejected_by_arguments_limit: Counter,
    /// [`Action::PreviewPatch`] was emitted for a patch tool call
    /// (parsed successfully, within the shared turn/arguments limits).
    pub patch_calls_previewed: Counter,
    /// [`Event::PatchPreviewReady`] whose `call_id` matched an
    /// outstanding patch call; the diff summary and snapshots were
    /// stored on the pending tool result approval bumped to `Pending`,
    /// and the phase transitioned to `AwaitingApproval`.
    pub patch_previews_committed: Counter,
    /// [`Event::PatchPreviewReady`] dropped because no request was
    /// active, the id did not match, no outstanding patch call had
    /// the matching `call_id`, or the call was already resolved.
    pub patch_previews_dropped_as_stale: Counter,
    /// [`Event::ApproveToolCall`] whose `call_id` matched an
    /// approval-pending call; the tool-specific apply/execute action
    /// was emitted.
    pub tool_call_approvals_committed: Counter,
    /// [`Event::ApproveToolCall`] dropped because no approval-pending
    /// call had the matching `call_id`.
    pub tool_call_approvals_dropped_as_stale: Counter,
    /// [`Event::RejectToolCall`] whose `call_id` matched an
    /// approval-pending call; a synthetic `Err(_::Rejected)` outcome
    /// was recorded for the target tool.
    pub tool_call_rejections_committed: Counter,
    /// [`Event::RejectToolCall`] dropped because no approval-pending
    /// call had the matching `call_id`.
    pub tool_call_rejections_dropped_as_stale: Counter,
    /// A command call was accepted by `on_finish` (parsed and added
    /// to the approval queue with `ApprovalState::Pending`).
    pub command_calls_dispatched: Counter,
    /// [`Action::ExecuteCommand`] was emitted for an approved
    /// command call.
    pub command_executions_started: Counter,
    /// [`Event::CommandOutputChunk`] whose `call_id` matched a
    /// running command; the chunk was folded into the tool result's
    /// output tail.
    pub command_output_chunks_appended: Counter,
    /// [`Event::CommandOutputChunk`] dropped because no request was
    /// active, the id did not match, or no running command call had
    /// the matching `call_id`.
    pub command_output_chunks_dropped_as_stale: Counter,
}

impl AgentCore {
    pub fn new() -> Self {
        Self::default()
    }

    /// Record a human-readable workspace root for display in the
    /// command approval prompt. Empty string means "not set" — the
    /// TUI falls back to omitting the cwd line in that case.
    pub fn set_workspace_display(&mut self, display: String) {
        self.workspace_display = display;
    }

    /// The committed user / assistant message history.
    pub fn conversation(&self) -> &[ChatMessage] {
        &self.conversation
    }

    /// The buffered response for the in-flight request, if any.
    pub fn pending_response(&self) -> Option<&PendingResponse> {
        self.pending.as_ref().map(|p| &p.response)
    }

    /// The ID of the in-flight request, if any.
    pub fn active_request(&self) -> Option<RequestId> {
        self.pending.as_ref().map(|p| p.id)
    }

    /// Call id of the first tool call awaiting user approval, if
    /// any. Returned as an owned `String` because callers typically
    /// need to move the id into an `Event`.
    pub fn pending_approval_call_id(&self) -> Option<String> {
        // Any tool call whose approval is `Pending` is ready to
        // accept the user's decision — patch bumps to `Pending` on
        // `PatchPreviewReady`, command bumps to `Pending` at
        // `on_finish`. No further per-tool gating is needed.
        self.pending
            .as_ref()?
            .tool_results
            .iter()
            .find(|r| r.approval == ApprovalState::Pending)
            .map(|r| r.call_id.clone())
    }

    /// Coarse runtime status suitable for a status line.
    pub fn status(&self) -> Status {
        self.status
    }

    /// Tool calls associated with the in-flight request, ordered by
    /// their streaming index so the TUI can render them stably.
    pub fn active_tool_calls(&self) -> Vec<ActiveToolCall> {
        let Some(pending) = self.pending.as_ref() else {
            return Vec::new();
        };
        match pending.phase {
            PendingPhase::Streaming => pending
                .tool_call_slots
                .iter()
                .map(|(index, slot)| ActiveToolCall {
                    call_id: slot
                        .id
                        .clone()
                        .unwrap_or_else(|| format!("__pending_{index}")),
                    function_name: slot.function_name.clone().unwrap_or_default(),
                    arguments_json: slot.arguments.clone(),
                    outcome: None,
                    is_streaming: true,
                    approval: ApprovalState::NotRequired,
                    patch_preview: None,
                    preview_content: Vec::new(),
                    command_preview: None,
                    command_output_tail: None,
                })
                .collect(),
            PendingPhase::ToolRunning | PendingPhase::AwaitingApproval => pending
                .tool_results
                .iter()
                .map(|r| ActiveToolCall {
                    call_id: r.call_id.clone(),
                    function_name: r.function_name.clone(),
                    arguments_json: r.arguments_json.clone(),
                    outcome: r.outcome.clone(),
                    is_streaming: false,
                    approval: r.approval,
                    patch_preview: r.patch_preview.clone(),
                    preview_content: r.preview_content.clone(),
                    command_preview: r.command_preview.clone(),
                    command_output_tail: r.command_output_tail.clone(),
                })
                .collect(),
        }
    }

    /// Cumulative metrics for the branches taken by
    /// [`Self::handle_event`] over the lifetime of this instance.
    pub fn metrics(&self) -> &AgentMetrics {
        &self.metrics
    }

    /// Apply a single input event and return the resulting actions.
    pub fn handle_event(&mut self, event: Event) -> Vec<Action> {
        match event {
            Event::UserMessage(text) => self.on_user_message(text),
            Event::Cancel => self.on_cancel(),
            Event::ContentDelta { request, text } => self.on_content_delta(request, text),
            Event::ToolCallDelta {
                request,
                index,
                id,
                function_name,
                arguments_fragment,
            } => self.on_tool_call_delta(request, index, id, function_name, arguments_fragment),
            Event::Finish { request, reason } => self.on_finish(request, reason),
            Event::ToolResult {
                request,
                call_id,
                outcome,
            } => self.on_tool_result(request, call_id, outcome),
            Event::PatchPreviewReady {
                request,
                call_id,
                preview_content,
                preview,
            } => self.on_patch_preview_ready(request, call_id, preview_content, preview),
            Event::ApproveToolCall { call_id } => self.on_approve_tool_call(call_id),
            Event::RejectToolCall { call_id } => self.on_reject_tool_call(call_id),
            Event::CommandOutputChunk {
                request,
                call_id,
                stream,
                bytes,
            } => self.on_command_output_chunk(request, call_id, stream, bytes),
            Event::TransportError { request, message } => self.on_transport_error(request, message),
            Event::Timeout { request } => self.on_timeout(request),
        }
    }

    fn on_user_message(&mut self, text: String) -> Vec<Action> {
        if self.pending.is_some() {
            self.metrics.user_messages_rejected_while_active.inc();
            return Vec::new();
        }
        self.conversation.push(ChatMessage::User(text));
        let id = self.mint_id();
        self.pending = Some(Pending {
            id,
            phase: PendingPhase::Streaming,
            response: PendingResponse::default(),
            tool_call_slots: BTreeMap::new(),
            tool_results: Vec::new(),
        });
        self.status = Status::AwaitingModel;
        self.tool_calls_this_turn = 0;
        self.metrics.user_messages_accepted.inc();
        vec![
            Action::StartRequest {
                id,
                messages: self.conversation.clone(),
            },
            Action::Redraw,
        ]
    }

    fn on_cancel(&mut self) -> Vec<Action> {
        let Some(pending) = self.pending.take() else {
            self.metrics.cancels_ignored_when_idle.inc();
            return Vec::new();
        };
        let cancel_action = match pending.phase {
            PendingPhase::Streaming => Action::CancelRequest { id: pending.id },
            PendingPhase::ToolRunning | PendingPhase::AwaitingApproval => {
                Action::CancelToolExecution {
                    request: pending.id,
                }
            }
        };
        self.status = Status::Idle;
        self.tool_calls_this_turn = 0;
        self.metrics.cancels_applied.inc();
        vec![cancel_action, Action::Redraw]
    }

    fn on_content_delta(&mut self, request: RequestId, text: String) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.content_deltas_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending.id != request || pending.phase != PendingPhase::Streaming {
            self.metrics.content_deltas_dropped_as_stale.inc();
            return Vec::new();
        }
        pending.response.content.push_str(&text);
        self.status = Status::Streaming;
        self.metrics.content_deltas_appended.inc();
        vec![Action::Redraw]
    }

    fn on_tool_call_delta(
        &mut self,
        request: RequestId,
        index: u64,
        id: Option<String>,
        function_name: Option<String>,
        arguments_fragment: Option<String>,
    ) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.tool_call_deltas_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending.id != request || pending.phase != PendingPhase::Streaming {
            self.metrics.tool_call_deltas_dropped_as_stale.inc();
            return Vec::new();
        }
        let slot = pending
            .tool_call_slots
            .entry(index)
            .or_insert_with(|| ToolCallSlot {
                id: None,
                function_name: None,
                arguments: String::new(),
                over_limit: false,
            });
        if slot.id.is_none()
            && let Some(new_id) = id
        {
            slot.id = Some(new_id);
        }
        if slot.function_name.is_none()
            && let Some(new_name) = function_name
        {
            slot.function_name = Some(new_name);
        }
        if let Some(fragment) = arguments_fragment {
            if slot.over_limit {
                self.metrics
                    .tool_call_arguments_fragments_dropped_over_limit
                    .inc();
            } else if slot.arguments.len().saturating_add(fragment.len()) > ARGUMENTS_MAX_BYTES {
                slot.over_limit = true;
                self.metrics
                    .tool_call_arguments_fragments_dropped_over_limit
                    .inc();
            } else {
                slot.arguments.push_str(&fragment);
            }
        }
        self.status = Status::Streaming;
        self.metrics.tool_call_deltas_appended.inc();
        vec![Action::Redraw]
    }

    fn on_finish(&mut self, request: RequestId, reason: Option<String>) -> Vec<Action> {
        let Some(pending_ref) = self.pending.as_ref() else {
            self.metrics.finishes_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending_ref.id != request || pending_ref.phase != PendingPhase::Streaming {
            self.metrics.finishes_dropped_as_stale.inc();
            return Vec::new();
        }
        let mut pending = self.pending.take().expect("checked above");
        pending.response.finish_reason = reason.clone();
        let content = std::mem::take(&mut pending.response.content);
        let is_tool_calls_reason = reason.as_deref() == Some("tool_calls");
        let has_slots = !pending.tool_call_slots.is_empty();

        if !is_tool_calls_reason || !has_slots {
            self.conversation.push(ChatMessage::Assistant {
                content,
                tool_calls: Vec::new(),
            });
            self.status = Status::Idle;
            self.tool_calls_this_turn = 0;
            self.metrics.finishes_committed.inc();
            return vec![Action::Redraw];
        }

        // Tool-calls finish: finalise slots, commit assistant with
        // tool_calls, and dispatch (or synthetically reject) each call.
        let request_id = pending.id;
        let (tool_calls, over_limit_ids) =
            finalize_tool_call_slots(std::mem::take(&mut pending.tool_call_slots));

        self.conversation.push(ChatMessage::Assistant {
            content,
            tool_calls: tool_calls.clone(),
        });
        self.metrics.finishes_committed.inc();

        let mut actions = Vec::new();
        let mut pending_results: Vec<PendingToolResult> = Vec::with_capacity(tool_calls.len());
        for call in tool_calls.into_iter() {
            if over_limit_ids.contains(&call.id) {
                pending_results.push(synthetic_err_result(
                    call,
                    ToolExecutionError::ArgumentsTooLarge,
                ));
                self.metrics.tool_calls_rejected_by_arguments_limit.inc();
                continue;
            }
            if self.tool_calls_this_turn >= TURN_TOOL_CALL_LIMIT {
                pending_results.push(synthetic_err_result(
                    call,
                    ToolExecutionError::TurnToolCallLimitExceeded,
                ));
                self.metrics.tool_calls_rejected_by_turn_limit.inc();
                continue;
            }
            if call.function_name == "patch" {
                match PatchInvocation::parse(&call.arguments_json) {
                    Ok(invocation) => {
                        actions.push(Action::PreviewPatch {
                            request: request_id,
                            call_id: call.id.clone(),
                            invocation,
                        });
                        // Approval stays `NotRequired` until the
                        // preview arrives — user cannot see the diff
                        // yet, so exposing this call in the approval
                        // queue would prompt on an empty screen.
                        // `on_patch_preview_ready` bumps to `Pending`.
                        pending_results.push(patch_pending_result(call));
                        self.tool_calls_this_turn += 1;
                        self.metrics.patch_calls_previewed.inc();
                    }
                    Err(err) => {
                        pending_results.push(synthetic_err_result(call, err));
                    }
                }
            } else if call.function_name == "command" {
                match CommandInvocation::parse(&call.arguments_json) {
                    Ok(invocation) => {
                        let preview = CommandPreview {
                            argv: invocation.argv.clone(),
                            working_directory: self.workspace_display.clone(),
                        };
                        // No action emitted from on_finish; the shell
                        // waits for the user to approve. Action::ExecuteCommand
                        // will be produced by on_approve_tool_call.
                        pending_results.push(command_pending_result(call, preview));
                        self.tool_calls_this_turn += 1;
                        self.metrics.command_calls_dispatched.inc();
                    }
                    Err(err) => {
                        pending_results.push(synthetic_err_result(call, err));
                    }
                }
            } else {
                match ReadOnlyTool::parse(&call.function_name, &call.arguments_json) {
                    Ok(invocation) => {
                        actions.push(Action::ExecuteTool {
                            request: request_id,
                            call_id: call.id.clone(),
                            invocation,
                        });
                        pending_results.push(read_only_pending_result(call));
                        self.tool_calls_this_turn += 1;
                        self.metrics.tool_calls_executed.inc();
                    }
                    Err(err) => {
                        pending_results.push(synthetic_err_result(call, err));
                    }
                }
            }
        }

        let all_resolved = pending_results.iter().all(|r| r.outcome.is_some());
        if all_resolved {
            actions.extend(self.advance_to_next_request(pending_results));
            return actions;
        }

        pending.phase = PendingPhase::ToolRunning;
        pending.tool_results = pending_results;
        self.pending = Some(pending);
        self.status = Status::ToolRunning;
        // Command tool calls are already `Pending` approval as they
        // land here; bump the phase / status straight to
        // `AwaitingApproval` if any exists so the TUI does not have
        // to wait for a follow-up event before showing the prompt.
        self.recompute_phase_and_status();
        actions.push(Action::Redraw);
        actions
    }

    fn on_tool_result(
        &mut self,
        request: RequestId,
        call_id: String,
        outcome: ToolOutcome,
    ) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.tool_results_dropped_as_stale.inc();
            return Vec::new();
        };
        // Accept in both ToolRunning and AwaitingApproval phases so
        // read-only results can still land while a patch is waiting
        // for user approval.
        if pending.id != request || matches!(pending.phase, PendingPhase::Streaming) {
            self.metrics.tool_results_dropped_as_stale.inc();
            return Vec::new();
        }
        let Some(entry) = pending
            .tool_results
            .iter_mut()
            .find(|r| r.call_id == call_id && r.outcome.is_none())
        else {
            self.metrics.tool_results_dropped_as_stale.inc();
            return Vec::new();
        };
        entry.outcome = Some(outcome);
        self.metrics.tool_results_committed.inc();
        self.recompute_phase_and_status();

        self.maybe_advance_to_next_request()
    }

    fn on_patch_preview_ready(
        &mut self,
        request: RequestId,
        call_id: String,
        preview_content: Vec<PreviewContent>,
        preview: PatchPreview,
    ) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.patch_previews_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending.id != request || matches!(pending.phase, PendingPhase::Streaming) {
            self.metrics.patch_previews_dropped_as_stale.inc();
            return Vec::new();
        }
        let Some(entry) = pending.tool_results.iter_mut().find(|r| {
            r.call_id == call_id
                && r.approval == ApprovalState::NotRequired
                && r.outcome.is_none()
                && r.patch_preview.is_none()
        }) else {
            self.metrics.patch_previews_dropped_as_stale.inc();
            return Vec::new();
        };
        entry.patch_preview = Some(preview);
        entry.preview_content = preview_content;
        entry.approval = ApprovalState::Pending;
        self.metrics.patch_previews_committed.inc();
        self.recompute_phase_and_status();
        vec![Action::Redraw]
    }

    fn on_approve_tool_call(&mut self, call_id: String) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.tool_call_approvals_dropped_as_stale.inc();
            return Vec::new();
        };
        let request_id = pending.id;
        let Some(entry) = pending
            .tool_results
            .iter_mut()
            .find(|r| r.call_id == call_id && r.approval == ApprovalState::Pending)
        else {
            self.metrics.tool_call_approvals_dropped_as_stale.inc();
            return Vec::new();
        };
        entry.approval = ApprovalState::Approved;
        // Re-parse the arguments captured at on_finish. Parse cannot
        // fail here because on_finish already accepted it, but treat
        // an error as an immediate resolution to keep the loop
        // moving.
        let action = match entry.function_name.as_str() {
            "patch" => {
                let preview_content = entry.preview_content.clone();
                match PatchInvocation::parse(&entry.arguments_json) {
                    Ok(invocation) => Action::ApplyPatch {
                        request: request_id,
                        call_id: call_id.clone(),
                        invocation,
                        preview_content,
                    },
                    Err(err) => {
                        entry.outcome = Some(ToolOutcome::Err(err));
                        self.metrics.tool_call_approvals_committed.inc();
                        self.recompute_phase_and_status();
                        return self.maybe_advance_to_next_request();
                    }
                }
            }
            "command" => match CommandInvocation::parse(&entry.arguments_json) {
                Ok(invocation) => {
                    self.metrics.command_executions_started.inc();
                    Action::ExecuteCommand {
                        request: request_id,
                        call_id: call_id.clone(),
                        invocation,
                    }
                }
                Err(err) => {
                    entry.outcome = Some(ToolOutcome::Err(err));
                    self.metrics.tool_call_approvals_committed.inc();
                    self.recompute_phase_and_status();
                    return self.maybe_advance_to_next_request();
                }
            },
            other => {
                // Approval fired for a tool that never enters the
                // approval flow. Fail loudly through a synthetic Err.
                entry.outcome = Some(ToolOutcome::Err(ToolExecutionError::ArgumentsParseFailed(
                    format!("no approval flow for tool {other}"),
                )));
                self.metrics.tool_call_approvals_committed.inc();
                self.recompute_phase_and_status();
                return self.maybe_advance_to_next_request();
            }
        };
        self.metrics.tool_call_approvals_committed.inc();
        self.recompute_phase_and_status();
        vec![action, Action::Redraw]
    }

    fn on_reject_tool_call(&mut self, call_id: String) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.tool_call_rejections_dropped_as_stale.inc();
            return Vec::new();
        };
        let Some(entry) = pending
            .tool_results
            .iter_mut()
            .find(|r| r.call_id == call_id && r.approval == ApprovalState::Pending)
        else {
            self.metrics.tool_call_rejections_dropped_as_stale.inc();
            return Vec::new();
        };
        entry.approval = ApprovalState::Rejected;
        entry.outcome = Some(match entry.function_name.as_str() {
            "command" => ToolOutcome::Err(ToolExecutionError::Command(CommandError::Rejected)),
            // Patch is the only other tool that reaches this path; any
            // future approval-gated tool falls through to Patch::Rejected
            // by default, which is close enough for the model to see it
            // as "user did not approve".
            _ => ToolOutcome::Err(ToolExecutionError::Patch(PatchError::Rejected)),
        });
        self.metrics.tool_call_rejections_committed.inc();
        self.recompute_phase_and_status();
        self.maybe_advance_to_next_request()
    }

    fn on_command_output_chunk(
        &mut self,
        request: RequestId,
        call_id: String,
        stream: CommandOutputStream,
        bytes: Vec<u8>,
    ) -> Vec<Action> {
        let Some(pending) = self.pending.as_mut() else {
            self.metrics.command_output_chunks_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending.id != request || matches!(pending.phase, PendingPhase::Streaming) {
            self.metrics.command_output_chunks_dropped_as_stale.inc();
            return Vec::new();
        }
        let Some(entry) = pending.tool_results.iter_mut().find(|r| {
            r.call_id == call_id
                && r.approval == ApprovalState::Approved
                && r.outcome.is_none()
                && r.function_name == "command"
        }) else {
            self.metrics.command_output_chunks_dropped_as_stale.inc();
            return Vec::new();
        };
        let text = String::from_utf8_lossy(&bytes);
        let byte_len = bytes.len() as u64;
        let tail = entry
            .command_output_tail
            .get_or_insert_with(CommandOutputTail::default);
        match stream {
            CommandOutputStream::Stdout => {
                append_bounded(&mut tail.stdout_tail, &text, COMMAND_TAIL_CHARS);
                tail.stdout_bytes_total = tail.stdout_bytes_total.saturating_add(byte_len);
            }
            CommandOutputStream::Stderr => {
                append_bounded(&mut tail.stderr_tail, &text, COMMAND_TAIL_CHARS);
                tail.stderr_bytes_total = tail.stderr_bytes_total.saturating_add(byte_len);
            }
        }
        self.metrics.command_output_chunks_appended.inc();
        vec![Action::Redraw]
    }

    /// After any state change to `tool_results`, adjust `pending.phase`
    /// and `self.status` to match: any Pending patch keeps us in
    /// `AwaitingApproval`, otherwise back to `ToolRunning`.
    fn recompute_phase_and_status(&mut self) {
        let Some(pending) = self.pending.as_mut() else {
            return;
        };
        // A patch is only "still waiting for approval" while its
        // outcome has not been committed. If the shell fails preview
        // and short-circuits to Err via ToolResult, the call is done
        // regardless of the `approval` field.
        let has_pending_approval = pending
            .tool_results
            .iter()
            .any(|r| r.approval == ApprovalState::Pending && r.outcome.is_none());
        match (pending.phase, has_pending_approval) {
            (PendingPhase::Streaming, _) => {}
            (_, true) => {
                pending.phase = PendingPhase::AwaitingApproval;
                self.status = Status::AwaitingApproval;
            }
            (_, false) => {
                pending.phase = PendingPhase::ToolRunning;
                self.status = Status::ToolRunning;
            }
        }
    }

    /// If every tool result is resolved, commit them and start the
    /// follow-up request; otherwise emit a redraw so the TUI reflects
    /// the state change.
    fn maybe_advance_to_next_request(&mut self) -> Vec<Action> {
        let Some(pending) = self.pending.as_ref() else {
            return Vec::new();
        };
        if pending.tool_results.iter().all(|r| r.outcome.is_some()) {
            let pending = self.pending.take().expect("checked above");
            self.advance_to_next_request(pending.tool_results)
        } else {
            vec![Action::Redraw]
        }
    }

    fn on_transport_error(&mut self, request: RequestId, message: String) -> Vec<Action> {
        let Some(pending_ref) = self.pending.as_ref() else {
            self.metrics.transport_errors_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending_ref.id != request || pending_ref.phase != PendingPhase::Streaming {
            self.metrics.transport_errors_dropped_as_stale.inc();
            return Vec::new();
        }
        self.pending = None;
        self.status = Status::Idle;
        self.tool_calls_this_turn = 0;
        self.metrics.transport_errors_recorded.inc();
        vec![Action::ReportError { message }, Action::Redraw]
    }

    fn on_timeout(&mut self, request: RequestId) -> Vec<Action> {
        let Some(pending_ref) = self.pending.as_ref() else {
            self.metrics.timeouts_dropped_as_stale.inc();
            return Vec::new();
        };
        if pending_ref.id != request || pending_ref.phase != PendingPhase::Streaming {
            self.metrics.timeouts_dropped_as_stale.inc();
            return Vec::new();
        }
        let id = pending_ref.id;
        self.pending = None;
        self.status = Status::Idle;
        self.tool_calls_this_turn = 0;
        self.metrics.timeouts_applied.inc();
        vec![
            Action::CancelRequest { id },
            Action::ReportError {
                message: "request timed out".to_string(),
            },
            Action::Redraw,
        ]
    }

    fn mint_id(&mut self) -> RequestId {
        let id = RequestId(self.next_id);
        self.next_id = self.next_id.wrapping_add(1);
        id
    }

    /// All tool results in the just-finished turn's tool loop are in;
    /// commit them as `Tool` role messages and issue a fresh
    /// [`Action::StartRequest`] under a new [`RequestId`] so the model
    /// can consume them.
    fn advance_to_next_request(&mut self, results: Vec<PendingToolResult>) -> Vec<Action> {
        for result in results {
            let outcome = result
                .outcome
                .expect("advance_to_next_request called with unresolved tool result");
            let content = match outcome {
                ToolOutcome::Ok(s) => s,
                ToolOutcome::Err(err) => err.to_json_string(),
            };
            self.conversation.push(ChatMessage::Tool {
                tool_call_id: result.call_id,
                content,
            });
        }
        let id = self.mint_id();
        self.pending = Some(Pending {
            id,
            phase: PendingPhase::Streaming,
            response: PendingResponse::default(),
            tool_call_slots: BTreeMap::new(),
            tool_results: Vec::new(),
        });
        self.status = Status::AwaitingModel;
        vec![
            Action::StartRequest {
                id,
                messages: self.conversation.clone(),
            },
            Action::Redraw,
        ]
    }
}

fn synthetic_err_result(call: ToolCall, err: ToolExecutionError) -> PendingToolResult {
    PendingToolResult {
        call_id: call.id,
        function_name: call.function_name,
        arguments_json: call.arguments_json,
        approval: ApprovalState::NotRequired,
        patch_preview: None,
        preview_content: Vec::new(),
        command_preview: None,
        command_output_tail: None,
        outcome: Some(ToolOutcome::Err(err)),
    }
}

fn read_only_pending_result(call: ToolCall) -> PendingToolResult {
    PendingToolResult {
        call_id: call.id,
        function_name: call.function_name,
        arguments_json: call.arguments_json,
        approval: ApprovalState::NotRequired,
        patch_preview: None,
        preview_content: Vec::new(),
        command_preview: None,
        command_output_tail: None,
        outcome: None,
    }
}

fn patch_pending_result(call: ToolCall) -> PendingToolResult {
    PendingToolResult {
        call_id: call.id,
        function_name: call.function_name,
        arguments_json: call.arguments_json,
        approval: ApprovalState::NotRequired,
        patch_preview: None,
        preview_content: Vec::new(),
        command_preview: None,
        command_output_tail: None,
        outcome: None,
    }
}

/// Append `text` to `tail` while keeping `tail.chars().count()` at
/// most `max_chars`. Older content is dropped from the front so the
/// most recent output stays visible.
fn append_bounded(tail: &mut String, text: &str, max_chars: usize) {
    tail.push_str(text);
    let count = tail.chars().count();
    if count > max_chars {
        let drop = count - max_chars;
        let split = tail
            .char_indices()
            .nth(drop)
            .map(|(idx, _)| idx)
            .unwrap_or(0);
        tail.drain(..split);
    }
}

fn command_pending_result(call: ToolCall, preview: CommandPreview) -> PendingToolResult {
    PendingToolResult {
        call_id: call.id,
        function_name: call.function_name,
        arguments_json: call.arguments_json,
        approval: ApprovalState::Pending,
        patch_preview: None,
        preview_content: Vec::new(),
        command_preview: Some(preview),
        command_output_tail: None,
        outcome: None,
    }
}

/// Convert per-index streaming slots into the ordered [`ToolCall`] list
/// committed to the assistant turn. Returns the calls plus the set of
/// `id`s that were flagged `over_limit` during streaming and should be
/// resolved to `Err(ArgumentsTooLarge)` instead of being executed.
fn finalize_tool_call_slots(
    slots: BTreeMap<u64, ToolCallSlot>,
) -> (Vec<ToolCall>, std::collections::HashSet<String>) {
    let mut calls = Vec::with_capacity(slots.len());
    let mut over_limit = std::collections::HashSet::new();
    for (index, slot) in slots.into_iter() {
        let id = slot.id.unwrap_or_else(|| format!("__missing_id__{index}"));
        let function_name = slot.function_name.unwrap_or_default();
        if slot.over_limit {
            over_limit.insert(id.clone());
        }
        calls.push(ToolCall {
            id,
            function_name,
            arguments_json: slot.arguments,
        });
    }
    (calls, over_limit)
}

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

    fn user(core: &mut AgentCore, text: &str) -> Vec<Action> {
        core.handle_event(Event::UserMessage(text.to_string()))
    }

    fn last_start_id(actions: &[Action]) -> RequestId {
        for action in actions {
            if let Action::StartRequest { id, .. } = action {
                return *id;
            }
        }
        panic!("no StartRequest in {actions:?}");
    }

    #[test]
    fn user_message_from_idle_starts_request_and_appends_user_turn() {
        let mut core = AgentCore::new();
        let actions = user(&mut core, "hello");
        assert_eq!(core.status(), Status::AwaitingModel);
        assert_eq!(core.conversation().len(), 1);
        assert!(matches!(core.conversation()[0], ChatMessage::User(_)));
        assert!(matches!(actions[0], Action::StartRequest { .. }));
        assert!(actions.contains(&Action::Redraw));
        assert!(core.active_request().is_some());
    }

    #[test]
    fn user_message_while_active_is_ignored() {
        let mut core = AgentCore::new();
        let _ = user(&mut core, "first");
        let actions = user(&mut core, "second");
        assert!(actions.is_empty());
        assert_eq!(core.conversation().len(), 1);
    }

    #[test]
    fn content_delta_accumulates_and_flips_status_to_streaming() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = core.handle_event(Event::ContentDelta {
            request: id,
            text: "he".to_string(),
        });
        assert_eq!(actions, vec![Action::Redraw]);
        assert_eq!(core.status(), Status::Streaming);
        let _ = core.handle_event(Event::ContentDelta {
            request: id,
            text: "llo".to_string(),
        });
        let pending = core.pending_response().expect("pending");
        assert_eq!(pending.content, "hello");
    }

    #[test]
    fn finish_commits_assistant_turn_and_returns_to_idle() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::ContentDelta {
            request: id,
            text: "hello".to_string(),
        });
        let actions = core.handle_event(Event::Finish {
            request: id,
            reason: Some("stop".to_string()),
        });
        assert_eq!(actions, vec![Action::Redraw]);
        assert_eq!(core.status(), Status::Idle);
        assert!(core.active_request().is_none());
        assert!(core.pending_response().is_none());
        assert_eq!(core.conversation().len(), 2);
        match &core.conversation()[1] {
            ChatMessage::Assistant { content, .. } => assert_eq!(content, "hello"),
            other => panic!("expected assistant, got {other:?}"),
        }
    }

    #[test]
    fn cancel_drops_pending_response_and_asks_transport_to_cancel() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::ContentDelta {
            request: id,
            text: "partial".to_string(),
        });
        let actions = core.handle_event(Event::Cancel);
        assert!(actions.contains(&Action::CancelRequest { id }));
        assert!(actions.contains(&Action::Redraw));
        assert_eq!(core.status(), Status::Idle);
        assert!(core.pending_response().is_none());
        assert_eq!(core.conversation().len(), 1);
    }

    #[test]
    fn cancel_from_idle_is_no_op() {
        let mut core = AgentCore::new();
        assert!(core.handle_event(Event::Cancel).is_empty());
    }

    #[test]
    fn transport_error_ends_request_and_reports_message() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = core.handle_event(Event::TransportError {
            request: id,
            message: "boom".to_string(),
        });
        assert!(actions.contains(&Action::ReportError {
            message: "boom".to_string(),
        }));
        assert!(actions.contains(&Action::Redraw));
        assert_eq!(core.status(), Status::Idle);
        assert!(core.pending_response().is_none());
        assert_eq!(core.conversation().len(), 1);
    }

    #[test]
    fn timeout_cancels_transport_and_reports_error() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = core.handle_event(Event::Timeout { request: id });
        assert!(actions.contains(&Action::CancelRequest { id }));
        assert!(
            actions
                .iter()
                .any(|a| matches!(a, Action::ReportError { .. })),
            "expected ReportError, got {actions:?}",
        );
        assert!(actions.contains(&Action::Redraw));
        assert!(core.pending_response().is_none());
    }

    #[test]
    fn stale_deltas_are_dropped_without_state_change() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::Finish {
            request: id,
            reason: Some("stop".to_string()),
        });
        // Late delta from the finished request.
        let actions = core.handle_event(Event::ContentDelta {
            request: id,
            text: "late".to_string(),
        });
        assert!(actions.is_empty());
        assert_eq!(core.conversation().len(), 2);
    }

    #[test]
    fn events_tagged_with_unknown_id_are_dropped() {
        let mut core = AgentCore::new();
        let _ = user(&mut core, "hi");
        let actions = core.handle_event(Event::ContentDelta {
            request: RequestId::new(u64::MAX),
            text: "x".to_string(),
        });
        assert!(actions.is_empty());
        assert!(core.pending_response().expect("pending").content.is_empty());
    }

    #[test]
    fn each_start_request_gets_a_unique_id() {
        let mut core = AgentCore::new();
        let id1 = last_start_id(&user(&mut core, "first"));
        let _ = core.handle_event(Event::Finish {
            request: id1,
            reason: None,
        });
        let id2 = last_start_id(&user(&mut core, "second"));
        assert_ne!(id1, id2);
    }

    #[test]
    fn late_finish_after_cancel_is_ignored() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::Cancel);
        let actions = core.handle_event(Event::Finish {
            request: id,
            reason: Some("stop".to_string()),
        });
        assert!(actions.is_empty());
        assert_eq!(core.conversation().len(), 1);
    }

    #[test]
    fn start_request_carries_full_conversation_snapshot() {
        let mut core = AgentCore::new();
        let id1 = last_start_id(&user(&mut core, "first"));
        let _ = core.handle_event(Event::ContentDelta {
            request: id1,
            text: "one".to_string(),
        });
        let _ = core.handle_event(Event::Finish {
            request: id1,
            reason: None,
        });
        let actions = user(&mut core, "second");
        let messages = actions.iter().find_map(|a| match a {
            Action::StartRequest { messages, .. } => Some(messages.clone()),
            _ => None,
        });
        let messages = messages.expect("StartRequest present");
        assert_eq!(messages.len(), 3);
        assert!(matches!(messages[0], ChatMessage::User(_)));
        assert!(matches!(messages[1], ChatMessage::Assistant { .. }));
        match &messages[2] {
            ChatMessage::User(content) => assert_eq!(content, "second"),
            other => panic!("expected user, got {other:?}"),
        }
    }

    // -------------------------------------------------------------
    // metrics
    // -------------------------------------------------------------

    #[test]
    fn metrics_start_at_zero() {
        let core = AgentCore::new();
        assert_eq!(*core.metrics(), AgentMetrics::default());
    }

    #[test]
    fn user_message_accepted_and_rejected_counters() {
        let mut core = AgentCore::new();
        let _ = user(&mut core, "first");
        assert_eq!(core.metrics().user_messages_accepted.get(), 1);
        assert_eq!(core.metrics().user_messages_rejected_while_active.get(), 0);
        // Second user message while first is still active is rejected.
        let _ = user(&mut core, "second");
        assert_eq!(core.metrics().user_messages_accepted.get(), 1);
        assert_eq!(core.metrics().user_messages_rejected_while_active.get(), 1);
    }

    #[test]
    fn cancel_applied_and_ignored_counters() {
        let mut core = AgentCore::new();
        let _ = core.handle_event(Event::Cancel);
        assert_eq!(core.metrics().cancels_applied.get(), 0);
        assert_eq!(core.metrics().cancels_ignored_when_idle.get(), 1);
        let _ = user(&mut core, "hi");
        let _ = core.handle_event(Event::Cancel);
        assert_eq!(core.metrics().cancels_applied.get(), 1);
        assert_eq!(core.metrics().cancels_ignored_when_idle.get(), 1);
    }

    #[test]
    fn content_delta_appended_and_dropped_counters() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::ContentDelta {
            request: id,
            text: "a".to_string(),
        });
        let _ = core.handle_event(Event::ContentDelta {
            request: RequestId::new(u64::MAX),
            text: "b".to_string(),
        });
        assert_eq!(core.metrics().content_deltas_appended.get(), 1);
        assert_eq!(core.metrics().content_deltas_dropped_as_stale.get(), 1);
    }

    #[test]
    fn finish_committed_and_dropped_counters() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::Finish {
            request: id,
            reason: None,
        });
        // Second finish for the (now completed) request is stale.
        let _ = core.handle_event(Event::Finish {
            request: id,
            reason: None,
        });
        assert_eq!(core.metrics().finishes_committed.get(), 1);
        assert_eq!(core.metrics().finishes_dropped_as_stale.get(), 1);
    }

    #[test]
    fn transport_error_recorded_and_dropped_counters() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::TransportError {
            request: id,
            message: "boom".to_string(),
        });
        // No pending: dropped
        let _ = core.handle_event(Event::TransportError {
            request: id,
            message: "late".to_string(),
        });
        assert_eq!(core.metrics().transport_errors_recorded.get(), 1);
        assert_eq!(core.metrics().transport_errors_dropped_as_stale.get(), 1);
    }

    #[test]
    fn timeout_applied_and_dropped_counters() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(Event::Timeout { request: id });
        // No pending: dropped
        let _ = core.handle_event(Event::Timeout { request: id });
        assert_eq!(core.metrics().timeouts_applied.get(), 1);
        assert_eq!(core.metrics().timeouts_dropped_as_stale.get(), 1);
    }

    #[test]
    fn other_counters_do_not_move_on_a_single_event() {
        let mut core = AgentCore::new();
        let _ = user(&mut core, "hi");
        let m = core.metrics();
        assert_eq!(m.user_messages_accepted.get(), 1);
        // Every other counter is zero.
        assert_eq!(m.user_messages_rejected_while_active.get(), 0);
        assert_eq!(m.cancels_applied.get(), 0);
        assert_eq!(m.cancels_ignored_when_idle.get(), 0);
        assert_eq!(m.content_deltas_appended.get(), 0);
        assert_eq!(m.content_deltas_dropped_as_stale.get(), 0);
        assert_eq!(m.finishes_committed.get(), 0);
        assert_eq!(m.finishes_dropped_as_stale.get(), 0);
        assert_eq!(m.transport_errors_recorded.get(), 0);
        assert_eq!(m.transport_errors_dropped_as_stale.get(), 0);
        assert_eq!(m.timeouts_applied.get(), 0);
        assert_eq!(m.timeouts_dropped_as_stale.get(), 0);
        assert_eq!(m.tool_call_deltas_appended.get(), 0);
        assert_eq!(m.tool_call_deltas_dropped_as_stale.get(), 0);
        assert_eq!(m.tool_call_arguments_fragments_dropped_over_limit.get(), 0);
        assert_eq!(m.tool_results_committed.get(), 0);
        assert_eq!(m.tool_results_dropped_as_stale.get(), 0);
        assert_eq!(m.tool_calls_executed.get(), 0);
        assert_eq!(m.tool_calls_rejected_by_turn_limit.get(), 0);
        assert_eq!(m.tool_calls_rejected_by_arguments_limit.get(), 0);
        assert_eq!(m.patch_calls_previewed.get(), 0);
        assert_eq!(m.patch_previews_committed.get(), 0);
        assert_eq!(m.patch_previews_dropped_as_stale.get(), 0);
        assert_eq!(m.tool_call_approvals_committed.get(), 0);
        assert_eq!(m.tool_call_approvals_dropped_as_stale.get(), 0);
        assert_eq!(m.tool_call_rejections_committed.get(), 0);
        assert_eq!(m.tool_call_rejections_dropped_as_stale.get(), 0);
        assert_eq!(m.command_calls_dispatched.get(), 0);
        assert_eq!(m.command_executions_started.get(), 0);
        assert_eq!(m.command_output_chunks_appended.get(), 0);
        assert_eq!(m.command_output_chunks_dropped_as_stale.get(), 0);
    }

    // -------------------------------------------------------------
    // tool loop
    // -------------------------------------------------------------

    fn tool_call_delta(
        request: RequestId,
        index: u64,
        id: Option<&str>,
        function_name: Option<&str>,
        arguments_fragment: Option<&str>,
    ) -> Event {
        Event::ToolCallDelta {
            request,
            index,
            id: id.map(str::to_string),
            function_name: function_name.map(str::to_string),
            arguments_fragment: arguments_fragment.map(str::to_string),
        }
    }

    fn drive_single_tool_call(
        core: &mut AgentCore,
        request: RequestId,
        call_id: &str,
        function_name: &str,
        arguments_json: &str,
    ) -> Vec<Action> {
        let _ = core.handle_event(tool_call_delta(
            request,
            0,
            Some(call_id),
            Some(function_name),
            Some(arguments_json),
        ));
        core.handle_event(Event::Finish {
            request,
            reason: Some("tool_calls".to_string()),
        })
    }

    #[test]
    fn tool_call_delta_merges_fragments_and_emits_execute_tool_on_finish() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(tool_call_delta(
            id,
            0,
            Some("call_1"),
            Some("read"),
            Some(r#"{"path":""#),
        ));
        let _ = core.handle_event(tool_call_delta(id, 0, None, None, Some(r#"src/main.rs"}"#)));
        assert_eq!(core.metrics().tool_call_deltas_appended.get(), 2);
        let actions = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        assert_eq!(core.status(), Status::ToolRunning);
        assert_eq!(core.metrics().tool_calls_executed.get(), 1);
        assert!(actions.iter().any(|a| matches!(
            a,
            Action::ExecuteTool {
                call_id, invocation: ReadOnlyTool::Read { path, .. }, ..
            } if call_id == "call_1" && path == "src/main.rs"
        )));
        // Assistant turn was committed with the tool_calls attached.
        match &core.conversation()[1] {
            ChatMessage::Assistant { tool_calls, .. } => {
                assert_eq!(tool_calls.len(), 1);
                assert_eq!(tool_calls[0].function_name, "read");
            }
            other => panic!("expected assistant with tool_calls, got {other:?}"),
        }
    }

    #[test]
    fn multiple_parallel_tool_calls_are_ordered_by_index() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        // Arrive out of order.
        let _ = core.handle_event(tool_call_delta(
            id,
            1,
            Some("b"),
            Some("list"),
            Some(r#"{"path":"src"}"#),
        ));
        let _ = core.handle_event(tool_call_delta(
            id,
            0,
            Some("a"),
            Some("read"),
            Some(r#"{"path":"README.md"}"#),
        ));
        let actions = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        let execute_ids: Vec<String> = actions
            .iter()
            .filter_map(|a| match a {
                Action::ExecuteTool { call_id, .. } => Some(call_id.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(execute_ids, vec!["a".to_string(), "b".to_string()]);
    }

    #[test]
    fn tool_result_completes_slot_and_advances_to_next_request() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_tool_call(&mut core, id, "call_1", "list", r#"{"path":"."}"#);
        assert_eq!(core.status(), Status::ToolRunning);
        let actions = core.handle_event(Event::ToolResult {
            request: id,
            call_id: "call_1".to_string(),
            outcome: ToolOutcome::Ok(r#"[{"path":"a"}]"#.to_string()),
        });
        assert_eq!(core.metrics().tool_results_committed.get(), 1);
        // New request started with a fresh id, conversation now has
        // user + assistant(tool_calls) + tool + <no assistant yet>.
        let start = actions
            .iter()
            .find_map(|a| match a {
                Action::StartRequest { id, messages } => Some((*id, messages.clone())),
                _ => None,
            })
            .expect("StartRequest emitted");
        assert_ne!(start.0, id);
        assert_eq!(start.1.len(), 3);
        assert!(matches!(start.1[2], ChatMessage::Tool { .. }));
        assert_eq!(core.status(), Status::AwaitingModel);
    }

    #[test]
    fn tool_result_before_all_arrive_stays_in_tool_running() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(tool_call_delta(
            id,
            0,
            Some("a"),
            Some("read"),
            Some(r#"{"path":"a"}"#),
        ));
        let _ = core.handle_event(tool_call_delta(
            id,
            1,
            Some("b"),
            Some("read"),
            Some(r#"{"path":"b"}"#),
        ));
        let _ = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        let actions = core.handle_event(Event::ToolResult {
            request: id,
            call_id: "a".to_string(),
            outcome: ToolOutcome::Ok("ok".to_string()),
        });
        assert_eq!(core.status(), Status::ToolRunning);
        assert_eq!(actions, vec![Action::Redraw]);
    }

    #[test]
    fn tool_result_with_unknown_call_id_is_dropped_as_stale() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_tool_call(&mut core, id, "call_1", "list", r#"{"path":"."}"#);
        let actions = core.handle_event(Event::ToolResult {
            request: id,
            call_id: "does_not_exist".to_string(),
            outcome: ToolOutcome::Ok("ok".to_string()),
        });
        assert!(actions.is_empty());
        assert_eq!(core.metrics().tool_results_dropped_as_stale.get(), 1);
    }

    #[test]
    fn arguments_over_limit_yields_synthetic_arguments_too_large_err() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = core.handle_event(tool_call_delta(
            id,
            0,
            Some("call_big"),
            Some("read"),
            Some(&"x".repeat(ARGUMENTS_MAX_BYTES + 1)),
        ));
        assert_eq!(
            core.metrics()
                .tool_call_arguments_fragments_dropped_over_limit
                .get(),
            1
        );
        let actions = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        assert_eq!(
            core.metrics().tool_calls_rejected_by_arguments_limit.get(),
            1
        );
        assert_eq!(core.metrics().tool_calls_executed.get(), 0);
        // The synthetic Err resolves all results immediately; a new
        // StartRequest must have been emitted with the Tool message
        // carrying the arguments_too_large payload.
        let messages = actions
            .iter()
            .find_map(|a| match a {
                Action::StartRequest { messages, .. } => Some(messages.clone()),
                _ => None,
            })
            .expect("StartRequest emitted");
        let tool_msg = messages
            .iter()
            .find_map(|m| match m {
                ChatMessage::Tool { content, .. } => Some(content),
                _ => None,
            })
            .expect("Tool message present");
        assert!(tool_msg.contains("arguments_too_large"));
    }

    #[test]
    fn turn_tool_call_limit_forces_synthetic_err_for_extras() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        // 21 tool calls, indices 0..=20. Limit is 20.
        for i in 0..=TURN_TOOL_CALL_LIMIT as u64 {
            let call_id = format!("c{i}");
            let _ = core.handle_event(tool_call_delta(
                id,
                i,
                Some(&call_id),
                Some("list"),
                Some(r#"{"path":"."}"#),
            ));
        }
        let _ = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        assert_eq!(
            core.metrics().tool_calls_executed.get(),
            TURN_TOOL_CALL_LIMIT as u64
        );
        assert_eq!(core.metrics().tool_calls_rejected_by_turn_limit.get(), 1);
    }

    #[test]
    fn unknown_function_name_yields_synthetic_unknown_tool_err() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = drive_single_tool_call(&mut core, id, "call_1", "bogus", r#"{}"#);
        // Since it's synthetic Err (all resolved), next StartRequest is emitted.
        let messages = actions
            .iter()
            .find_map(|a| match a {
                Action::StartRequest { messages, .. } => Some(messages.clone()),
                _ => None,
            })
            .expect("StartRequest emitted");
        let tool_content = messages
            .iter()
            .find_map(|m| match m {
                ChatMessage::Tool { content, .. } => Some(content.clone()),
                _ => None,
            })
            .expect("Tool message present");
        assert!(tool_content.contains("unknown_tool"));
        assert_eq!(core.metrics().tool_calls_executed.get(), 0);
    }

    #[test]
    fn cancel_in_tool_running_emits_cancel_tool_execution() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_tool_call(&mut core, id, "call_1", "list", r#"{"path":"."}"#);
        assert_eq!(core.status(), Status::ToolRunning);
        let actions = core.handle_event(Event::Cancel);
        assert!(actions.contains(&Action::CancelToolExecution { request: id }));
        assert_eq!(core.status(), Status::Idle);
        assert!(core.pending_response().is_none());
    }

    #[test]
    fn transport_error_dropped_in_tool_running_phase() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_tool_call(&mut core, id, "call_1", "list", r#"{"path":"."}"#);
        let actions = core.handle_event(Event::TransportError {
            request: id,
            message: "should be ignored".to_string(),
        });
        assert!(actions.is_empty());
        assert_eq!(core.metrics().transport_errors_dropped_as_stale.get(), 1);
        assert_eq!(core.status(), Status::ToolRunning);
    }

    #[test]
    fn tool_result_dropped_in_streaming_phase() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        // We are still in Streaming phase — no tool_calls finish yet.
        let actions = core.handle_event(Event::ToolResult {
            request: id,
            call_id: "call_1".to_string(),
            outcome: ToolOutcome::Ok("x".to_string()),
        });
        assert!(actions.is_empty());
        assert_eq!(core.metrics().tool_results_dropped_as_stale.get(), 1);
    }

    #[test]
    fn tool_calls_this_turn_resets_between_user_turns() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_tool_call(&mut core, id, "call_1", "list", r#"{"path":"."}"#);
        // Provide result to advance out of tool loop; also emit a
        // final stop-finish so we return to Idle.
        let next_id = {
            let actions = core.handle_event(Event::ToolResult {
                request: id,
                call_id: "call_1".to_string(),
                outcome: ToolOutcome::Ok("ok".to_string()),
            });
            last_start_id(&actions)
        };
        let _ = core.handle_event(Event::Finish {
            request: next_id,
            reason: Some("stop".to_string()),
        });
        assert_eq!(core.status(), Status::Idle);
        // A brand-new user turn should reset the counter and be able
        // to emit up to TURN_TOOL_CALL_LIMIT executions again.
        let id2 = last_start_id(&user(&mut core, "second"));
        let _ = drive_single_tool_call(&mut core, id2, "c2", "list", r#"{"path":"."}"#);
        assert_eq!(core.metrics().tool_calls_executed.get(), 2);
        assert_eq!(core.metrics().tool_calls_rejected_by_turn_limit.get(), 0);
    }

    #[test]
    fn finish_with_tool_calls_reason_but_no_slots_falls_through_to_idle() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        assert_eq!(actions, vec![Action::Redraw]);
        assert_eq!(core.status(), Status::Idle);
        assert_eq!(core.conversation().len(), 2);
    }

    #[test]
    fn readonly_tool_definitions_expose_the_three_tools() {
        let defs = ReadOnlyTool::definitions();
        let names: Vec<&str> = defs.iter().map(|d| d.name.as_str()).collect();
        assert_eq!(names, vec!["list", "read", "search"]);
    }

    #[test]
    fn readonly_tool_parse_list_defaults() {
        let tool = ReadOnlyTool::parse("list", r#"{"path":"src"}"#).expect("parses");
        assert_eq!(
            tool,
            ReadOnlyTool::List {
                path: "src".to_string(),
                recursive: false,
                max_entries: DEFAULT_LIST_MAX_ENTRIES,
                include_hidden: false,
            }
        );
    }

    #[test]
    fn readonly_tool_parse_read_with_line_range() {
        let tool = ReadOnlyTool::parse("read", r#"{"path":"src/main.rs","line_range":[10,20]}"#)
            .expect("parses");
        assert_eq!(
            tool,
            ReadOnlyTool::Read {
                path: "src/main.rs".to_string(),
                line_range: Some((10, 20)),
            }
        );
    }

    #[test]
    fn readonly_tool_parse_search_with_defaults() {
        let tool = ReadOnlyTool::parse("search", r#"{"pattern":"TODO"}"#).expect("parses");
        assert_eq!(
            tool,
            ReadOnlyTool::Search {
                pattern: "TODO".to_string(),
                path_prefix: None,
                case_sensitive: false,
                max_results: DEFAULT_SEARCH_MAX_RESULTS,
            }
        );
    }

    #[test]
    fn readonly_tool_parse_unknown_function_name() {
        let err = ReadOnlyTool::parse("foo", "{}").expect_err("unknown");
        assert_eq!(err, ToolExecutionError::UnknownTool);
    }

    #[test]
    fn readonly_tool_parse_invalid_json_is_reported() {
        let err = ReadOnlyTool::parse("list", "not-json").expect_err("invalid");
        assert!(matches!(err, ToolExecutionError::ArgumentsParseFailed(_)));
    }

    #[test]
    fn tool_execution_error_to_json_includes_code_and_message() {
        let s = ToolExecutionError::OutsideWorkspace.to_json_string();
        assert!(s.contains(r#""error":"outside_workspace""#));
        assert!(s.contains(r#""message""#));
    }

    #[test]
    fn tool_execution_error_message_is_human_readable_and_matches_json() {
        // The stderr line prints `message()`; the model gets the same
        // string in the JSON envelope. Pin both to the same wording so
        // a human and the model never diverge on what went wrong.
        let err = ToolExecutionError::OutsideWorkspace;
        assert_eq!(err.message(), "path escapes the workspace root");
        let json = err.to_json_string();
        assert!(json.contains(err.message().as_str()), "got {json}");

        let parse = ToolExecutionError::ArgumentsParseFailed("bad shape".to_string());
        assert_eq!(parse.message(), "bad shape");
        // No `Debug`-style wrapper leaks into the human-facing message.
        assert!(!parse.message().contains("ArgumentsParseFailed"));
    }

    // -------------------------------------------------------------
    // PatchInvocation
    // -------------------------------------------------------------

    #[test]
    fn patch_definition_advertises_the_patch_function_name() {
        let def = PatchInvocation::definition();
        assert_eq!(def.name, "patch");
        assert!(def.description.contains("approval"));
        assert!(def.parameters_json.contains("edits"));
    }

    #[test]
    fn patch_parse_add_and_update_edits() {
        let inv = PatchInvocation::parse(
            r#"{"edits":[
                {"kind":"add","path":"a.txt","content":"hello"},
                {"kind":"update","path":"b.txt","before":"foo","after":"bar"}
            ]}"#,
        )
        .expect("parses");
        assert_eq!(inv.edits.len(), 2);
        assert_eq!(
            inv.edits[0],
            PatchTool::Add {
                path: "a.txt".to_string(),
                content: "hello".to_string(),
            }
        );
        assert_eq!(
            inv.edits[1],
            PatchTool::Update {
                path: "b.txt".to_string(),
                before: "foo".to_string(),
                after: "bar".to_string(),
            }
        );
    }

    #[test]
    fn patch_parse_rejects_same_path_twice() {
        let err = PatchInvocation::parse(
            r#"{"edits":[
                {"kind":"update","path":"dup","before":"a","after":"b"},
                {"kind":"update","path":"dup","before":"c","after":"d"}
            ]}"#,
        )
        .expect_err("same-path rejected");
        assert_eq!(
            err,
            ToolExecutionError::Patch(PatchError::MultipleEditsSamePath {
                path: "dup".to_string(),
            })
        );
    }

    #[test]
    fn patch_parse_rejects_empty_edits() {
        let err = PatchInvocation::parse(r#"{"edits":[]}"#).expect_err("empty rejected");
        assert!(matches!(err, ToolExecutionError::ArgumentsParseFailed(_)));
    }

    #[test]
    fn patch_parse_rejects_too_many_edits() {
        let mut edits = String::from("[");
        for i in 0..(PATCH_MAX_EDITS + 1) {
            if i > 0 {
                edits.push(',');
            }
            edits.push_str(&format!(r#"{{"kind":"add","path":"f{i}","content":""}}"#));
        }
        edits.push(']');
        let json = format!(r#"{{"edits":{edits}}}"#);
        let err = PatchInvocation::parse(&json).expect_err("too many rejected");
        assert!(matches!(
            err,
            ToolExecutionError::Patch(PatchError::TooManyEdits { .. })
        ));
    }

    #[test]
    fn patch_parse_rejects_unknown_kind() {
        let err = PatchInvocation::parse(r#"{"edits":[{"kind":"delete","path":"x"}]}"#)
            .expect_err("unknown kind rejected");
        assert!(matches!(err, ToolExecutionError::ArgumentsParseFailed(_)));
    }

    #[test]
    fn patch_parse_rejects_add_over_size_limit() {
        let big = "x".repeat(PATCH_MAX_FILE_BYTES + 1);
        let json = format!(
            r#"{{"edits":[{{"kind":"add","path":"big","content":{}}}]}}"#,
            nojson::Json(&big),
        );
        let err = PatchInvocation::parse(&json).expect_err("too big rejected");
        assert!(matches!(
            err,
            ToolExecutionError::Patch(PatchError::FileTooLarge { .. })
        ));
    }

    #[test]
    fn patch_error_json_encodes_code_and_message() {
        let e = ToolExecutionError::Patch(PatchError::NoMatch {
            path: "a.txt".to_string(),
        });
        let s = e.to_json_string();
        assert!(s.contains(r#""error":"patch_no_match""#), "got {s}");
        assert!(s.contains("a.txt"));
    }

    #[test]
    fn patch_error_json_includes_hint_for_same_path() {
        let e = ToolExecutionError::Patch(PatchError::MultipleEditsSamePath {
            path: "dup".to_string(),
        });
        let s = e.to_json_string();
        assert!(
            s.contains(r#""error":"patch_multiple_edits_same_path""#),
            "got {s}"
        );
        assert!(s.contains(r#""hint":"#), "expected a hint member in {s}");
        assert!(s.contains("separate patch calls"), "got {s}");
    }

    #[test]
    fn patch_error_json_emits_null_hint_when_not_actionable() {
        let e = ToolExecutionError::Patch(PatchError::Rejected);
        let s = e.to_json_string();
        assert!(s.contains(r#""error":"patch_rejected""#), "got {s}");
        assert!(
            s.contains(r#""hint":null"#),
            "Rejected should emit null hint: {s}"
        );
    }

    // -------------------------------------------------------------
    // CommandInvocation
    // -------------------------------------------------------------

    #[test]
    fn command_definition_advertises_the_command_function_name() {
        let def = CommandInvocation::definition();
        assert_eq!(def.name, "command");
        assert!(def.description.contains("approval"));
        assert!(def.parameters_json.contains("argv"));
        assert!(!def.parameters_json.contains("timeout_seconds"));
    }

    #[test]
    fn command_parse_extracts_argv() {
        let inv = CommandInvocation::parse(r#"{"argv":["ls","-la"]}"#).expect("parses");
        assert_eq!(inv.argv, vec!["ls".to_string(), "-la".to_string()]);
    }

    #[test]
    fn command_parse_ignores_stray_timeout_seconds() {
        // The field is no longer part of the schema but old sessions
        // (or a confused model) may still emit it. Parsing must not
        // fail on extra keys.
        let inv = CommandInvocation::parse(r#"{"argv":["cargo","test"],"timeout_seconds":120}"#)
            .expect("parses");
        assert_eq!(inv.argv, vec!["cargo".to_string(), "test".to_string()]);
    }

    #[test]
    fn command_parse_rejects_empty_argv() {
        let err = CommandInvocation::parse(r#"{"argv":[]}"#).expect_err("empty rejected");
        assert_eq!(err, ToolExecutionError::Command(CommandError::EmptyArgv));
    }

    #[test]
    fn command_error_json_encodes_code_and_message() {
        let e = ToolExecutionError::Command(CommandError::SpawnFailed {
            message: "no such file".to_string(),
        });
        let s = e.to_json_string();
        assert!(s.contains(r#""error":"command_spawn_failed""#), "got {s}");
        assert!(s.contains("no such file"));
    }

    // -------------------------------------------------------------
    // patch approval loop
    // -------------------------------------------------------------

    fn drive_single_patch_call(
        core: &mut AgentCore,
        request: RequestId,
        call_id: &str,
        arguments_json: &str,
    ) -> Vec<Action> {
        let _ = core.handle_event(tool_call_delta(
            request,
            0,
            Some(call_id),
            Some("patch"),
            Some(arguments_json),
        ));
        core.handle_event(Event::Finish {
            request,
            reason: Some("tool_calls".to_string()),
        })
    }

    fn valid_add_patch_json() -> &'static str {
        r#"{"edits":[{"kind":"add","path":"new.txt","content":"hi"}]}"#
    }

    #[test]
    fn patch_finish_emits_preview_patch_and_stays_in_tool_running() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = drive_single_patch_call(&mut core, id, "p1", valid_add_patch_json());

        assert_eq!(core.status(), Status::ToolRunning);
        assert!(actions.iter().any(|a| matches!(
            a,
            Action::PreviewPatch { call_id, .. } if call_id == "p1"
        )));
        assert_eq!(core.metrics().patch_calls_previewed.get(), 1);
        // no approval-visible call_id yet — preview not received
        assert_eq!(core.pending_approval_call_id(), None);
    }

    #[test]
    fn patch_preview_ready_transitions_to_awaiting_approval_and_publishes_call_id() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_patch_call(&mut core, id, "p1", valid_add_patch_json());

        let snapshot = PreviewContent {
            path: "new.txt".to_string(),
            content: None,
        };
        let preview = PatchPreview {
            target_paths: vec!["new.txt".to_string()],
            added_lines: 1,
            removed_lines: 0,
            edit_count: 1,
            auto_approve: false,
            not_revertible: None,
        };
        let actions = core.handle_event(Event::PatchPreviewReady {
            request: id,
            call_id: "p1".to_string(),
            preview_content: vec![snapshot],
            preview,
        });

        assert_eq!(actions, vec![Action::Redraw]);
        assert_eq!(core.status(), Status::AwaitingApproval);
        assert_eq!(core.pending_approval_call_id(), Some("p1".to_string()));
        assert_eq!(core.metrics().patch_previews_committed.get(), 1);

        let active = core.active_tool_calls();
        assert_eq!(active.len(), 1);
        assert_eq!(active[0].approval, ApprovalState::Pending);
        assert!(active[0].patch_preview.is_some());
    }

    #[test]
    fn patch_approve_emits_apply_patch_with_stored_snapshots() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_patch_call(&mut core, id, "p1", valid_add_patch_json());
        let snapshot = PreviewContent {
            path: "new.txt".to_string(),
            content: Some(b"before".to_vec()),
        };
        let _ = core.handle_event(Event::PatchPreviewReady {
            request: id,
            call_id: "p1".to_string(),
            preview_content: vec![snapshot.clone()],
            preview: PatchPreview::default(),
        });

        let actions = core.handle_event(Event::ApproveToolCall {
            call_id: "p1".to_string(),
        });

        let apply = actions
            .iter()
            .find_map(|a| match a {
                Action::ApplyPatch {
                    call_id,
                    preview_content,
                    ..
                } => Some((call_id.clone(), preview_content.clone())),
                _ => None,
            })
            .expect("ApplyPatch emitted");
        assert_eq!(apply.0, "p1");
        assert_eq!(apply.1, vec![snapshot]);
        assert_eq!(core.metrics().tool_call_approvals_committed.get(), 1);
        // Approved but not yet resolved — approval left, phase now ToolRunning.
        assert_eq!(core.status(), Status::ToolRunning);
        assert!(core.pending_approval_call_id().is_none());
    }

    #[test]
    fn patch_reject_synthesizes_err_and_advances_when_last() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_patch_call(&mut core, id, "p1", valid_add_patch_json());
        let _ = core.handle_event(Event::PatchPreviewReady {
            request: id,
            call_id: "p1".to_string(),
            preview_content: Vec::new(),
            preview: PatchPreview::default(),
        });

        let actions = core.handle_event(Event::RejectToolCall {
            call_id: "p1".to_string(),
        });

        // Rejection is the only outstanding result → advance emits StartRequest.
        assert!(
            actions
                .iter()
                .any(|a| matches!(a, Action::StartRequest { .. }))
        );
        assert_eq!(core.metrics().tool_call_rejections_committed.get(), 1);
        // The synthetic Tool message contains the patch_rejected code.
        let last = core.conversation().last().expect("has tool message");
        match last {
            ChatMessage::Tool { content, .. } => {
                assert!(content.contains("patch_rejected"), "content={content}");
            }
            other => panic!("expected Tool, got {other:?}"),
        }
    }

    #[test]
    fn patch_approve_dropped_if_no_pending_call() {
        let mut core = AgentCore::new();
        let _ = user(&mut core, "hi");
        let actions = core.handle_event(Event::ApproveToolCall {
            call_id: "nope".to_string(),
        });
        assert!(actions.is_empty());
        assert_eq!(core.metrics().tool_call_approvals_dropped_as_stale.get(), 1);
    }

    #[test]
    fn patch_preview_ready_dropped_if_call_id_unknown() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_patch_call(&mut core, id, "p1", valid_add_patch_json());
        let actions = core.handle_event(Event::PatchPreviewReady {
            request: id,
            call_id: "does_not_exist".to_string(),
            preview_content: Vec::new(),
            preview: PatchPreview::default(),
        });
        assert!(actions.is_empty());
        assert_eq!(core.metrics().patch_previews_dropped_as_stale.get(), 1);
    }

    #[test]
    fn read_only_result_lands_in_awaiting_approval_phase() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        // Two tool calls: one read-only, one patch. Patch first sets
        // approval pending after preview → phase AwaitingApproval;
        // read-only ToolResult must still land in that phase.
        let _ = core.handle_event(tool_call_delta(
            id,
            0,
            Some("r1"),
            Some("list"),
            Some(r#"{"path":"."}"#),
        ));
        let _ = core.handle_event(tool_call_delta(
            id,
            1,
            Some("p1"),
            Some("patch"),
            Some(valid_add_patch_json()),
        ));
        let _ = core.handle_event(Event::Finish {
            request: id,
            reason: Some("tool_calls".to_string()),
        });
        let _ = core.handle_event(Event::PatchPreviewReady {
            request: id,
            call_id: "p1".to_string(),
            preview_content: Vec::new(),
            preview: PatchPreview::default(),
        });
        assert_eq!(core.status(), Status::AwaitingApproval);

        let actions = core.handle_event(Event::ToolResult {
            request: id,
            call_id: "r1".to_string(),
            outcome: ToolOutcome::Ok("ok".to_string()),
        });
        assert_eq!(core.metrics().tool_results_committed.get(), 1);
        assert_eq!(actions, vec![Action::Redraw]);
        // Still in approval phase because patch is not yet resolved.
        assert_eq!(core.status(), Status::AwaitingApproval);
    }

    // -------------------------------------------------------------
    // command approval loop
    // -------------------------------------------------------------

    fn drive_single_command_call(
        core: &mut AgentCore,
        request: RequestId,
        call_id: &str,
        arguments_json: &str,
    ) -> Vec<Action> {
        let _ = core.handle_event(tool_call_delta(
            request,
            0,
            Some(call_id),
            Some("command"),
            Some(arguments_json),
        ));
        core.handle_event(Event::Finish {
            request,
            reason: Some("tool_calls".to_string()),
        })
    }

    fn valid_command_json() -> &'static str {
        r#"{"argv":["echo","hi"]}"#
    }

    #[test]
    fn command_finish_populates_command_preview_and_marks_pending() {
        let mut core = AgentCore::new();
        core.set_workspace_display("/tmp/wksp".to_string());
        let id = last_start_id(&user(&mut core, "hi"));
        let actions = drive_single_command_call(&mut core, id, "c1", valid_command_json());

        // No ExecuteCommand yet — that only fires on approval.
        assert!(
            !actions
                .iter()
                .any(|a| matches!(a, Action::ExecuteCommand { .. }))
        );
        assert_eq!(core.status(), Status::AwaitingApproval);
        assert_eq!(core.metrics().command_calls_dispatched.get(), 1);

        let active = core.active_tool_calls();
        assert_eq!(active.len(), 1);
        assert_eq!(active[0].approval, ApprovalState::Pending);
        let preview = active[0]
            .command_preview
            .as_ref()
            .expect("preview populated");
        assert_eq!(preview.argv, vec!["echo".to_string(), "hi".to_string()]);
        assert_eq!(preview.working_directory, "/tmp/wksp");
        assert_eq!(core.pending_approval_call_id(), Some("c1".to_string()));
    }

    #[test]
    fn command_approve_emits_execute_command_action() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_command_call(&mut core, id, "c1", valid_command_json());

        let actions = core.handle_event(Event::ApproveToolCall {
            call_id: "c1".to_string(),
        });

        assert_eq!(core.metrics().tool_call_approvals_committed.get(), 1);
        assert_eq!(core.metrics().command_executions_started.get(), 1);
        let matched = actions.iter().any(|a| {
            matches!(
                a,
                Action::ExecuteCommand { call_id, invocation, .. }
                    if call_id == "c1"
                        && invocation.argv == vec!["echo".to_string(), "hi".to_string()]
            )
        });
        assert!(matched, "expected ExecuteCommand, got {actions:?}");
        assert_eq!(core.status(), Status::ToolRunning);
    }

    #[test]
    fn command_reject_synthesizes_command_rejected_err() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_command_call(&mut core, id, "c1", valid_command_json());

        let actions = core.handle_event(Event::RejectToolCall {
            call_id: "c1".to_string(),
        });

        assert_eq!(core.metrics().tool_call_rejections_committed.get(), 1);
        // Advance emits StartRequest with the synthetic Tool message.
        let start = actions
            .iter()
            .find_map(|a| match a {
                Action::StartRequest { messages, .. } => Some(messages.clone()),
                _ => None,
            })
            .expect("StartRequest emitted");
        let tool_msg = start
            .iter()
            .rev()
            .find_map(|m| match m {
                ChatMessage::Tool { content, .. } => Some(content.clone()),
                _ => None,
            })
            .expect("Tool message present");
        assert!(tool_msg.contains("command_rejected"), "content={tool_msg}");
    }

    #[test]
    fn command_output_chunk_appends_to_tail_when_approved() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_command_call(&mut core, id, "c1", valid_command_json());
        let _ = core.handle_event(Event::ApproveToolCall {
            call_id: "c1".to_string(),
        });

        let _ = core.handle_event(Event::CommandOutputChunk {
            request: id,
            call_id: "c1".to_string(),
            stream: CommandOutputStream::Stdout,
            bytes: b"line 1\n".to_vec(),
        });
        let _ = core.handle_event(Event::CommandOutputChunk {
            request: id,
            call_id: "c1".to_string(),
            stream: CommandOutputStream::Stderr,
            bytes: b"warn\n".to_vec(),
        });

        assert_eq!(core.metrics().command_output_chunks_appended.get(), 2);
        let active = core.active_tool_calls();
        let tail = active[0]
            .command_output_tail
            .as_ref()
            .expect("tail populated");
        assert_eq!(tail.stdout_tail, "line 1\n");
        assert_eq!(tail.stderr_tail, "warn\n");
        assert_eq!(tail.stdout_bytes_total, 7);
        assert_eq!(tail.stderr_bytes_total, 5);
    }

    #[test]
    fn command_output_chunk_dropped_if_not_approved() {
        let mut core = AgentCore::new();
        let id = last_start_id(&user(&mut core, "hi"));
        let _ = drive_single_command_call(&mut core, id, "c1", valid_command_json());
        // Still Pending, not yet Approved → chunk must drop as stale.

        let actions = core.handle_event(Event::CommandOutputChunk {
            request: id,
            call_id: "c1".to_string(),
            stream: CommandOutputStream::Stdout,
            bytes: b"early".to_vec(),
        });
        assert!(actions.is_empty());
        assert_eq!(
            core.metrics().command_output_chunks_dropped_as_stale.get(),
            1
        );
    }

    // -----------------------------------------------------------------
    // SubmitPlanInvocation
    // -----------------------------------------------------------------
}