agentkit-tools-core 0.4.0

Tool traits, registry, execution, permissions, approvals, and auth for agentkit.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
//! Core abstractions for defining, registering, executing, and governing
//! tools in agentkit.
//!
//! This crate provides the [`Tool`] trait, [`ToolRegistry`],
//! [`BasicToolExecutor`], and a layered permission system built on
//! [`PermissionChecker`], [`PermissionPolicy`], and
//! [`CompositePermissionChecker`]. Together these types let you:
//!
//! - **Define tools** by implementing [`Tool`] with a [`ToolSpec`] and
//!   async `invoke` method.
//! - **Register tools** in a [`ToolRegistry`] and hand it to an executor
//!   or capability provider.
//! - **Check permissions** before execution using composable policies
//!   ([`PathPolicy`], [`CommandPolicy`], [`McpServerPolicy`],
//!   [`CustomKindPolicy`]).
//! - **Handle interruptions** (approval prompts, OAuth flows) via the
//!   [`ToolInterruption`] / [`ApprovalRequest`] / [`AuthRequest`] types.
//! - **Bridge to the capability layer** with [`ToolCapabilityProvider`],
//!   which wraps every registered tool as an [`Invocable`].

use std::any::Any;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;

use agentkit_capabilities::{
    CapabilityContext, CapabilityError, CapabilityName, CapabilityProvider, Invocable,
    InvocableOutput, InvocableRequest, InvocableResult, InvocableSpec, PromptProvider,
    ResourceProvider,
};
use agentkit_core::{
    ApprovalId, Item, ItemKind, MetadataMap, Part, SessionId, TaskId, ToolCallId, ToolOutput,
    ToolResultPart, TurnCancellation, TurnId,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use thiserror::Error;

/// Unique name identifying a [`Tool`] within a [`ToolRegistry`].
///
/// Tool names are used as registry keys and appear in [`ToolRequest`]s to
/// route calls to the correct implementation. Names are compared in a
/// case-sensitive, lexicographic order.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::ToolName;
///
/// let name = ToolName::new("file_read");
/// assert_eq!(name.to_string(), "file_read");
///
/// // Also converts from &str:
/// let name: ToolName = "shell_exec".into();
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct ToolName(pub String);

impl ToolName {
    /// Creates a new `ToolName` from any value that converts into a [`String`].
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }
}

impl fmt::Display for ToolName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

impl From<&str> for ToolName {
    fn from(value: &str) -> Self {
        Self::new(value)
    }
}

/// Hints that describe behavioural properties of a tool.
///
/// These flags are advisory — they influence UI presentation and permission
/// policies but do not enforce behaviour at runtime. For example, a
/// permission policy may automatically require approval for tools that
/// set `destructive_hint` to `true`.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolAnnotations {
    /// The tool only reads data and has no side-effects.
    pub read_only_hint: bool,
    /// The tool may perform destructive operations (e.g. file deletion).
    pub destructive_hint: bool,
    /// Repeated calls with the same input produce the same effect.
    pub idempotent_hint: bool,
    /// The tool should prompt for user approval before execution.
    pub needs_approval_hint: bool,
    /// The tool can stream partial results during execution.
    pub supports_streaming_hint: bool,
}

impl ToolAnnotations {
    /// Builds the default advisory flags.
    pub fn new() -> Self {
        Self::default()
    }

    /// Marks the tool as read-only.
    pub fn read_only() -> Self {
        Self::default().with_read_only(true)
    }

    /// Marks the tool as destructive.
    pub fn destructive() -> Self {
        Self::default().with_destructive(true)
    }

    /// Marks the tool as requiring approval.
    pub fn needs_approval() -> Self {
        Self::default().with_needs_approval(true)
    }

    /// Marks the tool as supporting streaming.
    pub fn streaming() -> Self {
        Self::default().with_supports_streaming(true)
    }

    pub fn with_read_only(mut self, read_only_hint: bool) -> Self {
        self.read_only_hint = read_only_hint;
        self
    }

    pub fn with_destructive(mut self, destructive_hint: bool) -> Self {
        self.destructive_hint = destructive_hint;
        self
    }

    pub fn with_idempotent(mut self, idempotent_hint: bool) -> Self {
        self.idempotent_hint = idempotent_hint;
        self
    }

    pub fn with_needs_approval(mut self, needs_approval_hint: bool) -> Self {
        self.needs_approval_hint = needs_approval_hint;
        self
    }

    pub fn with_supports_streaming(mut self, supports_streaming_hint: bool) -> Self {
        self.supports_streaming_hint = supports_streaming_hint;
        self
    }
}

/// Declarative specification of a tool's identity, schema, and behavioural hints.
///
/// Every [`Tool`] implementation exposes a `ToolSpec` that the framework uses to
/// advertise the tool to an LLM, validate inputs, and drive permission checks.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::{ToolAnnotations, ToolName, ToolSpec};
/// use serde_json::json;
///
/// let spec = ToolSpec::new(
///     ToolName::new("grep_search"),
///     "Search files by regex pattern",
///     json!({
///         "type": "object",
///         "properties": {
///             "pattern": { "type": "string" },
///             "path": { "type": "string" }
///         },
///         "required": ["pattern"]
///     }),
/// )
/// .with_annotations(ToolAnnotations::read_only());
/// ```
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolSpec {
    /// Machine-readable name used to route tool calls.
    pub name: ToolName,
    /// Human-readable description sent to the LLM so it knows when to use this tool.
    pub description: String,
    /// JSON Schema describing the expected input object.
    pub input_schema: Value,
    /// Advisory behavioural hints (read-only, destructive, etc.).
    pub annotations: ToolAnnotations,
    /// Arbitrary key-value pairs for framework extensions.
    pub metadata: MetadataMap,
}

impl ToolSpec {
    /// Builds a tool spec with default annotations and empty metadata.
    pub fn new(
        name: impl Into<ToolName>,
        description: impl Into<String>,
        input_schema: Value,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            input_schema,
            annotations: ToolAnnotations::default(),
            metadata: MetadataMap::new(),
        }
    }

    /// Replaces the tool annotations.
    pub fn with_annotations(mut self, annotations: ToolAnnotations) -> Self {
        self.annotations = annotations;
        self
    }

    /// Replaces the tool metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// An incoming request to execute a tool.
///
/// Created by the agent loop when the model emits a tool-call. The
/// [`BasicToolExecutor`] uses `tool_name` to look up the [`Tool`] in the
/// registry and forwards this request to [`Tool::invoke`].
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolRequest {
    /// Provider-assigned identifier for this specific call.
    pub call_id: ToolCallId,
    /// Name of the tool to invoke (must match a registered [`ToolName`]).
    pub tool_name: ToolName,
    /// JSON input parsed from the model's tool-call arguments.
    pub input: Value,
    /// Session that owns this call.
    pub session_id: SessionId,
    /// Turn within the session that triggered this call.
    pub turn_id: TurnId,
    /// Arbitrary key-value pairs for framework extensions.
    pub metadata: MetadataMap,
}

impl ToolRequest {
    /// Builds a tool request with empty metadata.
    pub fn new(
        call_id: impl Into<ToolCallId>,
        tool_name: impl Into<ToolName>,
        input: Value,
        session_id: impl Into<SessionId>,
        turn_id: impl Into<TurnId>,
    ) -> Self {
        Self {
            call_id: call_id.into(),
            tool_name: tool_name.into(),
            input,
            session_id: session_id.into(),
            turn_id: turn_id.into(),
            metadata: MetadataMap::new(),
        }
    }

    /// Replaces the request metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// The output produced by a successful tool invocation.
///
/// Returned from [`Tool::invoke`] and wrapped by [`ToolExecutionOutcome::Completed`]
/// after the executor finishes permission checks and execution.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolResult {
    /// The content payload sent back to the model.
    pub result: ToolResultPart,
    /// Wall-clock time the tool took to run, if measured.
    pub duration: Option<Duration>,
    /// Arbitrary key-value pairs for framework extensions.
    pub metadata: MetadataMap,
}

impl ToolResult {
    /// Builds a tool result with no duration and empty metadata.
    pub fn new(result: ToolResultPart) -> Self {
        Self {
            result,
            duration: None,
            metadata: MetadataMap::new(),
        }
    }

    /// Sets the measured duration.
    pub fn with_duration(mut self, duration: Duration) -> Self {
        self.duration = Some(duration);
        self
    }

