everruns-core 0.10.0

Core agent abstractions for Everruns - agent loop, events, tools, LLM providers
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
//! WebFetch Capability — fetches web content via fetchkit
//!
//! Design decisions:
//! - All metadata (description, schema, llmtxt) comes from fetchkit::ToolBuilder
//! - File download (`save_to_file`) auto-enabled when `session_file_system` is a sibling
//! - Bot-auth (Ed25519 request signing per RFC 9421) enabled via server-wide env vars
//! - Binary content accepted for file downloads, rejected for inline responses
//! - See specs/fetchkit.md for design details
//!
//! Trust boundary (TM-AGENT-013, TM-AGENT-018, TM-API-008):
//! - `risk_level()` returns `High`. Per the capability admin-only tier contract
//!   (`specs/capabilities.md`, `specs/permissions.md`), assigning `web_fetch`
//!   to an agent requires `OrgRole::Admin`; the canonical create/update gate is
//!   `check_high_risk_caps` in `crates/server/src/domains/agents/commands.rs`
//!   (invoked from `CreateAgent::execute`, `UpdateAgent::execute`, and
//!   `UpsertAgent::execute`). The sibling `require_admin_for_high_risk` helper
//!   in `crates/server/src/api/agents.rs` enforces the same contract on
//!   agent-import / copy paths. Existing member-owned agents that already had
//!   `web_fetch` before the elevation continue to run (gate is creation/update
//!   only, not runtime). New assignments by non-admin members are rejected
//!   with HTTP 403.
//! - Rationale: outbound HTTP from an agent doubles as both a data-exfiltration
//!   channel (TM-AGENT-013) and an SSRF vector if egress is not strictly
//!   isolated (TM-API-008 mitigates loopback/RFC1918 via `DnsPolicy::block_private_ips()`,
//!   but no general outbound URL allowlist exists yet — TM-AGENT-018 OPEN).
//!   Until a per-org outbound policy lands, admin assignment is the explicit
//!   trust gate.

use super::{Capability, CapabilityStatus, RiskLevel};
use crate::tool_types::ToolHints;
use crate::tools::{Tool, ToolExecutionResult};
use crate::traits::{SessionFileSystem, ToolContext};
use crate::typed_id::SessionId;
use async_trait::async_trait;
use base64::Engine as _;
use fetchkit::file_saver::{FileSaveError, FileSaver, SaveResult};
use fetchkit::{BotAuthConfig, FetchError, FetchRequest};
use serde_json::Value;
use std::sync::Arc;

/// Ed25519 public key JWK derived from a signing key seed.
///
/// Used to register the public key in the HTTP message signatures directory
/// so target servers can verify request signatures.
#[derive(Debug, Clone)]
pub struct BotAuthPublicKey {
    /// JWK Thumbprint (RFC 7638) — matches `BotAuthConfig::keyid()`
    pub key_id: String,
    /// Full JWK object: `{"kty":"OKP","crv":"Ed25519","x":"<base64url>"}`
    pub jwk: serde_json::Value,
}

/// Derive the Ed25519 public key JWK and key ID from a base64url-encoded seed.
///
/// Returns `None` if the seed is invalid. The key_id is the JWK Thumbprint
/// (base64url-encoded SHA-256 of the canonical JWK representation), matching
/// the keyid that fetchkit's `BotAuthConfig` puts in `Signature-Input`.
pub fn derive_bot_auth_public_key(base64_seed: &str) -> Option<BotAuthPublicKey> {
    use base64::Engine as _;
    use ed25519_dalek::SigningKey;
    use sha2::{Digest, Sha256};

    // Decode seed (base64url, no padding)
    let seed_bytes = base64::engine::general_purpose::URL_SAFE_NO_PAD
        .decode(base64_seed)
        .ok()?;
    if seed_bytes.len() != 32 {
        return None;
    }
    let mut seed = [0u8; 32];
    seed.copy_from_slice(&seed_bytes);

    // Derive public key
    let signing_key = SigningKey::from_bytes(&seed);
    let public_key = signing_key.verifying_key();
    let public_key_b64 =
        base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(public_key.as_bytes());

    // Build canonical JWK (RFC 7638 member ordering for OKP: crv, kty, x)
    let canonical_jwk = format!(
        r#"{{"crv":"Ed25519","kty":"OKP","x":"{}"}}"#,
        public_key_b64
    );

    // JWK Thumbprint = base64url(SHA-256(canonical_jwk))
    let thumbprint = Sha256::digest(canonical_jwk.as_bytes());
    let key_id = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(thumbprint);

    let jwk = serde_json::json!({
        "kty": "OKP",
        "crv": "Ed25519",
        "x": public_key_b64,
    });

    Some(BotAuthPublicKey { key_id, jwk })
}

/// WebFetch capability — fetches web content, optionally saves to session filesystem.
///
/// File download is enabled via per-capability config: `{"enable_file_download": true}`.
/// Bot-auth signing is server-wide: set `BOT_AUTH_SIGNING_KEY_SEED` env var.
/// Description, schema, and system prompt all come from fetchkit's ToolBuilder,
/// adapting to whether file download is on.
pub struct WebFetchCapability {
    /// Server-wide bot-auth config (from env vars). When set, all outbound
    /// HTTP requests are signed with Ed25519 per RFC 9421.
    bot_auth: Option<BotAuthConfig>,
}

impl WebFetchCapability {
    /// Create with optional server-wide bot-auth signing config.
    pub fn new(bot_auth: Option<BotAuthConfig>) -> Self {
        Self { bot_auth }
    }

    /// Create from environment variables.
    ///
    /// - `BOT_AUTH_SIGNING_KEY_SEED`: base64url-encoded 32-byte Ed25519 seed (required to enable)
    /// - `BOT_AUTH_AGENT_FQDN`: FQDN for Signature-Agent header (optional)
    /// - `BOT_AUTH_VALIDITY_SECS`: signature validity in seconds (optional, default 300)
    pub fn from_env() -> Self {
        Self {
            bot_auth: bot_auth_config_from_env(),
        }
    }
}

