gate4agent 0.4.5

Transport library for CLI AI agents — first tier: Claude Code, Codex, Kimi, Grok. Pipe, PTY, ACP (Agent Client Protocol), and Daemon transports.
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
//! ACP host-side handler trait, host policy, and bridge adapter.
//!
//! Rather than forcing callers to implement the low-level [`HostHandler`] with
//! raw string/JSON matching, this module provides a typed trait
//! [`AcpHostHandler`] with safe defaults. Internally [`AcpHostAdapter`]
//! bridges from [`HostHandler`] → [`AcpHostHandler`], so the reader loop can
//! use the existing RPC infrastructure unchanged.
//!
//! [`HostPolicy`] is the one production implementation's decision function:
//! it picks what `initialize` declares in `clientCapabilities` AND how
//! `session/request_permission` answers, so the two can never drift apart
//! (a policy that declares `terminal: false` also never selects an allow
//! option for an `execute` tool call, and vice versa).

use std::path::PathBuf;

use serde_json::{json, Value};

use crate::core::types::HostDecisionAuthority;
use crate::rpc::handler::{HostHandler, HostOutcome};
use crate::rpc::message::RpcError;

use super::gate::{self, DangerousCommandGate};
use super::protocol::{
    ClientCapabilities, FsCapabilities, FsReadParams, FsWriteParams, PermissionOption,
    PermissionOptionKind, PermissionOutcome, PermissionRequestParams, PermissionToolCall,
    TerminalCreateParams, TerminalExitStatus, TerminalIdParams, TerminalOutputResult, ToolKind,
};
use super::terminal::TerminalStore;

// ---------------------------------------------------------------------------
// HostRequestError — Denied vs Failed
// ---------------------------------------------------------------------------

/// One [`AcpHostHandler`] method's refusal, distinguishing a decision made
/// BEFORE any operation ran (`Denied` -- the dangerous-command gate or
/// `HostPolicy` refused it outright) from a failure encountered WHILE
/// running an operation that gate/policy had already authorized (`Failed`
/// -- a spawn error, a missing file, any I/O problem). Collapsing the two
/// into a single `Err(String)` is exactly the bug this type exists to rule
/// out: an execution failure on an ALLOWED `terminal/create` call used to
/// read back as `HostRequestDecision::Denied`, minting a policy block that
/// never happened (see `HostCallOutcome`, where a `Result<T,
/// HostRequestError>` becomes the audit-facing classification, and
/// `crate::core::types::HostRequestOutcome`, what `Failed` maps onto there).
///
/// [`AcpHostAdapter::handle`]'s JSON-RPC mapping reads only
/// [`message`](Self::message) from either variant -- the wire `RpcError` an
/// agent sees is byte-for-byte unchanged by this type existing; it exists
/// so the reader loop's audit trail can read the honest classification off
/// the SAME call, instead of guessing it back out of the refusal prose.
#[derive(Debug, Clone)]
pub(crate) enum HostRequestError {
    /// The gate or `HostPolicy` refused this call before anything executed.
    Denied(String),
    /// The call was authorized, but failed while executing it.
    Failed(String),
}

impl HostRequestError {
    /// The refusal/failure text, whichever variant this is -- what
    /// [`AcpHostAdapter::handle`] puts on the wire `RpcError`, unchanged
    /// either way.
    pub(crate) fn message(&self) -> &str {
        match self {
            HostRequestError::Denied(m) | HostRequestError::Failed(m) => m,
        }
    }
}

// ---------------------------------------------------------------------------
// AcpHostHandler — typed trait
// ---------------------------------------------------------------------------

/// Typed handler for agent → host ACP requests.
///
/// All methods have default implementations that return safe denials, so
/// callers only need to override the operations they actually support.
///
/// Implementations must be `Send + Sync` because the handler is called from
/// the reader loop's blocking thread.
pub(crate) trait AcpHostHandler: Send + Sync {
    /// Agent wants to read a file from the host filesystem.
    fn fs_read_text_file(&self, params: &FsReadParams) -> Result<String, HostRequestError> {
        Err(HostRequestError::Denied(format!(
            "fs/read_text_file not supported: {}",
            params.path
        )))
    }

    /// Agent wants to write (fully replace) a file on the host filesystem.
    fn fs_write_text_file(&self, params: &FsWriteParams) -> Result<(), HostRequestError> {
        Err(HostRequestError::Denied(format!(
            "fs/write_text_file not supported: {}",
            params.path
        )))
    }

    /// Agent wants to run a command on the host and get a terminal id back.
    fn terminal_create(&self, params: &TerminalCreateParams) -> Result<String, HostRequestError> {
        let _ = params;
        Err(HostRequestError::Denied("terminal/create not supported".to_string()))
    }

    /// Agent wants the accumulated output of a terminal it created earlier.
    fn terminal_output(
        &self,
        params: &TerminalIdParams,
    ) -> Result<TerminalOutputResult, HostRequestError> {
        let _ = params;
        Err(HostRequestError::Denied("terminal/output not supported".to_string()))
    }

    /// Agent wants to block until a terminal's command exits.
    fn terminal_wait_for_exit(
        &self,
        params: &TerminalIdParams,
    ) -> Result<TerminalExitStatus, HostRequestError> {
        let _ = params;
        Err(HostRequestError::Denied("terminal/wait_for_exit not supported".to_string()))
    }

    /// Agent wants to kill a terminal's command without releasing the id.
    fn terminal_kill(&self, params: &TerminalIdParams) -> Result<(), HostRequestError> {
        let _ = params;
        Err(HostRequestError::Denied("terminal/kill not supported".to_string()))
    }

    /// Agent is done with a terminal — kill it if still running and forget it.
    fn terminal_release(&self, params: &TerminalIdParams) -> Result<(), HostRequestError> {
        let _ = params;
        Err(HostRequestError::Denied("terminal/release not supported".to_string()))
    }

    /// Agent is requesting permission to perform a tool call.
    ///
    /// Per the ACP spec, a client (host) "MAY automatically allow or reject
    /// permission requests according to the user['s] settings" -- this is
    /// not a UI hook, it's a decision function. The default is the safest
    /// possible answer: never select any of the offered options.
    fn request_permission(&self, params: &PermissionRequestParams) -> PermissionOutcome {
        let _ = params;
        PermissionOutcome::Cancelled
    }

    /// The refusal text behind a `session/request_permission` call this
    /// session's [`request_permission`](Self::request_permission) would
    /// decline -- ACP models a decline as a normal `outcome` response, never
    /// an RPC error, so unlike every other method here (`fs/read_text_file`,
    /// `terminal/create`, ...) there is no `Err(String)` this reason can ride
    /// on; this is the dedicated path instead. Only meaningful for a call the
    /// caller already knows was NOT granted -- the caller (`acp::reader`)
    /// only ever asks this after computing that fact from the actual
    /// `PermissionOutcome`, never before. The default is `None`: only
    /// [`PolicyHostHandler`] has a reason to compute here at all.
    fn permission_refusal_reason(&self, params: &PermissionRequestParams) -> Option<String> {
        let _ = params;
        None
    }

    /// Whether the dangerous-command gate (`super::gate`) would block this
    /// `session/request_permission` call outright, independent of whatever
    /// [`request_permission`](Self::request_permission) itself would go on
    /// to decide.
    ///
    /// The default answer is `false` -- only [`PolicyHostHandler`] (the one
    /// implementation the gate is actually wired into) overrides it.
    /// [`AcpHostAdapter::handle_deferrable`] calls this BEFORE deciding
    /// whether to defer a `session/request_permission` call to an operator,
    /// so a gate block is always decided immediately and is NEVER left
    /// waiting on one -- the dangerous-command gate outranks deferral
    /// exactly as it already outranks [`HostPolicy`] (see the gate's own
    /// module doc comment). `request_permission` checks the same condition
    /// for the immediate path, so the two can never disagree about whether
    /// a given call is gate-blocked.
    fn permission_blocked_by_gate(&self, tool_call: &PermissionToolCall) -> bool {
        let _ = tool_call;
        false
    }

    /// Whether the dangerous-command gate would block this `terminal/
    /// create` call outright, independent of whatever
    /// [`terminal_create`](Self::terminal_create) itself would go on to
    /// decide -- the `terminal/create` counterpart to
    /// [`permission_blocked_by_gate`](Self::permission_blocked_by_gate).
    ///
    /// The default answer is `false` -- only [`PolicyHostHandler`] overrides
    /// it. [`AcpHostAdapter::decision_authority`] calls this purely to
    /// classify WHO decided a completed `terminal/create` call for
    /// `AgentEvent::RpcIncomingRequest`'s audit trail; it is never consulted
    /// to change what `terminal_create` itself decides -- that call runs the
    /// exact same check on its own, so the two can never disagree about
    /// whether a given call is gate-blocked.
    fn terminal_create_blocked_by_gate(&self, params: &TerminalCreateParams) -> bool {
        let _ = params;
        false
    }
}

// ---------------------------------------------------------------------------
// HostPolicy
// ---------------------------------------------------------------------------