    /// Replaces the result metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Trait for dependency injection into tool implementations.
///
/// Tools that need access to shared state (database handles, HTTP clients,
/// configuration, etc.) can downcast the `&dyn ToolResources` provided in
/// [`ToolContext`] to a concrete type.
///
/// The unit type `()` implements `ToolResources` and serves as the default
/// when no shared resources are needed.
///
/// # Example
///
/// ```rust
/// use std::any::Any;
/// use agentkit_tools_core::ToolResources;
///
/// struct AppResources {
///     project_root: std::path::PathBuf,
/// }
///
/// impl ToolResources for AppResources {
///     fn as_any(&self) -> &dyn Any {
///         self
///     }
/// }
/// ```
pub trait ToolResources: Send + Sync {
    /// Returns a reference to `self` as [`Any`] so callers can downcast to
    /// the concrete resource type.
    fn as_any(&self) -> &dyn Any;
}

impl ToolResources for () {
    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Runtime context passed to every [`Tool::invoke`] call.
///
/// Provides the tool with access to session/turn metadata, the active
/// permission checker, shared resources, and a cancellation signal so the
/// tool can abort long-running work when a turn is cancelled.
pub struct ToolContext<'a> {
    /// Capability-layer context carrying session and turn identifiers.
    pub capability: CapabilityContext<'a>,
    /// The active permission checker for sub-operations the tool may perform.
    pub permissions: &'a dyn PermissionChecker,
    /// Shared resources (e.g. database handles, config) injected by the host.
    pub resources: &'a dyn ToolResources,
    /// Signal that the current turn has been cancelled by the user.
    pub cancellation: Option<TurnCancellation>,
}

/// Owned execution context that can outlive a single stack frame.
///
/// This is useful for schedulers or task managers that need to move a tool
/// execution onto another task while still constructing the borrowed
/// [`ToolContext`] expected by existing tool implementations.
#[derive(Clone)]
pub struct OwnedToolContext {
    /// Session identifier for the invocation.
    pub session_id: SessionId,
    /// Turn identifier for the invocation.
    pub turn_id: TurnId,
    /// Arbitrary invocation metadata.
    pub metadata: MetadataMap,
    /// Shared permission checker.
    pub permissions: Arc<dyn PermissionChecker>,
    /// Shared resources injected by the host.
    pub resources: Arc<dyn ToolResources>,
    /// Cooperative cancellation signal for the invocation.
    pub cancellation: Option<TurnCancellation>,
}

impl OwnedToolContext {
    /// Creates a borrowed [`ToolContext`] view over this owned context.
    pub fn borrowed(&self) -> ToolContext<'_> {
        ToolContext {
            capability: CapabilityContext {
                session_id: Some(&self.session_id),
                turn_id: Some(&self.turn_id),
                metadata: &self.metadata,
            },
            permissions: self.permissions.as_ref(),
            resources: self.resources.as_ref(),
            cancellation: self.cancellation.clone(),
        }
    }
}

/// A description of an operation that requires permission before it can proceed.
///
/// Tool implementations return `PermissionRequest` objects from
/// [`Tool::proposed_requests`] so the executor can evaluate them against the
/// active [`PermissionChecker`] before invoking the tool.
///
/// Built-in implementations include [`ShellPermissionRequest`],
/// [`FileSystemPermissionRequest`], and [`McpPermissionRequest`].
///
/// # Implementing a custom request
///
/// ```rust
/// use std::any::Any;
/// use agentkit_core::MetadataMap;
/// use agentkit_tools_core::PermissionRequest;
///
/// struct NetworkPermissionRequest {
///     url: String,
///     metadata: MetadataMap,
/// }
///
/// impl PermissionRequest for NetworkPermissionRequest {
///     fn kind(&self) -> &'static str { "network.http" }
///     fn summary(&self) -> String { format!("HTTP request to {}", self.url) }
///     fn metadata(&self) -> &MetadataMap { &self.metadata }
///     fn as_any(&self) -> &dyn Any { self }
/// }
/// ```
pub trait PermissionRequest: Send + Sync {
    /// A dot-separated category string (e.g. `"filesystem.write"`, `"shell.command"`).
    fn kind(&self) -> &'static str;
    /// Human-readable one-line description of what is being requested.
    fn summary(&self) -> String;
    /// Arbitrary metadata attached to this request.
    fn metadata(&self) -> &MetadataMap;
    /// Returns `self` as [`Any`] so policies can downcast to the concrete type.
    fn as_any(&self) -> &dyn Any;
}

/// Machine-readable code indicating why a permission was denied.
///
/// Returned inside a [`PermissionDenial`] so callers can programmatically
/// react to specific denial categories.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum PermissionCode {
    /// A filesystem path is outside the allowed set.
    PathNotAllowed,
    /// A shell command or executable is not permitted.
    CommandNotAllowed,
    /// A network operation is not permitted.
    NetworkNotAllowed,
    /// An MCP server is not in the trusted set.
    ServerNotTrusted,
    /// An MCP auth scope is not in the allowed set.
    AuthScopeNotAllowed,
    /// A custom permission policy explicitly denied the request.
    CustomPolicyDenied,
    /// No policy recognised the request kind.
    UnknownRequest,
}

/// Structured denial produced when a [`PermissionChecker`] rejects an operation.
///
/// Contains a machine-readable [`PermissionCode`] and a human-readable
/// message suitable for logging or displaying to the user.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct PermissionDenial {
    /// Machine-readable denial category.
    pub code: PermissionCode,
    /// Human-readable explanation of why the operation was denied.
    pub message: String,
    /// Arbitrary metadata carried from the original request.
    pub metadata: MetadataMap,
}

/// Why a permission policy is requesting human approval before proceeding.
///
/// Used inside [`ApprovalRequest`] so the UI layer can display context-appropriate
/// prompts to the user.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ApprovalReason {
    /// The active policy always requires confirmation for this kind of operation.
    PolicyRequiresConfirmation,
    /// The operation was flagged as higher risk than usual.
    EscalatedRisk,
    /// The target (server, path, etc.) was not recognised by any policy.
    UnknownTarget,
    /// The operation targets a filesystem path that is not in the allowed set.
    SensitivePath,
    /// The shell command is not in the pre-approved allow-list.
    SensitiveCommand,
    /// The MCP server is not in the trusted set.
    SensitiveServer,
    /// The MCP auth scope is not in the pre-approved set.
    SensitiveAuthScope,
}

/// A request sent to the host when a tool execution needs human approval.
///
/// The agent loop surfaces this to the user. Once the user responds, the
/// loop can re-submit the tool call via [`ToolExecutor::execute_approved`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ApprovalRequest {
    /// Runtime task identifier associated with this approval request, if any.
    pub task_id: Option<TaskId>,
    /// The originating tool call id when this approval was raised from a
    /// tool invocation. Hosts can use this to resolve specific approvals.
    pub call_id: Option<ToolCallId>,
    /// Stable identifier so the executor can match the approval to its request.
    pub id: ApprovalId,
    /// The [`PermissionRequest::kind`] string that triggered the approval flow.
    pub request_kind: String,
    /// Why approval is needed.
    pub reason: ApprovalReason,
    /// Human-readable summary shown to the user.
    pub summary: String,
    /// Arbitrary metadata carried from the original permission request.
    pub metadata: MetadataMap,
}

impl ApprovalRequest {
    /// Builds an approval request with no task or call id.
    pub fn new(
        id: impl Into<ApprovalId>,
        request_kind: impl Into<String>,
        reason: ApprovalReason,
        summary: impl Into<String>,
    ) -> Self {
        Self {
            task_id: None,
            call_id: None,
            id: id.into(),
            request_kind: request_kind.into(),
            reason,
            summary: summary.into(),
            metadata: MetadataMap::new(),
        }
    }

    /// Sets the associated task id.
    pub fn with_task_id(mut self, task_id: impl Into<TaskId>) -> Self {
        self.task_id = Some(task_id.into());
        self
    }

    /// Sets the associated tool call id.
    pub fn with_call_id(mut self, call_id: impl Into<ToolCallId>) -> Self {
        self.call_id = Some(call_id.into());
        self
    }

    /// Replaces the approval metadata.
    pub fn with_metadata(mut self, metadata: MetadataMap) -> Self {
        self.metadata = metadata;
        self
    }
}

/// The user's response to an [`ApprovalRequest`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ApprovalDecision {
    /// The user approved the operation.
    Approve,
    /// The user denied the operation, optionally with a reason.
    Deny {
        /// Optional human-readable explanation for the denial.
        reason: Option<String>,
    },
}

/// A request for authentication credentials before a tool can proceed.
///
/// Emitted as [`ToolInterruption::AuthRequired`] when a tool (typically an
/// MCP integration) needs OAuth tokens, API keys, or other credentials that
/// the user must supply interactively.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct AuthRequest {
    /// Runtime task identifier associated with this auth request, if any.
    pub task_id: Option<TaskId>,
    /// Unique identifier for this auth challenge.
    pub id: String,
    /// Name of the authentication provider (e.g. `"github"`, `"google"`).
    pub provider: String,
    /// The operation that triggered the auth requirement.
    pub operation: AuthOperation,
    /// Provider-specific challenge data (e.g. OAuth URLs, scopes).
    pub challenge: MetadataMap,
}

