rsclaw 2026.4.20

AI Agent Engine Compatible with OpenClaw
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
//! ACP (Agent Client Protocol) client implementation
//!
//! Key insight from debugging:
//! - tokio's Lines iterator can miss wake-ups when used in a shared task
//! - Solution: dedicated subprocess task with manual polling
//!
//! Full ACP spec: https://agentclientprotocol.com

use std::{collections::HashMap, process::Stdio, sync::Arc};

use anyhow::{Context, Result};
use futures::future::BoxFuture;
use tokio::{
    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
    process::{Child, Command},
    sync::{Mutex, broadcast, mpsc},
    time::{Duration, timeout},
};

use crate::acp::{methods, notification::*, types::*};

pub const ACP_TIMEOUT: Duration = Duration::from_secs(60);
pub const LONG_TIMEOUT: Duration = Duration::from_secs(300);

// ---------------------------------------------------------------------------
// Callback Handlers (Agent → Client)
// ---------------------------------------------------------------------------

/// Handler for Agent -> Client requests (permissions, fs, terminal).
/// Uses BoxFuture for dyn-safety (used as `dyn AcpCallbackHandler`).
pub trait AcpCallbackHandler: Send + Sync {
    /// Handle permission request from agent
    fn handle_request_permission(
        &self,
        session_id: &SessionId,
        tool_call_id: &str,
        options: Vec<PermissionOption>,
    ) -> BoxFuture<'_, RequestPermissionOutcome>;

    /// Handle file read request from agent
    fn handle_read_text_file(&self, session_id: &SessionId, path: &str) -> BoxFuture<'_, Result<String>>;

    /// Handle file write request from agent
    fn handle_write_text_file(
        &self,
        session_id: &SessionId,
        path: &str,
        contents: &str,
    ) -> BoxFuture<'_, Result<()>>;

    /// Handle terminal create request from agent
    fn handle_terminal_create(
        &self,
        session_id: &SessionId,
        command: Option<&str>,
        args: Option<Vec<String>>,
    ) -> BoxFuture<'_, Result<String>>;

    /// Handle terminal output request from agent
    fn handle_terminal_output(
        &self,
        session_id: &SessionId,
        terminal_id: &str,
    ) -> BoxFuture<'_, Result<TerminalOutputResponse>>;

    /// Handle terminal kill request from agent
    fn handle_terminal_kill(&self, session_id: &SessionId, terminal_id: &str) -> BoxFuture<'_, Result<()>>;

    /// Handle terminal release request from agent
    fn handle_terminal_release(
        &self,
        session_id: &SessionId,
        terminal_id: &str,
    ) -> BoxFuture<'_, Result<()>>;

    /// Handle terminal wait for exit request from agent
    fn handle_terminal_wait_for_exit(
        &self,
        session_id: &SessionId,
        terminal_id: &str,
    ) -> BoxFuture<'_, Result<Option<i32>>>;
}

/// Default callback handler that auto-approves everything.
// TODO(H-21): DefaultAcpHandler and DefaultAcpHandlerWithTerminal share nearly
// identical handle_request_permission / handle_read_text_file / handle_write_text_file
// implementations.  Extract a shared helper or blanket impl to reduce duplication.
pub struct DefaultAcpHandler;

impl AcpCallbackHandler for DefaultAcpHandler {
    fn handle_request_permission(
        &self,
        _session_id: &SessionId,
        _tool_call_id: &str,
        options: Vec<PermissionOption>,
    ) -> BoxFuture<'_, RequestPermissionOutcome> {
        Box::pin(async move {
            // Log all options for debugging
            tracing::debug!(
                options = ?options.iter().map(|o| (&o.option_id, &o.kind)).collect::<Vec<_>>(),
                "handle_request_permission: received options"
            );

            // Auto-approve any non-reject option (more lenient for different agent implementations)
            for opt in options {
                // Match any "allow" type option
                if matches!(
                    opt.kind,
                    PermissionOptionKind::AllowOnce | PermissionOptionKind::AllowAlways
                ) {
                    tracing::debug!(
                        option_id = %opt.option_id,
                        kind = ?opt.kind,
                        "handle_request_permission: auto-approving"
                    );
                    return RequestPermissionOutcome::Selected {
                        option_id: opt.option_id,
                    };
                }
                // Also approve if option_id contains "allow" or "accept" (fallback for non-standard formats)
                if opt.option_id.contains("allow") || opt.option_id.contains("accept") {
                    tracing::debug!(
                        option_id = %opt.option_id,
                        "handle_request_permission: auto-approving by option_id pattern"
                    );
                    return RequestPermissionOutcome::Selected {
                        option_id: opt.option_id,
                    };
                }
            }
            tracing::warn!("handle_request_permission: no matching allow option found, cancelling");
            RequestPermissionOutcome::Cancelled
        })
    }

    fn handle_read_text_file(&self, _session_id: &SessionId, path: &str) -> BoxFuture<'_, Result<String>> {
        let path = path.to_owned();
        Box::pin(async move {
            tokio::fs::read_to_string(&path)
                .await
                .context("Failed to read file")
        })
    }

    fn handle_write_text_file(
        &self,
        _session_id: &SessionId,
        path: &str,
        contents: &str,
    ) -> BoxFuture<'_, Result<()>> {
        let path = path.to_owned();
        let contents = contents.to_owned();
        Box::pin(async move {
            tokio::fs::write(&path, &contents)
                .await
                .context("Failed to write file")
        })
    }

    fn handle_terminal_create(
        &self,
        _session_id: &SessionId,
        _command: Option<&str>,
        _args: Option<Vec<String>>,
    ) -> BoxFuture<'_, Result<String>> {
        Box::pin(async move {
            Err(anyhow::anyhow!(
                "Terminal operations not implemented in DefaultAcpHandler. Implement custom AcpCallbackHandler to enable terminal support."
            ))
        })
    }

    fn handle_terminal_output(
        &self,
        _session_id: &SessionId,
        _terminal_id: &str,
    ) -> BoxFuture<'_, Result<TerminalOutputResponse>> {
        Box::pin(async move {
            Err(anyhow::anyhow!(
                "Terminal operations not implemented in DefaultAcpHandler"
            ))
        })
    }

    fn handle_terminal_kill(
        &self,
        _session_id: &SessionId,
        _terminal_id: &str,
    ) -> BoxFuture<'_, Result<()>> {
        Box::pin(async move {
            Err(anyhow::anyhow!(
                "Terminal operations not implemented in DefaultAcpHandler"
            ))
        })
    }

    fn handle_terminal_release(
        &self,
        _session_id: &SessionId,
        _terminal_id: &str,
    ) -> BoxFuture<'_, Result<()>> {
        Box::pin(async move {
            Err(anyhow::anyhow!(
                "Terminal operations not implemented in DefaultAcpHandler"
            ))
        })
    }

    fn handle_terminal_wait_for_exit(
        &self,
        _session_id: &SessionId,
        _terminal_id: &str,
    ) -> BoxFuture<'_, Result<Option<i32>>> {
        Box::pin(async move {
            Err(anyhow::anyhow!(
                "Terminal operations not implemented in DefaultAcpHandler"
            ))
        })
    }
}

