rpi-cli 0.7.0

Terminal coding-agent CLI (the `rpi` binary) built on the rpi-* library crates
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
//! Output modes. Mirrors the v1-relevant slice of the TS
//! `packages/coding-agent/src/modes/{print-mode,json-event,rpc-mode}.ts` — the
//! three run shapes a harness-backed CLI needs:
//!
//! - [`print`] — single-shot: send the prompt(s), print the final assistant
//!   text (or the error) to stdout, exit. Mirrors TS `runPrintMode` (text mode).
//! - [`json`] — single-shot streaming: emit each harness event as a JSON line
//!   on stdout, then the final outcome. Mirrors TS `runPrintMode`
//!   (`mode === "json"`) + [`json_event::toJsonEvent`].
//! - [`interactive`] — a minimal line-oriented REPL: read prompts from stdin,
//!   run each, print the assistant text, loop until EOF / `/exit`. v1 does NOT
//!   port the TS `InteractiveMode` TUI (`modes/interactive/*` — a full terminal
//!   UI with Ink/React components); this is a deliberately minimal replacement,
//!   documented in the initial port notes (retired).
//!
//! All three drive the same `AgentHarness` via `AgentLane::prompt_text`.

use std::io::{BufRead, IsTerminal, Write};
use std::sync::{Arc, Mutex};

use rpi_agent::events::AgentEvent;
use rpi_ai::types::{AssistantMessage, Content, ImageContent, StopReason, UserMessage};
use rpi_harness::agent_harness::{
    AgentHarness, AgentLane, CompactionOutcome, CompactionResult, HarnessRunOutcome,
};
use rpi_harness::events::{HarnessEvent, RunEndOutcome};
use rpi_harness::session::types::{EntryOrder, LaneRecord, RecordQuery};

use crate::args::Args;
use crate::rpc::protocol as rpc_protocol;
use crate::rpc::writer::{start_rpc_writer, write_line, RpcWriter};

/// Extract the concatenated text content from an assistant message. Mirrors the
/// TS print-mode loop (`for content of assistantMsg.content if type===text`).
pub fn assistant_text(msg: &AssistantMessage) -> String {
    msg.content
        .iter()
        .filter_map(|c| match c {
            Content::Text(t) => Some(t.text.clone()),
            _ => None,
        })
        .collect()
}

/// The exit code a run's outcome maps to. Mirrors TS print mode: error/aborted
/// ⇒ exit 1; everything else ⇒ 0.
pub fn outcome_exit_code(outcome: &HarnessRunOutcome) -> i32 {
    match outcome {
        HarnessRunOutcome::Failed { .. } | HarnessRunOutcome::Aborted { .. } => 1,
        _ => 0,
    }
}

/// `print` mode: send the initial message (prompt text + inline `@file`
/// expansions), then any follow-up messages, print the final assistant text,
/// return the exit code. Mirrors TS `runPrintMode` (text).
pub async fn print(
    harness: &AgentHarness,
    _args: &Args,
    initial: Option<String>,
    extra_messages: &[String],
    initial_images: Vec<ImageContent>,
) -> i32 {
    let lane: Arc<dyn AgentLane> = harness.lane("main");

    let mut last_exit = 0;
    let mut last_msg: Option<AssistantMessage> = None;

    // The initial prompt (and its `@file` attachments) go in one user message;
    // extra positionals are separate prompts (mirrors the TS loop).
    let mut prompts: Vec<String> = Vec::new();
    if let Some(init) = initial {
        prompts.push(init);
    }
    for m in extra_messages {
        prompts.push(m.clone());
    }

    if prompts.is_empty() {
        // Nothing to do — print mode with no prompt is a no-op success.
        return 0;
    }

    let mut images = initial_images;
    for prompt in prompts {
        match lane.prompt_text(&prompt, std::mem::take(&mut images)).await {
            Ok(result) => {
                last_exit = outcome_exit_code(&result.outcome);
                match &result.outcome {
                    HarnessRunOutcome::Completed { final_message, .. }
                    | HarnessRunOutcome::Aborted { final_message, .. } => {
                        last_msg = Some(final_message.clone());
                    }
                    HarnessRunOutcome::Failed {
                        error,
                        final_message,
                        ..
                    } => {
                        if let Some(m) = final_message {
                            if m.stop_reason == StopReason::Error {
                                if let Some(em) = &m.error_message {
                                    eprintln!("{em}");
                                }
                            }
                        }
                        eprintln!("run failed: {error:?}");
                    }
                    HarnessRunOutcome::Suspended { .. } => {
                        eprintln!("run suspended (deferred) — resume is not supported in v1");
                        last_exit = 1;
                    }
                }
            }
            Err(e) => {
                eprintln!("prompt rejected: {e}");
                return 1;
            }
        }
    }

    // Print the final assistant text to stdout (TS: writeRawStdout text + "\n").
    if let Some(m) = &last_msg {
        match m.stop_reason {
            StopReason::Error => {
                if let Some(em) = &m.error_message {
                    eprintln!("{em}");
                }
                last_exit = 1;
            }
            StopReason::Aborted => {
                eprintln!("request aborted");
                last_exit = 1;
            }
            _ => {
                let text = assistant_text(m);
                let mut out = std::io::stdout();
                let _ = out.write_all(text.as_bytes());
                if !text.ends_with('\n') {
                    let _ = out.write_all(b"\n");
                }
                let _ = out.flush();
            }
        }
    }

    last_exit
}