/// Read bot-auth config from environment variables.
fn bot_auth_config_from_env() -> Option<BotAuthConfig> {
    let seed = std::env::var("BOT_AUTH_SIGNING_KEY_SEED").ok()?;

    let mut config = match BotAuthConfig::from_base64_seed(&seed) {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!(error = %e, "invalid BOT_AUTH_SIGNING_KEY_SEED, bot-auth disabled");
            return None;
        }
    };

    if let Ok(fqdn) = std::env::var("BOT_AUTH_AGENT_FQDN") {
        config = config.with_agent_fqdn(&fqdn);
    }

    if let Ok(secs) = std::env::var("BOT_AUTH_VALIDITY_SECS")
        && let Ok(secs) = secs.parse::<u64>()
    {
        config = config.with_validity_secs(secs);
    }

    tracing::info!("bot-auth request signing enabled");
    Some(config)
}

#[async_trait]
impl Capability for WebFetchCapability {
    fn id(&self) -> &str {
        "web_fetch"
    }

    fn name(&self) -> &str {
        "Web Fetch"
    }

    fn description(&self) -> &str {
        fetchkit::TOOL_DESCRIPTION
    }

    fn status(&self) -> CapabilityStatus {
        CapabilityStatus::Available
    }

    fn risk_level(&self) -> RiskLevel {
        RiskLevel::High
    }

    fn icon(&self) -> Option<&str> {
        Some("globe")
    }

    fn category(&self) -> Option<&str> {
        Some("Network")
    }

    fn system_prompt_addition(&self) -> Option<&str> {
        None
    }

    fn system_prompt_preview(&self) -> Option<String> {
        // Preview with all features for UI display
        Some(
            fetchkit::Tool::builder()
                .enable_save_to_file(true)
                .build()
                .llmtxt(),
        )
    }

    async fn system_prompt_contribution_with_config(
        &self,
        _ctx: &super::SystemPromptContext,
        config: &serde_json::Value,
    ) -> Option<String> {
        // Behavioral note only — parameter details live in the tool's JSON
        // schema. The full fetchkit llmtxt remains available via
        // `system_prompt_preview()` for UI display but is not injected on
        // every turn. The `save_to_file` mention is gated on the same
        // `enable_file_download` flag the tool itself uses, so the prompt
        // matches the actually-available capability.
        let enable_file_download = config
            .get("enable_file_download")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        let body = if enable_file_download {
            "`web_fetch` fetches one URL (GET/HEAD); it is not a search engine. For large or binary responses, pass `save_to_file` to write the body to the workspace instead of inlining it."
        } else {
            "`web_fetch` fetches one URL (GET/HEAD); it is not a search engine."
        };
        Some(format!(
            "<capability id=\"{}\">\n{}\n</capability>",
            self.id(),
            body
        ))
    }

    fn tools(&self) -> Vec<Box<dyn Tool>> {
        vec![Box::new(WebFetchTool::new(false, self.bot_auth.clone()))]
    }

    fn tools_with_config(&self, config: &serde_json::Value) -> Vec<Box<dyn Tool>> {
        let enable_file_download = config
            .get("enable_file_download")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);
        vec![Box::new(WebFetchTool::new(
            enable_file_download,
            self.bot_auth.clone(),
        ))]
    }
}

// ============================================================================
// SessionFileSaver — bridges fetchkit::FileSaver to SessionFileSystem
// ============================================================================

/// Adapter that routes fetchkit file saves through the session virtual filesystem.
///
/// Binary content is encoded as base64; text content is stored as-is.
struct SessionFileSaver {
    file_store: Arc<dyn SessionFileSystem>,
    session_id: SessionId,
}

#[async_trait]
impl FileSaver for SessionFileSaver {
    async fn save(&self, path: &str, bytes: &[u8]) -> Result<SaveResult, FileSaveError> {
        let (content, encoding) = match std::str::from_utf8(bytes) {
            Ok(text) => (text.to_string(), "text"),
            Err(_) => {
                let encoded = base64::engine::general_purpose::STANDARD.encode(bytes);
                (encoded, "base64")
            }
        };

        let file = self
            .file_store
            .write_file(self.session_id, path, &content, encoding)
            .await
            .map_err(|e| FileSaveError::Other(e.to_string()))?;

        Ok(SaveResult {
            path: file.path,
            bytes_written: bytes.len() as u64,
        })
    }
}

// ============================================================================
// Tool: web_fetch
// ============================================================================

/// Tool that fetches content from a URL using fetchkit
///
/// THREAT[TM-API-008]: SSRF protection via fetchkit DnsPolicy
/// Mitigation: Default FetchOptions uses DnsPolicy::block_private_ips(),
/// which blocks loopback, RFC1918, link-local (cloud metadata), and other
/// reserved IP ranges via resolve-then-check with DNS pinning.
///
/// File download: when `save_to_file` is provided, content is saved through
/// the session filesystem (SessionFileSystem) via the SessionFileSaver adapter.
pub struct WebFetchTool {
    fetchkit_tool: fetchkit::Tool,
    enable_save_to_file: bool,
    /// Cached description from ToolBuilder (owned copy of fetchkit's &str for our Tool trait)
    description: String,
    /// Host-wide system allowlist ("green list"). fetchkit owns its own HTTP
    /// client and does not (yet) route through `EgressService`, so the
    /// deployment-wide allowlist is enforced here as a pre-flight check that
    /// returns a clear system-policy error. `None` = no global enforcement.
    /// See `crate::system_allowlist` and `specs/system-allowlist.md`.
    system_allowlist: Option<Arc<crate::system_allowlist::SystemAllowlist>>,
}

impl WebFetchTool {
    /// Create a new WebFetchTool with file download and optional bot-auth signing.
    pub fn new(enable_save_to_file: bool, bot_auth: Option<BotAuthConfig>) -> Self {
        let mut builder = fetchkit::Tool::builder().enable_save_to_file(enable_save_to_file);
        if let Some(config) = bot_auth {
            builder = builder.bot_auth(config);
        }
        let fetchkit_tool = builder.build();
        let description = fetchkit_tool.description().to_string();
        Self {
            fetchkit_tool,
            enable_save_to_file,
            description,
            system_allowlist: crate::system_allowlist::SystemAllowlist::from_env(),
        }
    }

    /// Reject URLs not covered by the active system allowlist with an explicit
    /// system-policy error. Returns `None` when the allowlist is disabled or the
    /// URL is permitted.
    fn system_policy_block(&self, url: &str) -> Option<ToolExecutionResult> {
        match &self.system_allowlist {
            Some(allowlist) if !allowlist.is_url_allowed(url) => {
                Some(ToolExecutionResult::tool_error(format!(
                    "Endpoint blocked by system policy: {url} is not on the deployment's \
                     system allowlist of permitted public resources."
                )))
            }
            _ => None,
        }
    }
}