/// Callback handler with terminal support
pub struct DefaultAcpHandlerWithTerminal {
    state: Arc<Mutex<AcpState>>,
}

impl DefaultAcpHandlerWithTerminal {
    pub fn new() -> Self {
        Self {
            state: Arc::new(Mutex::new(AcpState {
                next_id: 1,
                session_id: None,
                pending_requests: HashMap::new(),
                handler: Arc::new(DefaultAcpHandler),
                capabilities: None,
                agent_info: None,
                config_options: Vec::new(),
                models: None,
                terminals: HashMap::new(),
            })),
        }
    }
}

impl AcpCallbackHandler for DefaultAcpHandlerWithTerminal {
    fn handle_request_permission(
        &self,
        _session_id: &SessionId,
        _tool_call_id: &str,
        options: Vec<PermissionOption>,
    ) -> BoxFuture<'_, RequestPermissionOutcome> {
        Box::pin(async move {
            // Log all options for debugging
            tracing::debug!(
                options = ?options.iter().map(|o| (&o.option_id, &o.kind)).collect::<Vec<_>>(),
                "handle_request_permission: received options"
            );

            // Auto-approve any non-reject option (more lenient for different agent implementations)
            for opt in options {
                // Match any "allow" type option
                if matches!(
                    opt.kind,
                    PermissionOptionKind::AllowOnce | PermissionOptionKind::AllowAlways
                ) {
                    tracing::debug!(
                        option_id = %opt.option_id,
                        kind = ?opt.kind,
                        "handle_request_permission: auto-approving"
                    );
                    return RequestPermissionOutcome::Selected {
                        option_id: opt.option_id,
                    };
                }
                // Also approve if option_id contains "allow" or "accept" (fallback for non-standard formats)
                if opt.option_id.contains("allow") || opt.option_id.contains("accept") {
                    tracing::debug!(
                        option_id = %opt.option_id,
                        "handle_request_permission: auto-approving by option_id pattern"
                    );
                    return RequestPermissionOutcome::Selected {
                        option_id: opt.option_id,
                    };
                }
            }
            tracing::warn!("handle_request_permission: no matching allow option found, cancelling");
            RequestPermissionOutcome::Cancelled
        })
    }

    fn handle_read_text_file(&self, _session_id: &SessionId, path: &str) -> BoxFuture<'_, Result<String>> {
        let path = path.to_owned();
        Box::pin(async move {
            tokio::fs::read_to_string(&path)
                .await
                .context("Failed to read file")
        })
    }

    fn handle_write_text_file(
        &self,
        _session_id: &SessionId,
        path: &str,
        contents: &str,
    ) -> BoxFuture<'_, Result<()>> {
        let path = path.to_owned();
        let contents = contents.to_owned();
        Box::pin(async move {
            tokio::fs::write(&path, &contents)
                .await
                .context("Failed to write file")
        })
    }

    fn handle_terminal_create(
        &self,
        _session_id: &SessionId,
        command: Option<&str>,
        _args: Option<Vec<String>>,
    ) -> BoxFuture<'_, Result<String>> {
        let command = command.map(|s| s.to_owned());
        Box::pin(async move {
            let default_shell = if cfg!(target_os = "windows") { "powershell.exe" } else { "sh" };
            let shell = command.as_deref().unwrap_or(default_shell);
            let mut cmd = Command::new(shell);
            cmd.stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::piped());
            #[cfg(windows)]
            {
                use std::os::windows::process::CommandExt;
                const CREATE_NO_WINDOW: u32 = 0x08000000;
                cmd.creation_flags(CREATE_NO_WINDOW);
            }
            let child = cmd.spawn()
                .context("Failed to spawn terminal process")?;
            let terminal_id = format!("terminal-{}", uuid::Uuid::new_v4());

            let mut state = self.state.lock().await;
            state.terminals.insert(terminal_id.clone(), child);

            tracing::info!(terminal_id = %terminal_id, "terminal created");
            Ok(terminal_id)
        })
    }

    fn handle_terminal_output(
        &self,
        _session_id: &SessionId,
        terminal_id: &str,
    ) -> BoxFuture<'_, Result<TerminalOutputResponse>> {
        let terminal_id = terminal_id.to_owned();
        Box::pin(async move {
            let mut state = self.state.lock().await;

            let child = state
                .terminals
                .get_mut(&terminal_id)
                .ok_or_else(|| anyhow::anyhow!("terminal not found: {}", terminal_id))?;

            let mut stdout_buf = String::new();
            let mut stderr_buf = String::new();

            if let Some(stdout) = child.stdout.as_mut() {
                let mut reader = BufReader::new(stdout);
                reader.read_line(&mut stdout_buf).await.ok();
            }

            if let Some(stderr) = child.stderr.as_mut() {
                let mut reader = BufReader::new(stderr);
                reader.read_line(&mut stderr_buf).await.ok();
            }

            let exit = match child.try_wait()? {
                Some(status) => status.code(),
                None => None,
            };

            tracing::debug!(terminal_id = %terminal_id, "terminal output read");

            Ok(TerminalOutputResponse {
                exit,
                stdout: stdout_buf,
                stderr: stderr_buf,
            })
        })
    }

    fn handle_terminal_kill(&self, _session_id: &SessionId, terminal_id: &str) -> BoxFuture<'_, Result<()>> {
        let terminal_id = terminal_id.to_owned();
        Box::pin(async move {
            let mut state = self.state.lock().await;

            if let Some(mut child) = state.terminals.remove(&terminal_id) {
                child.kill().await.ok();
                tracing::info!(terminal_id = %terminal_id, "terminal killed");
            }

            Ok(())
        })
    }

    fn handle_terminal_release(
        &self,
        _session_id: &SessionId,
        terminal_id: &str,
    ) -> BoxFuture<'_, Result<()>> {
        let terminal_id = terminal_id.to_owned();
        Box::pin(async move {
            let mut state = self.state.lock().await;

            if let Some(mut child) = state.terminals.remove(&terminal_id) {
                child.wait().await.ok();
                tracing::info!(terminal_id = %terminal_id, "terminal released");
            }

            Ok(())
        })
    }

    fn handle_terminal_wait_for_exit(
        &self,
        _session_id: &SessionId,
        terminal_id: &str,
    ) -> BoxFuture<'_, Result<Option<i32>>> {
        let terminal_id = terminal_id.to_owned();
        Box::pin(async move {
            let mut state = self.state.lock().await;

            if let Some(child) = state.terminals.get_mut(&terminal_id) {
                let status = child.wait().await.context("Failed to wait for terminal")?;
                let code = status.code();
                tracing::info!(terminal_id = %terminal_id, exit_code = ?code, "terminal exited");
                return Ok(code);
            }

            Ok(None)
        })
    }
}