/// `json` mode: emit each harness event as a JSON line on stdout, run the
/// prompts, then emit a terminal `result` line carrying the outcome + final
/// text. Mirrors TS `runPrintMode` (`mode === "json"`) streaming every event.
pub async fn json(
    harness: &AgentHarness,
    _args: &Args,
    initial: Option<String>,
    extra_messages: &[String],
    initial_images: Vec<ImageContent>,
    mut agent_events: Option<tokio::sync::broadcast::Receiver<AgentEvent>>,
) -> i32 {
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let collected: Arc<Mutex<Vec<HarnessEvent>>> = Arc::new(Mutex::new(Vec::new()));
    let collected_for_watch = collected.clone();

    // A watch captures every event (RunStart fires inline during prompt_text,
    // before a post-call listener could attach — same reason as the M5g test).
    let mut watch = harness.events().watch(|| ());
    watch.start(Arc::new(move |event: &HarnessEvent| {
        // Emit each event live as JSON, and also buffer for the final summary.
        emit_json_event(event);
        collected_for_watch.lock().unwrap().push(event.clone());
    }));
    // Keep the watch alive for the whole run. Leaking is acceptable for a
    // single-shot CLI process (the bus outlives this scope anyway).
    std::mem::forget(watch);

    // The harness bus carries run lifecycle events; the agent receiver carries
    // the native fine-grained stream (turns, message deltas, and tools).
    let (agent_done_tx, mut agent_done_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
    let agent_event_task = agent_events.take().map(|mut rx| {
        tokio::spawn(async move {
            let done_tx = agent_done_tx;
            loop {
                match rx.recv().await {
                    Ok(event) => {
                        let terminal = event.is_terminal();
                        emit_agent_event(&event);
                        if terminal {
                            let _ = done_tx.send(());
                        }
                    }
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                }
            }
        })
    });

    let mut prompts: Vec<String> = Vec::new();
    if let Some(init) = initial {
        prompts.push(init);
    }
    for m in extra_messages {
        prompts.push(m.clone());
    }

    let mut last_exit = 0;
    let mut final_outcome: Option<HarnessRunOutcome> = None;

    let mut images = initial_images;
    for prompt in prompts {
        match lane.prompt_text(&prompt, std::mem::take(&mut images)).await {
            Ok(result) => {
                // The harness resolves after its run outcome, while the
                // broadcast listener may still be scheduling the terminal
                // AgentEnd line. Wait briefly so JSON consumers see the full
                // lifecycle before the final result summary. The timeout is
                // deliberately bounded for custom/older harness emitters.
                let _ = tokio::time::timeout(
                    std::time::Duration::from_millis(250),
                    agent_done_rx.recv(),
                )
                .await;
                last_exit = outcome_exit_code(&result.outcome);
                final_outcome = Some(result.outcome);
            }
            Err(e) => {
                // Emit a structured error line + exit.
                let line = serde_json::json!({
                    "type": "error",
                    "error": e.to_string(),
                });
                println!("{line}");
                if let Some(task) = agent_event_task {
                    task.abort();
                }
                return 1;
            }
        }
    }

    // Terminal result summary.
    let (outcome_str, final_text) = match final_outcome {
        Some(HarnessRunOutcome::Completed { final_message, .. }) => {
            ("completed", Some(assistant_text(&final_message)))
        }
        Some(HarnessRunOutcome::Aborted { final_message, .. }) => {
            ("aborted", Some(assistant_text(&final_message)))
        }
        Some(HarnessRunOutcome::Failed { final_message, .. }) => {
            let t = final_message.as_ref().map(assistant_text);
            ("failed", t)
        }
        Some(HarnessRunOutcome::Suspended { .. }) => ("suspended", None),
        None => ("idle", None),
    };
    let result_line = serde_json::json!({
        "type": "result",
        "outcome": outcome_str,
        "finalText": final_text,
    });
    println!("{result_line}");
    if let Some(task) = agent_event_task {
        task.abort();
    }
    last_exit
}

fn emit_agent_event(event: &AgentEvent) {
    println!("{}", agent_event_json(event));
}

/// `rpc` mode: a headless JSONL command loop (the server-side agent).
///
/// Reads one JSON command per line from stdin (`{id?, type, ...}`), drives the
/// `main` lane, and writes one JSON object per line to stdout:
/// - fine-grained `AgentEvent`s via [`agent_event_json`] (each carries `type`),
/// - a `{"type":"response","id":<id>,"status":"ok"|"error",...}` per command.
///
/// Commands: `prompt`, `resume_pending`, and `compact` (drive the lane),
/// `abort`, `get_state`, `set_model`,
/// `set_thinking_level`, `set_active_tools`, `ping`, `stop`. `stop` (or stdin
/// EOF) ends the loop. This is the process `rpi-server` spawns and that
/// `rpi --connect` talks to. Mirrors TS `runRpcMode` / `modes/rpc`.
///
/// The extension `UiDialog` mailbox is bridged over the same channel: the host
/// emits `{"type":"ui_dialog_request","requestId","toolCallId","ui"}`, and the
/// client answers with `{"type":"ui_dialog_response","requestId","answer"}` (or
/// `"cancelled":true`). A `prompt` runs in its own task so this loop keeps
/// reading — that is what lets `abort` and dialog answers arrive mid-run.
pub async fn rpc(
    harness: &AgentHarness,
    mut agent_events: Option<tokio::sync::broadcast::Receiver<AgentEvent>>,
    model_catalog: Vec<rpi_ai::Model>,
    ui_dialog: rpi_extensions::UiDialogMailbox,
    oauth_snapshot: Option<Arc<rpi_extensions::RegistrySnapshot>>,
) -> i32 {
    rpc_with_io(
        harness,
        agent_events.take(),
        model_catalog,
        ui_dialog,
        oauth_snapshot,
        tokio::io::BufReader::new(tokio::io::stdin()),
        std::io::stdout(),
    )
    .await
}

async fn rpc_with_io<R, W>(
    harness: &AgentHarness,
    mut agent_events: Option<tokio::sync::broadcast::Receiver<AgentEvent>>,
    model_catalog: Vec<rpi_ai::Model>,
    ui_dialog: rpi_extensions::UiDialogMailbox,
    oauth_snapshot: Option<Arc<rpi_extensions::RegistrySnapshot>>,
    input: R,
    output: W,
) -> i32
where
    R: tokio::io::AsyncBufRead + Unpin,
    W: Write + Send + 'static,
{
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    // One blocking writer owns stdout. Producers only enqueue bounded messages,
    // so pipe backpressure never blocks a Tokio worker on IO or a std mutex.
    let (stdout, writer_task, writer_failed) = start_rpc_writer(output);
    let pump_stop = tokio_util::sync::CancellationToken::new();

    // A completion response is queued only after its final events, so a
    // subsequent prompt cannot overtake the previous run's agent_end.
    let (event_flush_tx, mut event_flush_rx) =
        tokio::sync::mpsc::unbounded_channel::<tokio::sync::oneshot::Sender<()>>();
    // Stream fine-grained AgentEvents as JSONL until the receiver closes.
    let event_task = agent_events.take().map(|mut rx| {
        let out = stdout.clone();
        let stop = pump_stop.clone();
        tokio::spawn(async move {
            loop {
                let received = tokio::select! {
                    _ = stop.cancelled() => {
                        drain_rpc_events(&out, &mut rx).await;
                        break;
                    }
                    Some(done) = event_flush_rx.recv() => {
                        drain_rpc_events(&out, &mut rx).await;
                        let _ = done.send(());
                        continue;
                    }
                    event = rx.recv() => event,
                };
                match received {
                    Ok(event) => write_line(&out, &agent_event_json(&event)).await,
                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
                    Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                }
            }
        })
    });

    let event_flush = event_task.as_ref().map(|_| event_flush_tx);

    // Bridge the extension `UiDialog` mailbox over the rpc channel so a
    // permission-gate extension can ask the client a question mid-run: we emit
    // `{"type":"ui_dialog_request",…}` and answer it from a
    // `{"type":"ui_dialog_response",…}` on stdin. Without this a headless run
    // leaves the mailbox detached and every `UiDialog` call fails.
    ui_dialog.attach();
    let dialog_task = {
        let mailbox = ui_dialog.clone();
        let out = stdout.clone();
        let stop = pump_stop.clone();
        tokio::spawn(async move {
            let mut shown = std::collections::HashSet::new();
            while !stop.is_cancelled() {
                while let Some(request) = mailbox.take_pending() {
                    let event = crate::remote::protocol::RemoteEvent::UiDialogRequest {
                        request_id: request.request_id.clone(),
                        tool_call_id: request.tool_call_id,
                        ui: request.ui,
                    };
                    write_line(&out, &serde_json::to_value(event).unwrap()).await;
                    shown.insert(request.request_id);
                }
                let closed: Vec<String> = shown
                    .iter()
                    .filter(|id| !mailbox.is_pending(id))
                    .cloned()
                    .collect();
                for request_id in closed {
                    shown.remove(&request_id);
                    let event = crate::remote::protocol::RemoteEvent::UiDialogClosed { request_id };
                    write_line(&out, &serde_json::to_value(event).unwrap()).await;
                }
                tokio::select! {
                    _ = stop.cancelled() => break,
                    _ = tokio::time::sleep(std::time::Duration::from_millis(30)) => {}
                }
            }
        })
    };

    // A `prompt` runs in a spawned task so this loop keeps reading stdin while
    // the run is active — otherwise `abort` and `ui_dialog_response` could not
    // be delivered mid-run. Only one prompt may be in flight at a time.
    let run_active = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let mut run_task: Option<tokio::task::JoinHandle<()>> = None;
    let mut run_cancel = tokio_util::sync::CancellationToken::new();
    let mut cancel_on_exit = false;

    use tokio::io::AsyncBufReadExt;

    let mut lines = input.lines();
    write_line(&stdout, &rpc_protocol::ready()).await;

    loop {
        let incoming = tokio::select! {
            _ = writer_failed.cancelled() => {
                cancel_on_exit = true;
                break;
            }
            line = lines.next_line() => line,
        };
        let line = match incoming {
            Ok(Some(line)) => line,
            Ok(None) => break, // EOF
            Err(error) => {
                eprintln!("[rpi] rpc stdin error: {error}");
                cancel_on_exit = true;
                break;
            }
        };
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let msg: serde_json::Value = match serde_json::from_str(line) {
            Ok(value) => value,
            Err(error) => {
                write_line(
                    &stdout,
                    &rpc_protocol::response(
                        None,
                        "invalid_request",
                        Err(format!("invalid json: {error}")),
                    ),
                )
                .await;
                continue;
            }
        };
        let id = msg.get("id").cloned().unwrap_or(serde_json::Value::Null);
        let kind = msg
            .get("type")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        if rpc_protocol::SUPPORTED_COMMANDS.contains(&kind.as_str())
            && serde_json::from_value::<rpc_protocol::Request>(msg.clone()).is_err()
        {
            write_line(
                &stdout,
                &rpc_protocol::response(
                    Some(id.clone()),
                    &kind,
                    Err("invalid command payload".to_string()),
                ),
            )
            .await;
            continue;
        }

        match kind.as_str() {
            "ui_dialog_response" => {
                let request_id = msg
                    .get("requestId")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();
                let result = if msg
                    .get("cancelled")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false)
                {
                    ui_dialog.cancel(&request_id)
                } else {
                    let answer = msg
                        .get("answer")
                        .cloned()
                        .unwrap_or(serde_json::Value::Null);
                    ui_dialog.respond(&request_id, answer)
                };
                if msg.get("id").is_some() {
                    let response = match result {
                        Ok(()) => rpc_protocol::response(
                            Some(id),
                            "ui_dialog_response",
                            Ok(Some(
                                serde_json::json!({"accepted":true,"requestId":request_id}),
                            )),
                        ),
                        Err(error) => {
                            rpc_protocol::response(Some(id), "ui_dialog_response", Err(error))
                        }
                    };
                    write_line(&stdout, &response).await;
                } else if let Err(error) = result {
                    eprintln!("[rpi] ui_dialog_response: {error}");
                }
                continue;
            }
            "stop" => {
                cancel_on_exit = true;
                write_line(
                    &stdout,
                    &rpc_protocol::response(
                        Some(id.clone()),
                        "stop",
                        Ok(Some(serde_json::json!({"stopped": true}))),
                    ),
                )
                .await;
                break;
            }
            "prompt" | "resume_pending" | "compact" => {
                let resume = kind == "resume_pending";
                let compact = kind == "compact";
                if run_active.swap(true, std::sync::atomic::Ordering::AcqRel) {
                    write_line(
                        &stdout,
                        &rpc_protocol::response(
                            Some(id.clone()),
                            &kind,
                            Err("a run is already active".to_string()),
                        ),
                    )
                    .await;
                    continue;
                }
                if let Some(task) = run_task.take() {
                    let _ = task.await;
                }
                run_cancel = tokio_util::sync::CancellationToken::new();
                let cancel_task = run_cancel.clone();
                // Resuming spends the tokens the interrupted run never did, so it
                // only proceeds when recovery actually left a pending run.
                if resume && !lane.has_pending_resume().await {
                    run_active.store(false, std::sync::atomic::Ordering::Release);
                    write_line(
                        &stdout,
                        &rpc_protocol::response(
                            Some(id),
                            "resume_pending",
                            Ok(Some(serde_json::json!({"resumed": false}))),
                        ),
                    )
                    .await;
                    continue;
                }
                let content = msg
                    .get("message")
                    .and_then(|v| v.as_str())
                    .map(str::to_owned);
                let lane_task = Arc::clone(&lane);
                let out_task = stdout.clone();
                let active_task = Arc::clone(&run_active);
                let mailbox_task = ui_dialog.clone();
                let flush_events = event_flush.clone();
                let Some(content) = content.or_else(|| (resume || compact).then(String::new))
                else {
                    active_task.store(false, std::sync::atomic::Ordering::Release);
                    write_line(
                        &stdout,
                        &rpc_protocol::response(
                            Some(id),
                            "prompt",
                            Err("prompt requires a string `message`".to_string()),
                        ),
                    )
                    .await;
                    continue;
                };
                write_line(
                    &stdout,
                    &rpc_protocol::response(
                        Some(id),
                        &kind,
                        Ok(Some(serde_json::json!({"accepted": true}))),
                    ),
                )
                .await;
                let instructions = msg
                    .get("customInstructions")
                    .and_then(|v| v.as_str())
                    .map(str::to_owned);
                run_task = Some(tokio::spawn(async move {
                    let result = if compact {
                        rpc_compact_cancellable(&lane_task, instructions, cancel_task).await
                    } else if resume {
                        rpc_resume_cancellable(&lane_task, cancel_task).await
                    } else {
                        rpc_prompt_cancellable(&lane_task, &content, cancel_task).await
                    };
                    if let Some(flush) = flush_events {
                        let (done, drained) = tokio::sync::oneshot::channel();
                        if flush.send(done).is_ok() {
                            let _ = drained.await;
                        }
                    }
                    let (outcome, aborted, error) = match &result {
                        Ok(value) => {
                            let outcome = value
                                .get("outcome")
                                .and_then(|v| v.as_str())
                                .unwrap_or("completed")
                                .to_string();
                            let error = value
                                .get("error")
                                .and_then(|v| v.as_str())
                                .map(str::to_owned);
                            (outcome.clone(), outcome == "aborted", error)
                        }
                        Err(ref error) => ("failed".to_string(), false, Some(error.clone())),
                    };
                    // Recovery may leave a continuable run behind an abort, so the
                    // settlement carries what the client needs to offer "continue".
                    let pending_resume = lane_task.has_pending_resume().await;
                    let summary = result
                        .as_ref()
                        .ok()
                        .and_then(|value| value.get("summary"))
                        .cloned();
                    let settled = serde_json::json!({
                        "type": "agent_settled",
                        "runId": result.as_ref().ok().and_then(|value| value.get("runId")),
                        "outcome": outcome,
                        "aborted": aborted,
                        "error": error,
                        "summary": summary,
                        "pendingResume": pending_resume,
                    });
                    write_line(&out_task, &settled).await;
                    mailbox_task.cancel_all();
                    active_task.store(false, std::sync::atomic::Ordering::Release);
                }));
                continue;
            }
            _ => {}
        }

        let result = match kind.as_str() {
            "abort" if run_active.load(std::sync::atomic::Ordering::Acquire) => {
                // This also covers abort arriving before the task enters the lane.
                run_cancel.cancel();
                Ok(serde_json::json!({"aborted": true}))
            }
            "abort" => lane
                .abort()
                .await
                .map(|_| serde_json::json!({"aborted": true}))
                .map_err(|e| e.to_string()),
            "get_state" => Ok(rpc_get_state(&lane, harness).await),
            "get_messages" => rpc_get_messages(&lane, harness, &msg).await,
            "get_history" => rpc_get_history(&lane, harness, &msg).await,
            "get_stats" => rpc_get_stats(&lane, harness).await,
            "get_queue" => rpc_get_queue(&lane, harness, &msg).await,
            "queue_message" => rpc_queue_message(&lane, &msg).await,
            "cancel_queued" => rpc_cancel_queued(&lane, &msg).await,
            "clear_queue" => rpc_clear_queue(&lane).await,
            "navigate" => rpc_navigate(&lane, &msg).await,
            "get_available_models" => Ok(rpc_get_available_models(&model_catalog)),
            "get_auth_status" => Ok(rpc_get_auth_status(&model_catalog, oauth_snapshot.as_ref())),
            "oauth" => rpc_oauth(&oauth_snapshot, &msg),
            "set_api_key" => rpc_set_api_key(&msg).await,
            "set_model" => rpc_set_model(&lane, &model_catalog, &msg).await,
            "get_available_thinking_levels" => Ok(rpc_get_available_thinking_levels(&lane).await),
            "set_thinking_level" => rpc_set_thinking_level(&lane, &msg).await,
            "get_available_tools" => Ok(rpc_get_available_tools(&lane, harness).await),
            "set_active_tools" => rpc_set_active_tools(&lane, &msg).await,
            "ping" => Ok(serde_json::json!({"pong": true})),
            other => Err(format!("unknown command type: {other}")),
        };

        let response = rpc_protocol::response(Some(id.clone()), &kind, result.map(Some));
        write_line(&stdout, &response).await;
    }

    // EOF closes the input half of the protocol, not an accepted prompt.
    // There can be no more dialog answers, so release approvals, then await the
    // run before SessionShutdown can unload plugins or the runtime exits.
    ui_dialog.detach();
    if cancel_on_exit {
        run_cancel.cancel();
    }
    let mut exit_code = 0;
    if let Some(task) = run_task {
        if let Err(error) = task.await {
            eprintln!("[rpi] rpc prompt task failed: {error}");
            exit_code = 1;
        }
    }
    pump_stop.cancel();
    let _ = dialog_task.await;
    if let Some(task) = event_task {
        let _ = task.await;
    }
    // All producers have joined; close the queue and flush every queued line.
    drop(stdout);
    match writer_task.await {
        Ok(Ok(())) => {}
        error => {
            eprintln!("[rpi] rpc output failed: {error:?}");
            exit_code = 1;
        }
    }
    exit_code
}