impl AuthRequest {
    /// Builds an auth request with no task id and empty challenge metadata.
    pub fn new(
        id: impl Into<String>,
        provider: impl Into<String>,
        operation: AuthOperation,
    ) -> Self {
        Self {
            task_id: None,
            id: id.into(),
            provider: provider.into(),
            operation,
            challenge: MetadataMap::new(),
        }
    }

    /// Sets the associated task id.
    pub fn with_task_id(mut self, task_id: impl Into<TaskId>) -> Self {
        self.task_id = Some(task_id.into());
        self
    }

    /// Replaces the auth challenge payload.
    pub fn with_challenge(mut self, challenge: MetadataMap) -> Self {
        self.challenge = challenge;
        self
    }
}

/// Describes the operation that triggered an [`AuthRequest`].
///
/// The agent loop can inspect this to decide how to present the auth
/// challenge and where to deliver the resulting credentials.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthOperation {
    /// A local tool call that requires auth.
    ToolCall {
        tool_name: String,
        input: Value,
        call_id: Option<ToolCallId>,
        session_id: Option<SessionId>,
        turn_id: Option<TurnId>,
        metadata: MetadataMap,
    },
    /// Connecting to an MCP server that requires auth.
    McpConnect {
        server_id: String,
        metadata: MetadataMap,
    },
    /// Invoking a tool on an MCP server that requires auth.
    McpToolCall {
        server_id: String,
        tool_name: String,
        input: Value,
        metadata: MetadataMap,
    },
    /// Reading a resource from an MCP server that requires auth.
    McpResourceRead {
        server_id: String,
        resource_id: String,
        metadata: MetadataMap,
    },
    /// Fetching a prompt from an MCP server that requires auth.
    McpPromptGet {
        server_id: String,
        prompt_id: String,
        args: Value,
        metadata: MetadataMap,
    },
    /// An application-defined operation that requires auth.
    Custom {
        kind: String,
        payload: Value,
        metadata: MetadataMap,
    },
}

impl AuthOperation {
    /// Returns the MCP server ID if this operation targets one, or looks it
    /// up in metadata for `ToolCall` and `Custom` variants.
    pub fn server_id(&self) -> Option<&str> {
        match self {
            Self::McpConnect { server_id, .. }
            | Self::McpToolCall { server_id, .. }
            | Self::McpResourceRead { server_id, .. }
            | Self::McpPromptGet { server_id, .. } => Some(server_id.as_str()),
            Self::ToolCall { metadata, .. } | Self::Custom { metadata, .. } => {
                metadata.get("server_id").and_then(Value::as_str)
            }
        }
    }
}

/// The outcome of an [`AuthRequest`] after the user interacts with the auth flow.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum AuthResolution {
    /// The user completed authentication and supplied credentials.
    Provided {
        /// The original auth request.
        request: AuthRequest,
        /// Credentials the user provided (tokens, keys, etc.).
        credentials: MetadataMap,
    },
    /// The user cancelled the authentication flow.
    Cancelled {
        /// The original auth request that was cancelled.
        request: AuthRequest,
    },
}

impl AuthResolution {
    /// Builds a successful auth resolution.
    pub fn provided(request: AuthRequest, credentials: MetadataMap) -> Self {
        Self::Provided {
            request,
            credentials,
        }
    }

    /// Builds a cancelled auth resolution.
    pub fn cancelled(request: AuthRequest) -> Self {
        Self::Cancelled { request }
    }

    /// Returns a reference to the underlying [`AuthRequest`] regardless of
    /// the resolution variant.
    pub fn request(&self) -> &AuthRequest {
        match self {
            Self::Provided { request, .. } | Self::Cancelled { request } => request,
        }
    }
}

impl AuthRequest {
    /// Convenience accessor that delegates to [`AuthOperation::server_id`].
    pub fn server_id(&self) -> Option<&str> {
        self.operation.server_id()
    }
}

/// A tool execution was paused because it needs external input.
///
/// The agent loop should handle the interruption (show a prompt, open an
/// OAuth flow, etc.) and then re-submit the tool call.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ToolInterruption {
    /// The operation requires human approval before it can proceed.
    ApprovalRequired(ApprovalRequest),
    /// The operation requires authentication credentials.
    AuthRequired(AuthRequest),
}

/// The verdict from a [`PermissionChecker`] for a single [`PermissionRequest`].
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum PermissionDecision {
    /// The operation is allowed to proceed.
    Allow,
    /// The operation is denied.
    Deny(PermissionDenial),
    /// The operation may proceed only after the user approves.
    RequireApproval(ApprovalRequest),
}

/// Evaluates a [`PermissionRequest`] and returns a final [`PermissionDecision`].
///
/// The [`BasicToolExecutor`] calls `evaluate` for every permission request
/// returned by [`Tool::proposed_requests`] before invoking the tool. If any
/// request is denied, execution is aborted; if any request requires approval,
/// the executor returns a [`ToolInterruption`].
///
/// For composing multiple policies, see [`CompositePermissionChecker`].
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::{PermissionChecker, PermissionDecision, PermissionRequest};
///
/// /// A checker that allows every operation unconditionally.
/// struct AllowAll;
///
/// impl PermissionChecker for AllowAll {
///     fn evaluate(&self, _request: &dyn PermissionRequest) -> PermissionDecision {
///         PermissionDecision::Allow
///     }
/// }
/// ```
pub trait PermissionChecker: Send + Sync {
    /// Evaluate a single permission request and return the decision.
    fn evaluate(&self, request: &dyn PermissionRequest) -> PermissionDecision;
}

/// The result of a single [`PermissionPolicy`] evaluation.
///
/// Unlike [`PermissionDecision`], a policy can return [`PolicyMatch::NoOpinion`]
/// to indicate it has nothing to say about this request kind, letting other
/// policies in the [`CompositePermissionChecker`] chain decide.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum PolicyMatch {
    /// This policy does not apply to the given request kind.
    NoOpinion,
    /// This policy explicitly allows the operation.
    Allow,
    /// This policy explicitly denies the operation.
    Deny(PermissionDenial),
    /// This policy requires user approval before the operation can proceed.
    RequireApproval(ApprovalRequest),
}

/// A single, focused permission rule that contributes to a composite decision.
///
/// Policies are combined inside a [`CompositePermissionChecker`]. Each policy
/// inspects the request and either returns a definitive answer or
/// [`PolicyMatch::NoOpinion`] to defer.
///
/// Built-in policies: [`PathPolicy`], [`CommandPolicy`], [`McpServerPolicy`],
/// [`CustomKindPolicy`].
pub trait PermissionPolicy: Send + Sync {
    /// Evaluate the request and return a match or [`PolicyMatch::NoOpinion`].
    fn evaluate(&self, request: &dyn PermissionRequest) -> PolicyMatch;
}

/// Chains multiple [`PermissionPolicy`] implementations into a single [`PermissionChecker`].
///
/// Policies are evaluated in registration order. The first `Deny` short-circuits
/// immediately. If any policy returns `RequireApproval`, that is used unless a
/// later policy denies. If at least one policy returns `Allow` and none deny or
/// require approval, the result is `Allow`. Otherwise the `fallback` decision
/// is returned.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::{
///     CommandPolicy, CompositePermissionChecker, PathPolicy, PermissionDecision,
/// };
///
/// let checker = CompositePermissionChecker::new(PermissionDecision::Allow)
///     .with_policy(PathPolicy::new().allow_root("/workspace"))
///     .with_policy(CommandPolicy::new().allow_executable("git"));
/// ```
pub struct CompositePermissionChecker {
    policies: Vec<Box<dyn PermissionPolicy>>,
    fallback: PermissionDecision,
}

impl CompositePermissionChecker {
    /// Creates a new composite checker with the given fallback decision.
    ///
    /// The fallback is used when no policy has an opinion about a request.
    ///
    /// # Arguments
    ///
    /// * `fallback` - Decision returned when every policy returns [`PolicyMatch::NoOpinion`].
    pub fn new(fallback: PermissionDecision) -> Self {
        Self {
            policies: Vec::new(),
            fallback,
        }
    }

    /// Appends a policy to the evaluation chain and returns `self` for chaining.
    pub fn with_policy(mut self, policy: impl PermissionPolicy + 'static) -> Self {
        self.policies.push(Box::new(policy));
        self
    }
}

impl PermissionChecker for CompositePermissionChecker {
    fn evaluate(&self, request: &dyn PermissionRequest) -> PermissionDecision {
        let mut saw_allow = false;
        let mut approval = None;

        for policy in &self.policies {
            match policy.evaluate(request) {
                PolicyMatch::NoOpinion => {}
                PolicyMatch::Allow => saw_allow = true,
                PolicyMatch::Deny(denial) => return PermissionDecision::Deny(denial),
                PolicyMatch::RequireApproval(req) => approval = Some(req),
            }
        }

        if let Some(req) = approval {
            PermissionDecision::RequireApproval(req)
        } else if saw_allow {
            PermissionDecision::Allow
        } else {
            self.fallback.clone()
        }
    }
}

