aidaemon-tools 0.27.3

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

use std::collections::HashMap;
use std::io::Cursor;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
use std::sync::OnceLock;
use std::time::Duration;

use async_trait::async_trait;
use reqwest::redirect::Policy;
use reqwest::{Client, StatusCode, Url};
use serde::Deserialize;
use serde_json::{Value, json};

use aidaemon_core::{
    AccessManifest, CallEffects, EffectClass, EffectKey, Hook, HookContext, Tool, ToolAnnotations,
    ToolCall, ToolContext, ToolDecision, ToolInfo, ToolOutput, ToolResult,
};

use crate::fs::ToolText;
use crate::outcome::{OutcomeTool, spec_of};
use crate::semantics::{
    NetworkReach, ToolCallContext, ToolCallMetadata, ToolCallOutcome, ToolCallSemantics,
    ToolCapabilities, ToolTargetHintKind, ToolVerificationMode,
};
use crate::util::{fail, parse_args, truncate_chars};

const DEFAULT_MAX_CHARS: usize = 20_000;
const MAX_MAX_CHARS: usize = 50_000;

/// Hard cap on response-body bytes buffered from a web fetch/search. The
/// model-facing output is already bounded (extracted-text char limit / result
/// count); this only bounds *transient memory* against a pathologically large
/// or mislabeled response that `.text()`/`.json()` would otherwise buffer whole.
pub const MAX_FETCH_BODY_BYTES: usize = 10 * 1024 * 1024;

/// Append `chunk` to `buf` without exceeding `max_bytes`. Returns true if the
/// chunk was (partially) dropped because the cap was reached. Truncation is on a
/// raw byte boundary, so callers must decode with `from_utf8_lossy`.
pub fn append_capped(buf: &mut Vec<u8>, chunk: &[u8], max_bytes: usize) -> bool {
    let remaining = max_bytes.saturating_sub(buf.len());
    if chunk.len() > remaining {
        buf.extend_from_slice(&chunk[..remaining]);
        true
    } else {
        buf.extend_from_slice(chunk);
        false
    }
}

/// Stream a response body into memory, capping at `max_bytes` to avoid unbounded
/// allocation. Returns the collected bytes and whether the body was truncated.
pub async fn read_body_capped(
    resp: reqwest::Response,
    max_bytes: usize,
) -> reqwest::Result<(Vec<u8>, bool)> {
    let mut resp = resp;
    let mut buf: Vec<u8> = Vec::new();
    let mut truncated = false;
    while let Some(chunk) = resp.chunk().await? {
        if append_capped(&mut buf, &chunk, max_bytes) {
            truncated = true;
            break;
        }
    }
    Ok((buf, truncated))
}

/// Validates a URL for SSRF vulnerabilities.
/// Returns Ok(()) if the URL is safe to fetch, Err with a message otherwise.
pub fn validate_url_for_ssrf(url: &str) -> Result<(), String> {
    let parsed = reqwest::Url::parse(url).map_err(|e| format!("Invalid URL: {}", e))?;

    // 1. Only allow http and https schemes
    match parsed.scheme() {
        "http" | "https" => {}
        scheme => {
            return Err(format!(
                "Blocked scheme '{}': only http/https allowed",
                scheme
            ));
        }
    }

    // 2. Must have a host
    let host = parsed
        .host_str()
        .ok_or_else(|| "URL must have a host".to_string())?;

    // 3. Block known dangerous hostnames
    let host_lower = host.to_lowercase();
    const BLOCKED_HOSTS: &[&str] = &[
        "localhost",
        "127.0.0.1",
        "::1",
        "[::1]",
        "0.0.0.0",
        "metadata.google.internal",
        "metadata.goog",
        "169.254.169.254",
    ];
    for blocked in BLOCKED_HOSTS {
        if host_lower == *blocked {
            return Err(format!("Blocked host: {}", host));
        }
    }

    // 4. Block hosts that look like internal addresses
    if host_lower.ends_with(".internal")
        || host_lower.ends_with(".local")
        || host_lower.ends_with(".localhost")
    {
        return Err(format!("Blocked internal hostname: {}", host));
    }

    // 5. Resolve the hostname and check all IP addresses
    let port = parsed.port().unwrap_or(match parsed.scheme() {
        "https" => 443,
        _ => 80,
    });

    // Try to resolve the hostname
    let socket_addr = format!("{}:{}", host, port);
    match socket_addr.to_socket_addrs() {
        Ok(addrs) => {
            for addr in addrs {
                if is_blocked_ip(addr.ip()) {
                    return Err(format!(
                        "Blocked IP address {} (resolved from {})",
                        addr.ip(),
                        host
                    ));
                }
            }
        }
        Err(_) => {
            // If we can't resolve, it might be a raw IP - try parsing it
            if let Ok(ip) = host.parse::<IpAddr>()
                && is_blocked_ip(ip)
            {
                return Err(format!("Blocked IP address: {}", ip));
            }
            // If resolution fails and it's not an IP, let the request fail naturally
        }
    }

    Ok(())
}

/// A client for one probe of a public URL: no redirects, `timeout`, and
/// connections only to public addresses (its resolver refuses private
/// ones, so a name that passed [`validate_url_for_ssrf`] cannot be
/// re-pointed at a private address between the check and the connection).
/// Probes of loopback test servers build their own client.
pub fn public_probe_client(timeout: std::time::Duration) -> reqwest::Result<reqwest::Client> {
    reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(timeout)
        .dns_resolver(std::sync::Arc::new(PublicOnlyResolver))
        .build()
}

/// Refuses at connection time any name that resolves to a blocked address.
/// The check before a request and the connection look a name up separately,
/// so a name could answer with a public address first and a private one next.
pub(crate) struct PublicOnlyResolver;

impl reqwest::dns::Resolve for PublicOnlyResolver {
    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
        let host = name.as_str().to_string();
        Box::pin(async move {
            let addrs: Vec<std::net::SocketAddr> =
                tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
            if let Some(blocked) = addrs.iter().find(|addr| is_blocked_ip(addr.ip())) {
                let reason = format!("{host} resolves to blocked address {}", blocked.ip());
                return Err(
                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, reason).into(),
                );
            }
            Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)
        })
    }
}

/// Check if an IP address is in a blocked range (private, loopback, link-local, etc.)
fn is_blocked_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ipv4) => is_blocked_ipv4(ipv4),
        IpAddr::V6(ipv6) => is_blocked_ipv6(ipv6),
    }
}

fn is_blocked_ipv4(ip: Ipv4Addr) -> bool {
    let octets = ip.octets();

    // Loopback: 127.0.0.0/8
    if octets[0] == 127 {
        return true;
    }

    // Private: 10.0.0.0/8
    if octets[0] == 10 {
        return true;
    }

    // Private: 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
        return true;
    }

    // Private: 192.168.0.0/16
    if octets[0] == 192 && octets[1] == 168 {
        return true;
    }

    // Link-local: 169.254.0.0/16 (includes cloud metadata at 169.254.169.254)
    if octets[0] == 169 && octets[1] == 254 {
        return true;
    }

    // Broadcast: 255.255.255.255
    if ip == Ipv4Addr::BROADCAST {
        return true;
    }

    // Unspecified: 0.0.0.0
    if ip == Ipv4Addr::UNSPECIFIED {
        return true;
    }

    // Documentation ranges (TEST-NET): 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24
    if (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
    {
        return true;
    }

    // Shared address space (CGNAT, tailnets): 100.64.0.0/10
    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
        return true;
    }

    // "This network" 0.0.0.0/8 (0.x.y.z reaches the local host on some
    // systems), IETF protocol assignments 192.0.0.0/24, benchmarking
    // 198.18.0.0/15, multicast 224.0.0.0/4 and reserved 240.0.0.0/4.
    if octets[0] == 0
        || (octets[0] == 192 && octets[1] == 0 && octets[2] == 0)
        || (octets[0] == 198 && (18..=19).contains(&octets[1]))
        || octets[0] >= 224
    {
        return true;
    }

    false
}

fn is_blocked_ipv6(ip: Ipv6Addr) -> bool {
    // Loopback: ::1
    if ip.is_loopback() {
        return true;
    }

    // Unspecified: ::
    if ip.is_unspecified() {
        return true;
    }

    // IPv4-mapped addresses: check the embedded IPv4
    if let Some(ipv4) = ip.to_ipv4_mapped() {
        return is_blocked_ipv4(ipv4);
    }

    let segments = ip.segments();
    let embedded_v4 = |high: u16, low: u16| {
        Ipv4Addr::new(
            (high >> 8) as u8,
            (high & 0xff) as u8,
            (low >> 8) as u8,
            (low & 0xff) as u8,
        )
    };

    // IPv4-compatible (deprecated) ::a.b.c.d: the first 96 bits are zero.
    if segments[..6].iter().all(|segment| *segment == 0) {
        return is_blocked_ipv4(embedded_v4(segments[6], segments[7]));
    }

    // NAT64 well-known prefix 64:ff9b::/96 and local-use 64:ff9b:1::/48:
    // a translator forwards these to the embedded IPv4 address.
    if segments[0] == 0x0064 && segments[1] == 0xff9b {
        return segments[2..6].iter().all(|segment| *segment == 0)
            && is_blocked_ipv4(embedded_v4(segments[6], segments[7]))
            || segments[2] == 0x0001;
    }

    // 6to4 2002::/16 carries an IPv4 address in its next 32 bits.
    if segments[0] == 0x2002 {
        return is_blocked_ipv4(embedded_v4(segments[1], segments[2]));
    }

    // Teredo 2001::/32 tunnels to an obfuscated IPv4 address; discard-only
    // 100::/64; site-local fec0::/10 (deprecated private); multicast ff00::/8.
    if (segments[0] == 0x2001 && segments[1] == 0)
        || (segments[0] == 0x0100 && segments[1..4].iter().all(|segment| *segment == 0))
        || (segments[0] & 0xffc0) == 0xfec0
        || (segments[0] & 0xff00) == 0xff00
    {
        return true;
    }

    // Link-local: fe80::/10
    if (segments[0] & 0xffc0) == 0xfe80 {
        return true;
    }

    // Unique local addresses (private): fc00::/7
    if (segments[0] & 0xfe00) == 0xfc00 {
        return true;
    }

    false
}