async fn drain_rpc_events(
    out: &RpcWriter,
    events: &mut tokio::sync::broadcast::Receiver<AgentEvent>,
) {
    loop {
        match events.try_recv() {
            Ok(event) => write_line(out, &agent_event_json(&event)).await,
            Err(tokio::sync::broadcast::error::TryRecvError::Lagged(_)) => continue,
            Err(_) => break,
        }
    }
}

/// Cancellation is delivered even if abort/stop arrives before prompt_text has
/// registered a run. Once active, await its normal aborted outcome and cleanup.
async fn rpc_prompt_cancellable(
    lane: &Arc<dyn AgentLane>,
    content: &str,
    cancel: tokio_util::sync::CancellationToken,
) -> Result<serde_json::Value, String> {
    let prompt = rpc_prompt_text(lane, content);
    tokio::pin!(prompt);
    tokio::select! {
        biased;
        _ = cancel.cancelled() => {
            match lane.abort().await {
                Ok(_) => prompt.await,
                Err(_) => Err("Operation aborted".to_string()),
            }
        }
        result = &mut prompt => result,
    }
}

/// Compact the branch, unless the caller cancels first.
///
/// Compaction is its own operation kind in the harness: it spends a provider
/// call on the summary, so it takes the same single-run slot and reports the
/// same settlement shape a prompt does.
async fn rpc_compact_cancellable(
    lane: &Arc<dyn AgentLane>,
    instructions: Option<String>,
    cancel: tokio_util::sync::CancellationToken,
) -> Result<serde_json::Value, String> {
    let compact = async {
        match lane.compact(instructions.as_deref()).await {
            Ok(result) => Ok(compaction_json(&result)),
            Err(error) => Err(error.to_string()),
        }
    };
    tokio::pin!(compact);
    tokio::select! {
        biased;
        _ = cancel.cancelled() => {
            let _ = lane.abort().await;
            compact.await
        }
        result = &mut compact => result,
    }
}

/// Reduce a compaction result to what a client needs: the verdict, and a line
/// a transcript can print.
fn compaction_json(result: &CompactionResult) -> serde_json::Value {
    let mut value = match &result.outcome {
        CompactionOutcome::Completed { leaf_id, entry } => {
            let (tokens_before, retained) = match entry {
                rpi_harness::session::types::Entry::Compaction(compaction) => {
                    (compaction.tokens_before, compaction.retained_tail.len())
                }
                _ => (0, 0),
            };
            serde_json::json!({
                "outcome": "compacted",
                "leafId": leaf_id,
                "tokensBefore": tokens_before,
                "retainedMessages": retained,
                "summary": format!(
                    "Conversation compacted · {} tokens before, {} messages kept.",
                    tokens_before, retained
                ),
            })
        }
        CompactionOutcome::Declined { leaf_id } => serde_json::json!({
            "outcome": "declined",
            "leafId": leaf_id,
            "summary": "Nothing to compact yet.",
        }),
        CompactionOutcome::Aborted { leaf_id } => serde_json::json!({
            "outcome": "aborted",
            "leafId": leaf_id,
            "summary": "Compaction aborted.",
        }),
        CompactionOutcome::Failed { leaf_id, error } => serde_json::json!({
            "outcome": "failed",
            "leafId": leaf_id,
            "error": error.message,
            "summary": format!("Compaction failed: {}", error.message),
        }),
    };
    value["runId"] = serde_json::json!(result.run_id);
    value
}

/// Drive the run recovery left behind, unless the caller cancels first.
///
/// `Ok(None)` from the lane means there was nothing to resume: the run is
/// reported as `skipped` so the client can settle without inventing an outcome.
async fn rpc_resume_cancellable(
    lane: &Arc<dyn AgentLane>,
    cancel: tokio_util::sync::CancellationToken,
) -> Result<serde_json::Value, String> {
    let resume = async {
        match lane.resume_pending().await {
            Ok(Some(result)) => {
                let (outcome, final_text, error) = rpc_outcome_str(&result.outcome);
                Ok(serde_json::json!({
                    "runId": result.run_id,
                    "outcome": outcome,
                    "finalText": final_text,
                    "error": error,
                    "resumed": true,
                }))
            }
            Ok(None) => Ok(serde_json::json!({"outcome": "skipped", "resumed": false})),
            Err(error) => Err(error.to_string()),
        }
    };
    tokio::pin!(resume);
    tokio::select! {
        biased;
        _ = cancel.cancelled() => {
            let _ = lane.abort().await;
            resume.await
        }
        result = &mut resume => result,
    }
}

fn rpc_outcome_str(outcome: &HarnessRunOutcome) -> (&'static str, Option<String>, Option<String>) {
    match outcome {
        HarnessRunOutcome::Completed { final_message, .. } => {
            ("completed", Some(assistant_text(final_message)), None)
        }
        HarnessRunOutcome::Aborted { final_message, .. } => {
            ("aborted", Some(assistant_text(final_message)), None)
        }
        // A failed run can end with nothing to say, which is exactly when the
        // reason matters: rate limits and provider errors live here.
        HarnessRunOutcome::Failed {
            final_message,
            error,
            ..
        } => (
            "failed",
            final_message.as_ref().map(assistant_text),
            Some(error.message.clone()),
        ),
        HarnessRunOutcome::Suspended { .. } => ("suspended", None, None),
    }
}

async fn rpc_prompt_text(
    lane: &Arc<dyn AgentLane>,
    content: &str,
) -> Result<serde_json::Value, String> {
    let result = lane
        .prompt_text(content, Vec::new())
        .await
        .map_err(|e| e.to_string())?;
    let (outcome, final_text, error) = rpc_outcome_str(&result.outcome);
    Ok(
        serde_json::json!({"runId":result.run_id, "outcome": outcome, "finalText": final_text, "error": error}),
    )
}

async fn rpc_get_state(lane: &Arc<dyn AgentLane>, harness: &AgentHarness) -> serde_json::Value {
    let model = lane.get_model().await.ok();
    let thinking = lane
        .get_thinking_level()
        .await
        .ok()
        .map(|t| serde_json::to_value(t).unwrap_or(serde_json::Value::Null));
    let active_tools = lane.get_active_tools().await.unwrap_or_default();
    let leaf_id = lane.get_leaf_id().await.ok().flatten();
    let context = rpc_context_usage(lane, harness).await;
    let active_operation = lane
        .snapshot()
        .await
        .ok()
        .and_then(|snapshot| snapshot.active)
        .map(|active| {
            serde_json::json!({
                "runId": active.run_id,
                "lane": active.lane,
                "kind": format!("{:?}", active.kind).to_lowercase(),
            })
        });
    let queued = lane.queued_messages().await.unwrap_or_default();
    let stats = rpc_get_stats(lane, harness).await.ok();
    serde_json::json!({
        "modelId": model.as_ref().map(|model| model.id.clone()),
        "provider": model.as_ref().map(|model| model.provider.clone()),
        "thinkingLevel": thinking,
        "activeTools": active_tools,
        "leafId": leaf_id,
        "context": context,
        "sessionId": harness.session().storage().metadata().id,
        "activeOperation": active_operation,
        "queue": {
            "steering": queued.steering,
            "followUp": queued.follow_up,
            "steeringCount": queued.steering.len(),
            "followUpCount": queued.follow_up.len(),
        },
        "stats": stats,
    })
}