/// Permission request for executing a shell command.
///
/// Evaluated by [`CommandPolicy`] to decide whether the executable, arguments,
/// working directory, and environment variables are acceptable.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ShellPermissionRequest {
    /// The executable name or path (e.g. `"git"`, `"/usr/bin/curl"`).
    pub executable: String,
    /// Command-line arguments passed to the executable.
    pub argv: Vec<String>,
    /// Working directory for the command, if specified.
    pub cwd: Option<PathBuf>,
    /// Names of environment variables the command will receive.
    pub env_keys: Vec<String>,
    /// Arbitrary metadata for policy extensions.
    pub metadata: MetadataMap,
}

impl PermissionRequest for ShellPermissionRequest {
    fn kind(&self) -> &'static str {
        "shell.command"
    }

    fn summary(&self) -> String {
        if self.argv.is_empty() {
            self.executable.clone()
        } else {
            format!("{} {}", self.executable, self.argv.join(" "))
        }
    }

    fn metadata(&self) -> &MetadataMap {
        &self.metadata
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Permission request for a filesystem operation.
///
/// Evaluated by [`PathPolicy`] to decide whether the target path(s) fall
/// within allowed or protected directory roots.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum FileSystemPermissionRequest {
    /// Read a file's contents.
    Read {
        path: PathBuf,
        metadata: MetadataMap,
    },
    /// Write (create or overwrite) a file.
    Write {
        path: PathBuf,
        metadata: MetadataMap,
    },
    /// Edit (modify in place) an existing file.
    Edit {
        path: PathBuf,
        metadata: MetadataMap,
    },
    /// Delete a file or directory.
    Delete {
        path: PathBuf,
        metadata: MetadataMap,
    },
    /// Move or rename a file.
    Move {
        from: PathBuf,
        to: PathBuf,
        metadata: MetadataMap,
    },
    /// List directory contents.
    List {
        path: PathBuf,
        metadata: MetadataMap,
    },
    /// Create a directory (including parents).
    CreateDir {
        path: PathBuf,
        metadata: MetadataMap,
    },
}

impl FileSystemPermissionRequest {
    fn metadata_map(&self) -> &MetadataMap {
        match self {
            Self::Read { metadata, .. }
            | Self::Write { metadata, .. }
            | Self::Edit { metadata, .. }
            | Self::Delete { metadata, .. }
            | Self::Move { metadata, .. }
            | Self::List { metadata, .. }
            | Self::CreateDir { metadata, .. } => metadata,
        }
    }
}

impl PermissionRequest for FileSystemPermissionRequest {
    fn kind(&self) -> &'static str {
        match self {
            Self::Read { .. } => "filesystem.read",
            Self::Write { .. } => "filesystem.write",
            Self::Edit { .. } => "filesystem.edit",
            Self::Delete { .. } => "filesystem.delete",
            Self::Move { .. } => "filesystem.move",
            Self::List { .. } => "filesystem.list",
            Self::CreateDir { .. } => "filesystem.mkdir",
        }
    }

    fn summary(&self) -> String {
        match self {
            Self::Read { path, .. } => format!("Read {}", path.display()),
            Self::Write { path, .. } => format!("Write {}", path.display()),
            Self::Edit { path, .. } => format!("Edit {}", path.display()),
            Self::Delete { path, .. } => format!("Delete {}", path.display()),
            Self::Move { from, to, .. } => {
                format!("Move {} to {}", from.display(), to.display())
            }
            Self::List { path, .. } => format!("List {}", path.display()),
            Self::CreateDir { path, .. } => format!("Create directory {}", path.display()),
        }
    }

    fn metadata(&self) -> &MetadataMap {
        self.metadata_map()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Permission request for an MCP (Model Context Protocol) operation.
///
/// Evaluated by [`McpServerPolicy`] to decide whether the target server is
/// trusted and the requested auth scopes are allowed.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum McpPermissionRequest {
    /// Connect to an MCP server.
    Connect {
        server_id: String,
        metadata: MetadataMap,
    },
    /// Invoke a tool exposed by an MCP server.
    InvokeTool {
        server_id: String,
        tool_name: String,
        metadata: MetadataMap,
    },
    /// Read a resource from an MCP server.
    ReadResource {
        server_id: String,
        resource_id: String,
        metadata: MetadataMap,
    },
    /// Fetch a prompt template from an MCP server.
    FetchPrompt {
        server_id: String,
        prompt_id: String,
        metadata: MetadataMap,
    },
    /// Request an auth scope on an MCP server.
    UseAuthScope {
        server_id: String,
        scope: String,
        metadata: MetadataMap,
    },
}

impl McpPermissionRequest {
    fn metadata_map(&self) -> &MetadataMap {
        match self {
            Self::Connect { metadata, .. }
            | Self::InvokeTool { metadata, .. }
            | Self::ReadResource { metadata, .. }
            | Self::FetchPrompt { metadata, .. }
            | Self::UseAuthScope { metadata, .. } => metadata,
        }
    }
}

impl PermissionRequest for McpPermissionRequest {
    fn kind(&self) -> &'static str {
        match self {
            Self::Connect { .. } => "mcp.connect",
            Self::InvokeTool { .. } => "mcp.invoke_tool",
            Self::ReadResource { .. } => "mcp.read_resource",
            Self::FetchPrompt { .. } => "mcp.fetch_prompt",
            Self::UseAuthScope { .. } => "mcp.use_auth_scope",
        }
    }

    fn summary(&self) -> String {
        match self {
            Self::Connect { server_id, .. } => format!("Connect MCP server {server_id}"),
            Self::InvokeTool {
                server_id,
                tool_name,
                ..
            } => format!("Invoke MCP tool {server_id}.{tool_name}"),
            Self::ReadResource {
                server_id,
                resource_id,
                ..
            } => format!("Read MCP resource {server_id}:{resource_id}"),
            Self::FetchPrompt {
                server_id,
                prompt_id,
                ..
            } => format!("Fetch MCP prompt {server_id}:{prompt_id}"),
            Self::UseAuthScope {
                server_id, scope, ..
            } => format!("Use MCP auth scope {server_id}:{scope}"),
        }
    }

    fn metadata(&self) -> &MetadataMap {
        self.metadata_map()
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// A [`PermissionPolicy`] that matches requests whose [`PermissionRequest::kind`]
/// starts with `"custom."` and allows or denies them by name.
///
/// Use this to govern application-defined permission categories without
/// writing a full policy implementation.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::CustomKindPolicy;
///
/// let policy = CustomKindPolicy::new(true)
///     .allow_kind("custom.analytics")
///     .deny_kind("custom.billing");
/// ```
pub struct CustomKindPolicy {
    allowed_kinds: BTreeSet<String>,
    denied_kinds: BTreeSet<String>,
    require_approval_by_default: bool,
}

impl CustomKindPolicy {
    /// Creates a new policy.
    ///
    /// # Arguments
    ///
    /// * `require_approval_by_default` - When `true`, unrecognised `custom.*`
    ///   kinds require approval instead of returning [`PolicyMatch::NoOpinion`].
    pub fn new(require_approval_by_default: bool) -> Self {
        Self {
            allowed_kinds: BTreeSet::new(),
            denied_kinds: BTreeSet::new(),
            require_approval_by_default,
        }
    }

    /// Adds a kind string to the allow-list.
    pub fn allow_kind(mut self, kind: impl Into<String>) -> Self {
        self.allowed_kinds.insert(kind.into());
        self
    }

    /// Adds a kind string to the deny-list.
    pub fn deny_kind(mut self, kind: impl Into<String>) -> Self {
        self.denied_kinds.insert(kind.into());
        self
    }
}

impl PermissionPolicy for CustomKindPolicy {
    fn evaluate(&self, request: &dyn PermissionRequest) -> PolicyMatch {
        let kind = request.kind();
        if !kind.starts_with("custom.") {
            return PolicyMatch::NoOpinion;
        }
        if self.denied_kinds.contains(kind) {
            return PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::CustomPolicyDenied,
                message: format!("custom permission kind {kind} is denied"),
                metadata: request.metadata().clone(),
            });
        }
        if self.allowed_kinds.contains(kind) {
            return PolicyMatch::Allow;
        }
        if self.require_approval_by_default {
            PolicyMatch::RequireApproval(ApprovalRequest {
                task_id: None,
                call_id: None,
                id: ApprovalId::new(format!("approval:{kind}")),
                request_kind: kind.to_string(),
                reason: ApprovalReason::PolicyRequiresConfirmation,
                summary: request.summary(),
                metadata: request.metadata().clone(),
            })
        } else {
            PolicyMatch::NoOpinion
        }
    }
}