// ---------------------------------------------------------------------------
// Session Update Events
// ---------------------------------------------------------------------------

/// Session update event from agent
#[derive(Debug, Clone)]
pub enum SessionEvent {
    /// Agent message chunk
    AgentMessageChunk { content: String },
    /// Agent thought chunk
    AgentThoughtChunk { content: String },
    /// Tool call started
    ToolCallStarted {
        tool_call_id: String,
        title: Option<String>,
        kind: ToolKind,
    },
    /// Tool call in progress
    ToolCallInProgress { tool_call_id: String },
    /// Tool call completed
    ToolCallCompleted {
        tool_call_id: String,
        result: Option<String>,
    },
    /// Tool call failed
    ToolCallFailed { tool_call_id: String, error: String },
    /// Mode changed
    ModeChanged { mode_id: String },
    /// Config option updated
    ConfigOptionUpdated { options: Vec<SessionConfigOption> },
    /// Session info updated
    SessionInfoUpdated {
        title: Option<String>,
        updated_at: Option<String>,
    },
    /// Usage updated
    UsageUpdated { used: u32, size: u32 },
    /// Available commands updated
    AvailableCommandsUpdated { commands: Vec<AvailableCommand> },
}

// ---------------------------------------------------------------------------
// Internal State
// ---------------------------------------------------------------------------

/// Shared state for the ACP client.
#[allow(dead_code)]
struct AcpState {
    next_id: i64,
    session_id: Option<SessionId>,
    pending_requests: HashMap<i64, mpsc::Sender<Result<serde_json::Value>>>,
    handler: Arc<dyn AcpCallbackHandler>,
    capabilities: Option<AgentCapabilities>,
    agent_info: Option<Implementation>,
    config_options: Vec<SessionConfigOption>,
    models: Option<SessionModels>,
    /// Active terminal processes
    terminals: HashMap<String, Child>,
}

/// Commands for subprocess task
#[derive(Debug)]
enum SubprocessCmd {
    SendRequest {
        request: String,
        response_tx: mpsc::Sender<Result<serde_json::Value>>,
    },
    Shutdown,
}

/// Internal message from subprocess to client
#[derive(Debug)]
#[allow(dead_code)]
enum SubprocessEvent {
    Response {
        id: i64,
        result: Result<serde_json::Value>,
    },
    SessionUpdate {
        session_id: SessionId,
        event: SessionEvent,
    },
    AgentRequest {
        request: serde_json::Value,
    },
}

// ---------------------------------------------------------------------------
// ACP Client
// ---------------------------------------------------------------------------

/// ACP client for communicating with ACP-compatible agents.
#[derive(Clone)]
pub struct AcpClient {
    cmd_tx: Arc<Mutex<Option<mpsc::Sender<SubprocessCmd>>>>,
    state: Arc<Mutex<AcpState>>,
    collected_content: Arc<Mutex<String>>,
    event_tx: broadcast::Sender<SessionEvent>,
    notification_manager: Arc<Mutex<NotificationManager>>,
}

impl AcpClient {
    pub async fn spawn(command: &str, args: &[&str]) -> Result<Self> {
        Self::spawn_with_handler(
            command,
            args,
            Arc::new(DefaultAcpHandler),
            Arc::new(Mutex::new(NotificationManager::new())),
        )
        .await
    }

    pub async fn spawn_with_handler(
        command: &str,
        args: &[&str],
        handler: Arc<dyn AcpCallbackHandler>,
        notification_manager: Arc<Mutex<NotificationManager>>,
    ) -> Result<Self> {
        // First, check if the command exists (for better error messages)
        let command_path = which::which(command)
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_else(|_| command.to_string());

        // Try to spawn the process first to catch errors early
        let test_child = std::process::Command::new(&command_path)
            .args(args)
            .stdin(std::process::Stdio::null())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn();

        match test_child {
            Ok(mut child) => {
                // Process started successfully, kill it and spawn the real one
                let _ = child.kill();
            }
            Err(e) => {
                return Err(anyhow::anyhow!(
                    "Failed to spawn ACP subprocess '{}': {}. Please ensure the command exists and is executable.",
                    command_path,
                    e
                ));
            }
        }

        let command_owned = command_path.clone();
        let args_owned: Vec<String> = args.iter().map(|s| s.to_string()).collect();

        let (cmd_tx, cmd_rx) = mpsc::channel(32);
        let cmd_tx_clone = cmd_tx.clone();
        let collected = Arc::new(Mutex::new(String::new()));
        let collected_clone = collected.clone();
        let handler_clone = handler.clone();
        let notification_manager_clone = notification_manager.clone();

        let (event_tx, _) = broadcast::channel(256);
        let event_tx_clone = event_tx.clone();

        tokio::spawn(async move {
            let _ = run_subprocess(
                &command_owned,
                &args_owned,
                cmd_rx,
                collected_clone,
                handler_clone,
                event_tx_clone,
                notification_manager_clone,
            ).await;
        });

        // Brief startup delay to allow subprocess to initialize
        tokio::time::sleep(Duration::from_millis(100)).await;

        Ok(Self {
            cmd_tx: Arc::new(Mutex::new(Some(cmd_tx_clone))),
            state: Arc::new(Mutex::new(AcpState {
                next_id: 1,
                session_id: None,
                pending_requests: HashMap::new(),
                handler,
                capabilities: None,
                agent_info: None,
                config_options: Vec::new(),
                models: None,
                terminals: HashMap::new(),
            })),
            collected_content: collected,
            event_tx,
            notification_manager,
        })
    }

    /// Subscribe to session update events
    pub fn subscribe_events(&self) -> broadcast::Receiver<SessionEvent> {
        self.event_tx.subscribe()
    }

    /// Add a notification sink for sending critical events to channels
    pub fn add_notification_sink(&self, sink: Arc<dyn NotificationSink>) {
        if let Ok(mut guard) = self.notification_manager.try_lock() {
            guard.add_sink(sink);
        }
    }

    /// Get the collected content from notifications
    pub async fn get_collected_content(&self) -> String {
        self.collected_content.lock().await.clone()
    }

    /// Clear collected content
    pub async fn clear_collected_content(&self) {
        self.collected_content.lock().await.clear();
    }

    /// Get current session ID
    pub async fn session_id(&self) -> Option<SessionId> {
        self.state.lock().await.session_id.clone()
    }