fn rpc_now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|duration| duration.as_millis() as i64)
        .unwrap_or_default()
}

fn rpc_message_text(value: &serde_json::Value) -> String {
    let Some(content) = value.get("content") else {
        return String::new();
    };
    if let Some(text) = content.as_str() {
        return text.to_string();
    }
    content
        .as_array()
        .into_iter()
        .flatten()
        .filter_map(|block| block.get("text").and_then(|text| text.as_str()))
        .collect::<Vec<_>>()
        .join("\\n")
}

async fn rpc_get_history(
    lane: &Arc<dyn AgentLane>,
    harness: &AgentHarness,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let limit = msg
        .get("limit")
        .and_then(serde_json::Value::as_u64)
        .unwrap_or(100)
        .clamp(1, 500) as usize;
    let after_seq = msg.get("afterSeq").and_then(serde_json::Value::as_u64);
    let before_seq = msg.get("beforeSeq").and_then(serde_json::Value::as_u64);
    let mut records = harness
        .session()
        .find_records(&RecordQuery {
            lane: Some(lane.name().to_string()),
            after_seq,
            order: Some(EntryOrder::OldestFirst),
            ..Default::default()
        })
        .await
        .map_err(|error| error.to_string())?;
    if let Some(before) = before_seq {
        records.retain(|record| record.seq() < before);
    }
    let total = records.len();
    let has_more = records.len() > limit;
    if before_seq.is_some() {
        if has_more {
            records = records.split_off(records.len() - limit);
        }
    } else if after_seq.is_some() {
        records.truncate(limit);
    } else if has_more {
        records = records.split_off(records.len() - limit);
    }
    let first_seq = records.first().map(LaneRecord::seq);
    let last_seq = records.last().map(LaneRecord::seq);
    let open_operations = harness
        .session()
        .find_open_operations(lane.name(), Some(50))
        .await
        .map_err(|error| error.to_string())?;
    Ok(serde_json::json!({
        "records": records.iter().map(|record| serde_json::to_value(record).unwrap_or(serde_json::Value::Null)).collect::<Vec<_>>(),
        "total": total,
        "limit": limit,
        "afterSeq": after_seq,
        "beforeSeq": before_seq,
        "firstSeq": first_seq,
        "lastSeq": last_seq,
        "hasMore": has_more,
        "leafId": lane.get_leaf_id().await.ok().flatten(),
        "openOperations": open_operations.iter().map(|record| serde_json::to_value(record).unwrap_or(serde_json::Value::Null)).collect::<Vec<_>>(),
    }))
}

async fn rpc_get_stats(
    lane: &Arc<dyn AgentLane>,
    harness: &AgentHarness,
) -> Result<serde_json::Value, String> {
    let stats = lane.get_stats().await.map_err(|error| error.to_string())?;
    let records = harness
        .session()
        .find_records(&RecordQuery {
            lane: Some(lane.name().to_string()),
            order: Some(EntryOrder::OldestFirst),
            ..Default::default()
        })
        .await
        .map_err(|error| error.to_string())?;
    let mut operation_counts = std::collections::BTreeMap::<String, u64>::new();
    for record in &records {
        let kind = match record {
            LaneRecord::OperationStarted(started) => {
                let key = started.intent.kind();
                *operation_counts.entry(key.to_string()).or_default() += 1;
                if matches!(
                    &started.intent,
                    rpi_harness::session::types::OperationIntent::Run {
                        resume_data: Some(_),
                        ..
                    }
                ) {
                    *operation_counts.entry("resume".to_string()).or_default() += 1;
                }
                continue;
            }
            LaneRecord::OperationFinished(_) => "operation_finished",
            LaneRecord::RetryPending(_) => "retry_pending",
            LaneRecord::Usage(_) => "usage",
            _ => continue,
        };
        *operation_counts.entry(kind.to_string()).or_default() += 1;
    }
    let count = |name: &str| operation_counts.get(name).copied().unwrap_or_default();
    let model = lane.get_model().await.ok();
    let input = stats.cached_tokens + stats.uncached_tokens;
    Ok(serde_json::json!({
        "messageCount": stats.message_count,
        "operationCount": count("operation_finished"),
        "retryCount": count("retry_pending"),
        "compactionCount": count("compaction"),
        "resumeCount": count("resume"),
        "operationCounts": operation_counts,
        "provider": model.as_ref().map(|value| value.provider.clone()),
        "modelId": model.as_ref().map(|value| value.id.clone()),
        "cachedTokens": stats.cached_tokens,
        "uncachedTokens": stats.uncached_tokens,
        "totalTokens": stats.total_tokens,
        "costTotal": stats.cost_total,
        "cacheHitRatio": if input > 0 { Some(stats.cached_tokens as f64 / input as f64) } else { None::<f64> },
    }))
}

async fn rpc_get_queue(
    lane: &Arc<dyn AgentLane>,
    harness: &AgentHarness,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let include_completed = msg
        .get("includeCompleted")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false);
    let records = harness
        .session()
        .find_records(&RecordQuery {
            lane: Some(lane.name().to_string()),
            order: Some(EntryOrder::OldestFirst),
            ..Default::default()
        })
        .await
        .map_err(|error| error.to_string())?;
    let mut cancelled = std::collections::HashMap::<String, u64>::new();
    for record in &records {
        if let LaneRecord::QueueCancelled(record) = record {
            cancelled.insert(record.entry_id.clone(), record.base.seq);
        }
    }
    let mut items = Vec::new();
    for record in records {
        let LaneRecord::QueueEnqueued(record) = record else {
            continue;
        };
        let Some(entry_id) = record.target.get("id").and_then(|value| value.as_str()) else {
            continue;
        };
        let (status, completed_seq) = if let Some(seq) = cancelled.get(entry_id) {
            ("cancelled", Some(*seq))
        } else if let Some(entry) = harness.get_entry(entry_id).await.ok().flatten() {
            ("consumed", Some(entry.base().seq))
        } else {
            ("queued", None)
        };
        if status != "queued" && !include_completed {
            continue;
        }
        let message = record
            .target
            .get("message")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        items.push(serde_json::json!({
            "entryId": entry_id,
            "queue": record.queue,
            "status": status,
            "text": rpc_message_text(&message),
            "message": message,
            "runId": record.run_id,
            "seq": record.base.seq,
            "completedSeq": completed_seq,
        }));
    }
    Ok(
        serde_json::json!({"items": items, "count": items.len(), "includeCompleted": include_completed}),
    )
}

async fn rpc_queue_message(
    lane: &Arc<dyn AgentLane>,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let text = msg
        .get("message")
        .and_then(serde_json::Value::as_str)
        .filter(|text| !text.trim().is_empty())
        .ok_or_else(|| "queue_message requires a non-empty string `message`".to_string())?;
    let message = rpi_agent::message::AgentMessage::User(UserMessage::new(text, rpc_now_ms()));
    let queue = msg
        .get("deliverAs")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("followUp");
    let result = match queue {
        "steer" => lane.steer(message).await,
        "followUp" | "follow_up" => lane.follow_up(message).await,
        "nextTurn" | "next_run" => lane.next_run(message).await,
        other => return Err(format!("unknown queue kind: {other}")),
    }
    .map_err(|error| error.to_string())?;
    Ok(serde_json::json!({
        "accepted": true,
        "entryId": result.entry_id,
        "queue": queue,
    }))
}

async fn rpc_cancel_queued(
    lane: &Arc<dyn AgentLane>,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let entry_id = msg
        .get("entryId")
        .and_then(serde_json::Value::as_str)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| "cancel_queued requires `entryId`".to_string())?;
    let result = lane
        .cancel_queued(entry_id)
        .await
        .map_err(|error| error.to_string())?;
    Ok(serde_json::json!({
        "entryId": entry_id,
        "outcome": format!("{:?}", result.outcome).to_lowercase(),
    }))
}

async fn rpc_clear_queue(lane: &Arc<dyn AgentLane>) -> Result<serde_json::Value, String> {
    let result = lane
        .clear_queue()
        .await
        .map_err(|error| error.to_string())?;
    Ok(serde_json::json!({
        "cleared": result.steering.len() + result.follow_up.len(),
        "steering": result.steering,
        "followUp": result.follow_up,
    }))
}

async fn rpc_navigate(
    lane: &Arc<dyn AgentLane>,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let target_id = msg
        .get("targetId")
        .and_then(serde_json::Value::as_str)
        .filter(|value| !value.is_empty());
    if lane
        .snapshot()
        .await
        .map_err(|error| error.to_string())?
        .active
        .is_some()
    {
        return Err("cannot navigate while an operation is active".to_string());
    }
    let result = lane
        .navigate_tree(target_id, false, None, None)
        .await
        .map_err(|error| error.to_string())?;
    let (outcome, leaf_id, error) = match result.outcome {
        rpi_harness::agent_harness::NavigationOutcome::Completed { new_leaf_id, .. } => {
            ("completed", new_leaf_id, None)
        }
        rpi_harness::agent_harness::NavigationOutcome::Declined { leaf_id } => {
            ("declined", leaf_id, None)
        }
        rpi_harness::agent_harness::NavigationOutcome::Aborted { leaf_id } => {
            ("aborted", leaf_id, None)
        }
        rpi_harness::agent_harness::NavigationOutcome::Failed { leaf_id, error } => {
            ("failed", leaf_id, Some(error.message))
        }
    };
    Ok(serde_json::json!({
        "runId": result.run_id,
        "outcome": outcome,
        "leafId": leaf_id,
        "error": error,
    }))
}