/// A [`PermissionPolicy`] that governs [`FileSystemPermissionRequest`]s by
/// checking whether target paths fall within allowed or protected directory trees.
///
/// Protected roots take priority: any path under a protected root is denied
/// immediately. Paths under an allowed root are permitted. Paths outside both
/// sets either require approval or are denied, depending on
/// `require_approval_outside_allowed`.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::PathPolicy;
///
/// let policy = PathPolicy::new()
///     .allow_root("/workspace/project")
///     .read_only_root("/workspace/project/vendor")
///     .protect_root("/workspace/project/.env")
///     .require_approval_outside_allowed(true);
/// ```
pub struct PathPolicy {
    allowed_roots: Vec<PathBuf>,
    read_only_roots: Vec<PathBuf>,
    protected_roots: Vec<PathBuf>,
    require_approval_outside_allowed: bool,
}

impl PathPolicy {
    /// Creates a new path policy with no roots and approval required for
    /// paths outside allowed roots.
    pub fn new() -> Self {
        Self {
            allowed_roots: Vec::new(),
            read_only_roots: Vec::new(),
            protected_roots: Vec::new(),
            require_approval_outside_allowed: true,
        }
    }

    /// Adds a directory tree that filesystem operations are allowed to target.
    pub fn allow_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.allowed_roots.push(root.into());
        self
    }

    /// Adds a directory tree that may be read or listed but not mutated.
    pub fn read_only_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.read_only_roots.push(root.into());
        self
    }

    /// Adds a directory tree that filesystem operations are never allowed to target.
    pub fn protect_root(mut self, root: impl Into<PathBuf>) -> Self {
        self.protected_roots.push(root.into());
        self
    }

    /// When `true` (the default), paths outside allowed roots trigger an
    /// approval request instead of an outright denial.
    pub fn require_approval_outside_allowed(mut self, value: bool) -> Self {
        self.require_approval_outside_allowed = value;
        self
    }
}

impl Default for PathPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl PermissionPolicy for PathPolicy {
    fn evaluate(&self, request: &dyn PermissionRequest) -> PolicyMatch {
        let Some(fs) = request
            .as_any()
            .downcast_ref::<FileSystemPermissionRequest>()
        else {
            return PolicyMatch::NoOpinion;
        };

        let raw_paths: Vec<&Path> = match fs {
            FileSystemPermissionRequest::Move { from, to, .. } => {
                vec![from.as_path(), to.as_path()]
            }
            FileSystemPermissionRequest::Read { path, .. }
            | FileSystemPermissionRequest::Write { path, .. }
            | FileSystemPermissionRequest::Edit { path, .. }
            | FileSystemPermissionRequest::Delete { path, .. }
            | FileSystemPermissionRequest::List { path, .. }
            | FileSystemPermissionRequest::CreateDir { path, .. } => vec![path.as_path()],
        };

        let candidate_paths: Vec<PathBuf> = raw_paths
            .iter()
            .map(|p| std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf()))
            .collect();

        let mutates = matches!(
            fs,
            FileSystemPermissionRequest::Write { .. }
                | FileSystemPermissionRequest::Edit { .. }
                | FileSystemPermissionRequest::Delete { .. }
                | FileSystemPermissionRequest::Move { .. }
                | FileSystemPermissionRequest::CreateDir { .. }
        );

        if candidate_paths.iter().any(|path| {
            self.protected_roots
                .iter()
                .any(|root| path.starts_with(root))
        }) {
            return PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::PathNotAllowed,
                message: format!("path access denied for {}", fs.summary()),
                metadata: fs.metadata().clone(),
            });
        }

        if mutates
            && candidate_paths.iter().any(|path| {
                self.read_only_roots
                    .iter()
                    .any(|root| path.starts_with(root))
            })
        {
            return PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::PathNotAllowed,
                message: format!("path is read-only for {}", fs.summary()),
                metadata: fs.metadata().clone(),
            });
        }

        if self.allowed_roots.is_empty() {
            return PolicyMatch::NoOpinion;
        }

        let all_allowed = candidate_paths
            .iter()
            .all(|path| self.allowed_roots.iter().any(|root| path.starts_with(root)));

        if all_allowed {
            PolicyMatch::Allow
        } else if self.require_approval_outside_allowed {
            PolicyMatch::RequireApproval(ApprovalRequest {
                task_id: None,
                call_id: None,
                id: ApprovalId::new(format!("approval:{}", fs.kind())),
                request_kind: fs.kind().to_string(),
                reason: ApprovalReason::SensitivePath,
                summary: fs.summary(),
                metadata: fs.metadata().clone(),
            })
        } else {
            PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::PathNotAllowed,
                message: format!("path outside allowed roots for {}", fs.summary()),
                metadata: fs.metadata().clone(),
            })
        }
    }
}

/// A [`PermissionPolicy`] that governs [`ShellPermissionRequest`]s by checking
/// the executable name, working directory, and environment variables.
///
/// Denied executables and env keys are rejected immediately. Allowed
/// executables pass. Unknown executables either require approval or are
/// denied, depending on `require_approval_for_unknown`.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::CommandPolicy;
///
/// let policy = CommandPolicy::new()
///     .allow_executable("git")
///     .allow_executable("cargo")
///     .deny_executable("rm")
///     .deny_env_key("AWS_SECRET_ACCESS_KEY")
///     .allow_cwd("/workspace")
///     .require_approval_for_unknown(true);
/// ```
pub struct CommandPolicy {
    allowed_executables: BTreeSet<String>,
    denied_executables: BTreeSet<String>,
    allowed_cwds: Vec<PathBuf>,
    denied_env_keys: BTreeSet<String>,
    require_approval_for_unknown: bool,
}

impl CommandPolicy {
    /// Creates a new command policy with no rules and approval required
    /// for unknown executables.
    pub fn new() -> Self {
        Self {
            allowed_executables: BTreeSet::new(),
            denied_executables: BTreeSet::new(),
            allowed_cwds: Vec::new(),
            denied_env_keys: BTreeSet::new(),
            require_approval_for_unknown: true,
        }
    }

    /// Adds an executable name to the allow-list.
    pub fn allow_executable(mut self, executable: impl Into<String>) -> Self {
        self.allowed_executables.insert(executable.into());
        self
    }

    /// Adds an executable name to the deny-list.
    pub fn deny_executable(mut self, executable: impl Into<String>) -> Self {
        self.denied_executables.insert(executable.into());
        self
    }

    /// Adds a directory root that commands are allowed to run in.
    pub fn allow_cwd(mut self, cwd: impl Into<PathBuf>) -> Self {
        self.allowed_cwds.push(cwd.into());
        self
    }

    /// Adds an environment variable name to the deny-list.
    pub fn deny_env_key(mut self, key: impl Into<String>) -> Self {
        self.denied_env_keys.insert(key.into());
        self
    }

    /// When `true` (the default), executables not in the allow-list trigger
    /// an approval request instead of an outright denial.
    pub fn require_approval_for_unknown(mut self, value: bool) -> Self {
        self.require_approval_for_unknown = value;
        self
    }
}

impl Default for CommandPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl PermissionPolicy for CommandPolicy {
    fn evaluate(&self, request: &dyn PermissionRequest) -> PolicyMatch {
        let Some(shell) = request.as_any().downcast_ref::<ShellPermissionRequest>() else {
            return PolicyMatch::NoOpinion;
        };

        if self.denied_executables.contains(&shell.executable)
            || shell
                .env_keys
                .iter()
                .any(|key| self.denied_env_keys.contains(key))
        {
            return PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::CommandNotAllowed,
                message: format!("command denied for {}", shell.summary()),
                metadata: shell.metadata().clone(),
            });
        }

        if let Some(cwd) = &shell.cwd
            && !self.allowed_cwds.is_empty()
            && !self.allowed_cwds.iter().any(|root| cwd.starts_with(root))
        {
            return PolicyMatch::RequireApproval(ApprovalRequest {
                task_id: None,
                call_id: None,
                id: ApprovalId::new("approval:shell.cwd"),
                request_kind: shell.kind().to_string(),
                reason: ApprovalReason::SensitiveCommand,
                summary: shell.summary(),
                metadata: shell.metadata().clone(),
            });
        }

        if self.allowed_executables.is_empty()
            || self.allowed_executables.contains(&shell.executable)
        {
            PolicyMatch::Allow
        } else if self.require_approval_for_unknown {
            PolicyMatch::RequireApproval(ApprovalRequest {
                task_id: None,
                call_id: None,
                id: ApprovalId::new("approval:shell.command"),
                request_kind: shell.kind().to_string(),
                reason: ApprovalReason::SensitiveCommand,
                summary: shell.summary(),
                metadata: shell.metadata().clone(),
            })
        } else {
            PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::CommandNotAllowed,
                message: format!("executable {} is not allowed", shell.executable),
                metadata: shell.metadata().clone(),
            })
        }
    }
}