    /// Get agent capabilities (available after initialize)
    pub async fn capabilities(&self) -> Option<AgentCapabilities> {
        self.state.lock().await.capabilities.clone()
    }

    /// Get agent info (available after initialize)
    pub async fn agent_info(&self) -> Option<Implementation> {
        self.state.lock().await.agent_info.clone()
    }

    pub async fn config_options(&self) -> Vec<SessionConfigOption> {
        self.state.lock().await.config_options.clone()
    }

    pub async fn models(&self) -> Option<SessionModels> {
        self.state.lock().await.models.clone()
    }

    /// Check if agent supports loading sessions
    pub async fn supports_load_session(&self) -> bool {
        self.state
            .lock()
            .await
            .capabilities
            .as_ref()
            .and_then(|c| c.load_session)
            .unwrap_or(false)
    }

    /// Check if agent supports images in prompts
    pub async fn supports_images(&self) -> bool {
        self.state
            .lock()
            .await
            .capabilities
            .as_ref()
            .and_then(|c| c.prompt_capabilities.as_ref())
            .map(|p| p.image)
            .unwrap_or(false)
    }

    /// Check if agent supports audio in prompts
    pub async fn supports_audio(&self) -> bool {
        self.state
            .lock()
            .await
            .capabilities
            .as_ref()
            .and_then(|c| c.prompt_capabilities.as_ref())
            .map(|p| p.audio)
            .unwrap_or(false)
    }

    /// Check if agent supports embedded context (resources)
    pub async fn supports_embedded_context(&self) -> bool {
        self.state
            .lock()
            .await
            .capabilities
            .as_ref()
            .and_then(|c| c.prompt_capabilities.as_ref())
            .map(|p| p.embedded_context)
            .unwrap_or(false)
    }

    // ---------------------------------------------------------------------------
    // Client → Agent Methods
    // ---------------------------------------------------------------------------

    /// Initialize the ACP connection.
    pub async fn initialize(
        &self,
        client_name: &str,
        client_version: &str,
    ) -> Result<InitializeResponse> {
        let params = serde_json::json!({
            "protocolVersion": PROTOCOL_VERSION,
            "clientInfo": {"name": client_name, "version": client_version},
            "clientCapabilities": {
                "fs": { "readTextFile": true, "writeTextFile": true },
                "terminal": true
            }
        });
        let resp = self.rpc(methods::INITIALIZE, params).await?;
        tracing::debug!(response = ?resp, "ACP initialize response");
        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let init_resp: InitializeResponse =
            serde_json::from_value(result).context("Failed to parse initialize response")?;

        // Store capabilities and agent info for later use
        let mut state = self.state.lock().await;
        state.capabilities = Some(init_resp.agent_capabilities.clone());
        state.agent_info = Some(init_resp.agent_info.clone());

        Ok(init_resp)
    }

    /// Create a new session.
    pub async fn create_session(
        &self,
        cwd: &str,
        model: Option<&str>,
        mcp_servers: Option<Vec<McpServerConfig>>,
    ) -> Result<NewSessionResponse> {
        tracing::debug!(
            cwd = %cwd,
            model = ?model,
            "create_session: called with params"
        );
        let mut params = serde_json::json!({
            "cwd": cwd,
            "mcpServers": mcp_servers.unwrap_or_default()
        });

        if let Some(m) = model {
            params["modelId"] = serde_json::json!(m);
            tracing::debug!(model = %m, params = ?params, "Adding modelId to session/new request");
        } else {
            tracing::warn!("create_session: no model provided, will use agent default");
        }

        let resp = self.rpc(methods::SESSION_NEW, params).await?;
        tracing::debug!(response = ?resp, "ACP session/new response");
        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let session_resp: NewSessionResponse =
            serde_json::from_value(result).context("Failed to parse session/new response")?;

        let mut state = self.state.lock().await;
        state.session_id = Some(session_resp.session_id.clone());
        state.config_options = session_resp.config_options.clone().unwrap_or_default();
        state.models = session_resp.models.clone();

        if let Some(ref models) = session_resp.models {
            tracing::debug!("Available models: {:?}", models.available_models);
        }
        if let Some(ref opts) = session_resp.config_options {
            tracing::debug!("Config options available: {}", opts.len());
            for opt in opts {
                tracing::debug!(
                    "  - {}: {} (current: {})",
                    opt.id,
                    opt.name,
                    opt.current_value
                );
            }
        }

        Ok(session_resp)
    }

    /// Load an existing session.
    pub async fn load_session(
        &self,
        session_id: &SessionId,
        cwd: Option<&str>,
        mcp_servers: Option<Vec<McpServerConfig>>,
    ) -> Result<LoadSessionResponse> {
        let mut params = serde_json::json!({
            "sessionId": session_id,
        });
        if let Some(cwd) = cwd {
            params["cwd"] = serde_json::json!(cwd);
        }
        params["mcpServers"] = serde_json::json!(mcp_servers.unwrap_or_default());

        let resp = self.rpc(methods::SESSION_LOAD, params).await?;
        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let load_resp: LoadSessionResponse =
            serde_json::from_value(result).context("Failed to parse session/load response")?;
        self.state.lock().await.session_id = Some(session_id.to_string());
        Ok(load_resp)
    }

    /// Send a prompt to the agent.
    pub async fn send_prompt(&self, prompt: &str) -> Result<PromptResponse> {
        let session_id = self.session_id().await.context("No active session")?;
        let params = serde_json::json!({
            "sessionId": session_id,
            "prompt": [{"type": "text", "text": prompt}]
        });

        // session/prompt can take a LONG time - use no timeout for this method
        let resp = self
            .rpc_no_timeout(methods::SESSION_PROMPT, params)
            .await
            .map_err(|e| {
                // If it's a timeout or subprocess died error, make it clearer
                if e.to_string().contains("timeout")
                    || e.to_string().contains("Subprocess task died")
                    || e.to_string().contains("Channel closed")
                {
                    let lang = crate::i18n::default_lang();
                    anyhow::anyhow!("{}", crate::i18n::t_fmt("acp_timeout", lang, &[("name", "OpenCode")]))
                } else {
                    e
                }
            })?;

        tracing::debug!("=== send_prompt raw response ===");
        tracing::debug!(
            "Full response: {}",
            serde_json::to_string(&resp).unwrap_or_default()
        );

        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);

        tracing::debug!("=== send_prompt result ===");
        tracing::debug!(
            "Result: {}",
            serde_json::to_string(&result).unwrap_or_default()
        );

        let prompt_resp: PromptResponse =
            serde_json::from_value(result.clone()).context("Failed to parse prompt response")?;