impl Default for WebFetchTool {
    fn default() -> Self {
        Self::new(false, None)
    }
}

impl WebFetchTool {
    /// Build a FetchRequest from JSON arguments.
    fn parse_request(arguments: &Value) -> Result<FetchRequest, ToolExecutionResult> {
        let url = match arguments.get("url").and_then(|v| v.as_str()) {
            Some(u) => u.to_string(),
            None => {
                return Err(ToolExecutionResult::tool_error(
                    "Missing required parameter: url",
                ));
            }
        };

        let method = arguments
            .get("method")
            .and_then(|v| v.as_str())
            .map(|s| match s.to_uppercase().as_str() {
                "GET" => Some(fetchkit::HttpMethod::Get),
                "HEAD" => Some(fetchkit::HttpMethod::Head),
                _ => None,
            })
            .unwrap_or(Some(fetchkit::HttpMethod::Get));

        let method = match method {
            Some(m) => m,
            None => {
                return Err(ToolExecutionResult::tool_error(
                    "Invalid method: must be GET or HEAD",
                ));
            }
        };

        let as_markdown = arguments
            .get("as_markdown")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let as_text = arguments
            .get("as_text")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        let save_to_file = arguments
            .get("save_to_file")
            .and_then(|v| v.as_str())
            .map(|s| s.to_string());

        Ok(FetchRequest {
            url,
            method: Some(method),
            as_markdown: if as_markdown { Some(true) } else { None },
            as_text: if as_text { Some(true) } else { None },
            save_to_file,
            content_focus: None,
            if_none_match: None,
            if_modified_since: None,
        })
    }

    /// Map a fetchkit error to a ToolExecutionResult.
    fn map_error(e: FetchError) -> ToolExecutionResult {
        let error_message = match e {
            FetchError::MissingUrl => "Missing required parameter: url".to_string(),
            FetchError::InvalidUrlScheme => {
                "Invalid URL: must start with http:// or https://".to_string()
            }
            FetchError::InvalidMethod => "Invalid method: must be GET or HEAD".to_string(),
            FetchError::BlockedUrl => "URL is blocked by policy".to_string(),
            FetchError::ClientBuildError(_) => "Failed to create HTTP client".to_string(),
            FetchError::FirstByteTimeout => {
                "Request timed out: server did not respond within 1 second".to_string()
            }
            FetchError::ConnectError(_) => "Failed to connect to server".to_string(),
            FetchError::RequestError(msg) => format!("Request failed: {msg}"),
            FetchError::FetcherError(msg) => format!("Fetch error: {msg}"),
            FetchError::SaveError(msg) => format!("Failed to save file: {msg}"),
            FetchError::SaverNotAvailable => "File saving not available".to_string(),
        };
        ToolExecutionResult::tool_error(error_message)
    }
}

#[async_trait]
impl Tool for WebFetchTool {
    fn name(&self) -> &str {
        "web_fetch"
    }

    fn display_name(&self) -> Option<&str> {
        Some("Web Fetch")
    }

    fn description(&self) -> &str {
        &self.description
    }

    fn parameters_schema(&self) -> Value {
        self.fetchkit_tool.input_schema()
    }

    fn requires_context(&self) -> bool {
        // Needed for save_to_file (SessionFileSystem access)
        true
    }

    fn hints(&self) -> ToolHints {
        ToolHints::default()
            .with_readonly(true)
            .with_open_world(true)
            .with_long_running(true)
    }

    async fn execute(&self, arguments: Value) -> ToolExecutionResult {
        // Without context, save_to_file is not supported — execute normally
        let request = match Self::parse_request(&arguments) {
            Ok(mut req) => {
                req.save_to_file = None; // Cannot save without context
                req
            }
            Err(e) => return e,
        };

        // Host-wide system allowlist applies even without a session context.
        if let Some(blocked) = self.system_policy_block(&request.url) {
            return blocked;
        }

        match self.fetchkit_tool.execute(request).await {
            Ok(response) => {
                ToolExecutionResult::success(serde_json::to_value(&response).unwrap_or_else(
                    |_| serde_json::json!({"error": "Failed to serialize response"}),
                ))
            }
            Err(e) => Self::map_error(e),
        }
    }