/// The host's authority mode for one ACP session — governs both what
/// `clientCapabilities` `initialize` declares and how `session/request_
/// permission` is answered. Modes exist primarily so a parent agent can
/// bound a child agent's authority, not to prompt a human: every mode here
/// resolves permission requests on its own, per the ACP spec's explicit
/// allowance for a client to decide automatically.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostPolicy {
    /// Everything allowed, no distinctions. Prefers `allow_always` options
    /// so an agent that respects them stops asking for the same class of
    /// operation again this session.
    Yolo,
    /// Reads, writes, and command execution are all allowed without
    /// prompting — the default. Prefers `allow_once` options over
    /// `allow_always`, so each grant stays an individually observable
    /// decision (see `AgentEvent::RpcIncomingRequest`) rather than one the
    /// agent stops asking about.
    Auto,
    /// Only read-shaped operations (`fs/read_text_file`, and tool calls of
    /// kind `read`/`search`/`think`/`fetch`) are allowed; writes, deletes,
    /// moves, and command execution are refused.
    ReadOnly,
    /// Refuse everything. Today's behavior prior to `HostPolicy` existing;
    /// kept reachable because it is load-bearing for the fail-closed tests.
    Deny,
}

impl Default for HostPolicy {
    /// `Auto` — the owner's decision: default to answering permission
    /// requests without a human in the loop, not to fail closed.
    fn default() -> Self {
        HostPolicy::Auto
    }
}

// ---------------------------------------------------------------------------
// PermissionDeferral
// ---------------------------------------------------------------------------

/// Session-level policy for [`AcpHostAdapter::handle_deferrable`]: whether
/// `session/request_permission` may return [`HostOutcome::Deferred`] instead
/// of being decided by the wrapped [`AcpHostHandler`] the instant it arrives.
///
/// This is a THIRD axis alongside [`HostPolicy`] and
/// [`super::gate::DangerousCommandGate`] -- and, like the gate, it is
/// switched independently of `HostPolicy` rather than folded into it: a
/// permissive `HostPolicy` (`Yolo`, `Auto`) still answers every permission
/// request itself when deferral is `Disabled`, and a restrictive one
/// (`ReadOnly`, `Deny`) still gets deferred when it is `Enabled` -- "how much
/// authority does this session have" and "should an operator get a chance to
/// answer before that authority decides" are independent questions. Default:
/// `Disabled`, so a caller that never sets
/// [`crate::acp::session::AcpSessionOptions::defer_permission_requests`]
/// gets exactly today's behavior.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PermissionDeferral {
    /// [`AcpHostAdapter::handle_deferrable`] is byte-for-byte
    /// `Immediate(self.handle(...))` for every method, matching the
    /// [`HostHandler`] trait's own default.
    Disabled,
    /// `session/request_permission` returns `Deferred` UNLESS the
    /// dangerous-command gate would block it -- see
    /// [`AcpHostHandler::permission_blocked_by_gate`]. Every other method is
    /// still decided immediately regardless.
    Enabled,
}

impl Default for PermissionDeferral {
    fn default() -> Self {
        PermissionDeferral::Disabled
    }
}

impl HostPolicy {
    /// The `clientCapabilities` this policy declares at `initialize`.
    pub(crate) fn client_capabilities(self) -> ClientCapabilities {
        match self {
            HostPolicy::Yolo | HostPolicy::Auto => ClientCapabilities {
                fs: FsCapabilities { read_text_file: true, write_text_file: true },
                terminal: true,
            },
            HostPolicy::ReadOnly => ClientCapabilities {
                fs: FsCapabilities { read_text_file: true, write_text_file: false },
                terminal: false,
            },
            HostPolicy::Deny => ClientCapabilities {
                fs: FsCapabilities { read_text_file: false, write_text_file: false },
                terminal: false,
            },
        }
    }

    /// Whether this policy allows real file writes and command execution.
    fn allows_mutation(self) -> bool {
        matches!(self, HostPolicy::Yolo | HostPolicy::Auto)
    }

    /// Whether this policy allows real file reads.
    fn allows_read(self) -> bool {
        !matches!(self, HostPolicy::Deny)
    }

    /// Pick one of the agent's offered `options` for a `session/request_
    /// permission` call, or decline to pick any of them.
    ///
    /// `options` is whatever subset of the four known
    /// [`PermissionOptionKind`] values the agent chose to offer -- this
    /// walks a preference order and returns the first offered kind that
    /// matches, so it tolerates an agent that omits some (or three) of
    /// them.
    ///
    /// When that walk finds nothing AND this policy prefers allow (`Yolo`,
    /// `Auto`, or `ReadOnly` on a read-shaped call), it does not stop there:
    /// a third-party adapter that words its options differently (every
    /// `kind` string [`PermissionOptionKind::Unknown`]) must not read back
    /// as a refusal when the policy would have allowed the call under any
    /// of the four spellings it does recognise -- see
    /// [`allow_ish_option`]'s own doc comment for the exact rule. This
    /// fallback never runs when `prefer_allow` is false: `ReadOnly` on a
    /// non-read call and `Deny` keep returning `Cancelled` exactly as
    /// before, same as when the walk itself finds a known reject-kind
    /// option.
    ///
    /// Every `Cancelled` result this returns is logged with every option
    /// the agent actually offered (see [`warn_permission_cancelled`]) --
    /// `PermissionOutcome` has no field to carry a reason on, so this is
    /// the only place that reason is ever recorded.
    pub(crate) fn select_permission_option(
        self,
        tool_call: &PermissionToolCall,
        options: &[PermissionOption],
    ) -> PermissionOutcome {
        let prefer_allow = match self {
            HostPolicy::Yolo | HostPolicy::Auto => true,
            HostPolicy::ReadOnly => tool_call.kind.is_read_only(),
            HostPolicy::Deny => false,
        };
        let preference: &[PermissionOptionKind] = if prefer_allow {
            if matches!(self, HostPolicy::Yolo) {
                &[PermissionOptionKind::AllowAlways, PermissionOptionKind::AllowOnce]
            } else {
                &[PermissionOptionKind::AllowOnce, PermissionOptionKind::AllowAlways]
            }
        } else {
            &[PermissionOptionKind::RejectOnce, PermissionOptionKind::RejectAlways]
        };
        let outcome = select_offered_option(options, preference);

        let outcome = if prefer_allow && outcome == PermissionOutcome::Cancelled {
            match allow_ish_option(options) {
                Some(option) => {
                    eprintln!(
                        "[gate4agent::acp::host] session/request_permission: no known \
                         PermissionOptionKind offered under {self:?} for toolCallId={:?}; \
                         falling back to allow-ish option optionId={:?} name={:?} kind={:?}",
                        tool_call.tool_call_id, option.option_id, option.name, option.kind
                    );
                    PermissionOutcome::Selected { option_id: option.option_id.clone() }
                }
                None => outcome,
            }
        } else {
            outcome
        };

        if outcome == PermissionOutcome::Cancelled {
            warn_permission_cancelled(self, tool_call, options);
        }
        outcome
    }
}

/// Find the first offered option whose `optionId` or `name` reads as an
/// allow -- case-insensitive `contains` of any of `allow`, `approve`,
/// `always`, `yes` -- for [`HostPolicy::select_permission_option`]'s
/// fallback when its by-`kind` preference walk found none of the four
/// known kinds it was looking for. Only ever consulted when that policy
/// already decided `prefer_allow`, so this never fires for `ReadOnly` on a
/// non-read call or for `Deny`; it exists purely so an adapter that offers
/// every option under an unfamiliar [`PermissionOptionKind::Unknown`]
/// still gets an allow when the policy would have picked one under any of
/// the four spellings it recognises.
fn allow_ish_option(options: &[PermissionOption]) -> Option<&PermissionOption> {
    const ALLOW_ISH: [&str; 4] = ["allow", "approve", "always", "yes"];
    options.iter().find(|option| {
        let id = option.option_id.to_lowercase();
        let name = option.name.to_lowercase();
        ALLOW_ISH.iter().any(|needle| id.contains(needle) || name.contains(needle))
    })
}

/// Log every option the agent actually offered (`optionId`, `name`, `kind`)
/// plus the deciding `policy`, at the moment [`HostPolicy::
/// select_permission_option`] is about to answer `Cancelled` -- ACP has no
/// wire field for a `Cancelled` outcome to carry a reason on, so without
/// this call the actual inputs behind a refusal are gone the instant it is
/// sent. An empty `options` slice is called out by name: that is either
/// "the agent offered nothing" or "its `PermissionRequestParams` failed to
/// parse and every `.ok()`/`parse_params` site upstream already fell back
/// to an empty list" -- the parse-failure sites themselves warn separately
/// (see [`warn_permission_params_parse_failed`]) with the actual serde
/// error text, this call only ever sees the already-empty result.
fn warn_permission_cancelled(policy: HostPolicy, tool_call: &PermissionToolCall, options: &[PermissionOption]) {
    if options.is_empty() {
        eprintln!(
            "[gate4agent::acp::host] session/request_permission cancelled under {policy:?} for \
             toolCallId={:?}: no options offered (params may have failed to parse, or the agent \
             offered none)",
            tool_call.tool_call_id
        );
        return;
    }
    let described: Vec<String> = options
        .iter()
        .map(|option| {
            format!(
                "(optionId={:?}, name={:?}, kind={:?})",
                option.option_id, option.name, option.kind
            )
        })
        .collect();
    eprintln!(
        "[gate4agent::acp::host] session/request_permission cancelled under {policy:?} for \
         toolCallId={:?}: offered options were [{}]",
        tool_call.tool_call_id,
        described.join(", ")
    );
}