/// A coarse classification of *why* a host is blocked by the private-network
/// policy. The whole point of this enum is **secret safety**: it carries only a
/// fixed, low-cardinality category — never the URL, host, path, query, or
/// credentials. Surfacing `class.label()` in an error message therefore cannot
/// leak any caller-supplied data.
///
/// Shared by `web_fetch` and the `browser` tool so both name a blocked request
/// the same way.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockedHostClass {
    /// Loopback (`127.0.0.0/8`, `::1`, `localhost`, `0.0.0.0`).
    Loopback,
    /// RFC1918 / unique-local private ranges (`10/8`, `172.16/12`, `192.168/16`,
    /// `fc00::/7`) and CGNAT shared space (`100.64.0.0/10`).
    PrivateNetwork,
    /// Link-local, including the cloud metadata endpoint (`169.254.0.0/16`,
    /// notably `169.254.169.254`; `fe80::/10`; `*.internal`/metadata hostnames).
    LinkLocalMetadata,
    /// A non-http(s) scheme (e.g. `file:`, `ftp:`, `data:`).
    DisallowedScheme,
    /// Malformed URL or a URL with no host.
    Malformed,
    /// Other reserved/blocked address (broadcast, documentation/TEST-NET ranges,
    /// `.local` hostnames) that isn't one of the more specific classes above.
    OtherReserved,
}

impl BlockedHostClass {
    /// A short, human-readable label naming ONLY the host class. Safe to embed
    /// in a user/LLM-facing error: it contains no caller data.
    pub fn label(self) -> &'static str {
        match self {
            BlockedHostClass::Loopback => "loopback address",
            BlockedHostClass::PrivateNetwork => "private network",
            BlockedHostClass::LinkLocalMetadata => "link-local/metadata address",
            BlockedHostClass::DisallowedScheme => "disallowed scheme",
            BlockedHostClass::Malformed => "malformed URL",
            BlockedHostClass::OtherReserved => "reserved/blocked address",
        }
    }
}

/// Classify a blocked IPv4 address into a [`BlockedHostClass`]. Mirrors
/// [`is_blocked_ipv4`] exactly (same ranges, same order) but reports the
/// category instead of a bool. Returns `None` for a public address.
fn classify_blocked_ipv4(ip: Ipv4Addr) -> Option<BlockedHostClass> {
    let octets = ip.octets();

    // Loopback: 127.0.0.0/8
    if octets[0] == 127 {
        return Some(BlockedHostClass::Loopback);
    }
    // Unspecified: 0.0.0.0 — treated as loopback-class (targets the local host).
    if ip == Ipv4Addr::UNSPECIFIED {
        return Some(BlockedHostClass::Loopback);
    }
    // Private: 10.0.0.0/8
    if octets[0] == 10 {
        return Some(BlockedHostClass::PrivateNetwork);
    }
    // Private: 172.16.0.0/12
    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
        return Some(BlockedHostClass::PrivateNetwork);
    }
    // Private: 192.168.0.0/16
    if octets[0] == 192 && octets[1] == 168 {
        return Some(BlockedHostClass::PrivateNetwork);
    }
    // Shared address space (CGNAT): 100.64.0.0/10
    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
        return Some(BlockedHostClass::PrivateNetwork);
    }
    // Link-local: 169.254.0.0/16 (includes cloud metadata 169.254.169.254)
    if octets[0] == 169 && octets[1] == 254 {
        return Some(BlockedHostClass::LinkLocalMetadata);
    }
    // Broadcast + documentation/TEST-NET ranges.
    if ip == Ipv4Addr::BROADCAST
        || (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
    {
        return Some(BlockedHostClass::OtherReserved);
    }
    None
}

/// Classify a blocked IPv6 address into a [`BlockedHostClass`]. Mirrors
/// [`is_blocked_ipv6`] (IPv4-mapped addresses are unwrapped and classified as
/// their embedded v4 class). Returns `None` for a public address.
fn classify_blocked_ipv6(ip: Ipv6Addr) -> Option<BlockedHostClass> {
    if ip.is_loopback() || ip.is_unspecified() {
        return Some(BlockedHostClass::Loopback);
    }
    // IPv4-mapped (::ffff:a.b.c.d) — classify by the embedded IPv4 address.
    if let Some(ipv4) = ip.to_ipv4_mapped() {
        return classify_blocked_ipv4(ipv4);
    }
    let segments = ip.segments();
    // Link-local: fe80::/10
    if (segments[0] & 0xffc0) == 0xfe80 {
        return Some(BlockedHostClass::LinkLocalMetadata);
    }
    // Unique local (private): fc00::/7
    if (segments[0] & 0xfe00) == 0xfc00 {
        return Some(BlockedHostClass::PrivateNetwork);
    }
    None
}

fn classify_blocked_ip(ip: IpAddr) -> Option<BlockedHostClass> {
    match ip {
        IpAddr::V4(v4) => classify_blocked_ipv4(v4),
        IpAddr::V6(v6) => classify_blocked_ipv6(v6),
    }
}

/// Classify a URL against the private-network policy and, if blocked, return the
/// host CLASS — never the URL itself.
///
/// This is the shared, secret-safe entry point used by the `browser` tool to
/// build request-level block errors. It applies the SAME policy as
/// [`validate_url_for_ssrf`] (same scheme allow-list, same blocked-host names,
/// same IP ranges, same DNS resolution), so the two tools never diverge.
///
/// Returns `None` when the URL is allowed (public http/https).
pub fn classify_blocked_host(url: &str) -> Option<BlockedHostClass> {
    let parsed = match reqwest::Url::parse(url) {
        Ok(u) => u,
        Err(_) => return Some(BlockedHostClass::Malformed),
    };

    match parsed.scheme() {
        "http" | "https" => {}
        _ => return Some(BlockedHostClass::DisallowedScheme),
    }

    let host = match parsed.host_str() {
        Some(h) => h,
        None => return Some(BlockedHostClass::Malformed),
    };
    let host_lower = host.to_lowercase();

    // Named loopback / metadata hosts (mirrors BLOCKED_HOSTS in validate_url_for_ssrf).
    match host_lower.as_str() {
        "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0" => {
            return Some(BlockedHostClass::Loopback);
        }
        "metadata.google.internal" | "metadata.goog" | "169.254.169.254" => {
            return Some(BlockedHostClass::LinkLocalMetadata);
        }
        _ => {}
    }
    if host_lower.ends_with(".internal") {
        return Some(BlockedHostClass::LinkLocalMetadata);
    }
    if host_lower.ends_with(".local") || host_lower.ends_with(".localhost") {
        // `.localhost` resolves to loopback; `.local` is mDNS link-local-ish but
        // historically grouped with internal names — report as reserved.
        if host_lower.ends_with(".localhost") {
            return Some(BlockedHostClass::Loopback);
        }
        return Some(BlockedHostClass::OtherReserved);
    }

    // Resolve and classify every address the host maps to.
    let port = parsed.port().unwrap_or(match parsed.scheme() {
        "https" => 443,
        _ => 80,
    });
    let socket_addr = format!("{}:{}", host, port);
    match socket_addr.to_socket_addrs() {
        Ok(addrs) => {
            for addr in addrs {
                if let Some(class) = classify_blocked_ip(addr.ip()) {
                    return Some(class);
                }
            }
        }
        Err(_) => {
            // Couldn't resolve via DNS — try parsing the host as a raw IP.
            if let Ok(ip) = host.parse::<IpAddr>()
                && let Some(class) = classify_blocked_ip(ip)
            {
                return Some(class);
            }
            // Unresolvable non-IP host: let the request fail naturally (matches
            // validate_url_for_ssrf). Not classified as blocked here.
        }
    }

    None
}

/// What the owner approves to reach a site on this computer, or `None` when
/// `url` is not loopback-only (public, private network, metadata and malformed
/// targets are never approvable). A dev site's name is its own key;
/// `localhost` and IP literals are shared by every local service, so their key
/// includes the port.
pub fn local_site_key(url: &str) -> Option<String> {
    if !resolves_only_to_loopback(url) {
        return None;
    }
    let parsed = reqwest::Url::parse(url).ok()?;
    let host = parsed.host_str()?.to_lowercase();
    let shared_name = host == "localhost"
        || host
            .trim_matches(['[', ']'])
            .parse::<std::net::IpAddr>()
            .is_ok();
    if shared_name {
        Some(format!("{host}:{}", parsed.port_or_known_default()?))
    } else {
        Some(host)
    }
}

/// Whether `url` targets this computer and nothing else: blocked as loopback,
/// with every address its host resolves to on loopback. A name that also maps
/// to a private or metadata address is not loopback-only.
fn resolves_only_to_loopback(url: &str) -> bool {
    if classify_blocked_host(url) != Some(BlockedHostClass::Loopback) {
        return false;
    }
    let Ok(parsed) = reqwest::Url::parse(url) else {
        return false;
    };
    let Some(host) = parsed.host_str().map(str::to_lowercase) else {
        return false;
    };
    if matches!(
        host.as_str(),
        "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0"
    ) || host.ends_with(".localhost")
    {
        return true;
    }
    let Some(port) = parsed.port_or_known_default() else {
        return false;
    };
    match format!("{host}:{port}").to_socket_addrs() {
        Ok(addrs) => {
            let mut addrs = addrs.peekable();
            addrs.peek().is_some()
                && addrs
                    .all(|addr| classify_blocked_ip(addr.ip()) == Some(BlockedHostClass::Loopback))
        }
        // A literal IP in a form the resolver refused was classified above.
        Err(_) => host
            .parse::<IpAddr>()
            .is_ok_and(|ip| classify_blocked_ip(ip) == Some(BlockedHostClass::Loopback)),
    }
}

/// Whether `host` is a cloud metadata endpoint: by name, by address, or by
/// what it resolves to. Narrower than [`BlockedHostClass::LinkLocalMetadata`],
/// which also covers ordinary `*.internal` names.
fn is_metadata_endpoint(host: &str, port: u16) -> bool {
    let name = host.trim_end_matches('.').to_ascii_lowercase();
    if matches!(name.as_str(), "metadata.google.internal" | "metadata.goog") {
        return true;
    }
    let is_metadata_ip = |ip: IpAddr| match ip {
        IpAddr::V4(v4) => v4.octets()[..2] == [169, 254],
        IpAddr::V6(v6) => {
            (v6.segments()[0] & 0xffc0) == 0xfe80
                || v6 == Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254)
                || v6
                    .to_ipv4_mapped()
                    .is_some_and(|v4| v4.octets()[..2] == [169, 254])
        }
    };
    if let Ok(ip) = name.parse::<IpAddr>() {
        return is_metadata_ip(ip);
    }
    (name.as_str(), port)
        .to_socket_addrs()
        .is_ok_and(|mut addrs| addrs.any(|addr| is_metadata_ip(addr.ip())))
}