    async fn execute_with_context(
        &self,
        arguments: Value,
        context: &ToolContext,
    ) -> ToolExecutionResult {
        let request = match Self::parse_request(&arguments) {
            Ok(req) => req,
            Err(e) => return e,
        };

        if request.save_to_file.is_some() && !self.enable_save_to_file {
            return ToolExecutionResult::tool_error(
                "File download is disabled for this capability",
            );
        }

        // Host-wide system allowlist (green list). Enforced before the
        // per-session access list so the operator-level policy yields a clear,
        // distinct error.
        if let Some(blocked) = self.system_policy_block(&request.url) {
            return blocked;
        }

        // THREAT[TM-AGENT-018]: Enforce network access list
        if let Some(ref acl) = context.network_access
            && !acl.is_url_allowed(&request.url)
        {
            return ToolExecutionResult::tool_error(format!(
                "URL blocked by network access policy: {}",
                request.url
            ));
        }

        // If no save_to_file, use the simple path (no saver needed)
        if request.save_to_file.is_none() {
            return match self.fetchkit_tool.execute(request).await {
                Ok(response) => {
                    ToolExecutionResult::success(serde_json::to_value(&response).unwrap_or_else(
                        |_| serde_json::json!({"error": "Failed to serialize response"}),
                    ))
                }
                Err(e) => Self::map_error(e),
            };
        }

        // save_to_file requested — need SessionFileSystem
        let file_store = match &context.file_store {
            Some(store) => store.clone(),
            None => {
                return ToolExecutionResult::tool_error(
                    "File system not available in this context",
                );
            }
        };

        let saver = SessionFileSaver {
            file_store,
            session_id: context.session_id,
        };

        match self
            .fetchkit_tool
            .execute_with_saver(request, Some(&saver))
            .await
        {
            Ok(response) => {
                ToolExecutionResult::success(serde_json::to_value(&response).unwrap_or_else(
                    |_| serde_json::json!({"error": "Failed to serialize response"}),
                ))
            }
            Err(e) => Self::map_error(e),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::typed_id::SessionId;
    use wiremock::matchers::{method, path};
    use wiremock::{Mock, MockServer, ResponseTemplate};

    /// Create a WebFetchTool with permissive DNS policy for wiremock tests
    /// (wiremock binds to 127.0.0.1 which is blocked by default).
    fn tool_for_wiremock() -> WebFetchTool {
        let fetchkit_tool = fetchkit::Tool::builder()
            .enable_save_to_file(true)
            .block_private_ips(false)
            .build();
        let description = fetchkit_tool.description().to_string();
        WebFetchTool {
            fetchkit_tool,
            enable_save_to_file: true,
            description,
            system_allowlist: None,
        }
    }

    #[tokio::test]
    async fn system_allowlist_blocks_with_clear_system_policy_error() {
        use crate::system_allowlist::SystemAllowlist;

        let mut tool = tool_for_wiremock();
        tool.system_allowlist = Some(
            SystemAllowlist::from_toml("[groups.test]\nallowed = [\"allowed.example.com\"]\n")
                .map(Arc::new)
                .unwrap(),
        );

        let result = tool
            .execute(serde_json::json!({ "url": "https://blocked.example.com/path" }))
            .await;

        let message = match result {
            ToolExecutionResult::ToolError(message) => message,
            other => panic!("blocked URL should be a tool error, got: {other:?}"),
        };
        assert!(
            message.contains("blocked by system policy"),
            "error should name the system policy, got: {message}"
        );
        assert!(
            message.contains("blocked.example.com"),
            "error should include the URL, got: {message}"
        );
    }

    #[test]
    fn test_derive_bot_auth_public_key() {
        // 32 bytes of 'A' (0x41), base64url-encoded
        let seed = "QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUE";
        let pk = super::derive_bot_auth_public_key(seed).unwrap();

        // JWK has correct structure
        assert_eq!(pk.jwk["kty"], "OKP");
        assert_eq!(pk.jwk["crv"], "Ed25519");
        assert!(pk.jwk["x"].is_string());

        // key_id matches fetchkit's BotAuthConfig::keyid()
        let fetchkit_config = fetchkit::BotAuthConfig::from_base64_seed(seed).unwrap();
        assert_eq!(pk.key_id, fetchkit_config.keyid());
    }

    #[test]
    fn test_derive_bot_auth_public_key_invalid_seed() {
        assert!(super::derive_bot_auth_public_key("tooshort").is_none());
        assert!(super::derive_bot_auth_public_key("!!!invalid!!!").is_none());
    }

    #[test]
    fn test_web_fetch_tool_parameters() {
        let tool = WebFetchTool::default();
        let schema = tool.parameters_schema();

        assert_eq!(schema["type"], "object");
        assert!(schema["properties"]["url"].is_object());
        assert!(schema["properties"]["method"].is_object());
        assert!(schema["properties"]["as_markdown"].is_object());
        assert!(schema["properties"]["as_text"].is_object());
        assert_eq!(schema["required"], serde_json::json!(["url"]));
    }

    #[test]
    fn test_web_fetch_capability_metadata() {
        let cap = WebFetchCapability::new(None);

        assert_eq!(cap.id(), "web_fetch");
        assert_eq!(cap.name(), "Web Fetch");
        assert_eq!(cap.status(), CapabilityStatus::Available);
        assert_eq!(cap.risk_level(), RiskLevel::High);
        assert_eq!(cap.icon(), Some("globe"));
        assert_eq!(cap.category(), Some("Network"));
        // System prompt comes from fetchkit ToolBuilder via system_prompt_contribution_with_config
        assert!(cap.system_prompt_addition().is_none());
        // Preview shows full features for UI
        let preview = cap.system_prompt_preview().unwrap();
        assert!(preview.contains("web_fetch"));
    }

    #[test]
    fn test_web_fetch_capability_has_tool() {
        let cap = WebFetchCapability::new(None);
        let tools = cap.tools();

        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0].name(), "web_fetch");
    }