/// A [`PermissionPolicy`] that governs [`McpPermissionRequest`]s by checking
/// whether the target server is trusted and the requested auth scopes are
/// in the allow-list.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::McpServerPolicy;
///
/// let policy = McpServerPolicy::new()
///     .trust_server("github-mcp")
///     .allow_auth_scope("repo:read");
/// ```
pub struct McpServerPolicy {
    trusted_servers: BTreeSet<String>,
    allowed_auth_scopes: BTreeSet<String>,
    require_approval_for_untrusted: bool,
}

impl McpServerPolicy {
    /// Creates a new MCP server policy with approval required for untrusted
    /// servers.
    pub fn new() -> Self {
        Self {
            trusted_servers: BTreeSet::new(),
            allowed_auth_scopes: BTreeSet::new(),
            require_approval_for_untrusted: true,
        }
    }

    /// Marks a server as trusted so operations targeting it are allowed.
    pub fn trust_server(mut self, server_id: impl Into<String>) -> Self {
        self.trusted_servers.insert(server_id.into());
        self
    }

    /// Adds an auth scope to the allow-list.
    pub fn allow_auth_scope(mut self, scope: impl Into<String>) -> Self {
        self.allowed_auth_scopes.insert(scope.into());
        self
    }
}

impl Default for McpServerPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl PermissionPolicy for McpServerPolicy {
    fn evaluate(&self, request: &dyn PermissionRequest) -> PolicyMatch {
        let Some(mcp) = request.as_any().downcast_ref::<McpPermissionRequest>() else {
            return PolicyMatch::NoOpinion;
        };

        let server_id = match mcp {
            McpPermissionRequest::Connect { server_id, .. }
            | McpPermissionRequest::InvokeTool { server_id, .. }
            | McpPermissionRequest::ReadResource { server_id, .. }
            | McpPermissionRequest::FetchPrompt { server_id, .. }
            | McpPermissionRequest::UseAuthScope { server_id, .. } => server_id,
        };

        if !self.trusted_servers.is_empty() && !self.trusted_servers.contains(server_id) {
            return if self.require_approval_for_untrusted {
                PolicyMatch::RequireApproval(ApprovalRequest {
                    task_id: None,
                    call_id: None,
                    id: ApprovalId::new(format!("approval:mcp:{server_id}")),
                    request_kind: mcp.kind().to_string(),
                    reason: ApprovalReason::SensitiveServer,
                    summary: mcp.summary(),
                    metadata: mcp.metadata().clone(),
                })
            } else {
                PolicyMatch::Deny(PermissionDenial {
                    code: PermissionCode::ServerNotTrusted,
                    message: format!("MCP server {server_id} is not trusted"),
                    metadata: mcp.metadata().clone(),
                })
            };
        }

        if let McpPermissionRequest::UseAuthScope { scope, .. } = mcp
            && !self.allowed_auth_scopes.is_empty()
            && !self.allowed_auth_scopes.contains(scope)
        {
            return PolicyMatch::Deny(PermissionDenial {
                code: PermissionCode::AuthScopeNotAllowed,
                message: format!("MCP auth scope {scope} is not allowed"),
                metadata: mcp.metadata().clone(),
            });
        }

        PolicyMatch::Allow
    }
}

/// The central abstraction for an executable tool in an agentkit agent.
///
/// Implement this trait to define a tool that an LLM can call. Each tool
/// provides a [`ToolSpec`] describing its name, schema, and hints, optional
/// permission requests via [`proposed_requests`](Tool::proposed_requests),
/// and the actual execution logic in [`invoke`](Tool::invoke).
///
/// # Example
///
/// ```rust
/// use agentkit_core::{MetadataMap, ToolOutput, ToolResultPart};
/// use agentkit_tools_core::{
///     Tool, ToolContext, ToolError, ToolName, ToolRequest, ToolResult, ToolSpec,
/// };
/// use async_trait::async_trait;
/// use serde_json::json;
///
/// struct TimeTool {
///     spec: ToolSpec,
/// }
///
/// impl TimeTool {
///     fn new() -> Self {
///         Self {
///             spec: ToolSpec::new(
///                 ToolName::new("current_time"),
///                 "Returns the current UTC time",
///                 json!({ "type": "object" }),
///             ),
///         }
///     }
/// }
///
/// #[async_trait]
/// impl Tool for TimeTool {
///     fn spec(&self) -> &ToolSpec {
///         &self.spec
///     }
///
///     async fn invoke(
///         &self,
///         request: ToolRequest,
///         _ctx: &mut ToolContext<'_>,
///     ) -> Result<ToolResult, ToolError> {
///         Ok(ToolResult::new(ToolResultPart::success(
///             request.call_id,
///             ToolOutput::text("2026-03-22T12:00:00Z"),
///         )))
///     }
/// }
/// ```
#[async_trait]
pub trait Tool: Send + Sync {
    /// Returns the static specification for this tool.
    fn spec(&self) -> &ToolSpec;

    /// Returns the current specification for this tool, if it should be
    /// advertised right now.
    ///
    /// Most tools are static and can rely on the default implementation,
    /// which clones [`spec`](Self::spec). Override this when the description
    /// or input schema should reflect runtime state, or when the tool should
    /// be temporarily hidden from the model.
    fn current_spec(&self) -> Option<ToolSpec> {
        Some(self.spec().clone())
    }

    /// Returns permission requests the executor should evaluate before calling
    /// [`invoke`](Tool::invoke).
    ///
    /// The default implementation returns an empty list (no permissions needed).
    /// Override this to declare filesystem, shell, or custom permission
    /// requirements based on the incoming request.
    ///
    /// # Errors
    ///
    /// Return [`ToolError::InvalidInput`] if the request input is malformed
    /// and permission requests cannot be constructed.
    fn proposed_requests(
        &self,
        _request: &ToolRequest,
    ) -> Result<Vec<Box<dyn PermissionRequest>>, ToolError> {
        Ok(Vec::new())
    }

    /// Executes the tool and returns a result or error.
    ///
    /// # Errors
    ///
    /// Return an appropriate [`ToolError`] variant on failure. Returning
    /// [`ToolError::AuthRequired`] causes the executor to emit a
    /// [`ToolInterruption::AuthRequired`] instead of treating it as a
    /// hard failure.
    async fn invoke(
        &self,
        request: ToolRequest,
        ctx: &mut ToolContext<'_>,
    ) -> Result<ToolResult, ToolError>;
}

/// A name-keyed collection of [`Tool`] implementations.
///
/// The registry owns `Arc`-wrapped tools and is passed to a
/// [`BasicToolExecutor`] (or consumed by [`ToolCapabilityProvider`]) so the
/// agent loop can look up tools by name at execution time.
///
/// # Example
///
/// ```rust
/// use agentkit_tools_core::ToolRegistry;
/// # use agentkit_tools_core::{Tool, ToolContext, ToolError, ToolName, ToolRequest, ToolResult, ToolSpec};
/// # use async_trait::async_trait;
/// # use serde_json::json;
/// # struct NoopTool(ToolSpec);
/// # #[async_trait]
/// # impl Tool for NoopTool {
/// #     fn spec(&self) -> &ToolSpec { &self.0 }
/// #     async fn invoke(&self, _r: ToolRequest, _c: &mut ToolContext<'_>) -> Result<ToolResult, ToolError> { todo!() }
/// # }
///
/// let registry = ToolRegistry::new()
///     .with(NoopTool(ToolSpec::new(
///         ToolName::new("noop"),
///         "Does nothing",
///         json!({"type": "object"}),
///     )));
///
/// assert!(registry.get(&ToolName::new("noop")).is_some());
/// assert_eq!(registry.specs().len(), 1);
/// ```
#[derive(Clone, Default)]
pub struct ToolRegistry {
    tools: BTreeMap<ToolName, Arc<dyn Tool>>,
}

impl ToolRegistry {
    /// Creates an empty registry.
    pub fn new() -> Self {
        Self::default()
    }

    /// Registers a tool by value and returns `&mut self` for imperative chaining.
    pub fn register<T>(&mut self, tool: T) -> &mut Self
    where
        T: Tool + 'static,
    {
        self.tools.insert(tool.spec().name.clone(), Arc::new(tool));
        self
    }

    /// Registers a tool by value and returns `self` for builder-style chaining.
    pub fn with<T>(mut self, tool: T) -> Self
    where
        T: Tool + 'static,
    {
        self.register(tool);
        self
    }

    /// Registers a pre-wrapped `Arc<dyn Tool>`.
    pub fn register_arc(&mut self, tool: Arc<dyn Tool>) -> &mut Self {
        self.tools.insert(tool.spec().name.clone(), tool);
        self
    }

    /// Looks up a tool by name, returning `None` if not registered.
    pub fn get(&self, name: &ToolName) -> Option<Arc<dyn Tool>> {
        self.tools.get(name).cloned()
    }