/// Log that a `session/request_permission` `params` blob failed to
/// deserialize into [`PermissionRequestParams`], naming which call site saw
/// it (`context`) and the serde error text (`detail`). Every site that
/// reads this type off raw `Value` folds a parse failure into a fallback --
/// `false` in [`AcpHostAdapter::decision_authority`], `None` in
/// [`AcpHostAdapter::permission_refusal_reason`], the immediate
/// non-deferred path in [`AcpHostAdapter::dispatch_deferrable`], or the
/// `INVALID_PARAMS` `RpcError` `dispatch` already sends back for
/// `session/request_permission` itself -- without this call the actual
/// reason a permission request never even reached [`HostPolicy::
/// select_permission_option`] was invisible; the host just looked like it
/// refused on purpose.
fn warn_permission_params_parse_failed(context: &str, detail: &str) {
    eprintln!(
        "[gate4agent::acp::host] session/request_permission params failed to parse ({context}): {detail}"
    );
}

/// Walk `preference` in order and return the first kind the agent actually
/// offered, as a `Selected` outcome naming that option's own id; `Cancelled`
/// if it offered none of them.
///
/// Shared deliberately between [`HostPolicy::select_permission_option`] and
/// [`super::session::AcpSession::resolve_pending_request_as`]: policy and
/// operator must pick from the same list by the same rule, or the same intent
/// would mean two different things depending on who acted on it. Neither
/// caller may invent an `option_id` — an id the agent never offered is not
/// refused by the agent so much as ignored by it, which would grant nothing
/// while reporting success.
pub(crate) fn select_offered_option(
    options: &[PermissionOption],
    preference: &[PermissionOptionKind],
) -> PermissionOutcome {
    for kind in preference {
        if let Some(option) = options.iter().find(|option| option.kind == *kind) {
            return PermissionOutcome::Selected { option_id: option.option_id.clone() };
        }
    }
    PermissionOutcome::Cancelled
}

// ---------------------------------------------------------------------------
// PolicyHostHandler — the one production AcpHostHandler
// ---------------------------------------------------------------------------

/// The production [`AcpHostHandler`]: serves real filesystem reads/writes
/// and real terminal execution, gated by a [`HostPolicy`]. This is the only
/// handler `AcpSession` ever constructs outside tests.
pub(crate) struct PolicyHostHandler {
    policy: HostPolicy,
    working_dir: PathBuf,
    terminals: TerminalStore,
    /// Whether the dangerous-command gate (`super::gate`) runs ahead of
    /// `policy` for `terminal/create` and `execute`-kind `session/request_
    /// permission` -- a decision independent of `policy` itself, see
    /// [`DangerousCommandGate`].
    dangerous_command_gate: DangerousCommandGate,
}

impl PolicyHostHandler {
    pub(crate) fn new(
        policy: HostPolicy,
        working_dir: PathBuf,
        dangerous_command_gate: DangerousCommandGate,
    ) -> Self {
        Self { policy, working_dir, terminals: TerminalStore::new(), dangerous_command_gate }
    }

    /// The directory a `terminal/create` call actually runs in: its own
    /// `cwd` override when present, otherwise the session's working
    /// directory -- shared by `AcpHostHandler::terminal_create` and
    /// `AcpHostHandler::terminal_create_blocked_by_gate` so the two never
    /// evaluate the gate against different directories.
    fn terminal_create_cwd(&self, cwd_override: Option<&str>) -> PathBuf {
        cwd_override
            .map(PathBuf::from)
            .unwrap_or_else(|| self.working_dir.clone())
    }
}

/// Apply an ACP `fs/read_text_file` line window (`line` 1-based, `limit` a
/// line count) to already-read file content. Absent both, the whole file.
fn windowed_read(content: &str, line: Option<u32>, limit: Option<u32>) -> String {
    if line.is_none() && limit.is_none() {
        return content.to_owned();
    }
    let start = line.unwrap_or(1).saturating_sub(1) as usize;
    let lines = content.split_inclusive('\n').skip(start);
    match limit {
        Some(n) => lines.take(n as usize).collect(),
        None => lines.collect(),
    }
}

impl AcpHostHandler for PolicyHostHandler {
    fn fs_read_text_file(&self, params: &FsReadParams) -> Result<String, HostRequestError> {
        if !self.policy.allows_read() {
            return Err(HostRequestError::Denied(format!(
                "fs/read_text_file denied by host policy: {}",
                params.path
            )));
        }
        // Authorized -- anything past this point is an I/O problem, not a
        // refusal: the file may not exist, be unreadable, or not be valid
        // UTF-8. `Failed`, never `Denied`.
        let content = std::fs::read_to_string(&params.path)
            .map_err(|e| HostRequestError::Failed(e.to_string()))?;
        Ok(windowed_read(&content, params.line, params.limit))
    }

    fn fs_write_text_file(&self, params: &FsWriteParams) -> Result<(), HostRequestError> {
        if !self.policy.allows_mutation() {
            return Err(HostRequestError::Denied(format!(
                "fs/write_text_file denied by host policy: {}",
                params.path
            )));
        }
        std::fs::write(&params.path, &params.content)
            .map_err(|e| HostRequestError::Failed(e.to_string()))
    }

    fn terminal_create(&self, params: &TerminalCreateParams) -> Result<String, HostRequestError> {
        // The dangerous-command gate runs before `policy` gets a say, and
        // is not skipped by any `HostPolicy` value including `Yolo` -- see
        // `DangerousCommandGate`'s doc comment for why this is a second,
        // separately-switched axis rather than folded into the policy.
        if self.terminal_create_blocked_by_gate(params) {
            let cwd = self.terminal_create_cwd(params.cwd.as_deref());
            let verdict = gate::evaluate_command(&params.command, &params.args, &cwd);
            // `terminal_create_blocked_by_gate` already proved this is a
            // `Block` verdict -- `refusal_message()` only returns `None`
            // for `Allow`/`Uncertain`, neither of which `is_blocked()`
            // reports as blocked.
            let refusal = verdict.refusal_message().unwrap_or_default();
            return Err(HostRequestError::Denied(format!("terminal/create {refusal}")));
        }
        if !self.policy.allows_mutation() {
            return Err(HostRequestError::Denied("terminal/create denied by host policy".to_string()));
        }
        // Authorized -- `TerminalStore::create`'s own `Err` is always a
        // spawn/I/O problem from here (empty-command validation, the
        // `Command::spawn` call itself, a missing stdout/stderr pipe, a
        // poisoned terminal-table mutex), never a second refusal: this is
        // the exact call whose OS-level spawn failure used to be reported
        // as `Denied { by: Gate | Policy }` (a block that never happened)
        // instead of an authorized call that failed running. `Failed`.
        self.terminals.create(&self.working_dir, params).map_err(HostRequestError::Failed)
    }

    fn terminal_output(
        &self,
        params: &TerminalIdParams,
    ) -> Result<TerminalOutputResult, HostRequestError> {
        // No gate/policy check precedes this call -- every error path here
        // (unknown terminal id, a poisoned mutex) is an execution problem,
        // never a refusal decided ahead of time.
        self.terminals.output(&params.terminal_id).map_err(HostRequestError::Failed)
    }

    fn terminal_wait_for_exit(
        &self,
        params: &TerminalIdParams,
    ) -> Result<TerminalExitStatus, HostRequestError> {
        self.terminals.wait_for_exit(&params.terminal_id).map_err(HostRequestError::Failed)
    }

    fn terminal_kill(&self, params: &TerminalIdParams) -> Result<(), HostRequestError> {
        self.terminals.kill(&params.terminal_id).map_err(HostRequestError::Failed)
    }

    fn terminal_release(&self, params: &TerminalIdParams) -> Result<(), HostRequestError> {
        self.terminals.release(&params.terminal_id).map_err(HostRequestError::Failed)
    }

    fn request_permission(&self, params: &PermissionRequestParams) -> PermissionOutcome {
        // Same gate, same "above the policy" placement as `terminal_create`
        // -- and now the single source of truth `AcpHostAdapter::
        // handle_deferrable` also consults (via `permission_blocked_by_gate`
        // below) before it will even consider deferring this call to an
        // operator, so the two paths can never disagree about whether a
        // given call is gate-blocked. A `Block` verdict here has no wire
        // field to carry its reason on (`PermissionOutcome` is
        // `Selected`/`Cancelled`, not an error), so it is answered the same
        // way `HostPolicy::Deny` answers any execute-kind request: prefer a
        // reject-kind option the agent offered, else decline to pick any of
        // them.
        if self.permission_blocked_by_gate(&params.tool_call) {
            return HostPolicy::Deny.select_permission_option(&params.tool_call, &params.options);
        }
        self.policy.select_permission_option(&params.tool_call, &params.options)
    }