    #[tokio::test]
    async fn test_web_fetch_missing_url() {
        let tool = WebFetchTool::default();
        let result = tool.execute(serde_json::json!({})).await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(msg.contains("url"));
        } else {
            panic!("Expected tool error for missing URL");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_invalid_url() {
        let tool = WebFetchTool::default();
        let result = tool
            .execute(serde_json::json!({"url": "not-a-valid-url"}))
            .await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(msg.contains("Invalid URL"));
        } else {
            panic!("Expected tool error for invalid URL");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_invalid_method() {
        let tool = WebFetchTool::default();
        let result = tool
            .execute(serde_json::json!({"url": "https://example.com", "method": "POST"}))
            .await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(msg.contains("Invalid method"));
        } else {
            panic!("Expected tool error for invalid method");
        }
    }

    // Integration tests using wiremock
    #[tokio::test]
    async fn test_web_fetch_real_request() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("<html><body><p>Herman Melville - Moby Dick</p></body></html>")
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri()),
                "as_text": true
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert!(
                value["content"]
                    .as_str()
                    .unwrap()
                    .contains("Herman Melville")
            );
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_head_request() {
        let mock_server = MockServer::start().await;

        Mock::given(method("HEAD"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/html")
                    .insert_header("content-length", "100"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri()),
                "method": "HEAD"
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert_eq!(value["method"], "HEAD");
            // HEAD requests should not have content
            assert!(value.get("content").is_none() || value["content"].is_null());
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_response_includes_size() {
        let mock_server = MockServer::start().await;
        let body = "<html><body>Test content</body></html>";

        Mock::given(method("GET"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(body)
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            // Size should be present and > 0
            assert!(value["size"].as_u64().unwrap() > 0);
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_binary_returns_metadata() {
        let mock_server = MockServer::start().await;

        // Simulate a PNG image response
        Mock::given(method("GET"))
            .and(path("/image/png"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_bytes(vec![0x89, 0x50, 0x4E, 0x47]) // PNG magic bytes
                    .insert_header("content-type", "image/png")
                    .insert_header("content-length", "4"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/image/png", mock_server.uri())
            }))
            .await;

        // Binary content should return success with error message and metadata
        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert!(
                value["content_type"]
                    .as_str()
                    .unwrap()
                    .contains("image/png")
            );
            assert!(
                value["error"].as_str().unwrap().contains("Binary content")
                    || value["error"].as_str().unwrap().contains("binary")
            );
            // Should have size metadata if available
            assert!(value.get("size").is_some() || value["size"].is_null());
        } else {
            panic!("Expected success response with metadata for binary content");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_truncated_field() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("<html><body>Short content</body></html>")
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        // Normal response should have truncated: false
        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            // truncated should be false or null for non-truncated content
            assert!(
                value["truncated"].is_null()
                    || value["truncated"] == false
                    || value.get("truncated").is_none()
            );
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_timeout_unreachable_host() {
        // Use TEST-NET-1 (192.0.2.0/24, RFC 5737) which is non-routable and will timeout.
        // Note: fetchkit v0.1.2 blocks RFC1918 private IPs, but TEST-NET ranges
        // are also blocked by DNS policy. Use a wiremock server with a delay instead.
        let mock_server = MockServer::start().await;

        // Mount a mock that takes 5 seconds to respond (exceeds 1s first-byte timeout)
        Mock::given(method("GET"))
            .and(path("/slow"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("slow response")
                    .set_delay(std::time::Duration::from_secs(5)),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/slow", mock_server.uri())
            }))
            .await;

        match result {
            ToolExecutionResult::ToolError(msg) => {
                assert!(
                    msg.contains("timed out") || msg.contains("connect") || msg.contains("failed"),
                    "Expected timeout or connection error, got: {}",
                    msg
                );
            }
            _ => {
                // Some environments may handle timeouts differently
            }
        }
    }

    #[tokio::test]
    async fn test_web_fetch_response_has_all_expected_fields() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("<html><body>Test</body></html>")
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            // Verify all expected fields are present
            assert!(value.get("url").is_some(), "Missing 'url' field");
            assert!(
                value.get("status_code").is_some(),
                "Missing 'status_code' field"
            );
            assert!(
                value.get("content_type").is_some(),
                "Missing 'content_type' field"
            );
            assert!(value.get("size").is_some(), "Missing 'size' field");
            // format, content may or may not be present depending on response type
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_head_response_structure() {
        let mock_server = MockServer::start().await;

        Mock::given(method("HEAD"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/html")
                    .insert_header("content-length", "100"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri()),
                "method": "HEAD"
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            // HEAD response should have metadata but not content
            assert!(value.get("url").is_some());
            assert!(value.get("status_code").is_some());
            assert!(value.get("method").is_some());
            assert_eq!(value["method"], "HEAD");
            // Should NOT have content for HEAD
            assert!(value.get("content").is_none() || value["content"].is_null());
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_html_returns_markdown_by_default() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(
                        "<!DOCTYPE html><html><body><h1>Title</h1><p>Content</p></body></html>",
                    )
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        // No as_markdown needed - fetchkit returns markdown by default for HTML
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            // Content should be present
            let content = value["content"].as_str().unwrap();
            assert!(content.contains("Title") || content.contains("Content"));
            // Format should be "markdown" or "raw" depending on fetchkit's detection
            let format = value["format"].as_str().unwrap_or("raw");
            assert!(format == "markdown" || format == "raw");
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_as_text_strips_html() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("<!DOCTYPE html><html><body><b>Test</b> content</body></html>")
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/html", mock_server.uri()),
                "as_text": true
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            // Content should be present
            let content = value["content"].as_str().unwrap();
            assert!(content.contains("Test") || content.contains("content"));
            // Format should be "text" or "raw" depending on fetchkit's detection
            let format = value["format"].as_str().unwrap_or("raw");
            assert!(format == "text" || format == "raw");
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_raw_format_for_non_html() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/json"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("{\"key\": \"value\"}")
                    .insert_header("content-type", "application/json"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/json", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            // JSON content should return "raw" format
            assert_eq!(value["format"], "raw");
        } else {
            panic!("Expected successful response");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_404_returns_success_with_status() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/status/404"))
            .respond_with(ResponseTemplate::new(404).set_body_string("Not Found"))
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/status/404", mock_server.uri())
            }))
            .await;

        // 404 should still be a "success" from tool perspective - it got a response
        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 404);
        } else {
            panic!("Expected successful response even for 404");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_500_returns_success_with_status() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/status/500"))
            .respond_with(ResponseTemplate::new(500).set_body_string("Internal Server Error"))
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/status/500", mock_server.uri())
            }))
            .await;

        // 500 should still be a "success" from tool perspective
        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 500);
        } else {
            panic!("Expected successful response even for 500");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_dns_failure() {
        let tool = WebFetchTool::default();
        let result = tool
            .execute(serde_json::json!({
                "url": "https://this-domain-definitely-does-not-exist-12345.com/test"
            }))
            .await;

        // DNS failure returns a tool error. With fetchkit v0.1.2's resolve-then-check,
        // DNS resolution failures may surface as "blocked by policy" since the hostname
        // cannot be validated against the DNS policy.
        if let ToolExecutionResult::ToolError(msg) = result {
            let msg_lower = msg.to_lowercase();
            assert!(
                msg_lower.contains("failed")
                    || msg_lower.contains("error")
                    || msg_lower.contains("timed out")
                    || msg_lower.contains("connect")
                    || msg_lower.contains("blocked"),
                "Expected error message about failure, got: {}",
                msg
            );
        } else {
            // Some environments might timeout instead of DNS failure
        }
    }

    #[tokio::test]
    async fn test_web_fetch_rejects_ftp_url() {
        let tool = WebFetchTool::default();
        let result = tool
            .execute(serde_json::json!({
                "url": "ftp://example.com/file.txt"
            }))
            .await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(msg.contains("Invalid URL"));
        } else {
            panic!("Expected tool error for FTP URL");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_rejects_file_url() {
        let tool = WebFetchTool::default();
        let result = tool
            .execute(serde_json::json!({
                "url": "file:///etc/passwd"
            }))
            .await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(msg.contains("Invalid URL"));
        } else {
            panic!("Expected tool error for file:// URL");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_accepts_http_url() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/get"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("{\"url\": \"http://localhost/get\"}")
                    .insert_header("content-type", "application/json"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        // Note: mock_server.uri() returns http:// URL
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/get", mock_server.uri())
            }))
            .await;

        // HTTP (not HTTPS) should work
        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
        } else {
            panic!("Expected successful response for HTTP URL");
        }
    }