    /// Returns all registered tools as a `Vec`.
    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
        self.tools.values().cloned().collect()
    }

    /// Merges all tools from another registry into this one, consuming it.
    ///
    /// Supports builder-style chaining:
    ///
    /// ```ignore
    /// let registry = agentkit_tool_fs::registry()
    ///     .merge(agentkit_tool_shell::registry());
    /// ```
    pub fn merge(mut self, other: Self) -> Self {
        self.tools.extend(other.tools);
        self
    }

    /// Returns the [`ToolSpec`] for every registered tool.
    pub fn specs(&self) -> Vec<ToolSpec> {
        self.tools
            .values()
            .filter_map(|tool| tool.current_spec())
            .collect()
    }
}

impl ToolSpec {
    /// Converts this spec into an [`InvocableSpec`] for use with the
    /// capability layer.
    pub fn as_invocable_spec(&self) -> InvocableSpec {
        InvocableSpec::new(
            CapabilityName::new(self.name.0.clone()),
            self.description.clone(),
            self.input_schema.clone(),
        )
        .with_metadata(self.metadata.clone())
    }
}

/// Wraps a [`Tool`] as an [`Invocable`] so it can be surfaced through the
/// agentkit capability layer.
///
/// Created automatically by [`ToolCapabilityProvider::from_registry`]; you
/// rarely need to construct one yourself.
pub struct ToolInvocableAdapter {
    spec: InvocableSpec,
    tool: Arc<dyn Tool>,
    permissions: Arc<dyn PermissionChecker>,
    resources: Arc<dyn ToolResources>,
    next_call_id: AtomicU64,
}

impl ToolInvocableAdapter {
    /// Creates a new adapter that wraps `tool` with the given permission
    /// checker and shared resources.
    pub fn new(
        tool: Arc<dyn Tool>,
        permissions: Arc<dyn PermissionChecker>,
        resources: Arc<dyn ToolResources>,
    ) -> Option<Self> {
        let spec = tool.current_spec()?.as_invocable_spec();
        Some(Self {
            spec,
            tool,
            permissions,
            resources,
            next_call_id: AtomicU64::new(1),
        })
    }
}

#[async_trait]
impl Invocable for ToolInvocableAdapter {
    fn spec(&self) -> &InvocableSpec {
        &self.spec
    }

    async fn invoke(
        &self,
        request: InvocableRequest,
        ctx: &mut CapabilityContext<'_>,
    ) -> Result<InvocableResult, CapabilityError> {
        let tool_request = ToolRequest {
            call_id: ToolCallId::new(format!(
                "tool-call-{}",
                self.next_call_id.fetch_add(1, Ordering::Relaxed)
            )),
            tool_name: self.tool.spec().name.clone(),
            input: request.input,
            session_id: ctx
                .session_id
                .cloned()
                .unwrap_or_else(|| SessionId::new("capability-session")),
            turn_id: ctx
                .turn_id
                .cloned()
                .unwrap_or_else(|| TurnId::new("capability-turn")),
            metadata: request.metadata,
        };

        for permission_request in self
            .tool
            .proposed_requests(&tool_request)
            .map_err(|error| CapabilityError::InvalidInput(error.to_string()))?
        {
            match self.permissions.evaluate(permission_request.as_ref()) {
                PermissionDecision::Allow => {}
                PermissionDecision::Deny(denial) => {
                    return Err(CapabilityError::ExecutionFailed(format!(
                        "tool permission denied: {denial:?}"
                    )));
                }
                PermissionDecision::RequireApproval(req) => {
                    return Err(CapabilityError::Unavailable(format!(
                        "tool invocation requires approval: {}",
                        req.summary
                    )));
                }
            }
        }

        let mut tool_ctx = ToolContext {
            capability: CapabilityContext {
                session_id: ctx.session_id,
                turn_id: ctx.turn_id,
                metadata: ctx.metadata,
            },
            permissions: self.permissions.as_ref(),
            resources: self.resources.as_ref(),
            cancellation: None,
        };

        let result = self
            .tool
            .invoke(tool_request, &mut tool_ctx)
            .await
            .map_err(|error| CapabilityError::ExecutionFailed(error.to_string()))?;

        Ok(InvocableResult {
            output: match result.result.output {
                ToolOutput::Text(text) => InvocableOutput::Text(text),
                ToolOutput::Structured(value) => InvocableOutput::Structured(value),
                ToolOutput::Parts(parts) => InvocableOutput::Items(vec![Item {
                    id: None,
                    kind: ItemKind::Tool,
                    parts,
                    metadata: MetadataMap::new(),
                }]),
                ToolOutput::Files(files) => {
                    let parts = files.into_iter().map(Part::File).collect();
                    InvocableOutput::Items(vec![Item {
                        id: None,
                        kind: ItemKind::Tool,
                        parts,
                        metadata: MetadataMap::new(),
                    }])
                }
            },
            metadata: result.metadata,
        })
    }
}

/// A [`CapabilityProvider`] that exposes every tool in a [`ToolRegistry`]
/// as an [`Invocable`] in the agentkit capability layer.
///
/// This is the bridge between the tool subsystem and the generic capability
/// API that the agent loop consumes.
pub struct ToolCapabilityProvider {
    invocables: Vec<Arc<dyn Invocable>>,
}

impl ToolCapabilityProvider {
    /// Builds a provider from all tools in `registry`, sharing the given
    /// permission checker and resources across every adapter.
    pub fn from_registry(
        registry: &ToolRegistry,
        permissions: Arc<dyn PermissionChecker>,
        resources: Arc<dyn ToolResources>,
    ) -> Self {
        let invocables = registry
            .tools()
            .into_iter()
            .filter_map(|tool| {
                ToolInvocableAdapter::new(tool, permissions.clone(), resources.clone())
                    .map(|adapter| Arc::new(adapter) as Arc<dyn Invocable>)
            })
            .collect();

        Self { invocables }
    }
}

impl CapabilityProvider for ToolCapabilityProvider {
    fn invocables(&self) -> Vec<Arc<dyn Invocable>> {
        self.invocables.clone()
    }

    fn resources(&self) -> Vec<Arc<dyn ResourceProvider>> {
        Vec::new()
    }

    fn prompts(&self) -> Vec<Arc<dyn PromptProvider>> {
        Vec::new()
    }
}

/// The three-way result of a [`ToolExecutor::execute`] call.
///
/// Unlike a simple `Result`, this type distinguishes between a successful
/// completion, an interruption requiring user input (approval or auth), and
/// an outright failure.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum ToolExecutionOutcome {
    /// The tool ran to completion and produced a result.
    Completed(ToolResult),
    /// The tool was interrupted and needs user input before it can continue.
    Interrupted(ToolInterruption),
    /// The tool failed with an error.
    Failed(ToolError),
}

/// Trait for executing tool calls with permission checking and interruption
/// handling.
///
/// The agent loop calls [`execute`](ToolExecutor::execute) for every tool
/// call the model emits. If execution returns
/// [`ToolExecutionOutcome::Interrupted`], the loop collects user input and
/// retries with [`execute_approved`](ToolExecutor::execute_approved).
#[async_trait]
pub trait ToolExecutor: Send + Sync {
    /// Returns the current specification for every available tool.
    fn specs(&self) -> Vec<ToolSpec>;

    /// Looks up the tool, evaluates permissions, and invokes it.
    async fn execute(
        &self,
        request: ToolRequest,
        ctx: &mut ToolContext<'_>,
    ) -> ToolExecutionOutcome;

    /// Looks up the tool, evaluates permissions, and invokes it using an
    /// owned execution context.
    async fn execute_owned(
        &self,
        request: ToolRequest,
        ctx: OwnedToolContext,
    ) -> ToolExecutionOutcome {
        let mut borrowed = ctx.borrowed();
        self.execute(request, &mut borrowed).await
    }

    /// Re-executes a tool call that was previously interrupted for approval.
    ///
    /// The default implementation ignores `approved_request` and delegates
    /// to [`execute`](ToolExecutor::execute). [`BasicToolExecutor`]
    /// overrides this to skip the approval gate for the matching request.
    async fn execute_approved(
        &self,
        request: ToolRequest,
        approved_request: &ApprovalRequest,
        ctx: &mut ToolContext<'_>,
    ) -> ToolExecutionOutcome {
        let _ = approved_request;
        self.execute(request, ctx).await
    }

    /// Re-executes a tool call that was previously interrupted for approval
    /// using an owned execution context.
    async fn execute_approved_owned(
        &self,
        request: ToolRequest,
        approved_request: &ApprovalRequest,
        ctx: OwnedToolContext,
    ) -> ToolExecutionOutcome {
        let mut borrowed = ctx.borrowed();
        self.execute_approved(request, approved_request, &mut borrowed)
            .await
    }
}