        tracing::debug!("=== send_prompt parsed ===");
        tracing::debug!("stop_reason: {:?}", prompt_resp.stop_reason);
        tracing::debug!("usage: {:?}", prompt_resp.usage);
        if let Some(ref r) = prompt_resp.result {
            tracing::debug!("content blocks: {}", r.content.len());
            for (i, block) in r.content.iter().enumerate() {
                match block {
                    crate::acp::types::ContentBlock::Text { text } => {
                        tracing::debug!("  [{}] Text: {}", i, text);
                    }
                    crate::acp::types::ContentBlock::Image { .. } => {
                        tracing::debug!("  [{}] Image", i);
                    }
                    crate::acp::types::ContentBlock::Resource { .. } => {
                        tracing::debug!("  [{}] Resource", i);
                    }
                    crate::acp::types::ContentBlock::ResourceLink { .. } => {
                        tracing::debug!("  [{}] ResourceLink", i);
                    }
                }
            }
            if let Some(ref calls) = r.tool_calls {
                tracing::debug!("tool_calls: {} calls", calls.len());
                for (i, call) in calls.iter().enumerate() {
                    tracing::debug!("  [{}] tool_call: id={}, name={}", i, call.id, call.name);
                }
            }
        }

        Ok(prompt_resp)
    }

    /// Send a prompt with content blocks (supports images, resources).
    pub async fn send_prompt_with_content(
        &self,
        prompt: Vec<ContentBlock>,
    ) -> Result<PromptResponse> {
        let session_id = self.session_id().await.context("No active session")?;
        let params = serde_json::json!({
            "sessionId": session_id,
            "prompt": prompt
        });
        // session/prompt can take a LONG time - use no timeout
        let resp = self.rpc_no_timeout(methods::SESSION_PROMPT, params).await?;
        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        serde_json::from_value(result).context("Failed to parse prompt response")
    }

    /// Cancel the current session operation.
    pub async fn cancel_session(&self) -> Result<()> {
        let session_id = self.session_id().await.context("No active session")?;
        let params = serde_json::json!({
            "sessionId": session_id
        });
        // Cancel is a notification, not a request
        self.send_notification(methods::SESSION_CANCEL, params)
            .await?;
        Ok(())
    }

    /// List all sessions.
    pub async fn list_sessions(&self, cwd: Option<&str>) -> Result<ListSessionsResponse> {
        let params = if let Some(cwd) = cwd {
            serde_json::json!({ "cwd": cwd })
        } else {
            serde_json::json!({})
        };
        let resp = self.rpc(methods::SESSION_LIST, params).await?;
        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        serde_json::from_value(result).context("Failed to parse session/list response")
    }

    /// Set the session mode.
    pub async fn set_mode(&self, mode_id: &str) -> Result<()> {
        let session_id = self.session_id().await.context("No active session")?;
        let params = serde_json::json!({
            "sessionId": session_id,
            "modeId": mode_id
        });
        let _resp = self.rpc(methods::SESSION_SET_MODE, params).await?;
        Ok(())
    }

    /// Set the model for the session.
    pub async fn set_model(&self, model_id: &str) -> Result<Vec<SessionConfigOption>> {
        let session_id = self.session_id().await.context("No active session")?;
        let params = serde_json::json!({
            "sessionId": session_id,
            "configId": "model",
            "value": model_id
        });
        tracing::debug!(model_id = %model_id, "Calling session/set_config_option");
        let resp = self.rpc(methods::SESSION_SET_CONFIG_OPTION, params).await?;
        tracing::debug!(response = ?resp, "set_model response");

        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let config_resp: SetSessionConfigOptionResponse =
            serde_json::from_value(result).context("Failed to parse config option response")?;

        let options = config_resp.config_options.unwrap_or_default();
        self.state.lock().await.config_options = options.clone();

        Ok(options)
    }

    /// Set a session config option.
    pub async fn set_config_option(
        &self,
        config_id: &str,
        value: &str,
    ) -> Result<Vec<SessionConfigOption>> {
        let session_id = self.session_id().await.context("No active session")?;
        let params = serde_json::json!({
            "sessionId": session_id,
            "configId": config_id,
            "value": value
        });
        let resp = self.rpc(methods::SESSION_SET_CONFIG_OPTION, params).await?;
        let result = resp
            .get("result")
            .cloned()
            .unwrap_or(serde_json::Value::Null);
        let config_resp: SetSessionConfigOptionResponse =
            serde_json::from_value(result).context("Failed to parse config option response")?;
        Ok(config_resp.config_options.unwrap_or_default())
    }

    /// Authenticate with the agent.
    pub async fn authenticate(
        &self,
        method_id: &str,
        credentials: Option<serde_json::Value>,
    ) -> Result<()> {
        let params = serde_json::json!({
            "methodId": method_id,
            "credentials": credentials
        });
        let _resp = self.rpc(methods::AUTHENTICATE, params).await?;
        Ok(())
    }

    /// Shutdown the client.
    pub async fn shutdown(self) -> Result<()> {
        let guard = self.cmd_tx.lock().await;
        if let Some(tx) = guard.as_ref() {
            let _ = tx.send(SubprocessCmd::Shutdown).await;
        }
        Ok(())
    }

    // ---------------------------------------------------------------------------
    // Internal RPC Methods
    // ---------------------------------------------------------------------------

    /// Internal RPC call
    async fn rpc(&self, method: &str, params: serde_json::Value) -> Result<serde_json::Value> {
        let id = {
            let mut state = self.state.lock().await;
            let id = state.next_id;
            state.next_id += 1;
            id
        };

        let guard = self.cmd_tx.lock().await;
        let tx = guard.as_ref().context("Subprocess task died")?;

        let (resp_tx, mut resp_rx) = mpsc::channel(1);

        let request = serde_json::to_string(&serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params
        }))?;

        tracing::debug!(method, id, request = %request, "ACP sending request");

        tx.send(SubprocessCmd::SendRequest {
            request,
            response_tx: resp_tx,
        })
        .await
        .context("Failed to send request")?;

        let resp = timeout(LONG_TIMEOUT, resp_rx.recv())
            .await
            .context("RPC timeout")?
            .context("Channel closed")?;

        tracing::debug!(method, id, response = ?resp, "ACP received response");
        resp
    }

    /// RPC call without timeout - for long-running operations like
    /// session/prompt
    async fn rpc_no_timeout(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value> {
        let id = {
            let mut state = self.state.lock().await;
            let id = state.next_id;
            state.next_id += 1;
            id
        };

        let guard = self.cmd_tx.lock().await;
        let tx = guard.as_ref().context("Subprocess task died")?;

        let (resp_tx, mut resp_rx) = mpsc::channel(1);

        let request = serde_json::to_string(&serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params
        }))?;

        tracing::debug!(method, id, request = %request, "ACP sending request (no timeout)");

        tx.send(SubprocessCmd::SendRequest {
            request,
            response_tx: resp_tx,
        })
        .await
        .context("Failed to send request")?;

        // Wait indefinitely for response (session/prompt can take very long)
        let resp = resp_rx
            .recv()
            .await
            .context("Channel closed - subprocess died")?;

        tracing::debug!(method, id, response = ?resp, "ACP received response");
        resp
    }

    /// Send a notification (no response expected)
    async fn send_notification(&self, method: &str, params: serde_json::Value) -> Result<()> {
        let guard = self.cmd_tx.lock().await;
        let tx = guard.as_ref().context("Subprocess task died")?;

        let notification = serde_json::to_string(&serde_json::json!({
            "jsonrpc": "2.0",
            "method": method,
            "params": params
        }))?;

        // Send as request but don't wait for response
        let (resp_tx, _) = mpsc::channel(1);

        tx.send(SubprocessCmd::SendRequest {
            request: notification,
            response_tx: resp_tx,
        })
        .await
        .context("Failed to send notification")?;

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Subprocess Handler
// ---------------------------------------------------------------------------

/// Subprocess handler task
async fn run_subprocess(
    command: &str,
    args: &[String],
    mut cmd_rx: mpsc::Receiver<SubprocessCmd>,
    collected_content: Arc<Mutex<String>>,
    handler: Arc<dyn AcpCallbackHandler>,
    event_tx: broadcast::Sender<SessionEvent>,
    notification_manager: Arc<Mutex<NotificationManager>>,
) -> Result<()> {
    let mut child = Command::new(command)
        .args(args)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .kill_on_drop(true)
        .spawn()
        .with_context(|| format!("Failed to spawn ACP subprocess: {} {:?}", command, args))?;

    let mut stdin = child.stdin.take().context("Failed to get stdin")?;
    let stdout = child.stdout.take().context("Failed to get stdout")?;
    let mut reader = BufReader::new(stdout);

    tracing::info!("ACP subprocess started: {} {:?}", command, args);

    loop {
        tokio::select! {
            // Handle commands from AcpClient
            cmd = cmd_rx.recv() => {
                match cmd {
                    Some(SubprocessCmd::SendRequest { request, response_tx }) => {
                        collected_content.lock().await.clear();

                        let request_id = serde_json::from_str::<serde_json::Value>(&request)
                            .ok()
                            .and_then(|v| v.get("id").and_then(|i| i.as_i64()));

                        // Single write for JSON + newline
                        let mut combined = request.as_bytes().to_vec();
                        combined.push(b'\n');
                        if stdin.write_all(&combined).await.is_err() {
                            let _ = response_tx.send(Err(anyhow::anyhow!("Write error"))).await;
                            break;
                        }
                        if stdin.flush().await.is_err() {
                            let _ = response_tx.send(Err(anyhow::anyhow!("Flush error"))).await;
                            break;
                        }

                        tracing::debug!("ACP request sent: {}", request);

                        // Read response and notifications until we get the matching response
                        let mut line_buf = Vec::new(); // Use byte buffer to handle non-UTF8

                        // Read until we get the response for this request (no timeout - can take very long!)
                        loop {
                            line_buf.clear();
                            tokio::select! {
                                result = reader.read_until(b'\n', &mut line_buf) => {
                                    match result {
                                        Ok(0) => {
                                            let _ = response_tx.send(Err(anyhow::anyhow!("EOF"))).await;
                                            break;
                                        }
                                        Ok(_) => {
                                            // Convert to string, replacing invalid UTF-8 sequences
                                            let line = String::from_utf8_lossy(&line_buf).trim().to_string();
                                            if line.is_empty() {
                                                continue;
                                            }

                                            if let Ok(msg) = serde_json::from_str::<serde_json::Value>(&line) {
                                                let method_field = msg.get("method").and_then(|m| m.as_str());

                                                // Log all incoming messages with method field at INFO level
                                                if let Some(method) = method_field {
                                                    tracing::debug!("ACP incoming method: {} | msg: {}", method, line);
                                                } else if msg.get("id").is_some() {
                                                    tracing::debug!("ACP response: {}", line);
                                                } else {
                                                    tracing::debug!("ACP message: {}", line);
                                                }

                                                // Handle session/update notification
                                                if method_field == Some(methods::SESSION_UPDATE) {
                                                    handle_session_update(&msg, &collected_content, &event_tx, &notification_manager).await;
                                                    continue;
                                                }

                                                // Handle Agent → Client requests
                                                if let Some(method) = method_field {
                                                    tracing::debug!("Handling agent request: {}", method);
                                                    if handle_agent_request(&mut stdin, &msg, method, &handler).await {
                                                        continue;
                                                    }
                                                }

                                                // Check if this is the response to our request
                                                let resp_id = msg.get("id").and_then(|i| i.as_i64());
                                                if resp_id == request_id {
                                                    let _ = response_tx.send(Ok(msg)).await;
                                                    break;
                                                }
                                            }
                                        }
                                        Err(e) => {
                                            let _ = response_tx.send(Err(anyhow::anyhow!("{}", e))).await;
                                            break;
                                        }
                                    }
                                }
                                _ = tokio::time::sleep(Duration::from_millis(50)) => {
                                    // Continue polling
                                }
                            }
                        }
                    }
                    Some(SubprocessCmd::Shutdown) => {
                        tracing::info!("ACP subprocess shutting down");
                        break;
                    }
                    None => {
                        break;
                    }
                }
            }
            // Prevent tight loop
            _ = tokio::time::sleep(Duration::from_millis(10)) => {}
        }
    }

    Ok(())
}

/// Handle session/update notification
async fn handle_session_update(
    msg: &serde_json::Value,
    collected_content: &Arc<Mutex<String>>,
    event_tx: &broadcast::Sender<SessionEvent>,
    notification_manager: &Arc<Mutex<NotificationManager>>,
) {
    let params = msg.get("params");
    let session_id = params
        .and_then(|p| p.get("sessionId"))
        .and_then(|s| s.as_str())
        .map(String::from);
    let update = params.and_then(|p| p.get("update"));

    if let Some(update) = update {
        let session_update = update.get("sessionUpdate").and_then(|s| s.as_str());

        match session_update {
            Some("plan") => {
                tracing::debug!("ACP plan received");
                if let Some(entries) = update.get("entries").and_then(|e| e.as_array()) {
                    for entry in entries {
                        if let Some(content) = entry.get("content").and_then(|c| c.as_str()) {
                            tracing::debug!("Plan entry: {}", content);
                        }
                    }
                }
            }
            Some("user_message") | Some("user_message_chunk") => {
                tracing::debug!("ACP user_message received");
            }
            Some("agent_message") => {
                if let Some(content) = update.get("content") {
                    extract_text_content(content, collected_content).await;
                }
            }
            Some("agent_message_chunk") => {
                if let Some(content) = update.get("content") {
                    extract_text_content(content, collected_content).await;
                    if let Some(text) = content.get("text").and_then(|t| t.as_str()) {
                        let _ = event_tx.send(SessionEvent::AgentMessageChunk {
                            content: text.to_string(),
                        });
                    }
                }
            }
            Some("agent_thought_chunk") => {
                if let Some(content) = update.get("content") {
                    if let Some(text) = content.get("text").and_then(|t| t.as_str()) {
                        tracing::debug!("ACP thought: {}", text);
                        let _ = event_tx.send(SessionEvent::AgentThoughtChunk {
                            content: text.to_string(),
                        });
                    }
                }
            }
            Some("tool_call") => {
                let tool_call_id = update
                    .get("toolCallId")
                    .and_then(|t| t.as_str())
                    .unwrap_or("?")
                    .to_string();
                let title = update
                    .get("title")
                    .and_then(|t| t.as_str())
                    .map(String::from);
                let kind = parse_tool_kind(update.get("kind").and_then(|k| k.as_str()));
                let status = update.get("status").and_then(|s| s.as_str());

                tracing::debug!(
                    "ACP tool_call: {} - {:?} ({:?})",
                    tool_call_id,
                    title,
                    status
                );

                match status {
                    Some("pending") => {
                        let _ = event_tx.send(SessionEvent::ToolCallStarted {
                            tool_call_id: tool_call_id.clone(),
                            title: title.clone(),
                            kind: kind.clone(),
                        });
                        let _lang = crate::i18n::default_lang();
                        let notif = Notification::new(
                            NotificationPriority::Medium,
                            &crate::i18n::t("acp_tool_start", _lang),
                            &crate::i18n::t_fmt("acp_tool_executing", _lang, &[("title", title.as_deref().unwrap_or(""))]),
                        );
                        if let Ok(nm) = notification_manager.try_lock() {
                            nm.send(&notif.with_session_id(session_id.clone().unwrap_or_default()))
                                .await;
                        }
                    }
                    Some("in_progress") => {
                        let _ = event_tx.send(SessionEvent::ToolCallInProgress { tool_call_id });
                    }
                    Some("completed") => {
                        let result = update
                            .get("result")
                            .and_then(|r| r.get("text"))
                            .and_then(|t| t.as_str())
                            .map(String::from);
                        let _ = event_tx.send(SessionEvent::ToolCallCompleted {
                            tool_call_id: tool_call_id.clone(),
                            result: result.clone(),
                        });
                        let _lang = crate::i18n::default_lang();
                        let notif = Notification::new(
                            NotificationPriority::Medium,
                            &crate::i18n::t("acp_tool_done", _lang),
                            &crate::i18n::t_fmt("acp_tool_completed", _lang, &[("title", title.as_deref().unwrap_or(""))]),
                        );
                        if let Ok(nm) = notification_manager.try_lock() {
                            nm.send(&notif.with_session_id(session_id.clone().unwrap_or_default()))
                                .await;
                        }
                    }
                    Some("failed") => {
                        let error = update
                            .get("error")
                            .and_then(|e| e.as_str())
                            .unwrap_or("Unknown error")
                            .to_string();
                        let _ = event_tx.send(SessionEvent::ToolCallFailed {
                            tool_call_id: tool_call_id.clone(),
                            error: error.clone(),
                        });
                        let _lang = crate::i18n::default_lang();
                        let notif = Notification::new(
                            NotificationPriority::High,
                            &crate::i18n::t("acp_tool_failed", _lang),
                            &crate::i18n::t_fmt("acp_tool_error", _lang, &[
                                ("title", title.as_deref().unwrap_or("")),
                                ("error", &error),
                            ]),
                        )
                        .with_burn_after_read();
                        if let Ok(nm) = notification_manager.try_lock() {
                            nm.send(&notif.with_session_id(session_id.clone().unwrap_or_default()))
                                .await;
                        }
                    }
                    _ => {}
                }
            }
            Some("mode_change") => {
                if let Some(mode_id) = update.get("modeId").and_then(|m| m.as_str()) {
                    tracing::debug!("ACP mode_change: {}", mode_id);
                    let _ = event_tx.send(SessionEvent::ModeChanged {
                        mode_id: mode_id.to_string(),
                    });
                }
            }
            Some("config_option_update") => {
                if let Some(options) = update.get("configOptions").and_then(|o| o.as_array()) {
                    let config_options: Vec<SessionConfigOption> = options
                        .iter()
                        .filter_map(|v| serde_json::from_value(v.clone()).ok())
                        .collect();
                    let _ = event_tx.send(SessionEvent::ConfigOptionUpdated {
                        options: config_options,
                    });
                }
            }
            Some("session_info_update") => {
                let title = update
                    .get("title")
                    .and_then(|t| t.as_str())
                    .map(String::from);
                let updated_at = update
                    .get("updatedAt")
                    .and_then(|t| t.as_str())
                    .map(String::from);
                let _ = event_tx.send(SessionEvent::SessionInfoUpdated {
                    title: title.clone(),
                    updated_at: updated_at.clone(),
                });
                let _lang = crate::i18n::default_lang();
                let notif = Notification::new(
                    NotificationPriority::High,
                    &crate::i18n::t("acp_session_created", _lang),
                    &crate::i18n::t_fmt("acp_session_info", _lang, &[
                        ("id", session_id.as_deref().unwrap_or("")),
                        ("title", title.as_deref().unwrap_or("")),
                    ]),
                )
                .with_burn_after_read();
                if let Ok(nm) = notification_manager.try_lock() {
                    nm.send(&notif).await;
                }
            }
            Some("usage_update") => {
                let used = update.get("used").and_then(|u| u.as_u64()).unwrap_or(0) as u32;
                let size = update.get("size").and_then(|s| s.as_u64()).unwrap_or(0) as u32;
                let _ = event_tx.send(SessionEvent::UsageUpdated { used, size });
            }
            Some("available_commands_update") => {
                if let Some(commands) = update.get("availableCommands").and_then(|c| c.as_array()) {
                    let cmds: Vec<AvailableCommand> = commands
                        .iter()
                        .filter_map(|v| serde_json::from_value(v.clone()).ok())
                        .collect();
                    let _ =
                        event_tx.send(SessionEvent::AvailableCommandsUpdated { commands: cmds });
                }
            }
            _ => {
                tracing::debug!("ACP session_update: {:?}", session_update);
            }
        }
    }
}

/// Extract text content from content block
async fn extract_text_content(content: &serde_json::Value, collected_content: &Arc<Mutex<String>>) {
    if let Some(text) = content.get("text").and_then(|t| t.as_str()) {
        collected_content.lock().await.push_str(text);
    }
    if let Some(arr) = content.as_array() {
        for item in arr {
            if let Some(text) = item.get("text").and_then(|t| t.as_str()) {
                collected_content.lock().await.push_str(text);
            }
        }
    }
}

/// Parse tool kind from string
fn parse_tool_kind(kind: Option<&str>) -> ToolKind {
    match kind {
        Some("read") => ToolKind::Read,
        Some("edit") => ToolKind::Edit,
        Some("delete") => ToolKind::Delete,
        Some("move") => ToolKind::Move,
        Some("search") => ToolKind::Search,
        Some("execute") => ToolKind::Execute,
        Some("think") => ToolKind::Think,
        Some("fetch") => ToolKind::Fetch,
        _ => ToolKind::Other,
    }
}

/// Handle Agent → Client request (permissions, fs, terminal)
/// Returns true if handled, false if not an agent request
async fn handle_agent_request(
    stdin: &mut tokio::process::ChildStdin,
    msg: &serde_json::Value,
    method: &str,
    handler: &Arc<dyn AcpCallbackHandler>,
) -> bool {
    let request_id = msg.get("id").and_then(|i| i.as_i64());
    let params = msg
        .get("params")
        .cloned()
        .unwrap_or(serde_json::Value::Null);
    let session_id = params
        .get("sessionId")
        .and_then(|s| s.as_str())
        .unwrap_or("")
        .to_string();

    let result: Result<serde_json::Value> = match method {
        // Permission request
        methods::SESSION_REQUEST_PERMISSION => {
            let tool_call_id = params
                .get("toolCall")
                .and_then(|t| t.get("id").and_then(|i| i.as_str()))
                .unwrap_or("");

            let options: Vec<PermissionOption> = params
                .get("options")
                .and_then(|o| o.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|v| serde_json::from_value(v.clone()).ok())
                        .collect()
                })
                .unwrap_or_default();

            let outcome = handler
                .handle_request_permission(&session_id, tool_call_id, options)
                .await;
            Ok(serde_json::to_value(RequestPermissionResponse { outcome })
                .unwrap_or(serde_json::Value::Null))
        }

        // File system operations
        methods::FS_READ_TEXT_FILE => {
            let path = params.get("path").and_then(|p| p.as_str()).unwrap_or("");
            match handler.handle_read_text_file(&session_id, path).await {
                Ok(contents) => Ok(serde_json::to_value(ReadTextFileResponse { contents })
                    .unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        methods::FS_WRITE_TEXT_FILE => {
            let path = params.get("path").and_then(|p| p.as_str()).unwrap_or("");
            let contents = params
                .get("contents")
                .and_then(|c| c.as_str())
                .unwrap_or("");
            match handler
                .handle_write_text_file(&session_id, path, contents)
                .await
            {
                Ok(_) => Ok(serde_json::to_value(WriteTextFileResponse {})
                    .unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        // Terminal operations
        methods::TERMINAL_CREATE => {
            let command = params.get("command").and_then(|c| c.as_str());
            let args = params.get("args").and_then(|a| a.as_array()).map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            });
            match handler
                .handle_terminal_create(&session_id, command, args)
                .await
            {
                Ok(terminal_id) => Ok(serde_json::to_value(CreateTerminalResponse { terminal_id })
                    .unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        methods::TERMINAL_OUTPUT => {
            let terminal_id = params
                .get("terminalId")
                .and_then(|t| t.as_str())
                .unwrap_or("");
            match handler
                .handle_terminal_output(&session_id, terminal_id)
                .await
            {
                Ok(resp) => Ok(serde_json::to_value(resp).unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        methods::TERMINAL_KILL => {
            let terminal_id = params
                .get("terminalId")
                .and_then(|t| t.as_str())
                .unwrap_or("");
            match handler.handle_terminal_kill(&session_id, terminal_id).await {
                Ok(_) => Ok(serde_json::to_value(KillTerminalResponse {})
                    .unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        methods::TERMINAL_RELEASE => {
            let terminal_id = params
                .get("terminalId")
                .and_then(|t| t.as_str())
                .unwrap_or("");
            match handler
                .handle_terminal_release(&session_id, terminal_id)
                .await
            {
                Ok(_) => Ok(serde_json::to_value(ReleaseTerminalResponse {})
                    .unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        methods::TERMINAL_WAIT_FOR_EXIT => {
            let terminal_id = params
                .get("terminalId")
                .and_then(|t| t.as_str())
                .unwrap_or("");
            match handler
                .handle_terminal_wait_for_exit(&session_id, terminal_id)
                .await
            {
                Ok(exit) => Ok(serde_json::to_value(WaitForTerminalExitResponse { exit })
                    .unwrap_or(serde_json::Value::Null)),
                Err(e) => Err(e),
            }
        }

        _ => return false, // Not an agent request we handle
    };

    // Send response back to agent
    if let Some(id) = request_id {
        let response = match result {
            Ok(value) => serde_json::json!({
                "jsonrpc": "2.0",
                "id": id,
                "result": value
            }),
            Err(e) => serde_json::json!({
                "jsonrpc": "2.0",
                "id": id,
                "error": { "code": -32603, "message": e.to_string() }
            }),
        };

        let response_str = serde_json::to_string(&response).unwrap_or_default();
        tracing::debug!("ACP response to agent: {}", response_str);

        let mut combined = response_str.as_bytes().to_vec();
        combined.push(b'\n');

        // Use blocking write since we're in async context
        use tokio::io::AsyncWriteExt;
        if let Err(e) = stdin.write_all(&combined).await {
            tracing::error!("ACP response write failed: {}", e);
        }
        if let Err(e) = stdin.flush().await {
            tracing::error!("ACP response flush failed: {}", e);
        }

        tracing::debug!("ACP response sent successfully for method {}", method);
    }

    true
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_default_handler_permission() {
        let _handler = DefaultAcpHandler;
        let options = [
            PermissionOption {
                option_id: "deny".to_string(),
                kind: PermissionOptionKind::RejectOnce,
                label: None,
            },
            PermissionOption {
                option_id: "allow".to_string(),
                kind: PermissionOptionKind::AllowOnce,
                label: None,
            },
        ];

        // Can't easily test async in unit test, but structure is valid
        assert!(matches!(options[1].kind, PermissionOptionKind::AllowOnce));
    }

    #[test]
    fn test_session_event_variants() {
        let event = SessionEvent::AgentMessageChunk {
            content: "test".to_string(),
        };
        assert!(matches!(event, SessionEvent::AgentMessageChunk { .. }));

        let event = SessionEvent::ToolCallStarted {
            tool_call_id: "call_1".to_string(),
            title: Some("Reading file".to_string()),
            kind: ToolKind::Read,
        };
        assert!(matches!(event, SessionEvent::ToolCallStarted { .. }));
    }
}