    #[tokio::test]
    async fn test_web_fetch_filters_excessive_newlines() {
        let mock_server = MockServer::start().await;

        // Response with many consecutive newlines
        Mock::given(method("GET"))
            .and(path("/newlines"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("line1\n\n\n\n\n\n\n\nline2")
                    .insert_header("content-type", "text/plain"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/newlines", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            let content = value["content"].as_str().unwrap();
            // Should have at most 2 consecutive newlines
            assert!(
                !content.contains("\n\n\n"),
                "Content should not have more than 2 consecutive newlines"
            );
        } else {
            panic!("Expected successful response");
        }
    }

    // ========================================================================
    // SSRF security tests (TM-API-008 through TM-API-012)
    //
    // fetchkit v0.1.2 blocks private/internal IPs by default via
    // resolve-then-check with DNS pinning. These tests verify that
    // private/internal URLs are blocked by policy.
    //
    // Run with: cargo test -p everruns-core --lib -- web_fetch::tests::test_ssrf
    // ========================================================================

    // Helper: asserts that a private/internal URL IS blocked by fetchkit's
    // DNS policy (SSRF protection). The tool should return a ToolError
    // containing "blocked".
    async fn assert_blocked_by_policy(url: &str) {
        let tool = WebFetchTool::default();
        let result = tool.execute(serde_json::json!({"url": url})).await;
        assert!(
            matches!(&result, ToolExecutionResult::ToolError(msg) if msg.contains("blocked")),
            "Expected URL {url} to be blocked by policy, got: {:?}",
            result
        );
    }

    /// THREAT[TM-API-009]: Cloud metadata endpoint blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_cloud_metadata_blocked() {
        assert_blocked_by_policy("http://169.254.169.254/latest/meta-data/").await;
    }

    /// THREAT[TM-API-008]: Localhost blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_localhost_blocked() {
        assert_blocked_by_policy("http://127.0.0.1:1/").await;
    }