/// Why a call to `target` (`host:port`) is refused under `reach`. Names only
/// the class of address, never the target.
fn network_refusal(reach: NetworkReach, target: &str) -> Option<&'static str> {
    let (host, port) = target.rsplit_once(':')?;
    let port: u16 = port.parse().ok()?;
    if is_metadata_endpoint(host, port) {
        return Some("cloud metadata endpoint");
    }
    if reach == NetworkReach::Any {
        return None;
    }
    let authority = if host.contains(':') {
        format!("[{host}]:{port}")
    } else {
        format!("{host}:{port}")
    };
    let class = classify_blocked_host(&format!("http://{authority}/"))?;
    (reach == NetworkReach::PublicOnly || class != BlockedHostClass::Loopback)
        .then(|| class.label())
}

/// Refuses calls whose declared egress names an address the tool may not
/// reach, before anyone is asked. It sees the first request of a call: a
/// redirect exists only once that request runs, so the tools recheck each
/// hop themselves.
#[derive(Debug, Clone, Default)]
pub struct NetworkGuard {
    reach: HashMap<String, NetworkReach>,
}

impl NetworkGuard {
    pub fn new() -> Self {
        Self::default()
    }

    /// State how far `tool` may reach. A tool not named reaches
    /// [`NetworkReach::Any`].
    pub fn reach(mut self, tool: impl Into<String>, reach: NetworkReach) -> Self {
        self.reach.insert(tool.into(), reach);
        self
    }
}

#[async_trait]
impl Hook for NetworkGuard {
    async fn before_tool(
        &self,
        _ctx: &HookContext<'_>,
        call: &ToolCall,
        tool: &ToolInfo,
    ) -> ToolDecision {
        let reach = self.reach.get(&call.name).copied().unwrap_or_default();
        let targets: Vec<String> = tool
            .effects
            .keys
            .iter()
            .filter(|key| key.class == EffectClass::Egress)
            .map(|key| key.target.clone())
            .collect();
        if targets.is_empty() {
            return ToolDecision::Allow;
        }
        // Classifying can resolve a name.
        let refusal = tokio::task::spawn_blocking(move || {
            targets
                .iter()
                .find_map(|target| network_refusal(reach, target))
        })
        .await
        .unwrap_or(Some("address that could not be checked"));
        match refusal {
            Some(label) => ToolDecision::Deny {
                reason: format!("Request blocked: target is a {label}"),
            },
            None => ToolDecision::Allow,
        }
    }
}

const BROWSER_USER_AGENT: &str =
    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:142.0) Gecko/20100101 Firefox/142.0";

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Redirects {
    SameHost,
    Public,
}

/// Which redirects one client follows.
enum Hops {
    None,
    SameHost(String),
    Public,
}

/// Fetch a web page over http(s) and return its readable text.
#[derive(Debug, Clone)]
pub struct WebFetch {
    max_chars: usize,
    timeout: Duration,
    use_proxy: bool,
    user_agent: String,
    browser_headers: bool,
    allow_private: bool,
    redirects: Redirects,
    text: ToolText,
    public_client: OnceLock<Result<Client, String>>,
    no_redirect_client: OnceLock<Result<Client, String>>,
}

impl Default for WebFetch {
    fn default() -> Self {
        Self {
            max_chars: DEFAULT_MAX_CHARS,
            timeout: Duration::from_secs(30),
            use_proxy: true,
            user_agent: concat!("aidaemon-tools/", env!("CARGO_PKG_VERSION")).into(),
            browser_headers: false,
            allow_private: false,
            redirects: Redirects::SameHost,
            text: ToolText {
                short: "Fetch a web page and return its readable text".into(),
                schema: "Fetch a URL with HTTP GET (http/https only) and return the readable text \
                         of the page; plain text and JSON are returned as is. A PDF or other \
                         binary body is described (type and size), not shown. Private and \
                         internal addresses are refused. Redirects to a different host are not \
                         followed; the new location is reported instead."
                    .into(),
            },
            public_client: OnceLock::new(),
            no_redirect_client: OnceLock::new(),
        }
    }
}

impl WebFetch {
    pub fn new() -> Self {
        Self::default()
    }

    /// Default characters of text returned to the model.
    pub fn max_chars(mut self, chars: usize) -> Self {
        self.max_chars = chars.max(100);
        self
    }

    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Ignore `HTTP(S)_PROXY` environment variables.
    pub fn without_proxy(mut self) -> Self {
        self.use_proxy = false;
        self
    }

    pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
        self.user_agent = agent.into();
        self
    }

    /// Send a browser's user agent and headers, for sites that refuse other
    /// clients.
    pub fn browser_identity(mut self) -> Self {
        self.user_agent = BROWSER_USER_AGENT.into();
        self.browser_headers = true;
        self
    }

    /// Follow redirects to other public hosts as well. Each hop is still
    /// checked against the private-network policy.
    pub fn follow_public_redirects(mut self) -> Self {
        self.redirects = Redirects::Public;
        self
    }

    /// Turn off the private-network policy, for a tool that is meant to reach
    /// local services.
    pub fn allow_private_hosts(mut self) -> Self {
        self.allow_private = true;
        self
    }

    /// Replace the model-facing descriptions.
    pub fn with_text(mut self, text: ToolText) -> Self {
        self.text = text;
        self
    }

    fn build_client(&self, hops: Hops) -> Result<Client, String> {
        let guarded = !self.allow_private;
        let allowed = move |url: &str| !guarded || validate_url_for_ssrf(url).is_ok();
        let policy = match hops {
            Hops::None => Policy::none(),
            Hops::Public => Policy::custom(move |attempt| {
                if !allowed(attempt.url().as_str()) || attempt.previous().len() >= 10 {
                    attempt.stop()
                } else {
                    attempt.follow()
                }
            }),
            Hops::SameHost(host) => Policy::custom(move |attempt| {
                if attempt.previous().len() >= 10 {
                    attempt.error("too many redirects")
                } else if attempt.url().host_str() == Some(host.as_str())
                    && matches!(attempt.url().scheme(), "http" | "https")
                    && allowed(attempt.url().as_str())
                {
                    attempt.follow()
                } else {
                    attempt.stop()
                }
            }),
        };
        let mut builder = Client::builder()
            .timeout(self.timeout)
            .redirect(policy)
            .user_agent(&self.user_agent);
        if guarded {
            builder = builder.dns_resolver(std::sync::Arc::new(PublicOnlyResolver));
        }
        if self.browser_headers {
            builder = builder.default_headers(browser_headers());
        }
        if !self.use_proxy {
            builder = builder.no_proxy();
        }
        builder
            .build()
            .map_err(|error| format!("cannot build HTTP client: {error}"))
    }

    fn client_for(&self, url: &str, follow: bool) -> anyhow::Result<Client> {
        let cached = |cell: &OnceLock<Result<Client, String>>, hops| {
            cell.get_or_init(|| self.build_client(hops)).clone()
        };
        let client = match (follow, self.redirects) {
            (false, _) => cached(&self.no_redirect_client, Hops::None),
            (true, Redirects::Public) => cached(&self.public_client, Hops::Public),
            (true, Redirects::SameHost) => {
                let host = Url::parse(url)?.host_str().unwrap_or_default().to_string();
                self.build_client(Hops::SameHost(host))
            }
        };
        client.map_err(anyhow::Error::msg)
    }

    /// Check the policy, send the request and read the capped body.
    async fn fetch(&self, url: &str, follow: bool, read_error_body: bool) -> anyhow::Result<Fetch> {
        if !self.allow_private
            && let Err(reason) = validate_url_for_ssrf(url)
        {
            return Ok(Fetch::Blocked(reason));
        }
        let response = self.client_for(url, follow)?.get(url).send().await?;
        let status = response.status();
        let final_url = response.url().to_string();
        let header = |name| {
            response
                .headers()
                .get(name)
                .and_then(|value: &reqwest::header::HeaderValue| value.to_str().ok())
                .map(str::to_string)
        };
        let content_type = header(reqwest::header::CONTENT_TYPE).unwrap_or_default();
        let location = header(reqwest::header::LOCATION);
        let (body, body_truncated) = if status.is_success() || read_error_body {
            read_body_capped(response, MAX_FETCH_BODY_BYTES).await?
        } else {
            (Vec::new(), false)
        };
        Ok(Fetch::Response(Fetched {
            status,
            final_url,
            content_type,
            location,
            body,
            body_truncated,
        }))
    }
}

enum Fetch {
    Blocked(String),
    Response(Fetched),
}

struct Fetched {
    status: StatusCode,
    final_url: String,
    content_type: String,
    location: Option<String>,
    body: Vec<u8>,
    body_truncated: bool,
}

fn browser_headers() -> reqwest::header::HeaderMap {
    let mut h = reqwest::header::HeaderMap::new();
    h.insert(
        "Accept",
        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
            .parse()
            .unwrap(),
    );
    h.insert("Accept-Language", "en-US,en;q=0.5".parse().unwrap());
    h.insert("Accept-Encoding", "gzip, deflate, br".parse().unwrap());
    h.insert("DNT", "1".parse().unwrap());
    h.insert("Upgrade-Insecure-Requests", "1".parse().unwrap());
    h.insert("Sec-Fetch-Dest", "document".parse().unwrap());
    h.insert("Sec-Fetch-Mode", "navigate".parse().unwrap());
    h.insert("Sec-Fetch-Site", "none".parse().unwrap());
    h.insert("Sec-Fetch-User", "?1".parse().unwrap());
    h.insert("Sec-GPC", "1".parse().unwrap());
    h
}

/// An HTTP client with browser-like headers whose redirects are re-validated
/// against the private-network policy.
pub fn build_browser_client() -> Client {
    WebFetch::new()
        .browser_identity()
        .build_client(Hops::Public)
        .expect("failed to build browser HTTP client")
}

fn parse_url(raw: &str) -> Result<Url, String> {
    let url = Url::parse(raw.trim()).map_err(|e| {
        format!("invalid URL `{raw}`: {e}. Give a full URL such as https://example.com/page")
    })?;
    match url.scheme() {
        "http" | "https" => {}
        other => return Err(format!("unsupported scheme `{other}`; only http and https")),
    }
    if url.host_str().is_none() {
        return Err(format!("URL `{raw}` has no host"));
    }
    Ok(url)
}