/// How full the model's context is, measured the way compaction measures it.
///
/// The branch is projected into model input first (that is what applies a
/// compaction boundary), so the number matches what the next provider call will
/// actually send rather than how many messages the transcript happens to hold.
async fn rpc_context_usage(lane: &Arc<dyn AgentLane>, harness: &AgentHarness) -> serde_json::Value {
    use rpi_harness::compaction::{build_session_context, estimate_context_tokens};
    use rpi_harness::session::types::{BranchBounds, EntryOrder, EntryQuery};

    let entries = harness
        .find_entries_on_branch(
            &EntryQuery {
                order: Some(EntryOrder::OldestFirst),
                ..Default::default()
            },
            &BranchBounds::default(),
        )
        .await
        .unwrap_or_default();
    let estimate = estimate_context_tokens(&build_session_context(&entries).messages);
    let window = lane
        .get_model()
        .await
        .ok()
        .map(|model| model.context_window)
        .unwrap_or(0);
    let settings = harness.compaction_settings();
    let window = window as i64;
    let threshold = window - settings.reserve_tokens;
    let percent = if window > 0 {
        (estimate.tokens as f64) * 100.0 / (window as f64)
    } else {
        0.0
    };
    serde_json::json!({
        "tokens": estimate.tokens,
        "window": window,
        "threshold": threshold,
        "percent": (percent * 10.0).round() / 10.0,
        "reserveTokens": settings.reserve_tokens,
        "keepRecentTokens": settings.keep_recent_tokens,
        "compactionEnabled": settings.enabled,
        // False once a real provider usage report backs the number; until then
        // it is a character-based estimate.
        "estimated": estimate.last_usage_index.is_none(),
        "trailingTokens": estimate.trailing_tokens,
    })
}

/// The window `get_messages` returns, expressed as a slice range plus whether an
/// older page still exists. `before` is the index of the `beforeId` entry.
fn page_window(
    total: usize,
    limit: usize,
    before: Option<usize>,
) -> (std::ops::Range<usize>, bool) {
    match before {
        Some(index) => {
            let start = index.saturating_sub(limit);
            (start..index, start > 0)
        }
        None => {
            let skip = total.saturating_sub(limit);
            (skip..total, skip > 0)
        }
    }
}

/// Read-only snapshot of the current branch, oldest first. Messages are
/// projected with the same `AgentMessage` encoding the event stream uses, so a
/// client can render a transcript without understanding session entries.
async fn rpc_get_messages(
    lane: &Arc<dyn AgentLane>,
    harness: &AgentHarness,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    use rpi_harness::session::types::{BranchBounds, Entry, EntryOrder, EntryQuery};

    const DEFAULT_LIMIT: usize = 400;
    let limit = msg
        .get("limit")
        .and_then(|value| value.as_u64())
        .map(|value| value as usize)
        .unwrap_or(DEFAULT_LIMIT)
        .max(1);
    // `beforeId` pages backwards: the returned window ends immediately before
    // the entry with that id, so a client can walk a long branch one page at a
    // time instead of always re-reading the tail.
    let before_id = msg
        .get("beforeId")
        .and_then(|value| value.as_str())
        .filter(|value| !value.is_empty())
        .map(str::to_owned);
    let entries = harness
        .find_entries_on_branch(
            &EntryQuery {
                order: Some(EntryOrder::OldestFirst),
                ..Default::default()
            },
            &BranchBounds::default(),
        )
        .await
        .map_err(|error| error.to_string())?;
    let mut items: Vec<(String, serde_json::Value)> = Vec::new();
    for entry in entries {
        match entry {
            Entry::Message(entry) => {
                let mut value = serde_json::to_value(&entry.message).map_err(|e| e.to_string())?;
                // The session entry id, not the message's own id: it is what
                // `beforeId` keys on, and what makes rows stable across reloads.
                value["entryId"] = serde_json::json!(entry.base.id);
                items.push((entry.base.id, value));
            }
            // Compaction rewrites what the model sees, not the branch, so the
            // transcript keeps its messages. Marking the boundary is what lets a
            // client explain why the context suddenly shrank.
            Entry::Compaction(compaction) => items.push((
                compaction.base.id.clone(),
                serde_json::json!({
                    "role": "compaction",
                    "entryId": compaction.base.id,
                    "tokensBefore": compaction.tokens_before,
                    "retainedMessages": compaction.retained_tail.len(),
                    "timestamp": compaction.base.timestamp,
                }),
            )),
            _ => {}
        }
    }
    let total = items.len();
    let before_index = match &before_id {
        Some(before) => match items.iter().position(|(id, _)| id == before) {
            Some(index) => Some(index),
            None => return Err(format!("beforeId not found: {before}")),
        },
        None => None,
    };
    let (range, has_more) = page_window(total, limit, before_index);
    let window = items[range].to_vec();
    let first_id = window.first().map(|(id, _)| id.clone());
    let last_id = window.last().map(|(id, _)| id.clone());
    let messages = window
        .iter()
        .map(|(_, value)| value.clone())
        .collect::<Vec<_>>();
    // Read-only branch position: the leaf the snapshot ends on, and whether
    // recovery left an interrupted run that a client may want to surface.
    let leaf_id = lane.get_leaf_id().await.ok().flatten();
    let pending_resume = lane.has_pending_resume().await;
    Ok(serde_json::json!({
        "messages": messages,
        "total": total,
        "truncated": has_more,
        "limit": limit,
        "firstId": first_id,
        "lastId": last_id,
        "hasMore": has_more,
        "beforeId": before_id,
        "leafId": leaf_id,
        "pendingResume": pending_resume,
    }))
}

fn rpc_auth_provider_ids(model_catalog: &[rpi_ai::Model]) -> std::collections::BTreeSet<String> {
    let mut providers =
        std::collections::BTreeSet::from(["anthropic".to_string(), "openai".to_string()]);
    providers.extend(model_catalog.iter().map(|model| model.provider.clone()));
    if let Ok(models) = crate::config::load_models_config() {
        providers.extend(models.providers.keys().cloned());
    }
    providers
}

fn rpc_get_auth_status(
    model_catalog: &[rpi_ai::Model],
    oauth_snapshot: Option<&Arc<rpi_extensions::RegistrySnapshot>>,
) -> serde_json::Value {
    let store = crate::config::read_auth().unwrap_or_default();
    let models = crate::config::load_models_config().unwrap_or_default();
    let providers = rpc_auth_provider_ids(model_catalog)
        .into_iter()
        .map(|provider| {
            let credential = store.get(&provider);
            let source = crate::credentials::resolve(
                &provider,
                models.providers.get(&provider),
                &store,
                None,
            );
            let oauth = matches!(credential, Some(crate::config::Credential::Oauth { .. }));
            let oauth_available =
                oauth_snapshot.is_some_and(|snapshot| snapshot.oauth_provider(&provider).is_some());
            serde_json::json!({
                "provider": provider,
                "ready": source.source.is_present(),
                "source": source.source.as_json_str(),
                "oauth": oauth,
                "oauthAvailable": oauth_available,
            })
        })
        .collect::<Vec<_>>();
    serde_json::json!({"providers": providers})
}

fn rpc_oauth(
    snapshot: &Option<Arc<rpi_extensions::RegistrySnapshot>>,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let snapshot = snapshot
        .as_ref()
        .ok_or_else(|| "OAuth is unavailable without an extension provider".to_string())?;
    let provider = msg
        .get("provider")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| "oauth requires a provider".to_string())?;
    let action = msg
        .get("action")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| matches!(*value, "begin" | "exchange" | "refresh" | "revoke"))
        .ok_or_else(|| "oauth requires a valid action".to_string())?;
    let input = msg
        .get("input")
        .cloned()
        .unwrap_or_else(|| serde_json::json!({}));
    let raw = rpi_extensions::request_oauth(snapshot, provider, action, input)
        .map_err(|_| "OAuth provider request failed".to_string())?;
    let response = rpi_extensions::OAuthActionResponse::parse(raw)
        .map_err(|_| "OAuth provider returned an invalid response".to_string())?;
    match response.kind {
        rpi_extensions::OAuthResponseKind::Credential => {
            let credential = response
                .credential()
                .map_err(|_| "OAuth provider returned an invalid credential".to_string())?
                .ok_or_else(|| "OAuth provider returned no credential".to_string())?;
            crate::config::upsert_oauth_token(
                provider,
                credential.access,
                credential.refresh,
                credential.expires_at,
            )
            .map_err(|_| "OAuth credentials could not be saved".to_string())?;
            Ok(serde_json::json!({
                "provider": provider,
                "status": "authenticated"
            }))
        }
        rpi_extensions::OAuthResponseKind::Interaction => Ok(serde_json::json!({
            "provider": provider,
            "status": "interaction",
            "display": oauth_display(&response.payload)
        })),
        rpi_extensions::OAuthResponseKind::Success => Ok(serde_json::json!({
            "provider": provider,
            "status": "success"
        })),
        rpi_extensions::OAuthResponseKind::Error => {
            Err("OAuth provider rejected the request".to_string())
        }
    }
}

/// Keep provider-defined OAuth UI data deliberately narrow. In particular,
/// token-like fields never cross the RPC boundary, even if a plugin includes
/// them in an interaction payload by mistake.
fn oauth_display(payload: &serde_json::Value) -> serde_json::Value {
    let display = payload.get("display").unwrap_or(payload);
    let Some(object) = display.as_object() else {
        return serde_json::json!({});
    };
    let mut safe = serde_json::Map::new();
    for key in [
        "title",
        "url",
        "instructions",
        "user_code",
        "verification_uri",
    ] {
        if let Some(value) = object.get(key) {
            safe.insert(key.to_string(), value.clone());
        }
    }
    serde_json::Value::Object(safe)
}

async fn rpc_set_api_key(msg: &serde_json::Value) -> Result<serde_json::Value, String> {
    let provider = msg
        .get("provider")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| "set_api_key requires a provider".to_string())?;
    let api_key = msg
        .get("apiKey")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| "set_api_key requires a non-empty apiKey".to_string())?;
    crate::config::upsert_credential(
        provider,
        crate::config::Credential::ApiKey {
            key: Some(api_key.to_string()),
            env: None,
        },
    )
    .map_err(|error| error.to_string())?;
    Ok(serde_json::json!({
        "provider": provider,
        "ready": true,
        "source": "auth.json",
        "requiresRestart": true,
    }))
}

fn rpc_get_available_models(catalog: &[rpi_ai::Model]) -> serde_json::Value {
    let models = catalog
        .iter()
        .map(crate::rpc::protocol::model_descriptor)
        .collect::<Vec<_>>();
    serde_json::json!({"models": models})
}