    /// Mirrors [`request_permission`](Self::request_permission)'s own two
    /// branches exactly, so the reason always describes whichever one
    /// actually decided: the gate's own rule-and-argument text
    /// (`GateVerdict::refusal_message`, the SAME verdict `terminal/create`'s
    /// `Err(String)` already carries this text from) when gate-blocked, else
    /// a fixed sentence naming host policy as the authority -- `terminal/
    /// create`'s own denial has an equally fixed "denied by host policy"
    /// text for the non-gate case, this is that sentence's `session/
    /// request_permission` counterpart. The caller only invokes this after
    /// already establishing the call was NOT granted (see the trait method's
    /// own doc comment), so a non-gate-blocked call reaching here is a
    /// policy denial by construction, never a grant this text would
    /// mischaracterize.
    fn permission_refusal_reason(&self, params: &PermissionRequestParams) -> Option<String> {
        if self.permission_blocked_by_gate(&params.tool_call) {
            return gate::evaluate_permission_tool_call(&params.tool_call, &self.working_dir)
                .refusal_message();
        }
        Some("session/request_permission denied by host policy".to_string())
    }

    fn permission_blocked_by_gate(&self, tool_call: &PermissionToolCall) -> bool {
        self.dangerous_command_gate == DangerousCommandGate::Enforced
            && tool_call.kind == ToolKind::Execute
            && gate::evaluate_permission_tool_call(tool_call, &self.working_dir).is_blocked()
    }

    fn terminal_create_blocked_by_gate(&self, params: &TerminalCreateParams) -> bool {
        self.dangerous_command_gate == DangerousCommandGate::Enforced
            && gate::evaluate_command(
                &params.command,
                &params.args,
                &self.terminal_create_cwd(params.cwd.as_deref()),
            )
            .is_blocked()
    }
}

// ---------------------------------------------------------------------------
// AcpHostAdapter — bridges AcpHostHandler → HostHandler
// ---------------------------------------------------------------------------

/// Bridges [`AcpHostHandler`] → [`HostHandler`] for use in the reader loop.
///
/// Wraps `Arc<dyn AcpHostHandler>` so it can be cloned cheaply without
/// requiring `'static + Clone` bounds on the trait, plus the session's
/// [`PermissionDeferral`] policy -- the one piece `handle_deferrable` needs
/// that a bare `Arc<dyn AcpHostHandler>` cannot answer on its own (whether
/// THIS session is even allowed to leave a `session/request_permission`
/// call unanswered for a while).
pub(crate) struct AcpHostAdapter {
    inner: std::sync::Arc<dyn AcpHostHandler>,
    deferral: PermissionDeferral,
}

impl AcpHostAdapter {
    pub(crate) fn new(
        inner: std::sync::Arc<dyn AcpHostHandler>,
        deferral: PermissionDeferral,
    ) -> Self {
        Self { inner, deferral }
    }

    /// Classify WHO decided (or will decide) `method`/`params`, for
    /// [`crate::core::types::HostRequestDecision`]'s `by` field.
    ///
    /// Purely observational: it re-runs the exact same gate query
    /// [`handle`](HostHandler::handle)/[`handle_deferrable`] already
    /// consulted (`permission_blocked_by_gate`/
    /// `terminal_create_blocked_by_gate`) so the two can never disagree
    /// about whether a given call was gate-blocked, but it never feeds back
    /// into what either of those methods decides.
    ///
    /// Only `terminal/create` and `session/request_permission` can ever
    /// come back `Gate` -- every other method answers `Policy` here, which
    /// is correct even for `terminal/output`/`terminal/wait_for_exit`/
    /// `terminal/kill`/`terminal/release` (no `HostPolicy` value gates
    /// those beyond `terminal/create` itself, so "decided immediately, not
    /// gate-blocked, not deferred" -- `Policy`'s own definition -- is the
    /// honest answer for them too). `Deferred`, `Operator`, and
    /// `DeadlinePolicy` are never returned here -- a caller reaches this
    /// only for a request that is being decided NOW, on this thread, and
    /// those three describe request states this call never sees (see
    /// `crate::core::types::HostDecisionAuthority`'s own doc comment for
    /// why `Operator`/`DeadlinePolicy` only ever come from `AcpSession::
    /// resolve_pending_request`/`expire_deadlines` instead).
    pub(crate) fn decision_authority(
        &self,
        method: &str,
        params: Option<&Value>,
    ) -> HostDecisionAuthority {
        let gate_blocked = match method {
            "terminal/create" => params
                .and_then(|v| serde_json::from_value::<TerminalCreateParams>(v.clone()).ok())
                .is_some_and(|p| self.inner.terminal_create_blocked_by_gate(&p)),
            "session/request_permission" => match params {
                Some(v) => match serde_json::from_value::<PermissionRequestParams>(v.clone()) {
                    Ok(p) => self.inner.permission_blocked_by_gate(&p.tool_call),
                    Err(e) => {
                        warn_permission_params_parse_failed("decision_authority", &e.to_string());
                        false
                    }
                },
                None => false,
            },
            _ => false,
        };
        if gate_blocked {
            HostDecisionAuthority::Gate
        } else {
            HostDecisionAuthority::Policy
        }
    }

    /// The refusal text for a `session/request_permission` call the caller
    /// already knows was NOT granted -- reparses `params` into
    /// [`PermissionRequestParams`] the same way [`decision_authority`]
    /// (Self::decision_authority) does, then delegates to the wrapped
    /// handler's own [`AcpHostHandler::permission_refusal_reason`]. `None`
    /// when `params` fails to parse (the same defensive, practically
    /// unreachable branch `decision_authority` falls back on for the same
    /// reason) or when the wrapped handler has no reason to report.
    pub(crate) fn permission_refusal_reason(&self, params: Option<&Value>) -> Option<String> {
        let parsed = match serde_json::from_value::<PermissionRequestParams>(params?.clone()) {
            Ok(p) => p,
            Err(e) => {
                warn_permission_params_parse_failed("permission_refusal_reason", &e.to_string());
                return None;
            }
        };
        self.inner.permission_refusal_reason(&parsed)
    }
}

// ---------------------------------------------------------------------------
// HostCallOutcome / dispatch — the single place Denied vs Granted(-but-
// Failed) is decided, for every method whose refusal is modeled as an `Err`
// ---------------------------------------------------------------------------

/// How one dispatched call classifies, for the reader loop's audit trail
/// (`crate::core::types::AgentEvent::RpcIncomingRequest`) -- computed
/// together with the wire response in [`AcpHostAdapter::dispatch`] so the
/// two can never disagree about the SAME call.
///
/// Not meaningful for `session/request_permission`: that method has no
/// execution step to fail (selecting or cancelling an offered option is not
/// I/O), so its `Granted`/`Denied` classification is recovered entirely
/// from the `PermissionOutcome` it returns, by `acp::reader::
/// request_granted` -- unchanged by this type's existence. `dispatch`
/// answers `Granted` for it unconditionally; callers must not read that as
/// a claim about what was actually decided.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum HostCallOutcome {
    /// The gate or `HostPolicy` refused this call before anything executed.
    Denied,
    /// The call was authorized and ran without error.
    Granted,
    /// The call was authorized but failed while running it. `error` is the
    /// same bounded text the wire `RpcError.message` already carries for
    /// this call.
    GrantedButFailed { error: String },
}

/// The wire response `handle` would have returned for this call, paired
/// with its [`HostCallOutcome`] -- both computed from the SAME single
/// dispatch, never from two separate calls (a `terminal/create` call must
/// spawn its command exactly once).
pub(crate) struct HostCallResult {
    pub(crate) response: Result<Value, RpcError>,
    pub(crate) outcome: HostCallOutcome,
}

/// Build a [`HostCallResult`] from one [`AcpHostHandler`] method's `Err`,
/// reading the wire `code` this method has always used (`PERMISSION_DENIED`
/// for `fs/*` and `terminal/create`, `NOT_FOUND` for the other `terminal/*`
/// methods) and classifying `Denied`/`GrantedButFailed` off the SAME
/// [`HostRequestError`] variant the message came from.
fn host_call_result_from_error(code: i32, err: HostRequestError) -> HostCallResult {
    let message = err.message().to_string();
    let outcome = match err {
        HostRequestError::Denied(_) => HostCallOutcome::Denied,
        HostRequestError::Failed(_) => HostCallOutcome::GrantedButFailed { error: message.clone() },
    };
    HostCallResult { response: Err(RpcError { code, message, data: None }), outcome }
}

/// Outcome of [`AcpHostAdapter::dispatch_deferrable`] -- the
/// `HostCallOutcome`-carrying counterpart to [`HostOutcome`] the reader
/// loop calls directly on the concrete `AcpHostAdapter` (not through the
/// `HostHandler` trait), because `HostOutcome::Immediate` has no room for
/// the outcome classification `Denied`/`Granted`/`GrantedButFailed` reads
/// need.
pub(crate) enum HostDispatchOutcome {
    /// Decided now. `response` is byte-for-byte what
    /// [`HostHandler::handle`] would have returned for the same call.
    Immediate { response: Result<Value, RpcError>, outcome: HostCallOutcome },
    /// See [`HostOutcome::Deferred`] -- identical meaning.
    Deferred,
}