/// The one effect of fetching `url`.
fn url_effect(url: &Url) -> Option<EffectKey> {
    // `Url` brackets an IPv6 host; the effect target does not.
    let host = url
        .host_str()?
        .trim_start_matches('[')
        .trim_end_matches(']');
    Some(EffectKey::egress(url.scheme(), host, url.port()))
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FetchArgs {
    url: String,
    max_chars: Option<usize>,
    #[serde(default)]
    offset: usize,
}

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

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

    fn schema(&self) -> Value {
        json!({
            "name": "web_fetch",
            "description": self.text.schema,
            "parameters": {
                "type": "object",
                "properties": {
                    "url": {
                        "type": "string",
                        "description": "The URL to fetch"
                    },
                    "max_chars": {
                        "type": "integer",
                        "description": "Maximum characters to return (default 20000, max 50000)"
                    },
                    "offset": {
                        "type": "integer",
                        "description": "Characters of page text to skip, to read past a truncated reply"
                    }
                },
                "required": ["url"],
                "additionalProperties": false
            }
        })
    }

    async fn execute(
        &self,
        arguments: &str,
        facts: &ToolCallContext,
    ) -> anyhow::Result<ToolCallOutcome> {
        let args: Value = serde_json::from_str(arguments)?;
        let url = args["url"]
            .as_str()
            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: url"))?;
        let max_chars = args["max_chars"]
            .as_u64()
            .map(|n| n as usize)
            .unwrap_or(self.max_chars)
            .clamp(1, MAX_MAX_CHARS);

        let offset = args["offset"].as_u64().unwrap_or(0) as usize;

        let fetched = match self.fetch(url, !facts.mandate_execution, true).await? {
            Fetch::Blocked(reason) => {
                return Ok(ToolCallOutcome::from_output(format!(
                    "Request blocked: {reason}"
                )));
            }
            Fetch::Response(fetched) => fetched,
        };
        let reply = fetch_reply(&fetched, max_chars, offset);
        let output = if reply.ok {
            format!("{}\n{}", fetch_header(url, &fetched), reply.text)
        } else {
            reply.text
        };
        Ok(ToolCallOutcome {
            output,
            metadata: ToolCallMetadata {
                truncation: reply.truncation,
                ..Default::default()
            },
            finish: None,
        })
    }
}

#[async_trait]
impl Tool for WebFetch {
    fn spec(&self) -> aidaemon_core::ToolSpec {
        spec_of(self)
    }

    /// A read, but the request (its URL, query included) leaves the
    /// machine, so outbound policies such as an egress secret scan see it.
    fn annotations(&self) -> ToolAnnotations {
        ToolAnnotations {
            egress: true,
            ..ToolAnnotations::READ_ONLY
        }
    }

    fn outbound(&self, arguments: &Value) -> aidaemon_core::Outbound {
        outbound_of_url(arguments)
    }

    /// The host contacted. An unparsable URL is refused by `validate` before
    /// any policy runs; its effects are unknown.
    fn effects(&self, arguments: &Value) -> CallEffects {
        arguments
            .get("url")
            .and_then(Value::as_str)
            .and_then(|url| parse_url(url).ok())
            .and_then(|url| url_effect(&url))
            .map_or_else(CallEffects::unknown, |key| CallEffects {
                keys: vec![key],
                complete: true,
                understood: false,
            })
    }

    fn validate(&self, arguments: &Value) -> Result<(), String> {
        let url = arguments
            .get("url")
            .and_then(Value::as_str)
            .ok_or("`url` is required and must be a string")?;
        parse_url(url).map(|_| ())
    }

    fn access(&self, arguments: &Value) -> AccessManifest {
        let host = arguments
            .get("url")
            .and_then(Value::as_str)
            .and_then(|u| parse_url(u).ok())
            .and_then(|u| u.host_str().map(str::to_string));
        AccessManifest {
            hosts: host.into_iter().collect(),
            ..Default::default()
        }
    }

    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
        let args: FetchArgs = match parse_args("web_fetch", arguments) {
            Ok(a) => a,
            Err(e) => return Ok(fail(e)),
        };
        let url = match parse_url(&args.url) {
            Ok(u) => u,
            Err(e) => return Ok(fail(e)),
        };
        let max_chars = args
            .max_chars
            .unwrap_or(self.max_chars)
            .clamp(1, MAX_MAX_CHARS.max(self.max_chars));
        let host = url.host_str().unwrap_or_default().to_string();
        let result = tokio::select! {
            result = self.fetch(url.as_str(), true, true) => result,
            _ = ctx.cancel.cancelled() => return Ok(fail("cancelled")),
        };
        let fetched = match result {
            Ok(Fetch::Blocked(reason)) => {
                return Ok(fail(format!("Request blocked: {reason}"))
                    .with_details(json!({"url": url.as_str(), "host": host})));
            }
            Ok(Fetch::Response(fetched)) => fetched,
            Err(e) => {
                return Ok(fail(format!("request to {url} failed: {e}"))
                    .with_details(json!({"url": url.as_str(), "host": host})));
            }
        };
        let Fetched {
            status,
            final_url,
            content_type,
            location,
            body,
            body_truncated,
        } = fetched;

        let mut details = json!({
            "url": url.as_str(),
            "final_url": final_url,
            "host": host,
            "status": status.as_u16(),
            "content_type": content_type,
            "bytes": body.len(),
        });

        if status.is_redirection() {
            let target = location.unwrap_or_else(|| "(no Location header)".into());
            details["location"] = json!(target);
            return Ok(fail(format!(
                "HTTP {status}: {final_url} redirects to {target}, which was not followed. \
                 Fetch that URL explicitly if it is the page you want."
            ))
            .with_details(details));
        }

        let fetched = Fetched {
            status,
            final_url,
            content_type,
            location: None,
            body,
            body_truncated,
        };
        let reply = fetch_reply(&fetched, max_chars, args.offset);
        let cut = reply.truncation.is_some() || fetched.body_truncated;
        details["truncated"] = json!(cut);
        if !reply.ok {
            return Ok(fail(reply.text).with_details(details));
        }
        let mut text = reply.text;
        if let Some(info) = &reply.truncation {
            text.push_str(&format!(
                "\n\n[Content truncated to {max_chars} characters. Fetch again with offset={} \
                 for the next part ({} characters in all).]",
                args.offset + info.shown_chars,
                info.total_chars
            ));
        } else if fetched.body_truncated {
            text.push_str(&format!(
                "\n\n[Content truncated: the body was larger than {MAX_FETCH_BODY_BYTES} bytes.]"
            ));
        }
        Ok(
            ToolOutput::text(format!("{}\n{text}", fetch_header(url.as_str(), &fetched)))
                .with_details(details),
        )
    }
}

/// A fetch sends its URL and nothing else.
fn outbound_of_url(arguments: &Value) -> aidaemon_core::Outbound {
    match arguments.get("url").and_then(Value::as_str) {
        Some(url) => aidaemon_core::Outbound::Exact(vec![url.to_string()]),
        None => aidaemon_core::Outbound::Composed,
    }
}

impl crate::semantics::ToolSemantics for WebFetch {
    fn call_outbound(&self, arguments: &str) -> aidaemon_core::Outbound {
        serde_json::from_str::<Value>(arguments).map_or(aidaemon_core::Outbound::Composed, |args| {
            outbound_of_url(&args)
        })
    }

    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
        crate::semantics::ToolDispatchFacts {
            offering: crate::semantics::Offering::Core,
            network_reach: crate::semantics::NetworkReach::PublicOnly,
            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
            recap: crate::semantics::RecapKind::ExternalRead,
            activity: crate::semantics::ToolActivity::Fixed(aidaemon_core::card::ActivityKind::Web),
            status_label: Some("fetching a page"),
            result_fit: crate::semantics::ResultFit {
                compact_json: true,
                ..Default::default()
            },
            evidence: crate::semantics::EvidenceSource::RemoteRead,
            semantic_scope: Some(crate::semantics::ToolSemanticScope::ExternalRemote),
            ..Default::default()
        }
    }

    fn capabilities(&self) -> ToolCapabilities {
        ToolCapabilities::READ_ONLY_EXTERNAL
    }

    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
        let url = serde_json::from_str::<Value>(arguments)
            .ok()
            .and_then(|args| {
                args.get("url")
                    .and_then(|value| value.as_str())
                    .map(str::to_string)
            })
            .unwrap_or_default();

        ToolCallSemantics::observation()
            .with_operation(crate::semantics::ToolCallOperation::Get)
            .with_verification_mode(ToolVerificationMode::ResultContent)
            .with_target_hint(ToolTargetHintKind::Url, url)
    }

    /// The page's host.
    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
        serde_json::from_str::<Value>(arguments)
            .ok()
            .and_then(|args| url_effect(&parse_url(args.get("url")?.as_str()?).ok()?))
            .map_or_else(aidaemon_core::CallEffects::unknown, |key| {
                aidaemon_core::CallEffects {
                    keys: vec![key],
                    complete: true,
                    understood: false,
                }
            })
    }
}

fn looks_like_html(body: &[u8]) -> bool {
    let head = String::from_utf8_lossy(&body[..body.len().min(512)]).to_ascii_lowercase();
    head.contains("<html") || head.contains("<!doctype html")
}

/// What a fetched body is: by its declared type, sniffed when undeclared.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BodyKind {
    Html,
    Text,
    Pdf,
    Binary,
}

fn body_kind(content_type: &str, body: &[u8]) -> BodyKind {
    let lower = content_type.to_ascii_lowercase();
    if lower.contains("pdf") || (lower.is_empty() && body.starts_with(b"%PDF-")) {
        BodyKind::Pdf
    } else if lower.contains("html") || (lower.is_empty() && looks_like_html(body)) {
        BodyKind::Html
    } else if lower.starts_with("text/")
        || lower.contains("json")
        || lower.contains("xml")
        || lower.contains("javascript")
        || (lower.is_empty() && std::str::from_utf8(&body[..body.len().min(1024)]).is_ok())
    {
        BodyKind::Text
    } else {
        BodyKind::Binary
    }
}

/// The model's view of one fetch, for both entry points: the page's text
/// (from `offset`, cut at `max_chars`, with the cut as metadata), or an
/// error that says why there is no text.
struct FetchReply {
    ok: bool,
    text: String,
    truncation: Option<crate::semantics::TruncationInfo>,
}

fn fetch_reply(fetched: &Fetched, max_chars: usize, offset: usize) -> FetchReply {
    let url = fetched.final_url.as_str();
    let status = fetched.status;
    let error = |text: String| FetchReply {
        ok: false,
        text,
        truncation: None,
    };
    if status.is_redirection() {
        let target = fetched
            .location
            .as_deref()
            .unwrap_or("(no Location header)");
        return error(format!(
            "HTTP {status}: {url} redirects to {target}, which was not followed. Fetch that URL \
             explicitly if it is the page you want."
        ));
    }
    let kind = body_kind(&fetched.content_type, &fetched.body);
    let bytes = fetched.body.len();
    let content_type = if fetched.content_type.is_empty() {
        "an undeclared type"
    } else {
        fetched.content_type.as_str()
    };
    match kind {
        BodyKind::Pdf if status.is_success() => {
            return error(format!(
                "{url} is a PDF document ({bytes} bytes, {content_type}). web_fetch does not \
                 extract PDF text: download the file to the workspace and read it with read_file, \
                 which says how to extract its text."
            ));
        }
        BodyKind::Binary if status.is_success() => {
            return error(format!(
                "{url} returned binary content, {bytes} bytes, type {content_type}, which is not \
                 text and cannot be shown."
            ));
        }
        _ => {}
    }
    let raw = String::from_utf8_lossy(&fetched.body);
    if !status.is_success() {
        let text = match kind {
            BodyKind::Html => extract_page_text(&raw, url),
            BodyKind::Text => raw.into_owned(),
            BodyKind::Pdf | BodyKind::Binary => String::new(),
        };
        let (snippet, _) = truncate_chars(text.trim(), 2000);
        return error(format!("HTTP {status} from {url}.\n\n{snippet}"));
    }
    let (text, truncation) = match kind {
        BodyKind::Html => build_fetch_reply_at(url, &raw, max_chars, offset),
        _ => format_fetch_window(url, &raw, max_chars, offset),
    };
    FetchReply {
        ok: true,
        text,
        truncation,
    }
}