async fn rpc_get_available_thinking_levels(lane: &Arc<dyn AgentLane>) -> serde_json::Value {
    let levels = lane
        .get_model()
        .await
        .map(|model| model.supported_thinking_levels())
        .unwrap_or_default();
    serde_json::json!({"levels": levels})
}

async fn rpc_get_available_tools(
    lane: &Arc<dyn AgentLane>,
    harness: &AgentHarness,
) -> serde_json::Value {
    let active = lane.get_active_tools().await.unwrap_or_default();
    let tools = harness
        .get_tools()
        .await
        .map(|tools| {
            tools
                .iter()
                .map(|tool| tool.tool.schema().name.clone())
                .collect::<Vec<_>>()
        })
        .unwrap_or_else(|_| active.clone());
    serde_json::json!({"tools": tools, "activeTools": active})
}

async fn rpc_set_model(
    lane: &Arc<dyn AgentLane>,
    catalog: &[rpi_ai::Model],
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let id = msg
        .get("modelId")
        .or_else(|| msg.get("model"))
        .and_then(|v| v.as_str())
        .ok_or("set_model requires `modelId`")?;
    let provider = msg.get("provider").and_then(|v| v.as_str());
    let model = catalog
        .iter()
        .find(|m| {
            m.id.eq_ignore_ascii_case(id)
                && provider.is_none_or(|provider| m.provider.eq_ignore_ascii_case(provider))
        })
        .cloned()
        .ok_or_else(|| format!("unknown model: {id}"))?;
    lane.set_model(model).await.map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"modelId": id, "provider": provider}))
}

async fn rpc_set_thinking_level(
    lane: &Arc<dyn AgentLane>,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let value = msg
        .get("level")
        .or_else(|| msg.get("thinkingLevel"))
        .ok_or("set_thinking_level requires `level`")?;
    let level: rpi_ai::types::ThinkingLevel =
        serde_json::from_value(value.clone()).map_err(|_| {
            "invalid thinking level (off|minimal|low|medium|high|xhigh|max)".to_string()
        })?;
    lane.set_thinking_level(level)
        .await
        .map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"thinkingLevel": level}))
}

async fn rpc_set_active_tools(
    lane: &Arc<dyn AgentLane>,
    msg: &serde_json::Value,
) -> Result<serde_json::Value, String> {
    let tools = msg
        .get("tools")
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(str::to_owned))
                .collect::<Vec<_>>()
        })
        .ok_or("set_active_tools requires a `tools` array")?;
    lane.set_active_tools(tools.clone())
        .await
        .map_err(|e| e.to_string())?;
    Ok(serde_json::json!({"activeTools": tools}))
}

/// Stable JSON projection for the fine-grained agent lifecycle stream.
///
/// Delegates to the shared [`crate::remote::protocol::RemoteEvent`] so the
/// server and the `--connect` client agree on the wire shape by construction.
fn agent_event_json(event: &AgentEvent) -> serde_json::Value {
    crate::rpc::events::project(event)
}

/// Emit a single harness event as a JSON line on stdout. Mirrors the TS
/// `toJsonEvent` projection (here a lossy but stable shape: `type` + the event
/// payload's key fields).
fn emit_json_event(event: &HarnessEvent) {
    let line = match event {
        HarnessEvent::CompactionProgress(e) => {
            serde_json::json!({ "type": "compaction_progress", "lane": e.lane, "manual": e.manual, "active": e.active })
        }
        HarnessEvent::RunStart(e) => serde_json::json!({
            "type": "run_start",
            "lane": e.lane,
            "runId": e.run_id,
        }),
        HarnessEvent::RunEnd(e) => serde_json::json!({
            "type": "run_end",
            "lane": e.lane,
            "runId": e.run_id,
            "outcome": run_end_outcome_str(e.outcome),
            "leafId": e.leaf_id,
        }),
    };
    println!("{line}");
}

fn run_end_outcome_str(o: RunEndOutcome) -> &'static str {
    match o {
        RunEndOutcome::Completed => "completed",
        RunEndOutcome::Aborted => "aborted",
        RunEndOutcome::Failed => "failed",
    }
}

/// `interactive` mode: uses TUI if terminal supports it, falls back to minimal REPL.
///
/// `event_rx` carries the live `AgentEvent` stream (drained by the TUI to
/// render streaming responses). The REPL fallback ignores it.
///
/// `model_catalog` is the resolved provider's full model list, passed through
/// so the TUI's `/model` selector can display available models (read-only —
/// v1 does not switch models mid-session; see the initial port notes (retired)).
pub async fn interactive(
    harness: &AgentHarness,
    event_rx: Option<tokio::sync::broadcast::Receiver<rpi_agent::AgentEvent>>,
    args: &Args,
    model_catalog: Vec<rpi_ai::Model>,
    initial: Option<String>,
    extra_messages: &[String],
    initial_images: Vec<ImageContent>,
    theme: Option<&str>,
    no_themes: bool,
    reload_context: &crate::session::ReloadContext,
) -> i32 {
    // ---- Session lifecycle (P1): BeforeTuiStart ----
    // `BeforeTuiStart`: extensions may prepare (connect a server, load a
    // resource) before the interactive UI initializes. Runs with a per-event
    // timeout; a handler returning `EVENT_HANDLER_ABORT` **vetoes** startup —
    // we print the reason and exit without entering the TUI. No-op when no
    // extension subscribes.
    if let Some(reason) = crate::session::dispatch_session_event_async(
        reload_context,
        rpi_plugin_sdk::EventTag::BeforeTuiStart,
    )
    .await
    {
        eprintln!("[rpi] startup vetoed by extension: {reason}");
        return crate::app::EXIT_VETOED;
    }

    // Check if TUI is supported
    let force_tui = std::env::var("RPI_FORCE_TUI")
        .map(|v| v == "1")
        .unwrap_or(false);
    let code = if force_tui || crate::interactive_tui::is_tui_supported() {
        // Use TUI-based interactive mode
        crate::interactive_tui::interactive_tui(
            harness,
            event_rx,
            args,
            model_catalog,
            initial,
            extra_messages,
            initial_images,
            theme,
            no_themes,
            reload_context,
        )
        .await
    } else {
        // Fall back to simple REPL
        interactive_repl(harness, args, initial, extra_messages, initial_images).await
    };

    // `SessionShutdown`: the interactive session closed (TUI/REPL returned) —
    // extensions release resources, disconnect, persist state. Fired after the
    // UI returns so it always runs (even on early-return paths inside the TUI).
    // A veto here is **advisory** (the session is already closing) — warn and
    // continue.
    if let Some(reason) = crate::session::dispatch_session_event_async(
        reload_context,
        rpi_plugin_sdk::EventTag::SessionShutdown,
    )
    .await
    {
        tracing::warn!(
            "[rpi] extension vetoed SessionShutdown (ignored, session closing): {reason}"
        );
    }

    code
}

/// Simple REPL-based interactive mode (fallback for non-TTY environments).
pub async fn interactive_repl(
    harness: &AgentHarness,
    #[allow(unused_variables)] args: &Args,
    initial: Option<String>,
    extra_messages: &[String],
    initial_images: Vec<ImageContent>,
) -> i32 {
    // Debug: confirm we entered REPL mode
    let lane: Arc<dyn AgentLane> = harness.lane("main");
    let stdin = std::io::stdin();
    let is_tty = stdin.is_terminal();

    if is_tty {
        println!(
            "rpi interactive (v1 minimal REPL). Type /exit to quit, /abort to cancel a run.\n"
        );
    }

    // Run the initial prompt + extra messages first (same as print mode).
    let mut prompts: Vec<String> = Vec::new();
    if let Some(init) = initial {
        prompts.push(init);
    }
    for m in extra_messages {
        prompts.push(m.clone());
    }
    let mut images = initial_images;
    for prompt in prompts {
        if let Err(code) = run_one(&lane, &prompt, std::mem::take(&mut images)).await {
            return code;
        }
    }

    // Then read lines from stdin until EOF / `/exit`.
    let mut line = String::new();
    loop {
        if is_tty {
            print!("> ");
            let _ = std::io::stdout().flush();
        }
        line.clear();
        match stdin.lock().read_line(&mut line) {
            Ok(0) => break, // EOF
            Ok(_) => {}
            Err(_) => break,
        }
        let trimmed = line.trim();
        if trimmed.is_empty() {
            continue;
        }
        if trimmed == "/exit" || trimmed == "/quit" {
            break;
        }
        if trimmed == "/abort" {
            let _ = lane.abort().await;
            eprintln!("(aborted)");
            continue;
        }
        if let Err(code) = run_one(&lane, trimmed, Vec::new()).await {
            return code;
        }
    }
    0
}