impl AcpHostAdapter {
    /// Dispatches one agent → host request, computing the wire response and
    /// its [`HostCallOutcome`] together from a single call to the wrapped
    /// [`AcpHostHandler`] method -- the one place both
    /// [`HostHandler::handle`] and [`Self::dispatch_deferrable`] (and, through
    /// it, the reader loop's audit trail) read from, so a `terminal/create`
    /// spawn or an `fs/write_text_file` write happens exactly once no matter
    /// which of those two callers is asking.
    fn dispatch(&self, method: &str, params: Option<Value>) -> HostCallResult {
        match method {
            "fs/read_text_file" => {
                let p: FsReadParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.fs_read_text_file(&p) {
                    Ok(content) => HostCallResult {
                        response: Ok(json!({ "content": content })),
                        outcome: HostCallOutcome::Granted,
                    },
                    Err(err) => host_call_result_from_error(RpcError::PERMISSION_DENIED, err),
                }
            }

            "fs/write_text_file" => {
                let p: FsWriteParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.fs_write_text_file(&p) {
                    Ok(()) => {
                        HostCallResult { response: Ok(json!({})), outcome: HostCallOutcome::Granted }
                    }
                    Err(err) => host_call_result_from_error(RpcError::PERMISSION_DENIED, err),
                }
            }

            "terminal/create" => {
                let p: TerminalCreateParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.terminal_create(&p) {
                    Ok(terminal_id) => HostCallResult {
                        response: Ok(json!({ "terminalId": terminal_id })),
                        outcome: HostCallOutcome::Granted,
                    },
                    Err(err) => host_call_result_from_error(RpcError::PERMISSION_DENIED, err),
                }
            }

            "terminal/output" => {
                let p: TerminalIdParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.terminal_output(&p) {
                    Ok(result) => HostCallResult {
                        response: Ok(serde_json::to_value(result).unwrap_or(Value::Null)),
                        outcome: HostCallOutcome::Granted,
                    },
                    Err(err) => host_call_result_from_error(RpcError::NOT_FOUND, err),
                }
            }

            "terminal/wait_for_exit" => {
                let p: TerminalIdParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.terminal_wait_for_exit(&p) {
                    Ok(result) => HostCallResult {
                        response: Ok(serde_json::to_value(result).unwrap_or(Value::Null)),
                        outcome: HostCallOutcome::Granted,
                    },
                    Err(err) => host_call_result_from_error(RpcError::NOT_FOUND, err),
                }
            }

            "terminal/kill" => {
                let p: TerminalIdParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.terminal_kill(&p) {
                    Ok(()) => {
                        HostCallResult { response: Ok(json!({})), outcome: HostCallOutcome::Granted }
                    }
                    Err(err) => host_call_result_from_error(RpcError::NOT_FOUND, err),
                }
            }

            "terminal/release" => {
                let p: TerminalIdParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied },
                };
                match self.inner.terminal_release(&p) {
                    Ok(()) => {
                        HostCallResult { response: Ok(json!({})), outcome: HostCallOutcome::Granted }
                    }
                    Err(err) => host_call_result_from_error(RpcError::NOT_FOUND, err),
                }
            }

            "session/request_permission" => {
                let p: PermissionRequestParams = match parse_params(params) {
                    Ok(p) => p,
                    Err(e) => {
                        warn_permission_params_parse_failed("dispatch", &e.message);
                        return HostCallResult { response: Err(e), outcome: HostCallOutcome::Denied };
                    }
                };
                let outcome = self.inner.request_permission(&p);
                HostCallResult {
                    response: Ok(serde_json::to_value(outcome).unwrap_or(Value::Null)),
                    // See `HostCallOutcome`'s own doc comment -- never read
                    // by the reader loop for this method.
                    outcome: HostCallOutcome::Granted,
                }
            }

            other => HostCallResult {
                response: Err(RpcError::method_not_found(other)),
                outcome: HostCallOutcome::Denied,
            },
        }
    }

    /// [`Self::dispatch`], but returning [`HostDispatchOutcome`] instead of
    /// a bare wire response, and able to answer `Deferred` for
    /// `session/request_permission` exactly as [`HostHandler::
    /// handle_deferrable`] does -- indeed `handle_deferrable` is now a thin
    /// wrapper around this. The reader loop (`acp::reader`) calls this
    /// directly on the concrete `AcpHostAdapter`, not through the
    /// `HostHandler` trait, because it needs the `HostCallOutcome`
    /// `HostOutcome::Immediate` has no field for.
    ///
    /// A gate block is decided immediately even when deferral is `Enabled`:
    /// the dangerous-command gate outranks the operator (see
    /// `AcpHostHandler::permission_blocked_by_gate`'s doc comment), so
    /// nobody is ever asked to approve what the gate has already refused.
    pub(crate) fn dispatch_deferrable(&self, method: &str, params: Option<Value>) -> HostDispatchOutcome {
        if method != "session/request_permission" || self.deferral == PermissionDeferral::Disabled {
            let result = self.dispatch(method, params);
            return HostDispatchOutcome::Immediate { response: result.response, outcome: result.outcome };
        }

        // Parse once, here, purely to run the gate check ahead of the
        // deferral decision. A params blob that fails to parse takes the
        // immediate path too -- `dispatch`'s own `session/request_permission`
        // arm parses `params` again independently and reports the exact
        // same `INVALID_PARAMS` either way, so a parse failure is never
        // silently swallowed into a `Deferred` that can never be answered.
        let parsed = match params.clone() {
            Some(v) => match serde_json::from_value::<PermissionRequestParams>(v) {
                Ok(p) => Some(p),
                Err(e) => {
                    warn_permission_params_parse_failed("dispatch_deferrable", &e.to_string());
                    None
                }
            },
            None => None,
        };
        let Some(parsed) = parsed else {
            let result = self.dispatch(method, params);
            return HostDispatchOutcome::Immediate { response: result.response, outcome: result.outcome };
        };

        if self.inner.permission_blocked_by_gate(&parsed.tool_call) {
            let result = self.dispatch(method, params);
            return HostDispatchOutcome::Immediate { response: result.response, outcome: result.outcome };
        }

        HostDispatchOutcome::Deferred
    }
}

impl HostHandler for AcpHostAdapter {
    fn handle(&self, method: &str, params: Option<Value>) -> Result<Value, RpcError> {
        self.dispatch(method, params).response
    }

    /// Only `session/request_permission`, and only when this session's
    /// [`PermissionDeferral`] is `Enabled`, can return
    /// [`HostOutcome::Deferred`] -- every other method, and every session
    /// with deferral `Disabled`, is `Immediate(self.handle(method, params))`
    /// with today's behavior, byte for byte. A thin wrapper around
    /// [`AcpHostAdapter::dispatch_deferrable`], discarding the
    /// `HostCallOutcome` that method's other caller (`acp::reader`) reads
    /// directly -- callers going through the `HostHandler` trait never
    /// needed it.
    fn handle_deferrable(&self, method: &str, params: Option<Value>) -> HostOutcome {
        match self.dispatch_deferrable(method, params) {
            HostDispatchOutcome::Immediate { response, .. } => HostOutcome::Immediate(response),
            HostDispatchOutcome::Deferred => HostOutcome::Deferred,
        }
    }
}

// ---------------------------------------------------------------------------
// Helper
// ---------------------------------------------------------------------------