/// Extracted text shorter than this (on a large page) means extraction
/// failed, not that the page is thin.
const MIN_EXTRACTED_CHARS: usize = 200;
/// Only pages at least this large trigger the extraction-failure check —
/// genuinely tiny pages legitimately yield little text.
const MIN_HTML_FOR_EXTRACTION_CHECK: usize = 10_000;

/// Full fetch-reply pipeline: strip non-visible blocks, extract readable
/// text, detect failed extraction, format with truncation honesty.
#[cfg(test)]
fn build_fetch_reply(
    url: &str,
    html: &str,
    max_chars: usize,
) -> (String, Option<crate::semantics::TruncationInfo>) {
    build_fetch_reply_at(url, html, max_chars, 0)
}

fn build_fetch_reply_at(
    url: &str,
    html: &str,
    max_chars: usize,
    offset: usize,
) -> (String, Option<crate::semantics::TruncationInfo>) {
    let text = extract_page_text(html, url);
    let trimmed = text.trim();
    if trimmed.chars().count() < MIN_EXTRACTED_CHARS && html.len() >= MIN_HTML_FOR_EXTRACTION_CHECK
    {
        // A large page that yields almost no readable text is the signature
        // of a JavaScript-rendered (or bot-walled) page. Without this notice
        // the model treats the empty result as the page's actual content —
        // or worse, re-fetches the same URL expecting a different outcome.
        // This is a distinct extraction-failure signal, not truncation, so it
        // stays an embedded instructional marker (no TruncationInfo applies).
        return (
            format!(
                "Content from {}:\n\n{}\n\n[⚠ EXTRACTION FAILED — this {} KB page yielded only {} \
                 characters of readable text; it is likely JavaScript-rendered or blocking \
                 non-browser clients. Do NOT treat this as the page's content, and do NOT re-fetch \
                 this same URL — the result will not change. Fetch a different source URL from your \
                 search results, or use a browser-based tool on this URL if one is available.]",
                url,
                trimmed,
                html.len() / 1024,
                trimmed.chars().count(),
            ),
            None,
        );
    }
    format_fetch_window(url, &text, max_chars, offset)
}

/// Extract readable page text: readability first, raw-HTML-to-markdown
/// fallback. `<script>`/`<style>`/`<noscript>` blocks are stripped FIRST —
/// both paths can leak inline script bodies into the "text" (observed:
/// Wikipedia fetches returning JS soup that consumed the whole max_chars
/// window before any article content).
fn extract_page_text(html: &str, url: &str) -> String {
    let text = extract_page_body(html, url);
    // Readability keeps the article body and drops a heading that repeats
    // the page title, so a page whose one heading is its title came back
    // without it (live 2026-11-20: every "what is the page's heading?" turn
    // re-fetched the page with curl two or three times to find it). The
    // page's heading leads the text when the text lacks it.
    match page_heading(html) {
        Some(heading) if !text.contains(&heading) => format!("# {heading}\n\n{text}"),
        _ => text,
    }
}

/// The page's main heading as plain text: its first `<h1>`, else its
/// `<title>` (HTML markup, a machine format).
fn page_heading(html: &str) -> Option<String> {
    let cleaned = strip_nonvisible_blocks(html);
    ["h1", "title"]
        .into_iter()
        .find_map(|tag| first_element_text(&cleaned, tag))
}

/// The text inside the first `<tag ...>...</tag>`, tags removed, entities
/// decoded and whitespace collapsed; `None` when absent or empty.
fn first_element_text(html: &str, tag: &str) -> Option<String> {
    let bytes = html.as_bytes();
    let open = format!("<{tag}");
    let mut from = 0;
    let start = loop {
        let at = find_ascii_ci(bytes, open.as_bytes(), from)?;
        // "<h1" must end the tag name ("<h10" or "<titles" is another tag).
        if matches!(
            bytes.get(at + open.len()),
            Some(b' ') | Some(b'>') | Some(b'\t') | Some(b'\n') | Some(b'\r')
        ) {
            break at;
        }
        from = at + open.len();
    };
    let inner_start = start + html[start..].find('>')? + 1;
    let close = format!("</{tag}");
    let inner_end = find_ascii_ci(bytes, close.as_bytes(), inner_start)?;
    let inner = htmd::convert(&html[inner_start..inner_end]).unwrap_or_default();
    let text = inner
        .replace(['*', '_', '#', '`'], "")
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    (!text.is_empty()).then_some(text)
}

/// [`extract_page_text`] before the page's heading is added.
fn extract_page_body(html: &str, url: &str) -> String {
    let cleaned = strip_nonvisible_blocks(html);
    let parsed_url = reqwest::Url::parse(url)
        .unwrap_or_else(|_| reqwest::Url::parse("http://example.com").unwrap());
    let mut cursor = Cursor::new(cleaned.as_bytes());
    let full_page = || htmd::convert(&cleaned).unwrap_or_else(|_| cleaned.clone());
    match llm_readability::extractor::extract(&mut cursor, &parsed_url) {
        Ok(product) if !product.text.trim().is_empty() => {
            // Readability's plain text runs its blocks together ("Example
            // DomainThis domain ..."); its HTML as markdown keeps headings
            // and paragraphs apart.
            let article = htmd::convert(&strip_nonvisible_blocks(&product.content))
                .ok()
                .filter(|markdown| !markdown.trim().is_empty())
                .unwrap_or_else(|| product.text.clone());
            // Readability keeps one block. On an article that is the content;
            // on a listing page (downloads, release lists, tables) it is a
            // side section, and the answer is in what it dropped. A short
            // extract cut from a much larger page gets the whole page.
            let article_chars = article.trim().chars().count();
            if article_chars >= MIN_ARTICLE_CHARS {
                return article;
            }
            let full = full_page();
            let full_chars = full.trim().chars().count();
            if (article_chars as f64) >= MIN_ARTICLE_COVERAGE * full_chars as f64 {
                article
            } else {
                full
            }
        }
        _ => full_page(),
    }
}

/// Readability output at least this long is an article in its own right.
const MIN_ARTICLE_CHARS: usize = 8_000;
/// A shorter extract must cover at least this share of the page's text to
/// count as its main content.
const MIN_ARTICLE_COVERAGE: f64 = 0.35;

/// Remove `<script>`, `<style>`, and `<noscript>` blocks (case-insensitive,
/// unclosed blocks dropped to end-of-input).
fn strip_nonvisible_blocks(html: &str) -> String {
    let mut out = html.to_string();
    for tag in ["script", "style", "noscript"] {
        out = strip_tag_blocks(&out, tag);
    }
    out
}

fn strip_tag_blocks(html: &str, tag: &str) -> String {
    let open = format!("<{}", tag);
    let close = format!("</{}>", tag);
    let bytes = html.as_bytes();
    let mut out = String::with_capacity(html.len());
    let mut pos = 0;
    while let Some(start) = find_ascii_ci(bytes, open.as_bytes(), pos) {
        // The byte after "<tag" must terminate the tag name, else "<scriptx"
        // or a "<style-like" element would match.
        let after = bytes.get(start + open.len());
        if !matches!(
            after,
            Some(b' ') | Some(b'>') | Some(b'\t') | Some(b'\n') | Some(b'/')
        ) {
            out.push_str(&html[pos..start + open.len()]);
            pos = start + open.len();
            continue;
        }
        out.push_str(&html[pos..start]);
        match find_ascii_ci(bytes, close.as_bytes(), start) {
            Some(end) => pos = end + close.len(),
            None => {
                pos = html.len();
                break;
            }
        }
    }
    out.push_str(&html[pos..]);
    out
}

/// ASCII-case-insensitive substring search from `from`. Byte positions are
/// safe to slice with because the needles are pure ASCII.
fn find_ascii_ci(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
    if from >= haystack.len() || needle.is_empty() {
        return None;
    }
    haystack[from..]
        .windows(needle.len())
        .position(|w| w.eq_ignore_ascii_case(needle))
        .map(|i| i + from)
}

/// Format extracted page text, truncating to `max_chars` (bytes, floored to a
/// char boundary). Truncation is reported via the returned `TruncationInfo`,
/// not embedded in the text — the agent loop renders the instructional
/// notice from that metadata (see `crate::utils::render_truncation_notice`),
/// so text-scanning consumers (classifiers, summaries) always see clean
/// output. A passive "[Truncated]" marker baked into the text is routinely
/// ignored and the model fabricates the omitted content (e.g. inventing the
/// rest of a roster) — this is why the notice must reach the model through
/// the loop's instructional rendering rather than raw tool output.
#[cfg(test)]
fn format_fetch_result(
    url: &str,
    text: &str,
    max_chars: usize,
) -> (String, Option<crate::semantics::TruncationInfo>) {
    format_fetch_window(url, text, max_chars, 0)
}

/// One line stating what a fetch reached: status, content type, the final
/// URL (and the URL asked for when a redirect moved it) and the page title,
/// so the model need not check them with another request (live 2026-11-14
/// to 11-20: 51 curl status checks, 9 right after a fetch).
fn fetch_header(requested: &str, fetched: &Fetched) -> String {
    let same = |a: &str, b: &str| a.trim_end_matches('/') == b.trim_end_matches('/');
    let mut parts = vec![
        format!("HTTP {}", fetched.status.as_u16()),
        fetched.content_type.clone(),
    ];
    if same(requested, &fetched.final_url) {
        parts.push(fetched.final_url.clone());
    } else {
        parts.push(format!(
            "{} (redirected from {requested})",
            fetched.final_url
        ));
    }
    if fetched.content_type.contains("html")
        && let Some(title) = first_element_text(&String::from_utf8_lossy(&fetched.body), "title")
    {
        parts.push(format!("title \"{title}\""));
    }
    parts.join(" \u{b7} ")
}