    /// THREAT[TM-API-008]: RFC1918 10.x.x.x blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_private_10_blocked() {
        assert_blocked_by_policy("http://10.0.0.1:1/").await;
    }

    /// THREAT[TM-API-008]: RFC1918 172.16.x.x blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_private_172_blocked() {
        assert_blocked_by_policy("http://172.16.0.1:1/").await;
    }

    /// THREAT[TM-API-008]: RFC1918 192.168.x.x blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_private_192_blocked() {
        assert_blocked_by_policy("http://192.168.0.1:1/").await;
    }

    /// THREAT[TM-API-008]: IPv6 localhost blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_ipv6_localhost_blocked() {
        assert_blocked_by_policy("http://[::1]:1/").await;
    }

    /// THREAT[TM-API-008]: 0.0.0.0 blocked by fetchkit DNS policy.
    #[tokio::test]
    async fn test_ssrf_unspecified_blocked() {
        assert_blocked_by_policy("http://0.0.0.0:1/").await;
    }

    /// Verify file://, ftp://, gopher:// schemes are blocked (existing protection).
    #[tokio::test]
    async fn test_ssrf_non_http_schemes_blocked() {
        let tool = WebFetchTool::default();

        for (scheme, url) in [
            ("file://", "file:///etc/passwd"),
            ("ftp://", "ftp://internal-server/data"),
            ("gopher://", "gopher://internal-server/"),
        ] {
            let result = tool.execute(serde_json::json!({"url": url})).await;
            assert!(
                matches!(&result, ToolExecutionResult::ToolError(msg) if msg.contains("Invalid URL")),
                "{scheme} should be rejected"
            );
        }
    }

    // ========================================================================
    // Integration tests using wiremock (no network access needed)
    // ========================================================================

    #[tokio::test]
    async fn test_fetch_html_page() {
        let mock_server = MockServer::start().await;
        let html = r#"<html><head><title>Wasmtime Docs</title></head>
        <body><h1>Wasmtime</h1><p>A fast and secure runtime for WebAssembly.</p>
        <p>Wasmtime is a standalone runtime for WebAssembly that can be used
        as a CLI tool or embedded into other systems.</p></body></html>"#;

        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(html)
                    .insert_header("content-type", "text/html; charset=utf-8"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            let content = value["content"].as_str().unwrap();
            assert!(
                content.contains("Wasmtime") || content.contains("wasmtime"),
                "Content should mention Wasmtime"
            );
            assert!(
                value["size"].as_u64().unwrap() > 100,
                "Page should have substantial content"
            );
        } else {
            panic!("Expected successful response, got: {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_fetch_html_as_text() {
        let mock_server = MockServer::start().await;
        let html = r#"<html><head><title>Wasmtime Docs</title></head>
        <body><h1>Wasmtime</h1><p>A fast and secure runtime.</p></body></html>"#;

        Mock::given(method("GET"))
            .and(path("/"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(html)
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/", mock_server.uri()),
                "as_text": true
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            let content = value["content"].as_str().unwrap();
            assert!(
                content.contains("Wasmtime") || content.contains("wasmtime"),
                "Text should contain Wasmtime reference"
            );
            let format = value["format"].as_str().unwrap_or("raw");
            assert!(
                format == "text" || format == "raw",
                "Format should be text or raw, got: {}",
                format
            );
        } else {
            panic!(
                "Expected successful response with text conversion, got: {:?}",
                result
            );
        }
    }

    #[tokio::test]
    async fn test_fetch_head_request() {
        let mock_server = MockServer::start().await;

        Mock::given(method("HEAD"))
            .and(path("/"))
            .respond_with(
                ResponseTemplate::new(200)
                    .insert_header("content-type", "text/html; charset=utf-8")
                    .insert_header("content-length", "5000"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/", mock_server.uri()),
                "method": "HEAD"
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert_eq!(value["method"], "HEAD");
            assert!(
                value["content"].is_null()
                    || value["content"].as_str().is_none_or(|s| s.is_empty()),
                "HEAD request should not return content body"
            );
            assert!(value["content_type"].as_str().is_some());
        } else {
            panic!("Expected successful HEAD response, got: {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_fetch_subpage() {
        let mock_server = MockServer::start().await;
        // Build a page with >500 chars of content
        let body = format!(
            "<html><body><h1>Introduction</h1><p>{}</p></body></html>",
            "WebAssembly is a portable binary instruction format. ".repeat(20)
        );

        Mock::given(method("GET"))
            .and(path("/introduction.html"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(&body)
                    .insert_header("content-type", "text/html"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/introduction.html", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            let content = value["content"].as_str().unwrap();
            assert!(
                content.len() > 500,
                "Subpage should have substantial content, got {} bytes",
                content.len()
            );
        } else {
            panic!(
                "Expected successful response from subpage, got: {:?}",
                result
            );
        }
    }

    #[tokio::test]
    async fn test_fetch_repo_page() {
        let mock_server = MockServer::start().await;
        let html = r#"<html><body>
        <h1>wasm3/wasm3</h1>
        <p>The fastest WebAssembly interpreter (and target for wasm3).</p>
        <div class="readme"><h2>README</h2><p>wasm3 is a high performance
        WebAssembly interpreter written in C.</p></div>
        </body></html>"#;

        Mock::given(method("GET"))
            .and(path("/wasm3/wasm3"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(html)
                    .insert_header("content-type", "text/html; charset=utf-8"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/wasm3/wasm3", mock_server.uri())
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            let content = value["content"].as_str().unwrap();
            assert!(
                content.to_lowercase().contains("wasm3"),
                "Content should mention wasm3"
            );
        } else {
            panic!("Expected successful response, got: {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_fetch_repo_page_as_text() {
        let mock_server = MockServer::start().await;
        let html = r#"<html><body>
        <h1>wasm3/wasm3</h1>
        <p>The fastest WebAssembly interpreter written in C.</p>
        </body></html>"#;

        Mock::given(method("GET"))
            .and(path("/wasm3/wasm3"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string(html)
                    .insert_header("content-type", "text/html; charset=utf-8"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/wasm3/wasm3", mock_server.uri()),
                "as_text": true
            }))
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            let content = value["content"].as_str().unwrap();
            assert!(
                content.to_lowercase().contains("wasm3"),
                "Content should mention wasm3"
            );
        } else {
            panic!("Expected successful response, got: {:?}", result);
        }
    }

    // ========================================================================
    // File download tests (save_to_file via SessionFileSaver)
    // ========================================================================

    /// In-memory SessionFileSystem for testing file downloads
    struct MockFileStore {
        files: tokio::sync::Mutex<std::collections::HashMap<(SessionId, String), (String, String)>>,
    }

    impl MockFileStore {
        fn new() -> Self {
            Self {
                files: tokio::sync::Mutex::new(std::collections::HashMap::new()),
            }
        }

        async fn get_file(&self, session_id: SessionId, path: &str) -> Option<(String, String)> {
            self.files
                .lock()
                .await
                .get(&(session_id, path.to_string()))
                .cloned()
        }
    }

    #[async_trait]
    impl SessionFileSystem for MockFileStore {
        async fn read_file(
            &self,
            session_id: SessionId,
            path: &str,
        ) -> crate::error::Result<Option<crate::session_file::SessionFile>> {
            let guard = self.files.lock().await;
            if let Some((content, encoding)) = guard.get(&(session_id, path.to_string())) {
                Ok(Some(crate::session_file::SessionFile {
                    id: uuid::Uuid::new_v4(),
                    session_id: session_id.uuid(),
                    path: path.to_string(),
                    name: path.rsplit('/').next().unwrap_or(path).to_string(),
                    content: Some(content.clone()),
                    encoding: encoding.clone(),
                    size_bytes: content.len() as i64,
                    is_directory: false,
                    is_readonly: false,
                    created_at: chrono::Utc::now(),
                    updated_at: chrono::Utc::now(),
                }))
            } else {
                Ok(None)
            }
        }

        async fn write_file(
            &self,
            session_id: SessionId,
            path: &str,
            content: &str,
            encoding: &str,
        ) -> crate::error::Result<crate::session_file::SessionFile> {
            self.files.lock().await.insert(
                (session_id, path.to_string()),
                (content.to_string(), encoding.to_string()),
            );
            Ok(crate::session_file::SessionFile {
                id: uuid::Uuid::new_v4(),
                session_id: session_id.uuid(),
                path: path.to_string(),
                name: path.rsplit('/').next().unwrap_or(path).to_string(),
                content: Some(content.to_string()),
                encoding: encoding.to_string(),
                size_bytes: content.len() as i64,
                is_directory: false,
                is_readonly: false,
                created_at: chrono::Utc::now(),
                updated_at: chrono::Utc::now(),
            })
        }

        async fn delete_file(
            &self,
            _session_id: SessionId,
            _path: &str,
            _recursive: bool,
        ) -> crate::error::Result<bool> {
            Ok(false)
        }

        async fn list_directory(
            &self,
            _session_id: SessionId,
            _path: &str,
        ) -> crate::error::Result<Vec<crate::session_file::FileInfo>> {
            Ok(vec![])
        }

        async fn stat_file(
            &self,
            _session_id: SessionId,
            _path: &str,
        ) -> crate::error::Result<Option<crate::session_file::FileStat>> {
            Ok(None)
        }

        async fn grep_files(
            &self,
            _session_id: SessionId,
            _pattern: &str,
            _path_pattern: Option<&str>,
        ) -> crate::error::Result<Vec<crate::session_file::GrepMatch>> {
            Ok(vec![])
        }

        async fn create_directory(
            &self,
            _session_id: SessionId,
            _path: &str,
        ) -> crate::error::Result<crate::session_file::FileInfo> {
            unimplemented!()
        }
    }

    #[test]
    fn test_web_fetch_tool_schema_save_to_file_gated_by_config() {
        // Default (no file download): save_to_file NOT in schema
        let tool = WebFetchTool::new(false, None);
        let schema = tool.parameters_schema();
        assert!(
            !schema["properties"]["save_to_file"].is_object(),
            "Schema should NOT include save_to_file when disabled"
        );

        // With file download enabled: save_to_file in schema
        let tool = WebFetchTool::new(true, None);
        let schema = tool.parameters_schema();
        assert!(
            schema["properties"]["save_to_file"].is_object(),
            "Schema should include save_to_file when enabled"
        );
    }

    #[test]
    fn test_web_fetch_tool_requires_context() {
        let tool = WebFetchTool::default();
        assert!(tool.requires_context());
    }

    #[test]
    fn test_web_fetch_tools_with_config_enables_file_download() {
        let cap = WebFetchCapability::new(None);

        // Without config: no save_to_file in schema
        let tools = cap.tools_with_config(&serde_json::json!({}));
        assert_eq!(tools.len(), 1);
        let schema = tools[0].parameters_schema();
        assert!(!schema["properties"]["save_to_file"].is_object());

        // With enable_file_download: save_to_file in schema
        let tools = cap.tools_with_config(&serde_json::json!({"enable_file_download": true}));
        assert_eq!(tools.len(), 1);
        let schema = tools[0].parameters_schema();
        assert!(schema["properties"]["save_to_file"].is_object());
    }

    #[tokio::test]
    async fn test_web_fetch_system_prompt_adapts_to_config() {
        let cap = WebFetchCapability::new(None);
        let ctx = super::super::SystemPromptContext::without_file_store(SessionId::new());

        // Without file download: no save_to_file mention in prompt
        let prompt = cap
            .system_prompt_contribution_with_config(&ctx, &serde_json::json!({}))
            .await
            .unwrap();
        assert!(!prompt.contains("save_to_file"));

        // With file download: save_to_file documented in prompt
        let prompt = cap
            .system_prompt_contribution_with_config(
                &ctx,
                &serde_json::json!({"enable_file_download": true}),
            )
            .await
            .unwrap();
        assert!(prompt.contains("save_to_file"));
    }

    #[tokio::test]
    async fn test_save_to_file_text_content() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/data.json"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("{\"key\": \"value\"}")
                    .insert_header("content-type", "application/json"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let file_store = Arc::new(MockFileStore::new());
        let session_id = SessionId::new();
        let context = ToolContext::with_file_store(session_id, file_store.clone());

        let result = tool
            .execute_with_context(
                serde_json::json!({
                    "url": format!("{}/data.json", mock_server.uri()),
                    "save_to_file": "/downloads/data.json"
                }),
                &context,
            )
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert!(value["saved_path"].as_str().is_some());
            assert!(value["bytes_written"].as_u64().unwrap() > 0);
            // Content should NOT be inline when saving to file
            assert!(
                value.get("content").is_none() || value["content"].is_null(),
                "Content should not be inline when saving to file"
            );

            // Verify file was written to the store
            let (content, encoding) = file_store
                .get_file(session_id, "/downloads/data.json")
                .await
                .expect("File should have been written");
            assert_eq!(encoding, "text");
            assert!(content.contains("value"));
        } else {
            panic!("Expected successful response, got: {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_save_to_file_binary_content() {
        let mock_server = MockServer::start().await;

        // Serve a PNG image (binary content)
        let png_bytes = vec![0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0xFF, 0xFE];
        Mock::given(method("GET"))
            .and(path("/image.png"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_bytes(png_bytes.clone())
                    .insert_header("content-type", "image/png"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let file_store = Arc::new(MockFileStore::new());
        let session_id = SessionId::new();
        let context = ToolContext::with_file_store(session_id, file_store.clone());

        let result = tool
            .execute_with_context(
                serde_json::json!({
                    "url": format!("{}/image.png", mock_server.uri()),
                    "save_to_file": "/downloads/image.png"
                }),
                &context,
            )
            .await;

        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert!(value["saved_path"].as_str().is_some());
            assert_eq!(
                value["bytes_written"].as_u64().unwrap(),
                png_bytes.len() as u64
            );

            // Verify file was written as base64 (binary content)
            let (content, encoding) = file_store
                .get_file(session_id, "/downloads/image.png")
                .await
                .expect("File should have been written");
            assert_eq!(encoding, "base64");

            // Decode and verify
            let decoded = base64::engine::general_purpose::STANDARD
                .decode(&content)
                .expect("Should be valid base64");
            assert_eq!(decoded, png_bytes);
        } else {
            panic!("Expected successful response, got: {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_save_to_file_no_file_store_returns_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/file.txt"))
            .respond_with(ResponseTemplate::new(200).set_body_string("content"))
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        // Context without file_store
        let context = ToolContext::new(SessionId::new());

        let result = tool
            .execute_with_context(
                serde_json::json!({
                    "url": format!("{}/file.txt", mock_server.uri()),
                    "save_to_file": "/downloads/file.txt"
                }),
                &context,
            )
            .await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(
                msg.contains("not available"),
                "Expected file system not available error, got: {}",
                msg
            );
        } else {
            panic!("Expected tool error, got: {:?}", result);
        }
    }

    #[tokio::test]
    async fn test_save_to_file_disabled_by_config_returns_error() {
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/file.txt"))
            .respond_with(ResponseTemplate::new(200).set_body_string("content"))
            .mount(&mock_server)
            .await;

        let tool = WebFetchTool::new(false, None);
        let file_store = Arc::new(MockFileStore::new());
        let session_id = SessionId::new();
        let context = ToolContext::with_file_store(session_id, file_store.clone());

        let result = tool
            .execute_with_context(
                serde_json::json!({
                    "url": format!("{}/file.txt", mock_server.uri()),
                    "save_to_file": "/downloads/file.txt"
                }),
                &context,
            )
            .await;

        if let ToolExecutionResult::ToolError(msg) = result {
            assert!(
                msg.contains("disabled"),
                "Expected file download disabled error, got: {}",
                msg
            );
        } else {
            panic!("Expected tool error, got: {:?}", result);
        }

        assert!(
            file_store
                .get_file(session_id, "/downloads/file.txt")
                .await
                .is_none(),
            "File should not be written when save_to_file is disabled",
        );
    }

    #[tokio::test]
    async fn test_save_to_file_without_context_strips_save() {
        // When execute() is called (no context), save_to_file should be ignored
        let mock_server = MockServer::start().await;

        Mock::given(method("GET"))
            .and(path("/file.txt"))
            .respond_with(
                ResponseTemplate::new(200)
                    .set_body_string("hello")
                    .insert_header("content-type", "text/plain"),
            )
            .mount(&mock_server)
            .await;

        let tool = tool_for_wiremock();
        let result = tool
            .execute(serde_json::json!({
                "url": format!("{}/file.txt", mock_server.uri()),
                "save_to_file": "/downloads/file.txt"
            }))
            .await;

        // Should succeed with inline content (save_to_file stripped)
        if let ToolExecutionResult::Success(value) = result {
            assert_eq!(value["status_code"], 200);
            assert!(value["content"].as_str().is_some());
            assert!(value.get("saved_path").is_none() || value["saved_path"].is_null());
        } else {
            panic!("Expected successful response, got: {:?}", result);
        }
    }
}