/// Run a single prompt in interactive mode, printing the assistant reply (or
/// the error). Returns `Ok(())` on success/soft-failure, `Err(exit_code)` on a
/// hard rejection.
async fn run_one(
    lane: &Arc<dyn AgentLane>,
    prompt: &str,
    images: Vec<ImageContent>,
) -> Result<(), i32> {
    match lane.prompt_text(prompt, images).await {
        Ok(result) => {
            match &result.outcome {
                HarnessRunOutcome::Completed { final_message, .. }
                | HarnessRunOutcome::Aborted { final_message, .. } => {
                    let text = assistant_text(final_message);
                    if !text.is_empty() {
                        println!("{text}");
                    }
                }
                HarnessRunOutcome::Failed {
                    error,
                    final_message,
                    ..
                } => {
                    if let Some(m) = final_message {
                        if let Some(em) = &m.error_message {
                            eprintln!("error: {em}");
                        }
                    }
                    eprintln!("run failed: {error:?}");
                }
                HarnessRunOutcome::Suspended { .. } => {
                    eprintln!("run suspended (deferred) — resume not supported in v1");
                }
            }
            Ok(())
        }
        Err(e) => {
            eprintln!("prompt rejected: {e}");
            Err(1)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rpi_agent::events::AgentEvent;
    use rpi_agent::types::AgentToolResult;
    use rpi_ai::types::{
        AssistantMessage, Content, StopReason, TextContent, TextContentType, Usage,
    };
    use rpi_harness::session::types::OperationError;

    #[test]
    fn oauth_display_drops_token_like_fields() {
        let display = oauth_display(&serde_json::json!({
            "display": {
                "title": "Sign in",
                "url": "https://example.test/authorize",
                "instructions": ["Paste the code"],
                "access_token": "secret-access",
                "refresh_token": "secret-refresh",
            }
        }));
        assert_eq!(display["title"], "Sign in");
        assert!(display.get("access_token").is_none());
        assert!(display.get("refresh_token").is_none());
    }

    #[derive(Clone, Default)]
    struct RpcOutput(Arc<Mutex<Vec<u8>>>);

    impl Write for RpcOutput {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.0.lock().unwrap().extend_from_slice(bytes);
            Ok(bytes.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl RpcOutput {
        fn messages(&self) -> Vec<serde_json::Value> {
            String::from_utf8(self.0.lock().unwrap().clone())
                .unwrap()
                .lines()
                .map(|line| serde_json::from_str(line).unwrap())
                .collect()
        }

        async fn wait_for(
            &self,
            predicate: impl Fn(&serde_json::Value) -> bool,
        ) -> serde_json::Value {
            tokio::time::timeout(std::time::Duration::from_secs(3), async {
                loop {
                    if let Some(message) = self.messages().into_iter().find(&predicate) {
                        return message;
                    }
                    tokio::time::sleep(std::time::Duration::from_millis(1)).await;
                }
            })
            .await
            .expect("RPC message not received")
        }
    }

    async fn rpc_test_harness(
        text: &str,
        tokens_per_second: f64,
    ) -> (AgentHarness, Arc<rpi_ai::providers::faux::FauxProvider>) {
        let provider = rpi_ai::providers::faux::FauxProvider::new(
            rpi_ai::providers::faux::FauxScript::new()
                .with_text(text)
                .with_tokens_per_second(tokens_per_second),
        );
        let options = rpi_harness::types::AgentHarnessOptions {
            model: provider.default_model().clone(),
            models: vec![provider.clone()],
            ..Default::default()
        };
        (AgentHarness::create(options).await.unwrap(), provider)
    }

    fn start_test_rpc(
        harness: AgentHarness,
        ui: rpi_extensions::UiDialogMailbox,
    ) -> (
        tokio::io::DuplexStream,
        RpcOutput,
        tokio::task::JoinHandle<i32>,
    ) {
        let (client, input) = tokio::io::duplex(4096);
        let output = RpcOutput::default();
        let captured = output.clone();
        let task = tokio::spawn(async move {
            rpc_with_io(
                &harness,
                None,
                vec![],
                ui,
                None,
                tokio::io::BufReader::new(input),
                captured,
            )
            .await
        });
        (client, output, task)
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_eof_waits_for_accepted_prompt() {
        use tokio::io::AsyncWriteExt;
        let (harness, _) = rpc_test_harness("completed", 100.0).await;
        let ui = rpi_extensions::UiDialogMailbox::new();
        let (mut client, output, task) = start_test_rpc(harness, ui.clone());
        client
            .write_all(b"{\"type\":\"prompt\",\"id\":1,\"message\":\"test\"}\n")
            .await
            .unwrap();
        client.shutdown().await.unwrap();
        assert_eq!(
            tokio::time::timeout(std::time::Duration::from_secs(3), task)
                .await
                .unwrap()
                .unwrap(),
            0
        );
        let response = output
            .messages()
            .into_iter()
            .find(|m| m["id"] == 1)
            .unwrap();
        assert_eq!(response["command"], "prompt");
        assert_eq!(response["data"]["accepted"], true);
        assert!(output.messages().iter().any(|message| {
            message["type"] == "agent_settled" && message["outcome"] == "completed"
        }));
        assert!(!ui.is_attached());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_compaction_settlement_identifies_its_durable_operation() {
        let (harness, _) = rpc_test_harness("unused", 0.0).await;
        let output = RpcOutput::default();
        let code = rpc_with_io(
            &harness,
            None,
            vec![],
            rpi_extensions::UiDialogMailbox::new(),
            None,
            tokio::io::BufReader::new(&b"{\"type\":\"compact\",\"id\":1}\n"[..]),
            output.clone(),
        )
        .await;
        assert_eq!(code, 0);
        let messages = output.messages();
        let settled = messages
            .iter()
            .find(|message| message["type"] == "agent_settled")
            .unwrap();
        assert_eq!(settled["outcome"], "declined");
        let run_id = settled["runId"]
            .as_str()
            .expect("compaction settlement needs its durable run id");
        let records = harness
            .session()
            .find_records(&Default::default())
            .await
            .unwrap();
        assert!(records.iter().any(|record| matches!(record,
            rpi_harness::session::types::LaneRecord::OperationFinished(finished)
                if finished.run_id == run_id)));
    }

    #[tokio::test]
    async fn rpc_eof_drains_queued_final_events() {
        let harness = AgentHarness::create(Default::default()).await.unwrap();
        let (tx, rx) = tokio::sync::broadcast::channel(256);
        for _ in 0..100 {
            tx.send(AgentEvent::AgentStart).unwrap();
        }
        tx.send(AgentEvent::AgentEnd { messages: vec![] }).unwrap();
        let output = RpcOutput::default();
        let code = rpc_with_io(
            &harness,
            Some(rx),
            vec![],
            rpi_extensions::UiDialogMailbox::new(),
            None,
            tokio::io::BufReader::new(&b""[..]),
            output.clone(),
        )
        .await;
        assert_eq!(code, 0);
        let messages = output.messages();
        assert_eq!(
            messages.len(),
            102,
            "ready plus every queued event must be flushed"
        );
        assert_eq!(messages.last().unwrap()["type"], "agent_end");
    }

    struct BackpressuredOutput {
        entered: Arc<std::sync::atomic::AtomicBool>,
        release: Arc<std::sync::atomic::AtomicBool>,
        output: RpcOutput,
    }

    impl Write for BackpressuredOutput {
        fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
            self.entered
                .store(true, std::sync::atomic::Ordering::SeqCst);
            while !self.release.load(std::sync::atomic::Ordering::SeqCst) {
                std::thread::sleep(std::time::Duration::from_millis(1));
            }
            self.output.write(bytes)
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_output_backpressure_is_bounded_and_keeps_workers_responsive() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let release = Arc::new(AtomicBool::new(false));
        struct ReleaseOnDrop(Arc<AtomicBool>);
        impl Drop for ReleaseOnDrop {
            fn drop(&mut self) {
                self.0.store(true, Ordering::SeqCst);
            }
        }
        let _release = ReleaseOnDrop(release.clone());
        let entered = Arc::new(AtomicBool::new(false));
        let output = RpcOutput::default();
        let (writer, task, _) = start_rpc_writer(BackpressuredOutput {
            entered: entered.clone(),
            release: release.clone(),
            output: output.clone(),
        });
        write_line(&writer, &serde_json::json!({"id": 0})).await;
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            while !entered.load(Ordering::SeqCst) {
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        let producer_writer = writer.clone();
        let producer = tokio::spawn(async move {
            for id in 1..=100 {
                write_line(&producer_writer, &serde_json::json!({"id": id})).await;
            }
        });
        tokio::time::timeout(
            std::time::Duration::from_millis(150),
            tokio::time::sleep(std::time::Duration::from_millis(20)),
        )
        .await
        .unwrap();
        assert!(
            !producer.is_finished(),
            "the bounded queue must apply backpressure"
        );
        release.store(true, Ordering::SeqCst);
        producer.await.unwrap();
        drop(writer);
        task.await.unwrap().unwrap();
        let messages = output.messages();
        assert_eq!(messages.len(), 101);
        for (index, message) in messages.iter().enumerate() {
            assert_eq!(message["id"], index);
        }
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_completion_response_follows_final_event_under_backpressure() {
        use std::sync::atomic::{AtomicBool, Ordering};
        let (harness, _) = rpc_test_harness("completed", 0.0).await;
        let (emitter, events) = rpi_agent::events::BroadcastEmitter::new(256);
        harness
            .set_agent_emitter(Some(Arc::new(emitter)))
            .await
            .unwrap();
        let output = RpcOutput::default();
        let release = Arc::new(AtomicBool::new(false));
        let release_writer = release.clone();
        let release_thread = std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_millis(50));
            release_writer.store(true, Ordering::SeqCst);
        });
        let code = rpc_with_io(
            &harness,
            Some(events),
            vec![],
            rpi_extensions::UiDialogMailbox::new(),
            None,
            tokio::io::BufReader::new(
                &b"{\"type\":\"prompt\",\"id\":1,\"message\":\"test\"}\n"[..],
            ),
            BackpressuredOutput {
                entered: Arc::new(AtomicBool::new(false)),
                release,
                output: output.clone(),
            },
        )
        .await;
        release_thread.join().unwrap();
        assert_eq!(code, 0);
        let messages = output.messages();
        let end = messages
            .iter()
            .position(|message| message["type"] == "agent_end")
            .unwrap();
        let settled = messages
            .iter()
            .position(|message| message["type"] == "agent_settled")
            .unwrap();
        assert!(end < settled);
        let run_id = messages[settled]["runId"].as_str().unwrap();
        assert!(!run_id.is_empty(), "settlement identifies its durable run");
        let records = harness
            .session()
            .find_records(&Default::default())
            .await
            .unwrap();
        assert!(records.iter().any(|record| matches!(record,
            rpi_harness::session::types::LaneRecord::OperationFinished(finished)
                if finished.run_id == run_id)));
        assert!(messages.iter().any(|message| {
            message["type"] == "response" && message["data"]["accepted"] == true
        }));
        assert!(messages.iter().any(|message| {
            message["type"] == "agent_settled" && message["outcome"] == "completed"
        }));
    }

    #[tokio::test]
    async fn rpc_output_failure_closes_without_waiting_for_more_input() {
        struct BrokenOutput;
        impl Write for BrokenOutput {
            fn write(&mut self, _: &[u8]) -> std::io::Result<usize> {
                Err(std::io::Error::new(
                    std::io::ErrorKind::BrokenPipe,
                    "closed client output",
                ))
            }
            fn flush(&mut self) -> std::io::Result<()> {
                Ok(())
            }
        }
        let harness = AgentHarness::create(Default::default()).await.unwrap();
        let (_client, input) = tokio::io::duplex(4096);
        let ui = rpi_extensions::UiDialogMailbox::new();
        let code = tokio::time::timeout(
            std::time::Duration::from_secs(2),
            rpc_with_io(
                &harness,
                None,
                vec![],
                ui.clone(),
                None,
                tokio::io::BufReader::new(input),
                BrokenOutput,
            ),
        )
        .await
        .unwrap();
        assert_eq!(code, 1);
        assert!(!ui.is_attached());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_stop_aborts_and_joins_active_prompt() {
        use tokio::io::AsyncWriteExt;
        let (harness, provider) = rpc_test_harness("still streaming the response", 20.0).await;
        let lane = harness.lane("main");
        let (mut client, output, task) =
            start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
        client
            .write_all(b"{\"type\":\"prompt\",\"id\":1,\"message\":\"test\"}\n")
            .await
            .unwrap();
        tokio::time::timeout(std::time::Duration::from_secs(3), async {
            while provider
                .state()
                .call_count
                .load(std::sync::atomic::Ordering::SeqCst)
                == 0
            {
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
        client
            .write_all(b"{\"type\":\"stop\",\"id\":2}\n")
            .await
            .unwrap();
        assert_eq!(
            tokio::time::timeout(std::time::Duration::from_secs(3), task)
                .await
                .unwrap()
                .unwrap(),
            0
        );
        let messages = output.messages();
        assert!(messages.iter().any(|message| {
            message["type"] == "agent_settled"
                && (message["outcome"] == "aborted" || message["outcome"] == "failed")
        }));
        assert_eq!(
            messages.iter().find(|m| m["id"] == 2).unwrap()["data"]["stopped"],
            true
        );
        assert!(
            lane.abort().await.is_err(),
            "RPC returned with an active lane"
        );
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_immediate_stop_cancels_prompt_before_or_after_lane_start() {
        use tokio::io::AsyncWriteExt;
        let (harness, _) = rpc_test_harness("not completed", 20.0).await;
        let lane = harness.lane("main");
        let (mut client, output, task) =
            start_test_rpc(harness, rpi_extensions::UiDialogMailbox::new());
        client.write_all(b"{\"type\":\"prompt\",\"id\":1,\"message\":\"test\"}\n{\"type\":\"stop\",\"id\":2}\n").await.unwrap();
        assert_eq!(
            tokio::time::timeout(std::time::Duration::from_secs(3), task)
                .await
                .unwrap()
                .unwrap(),
            0
        );
        let messages = output.messages();
        assert!(messages.iter().any(|message| {
            message["type"] == "agent_settled"
                && (message["outcome"] == "aborted" || message["outcome"] == "failed")
        }));
        assert!(lane.abort().await.is_err());
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_dialog_answers_and_ping_are_read_while_prompt_runs() {
        use tokio::io::AsyncWriteExt;
        let (harness, _) =
            rpc_test_harness("the streamed response finishes after the dialog", 30.0).await;
        let ui = rpi_extensions::UiDialogMailbox::new();
        let (mut client, output, task) = start_test_rpc(harness, ui.clone());
        output.wait_for(|m| m["type"] == "ready").await;
        client
            .write_all(b"{\"type\":\"prompt\",\"id\":1,\"message\":\"test\"}\n")
            .await
            .unwrap();
        ui.handle(serde_json::json!({"requestId":"approval", "toolCallId":"call", "ui":{}}))
            .unwrap();
        output.wait_for(|m| m["type"] == "ui_dialog_request").await;
        client.write_all(b"{\"type\":\"ui_dialog_response\",\"requestId\":\"approval\",\"answer\":true}\n{\"type\":\"ping\",\"id\":2}\n").await.unwrap();
        output.wait_for(|m| m["id"] == 2).await;
        assert_eq!(ui.poll("approval").unwrap()["answer"], true);
        output
            .wait_for(|m| m["type"] == "ui_dialog_closed" && m["requestId"] == "approval")
            .await;
        client.shutdown().await.unwrap();
        assert_eq!(
            tokio::time::timeout(std::time::Duration::from_secs(3), task)
                .await
                .unwrap()
                .unwrap(),
            0
        );
        assert!(output.messages().iter().any(|message| {
            message["type"] == "agent_settled" && message["outcome"] == "completed"
        }));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn rpc_notifies_client_when_an_approval_is_cancelled() {
        use tokio::io::AsyncWriteExt;
        let harness = AgentHarness::create(Default::default()).await.unwrap();
        let ui = rpi_extensions::UiDialogMailbox::new();
        let (mut client, output, task) = start_test_rpc(harness, ui.clone());
        output.wait_for(|m| m["type"] == "ready").await;
        ui.handle(serde_json::json!({"requestId":"cancelled", "toolCallId":"c", "ui":{}}))
            .unwrap();
        output.wait_for(|m| m["type"] == "ui_dialog_request").await;
        ui.cancel_tool_call("c");
        output
            .wait_for(|m| m["type"] == "ui_dialog_closed" && m["requestId"] == "cancelled")
            .await;
        // The notification must not consume the cancellation meant for the plugin.
        assert_eq!(ui.poll("cancelled").unwrap()["status"], "cancelled");
        client.shutdown().await.unwrap();
        assert_eq!(task.await.unwrap(), 0);
    }

    #[tokio::test]
    async fn rpc_accepts_native_dialog_responses_without_consuming_plugin_answers() {
        use crate::remote::protocol::RemoteCommand;
        use tokio::io::AsyncWriteExt;
        let harness = AgentHarness::create(Default::default()).await.unwrap();
        let ui = rpi_extensions::UiDialogMailbox::new();
        let (mut client, output, task) = start_test_rpc(harness, ui.clone());
        output.wait_for(|m| m["type"] == "ready").await;
        for (request_id, answer, response_id) in [
            (
                "answered",
                Some(serde_json::json!({"values":["No"],"kind":"selector"})),
                5,
            ),
            ("cancelled", None, 6),
        ] {
            ui.handle(serde_json::json!({"requestId":request_id,"toolCallId":request_id,"ui":{}}))
                .unwrap();
            output
                .wait_for(|m| m["type"] == "ui_dialog_request" && m["requestId"] == request_id)
                .await;
            let command = RemoteCommand::UiDialogResponse {
                request_id: request_id.into(),
                cancelled: answer.is_none(),
                answer,
            }
            .with_id(response_id);
            client
                .write_all(format!("{command}\n").as_bytes())
                .await
                .unwrap();
            let ack = output.wait_for(|m| m["id"] == response_id).await;
            assert_eq!(ack["data"]["accepted"], true);
            let result = ui.poll(request_id).unwrap();
            if request_id == "answered" {
                assert_eq!(result["answer"]["values"][0], "No");
            } else {
                assert_eq!(result["status"], "cancelled");
            }
        }
        client.shutdown().await.unwrap();
        assert_eq!(task.await.unwrap(), 0);
    }

    fn assistant(text: &str, stop: StopReason) -> AssistantMessage {
        AssistantMessage {
            role: rpi_ai::types::AssistantRole,
            content: vec![Content::Text(TextContent {
                kind: TextContentType,
                text: text.into(),
                text_signature: None,
            })],
            api: rpi_ai::Api::AnthropicMessages,
            provider: "anthropic".into(),
            model: "claude-sonnet-5".into(),
            response_model: None,
            response_id: None,
            usage: Usage::zero(),
            stop_reason: stop,
            deferred: None,
            error_message: None,
            raw_stop_reason: None,
            end_turn: None,
            timestamp: 0,
        }
    }

    #[test]
    fn assistant_text_concatenates_text_blocks() {
        let m = assistant("hello", StopReason::Stop);
        assert_eq!(assistant_text(&m), "hello");
    }

    #[test]
    fn outcome_exit_code_maps_failed_aborted_to_1() {
        let failed = HarnessRunOutcome::Failed {
            leaf_id: "l".into(),
            error: OperationError {
                code: "boom".into(),
                message: "boom".into(),
            },
            final_entry_id: None,
            final_message: None,
        };
        assert_eq!(outcome_exit_code(&failed), 1);
        let completed = HarnessRunOutcome::Completed {
            leaf_id: "l".into(),
            final_entry_id: "e".into(),
            final_message: assistant("ok", StopReason::Stop),
        };
        assert_eq!(outcome_exit_code(&completed), 0);
    }

    #[test]
    fn run_end_outcome_str_roundtrip() {
        assert_eq!(run_end_outcome_str(RunEndOutcome::Completed), "completed");
        assert_eq!(run_end_outcome_str(RunEndOutcome::Aborted), "aborted");
        assert_eq!(run_end_outcome_str(RunEndOutcome::Failed), "failed");
    }

    #[test]
    fn agent_event_projection_keeps_terminal_and_tool_payloads() {
        let end = agent_event_json(&AgentEvent::AgentEnd { messages: vec![] });
        assert_eq!(end["type"], "agent_end");
        assert_eq!(end["messages"], serde_json::json!([]));

        let tool = agent_event_json(&AgentEvent::ToolExecutionEnd {
            tool_call_id: "call-1".into(),
            tool_name: "read".into(),
            result: AgentToolResult::text("hello"),
            is_error: false,
        });
        assert_eq!(tool["type"], "tool_execution_end");
        assert_eq!(tool["result"]["content"][0]["text"], "hello");
        assert_eq!(tool["result"]["terminate"], false);

        let retry = agent_event_json(&AgentEvent::RetryScheduled {
            attempt: 3,
            max_retries: 10,
            delay_ms: 8_000,
            error: "503 service unavailable".into(),
        });
        assert_eq!(retry["type"], "retry_scheduled");
        assert_eq!(retry["attempt"], 3);
        assert_eq!(retry["maxRetries"], 10);
        assert_eq!(retry["delayMs"], 8_000);
        assert_eq!(retry["error"], "503 service unavailable");
    }
}

#[cfg(test)]
mod page_window_tests {
    use super::page_window;

    #[test]
    fn tail_is_kept_without_before_id() {
        // 12 items, limit 5 -> keep the last 5, more behind.
        assert_eq!(page_window(12, 5, None), (7..12, true));
        // Fewer items than the limit -> everything, nothing behind.
        assert_eq!(page_window(3, 5, None), (0..3, false));
    }

    #[test]
    fn before_id_opens_the_window_immediately_before_it() {
        // Page back from index 10 with limit 4 -> [6,10), more behind.
        assert_eq!(page_window(12, 4, Some(10)), (6..10, true));
        // Same, but reaching the very start -> no more behind.
        assert_eq!(page_window(12, 10, Some(10)), (0..10, false));
    }

    #[test]
    fn limit_larger_than_the_branch_never_underflows() {
        assert_eq!(page_window(5, 100, Some(2)), (0..2, false));
        assert_eq!(page_window(5, 100, None), (0..5, false));
    }
}