fn parse_params<T: serde::de::DeserializeOwned>(params: Option<Value>) -> Result<T, RpcError> {
    let v = params.unwrap_or(Value::Null);
    serde_json::from_value(v).map_err(|e| RpcError {
        code: RpcError::INVALID_PARAMS,
        message: format!("Invalid params: {}", e),
        data: None,
    })
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::acp::protocol::ToolCallLocation;
    use serde_json::json;
    use std::sync::Arc;

    /// The trait's own baked-in defaults (deny everything), independent of
    /// any concrete policy — proves nobody weakened the safe fallback.
    struct Bare;
    impl AcpHostHandler for Bare {}

    #[test]
    fn trait_defaults_deny_fs_read() {
        let params = FsReadParams { path: "/etc/passwd".to_owned(), session_id: String::new(), line: None, limit: None };
        assert!(Bare.fs_read_text_file(&params).is_err());
    }

    #[test]
    fn trait_defaults_deny_terminal_create() {
        let params = TerminalCreateParams {
            session_id: String::new(),
            command: "ls".to_owned(),
            args: vec![],
            env: vec![],
            cwd: None,
            output_byte_limit: None,
        };
        assert!(Bare.terminal_create(&params).is_err());
    }

    #[test]
    fn trait_defaults_cancel_permission() {
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: PermissionToolCall::default(),
            options: vec![PermissionOption {
                option_id: "a1".to_owned(),
                name: "Allow".to_owned(),
                kind: PermissionOptionKind::AllowOnce,
            }],
        };
        assert_eq!(Bare.request_permission(&params), PermissionOutcome::Cancelled);
    }

    fn adapter(policy: HostPolicy) -> AcpHostAdapter {
        AcpHostAdapter::new(
            Arc::new(PolicyHostHandler::new(policy, std::env::temp_dir(), DangerousCommandGate::Enforced)),
            PermissionDeferral::Disabled,
        )
    }

    fn adapter_with_gate(policy: HostPolicy, gate: DangerousCommandGate) -> AcpHostAdapter {
        AcpHostAdapter::new(
            Arc::new(PolicyHostHandler::new(policy, std::env::temp_dir(), gate)),
            PermissionDeferral::Disabled,
        )
    }

    fn adapter_with_deferral(
        policy: HostPolicy,
        gate: DangerousCommandGate,
        deferral: PermissionDeferral,
    ) -> AcpHostAdapter {
        AcpHostAdapter::new(Arc::new(PolicyHostHandler::new(policy, std::env::temp_dir(), gate)), deferral)
    }

    // -----------------------------------------------------------------------
    // Capabilities per policy
    // -----------------------------------------------------------------------

    #[test]
    fn yolo_and_auto_declare_full_capabilities() {
        for policy in [HostPolicy::Yolo, HostPolicy::Auto] {
            let caps = policy.client_capabilities();
            assert!(caps.fs.read_text_file);
            assert!(caps.fs.write_text_file);
            assert!(caps.terminal);
        }
    }

    #[test]
    fn read_only_declares_read_but_not_write_or_terminal() {
        let caps = HostPolicy::ReadOnly.client_capabilities();
        assert!(caps.fs.read_text_file);
        assert!(!caps.fs.write_text_file);
        assert!(!caps.terminal);
    }

    #[test]
    fn deny_declares_nothing() {
        let caps = HostPolicy::Deny.client_capabilities();
        assert!(!caps.fs.read_text_file);
        assert!(!caps.fs.write_text_file);
        assert!(!caps.terminal);
    }

    #[test]
    fn default_policy_is_auto() {
        assert_eq!(HostPolicy::default(), HostPolicy::Auto);
    }

    // -----------------------------------------------------------------------
    // fs/read_text_file, fs/write_text_file — real I/O
    // -----------------------------------------------------------------------

    #[test]
    fn auto_reads_and_writes_a_real_file() {
        let dir = std::env::temp_dir();
        let path = dir.join("gate4agent_host_test_rw.txt");
        std::fs::write(&path, "before").unwrap();

        let handler =
            PolicyHostHandler::new(HostPolicy::Auto, dir.clone(), DangerousCommandGate::Enforced);
        let read = handler
            .fs_read_text_file(&FsReadParams {
                path: path.to_string_lossy().into_owned(),
                session_id: String::new(),
                line: None,
                limit: None,
            })
            .unwrap();
        assert_eq!(read, "before");

        handler
            .fs_write_text_file(&FsWriteParams {
                path: path.to_string_lossy().into_owned(),
                session_id: String::new(),
                content: "after".to_owned(),
            })
            .unwrap();
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "after");

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn read_only_reads_but_refuses_to_write() {
        let dir = std::env::temp_dir();
        let path = dir.join("gate4agent_host_test_readonly.txt");
        std::fs::write(&path, "content").unwrap();

        let handler =
            PolicyHostHandler::new(HostPolicy::ReadOnly, dir, DangerousCommandGate::Enforced);
        assert!(handler
            .fs_read_text_file(&FsReadParams {
                path: path.to_string_lossy().into_owned(),
                session_id: String::new(),
                line: None,
                limit: None,
            })
            .is_ok());
        assert!(handler
            .fs_write_text_file(&FsWriteParams {
                path: path.to_string_lossy().into_owned(),
                session_id: String::new(),
                content: "nope".to_owned(),
            })
            .is_err());

        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn deny_refuses_read_and_write() {
        let dir = std::env::temp_dir();
        let handler = PolicyHostHandler::new(HostPolicy::Deny, dir, DangerousCommandGate::Enforced);
        assert!(handler
            .fs_read_text_file(&FsReadParams {
                path: "/etc/passwd".to_owned(),
                session_id: String::new(),
                line: None,
                limit: None,
            })
            .is_err());
        assert!(handler
            .fs_write_text_file(&FsWriteParams {
                path: "/tmp/should-not-be-written".to_owned(),
                session_id: String::new(),
                content: "x".to_owned(),
            })
            .is_err());
    }

    #[test]
    fn windowed_read_applies_line_and_limit() {
        let content = "one\ntwo\nthree\nfour\n";
        assert_eq!(windowed_read(content, None, None), content);
        assert_eq!(windowed_read(content, Some(2), None), "two\nthree\nfour\n");
        assert_eq!(windowed_read(content, Some(2), Some(1)), "two\n");
    }

    // -----------------------------------------------------------------------
    // session/request_permission selection per policy
    // -----------------------------------------------------------------------

    fn options_all_four() -> Vec<PermissionOption> {
        vec![
            PermissionOption { option_id: "ao".to_owned(), name: "Allow once".to_owned(), kind: PermissionOptionKind::AllowOnce },
            PermissionOption { option_id: "aa".to_owned(), name: "Allow always".to_owned(), kind: PermissionOptionKind::AllowAlways },
            PermissionOption { option_id: "ro".to_owned(), name: "Reject once".to_owned(), kind: PermissionOptionKind::RejectOnce },
            PermissionOption { option_id: "ra".to_owned(), name: "Reject always".to_owned(), kind: PermissionOptionKind::RejectAlways },
        ]
    }

    fn tool_call(kind: crate::acp::protocol::ToolKind) -> PermissionToolCall {
        PermissionToolCall {
            tool_call_id: "tc1".to_owned(),
            title: "test".to_owned(),
            kind,
            locations: vec![ToolCallLocation { path: "/repo/file.txt".to_owned(), line: None }],
            raw_input: Value::Null,
        }
    }

    #[test]
    fn yolo_prefers_allow_always() {
        let outcome = HostPolicy::Yolo
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "aa".to_owned() });
    }

    #[test]
    fn auto_prefers_allow_once_over_allow_always() {
        let outcome = HostPolicy::Auto
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "ao".to_owned() });
    }

    #[test]
    fn read_only_allows_a_read_kind_tool_call() {
        let outcome = HostPolicy::ReadOnly
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Read), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "ao".to_owned() });
    }

    #[test]
    fn read_only_rejects_an_execute_kind_tool_call() {
        let outcome = HostPolicy::ReadOnly
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "ro".to_owned() });
    }

    #[test]
    fn deny_always_rejects() {
        let outcome = HostPolicy::Deny
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Read), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "ro".to_owned() });
    }

    #[test]
    fn deny_cancels_when_the_agent_offers_only_allow_options() {
        let options = vec![
            PermissionOption { option_id: "ao".to_owned(), name: "Allow once".to_owned(), kind: PermissionOptionKind::AllowOnce },
        ];
        let outcome = HostPolicy::Deny
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options);
        assert_eq!(outcome, PermissionOutcome::Cancelled);
    }

    #[test]
    fn auto_falls_back_to_allow_always_when_agent_omits_allow_once() {
        // Regression for "agent does not send all four kinds" — here it only
        // offers allow_always and reject_once.
        let options = vec![
            PermissionOption { option_id: "aa".to_owned(), name: "Allow always".to_owned(), kind: PermissionOptionKind::AllowAlways },
            PermissionOption { option_id: "ro".to_owned(), name: "Reject once".to_owned(), kind: PermissionOptionKind::RejectOnce },
        ];
        let outcome = HostPolicy::Auto
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options);
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "aa".to_owned() });
    }

    fn allow_ish_unknown_option() -> Vec<PermissionOption> {
        // A third-party adapter that words every option under a `kind`
        // string this build does not recognise -- deserializes as
        // `PermissionOptionKind::Unknown` (see `protocol.rs`'s own test for
        // that deserialization step); this is what the allow-ish
        // name/`optionId` fallback in `select_permission_option` exists for.
        vec![PermissionOption {
            option_id: "always_allow".to_owned(),
            name: "Always allow".to_owned(),
            kind: PermissionOptionKind::Unknown,
        }]
    }

    #[test]
    fn auto_falls_back_to_allow_ish_unknown_option_when_no_known_kind_offered() {
        let outcome = HostPolicy::Auto.select_permission_option(
            &tool_call(crate::acp::protocol::ToolKind::Execute),
            &allow_ish_unknown_option(),
        );
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "always_allow".to_owned() });
    }

    #[test]
    fn yolo_falls_back_to_allow_ish_unknown_option_when_no_known_kind_offered() {
        let outcome = HostPolicy::Yolo.select_permission_option(
            &tool_call(crate::acp::protocol::ToolKind::Execute),
            &allow_ish_unknown_option(),
        );
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "always_allow".to_owned() });
    }

    #[test]
    fn known_kinds_still_win_over_the_allow_ish_fallback() {
        // The fallback must never alter existing behaviour when the four
        // known kinds ARE offered -- it only ever runs when the by-kind
        // preference walk found nothing.
        let outcome = HostPolicy::Yolo
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "aa".to_owned() });

        let outcome = HostPolicy::Auto
            .select_permission_option(&tool_call(crate::acp::protocol::ToolKind::Execute), &options_all_four());
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "ao".to_owned() });
    }

    #[test]
    fn allow_ish_fallback_never_fires_under_read_only_for_a_non_read_call() {
        let outcome = HostPolicy::ReadOnly.select_permission_option(
            &tool_call(crate::acp::protocol::ToolKind::Execute),
            &allow_ish_unknown_option(),
        );
        assert_eq!(outcome, PermissionOutcome::Cancelled);
    }

    #[test]
    fn allow_ish_fallback_never_fires_under_deny() {
        let outcome = HostPolicy::Deny.select_permission_option(
            &tool_call(crate::acp::protocol::ToolKind::Execute),
            &allow_ish_unknown_option(),
        );
        assert_eq!(outcome, PermissionOutcome::Cancelled);
    }

    #[test]
    fn adapter_selects_allow_ish_option_when_agent_offers_only_an_unknown_kind() {
        // End-to-end through the adapter: the agent's wire JSON uses a
        // `kind` string this build does not recognise for the only option
        // offered, so it deserializes as `PermissionOptionKind::Unknown`
        // instead of failing the whole request -- the allow-ish
        // name/optionId fallback must still pick it under `Auto`.
        let result = adapter(HostPolicy::Auto).handle(
            "session/request_permission",
            Some(json!({
                "sessionId": "s1",
                "toolCall": {"toolCallId": "tc1", "kind": "execute"},
                "options": [
                    {"optionId": "always_allow", "name": "Always allow", "kind": "allow_forever"}
                ]
            })),
        );
        let value = result.unwrap();
        assert_eq!(value["outcome"], "selected");
        assert_eq!(value["optionId"], "always_allow");
    }

    // -----------------------------------------------------------------------
    // Adapter dispatch
    // -----------------------------------------------------------------------

    #[test]
    fn adapter_dispatches_fs_read_success() {
        let dir = std::env::temp_dir();
        let path = dir.join("gate4agent_host_adapter_read.txt");
        std::fs::write(&path, "adapter content").unwrap();

        let result = adapter(HostPolicy::Auto)
            .handle("fs/read_text_file", Some(json!({"path": path.to_string_lossy()})));
        assert_eq!(result.unwrap()["content"], "adapter content");
        std::fs::remove_file(&path).ok();
    }

    #[test]
    fn adapter_dispatches_fs_read_denied_under_deny() {
        let result = adapter(HostPolicy::Deny)
            .handle("fs/read_text_file", Some(json!({"path": "/etc/passwd"})));
        assert_eq!(result.unwrap_err().code, RpcError::PERMISSION_DENIED);
    }

    #[test]
    fn adapter_dispatches_permission_request() {
        let result = adapter(HostPolicy::Yolo).handle(
            "session/request_permission",
            Some(json!({
                "sessionId": "s1",
                "toolCall": {"toolCallId": "tc1", "kind": "execute"},
                "options": [
                    {"optionId": "ao", "name": "Allow once", "kind": "allow_once"}
                ]
            })),
        );
        let value = result.unwrap();
        assert_eq!(value["outcome"], "selected");
        assert_eq!(value["optionId"], "ao");
    }

    #[test]
    fn adapter_unknown_method_returns_method_not_found() {
        let result = adapter(HostPolicy::Auto).handle("unknown/method", None);
        assert_eq!(result.unwrap_err().code, RpcError::METHOD_NOT_FOUND);
    }

    #[test]
    fn adapter_invalid_params_returns_invalid_params_error() {
        // terminal/create requires a "command" field.
        let result = adapter(HostPolicy::Auto).handle("terminal/create", Some(json!({})));
        assert_eq!(result.unwrap_err().code, RpcError::INVALID_PARAMS);
    }

    #[test]
    fn adapter_terminal_lifecycle_end_to_end() {
        let handler = adapter(HostPolicy::Auto);
        #[cfg(windows)]
        let create_params = json!({"command": "cmd", "args": ["/C", "echo lifecycle"]});
        #[cfg(not(windows))]
        let create_params = json!({"command": "sh", "args": ["-c", "echo lifecycle"]});

        let created = handler.handle("terminal/create", Some(create_params)).unwrap();
        let terminal_id = created["terminalId"].as_str().unwrap().to_owned();

        let waited = handler
            .handle("terminal/wait_for_exit", Some(json!({"terminalId": terminal_id})))
            .unwrap();
        assert_eq!(waited["exitCode"], 0);

        let output = handler
            .handle("terminal/output", Some(json!({"terminalId": terminal_id})))
            .unwrap();
        assert!(output["output"].as_str().unwrap().contains("lifecycle"));

        handler
            .handle("terminal/release", Some(json!({"terminalId": terminal_id})))
            .unwrap();

        let after_release =
            handler.handle("terminal/output", Some(json!({"terminalId": terminal_id})));
        assert_eq!(after_release.unwrap_err().code, RpcError::NOT_FOUND);
    }

    #[test]
    fn adapter_terminal_create_denied_under_read_only() {
        let result = adapter(HostPolicy::ReadOnly)
            .handle("terminal/create", Some(json!({"command": "echo", "args": []})));
        assert_eq!(result.unwrap_err().code, RpcError::PERMISSION_DENIED);
    }

    // -----------------------------------------------------------------------
    // Dangerous-command gate — stands above `HostPolicy`
    //
    // Every case here uses a command that is dangerous BY CONSTRUCTION
    // (`rm -rf /`) but never lets it reach `TerminalStore::create` — the
    // gate check returns `Err` before that call. Tests that need to prove
    // the gate was NOT consulted (the `Disabled` cases) pair it with
    // `HostPolicy::Deny`, whose OWN refusal keeps the test safe even if the
    // gate really were skipped, while the assertion tells the two refusals
    // apart by message.
    // -----------------------------------------------------------------------

    fn dangerous_terminal_params() -> TerminalCreateParams {
        TerminalCreateParams {
            session_id: String::new(),
            command: "rm".to_owned(),
            args: vec!["-rf".to_owned(), "/".to_owned()],
            env: vec![],
            cwd: None,
            output_byte_limit: None,
        }
    }

    fn dangerous_execute_tool_call() -> PermissionToolCall {
        PermissionToolCall {
            tool_call_id: "tc1".to_owned(),
            title: "Run rm -rf /".to_owned(),
            kind: crate::acp::protocol::ToolKind::Execute,
            locations: vec![],
            raw_input: json!({"command": "rm", "args": ["-rf", "/"]}),
        }
    }

    #[test]
    fn dangerous_command_gate_blocks_terminal_create_even_under_yolo_policy() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Yolo, std::env::temp_dir(), DangerousCommandGate::Enforced);
        let err = handler.terminal_create(&dangerous_terminal_params()).unwrap_err();
        // A gate block is decided BEFORE anything executes -- `Denied`,
        // never `Failed` (this call never reached `TerminalStore::create`).
        assert!(matches!(err, HostRequestError::Denied(_)), "gate block must be Denied, was: {err:?}");
        let message = err.message();
        assert!(message.contains("dangerous-command gate"), "message was: {message}");
        assert!(message.contains("filesystem-wipe"), "message was: {message}");
        assert!(message.contains("rule="), "refusal must name the rule: {message}");
        assert!(message.contains("argument="), "refusal must name the offending argument: {message}");
    }

    #[test]
    fn dangerous_command_gate_disabled_skips_straight_to_policy_for_terminal_create() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Deny, std::env::temp_dir(), DangerousCommandGate::Disabled);
        let err = handler.terminal_create(&dangerous_terminal_params()).unwrap_err();
        assert!(matches!(err, HostRequestError::Denied(_)), "policy refusal must be Denied, was: {err:?}");
        // The POLICY's refusal text, not the gate's -- proves the gate
        // itself never ran when explicitly disabled.
        assert_eq!(err.message(), "terminal/create denied by host policy");
    }

    #[test]
    fn dangerous_command_gate_blocks_execute_permission_request_even_under_yolo_policy() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Yolo, std::env::temp_dir(), DangerousCommandGate::Enforced);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        // Yolo alone would select allow_always ("aa") -- the gate must
        // override that and land on a reject-kind option instead.
        let outcome = handler.request_permission(&params);
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "ro".to_owned() });
    }

    #[test]
    fn dangerous_command_gate_disabled_leaves_execute_permission_request_to_policy() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Yolo, std::env::temp_dir(), DangerousCommandGate::Disabled);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        let outcome = handler.request_permission(&params);
        assert_eq!(outcome, PermissionOutcome::Selected { option_id: "aa".to_owned() });
    }

    #[test]
    fn dangerous_command_gate_allows_a_benign_terminal_create_under_yolo() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Yolo, std::env::temp_dir(), DangerousCommandGate::Enforced);
        let params = TerminalCreateParams {
            session_id: String::new(),
            command: "echo".to_owned(),
            args: vec!["hello".to_owned()],
            env: vec![],
            cwd: None,
            output_byte_limit: None,
        };
        // Reaches TerminalStore -- a real (harmless) process is fine here.
        assert!(handler.terminal_create(&params).is_ok());
    }

    #[test]
    fn adapter_dispatches_terminal_create_blocked_by_gate_as_permission_denied() {
        let result = adapter_with_gate(HostPolicy::Auto, DangerousCommandGate::Enforced)
            .handle("terminal/create", Some(json!({"command": "rm", "args": ["-rf", "/"]})));
        let error = result.unwrap_err();
        assert_eq!(error.code, RpcError::PERMISSION_DENIED);
        assert!(error.message.contains("filesystem-wipe"), "message was: {}", error.message);
    }

    // -----------------------------------------------------------------------
    // permission_refusal_reason — carries the gate/policy refusal text that
    // `session/request_permission` has no `Err(String)` to ride on (unlike
    // `terminal/create`'s denial, which already had one) -- see the trait
    // method's own doc comment.
    // -----------------------------------------------------------------------

    #[test]
    fn permission_refusal_reason_is_the_gate_verdict_text_when_gate_blocked() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Yolo, std::env::temp_dir(), DangerousCommandGate::Enforced);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        let reason = handler
            .permission_refusal_reason(&params)
            .expect("a gate-blocked call must explain why");
        assert!(reason.contains("dangerous-command gate"), "reason was: {reason}");
        assert!(reason.contains("rule="), "reason must name the rule: {reason}");
        assert!(reason.contains("argument="), "reason must name the offending argument: {reason}");
    }

    #[test]
    fn permission_refusal_reason_is_the_fixed_policy_sentence_when_not_gate_blocked() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Deny, std::env::temp_dir(), DangerousCommandGate::Enforced);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: PermissionToolCall {
                tool_call_id: "tc1".to_owned(),
                title: "Read a file".to_owned(),
                kind: crate::acp::protocol::ToolKind::Read,
                locations: vec![],
                raw_input: json!({}),
            },
            options: options_all_four(),
        };
        assert_eq!(
            handler.permission_refusal_reason(&params),
            Some("session/request_permission denied by host policy".to_string())
        );
    }

    #[test]
    fn adapter_permission_refusal_reason_reparses_raw_params_and_carries_the_gate_text() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        let raw = serde_json::to_value(&params).expect("PermissionRequestParams serializes");
        let reason = handler
            .permission_refusal_reason(Some(&raw))
            .expect("gate-blocked call must carry a reason through the adapter");
        assert!(reason.contains("dangerous-command gate"), "reason was: {reason}");
    }

    #[test]
    fn adapter_permission_refusal_reason_is_none_for_unparsable_params() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        assert_eq!(handler.permission_refusal_reason(Some(&json!("not an object"))), None);
    }

    /// The fact this whole change exists to fix: BEFORE this, a gate-blocked
    /// `terminal/create` had a refusal `Err(String)` an observer could read,
    /// while the SAME gate blocking a `session/request_permission` call on
    /// the SAME command shape produced a `Selected`/`Cancelled` outcome with
    /// no text anywhere -- "no wire field to carry its reason on". Proves
    /// both paths now surface the SAME rule-and-argument text (both fixtures
    /// hit the identical `filesystem-wipe` rule on `rm -rf /`), so an
    /// observer reading either one learns the same fact.
    #[test]
    fn gate_refusal_text_reaches_both_terminal_create_and_permission_request_paths() {
        let handler =
            PolicyHostHandler::new(HostPolicy::Yolo, std::env::temp_dir(), DangerousCommandGate::Enforced);

        let terminal_reason = handler.terminal_create(&dangerous_terminal_params()).unwrap_err();
        let terminal_reason = terminal_reason.message();

        let permission_params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        let permission_reason = handler
            .permission_refusal_reason(&permission_params)
            .expect("gate-blocked permission request must carry a reason");

        assert!(
            terminal_reason.contains("rule=filesystem-wipe"),
            "terminal reason was: {terminal_reason}"
        );
        assert!(
            permission_reason.contains("rule=filesystem-wipe"),
            "permission reason was: {permission_reason}"
        );
    }

    // -----------------------------------------------------------------------
    // handle_deferrable — PermissionDeferral
    // -----------------------------------------------------------------------

    #[test]
    fn handle_deferrable_never_defers_when_disabled() {
        let handler = adapter(HostPolicy::Auto);
        let outcome = handler.handle_deferrable(
            "session/request_permission",
            Some(json!({
                "sessionId": "s1",
                "toolCall": {"toolCallId": "tc1", "kind": "read"},
                "options": []
            })),
        );
        assert!(matches!(outcome, HostOutcome::Immediate(_)));
    }

    #[test]
    fn handle_deferrable_never_defers_methods_other_than_request_permission() {
        let handler =
            adapter_with_deferral(HostPolicy::Auto, DangerousCommandGate::Enforced, PermissionDeferral::Enabled);
        let outcome = handler.handle_deferrable("fs/read_text_file", Some(json!({"path": "/etc/passwd"})));
        assert!(matches!(outcome, HostOutcome::Immediate(_)));
    }

    #[test]
    fn handle_deferrable_defers_a_non_blocked_permission_request_when_enabled() {
        let handler =
            adapter_with_deferral(HostPolicy::Auto, DangerousCommandGate::Enforced, PermissionDeferral::Enabled);
        let outcome = handler.handle_deferrable(
            "session/request_permission",
            Some(json!({
                "sessionId": "s1",
                "toolCall": {"toolCallId": "tc1", "kind": "read"},
                "options": [{"optionId": "ao", "name": "Allow once", "kind": "allow_once"}]
            })),
        );
        assert!(matches!(outcome, HostOutcome::Deferred));
    }

    #[test]
    fn handle_deferrable_decides_a_gate_blocked_request_immediately_even_when_enabled() {
        let handler =
            adapter_with_deferral(HostPolicy::Yolo, DangerousCommandGate::Enforced, PermissionDeferral::Enabled);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        let outcome = handler.handle_deferrable(
            "session/request_permission",
            Some(serde_json::to_value(&params).expect("PermissionRequestParams serializes")),
        );
        match outcome {
            HostOutcome::Immediate(Ok(value)) => {
                assert_eq!(value["outcome"], "selected");
                // Yolo alone would pick "aa" (allow_always) -- the gate
                // overrides that to a reject-kind option, exactly as
                // `dangerous_command_gate_blocks_execute_permission_request_even_under_yolo_policy` proves for `request_permission` directly.
                assert_eq!(value["optionId"], "ro");
            }
            other => panic!("expected an immediate gate-blocked decision, got {other:?}"),
        }
    }

    #[test]
    fn handle_deferrable_falls_through_to_handle_on_unparsable_params() {
        let handler =
            adapter_with_deferral(HostPolicy::Auto, DangerousCommandGate::Enforced, PermissionDeferral::Enabled);
        let outcome = handler.handle_deferrable("session/request_permission", Some(json!("not an object")));
        match outcome {
            HostOutcome::Immediate(Err(err)) => assert_eq!(err.code, RpcError::INVALID_PARAMS),
            other => panic!("expected an immediate INVALID_PARAMS error, got {other:?}"),
        }
    }

    // -----------------------------------------------------------------------
    // decision_authority — classifies WHO decided, for HostRequestDecision
    // -----------------------------------------------------------------------

    #[test]
    fn decision_authority_is_gate_for_a_gate_blocked_terminal_create() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        let params = json!({"command": "rm", "args": ["-rf", "/"]});
        assert_eq!(
            handler.decision_authority("terminal/create", Some(&params)),
            HostDecisionAuthority::Gate
        );
    }

    #[test]
    fn decision_authority_is_policy_for_a_benign_terminal_create() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        let params = json!({"command": "echo", "args": ["hello"]});
        assert_eq!(
            handler.decision_authority("terminal/create", Some(&params)),
            HostDecisionAuthority::Policy
        );
    }

    #[test]
    fn decision_authority_is_policy_for_terminal_create_when_gate_disabled() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Disabled);
        let params = json!({"command": "rm", "args": ["-rf", "/"]});
        assert_eq!(
            handler.decision_authority("terminal/create", Some(&params)),
            HostDecisionAuthority::Policy
        );
    }

    #[test]
    fn decision_authority_is_gate_for_a_gate_blocked_permission_request() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: dangerous_execute_tool_call(),
            options: options_all_four(),
        };
        let value = serde_json::to_value(&params).expect("PermissionRequestParams serializes");
        assert_eq!(
            handler.decision_authority("session/request_permission", Some(&value)),
            HostDecisionAuthority::Gate
        );
    }

    #[test]
    fn decision_authority_is_policy_for_a_non_blocked_permission_request() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        let params = PermissionRequestParams {
            session_id: "s1".to_owned(),
            tool_call: tool_call(crate::acp::protocol::ToolKind::Read),
            options: options_all_four(),
        };
        let value = serde_json::to_value(&params).expect("PermissionRequestParams serializes");
        assert_eq!(
            handler.decision_authority("session/request_permission", Some(&value)),
            HostDecisionAuthority::Policy
        );
    }

    #[test]
    fn decision_authority_is_policy_for_every_other_method() {
        let handler = adapter_with_gate(HostPolicy::Yolo, DangerousCommandGate::Enforced);
        for method in [
            "fs/read_text_file",
            "fs/write_text_file",
            "terminal/output",
            "terminal/wait_for_exit",
            "terminal/kill",
            "terminal/release",
        ] {
            assert_eq!(
                handler.decision_authority(method, None),
                HostDecisionAuthority::Policy,
                "method was: {method}"
            );
        }
    }
}