/// The default [`ToolExecutor`] that looks up tools in a [`ToolRegistry`],
/// checks permissions via [`Tool::proposed_requests`], and invokes the tool.
///
/// # Example
///
/// ```rust,no_run
/// use agentkit_tools_core::{BasicToolExecutor, ToolRegistry};
///
/// let registry = ToolRegistry::new();
/// let executor = BasicToolExecutor::new(registry);
/// // Pass `executor` to the agent loop.
/// ```
pub struct BasicToolExecutor {
    registry: ToolRegistry,
}

impl BasicToolExecutor {
    /// Creates an executor backed by the given registry.
    pub fn new(registry: ToolRegistry) -> Self {
        Self { registry }
    }

    /// Returns the [`ToolSpec`] for every tool in the underlying registry.
    pub fn specs(&self) -> Vec<ToolSpec> {
        self.registry.specs()
    }

    async fn execute_inner(
        &self,
        request: ToolRequest,
        approved_request_id: Option<&ApprovalId>,
        ctx: &mut ToolContext<'_>,
    ) -> ToolExecutionOutcome {
        let Some(tool) = self.registry.get(&request.tool_name) else {
            return ToolExecutionOutcome::Failed(ToolError::NotFound(request.tool_name));
        };

        match tool.proposed_requests(&request) {
            Ok(requests) => {
                for permission_request in requests {
                    match ctx.permissions.evaluate(permission_request.as_ref()) {
                        PermissionDecision::Allow => {}
                        PermissionDecision::Deny(denial) => {
                            return ToolExecutionOutcome::Failed(ToolError::PermissionDenied(
                                denial,
                            ));
                        }
                        PermissionDecision::RequireApproval(mut req) => {
                            req.call_id = Some(request.call_id.clone());
                            if approved_request_id != Some(&req.id) {
                                return ToolExecutionOutcome::Interrupted(
                                    ToolInterruption::ApprovalRequired(req),
                                );
                            }
                        }
                    }
                }
            }
            Err(error) => return ToolExecutionOutcome::Failed(error),
        }

        match tool.invoke(request, ctx).await {
            Ok(result) => ToolExecutionOutcome::Completed(result),
            Err(ToolError::AuthRequired(request)) => {
                ToolExecutionOutcome::Interrupted(ToolInterruption::AuthRequired(*request))
            }
            Err(error) => ToolExecutionOutcome::Failed(error),
        }
    }
}

#[async_trait]
impl ToolExecutor for BasicToolExecutor {
    fn specs(&self) -> Vec<ToolSpec> {
        self.registry.specs()
    }

    async fn execute(
        &self,
        request: ToolRequest,
        ctx: &mut ToolContext<'_>,
    ) -> ToolExecutionOutcome {
        self.execute_inner(request, None, ctx).await
    }

    async fn execute_approved(
        &self,
        request: ToolRequest,
        approved_request: &ApprovalRequest,
        ctx: &mut ToolContext<'_>,
    ) -> ToolExecutionOutcome {
        self.execute_inner(request, Some(&approved_request.id), ctx)
            .await
    }
}

/// Errors that can occur during tool lookup, permission checking, or execution.
///
/// Returned from [`Tool::invoke`] and also used internally by
/// [`BasicToolExecutor`] to represent lookup and permission failures.
#[derive(Debug, Error, Clone, PartialEq, Serialize, Deserialize)]
pub enum ToolError {
    /// No tool with the given name exists in the registry.
    #[error("tool not found: {0}")]
    NotFound(ToolName),
    /// The input JSON did not match the tool's expected schema.
    #[error("invalid tool input: {0}")]
    InvalidInput(String),
    /// A permission policy denied the operation.
    #[error("tool permission denied: {0:?}")]
    PermissionDenied(PermissionDenial),
    /// The tool ran but encountered a runtime error.
    #[error("tool execution failed: {0}")]
    ExecutionFailed(String),
    /// The tool needs authentication credentials to proceed.
    ///
    /// The executor converts this into [`ToolInterruption::AuthRequired`].
    #[error("tool auth required: {0:?}")]
    AuthRequired(Box<AuthRequest>),
    /// The tool is temporarily unavailable.
    #[error("tool unavailable: {0}")]
    Unavailable(String),
    /// The turn was cancelled while the tool was running.
    #[error("tool execution cancelled")]
    Cancelled,
    /// An unexpected internal error.
    #[error("internal tool error: {0}")]
    Internal(String),
}

impl ToolError {
    /// Convenience constructor for the [`PermissionDenied`](ToolError::PermissionDenied) variant.
    pub fn permission_denied(denial: PermissionDenial) -> Self {
        Self::PermissionDenied(denial)
    }
}

impl From<PermissionDenial> for ToolError {
    fn from(value: PermissionDenial) -> Self {
        Self::permission_denied(value)
    }
}

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

    #[test]
    fn command_policy_can_deny_unknown_executables_without_approval() {
        let policy = CommandPolicy::new()
            .allow_executable("pwd")
            .require_approval_for_unknown(false);
        let request = ShellPermissionRequest {
            executable: "rm".into(),
            argv: vec!["-rf".into(), "/tmp/demo".into()],
            cwd: None,
            env_keys: Vec::new(),
            metadata: MetadataMap::new(),
        };

        match policy.evaluate(&request) {
            PolicyMatch::Deny(denial) => {
                assert_eq!(denial.code, PermissionCode::CommandNotAllowed);
            }
            other => panic!("unexpected policy match: {other:?}"),
        }
    }

    #[test]
    fn path_policy_allows_reads_under_read_only_roots() {
        let policy = PathPolicy::new().read_only_root("/workspace/vendor");
        let request = FileSystemPermissionRequest::Read {
            path: PathBuf::from("/workspace/vendor/lib.rs"),
            metadata: MetadataMap::new(),
        };

        match policy.evaluate(&request) {
            PolicyMatch::NoOpinion | PolicyMatch::Allow => {}
            other => panic!("unexpected policy match: {other:?}"),
        }
    }

    #[test]
    fn path_policy_denies_mutations_under_read_only_roots() {
        let policy = PathPolicy::new().read_only_root("/workspace/vendor");
        let request = FileSystemPermissionRequest::Edit {
            path: PathBuf::from("/workspace/vendor/lib.rs"),
            metadata: MetadataMap::new(),
        };

        match policy.evaluate(&request) {
            PolicyMatch::Deny(denial) => {
                assert_eq!(denial.code, PermissionCode::PathNotAllowed);
                assert!(denial.message.contains("read-only"));
            }
            other => panic!("unexpected policy match: {other:?}"),
        }
    }

    #[test]
    fn path_policy_denies_moves_into_read_only_roots() {
        let policy = PathPolicy::new().read_only_root("/workspace/vendor");
        let request = FileSystemPermissionRequest::Move {
            from: PathBuf::from("/workspace/src/lib.rs"),
            to: PathBuf::from("/workspace/vendor/lib.rs"),
            metadata: MetadataMap::new(),
        };

        match policy.evaluate(&request) {
            PolicyMatch::Deny(denial) => {
                assert_eq!(denial.code, PermissionCode::PathNotAllowed);
                assert!(denial.message.contains("read-only"));
            }
            other => panic!("unexpected policy match: {other:?}"),
        }
    }

    #[derive(Clone)]
    struct HiddenTool {
        spec: ToolSpec,
    }

    impl HiddenTool {
        fn new() -> Self {
            Self {
                spec: ToolSpec {
                    name: ToolName::new("hidden"),
                    description: "hidden".into(),
                    input_schema: json!({"type": "object"}),
                    annotations: ToolAnnotations::default(),
                    metadata: MetadataMap::new(),
                },
            }
        }
    }

    #[async_trait]
    impl Tool for HiddenTool {
        fn spec(&self) -> &ToolSpec {
            &self.spec
        }

        fn current_spec(&self) -> Option<ToolSpec> {
            None
        }

        async fn invoke(
            &self,
            request: ToolRequest,
            _ctx: &mut ToolContext<'_>,
        ) -> Result<ToolResult, ToolError> {
            Ok(ToolResult {
                result: ToolResultPart {
                    call_id: request.call_id,
                    output: ToolOutput::Text("hidden".into()),
                    is_error: false,
                    metadata: MetadataMap::new(),
                },
                duration: None,
                metadata: MetadataMap::new(),
            })
        }
    }

    #[test]
    fn hidden_tools_are_omitted_from_specs_and_capabilities() {
        let registry = ToolRegistry::new().with(HiddenTool::new());

        assert!(registry.specs().is_empty());

        let provider = ToolCapabilityProvider::from_registry(
            &registry,
            Arc::new(AllowAllPermissionChecker),
            Arc::new(()),
        );
        assert!(provider.invocables().is_empty());
    }

    struct AllowAllPermissionChecker;

    impl PermissionChecker for AllowAllPermissionChecker {
        fn evaluate(&self, _request: &dyn PermissionRequest) -> PermissionDecision {
            PermissionDecision::Allow
        }
    }
}