/// `max_chars` of `text` starting at character `offset`. A cut is reported
/// as metadata, with the offset that continues it.
fn format_fetch_window(
    url: &str,
    text: &str,
    max_chars: usize,
    offset: usize,
) -> (String, Option<crate::semantics::TruncationInfo>) {
    let total_chars = text.chars().count();
    let mut result = format!("Content from {}:\n\n", url);
    if offset >= total_chars && offset > 0 {
        result.push_str(&format!(
            "[offset {offset} is past the end: the page text has {total_chars} characters.]"
        ));
        return (result, None);
    }
    let window: String = text.chars().skip(offset).take(max_chars).collect();
    let shown_chars = window.chars().count();
    result.push_str(&window);
    if offset + shown_chars < total_chars {
        let truncation = crate::semantics::TruncationInfo {
            shown_chars,
            total_chars,
            remediation_hint: Some(format!(
                "If the answer may be in the omitted part, fetch again with offset={} (or a \
                 larger max_chars, up to 50000), or fetch a more specific page; if the full \
                 content is still not visible, tell the user the page was longer than you \
                 could read.",
                offset + shown_chars
            )),
        };
        (result, Some(truncation))
    } else {
        (result, None)
    }
}

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

    #[tokio::test]
    async fn a_name_resolving_to_a_blocked_address_is_refused_at_connection() {
        use reqwest::dns::Resolve;
        use std::str::FromStr;
        let name = reqwest::dns::Name::from_str("localhost").unwrap();
        let error = match PublicOnlyResolver.resolve(name).await {
            Ok(_) => panic!("localhost must not resolve"),
            Err(error) => error.to_string(),
        };
        assert!(error.contains("blocked address"), "{error}");
    }
    use crate::testutil::ctx;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    /// Addresses that reach a private or local host through an embedding
    /// (IPv4-compatible, NAT64, 6to4) or a reserved range are blocked;
    /// ordinary public addresses are not.
    #[test]
    fn embedded_and_reserved_addresses_are_blocked() {
        for blocked in [
            "100.100.100.100",
            "0.1.2.3",
            "198.18.0.1",
            "224.0.0.1",
            "240.0.0.1",
            "::127.0.0.1",
            "::ffff:10.0.0.1",
            "64:ff9b::a9fe:a9fe",
            "64:ff9b::7f00:1",
            "64:ff9b:1::1",
            "2002:7f00:1::1",
            "2002:a9fe:a9fe::",
            "2001:0:4136:e378:8000:63bf:3fff:fdd2",
            "fec0::1",
            "ff02::1",
            "100::1",
        ] {
            let ip: IpAddr = blocked.parse().unwrap();
            assert!(is_blocked_ip(ip), "{blocked}");
        }
        for public in [
            "93.184.216.34",
            "2606:4700::6810:84e5",
            "64:ff9b::5db8:d822",
            "2002:5db8:d822::1",
        ] {
            let ip: IpAddr = public.parse().unwrap();
            assert!(!is_blocked_ip(ip), "{public}");
        }
    }

    #[test]
    fn web_fetch_declares_its_egress_host() {
        let tool = WebFetch::new();
        assert!(tool.annotations().egress);
        assert!(tool.annotations().read_only);
        let effects = tool.effects(&json!({"url": "https://Docs.Example.Invalid/guide?q=1"}));
        assert!(effects.complete);
        assert_eq!(
            effects.keys,
            vec![EffectKey::egress("https", "docs.example.invalid", None)]
        );
        let local = tool.effects(&json!({"url": "http://[::1]:8765/status"}));
        assert_eq!(
            local.keys,
            vec![EffectKey::egress("http", "::1", Some(8765))]
        );
        assert!(!tool.effects(&json!({"url": "not a url"})).complete);
    }

    /// Serve canned responses on a local port: path -> (status line, content type, body).
    async fn serve(routes: Vec<(&'static str, &'static str, &'static str, String)>) -> String {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            loop {
                let Ok((mut sock, _)) = listener.accept().await else {
                    break;
                };
                let routes = routes.clone();
                tokio::spawn(async move {
                    let mut buf = vec![0u8; 4096];
                    let n = sock.read(&mut buf).await.unwrap_or(0);
                    let req = String::from_utf8_lossy(&buf[..n]);
                    let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();
                    let (status, ctype, body) = routes
                        .iter()
                        .find(|(p, ..)| *p == path)
                        .map(|(_, s, c, b)| (*s, *c, b.clone()))
                        .unwrap_or(("404 Not Found", "text/plain", "missing".to_string()));
                    let extra = if status.starts_with("302") {
                        format!("Location: {body}\r\n")
                    } else {
                        String::new()
                    };
                    let resp = format!(
                        "HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
                        body.len()
                    );
                    let _ = sock.write_all(resp.as_bytes()).await;
                    let _ = sock.shutdown().await;
                });
            }
        });
        format!("http://127.0.0.1:{}", addr.port())
    }

    /// The reply's first line says what the fetch reached: status, type,
    /// final URL (with the URL asked for when a redirect moved it) and
    /// title, on both entry points.
    #[tokio::test]
    async fn a_fetch_reports_status_final_url_and_title() {
        let base = serve(vec![
            (
                "/page",
                "200 OK",
                "text/html; charset=utf-8",
                "<html><head><title>Synthetic Shop</title></head><body><p>Hello.</p></body></html>"
                    .into(),
            ),
            ("/hop", "302 Found", "text/plain", "/page".into()),
        ])
        .await;
        let tool = WebFetch::new().without_proxy().allow_private_hosts();
        let out = tool
            .call(json!({"url": format!("{base}/page")}), &ctx())
            .await
            .unwrap();
        let first = out.content.lines().next().unwrap_or("").to_string();
        assert!(first.starts_with("HTTP 200 \u{b7} text/html"), "{first}");
        assert!(first.contains(&format!("{base}/page")), "{first}");
        assert!(first.contains("title \"Synthetic Shop\""), "{first}");
        assert!(!first.contains("redirected"), "{first}");

        let hop = format!("{base}/hop");
        let out = tool.call(json!({"url": hop}), &ctx()).await.unwrap();
        let first = out.content.lines().next().unwrap_or("").to_string();
        assert!(
            first.contains(&format!("{base}/page (redirected from {hop})")),
            "{first}"
        );

        // The daemon's entry point carries the same line.
        let outcome = OutcomeTool::execute(
            &tool,
            &json!({"url": hop}).to_string(),
            &ToolCallContext::default(),
        )
        .await
        .unwrap();
        let first = outcome.output.lines().next().unwrap_or("").to_string();
        assert!(first.starts_with("HTTP 200"), "{first}");
        assert!(first.contains("redirected from"), "{first}");
        assert!(first.contains("Synthetic Shop"), "{first}");
    }

    #[tokio::test]
    async fn fetches_html_as_markdown() {
        let base = serve(vec![
            (
                "/page",
                "200 OK",
                "text/html; charset=utf-8",
                "<html><head><title>T</title><script>evil()</script></head><body><h1>Synthetic Title</h1><p>Hello <b>world</b>.</p></body></html>".into(),
            ),
            ("/big", "200 OK", "text/plain", "x".repeat(5000)),
            ("/gone", "404 Not Found", "text/html", "<p>no such page</p>".into()),
            ("/away", "302 Found", "text/plain", "http://elsewhere.invalid/".into()),
            ("/img", "200 OK", "image/png", "\u{1}PNG".into()),
        ])
        .await;
        let tool = WebFetch::new()
            .without_proxy()
            .allow_private_hosts()
            .max_chars(1000);

        let url = format!("{base}/page");
        let out = tool.call(json!({"url": url}), &ctx()).await.unwrap();
        assert!(!out.is_error, "{}", out.content);
        assert!(out.content.contains("Hello"), "{}", out.content);
        assert!(!out.content.contains("evil"));
        assert_eq!(out.details["status"], 200);

        let out = tool
            .call(json!({"url": format!("{base}/big")}), &ctx())
            .await
            .unwrap();
        assert!(
            out.content
                .contains("[Content truncated to 1000 characters. Fetch again with offset=1000")
        );
        assert_eq!(out.details["truncated"], true);

        let out = tool
            .call(json!({"url": format!("{base}/gone")}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error);
        assert_eq!(out.details["status"], 404);
        assert!(out.content.contains("404") && out.content.contains("no such page"));

        let out = tool
            .call(json!({"url": format!("{base}/away")}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error && out.content.contains("elsewhere.invalid"));
        assert_eq!(out.details["status"], 302);

        let out = tool
            .call(json!({"url": format!("{base}/img")}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error && out.content.contains("image/png"));
    }

    /// Both entry points build the same reply: a PDF and a PNG are
    /// described, not decoded into junk text; a long page continues at
    /// `offset`; a JavaScript-only page says extraction failed.
    #[tokio::test]
    async fn both_paths_describe_binary_and_continue_at_an_offset() {
        let js_only = format!(
            "<html><head><script>{}</script></head><body><div id=\"root\"></div></body></html>",
            "z".repeat(20_000)
        );
        let base = serve(vec![
            (
                "/doc",
                "200 OK",
                "application/pdf",
                "%PDF-1.7 synthetic".into(),
            ),
            ("/img", "200 OK", "image/png", "\u{1}PNG".into()),
            (
                "/long",
                "200 OK",
                "text/plain",
                format!("{}{}", "a".repeat(1000), "b".repeat(500)),
            ),
            ("/spa", "200 OK", "text/html", js_only),
        ])
        .await;
        let tool = WebFetch::new()
            .without_proxy()
            .allow_private_hosts()
            .max_chars(1000);
        let facts = crate::semantics::ToolCallContext::default();
        let daemon = |args: Value| {
            let tool = &tool;
            let facts = &facts;
            async move {
                OutcomeTool::execute(tool, &args.to_string(), facts)
                    .await
                    .unwrap()
            }
        };

        let pdf = daemon(json!({"url": format!("{base}/doc")})).await.output;
        assert!(
            pdf.contains("PDF document") && pdf.contains("read_file"),
            "{pdf}"
        );
        assert!(!pdf.contains("%PDF"), "{pdf}");
        let out = tool
            .call(json!({"url": format!("{base}/doc")}), &ctx())
            .await
            .unwrap();
        assert!(out.is_error && out.content.contains("PDF document"));

        let png = daemon(json!({"url": format!("{base}/img")})).await.output;
        assert!(
            png.contains("binary content, 4 bytes, type image/png"),
            "{png}"
        );

        let first = daemon(json!({"url": format!("{base}/long")})).await;
        let info = first.metadata.truncation.expect("cut");
        assert_eq!((info.shown_chars, info.total_chars), (1000, 1500));
        assert!(info.remediation_hint.unwrap().contains("offset=1000"));
        let rest = daemon(json!({"url": format!("{base}/long"), "offset": 1000})).await;
        assert!(rest.output.ends_with(&"b".repeat(500)), "{}", rest.output);
        assert!(!rest.output.contains('a'.to_string().repeat(2).as_str()));
        assert!(rest.metadata.truncation.is_none());
        let out = tool
            .call(
                json!({"url": format!("{base}/long"), "offset": 1000}),
                &ctx(),
            )
            .await
            .unwrap();
        assert!(out.content.contains(&"b".repeat(500)) && !out.content.contains("aa"));

        let spa = daemon(json!({"url": format!("{base}/spa")})).await.output;
        assert!(spa.contains("EXTRACTION FAILED"), "{spa}");
    }

    #[tokio::test]
    async fn private_hosts_are_blocked_by_default() {
        let base = serve(vec![("/page", "200 OK", "text/plain", "private".into())]).await;
        let tool = WebFetch::new().without_proxy();
        let out = tool
            .call(json!({"url": format!("{base}/page")}), &ctx())
            .await
            .unwrap();
        assert!(
            out.is_error && out.content.contains("Request blocked"),
            "{}",
            out.content
        );
        assert!(!out.content.contains("private\n"));
    }

    #[tokio::test]
    async fn a_cross_host_redirect_is_reported_not_followed() {
        let base = serve(vec![(
            "/away",
            "302 Found",
            "text/plain",
            "http://localhost:9/landing".into(),
        )])
        .await;
        let tool = WebFetch::new().without_proxy().allow_private_hosts();
        let out = tool
            .call(json!({"url": format!("{base}/away")}), &ctx())
            .await
            .unwrap();
        assert!(
            out.is_error && out.content.contains("localhost:9"),
            "{}",
            out.content
        );
    }

    #[tokio::test]
    async fn mandate_execution_never_follows_a_redirect() {
        let base = serve(vec![
            ("/away", "302 Found", "text/plain", "/landing".into()),
            ("/landing", "200 OK", "text/html", "<p>arrived</p>".into()),
        ])
        .await;
        let tool = WebFetch::new()
            .without_proxy()
            .allow_private_hosts()
            .follow_public_redirects();
        let arguments = json!({"url": format!("{base}/away")}).to_string();

        let followed = tool
            .execute(&arguments, &ToolCallContext::default())
            .await
            .unwrap();
        assert!(followed.output.contains("arrived"), "{}", followed.output);

        let facts = ToolCallContext {
            mandate_execution: true,
            ..ToolCallContext::default()
        };
        let stopped = tool.execute(&arguments, &facts).await.unwrap();
        assert!(stopped.output.contains("HTTP 302"), "{}", stopped.output);
    }

    #[test]
    fn metadata_endpoints_are_refused_for_every_reach() {
        for target in [
            "169.254.169.254:80",
            "metadata.google.internal:80",
            "metadata.goog:443",
            "fe80::1:80",
            "fd00:ec2::254:80",
        ] {
            for reach in [
                NetworkReach::Any,
                NetworkReach::PublicAndLoopback,
                NetworkReach::PublicOnly,
            ] {
                assert!(
                    network_refusal(reach, target).is_some(),
                    "{target} {reach:?}"
                );
            }
        }
    }

    #[test]
    fn reach_decides_private_and_loopback() {
        use NetworkReach::*;
        // A shell still reaches the owner's own network and internal names.
        for target in ["10.0.0.5:22", "localhost:3000", "db.internal:5432"] {
            assert_eq!(network_refusal(Any, target), None, "{target}");
        }
        assert_eq!(network_refusal(PublicAndLoopback, "localhost:3000"), None);
        assert_eq!(
            network_refusal(PublicAndLoopback, "shop.localhost:80"),
            None
        );
        assert!(network_refusal(PublicAndLoopback, "10.0.0.5:80").is_some());
        assert!(network_refusal(PublicOnly, "localhost:3000").is_some());
        assert!(network_refusal(PublicOnly, "::1:80").is_some());
        assert_eq!(network_refusal(PublicOnly, "8.8.8.8:443"), None);
    }

    #[test]
    fn a_refusal_names_the_class_not_the_target() {
        let label = network_refusal(NetworkReach::PublicOnly, "10.1.2.3:8443").unwrap();
        assert!(!label.contains("10.1.2.3"));
    }

    #[test]
    fn validates_scheme_and_declares_host() {
        let tool = WebFetch::new();
        assert!(
            tool.validate(&json!({"url": "file:///etc/passwd"}))
                .is_err()
        );
        assert!(tool.validate(&json!({"url": "not a url"})).is_err());
        assert!(
            tool.validate(&json!({"url": "https://example.com/x"}))
                .is_ok()
        );
        assert_eq!(
            tool.access(&json!({"url": "https://docs.example.com/a?b=c"}))
                .hosts,
            vec!["docs.example.com"]
        );
        assert!(tool.annotations().read_only);
    }
}

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

    /// Every URL the shared classifier marks blocked must ALSO be rejected by
    /// `validate_url_for_ssrf`, and the class must match the expected category.
    /// This is the single-source-of-truth invariant: the browser tool's
    /// host-class classifier and the web_fetch validator never diverge.
    fn assert_blocked(url: &str, expected: BlockedHostClass) {
        let class = classify_blocked_host(url);
        assert_eq!(
            class,
            Some(expected),
            "expected {url} blocked as {expected:?}, got {class:?}"
        );
        assert!(
            validate_url_for_ssrf(url).is_err(),
            "validate_url_for_ssrf must also reject {url}"
        );
        // Secret-safety: the label must never echo the URL.
        let label = expected.label();
        assert!(
            !url.contains(label) || label.is_empty(),
            "label must be a fixed class string, not derived from the url"
        );
    }

    fn assert_allowed(url: &str) {
        assert_eq!(
            classify_blocked_host(url),
            None,
            "{url} should be allowed (public)"
        );
    }

    #[test]
    fn loopback_is_blocked() {
        assert_blocked("http://127.0.0.1/", BlockedHostClass::Loopback);
        assert_blocked("http://127.0.0.1:8080/admin", BlockedHostClass::Loopback);
        assert_blocked("http://127.5.6.7/", BlockedHostClass::Loopback); // 127/8
        assert_blocked("http://localhost/", BlockedHostClass::Loopback);
        assert_blocked("http://[::1]/", BlockedHostClass::Loopback);
        assert_blocked("http://0.0.0.0/", BlockedHostClass::Loopback);
    }

    #[test]
    fn rfc1918_private_ranges_are_blocked() {
        assert_blocked("http://10.0.0.1/", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://10.255.255.255/", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://172.16.0.1/", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://172.31.255.255/", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://192.168.1.1/", BlockedHostClass::PrivateNetwork);
        // CGNAT shared space.
        assert_blocked("http://100.64.0.1/", BlockedHostClass::PrivateNetwork);
    }

    #[test]
    fn link_local_and_cloud_metadata_are_blocked() {
        assert_blocked(
            "http://169.254.169.254/latest/meta-data/",
            BlockedHostClass::LinkLocalMetadata,
        );
        assert_blocked("http://169.254.0.1/", BlockedHostClass::LinkLocalMetadata);
        assert_blocked(
            "http://metadata.google.internal/",
            BlockedHostClass::LinkLocalMetadata,
        );
        assert_blocked(
            "http://anything.internal/",
            BlockedHostClass::LinkLocalMetadata,
        );
    }

    #[test]
    fn ipv4_mapped_ipv6_is_blocked_by_embedded_class() {
        // ::ffff:127.0.0.1 → loopback
        assert_blocked("http://[::ffff:127.0.0.1]/", BlockedHostClass::Loopback);
        // ::ffff:10.0.0.1 → private network
        assert_blocked(
            "http://[::ffff:10.0.0.1]/",
            BlockedHostClass::PrivateNetwork,
        );
        // ::ffff:169.254.169.254 → link-local/metadata
        assert_blocked(
            "http://[::ffff:169.254.169.254]/",
            BlockedHostClass::LinkLocalMetadata,
        );
    }

    #[test]
    fn ipv6_unique_local_and_link_local_are_blocked() {
        assert_blocked("http://[fc00::1]/", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://[fd12:3456::1]/", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://[fe80::1]/", BlockedHostClass::LinkLocalMetadata);
    }

    #[test]
    fn disallowed_schemes_are_blocked() {
        assert_blocked("file:///etc/passwd", BlockedHostClass::DisallowedScheme);
        assert_blocked("ftp://example.com/", BlockedHostClass::DisallowedScheme);
        assert_blocked(
            "data:text/html,<h1>hi</h1>",
            BlockedHostClass::DisallowedScheme,
        );
    }

    #[test]
    fn malformed_urls_are_blocked() {
        assert_eq!(
            classify_blocked_host("not a url"),
            Some(BlockedHostClass::Malformed)
        );
        assert_eq!(
            classify_blocked_host("http://"),
            Some(BlockedHostClass::Malformed)
        );
    }

    #[test]
    fn resolve_path_classifies_private_targets() {
        // A raw-IP host with an explicit port exercises the resolve→classify
        // path (to_socket_addrs succeeds and yields the embedded IP). This is
        // the same code path a DNS-rebinding host would hit when it resolves to
        // a private address — deterministic in CI because no real DNS is needed.
        assert_blocked("http://10.1.2.3:8443/x", BlockedHostClass::PrivateNetwork);
        assert_blocked("http://127.0.0.1:9000/x", BlockedHostClass::Loopback);
        // An unresolvable non-IP host is NOT falsely reported as blocked here —
        // the validator lets such a request fail naturally at connect time. This
        // documents that pure DNS-rebinding (public name → private A-record at
        // request time) is only catchable at request time (see browser
        // request-interception deferral), not by this pre-flight check.
        assert_eq!(
            classify_blocked_host("http://nonexistent-host.invalid/"),
            None,
            "unresolvable host is not pre-flight blocked (request-time only)"
        );
    }

    #[test]
    fn public_urls_are_allowed() {
        assert_allowed("https://example.com/");
        assert_allowed("https://www.rust-lang.org/learn");
        assert_allowed("http://93.184.216.34/"); // example.com public IP
        assert_allowed("https://8.8.8.8/");
    }

    #[test]
    fn labels_are_fixed_and_leak_no_data() {
        // Every label is a fixed class string with no caller data.
        for class in [
            BlockedHostClass::Loopback,
            BlockedHostClass::PrivateNetwork,
            BlockedHostClass::LinkLocalMetadata,
            BlockedHostClass::DisallowedScheme,
            BlockedHostClass::Malformed,
            BlockedHostClass::OtherReserved,
        ] {
            let label = class.label();
            assert!(!label.is_empty());
            // No URL syntax, no scheme, no query, no credentials.
            for forbidden in ["://", "?", "=", "@", "127.", "169.254", "secret"] {
                assert!(
                    !label.contains(forbidden),
                    "label {label:?} must not contain {forbidden:?}"
                );
            }
        }
    }
}

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

    #[test]
    fn truncated_fetch_carries_instructional_notice() {
        let text = "a".repeat(120);
        let (out, truncation) = format_fetch_result("https://example.com/page", &text, 50);
        assert!(out.contains("Content from https://example.com/page"));
        // The notice is metadata, not embedded text — text-scanning consumers
        // (classifiers, summaries) must see clean output.
        assert!(!out.contains("OUTPUT TRUNCATED"));
        assert!(!out.contains("[Truncated]"));
        let info = truncation.expect("truncation info");
        assert_eq!(info.total_chars, 120);
        assert_eq!(info.shown_chars, 50);
        // Remediation hint must be fetch-flavored, not terminal-flavored, and
        // preserved verbatim.
        let hint = info.remediation_hint.expect("remediation hint");
        assert!(hint.contains("max_chars"));
        assert!(!hint.contains("wc -l"));
    }

    /// A synthetic download page: a short release list, one long prose
    /// section and a lot of navigation, shaped like real listing pages.
    fn listing_page() -> String {
        let nav: String = (0..400)
            .map(|i| format!("<li><a href=\"/nav/{i}\">Section {i} overview</a></li>"))
            .collect();
        let prose: String = (0..12)
            .map(|i| {
                format!(
                    "<p>Paragraph {i} explains how release artifacts are signed and how a \
                     careful user can check that a downloaded installer is genuine before \
                     running it on their machine, step by step.</p>"
                )
            })
            .collect();
        format!(
            "<html><body><nav><ul>{nav}</ul></nav>\
             <div class=\"releases\"><h2>Downloads</h2><ul>\
             <li><a href=\"/r/9.4.2\">Download Acme 9.4.2</a></li>\
             <li><a href=\"/r/9.4.1\">Acme 9.4.1</a></li></ul></div>\
             <div class=\"article\"><h2>Verifying downloads</h2>{prose}</div>\
             </body></html>"
        )
    }

    /// A page whose one heading is its title keeps that heading: readability
    /// drops it, and the model would fetch the page again to find it.
    #[test]
    fn the_page_heading_survives_extraction() {
        // Shaped like example.com: a title, no heading, one paragraph.
        let html = "<!doctype html><html lang=en><head><meta charset=utf-8>\
                    <title>Example Domain</title><style>body{margin:auto}</style></head>\
                    <body><p>This domain is for use in synthetic documentation examples \
                    without needing permission.</p><script src=/s.js></script></body></html>";
        let text = extract_page_text(html, "https://example.com/");
        let first = text
            .lines()
            .find(|line| !line.trim().is_empty())
            .unwrap_or("");
        assert!(first.contains("Example Domain"), "{text}");
        assert!(text.contains("synthetic documentation"), "{text}");
        assert!(!text.contains("isReaderPage"), "{text}");
        // A heading in the body stays apart from the paragraph after it, and
        // is not added again.
        let html = "<html><head><title>Example Domain</title></head><body><div>\
                    <h1>Example Domain</h1><p>This domain is for use in synthetic \
                    documentation examples without needing permission.</p></div></body></html>";
        let text = extract_page_text(html, "https://example.com/");
        assert!(text.contains("# Example Domain"), "{text}");
        assert!(text.matches("Example Domain").count() <= 2, "{text}");
        assert!(!text.contains("DomainThis"), "{text}");
        // A title only, and a heading with markup inside.
        assert_eq!(
            page_heading("<title> Synthetic  Page </title><p>x</p>").as_deref(),
            Some("Synthetic Page")
        );
        assert_eq!(
            page_heading("<h10>no</h10><h1 class=\"t\">A <b>bold</b> &amp; plain</h1>").as_deref(),
            Some("A bold & plain")
        );
        assert_eq!(page_heading("<p>nothing</p>"), None);
    }

    #[test]
    fn listing_page_keeps_content_readability_would_drop() {
        let text = extract_page_text(&listing_page(), "https://acme.example/downloads/");
        assert!(
            text.contains("Download Acme 9.4.2"),
            "{}",
            &text[..text.len().min(400)]
        );
    }

    #[test]
    fn long_article_still_uses_readability() {
        let nav: String = (0..200)
            .map(|i| format!("<li><a href=\"/nav/{i}\">Menu entry {i}</a></li>"))
            .collect();
        let body: String = (0..120)
            .map(|i| {
                format!(
                    "<p>Paragraph {i} of a long synthetic article about mountain cities, \
                     their climate, history and the people who live there today.</p>"
                )
            })
            .collect();
        let html = format!(
            "<html><body><nav><ul>{nav}</ul></nav><article><h1>Mountain cities</h1>{body}</article></body></html>"
        );
        let text = extract_page_text(&html, "https://wiki.example/mountain");
        assert!(text.contains("Paragraph 119"));
        assert!(
            !text.contains("Menu entry 150"),
            "navigation leaked into an article"
        );
    }

    #[test]
    fn untruncated_fetch_has_no_notice() {
        let (out, truncation) = format_fetch_result("https://example.com", "short content", 1000);
        assert!(out.contains("short content"));
        assert!(!out.contains("OUTPUT TRUNCATED"));
        assert!(truncation.is_none());
    }

    #[test]
    fn truncation_respects_char_boundaries() {
        // 4-byte emoji straddling the cap must not panic.
        let text = format!("{}🦀🦀🦀", "x".repeat(49));
        let (_out, truncation) = format_fetch_result("https://example.com", &text, 51);
        assert!(truncation.is_some());
    }

    #[test]
    fn fetch_result_truncation_is_metadata_not_text() {
        let long = "y".repeat(9000);
        let (text, truncation) = format_fetch_result("https://example.com", &long, 4000);
        assert!(!text.contains("OUTPUT TRUNCATED"));
        let info = truncation.expect("truncation info");
        assert_eq!(info.total_chars, 9000);
        assert!(
            info.remediation_hint
                .as_deref()
                .unwrap_or("")
                .contains("max_chars")
        );
    }
}

#[cfg(test)]
mod extraction_tests {
    use super::*;
    use crate::semantics::ToolSemantics;

    /// Mimics the observed Wikipedia failure: a large inline <script> block
    /// ahead of the real content leaked into the "extracted" text and
    /// consumed the whole max_chars window.
    fn script_heavy_page() -> String {
        format!(
            "<html><head><title>Ecuador national football team - Wikipedia</title>\
             <script>(function(){{var className=\"client-js vector-feature-language-{}\";}})();</script>\
             <style>.mw-parser{{display:none}}{}</style></head>\
             <body><h1>Squad</h1><p>{}</p>\
             <table><tr><td>Willian Pacho</td></tr><tr><td>Moises Caicedo</td></tr></table>\
             </body></html>",
            "x".repeat(8_000),
            "y".repeat(8_000),
            "The current squad was announced ahead of the tournament. ".repeat(20),
        )
    }

    #[test]
    fn script_and_style_blocks_never_reach_the_model() {
        let (reply, _truncation) = build_fetch_reply(
            "https://en.wikipedia.org/wiki/X",
            &script_heavy_page(),
            2_000,
        );
        assert!(
            !reply.contains("var className"),
            "script body leaked: {}",
            reply
        );
        assert!(
            !reply.contains("display:none"),
            "style body leaked: {}",
            reply
        );
        assert!(reply.contains("Willian Pacho") || reply.contains("current squad"));
    }

    #[test]
    fn near_empty_extraction_gets_instructional_notice() {
        // Big page, no readable text — the JS-rendered-page signature.
        let html = format!(
            "<html><head><script>{}</script></head><body><div id=\"root\"></div></body></html>",
            "z".repeat(20_000)
        );
        let (reply, truncation) = build_fetch_reply("https://spa.example.com", &html, 20_000);
        assert!(
            reply.contains("EXTRACTION FAILED"),
            "missing notice: {}",
            reply
        );
        assert!(reply.contains("different source"));
        // Must not pretend the page was read.
        assert!(!reply.contains("OUTPUT TRUNCATED"));
        assert!(truncation.is_none());
    }

    #[test]
    fn normal_page_has_no_extraction_notice() {
        let (reply, _truncation) =
            build_fetch_reply("https://example.com", &script_heavy_page(), 20_000);
        assert!(!reply.contains("EXTRACTION FAILED"));
    }

    #[test]
    fn small_thin_pages_are_not_flagged() {
        // A genuinely tiny page is not an extraction failure.
        let (reply, _truncation) = build_fetch_reply(
            "https://example.com",
            "<html><body><p>hi</p></body></html>",
            20_000,
        );
        assert!(!reply.contains("EXTRACTION FAILED"));
    }

    #[test]
    fn append_capped_respects_byte_ceiling() {
        // Under the cap: whole chunk appended, not truncated.
        let mut buf = Vec::new();
        assert!(!append_capped(&mut buf, b"hello", 100));
        assert_eq!(buf, b"hello");

        // Exactly at the cap: still appended fully, not truncated.
        let mut buf = vec![0u8; 8];
        assert!(!append_capped(&mut buf, &[1u8, 2u8], 10));
        assert_eq!(buf.len(), 10);

        // Over the cap: partial copy up to the ceiling, truncated reported.
        let mut buf = vec![0u8; 8];
        assert!(append_capped(&mut buf, &[1, 2, 3, 4], 10));
        assert_eq!(buf.len(), 10);

        // Already full: nothing copied, truncation reported.
        let mut buf = vec![0u8; 10];
        assert!(append_capped(&mut buf, b"x", 10));
        assert_eq!(buf.len(), 10);
    }

    #[test]
    fn append_capped_truncation_is_utf8_safe() {
        // "€" is 3 bytes (E2 82 AC); capping at 3 keeps "ab" + 1 byte of it.
        // Decoding the capped bytes with from_utf8_lossy must not panic.
        let mut buf = Vec::new();
        assert!(append_capped(&mut buf, "ab€".as_bytes(), 3));
        assert_eq!(buf.len(), 3);
        let s = String::from_utf8_lossy(&buf);
        assert!(s.starts_with("ab"));
    }

    #[test]
    fn web_fetch_declares_egress_host() {
        let tool = WebFetch::new();
        let effects =
            tool.call_effects(&json!({"url": "https://Docs.Example.Invalid/guide"}).to_string());
        assert!(effects.complete);
        assert_eq!(
            effects.keys,
            vec![aidaemon_core::EffectKey::egress(
                "https",
                "docs.example.invalid",
                None
            )]
        );
        let bad = tool.call_effects(&json!({"url": "::"}).to_string());
        assert!(!bad.complete);
    }
}