Skip to main content

aidaemon_tools/
web.rs

1//! `web_fetch`: GET a page and return its readable text.
2//!
3//! Every request, and every redirect hop, is checked against the
4//! private-network policy ([`validate_url_for_ssrf`]). By default redirects
5//! stay on the requested host, so the host declared in [`Tool::access`] is
6//! the only host contacted; [`WebFetch::follow_public_redirects`] allows
7//! other public hosts.
8
9use std::collections::HashMap;
10use std::io::Cursor;
11use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, ToSocketAddrs};
12use std::sync::OnceLock;
13use std::time::Duration;
14
15use async_trait::async_trait;
16use reqwest::redirect::Policy;
17use reqwest::{Client, StatusCode, Url};
18use serde::Deserialize;
19use serde_json::{Value, json};
20
21use aidaemon_core::{
22    AccessManifest, CallEffects, EffectClass, EffectKey, Hook, HookContext, Tool, ToolAnnotations,
23    ToolCall, ToolContext, ToolDecision, ToolInfo, ToolOutput, ToolResult,
24};
25
26use crate::fs::ToolText;
27use crate::outcome::{OutcomeTool, spec_of};
28use crate::semantics::{
29    NetworkReach, ToolCallContext, ToolCallMetadata, ToolCallOutcome, ToolCallSemantics,
30    ToolCapabilities, ToolTargetHintKind, ToolVerificationMode,
31};
32use crate::util::{fail, parse_args, truncate_chars};
33
34const DEFAULT_MAX_CHARS: usize = 20_000;
35const MAX_MAX_CHARS: usize = 50_000;
36
37/// Hard cap on response-body bytes buffered from a web fetch/search. The
38/// model-facing output is already bounded (extracted-text char limit / result
39/// count); this only bounds *transient memory* against a pathologically large
40/// or mislabeled response that `.text()`/`.json()` would otherwise buffer whole.
41pub const MAX_FETCH_BODY_BYTES: usize = 10 * 1024 * 1024;
42
43/// Append `chunk` to `buf` without exceeding `max_bytes`. Returns true if the
44/// chunk was (partially) dropped because the cap was reached. Truncation is on a
45/// raw byte boundary, so callers must decode with `from_utf8_lossy`.
46pub fn append_capped(buf: &mut Vec<u8>, chunk: &[u8], max_bytes: usize) -> bool {
47    let remaining = max_bytes.saturating_sub(buf.len());
48    if chunk.len() > remaining {
49        buf.extend_from_slice(&chunk[..remaining]);
50        true
51    } else {
52        buf.extend_from_slice(chunk);
53        false
54    }
55}
56
57/// Stream a response body into memory, capping at `max_bytes` to avoid unbounded
58/// allocation. Returns the collected bytes and whether the body was truncated.
59pub async fn read_body_capped(
60    resp: reqwest::Response,
61    max_bytes: usize,
62) -> reqwest::Result<(Vec<u8>, bool)> {
63    let mut resp = resp;
64    let mut buf: Vec<u8> = Vec::new();
65    let mut truncated = false;
66    while let Some(chunk) = resp.chunk().await? {
67        if append_capped(&mut buf, &chunk, max_bytes) {
68            truncated = true;
69            break;
70        }
71    }
72    Ok((buf, truncated))
73}
74
75/// Validates a URL for SSRF vulnerabilities.
76/// Returns Ok(()) if the URL is safe to fetch, Err with a message otherwise.
77pub fn validate_url_for_ssrf(url: &str) -> Result<(), String> {
78    let parsed = reqwest::Url::parse(url).map_err(|e| format!("Invalid URL: {}", e))?;
79
80    // 1. Only allow http and https schemes
81    match parsed.scheme() {
82        "http" | "https" => {}
83        scheme => {
84            return Err(format!(
85                "Blocked scheme '{}': only http/https allowed",
86                scheme
87            ));
88        }
89    }
90
91    // 2. Must have a host
92    let host = parsed
93        .host_str()
94        .ok_or_else(|| "URL must have a host".to_string())?;
95
96    // 3. Block known dangerous hostnames
97    let host_lower = host.to_lowercase();
98    const BLOCKED_HOSTS: &[&str] = &[
99        "localhost",
100        "127.0.0.1",
101        "::1",
102        "[::1]",
103        "0.0.0.0",
104        "metadata.google.internal",
105        "metadata.goog",
106        "169.254.169.254",
107    ];
108    for blocked in BLOCKED_HOSTS {
109        if host_lower == *blocked {
110            return Err(format!("Blocked host: {}", host));
111        }
112    }
113
114    // 4. Block hosts that look like internal addresses
115    if host_lower.ends_with(".internal")
116        || host_lower.ends_with(".local")
117        || host_lower.ends_with(".localhost")
118    {
119        return Err(format!("Blocked internal hostname: {}", host));
120    }
121
122    // 5. Resolve the hostname and check all IP addresses
123    let port = parsed.port().unwrap_or(match parsed.scheme() {
124        "https" => 443,
125        _ => 80,
126    });
127
128    // Try to resolve the hostname
129    let socket_addr = format!("{}:{}", host, port);
130    match socket_addr.to_socket_addrs() {
131        Ok(addrs) => {
132            for addr in addrs {
133                if is_blocked_ip(addr.ip()) {
134                    return Err(format!(
135                        "Blocked IP address {} (resolved from {})",
136                        addr.ip(),
137                        host
138                    ));
139                }
140            }
141        }
142        Err(_) => {
143            // If we can't resolve, it might be a raw IP - try parsing it
144            if let Ok(ip) = host.parse::<IpAddr>()
145                && is_blocked_ip(ip)
146            {
147                return Err(format!("Blocked IP address: {}", ip));
148            }
149            // If resolution fails and it's not an IP, let the request fail naturally
150        }
151    }
152
153    Ok(())
154}
155
156/// Refuses at connection time any name that resolves to a blocked address.
157/// The check before a request and the connection look a name up separately,
158/// so a name could answer with a public address first and a private one next.
159pub(crate) struct PublicOnlyResolver;
160
161impl reqwest::dns::Resolve for PublicOnlyResolver {
162    fn resolve(&self, name: reqwest::dns::Name) -> reqwest::dns::Resolving {
163        let host = name.as_str().to_string();
164        Box::pin(async move {
165            let addrs: Vec<std::net::SocketAddr> =
166                tokio::net::lookup_host((host.as_str(), 0)).await?.collect();
167            if let Some(blocked) = addrs.iter().find(|addr| is_blocked_ip(addr.ip())) {
168                let reason = format!("{host} resolves to blocked address {}", blocked.ip());
169                return Err(
170                    std::io::Error::new(std::io::ErrorKind::PermissionDenied, reason).into(),
171                );
172            }
173            Ok(Box::new(addrs.into_iter()) as reqwest::dns::Addrs)
174        })
175    }
176}
177
178/// Check if an IP address is in a blocked range (private, loopback, link-local, etc.)
179fn is_blocked_ip(ip: IpAddr) -> bool {
180    match ip {
181        IpAddr::V4(ipv4) => is_blocked_ipv4(ipv4),
182        IpAddr::V6(ipv6) => is_blocked_ipv6(ipv6),
183    }
184}
185
186fn is_blocked_ipv4(ip: Ipv4Addr) -> bool {
187    let octets = ip.octets();
188
189    // Loopback: 127.0.0.0/8
190    if octets[0] == 127 {
191        return true;
192    }
193
194    // Private: 10.0.0.0/8
195    if octets[0] == 10 {
196        return true;
197    }
198
199    // Private: 172.16.0.0/12 (172.16.0.0 - 172.31.255.255)
200    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
201        return true;
202    }
203
204    // Private: 192.168.0.0/16
205    if octets[0] == 192 && octets[1] == 168 {
206        return true;
207    }
208
209    // Link-local: 169.254.0.0/16 (includes cloud metadata at 169.254.169.254)
210    if octets[0] == 169 && octets[1] == 254 {
211        return true;
212    }
213
214    // Broadcast: 255.255.255.255
215    if ip == Ipv4Addr::BROADCAST {
216        return true;
217    }
218
219    // Unspecified: 0.0.0.0
220    if ip == Ipv4Addr::UNSPECIFIED {
221        return true;
222    }
223
224    // Documentation ranges (TEST-NET): 192.0.2.0/24, 198.51.100.0/24, 203.0.113.0/24
225    if (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
226        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
227        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
228    {
229        return true;
230    }
231
232    // Shared address space (CGNAT): 100.64.0.0/10
233    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
234        return true;
235    }
236
237    false
238}
239
240fn is_blocked_ipv6(ip: Ipv6Addr) -> bool {
241    // Loopback: ::1
242    if ip.is_loopback() {
243        return true;
244    }
245
246    // Unspecified: ::
247    if ip.is_unspecified() {
248        return true;
249    }
250
251    // IPv4-mapped addresses: check the embedded IPv4
252    if let Some(ipv4) = ip.to_ipv4_mapped() {
253        return is_blocked_ipv4(ipv4);
254    }
255
256    // Link-local: fe80::/10
257    let segments = ip.segments();
258    if (segments[0] & 0xffc0) == 0xfe80 {
259        return true;
260    }
261
262    // Unique local addresses (private): fc00::/7
263    if (segments[0] & 0xfe00) == 0xfc00 {
264        return true;
265    }
266
267    false
268}
269
270/// A coarse classification of *why* a host is blocked by the private-network
271/// policy. The whole point of this enum is **secret safety**: it carries only a
272/// fixed, low-cardinality category — never the URL, host, path, query, or
273/// credentials. Surfacing `class.label()` in an error message therefore cannot
274/// leak any caller-supplied data.
275///
276/// Shared by `web_fetch` and the `browser` tool so both name a blocked request
277/// the same way.
278#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum BlockedHostClass {
280    /// Loopback (`127.0.0.0/8`, `::1`, `localhost`, `0.0.0.0`).
281    Loopback,
282    /// RFC1918 / unique-local private ranges (`10/8`, `172.16/12`, `192.168/16`,
283    /// `fc00::/7`) and CGNAT shared space (`100.64.0.0/10`).
284    PrivateNetwork,
285    /// Link-local, including the cloud metadata endpoint (`169.254.0.0/16`,
286    /// notably `169.254.169.254`; `fe80::/10`; `*.internal`/metadata hostnames).
287    LinkLocalMetadata,
288    /// A non-http(s) scheme (e.g. `file:`, `ftp:`, `data:`).
289    DisallowedScheme,
290    /// Malformed URL or a URL with no host.
291    Malformed,
292    /// Other reserved/blocked address (broadcast, documentation/TEST-NET ranges,
293    /// `.local` hostnames) that isn't one of the more specific classes above.
294    OtherReserved,
295}
296
297impl BlockedHostClass {
298    /// A short, human-readable label naming ONLY the host class. Safe to embed
299    /// in a user/LLM-facing error: it contains no caller data.
300    pub fn label(self) -> &'static str {
301        match self {
302            BlockedHostClass::Loopback => "loopback address",
303            BlockedHostClass::PrivateNetwork => "private network",
304            BlockedHostClass::LinkLocalMetadata => "link-local/metadata address",
305            BlockedHostClass::DisallowedScheme => "disallowed scheme",
306            BlockedHostClass::Malformed => "malformed URL",
307            BlockedHostClass::OtherReserved => "reserved/blocked address",
308        }
309    }
310}
311
312/// Classify a blocked IPv4 address into a [`BlockedHostClass`]. Mirrors
313/// [`is_blocked_ipv4`] exactly (same ranges, same order) but reports the
314/// category instead of a bool. Returns `None` for a public address.
315fn classify_blocked_ipv4(ip: Ipv4Addr) -> Option<BlockedHostClass> {
316    let octets = ip.octets();
317
318    // Loopback: 127.0.0.0/8
319    if octets[0] == 127 {
320        return Some(BlockedHostClass::Loopback);
321    }
322    // Unspecified: 0.0.0.0 — treated as loopback-class (targets the local host).
323    if ip == Ipv4Addr::UNSPECIFIED {
324        return Some(BlockedHostClass::Loopback);
325    }
326    // Private: 10.0.0.0/8
327    if octets[0] == 10 {
328        return Some(BlockedHostClass::PrivateNetwork);
329    }
330    // Private: 172.16.0.0/12
331    if octets[0] == 172 && (16..=31).contains(&octets[1]) {
332        return Some(BlockedHostClass::PrivateNetwork);
333    }
334    // Private: 192.168.0.0/16
335    if octets[0] == 192 && octets[1] == 168 {
336        return Some(BlockedHostClass::PrivateNetwork);
337    }
338    // Shared address space (CGNAT): 100.64.0.0/10
339    if octets[0] == 100 && (64..=127).contains(&octets[1]) {
340        return Some(BlockedHostClass::PrivateNetwork);
341    }
342    // Link-local: 169.254.0.0/16 (includes cloud metadata 169.254.169.254)
343    if octets[0] == 169 && octets[1] == 254 {
344        return Some(BlockedHostClass::LinkLocalMetadata);
345    }
346    // Broadcast + documentation/TEST-NET ranges.
347    if ip == Ipv4Addr::BROADCAST
348        || (octets[0] == 192 && octets[1] == 0 && octets[2] == 2)
349        || (octets[0] == 198 && octets[1] == 51 && octets[2] == 100)
350        || (octets[0] == 203 && octets[1] == 0 && octets[2] == 113)
351    {
352        return Some(BlockedHostClass::OtherReserved);
353    }
354    None
355}
356
357/// Classify a blocked IPv6 address into a [`BlockedHostClass`]. Mirrors
358/// [`is_blocked_ipv6`] (IPv4-mapped addresses are unwrapped and classified as
359/// their embedded v4 class). Returns `None` for a public address.
360fn classify_blocked_ipv6(ip: Ipv6Addr) -> Option<BlockedHostClass> {
361    if ip.is_loopback() || ip.is_unspecified() {
362        return Some(BlockedHostClass::Loopback);
363    }
364    // IPv4-mapped (::ffff:a.b.c.d) — classify by the embedded IPv4 address.
365    if let Some(ipv4) = ip.to_ipv4_mapped() {
366        return classify_blocked_ipv4(ipv4);
367    }
368    let segments = ip.segments();
369    // Link-local: fe80::/10
370    if (segments[0] & 0xffc0) == 0xfe80 {
371        return Some(BlockedHostClass::LinkLocalMetadata);
372    }
373    // Unique local (private): fc00::/7
374    if (segments[0] & 0xfe00) == 0xfc00 {
375        return Some(BlockedHostClass::PrivateNetwork);
376    }
377    None
378}
379
380fn classify_blocked_ip(ip: IpAddr) -> Option<BlockedHostClass> {
381    match ip {
382        IpAddr::V4(v4) => classify_blocked_ipv4(v4),
383        IpAddr::V6(v6) => classify_blocked_ipv6(v6),
384    }
385}
386
387/// Classify a URL against the private-network policy and, if blocked, return the
388/// host CLASS — never the URL itself.
389///
390/// This is the shared, secret-safe entry point used by the `browser` tool to
391/// build request-level block errors. It applies the SAME policy as
392/// [`validate_url_for_ssrf`] (same scheme allow-list, same blocked-host names,
393/// same IP ranges, same DNS resolution), so the two tools never diverge.
394///
395/// Returns `None` when the URL is allowed (public http/https).
396pub fn classify_blocked_host(url: &str) -> Option<BlockedHostClass> {
397    let parsed = match reqwest::Url::parse(url) {
398        Ok(u) => u,
399        Err(_) => return Some(BlockedHostClass::Malformed),
400    };
401
402    match parsed.scheme() {
403        "http" | "https" => {}
404        _ => return Some(BlockedHostClass::DisallowedScheme),
405    }
406
407    let host = match parsed.host_str() {
408        Some(h) => h,
409        None => return Some(BlockedHostClass::Malformed),
410    };
411    let host_lower = host.to_lowercase();
412
413    // Named loopback / metadata hosts (mirrors BLOCKED_HOSTS in validate_url_for_ssrf).
414    match host_lower.as_str() {
415        "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0" => {
416            return Some(BlockedHostClass::Loopback);
417        }
418        "metadata.google.internal" | "metadata.goog" | "169.254.169.254" => {
419            return Some(BlockedHostClass::LinkLocalMetadata);
420        }
421        _ => {}
422    }
423    if host_lower.ends_with(".internal") {
424        return Some(BlockedHostClass::LinkLocalMetadata);
425    }
426    if host_lower.ends_with(".local") || host_lower.ends_with(".localhost") {
427        // `.localhost` resolves to loopback; `.local` is mDNS link-local-ish but
428        // historically grouped with internal names — report as reserved.
429        if host_lower.ends_with(".localhost") {
430            return Some(BlockedHostClass::Loopback);
431        }
432        return Some(BlockedHostClass::OtherReserved);
433    }
434
435    // Resolve and classify every address the host maps to.
436    let port = parsed.port().unwrap_or(match parsed.scheme() {
437        "https" => 443,
438        _ => 80,
439    });
440    let socket_addr = format!("{}:{}", host, port);
441    match socket_addr.to_socket_addrs() {
442        Ok(addrs) => {
443            for addr in addrs {
444                if let Some(class) = classify_blocked_ip(addr.ip()) {
445                    return Some(class);
446                }
447            }
448        }
449        Err(_) => {
450            // Couldn't resolve via DNS — try parsing the host as a raw IP.
451            if let Ok(ip) = host.parse::<IpAddr>()
452                && let Some(class) = classify_blocked_ip(ip)
453            {
454                return Some(class);
455            }
456            // Unresolvable non-IP host: let the request fail naturally (matches
457            // validate_url_for_ssrf). Not classified as blocked here.
458        }
459    }
460
461    None
462}
463
464/// What the owner approves to reach a site on this computer, or `None` when
465/// `url` is not loopback-only (public, private network, metadata and malformed
466/// targets are never approvable). A dev site's name is its own key;
467/// `localhost` and IP literals are shared by every local service, so their key
468/// includes the port.
469pub fn local_site_key(url: &str) -> Option<String> {
470    if !resolves_only_to_loopback(url) {
471        return None;
472    }
473    let parsed = reqwest::Url::parse(url).ok()?;
474    let host = parsed.host_str()?.to_lowercase();
475    let shared_name = host == "localhost"
476        || host
477            .trim_matches(['[', ']'])
478            .parse::<std::net::IpAddr>()
479            .is_ok();
480    if shared_name {
481        Some(format!("{host}:{}", parsed.port_or_known_default()?))
482    } else {
483        Some(host)
484    }
485}
486
487/// Whether `url` targets this computer and nothing else: blocked as loopback,
488/// with every address its host resolves to on loopback. A name that also maps
489/// to a private or metadata address is not loopback-only.
490fn resolves_only_to_loopback(url: &str) -> bool {
491    if classify_blocked_host(url) != Some(BlockedHostClass::Loopback) {
492        return false;
493    }
494    let Ok(parsed) = reqwest::Url::parse(url) else {
495        return false;
496    };
497    let Some(host) = parsed.host_str().map(str::to_lowercase) else {
498        return false;
499    };
500    if matches!(
501        host.as_str(),
502        "localhost" | "127.0.0.1" | "::1" | "[::1]" | "0.0.0.0"
503    ) || host.ends_with(".localhost")
504    {
505        return true;
506    }
507    let Some(port) = parsed.port_or_known_default() else {
508        return false;
509    };
510    match format!("{host}:{port}").to_socket_addrs() {
511        Ok(addrs) => {
512            let mut addrs = addrs.peekable();
513            addrs.peek().is_some()
514                && addrs
515                    .all(|addr| classify_blocked_ip(addr.ip()) == Some(BlockedHostClass::Loopback))
516        }
517        // A literal IP in a form the resolver refused was classified above.
518        Err(_) => host
519            .parse::<IpAddr>()
520            .is_ok_and(|ip| classify_blocked_ip(ip) == Some(BlockedHostClass::Loopback)),
521    }
522}
523
524/// Whether `host` is a cloud metadata endpoint: by name, by address, or by
525/// what it resolves to. Narrower than [`BlockedHostClass::LinkLocalMetadata`],
526/// which also covers ordinary `*.internal` names.
527fn is_metadata_endpoint(host: &str, port: u16) -> bool {
528    let name = host.trim_end_matches('.').to_ascii_lowercase();
529    if matches!(name.as_str(), "metadata.google.internal" | "metadata.goog") {
530        return true;
531    }
532    let is_metadata_ip = |ip: IpAddr| match ip {
533        IpAddr::V4(v4) => v4.octets()[..2] == [169, 254],
534        IpAddr::V6(v6) => {
535            (v6.segments()[0] & 0xffc0) == 0xfe80
536                || v6 == Ipv6Addr::new(0xfd00, 0xec2, 0, 0, 0, 0, 0, 0x254)
537                || v6
538                    .to_ipv4_mapped()
539                    .is_some_and(|v4| v4.octets()[..2] == [169, 254])
540        }
541    };
542    if let Ok(ip) = name.parse::<IpAddr>() {
543        return is_metadata_ip(ip);
544    }
545    (name.as_str(), port)
546        .to_socket_addrs()
547        .is_ok_and(|mut addrs| addrs.any(|addr| is_metadata_ip(addr.ip())))
548}
549
550/// Why a call to `target` (`host:port`) is refused under `reach`. Names only
551/// the class of address, never the target.
552fn network_refusal(reach: NetworkReach, target: &str) -> Option<&'static str> {
553    let (host, port) = target.rsplit_once(':')?;
554    let port: u16 = port.parse().ok()?;
555    if is_metadata_endpoint(host, port) {
556        return Some("cloud metadata endpoint");
557    }
558    if reach == NetworkReach::Any {
559        return None;
560    }
561    let authority = if host.contains(':') {
562        format!("[{host}]:{port}")
563    } else {
564        format!("{host}:{port}")
565    };
566    let class = classify_blocked_host(&format!("http://{authority}/"))?;
567    (reach == NetworkReach::PublicOnly || class != BlockedHostClass::Loopback)
568        .then(|| class.label())
569}
570
571/// Refuses calls whose declared egress names an address the tool may not
572/// reach, before anyone is asked. It sees the first request of a call: a
573/// redirect exists only once that request runs, so the tools recheck each
574/// hop themselves.
575#[derive(Debug, Clone, Default)]
576pub struct NetworkGuard {
577    reach: HashMap<String, NetworkReach>,
578}
579
580impl NetworkGuard {
581    pub fn new() -> Self {
582        Self::default()
583    }
584
585    /// State how far `tool` may reach. A tool not named reaches
586    /// [`NetworkReach::Any`].
587    pub fn reach(mut self, tool: impl Into<String>, reach: NetworkReach) -> Self {
588        self.reach.insert(tool.into(), reach);
589        self
590    }
591}
592
593#[async_trait]
594impl Hook for NetworkGuard {
595    async fn before_tool(
596        &self,
597        _ctx: &HookContext<'_>,
598        call: &ToolCall,
599        tool: &ToolInfo,
600    ) -> ToolDecision {
601        let reach = self.reach.get(&call.name).copied().unwrap_or_default();
602        let targets: Vec<String> = tool
603            .effects
604            .keys
605            .iter()
606            .filter(|key| key.class == EffectClass::Egress)
607            .map(|key| key.target.clone())
608            .collect();
609        if targets.is_empty() {
610            return ToolDecision::Allow;
611        }
612        // Classifying can resolve a name.
613        let refusal = tokio::task::spawn_blocking(move || {
614            targets
615                .iter()
616                .find_map(|target| network_refusal(reach, target))
617        })
618        .await
619        .unwrap_or(Some("address that could not be checked"));
620        match refusal {
621            Some(label) => ToolDecision::Deny {
622                reason: format!("Request blocked: target is a {label}"),
623            },
624            None => ToolDecision::Allow,
625        }
626    }
627}
628
629const BROWSER_USER_AGENT: &str =
630    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:142.0) Gecko/20100101 Firefox/142.0";
631
632#[derive(Debug, Clone, Copy, PartialEq, Eq)]
633enum Redirects {
634    SameHost,
635    Public,
636}
637
638/// Which redirects one client follows.
639enum Hops {
640    None,
641    SameHost(String),
642    Public,
643}
644
645/// Fetch a web page over http(s) and return its readable text.
646#[derive(Debug, Clone)]
647pub struct WebFetch {
648    max_chars: usize,
649    timeout: Duration,
650    use_proxy: bool,
651    user_agent: String,
652    browser_headers: bool,
653    allow_private: bool,
654    redirects: Redirects,
655    text: ToolText,
656    public_client: OnceLock<Result<Client, String>>,
657    no_redirect_client: OnceLock<Result<Client, String>>,
658}
659
660impl Default for WebFetch {
661    fn default() -> Self {
662        Self {
663            max_chars: DEFAULT_MAX_CHARS,
664            timeout: Duration::from_secs(30),
665            use_proxy: true,
666            user_agent: concat!("aidaemon-tools/", env!("CARGO_PKG_VERSION")).into(),
667            browser_headers: false,
668            allow_private: false,
669            redirects: Redirects::SameHost,
670            text: ToolText {
671                short: "Fetch a web page and return its readable text".into(),
672                schema: "Fetch a URL with HTTP GET (http/https only) and return the readable text \
673                         of the page; plain text and JSON are returned as is. A PDF or other \
674                         binary body is described (type and size), not shown. Private and \
675                         internal addresses are refused. Redirects to a different host are not \
676                         followed; the new location is reported instead."
677                    .into(),
678            },
679            public_client: OnceLock::new(),
680            no_redirect_client: OnceLock::new(),
681        }
682    }
683}
684
685impl WebFetch {
686    pub fn new() -> Self {
687        Self::default()
688    }
689
690    /// Default characters of text returned to the model.
691    pub fn max_chars(mut self, chars: usize) -> Self {
692        self.max_chars = chars.max(100);
693        self
694    }
695
696    pub fn timeout(mut self, timeout: Duration) -> Self {
697        self.timeout = timeout;
698        self
699    }
700
701    /// Ignore `HTTP(S)_PROXY` environment variables.
702    pub fn without_proxy(mut self) -> Self {
703        self.use_proxy = false;
704        self
705    }
706
707    pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
708        self.user_agent = agent.into();
709        self
710    }
711
712    /// Send a browser's user agent and headers, for sites that refuse other
713    /// clients.
714    pub fn browser_identity(mut self) -> Self {
715        self.user_agent = BROWSER_USER_AGENT.into();
716        self.browser_headers = true;
717        self
718    }
719
720    /// Follow redirects to other public hosts as well. Each hop is still
721    /// checked against the private-network policy.
722    pub fn follow_public_redirects(mut self) -> Self {
723        self.redirects = Redirects::Public;
724        self
725    }
726
727    /// Turn off the private-network policy, for a tool that is meant to reach
728    /// local services.
729    pub fn allow_private_hosts(mut self) -> Self {
730        self.allow_private = true;
731        self
732    }
733
734    /// Replace the model-facing descriptions.
735    pub fn with_text(mut self, text: ToolText) -> Self {
736        self.text = text;
737        self
738    }
739
740    fn build_client(&self, hops: Hops) -> Result<Client, String> {
741        let guarded = !self.allow_private;
742        let allowed = move |url: &str| !guarded || validate_url_for_ssrf(url).is_ok();
743        let policy = match hops {
744            Hops::None => Policy::none(),
745            Hops::Public => Policy::custom(move |attempt| {
746                if !allowed(attempt.url().as_str()) || attempt.previous().len() >= 10 {
747                    attempt.stop()
748                } else {
749                    attempt.follow()
750                }
751            }),
752            Hops::SameHost(host) => Policy::custom(move |attempt| {
753                if attempt.previous().len() >= 10 {
754                    attempt.error("too many redirects")
755                } else if attempt.url().host_str() == Some(host.as_str())
756                    && matches!(attempt.url().scheme(), "http" | "https")
757                    && allowed(attempt.url().as_str())
758                {
759                    attempt.follow()
760                } else {
761                    attempt.stop()
762                }
763            }),
764        };
765        let mut builder = Client::builder()
766            .timeout(self.timeout)
767            .redirect(policy)
768            .user_agent(&self.user_agent);
769        if guarded {
770            builder = builder.dns_resolver(std::sync::Arc::new(PublicOnlyResolver));
771        }
772        if self.browser_headers {
773            builder = builder.default_headers(browser_headers());
774        }
775        if !self.use_proxy {
776            builder = builder.no_proxy();
777        }
778        builder
779            .build()
780            .map_err(|error| format!("cannot build HTTP client: {error}"))
781    }
782
783    fn client_for(&self, url: &str, follow: bool) -> anyhow::Result<Client> {
784        let cached = |cell: &OnceLock<Result<Client, String>>, hops| {
785            cell.get_or_init(|| self.build_client(hops)).clone()
786        };
787        let client = match (follow, self.redirects) {
788            (false, _) => cached(&self.no_redirect_client, Hops::None),
789            (true, Redirects::Public) => cached(&self.public_client, Hops::Public),
790            (true, Redirects::SameHost) => {
791                let host = Url::parse(url)?.host_str().unwrap_or_default().to_string();
792                self.build_client(Hops::SameHost(host))
793            }
794        };
795        client.map_err(anyhow::Error::msg)
796    }
797
798    /// Check the policy, send the request and read the capped body.
799    async fn fetch(&self, url: &str, follow: bool, read_error_body: bool) -> anyhow::Result<Fetch> {
800        if !self.allow_private
801            && let Err(reason) = validate_url_for_ssrf(url)
802        {
803            return Ok(Fetch::Blocked(reason));
804        }
805        let response = self.client_for(url, follow)?.get(url).send().await?;
806        let status = response.status();
807        let final_url = response.url().to_string();
808        let header = |name| {
809            response
810                .headers()
811                .get(name)
812                .and_then(|value: &reqwest::header::HeaderValue| value.to_str().ok())
813                .map(str::to_string)
814        };
815        let content_type = header(reqwest::header::CONTENT_TYPE).unwrap_or_default();
816        let location = header(reqwest::header::LOCATION);
817        let (body, body_truncated) = if status.is_success() || read_error_body {
818            read_body_capped(response, MAX_FETCH_BODY_BYTES).await?
819        } else {
820            (Vec::new(), false)
821        };
822        Ok(Fetch::Response(Fetched {
823            status,
824            final_url,
825            content_type,
826            location,
827            body,
828            body_truncated,
829        }))
830    }
831}
832
833enum Fetch {
834    Blocked(String),
835    Response(Fetched),
836}
837
838struct Fetched {
839    status: StatusCode,
840    final_url: String,
841    content_type: String,
842    location: Option<String>,
843    body: Vec<u8>,
844    body_truncated: bool,
845}
846
847fn browser_headers() -> reqwest::header::HeaderMap {
848    let mut h = reqwest::header::HeaderMap::new();
849    h.insert(
850        "Accept",
851        "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
852            .parse()
853            .unwrap(),
854    );
855    h.insert("Accept-Language", "en-US,en;q=0.5".parse().unwrap());
856    h.insert("Accept-Encoding", "gzip, deflate, br".parse().unwrap());
857    h.insert("DNT", "1".parse().unwrap());
858    h.insert("Upgrade-Insecure-Requests", "1".parse().unwrap());
859    h.insert("Sec-Fetch-Dest", "document".parse().unwrap());
860    h.insert("Sec-Fetch-Mode", "navigate".parse().unwrap());
861    h.insert("Sec-Fetch-Site", "none".parse().unwrap());
862    h.insert("Sec-Fetch-User", "?1".parse().unwrap());
863    h.insert("Sec-GPC", "1".parse().unwrap());
864    h
865}
866
867/// An HTTP client with browser-like headers whose redirects are re-validated
868/// against the private-network policy.
869pub fn build_browser_client() -> Client {
870    WebFetch::new()
871        .browser_identity()
872        .build_client(Hops::Public)
873        .expect("failed to build browser HTTP client")
874}
875
876fn parse_url(raw: &str) -> Result<Url, String> {
877    let url = Url::parse(raw.trim()).map_err(|e| {
878        format!("invalid URL `{raw}`: {e}. Give a full URL such as https://example.com/page")
879    })?;
880    match url.scheme() {
881        "http" | "https" => {}
882        other => return Err(format!("unsupported scheme `{other}`; only http and https")),
883    }
884    if url.host_str().is_none() {
885        return Err(format!("URL `{raw}` has no host"));
886    }
887    Ok(url)
888}
889
890/// The one effect of fetching `url`.
891fn url_effect(url: &Url) -> Option<EffectKey> {
892    // `Url` brackets an IPv6 host; the effect target does not.
893    let host = url
894        .host_str()?
895        .trim_start_matches('[')
896        .trim_end_matches(']');
897    Some(EffectKey::egress(url.scheme(), host, url.port()))
898}
899
900#[derive(Deserialize)]
901#[serde(deny_unknown_fields)]
902struct FetchArgs {
903    url: String,
904    max_chars: Option<usize>,
905    #[serde(default)]
906    offset: usize,
907}
908
909#[async_trait]
910impl OutcomeTool for WebFetch {
911    fn name(&self) -> &str {
912        "web_fetch"
913    }
914
915    fn description(&self) -> &str {
916        &self.text.short
917    }
918
919    fn schema(&self) -> Value {
920        json!({
921            "name": "web_fetch",
922            "description": self.text.schema,
923            "parameters": {
924                "type": "object",
925                "properties": {
926                    "url": {
927                        "type": "string",
928                        "description": "The URL to fetch"
929                    },
930                    "max_chars": {
931                        "type": "integer",
932                        "description": "Maximum characters to return (default 20000, max 50000)"
933                    },
934                    "offset": {
935                        "type": "integer",
936                        "description": "Characters of page text to skip, to read past a truncated reply"
937                    }
938                },
939                "required": ["url"],
940                "additionalProperties": false
941            }
942        })
943    }
944
945    async fn execute(
946        &self,
947        arguments: &str,
948        facts: &ToolCallContext,
949    ) -> anyhow::Result<ToolCallOutcome> {
950        let args: Value = serde_json::from_str(arguments)?;
951        let url = args["url"]
952            .as_str()
953            .ok_or_else(|| anyhow::anyhow!("Missing required parameter: url"))?;
954        let max_chars = args["max_chars"]
955            .as_u64()
956            .map(|n| n as usize)
957            .unwrap_or(self.max_chars)
958            .clamp(1, MAX_MAX_CHARS);
959
960        let offset = args["offset"].as_u64().unwrap_or(0) as usize;
961
962        let fetched = match self.fetch(url, !facts.mandate_execution, true).await? {
963            Fetch::Blocked(reason) => {
964                return Ok(ToolCallOutcome::from_output(format!(
965                    "Request blocked: {reason}"
966                )));
967            }
968            Fetch::Response(fetched) => fetched,
969        };
970        let reply = fetch_reply(&fetched, max_chars, offset);
971        let output = if reply.ok {
972            format!("{}\n{}", fetch_header(url, &fetched), reply.text)
973        } else {
974            reply.text
975        };
976        Ok(ToolCallOutcome {
977            output,
978            metadata: ToolCallMetadata {
979                truncation: reply.truncation,
980                ..Default::default()
981            },
982            finish: None,
983        })
984    }
985}
986
987#[async_trait]
988impl Tool for WebFetch {
989    fn spec(&self) -> aidaemon_core::ToolSpec {
990        spec_of(self)
991    }
992
993    /// A read, but the request (its URL, query included) leaves the
994    /// machine, so outbound policies such as an egress secret scan see it.
995    fn annotations(&self) -> ToolAnnotations {
996        ToolAnnotations {
997            egress: true,
998            ..ToolAnnotations::READ_ONLY
999        }
1000    }
1001
1002    fn outbound(&self, arguments: &Value) -> aidaemon_core::Outbound {
1003        outbound_of_url(arguments)
1004    }
1005
1006    /// The host contacted. An unparsable URL is refused by `validate` before
1007    /// any policy runs; its effects are unknown.
1008    fn effects(&self, arguments: &Value) -> CallEffects {
1009        arguments
1010            .get("url")
1011            .and_then(Value::as_str)
1012            .and_then(|url| parse_url(url).ok())
1013            .and_then(|url| url_effect(&url))
1014            .map_or_else(CallEffects::unknown, |key| CallEffects {
1015                keys: vec![key],
1016                complete: true,
1017                understood: false,
1018            })
1019    }
1020
1021    fn validate(&self, arguments: &Value) -> Result<(), String> {
1022        let url = arguments
1023            .get("url")
1024            .and_then(Value::as_str)
1025            .ok_or("`url` is required and must be a string")?;
1026        parse_url(url).map(|_| ())
1027    }
1028
1029    fn access(&self, arguments: &Value) -> AccessManifest {
1030        let host = arguments
1031            .get("url")
1032            .and_then(Value::as_str)
1033            .and_then(|u| parse_url(u).ok())
1034            .and_then(|u| u.host_str().map(str::to_string));
1035        AccessManifest {
1036            hosts: host.into_iter().collect(),
1037            ..Default::default()
1038        }
1039    }
1040
1041    async fn call(&self, arguments: Value, ctx: &ToolContext) -> ToolResult {
1042        let args: FetchArgs = match parse_args("web_fetch", arguments) {
1043            Ok(a) => a,
1044            Err(e) => return Ok(fail(e)),
1045        };
1046        let url = match parse_url(&args.url) {
1047            Ok(u) => u,
1048            Err(e) => return Ok(fail(e)),
1049        };
1050        let max_chars = args
1051            .max_chars
1052            .unwrap_or(self.max_chars)
1053            .clamp(1, MAX_MAX_CHARS.max(self.max_chars));
1054        let host = url.host_str().unwrap_or_default().to_string();
1055        let result = tokio::select! {
1056            result = self.fetch(url.as_str(), true, true) => result,
1057            _ = ctx.cancel.cancelled() => return Ok(fail("cancelled")),
1058        };
1059        let fetched = match result {
1060            Ok(Fetch::Blocked(reason)) => {
1061                return Ok(fail(format!("Request blocked: {reason}"))
1062                    .with_details(json!({"url": url.as_str(), "host": host})));
1063            }
1064            Ok(Fetch::Response(fetched)) => fetched,
1065            Err(e) => {
1066                return Ok(fail(format!("request to {url} failed: {e}"))
1067                    .with_details(json!({"url": url.as_str(), "host": host})));
1068            }
1069        };
1070        let Fetched {
1071            status,
1072            final_url,
1073            content_type,
1074            location,
1075            body,
1076            body_truncated,
1077        } = fetched;
1078
1079        let mut details = json!({
1080            "url": url.as_str(),
1081            "final_url": final_url,
1082            "host": host,
1083            "status": status.as_u16(),
1084            "content_type": content_type,
1085            "bytes": body.len(),
1086        });
1087
1088        if status.is_redirection() {
1089            let target = location.unwrap_or_else(|| "(no Location header)".into());
1090            details["location"] = json!(target);
1091            return Ok(fail(format!(
1092                "HTTP {status}: {final_url} redirects to {target}, which was not followed. \
1093                 Fetch that URL explicitly if it is the page you want."
1094            ))
1095            .with_details(details));
1096        }
1097
1098        let fetched = Fetched {
1099            status,
1100            final_url,
1101            content_type,
1102            location: None,
1103            body,
1104            body_truncated,
1105        };
1106        let reply = fetch_reply(&fetched, max_chars, args.offset);
1107        let cut = reply.truncation.is_some() || fetched.body_truncated;
1108        details["truncated"] = json!(cut);
1109        if !reply.ok {
1110            return Ok(fail(reply.text).with_details(details));
1111        }
1112        let mut text = reply.text;
1113        if let Some(info) = &reply.truncation {
1114            text.push_str(&format!(
1115                "\n\n[Content truncated to {max_chars} characters. Fetch again with offset={} \
1116                 for the next part ({} characters in all).]",
1117                args.offset + info.shown_chars,
1118                info.total_chars
1119            ));
1120        } else if fetched.body_truncated {
1121            text.push_str(&format!(
1122                "\n\n[Content truncated: the body was larger than {MAX_FETCH_BODY_BYTES} bytes.]"
1123            ));
1124        }
1125        Ok(
1126            ToolOutput::text(format!("{}\n{text}", fetch_header(url.as_str(), &fetched)))
1127                .with_details(details),
1128        )
1129    }
1130}
1131
1132/// A fetch sends its URL and nothing else.
1133fn outbound_of_url(arguments: &Value) -> aidaemon_core::Outbound {
1134    match arguments.get("url").and_then(Value::as_str) {
1135        Some(url) => aidaemon_core::Outbound::Exact(vec![url.to_string()]),
1136        None => aidaemon_core::Outbound::Composed,
1137    }
1138}
1139
1140impl crate::semantics::ToolSemantics for WebFetch {
1141    fn call_outbound(&self, arguments: &str) -> aidaemon_core::Outbound {
1142        serde_json::from_str::<Value>(arguments).map_or(aidaemon_core::Outbound::Composed, |args| {
1143            outbound_of_url(&args)
1144        })
1145    }
1146
1147    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
1148        crate::semantics::ToolDispatchFacts {
1149            offering: crate::semantics::Offering::Core,
1150            network_reach: crate::semantics::NetworkReach::PublicOnly,
1151            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
1152            recap: crate::semantics::RecapKind::ExternalRead,
1153            activity: crate::semantics::ToolActivity::Fixed(aidaemon_core::card::ActivityKind::Web),
1154            status_label: Some("fetching a page"),
1155            result_fit: crate::semantics::ResultFit {
1156                compact_json: true,
1157                ..Default::default()
1158            },
1159            evidence: crate::semantics::EvidenceSource::RemoteRead,
1160            semantic_scope: Some(crate::semantics::ToolSemanticScope::ExternalRemote),
1161            ..Default::default()
1162        }
1163    }
1164
1165    fn capabilities(&self) -> ToolCapabilities {
1166        ToolCapabilities {
1167            read_only: true,
1168            external_side_effect: true,
1169            needs_approval: false,
1170            idempotent: true,
1171            high_impact_write: false,
1172        }
1173    }
1174
1175    fn call_semantics(&self, arguments: &str) -> ToolCallSemantics {
1176        let url = serde_json::from_str::<Value>(arguments)
1177            .ok()
1178            .and_then(|args| {
1179                args.get("url")
1180                    .and_then(|value| value.as_str())
1181                    .map(str::to_string)
1182            })
1183            .unwrap_or_default();
1184
1185        ToolCallSemantics::observation()
1186            .with_operation(crate::semantics::ToolCallOperation::Get)
1187            .with_verification_mode(ToolVerificationMode::ResultContent)
1188            .with_target_hint(ToolTargetHintKind::Url, url)
1189    }
1190
1191    /// The page's host.
1192    fn call_effects(&self, arguments: &str) -> aidaemon_core::CallEffects {
1193        serde_json::from_str::<Value>(arguments)
1194            .ok()
1195            .and_then(|args| url_effect(&parse_url(args.get("url")?.as_str()?).ok()?))
1196            .map_or_else(aidaemon_core::CallEffects::unknown, |key| {
1197                aidaemon_core::CallEffects {
1198                    keys: vec![key],
1199                    complete: true,
1200                    understood: false,
1201                }
1202            })
1203    }
1204}
1205
1206fn looks_like_html(body: &[u8]) -> bool {
1207    let head = String::from_utf8_lossy(&body[..body.len().min(512)]).to_ascii_lowercase();
1208    head.contains("<html") || head.contains("<!doctype html")
1209}
1210
1211/// What a fetched body is: by its declared type, sniffed when undeclared.
1212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1213enum BodyKind {
1214    Html,
1215    Text,
1216    Pdf,
1217    Binary,
1218}
1219
1220fn body_kind(content_type: &str, body: &[u8]) -> BodyKind {
1221    let lower = content_type.to_ascii_lowercase();
1222    if lower.contains("pdf") || (lower.is_empty() && body.starts_with(b"%PDF-")) {
1223        BodyKind::Pdf
1224    } else if lower.contains("html") || (lower.is_empty() && looks_like_html(body)) {
1225        BodyKind::Html
1226    } else if lower.starts_with("text/")
1227        || lower.contains("json")
1228        || lower.contains("xml")
1229        || lower.contains("javascript")
1230        || (lower.is_empty() && std::str::from_utf8(&body[..body.len().min(1024)]).is_ok())
1231    {
1232        BodyKind::Text
1233    } else {
1234        BodyKind::Binary
1235    }
1236}
1237
1238/// The model's view of one fetch, for both entry points: the page's text
1239/// (from `offset`, cut at `max_chars`, with the cut as metadata), or an
1240/// error that says why there is no text.
1241struct FetchReply {
1242    ok: bool,
1243    text: String,
1244    truncation: Option<crate::semantics::TruncationInfo>,
1245}
1246
1247fn fetch_reply(fetched: &Fetched, max_chars: usize, offset: usize) -> FetchReply {
1248    let url = fetched.final_url.as_str();
1249    let status = fetched.status;
1250    let error = |text: String| FetchReply {
1251        ok: false,
1252        text,
1253        truncation: None,
1254    };
1255    if status.is_redirection() {
1256        let target = fetched
1257            .location
1258            .as_deref()
1259            .unwrap_or("(no Location header)");
1260        return error(format!(
1261            "HTTP {status}: {url} redirects to {target}, which was not followed. Fetch that URL \
1262             explicitly if it is the page you want."
1263        ));
1264    }
1265    let kind = body_kind(&fetched.content_type, &fetched.body);
1266    let bytes = fetched.body.len();
1267    let content_type = if fetched.content_type.is_empty() {
1268        "an undeclared type"
1269    } else {
1270        fetched.content_type.as_str()
1271    };
1272    match kind {
1273        BodyKind::Pdf if status.is_success() => {
1274            return error(format!(
1275                "{url} is a PDF document ({bytes} bytes, {content_type}). web_fetch does not \
1276                 extract PDF text: download the file to the workspace and read it with read_file, \
1277                 which says how to extract its text."
1278            ));
1279        }
1280        BodyKind::Binary if status.is_success() => {
1281            return error(format!(
1282                "{url} returned binary content, {bytes} bytes, type {content_type}, which is not \
1283                 text and cannot be shown."
1284            ));
1285        }
1286        _ => {}
1287    }
1288    let raw = String::from_utf8_lossy(&fetched.body);
1289    if !status.is_success() {
1290        let text = match kind {
1291            BodyKind::Html => extract_page_text(&raw, url),
1292            BodyKind::Text => raw.into_owned(),
1293            BodyKind::Pdf | BodyKind::Binary => String::new(),
1294        };
1295        let (snippet, _) = truncate_chars(text.trim(), 2000);
1296        return error(format!("HTTP {status} from {url}.\n\n{snippet}"));
1297    }
1298    let (text, truncation) = match kind {
1299        BodyKind::Html => build_fetch_reply_at(url, &raw, max_chars, offset),
1300        _ => format_fetch_window(url, &raw, max_chars, offset),
1301    };
1302    FetchReply {
1303        ok: true,
1304        text,
1305        truncation,
1306    }
1307}
1308
1309/// Extracted text shorter than this (on a large page) means extraction
1310/// failed, not that the page is thin.
1311const MIN_EXTRACTED_CHARS: usize = 200;
1312/// Only pages at least this large trigger the extraction-failure check —
1313/// genuinely tiny pages legitimately yield little text.
1314const MIN_HTML_FOR_EXTRACTION_CHECK: usize = 10_000;
1315
1316/// Full fetch-reply pipeline: strip non-visible blocks, extract readable
1317/// text, detect failed extraction, format with truncation honesty.
1318#[cfg(test)]
1319fn build_fetch_reply(
1320    url: &str,
1321    html: &str,
1322    max_chars: usize,
1323) -> (String, Option<crate::semantics::TruncationInfo>) {
1324    build_fetch_reply_at(url, html, max_chars, 0)
1325}
1326
1327fn build_fetch_reply_at(
1328    url: &str,
1329    html: &str,
1330    max_chars: usize,
1331    offset: usize,
1332) -> (String, Option<crate::semantics::TruncationInfo>) {
1333    let text = extract_page_text(html, url);
1334    let trimmed = text.trim();
1335    if trimmed.chars().count() < MIN_EXTRACTED_CHARS && html.len() >= MIN_HTML_FOR_EXTRACTION_CHECK
1336    {
1337        // A large page that yields almost no readable text is the signature
1338        // of a JavaScript-rendered (or bot-walled) page. Without this notice
1339        // the model treats the empty result as the page's actual content —
1340        // or worse, re-fetches the same URL expecting a different outcome.
1341        // This is a distinct extraction-failure signal, not truncation, so it
1342        // stays an embedded instructional marker (no TruncationInfo applies).
1343        return (
1344            format!(
1345                "Content from {}:\n\n{}\n\n[⚠ EXTRACTION FAILED — this {} KB page yielded only {} \
1346                 characters of readable text; it is likely JavaScript-rendered or blocking \
1347                 non-browser clients. Do NOT treat this as the page's content, and do NOT re-fetch \
1348                 this same URL — the result will not change. Fetch a different source URL from your \
1349                 search results, or use a browser-based tool on this URL if one is available.]",
1350                url,
1351                trimmed,
1352                html.len() / 1024,
1353                trimmed.chars().count(),
1354            ),
1355            None,
1356        );
1357    }
1358    format_fetch_window(url, &text, max_chars, offset)
1359}
1360
1361/// Extract readable page text: readability first, raw-HTML-to-markdown
1362/// fallback. `<script>`/`<style>`/`<noscript>` blocks are stripped FIRST —
1363/// both paths can leak inline script bodies into the "text" (observed:
1364/// Wikipedia fetches returning JS soup that consumed the whole max_chars
1365/// window before any article content).
1366fn extract_page_text(html: &str, url: &str) -> String {
1367    let text = extract_page_body(html, url);
1368    // Readability keeps the article body and drops a heading that repeats
1369    // the page title, so a page whose one heading is its title came back
1370    // without it (live 2026-11-20: every "what is the page's heading?" turn
1371    // re-fetched the page with curl two or three times to find it). The
1372    // page's heading leads the text when the text lacks it.
1373    match page_heading(html) {
1374        Some(heading) if !text.contains(&heading) => format!("# {heading}\n\n{text}"),
1375        _ => text,
1376    }
1377}
1378
1379/// The page's main heading as plain text: its first `<h1>`, else its
1380/// `<title>` (HTML markup, a machine format).
1381fn page_heading(html: &str) -> Option<String> {
1382    let cleaned = strip_nonvisible_blocks(html);
1383    ["h1", "title"]
1384        .into_iter()
1385        .find_map(|tag| first_element_text(&cleaned, tag))
1386}
1387
1388/// The text inside the first `<tag ...>...</tag>`, tags removed, entities
1389/// decoded and whitespace collapsed; `None` when absent or empty.
1390fn first_element_text(html: &str, tag: &str) -> Option<String> {
1391    let bytes = html.as_bytes();
1392    let open = format!("<{tag}");
1393    let mut from = 0;
1394    let start = loop {
1395        let at = find_ascii_ci(bytes, open.as_bytes(), from)?;
1396        // "<h1" must end the tag name ("<h10" or "<titles" is another tag).
1397        if matches!(
1398            bytes.get(at + open.len()),
1399            Some(b' ') | Some(b'>') | Some(b'\t') | Some(b'\n') | Some(b'\r')
1400        ) {
1401            break at;
1402        }
1403        from = at + open.len();
1404    };
1405    let inner_start = start + html[start..].find('>')? + 1;
1406    let close = format!("</{tag}");
1407    let inner_end = find_ascii_ci(bytes, close.as_bytes(), inner_start)?;
1408    let inner = htmd::convert(&html[inner_start..inner_end]).unwrap_or_default();
1409    let text = inner
1410        .replace(['*', '_', '#', '`'], "")
1411        .split_whitespace()
1412        .collect::<Vec<_>>()
1413        .join(" ");
1414    (!text.is_empty()).then_some(text)
1415}
1416
1417/// [`extract_page_text`] before the page's heading is added.
1418fn extract_page_body(html: &str, url: &str) -> String {
1419    let cleaned = strip_nonvisible_blocks(html);
1420    let parsed_url = reqwest::Url::parse(url)
1421        .unwrap_or_else(|_| reqwest::Url::parse("http://example.com").unwrap());
1422    let mut cursor = Cursor::new(cleaned.as_bytes());
1423    let full_page = || htmd::convert(&cleaned).unwrap_or_else(|_| cleaned.clone());
1424    match llm_readability::extractor::extract(&mut cursor, &parsed_url) {
1425        Ok(product) if !product.text.trim().is_empty() => {
1426            // Readability's plain text runs its blocks together ("Example
1427            // DomainThis domain ..."); its HTML as markdown keeps headings
1428            // and paragraphs apart.
1429            let article = htmd::convert(&strip_nonvisible_blocks(&product.content))
1430                .ok()
1431                .filter(|markdown| !markdown.trim().is_empty())
1432                .unwrap_or_else(|| product.text.clone());
1433            // Readability keeps one block. On an article that is the content;
1434            // on a listing page (downloads, release lists, tables) it is a
1435            // side section, and the answer is in what it dropped. A short
1436            // extract cut from a much larger page gets the whole page.
1437            let article_chars = article.trim().chars().count();
1438            if article_chars >= MIN_ARTICLE_CHARS {
1439                return article;
1440            }
1441            let full = full_page();
1442            let full_chars = full.trim().chars().count();
1443            if (article_chars as f64) >= MIN_ARTICLE_COVERAGE * full_chars as f64 {
1444                article
1445            } else {
1446                full
1447            }
1448        }
1449        _ => full_page(),
1450    }
1451}
1452
1453/// Readability output at least this long is an article in its own right.
1454const MIN_ARTICLE_CHARS: usize = 8_000;
1455/// A shorter extract must cover at least this share of the page's text to
1456/// count as its main content.
1457const MIN_ARTICLE_COVERAGE: f64 = 0.35;
1458
1459/// Remove `<script>`, `<style>`, and `<noscript>` blocks (case-insensitive,
1460/// unclosed blocks dropped to end-of-input).
1461fn strip_nonvisible_blocks(html: &str) -> String {
1462    let mut out = html.to_string();
1463    for tag in ["script", "style", "noscript"] {
1464        out = strip_tag_blocks(&out, tag);
1465    }
1466    out
1467}
1468
1469fn strip_tag_blocks(html: &str, tag: &str) -> String {
1470    let open = format!("<{}", tag);
1471    let close = format!("</{}>", tag);
1472    let bytes = html.as_bytes();
1473    let mut out = String::with_capacity(html.len());
1474    let mut pos = 0;
1475    while let Some(start) = find_ascii_ci(bytes, open.as_bytes(), pos) {
1476        // The byte after "<tag" must terminate the tag name, else "<scriptx"
1477        // or a "<style-like" element would match.
1478        let after = bytes.get(start + open.len());
1479        if !matches!(
1480            after,
1481            Some(b' ') | Some(b'>') | Some(b'\t') | Some(b'\n') | Some(b'/')
1482        ) {
1483            out.push_str(&html[pos..start + open.len()]);
1484            pos = start + open.len();
1485            continue;
1486        }
1487        out.push_str(&html[pos..start]);
1488        match find_ascii_ci(bytes, close.as_bytes(), start) {
1489            Some(end) => pos = end + close.len(),
1490            None => {
1491                pos = html.len();
1492                break;
1493            }
1494        }
1495    }
1496    out.push_str(&html[pos..]);
1497    out
1498}
1499
1500/// ASCII-case-insensitive substring search from `from`. Byte positions are
1501/// safe to slice with because the needles are pure ASCII.
1502fn find_ascii_ci(haystack: &[u8], needle: &[u8], from: usize) -> Option<usize> {
1503    if from >= haystack.len() || needle.is_empty() {
1504        return None;
1505    }
1506    haystack[from..]
1507        .windows(needle.len())
1508        .position(|w| w.eq_ignore_ascii_case(needle))
1509        .map(|i| i + from)
1510}
1511
1512/// Format extracted page text, truncating to `max_chars` (bytes, floored to a
1513/// char boundary). Truncation is reported via the returned `TruncationInfo`,
1514/// not embedded in the text — the agent loop renders the instructional
1515/// notice from that metadata (see `crate::utils::render_truncation_notice`),
1516/// so text-scanning consumers (classifiers, summaries) always see clean
1517/// output. A passive "[Truncated]" marker baked into the text is routinely
1518/// ignored and the model fabricates the omitted content (e.g. inventing the
1519/// rest of a roster) — this is why the notice must reach the model through
1520/// the loop's instructional rendering rather than raw tool output.
1521#[cfg(test)]
1522fn format_fetch_result(
1523    url: &str,
1524    text: &str,
1525    max_chars: usize,
1526) -> (String, Option<crate::semantics::TruncationInfo>) {
1527    format_fetch_window(url, text, max_chars, 0)
1528}
1529
1530/// One line stating what a fetch reached: status, content type, the final
1531/// URL (and the URL asked for when a redirect moved it) and the page title,
1532/// so the model need not check them with another request (live 2026-11-14
1533/// to 11-20: 51 curl status checks, 9 right after a fetch).
1534fn fetch_header(requested: &str, fetched: &Fetched) -> String {
1535    let same = |a: &str, b: &str| a.trim_end_matches('/') == b.trim_end_matches('/');
1536    let mut parts = vec![
1537        format!("HTTP {}", fetched.status.as_u16()),
1538        fetched.content_type.clone(),
1539    ];
1540    if same(requested, &fetched.final_url) {
1541        parts.push(fetched.final_url.clone());
1542    } else {
1543        parts.push(format!(
1544            "{} (redirected from {requested})",
1545            fetched.final_url
1546        ));
1547    }
1548    if fetched.content_type.contains("html")
1549        && let Some(title) = first_element_text(&String::from_utf8_lossy(&fetched.body), "title")
1550    {
1551        parts.push(format!("title \"{title}\""));
1552    }
1553    parts.join(" \u{b7} ")
1554}
1555
1556/// `max_chars` of `text` starting at character `offset`. A cut is reported
1557/// as metadata, with the offset that continues it.
1558fn format_fetch_window(
1559    url: &str,
1560    text: &str,
1561    max_chars: usize,
1562    offset: usize,
1563) -> (String, Option<crate::semantics::TruncationInfo>) {
1564    let total_chars = text.chars().count();
1565    let mut result = format!("Content from {}:\n\n", url);
1566    if offset >= total_chars && offset > 0 {
1567        result.push_str(&format!(
1568            "[offset {offset} is past the end: the page text has {total_chars} characters.]"
1569        ));
1570        return (result, None);
1571    }
1572    let window: String = text.chars().skip(offset).take(max_chars).collect();
1573    let shown_chars = window.chars().count();
1574    result.push_str(&window);
1575    if offset + shown_chars < total_chars {
1576        let truncation = crate::semantics::TruncationInfo {
1577            shown_chars,
1578            total_chars,
1579            remediation_hint: Some(format!(
1580                "If the answer may be in the omitted part, fetch again with offset={} (or a \
1581                 larger max_chars, up to 50000), or fetch a more specific page; if the full \
1582                 content is still not visible, tell the user the page was longer than you \
1583                 could read.",
1584                offset + shown_chars
1585            )),
1586        };
1587        (result, Some(truncation))
1588    } else {
1589        (result, None)
1590    }
1591}
1592
1593#[cfg(test)]
1594mod tests {
1595    use super::*;
1596
1597    #[tokio::test]
1598    async fn a_name_resolving_to_a_blocked_address_is_refused_at_connection() {
1599        use reqwest::dns::Resolve;
1600        use std::str::FromStr;
1601        let name = reqwest::dns::Name::from_str("localhost").unwrap();
1602        let error = match PublicOnlyResolver.resolve(name).await {
1603            Ok(_) => panic!("localhost must not resolve"),
1604            Err(error) => error.to_string(),
1605        };
1606        assert!(error.contains("blocked address"), "{error}");
1607    }
1608    use crate::testutil::ctx;
1609    use tokio::io::{AsyncReadExt, AsyncWriteExt};
1610
1611    #[test]
1612    fn web_fetch_declares_its_egress_host() {
1613        let tool = WebFetch::new();
1614        assert!(tool.annotations().egress);
1615        assert!(tool.annotations().read_only);
1616        let effects = tool.effects(&json!({"url": "https://Docs.Example.Invalid/guide?q=1"}));
1617        assert!(effects.complete);
1618        assert_eq!(
1619            effects.keys,
1620            vec![EffectKey::egress("https", "docs.example.invalid", None)]
1621        );
1622        let local = tool.effects(&json!({"url": "http://[::1]:8765/status"}));
1623        assert_eq!(
1624            local.keys,
1625            vec![EffectKey::egress("http", "::1", Some(8765))]
1626        );
1627        assert!(!tool.effects(&json!({"url": "not a url"})).complete);
1628    }
1629
1630    /// Serve canned responses on a local port: path -> (status line, content type, body).
1631    async fn serve(routes: Vec<(&'static str, &'static str, &'static str, String)>) -> String {
1632        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1633        let addr = listener.local_addr().unwrap();
1634        tokio::spawn(async move {
1635            loop {
1636                let Ok((mut sock, _)) = listener.accept().await else {
1637                    break;
1638                };
1639                let routes = routes.clone();
1640                tokio::spawn(async move {
1641                    let mut buf = vec![0u8; 4096];
1642                    let n = sock.read(&mut buf).await.unwrap_or(0);
1643                    let req = String::from_utf8_lossy(&buf[..n]);
1644                    let path = req.split_whitespace().nth(1).unwrap_or("/").to_string();
1645                    let (status, ctype, body) = routes
1646                        .iter()
1647                        .find(|(p, ..)| *p == path)
1648                        .map(|(_, s, c, b)| (*s, *c, b.clone()))
1649                        .unwrap_or(("404 Not Found", "text/plain", "missing".to_string()));
1650                    let extra = if status.starts_with("302") {
1651                        format!("Location: {body}\r\n")
1652                    } else {
1653                        String::new()
1654                    };
1655                    let resp = format!(
1656                        "HTTP/1.1 {status}\r\nContent-Type: {ctype}\r\nContent-Length: {}\r\n{extra}Connection: close\r\n\r\n{body}",
1657                        body.len()
1658                    );
1659                    let _ = sock.write_all(resp.as_bytes()).await;
1660                    let _ = sock.shutdown().await;
1661                });
1662            }
1663        });
1664        format!("http://127.0.0.1:{}", addr.port())
1665    }
1666
1667    /// The reply's first line says what the fetch reached: status, type,
1668    /// final URL (with the URL asked for when a redirect moved it) and
1669    /// title, on both entry points.
1670    #[tokio::test]
1671    async fn a_fetch_reports_status_final_url_and_title() {
1672        let base = serve(vec![
1673            (
1674                "/page",
1675                "200 OK",
1676                "text/html; charset=utf-8",
1677                "<html><head><title>Synthetic Shop</title></head><body><p>Hello.</p></body></html>"
1678                    .into(),
1679            ),
1680            ("/hop", "302 Found", "text/plain", "/page".into()),
1681        ])
1682        .await;
1683        let tool = WebFetch::new().without_proxy().allow_private_hosts();
1684        let out = tool
1685            .call(json!({"url": format!("{base}/page")}), &ctx())
1686            .await
1687            .unwrap();
1688        let first = out.content.lines().next().unwrap_or("").to_string();
1689        assert!(first.starts_with("HTTP 200 \u{b7} text/html"), "{first}");
1690        assert!(first.contains(&format!("{base}/page")), "{first}");
1691        assert!(first.contains("title \"Synthetic Shop\""), "{first}");
1692        assert!(!first.contains("redirected"), "{first}");
1693
1694        let hop = format!("{base}/hop");
1695        let out = tool.call(json!({"url": hop}), &ctx()).await.unwrap();
1696        let first = out.content.lines().next().unwrap_or("").to_string();
1697        assert!(
1698            first.contains(&format!("{base}/page (redirected from {hop})")),
1699            "{first}"
1700        );
1701
1702        // The daemon's entry point carries the same line.
1703        let outcome = OutcomeTool::execute(
1704            &tool,
1705            &json!({"url": hop}).to_string(),
1706            &ToolCallContext::default(),
1707        )
1708        .await
1709        .unwrap();
1710        let first = outcome.output.lines().next().unwrap_or("").to_string();
1711        assert!(first.starts_with("HTTP 200"), "{first}");
1712        assert!(first.contains("redirected from"), "{first}");
1713        assert!(first.contains("Synthetic Shop"), "{first}");
1714    }
1715
1716    #[tokio::test]
1717    async fn fetches_html_as_markdown() {
1718        let base = serve(vec![
1719            (
1720                "/page",
1721                "200 OK",
1722                "text/html; charset=utf-8",
1723                "<html><head><title>T</title><script>evil()</script></head><body><h1>Synthetic Title</h1><p>Hello <b>world</b>.</p></body></html>".into(),
1724            ),
1725            ("/big", "200 OK", "text/plain", "x".repeat(5000)),
1726            ("/gone", "404 Not Found", "text/html", "<p>no such page</p>".into()),
1727            ("/away", "302 Found", "text/plain", "http://elsewhere.invalid/".into()),
1728            ("/img", "200 OK", "image/png", "\u{1}PNG".into()),
1729        ])
1730        .await;
1731        let tool = WebFetch::new()
1732            .without_proxy()
1733            .allow_private_hosts()
1734            .max_chars(1000);
1735
1736        let url = format!("{base}/page");
1737        let out = tool.call(json!({"url": url}), &ctx()).await.unwrap();
1738        assert!(!out.is_error, "{}", out.content);
1739        assert!(out.content.contains("Hello"), "{}", out.content);
1740        assert!(!out.content.contains("evil"));
1741        assert_eq!(out.details["status"], 200);
1742
1743        let out = tool
1744            .call(json!({"url": format!("{base}/big")}), &ctx())
1745            .await
1746            .unwrap();
1747        assert!(
1748            out.content
1749                .contains("[Content truncated to 1000 characters. Fetch again with offset=1000")
1750        );
1751        assert_eq!(out.details["truncated"], true);
1752
1753        let out = tool
1754            .call(json!({"url": format!("{base}/gone")}), &ctx())
1755            .await
1756            .unwrap();
1757        assert!(out.is_error);
1758        assert_eq!(out.details["status"], 404);
1759        assert!(out.content.contains("404") && out.content.contains("no such page"));
1760
1761        let out = tool
1762            .call(json!({"url": format!("{base}/away")}), &ctx())
1763            .await
1764            .unwrap();
1765        assert!(out.is_error && out.content.contains("elsewhere.invalid"));
1766        assert_eq!(out.details["status"], 302);
1767
1768        let out = tool
1769            .call(json!({"url": format!("{base}/img")}), &ctx())
1770            .await
1771            .unwrap();
1772        assert!(out.is_error && out.content.contains("image/png"));
1773    }
1774
1775    /// Both entry points build the same reply: a PDF and a PNG are
1776    /// described, not decoded into junk text; a long page continues at
1777    /// `offset`; a JavaScript-only page says extraction failed.
1778    #[tokio::test]
1779    async fn both_paths_describe_binary_and_continue_at_an_offset() {
1780        let js_only = format!(
1781            "<html><head><script>{}</script></head><body><div id=\"root\"></div></body></html>",
1782            "z".repeat(20_000)
1783        );
1784        let base = serve(vec![
1785            (
1786                "/doc",
1787                "200 OK",
1788                "application/pdf",
1789                "%PDF-1.7 synthetic".into(),
1790            ),
1791            ("/img", "200 OK", "image/png", "\u{1}PNG".into()),
1792            (
1793                "/long",
1794                "200 OK",
1795                "text/plain",
1796                format!("{}{}", "a".repeat(1000), "b".repeat(500)),
1797            ),
1798            ("/spa", "200 OK", "text/html", js_only),
1799        ])
1800        .await;
1801        let tool = WebFetch::new()
1802            .without_proxy()
1803            .allow_private_hosts()
1804            .max_chars(1000);
1805        let facts = crate::semantics::ToolCallContext::default();
1806        let daemon = |args: Value| {
1807            let tool = &tool;
1808            let facts = &facts;
1809            async move {
1810                OutcomeTool::execute(tool, &args.to_string(), facts)
1811                    .await
1812                    .unwrap()
1813            }
1814        };
1815
1816        let pdf = daemon(json!({"url": format!("{base}/doc")})).await.output;
1817        assert!(
1818            pdf.contains("PDF document") && pdf.contains("read_file"),
1819            "{pdf}"
1820        );
1821        assert!(!pdf.contains("%PDF"), "{pdf}");
1822        let out = tool
1823            .call(json!({"url": format!("{base}/doc")}), &ctx())
1824            .await
1825            .unwrap();
1826        assert!(out.is_error && out.content.contains("PDF document"));
1827
1828        let png = daemon(json!({"url": format!("{base}/img")})).await.output;
1829        assert!(
1830            png.contains("binary content, 4 bytes, type image/png"),
1831            "{png}"
1832        );
1833
1834        let first = daemon(json!({"url": format!("{base}/long")})).await;
1835        let info = first.metadata.truncation.expect("cut");
1836        assert_eq!((info.shown_chars, info.total_chars), (1000, 1500));
1837        assert!(info.remediation_hint.unwrap().contains("offset=1000"));
1838        let rest = daemon(json!({"url": format!("{base}/long"), "offset": 1000})).await;
1839        assert!(rest.output.ends_with(&"b".repeat(500)), "{}", rest.output);
1840        assert!(!rest.output.contains('a'.to_string().repeat(2).as_str()));
1841        assert!(rest.metadata.truncation.is_none());
1842        let out = tool
1843            .call(
1844                json!({"url": format!("{base}/long"), "offset": 1000}),
1845                &ctx(),
1846            )
1847            .await
1848            .unwrap();
1849        assert!(out.content.contains(&"b".repeat(500)) && !out.content.contains("aa"));
1850
1851        let spa = daemon(json!({"url": format!("{base}/spa")})).await.output;
1852        assert!(spa.contains("EXTRACTION FAILED"), "{spa}");
1853    }
1854
1855    #[tokio::test]
1856    async fn private_hosts_are_blocked_by_default() {
1857        let base = serve(vec![("/page", "200 OK", "text/plain", "private".into())]).await;
1858        let tool = WebFetch::new().without_proxy();
1859        let out = tool
1860            .call(json!({"url": format!("{base}/page")}), &ctx())
1861            .await
1862            .unwrap();
1863        assert!(
1864            out.is_error && out.content.contains("Request blocked"),
1865            "{}",
1866            out.content
1867        );
1868        assert!(!out.content.contains("private\n"));
1869    }
1870
1871    #[tokio::test]
1872    async fn a_cross_host_redirect_is_reported_not_followed() {
1873        let base = serve(vec![(
1874            "/away",
1875            "302 Found",
1876            "text/plain",
1877            "http://localhost:9/landing".into(),
1878        )])
1879        .await;
1880        let tool = WebFetch::new().without_proxy().allow_private_hosts();
1881        let out = tool
1882            .call(json!({"url": format!("{base}/away")}), &ctx())
1883            .await
1884            .unwrap();
1885        assert!(
1886            out.is_error && out.content.contains("localhost:9"),
1887            "{}",
1888            out.content
1889        );
1890    }
1891
1892    #[tokio::test]
1893    async fn mandate_execution_never_follows_a_redirect() {
1894        let base = serve(vec![
1895            ("/away", "302 Found", "text/plain", "/landing".into()),
1896            ("/landing", "200 OK", "text/html", "<p>arrived</p>".into()),
1897        ])
1898        .await;
1899        let tool = WebFetch::new()
1900            .without_proxy()
1901            .allow_private_hosts()
1902            .follow_public_redirects();
1903        let arguments = json!({"url": format!("{base}/away")}).to_string();
1904
1905        let followed = tool
1906            .execute(&arguments, &ToolCallContext::default())
1907            .await
1908            .unwrap();
1909        assert!(followed.output.contains("arrived"), "{}", followed.output);
1910
1911        let facts = ToolCallContext {
1912            mandate_execution: true,
1913            ..ToolCallContext::default()
1914        };
1915        let stopped = tool.execute(&arguments, &facts).await.unwrap();
1916        assert!(stopped.output.contains("HTTP 302"), "{}", stopped.output);
1917    }
1918
1919    #[test]
1920    fn metadata_endpoints_are_refused_for_every_reach() {
1921        for target in [
1922            "169.254.169.254:80",
1923            "metadata.google.internal:80",
1924            "metadata.goog:443",
1925            "fe80::1:80",
1926            "fd00:ec2::254:80",
1927        ] {
1928            for reach in [
1929                NetworkReach::Any,
1930                NetworkReach::PublicAndLoopback,
1931                NetworkReach::PublicOnly,
1932            ] {
1933                assert!(
1934                    network_refusal(reach, target).is_some(),
1935                    "{target} {reach:?}"
1936                );
1937            }
1938        }
1939    }
1940
1941    #[test]
1942    fn reach_decides_private_and_loopback() {
1943        use NetworkReach::*;
1944        // A shell still reaches the owner's own network and internal names.
1945        for target in ["10.0.0.5:22", "localhost:3000", "db.internal:5432"] {
1946            assert_eq!(network_refusal(Any, target), None, "{target}");
1947        }
1948        assert_eq!(network_refusal(PublicAndLoopback, "localhost:3000"), None);
1949        assert_eq!(
1950            network_refusal(PublicAndLoopback, "shop.localhost:80"),
1951            None
1952        );
1953        assert!(network_refusal(PublicAndLoopback, "10.0.0.5:80").is_some());
1954        assert!(network_refusal(PublicOnly, "localhost:3000").is_some());
1955        assert!(network_refusal(PublicOnly, "::1:80").is_some());
1956        assert_eq!(network_refusal(PublicOnly, "8.8.8.8:443"), None);
1957    }
1958
1959    #[test]
1960    fn a_refusal_names_the_class_not_the_target() {
1961        let label = network_refusal(NetworkReach::PublicOnly, "10.1.2.3:8443").unwrap();
1962        assert!(!label.contains("10.1.2.3"));
1963    }
1964
1965    #[test]
1966    fn validates_scheme_and_declares_host() {
1967        let tool = WebFetch::new();
1968        assert!(
1969            tool.validate(&json!({"url": "file:///etc/passwd"}))
1970                .is_err()
1971        );
1972        assert!(tool.validate(&json!({"url": "not a url"})).is_err());
1973        assert!(
1974            tool.validate(&json!({"url": "https://example.com/x"}))
1975                .is_ok()
1976        );
1977        assert_eq!(
1978            tool.access(&json!({"url": "https://docs.example.com/a?b=c"}))
1979                .hosts,
1980            vec!["docs.example.com"]
1981        );
1982        assert!(tool.annotations().read_only);
1983    }
1984}
1985
1986#[cfg(test)]
1987mod ssrf_policy_tests {
1988    use super::*;
1989
1990    /// Every URL the shared classifier marks blocked must ALSO be rejected by
1991    /// `validate_url_for_ssrf`, and the class must match the expected category.
1992    /// This is the single-source-of-truth invariant: the browser tool's
1993    /// host-class classifier and the web_fetch validator never diverge.
1994    fn assert_blocked(url: &str, expected: BlockedHostClass) {
1995        let class = classify_blocked_host(url);
1996        assert_eq!(
1997            class,
1998            Some(expected),
1999            "expected {url} blocked as {expected:?}, got {class:?}"
2000        );
2001        assert!(
2002            validate_url_for_ssrf(url).is_err(),
2003            "validate_url_for_ssrf must also reject {url}"
2004        );
2005        // Secret-safety: the label must never echo the URL.
2006        let label = expected.label();
2007        assert!(
2008            !url.contains(label) || label.is_empty(),
2009            "label must be a fixed class string, not derived from the url"
2010        );
2011    }
2012
2013    fn assert_allowed(url: &str) {
2014        assert_eq!(
2015            classify_blocked_host(url),
2016            None,
2017            "{url} should be allowed (public)"
2018        );
2019    }
2020
2021    #[test]
2022    fn loopback_is_blocked() {
2023        assert_blocked("http://127.0.0.1/", BlockedHostClass::Loopback);
2024        assert_blocked("http://127.0.0.1:8080/admin", BlockedHostClass::Loopback);
2025        assert_blocked("http://127.5.6.7/", BlockedHostClass::Loopback); // 127/8
2026        assert_blocked("http://localhost/", BlockedHostClass::Loopback);
2027        assert_blocked("http://[::1]/", BlockedHostClass::Loopback);
2028        assert_blocked("http://0.0.0.0/", BlockedHostClass::Loopback);
2029    }
2030
2031    #[test]
2032    fn rfc1918_private_ranges_are_blocked() {
2033        assert_blocked("http://10.0.0.1/", BlockedHostClass::PrivateNetwork);
2034        assert_blocked("http://10.255.255.255/", BlockedHostClass::PrivateNetwork);
2035        assert_blocked("http://172.16.0.1/", BlockedHostClass::PrivateNetwork);
2036        assert_blocked("http://172.31.255.255/", BlockedHostClass::PrivateNetwork);
2037        assert_blocked("http://192.168.1.1/", BlockedHostClass::PrivateNetwork);
2038        // CGNAT shared space.
2039        assert_blocked("http://100.64.0.1/", BlockedHostClass::PrivateNetwork);
2040    }
2041
2042    #[test]
2043    fn link_local_and_cloud_metadata_are_blocked() {
2044        assert_blocked(
2045            "http://169.254.169.254/latest/meta-data/",
2046            BlockedHostClass::LinkLocalMetadata,
2047        );
2048        assert_blocked("http://169.254.0.1/", BlockedHostClass::LinkLocalMetadata);
2049        assert_blocked(
2050            "http://metadata.google.internal/",
2051            BlockedHostClass::LinkLocalMetadata,
2052        );
2053        assert_blocked(
2054            "http://anything.internal/",
2055            BlockedHostClass::LinkLocalMetadata,
2056        );
2057    }
2058
2059    #[test]
2060    fn ipv4_mapped_ipv6_is_blocked_by_embedded_class() {
2061        // ::ffff:127.0.0.1 → loopback
2062        assert_blocked("http://[::ffff:127.0.0.1]/", BlockedHostClass::Loopback);
2063        // ::ffff:10.0.0.1 → private network
2064        assert_blocked(
2065            "http://[::ffff:10.0.0.1]/",
2066            BlockedHostClass::PrivateNetwork,
2067        );
2068        // ::ffff:169.254.169.254 → link-local/metadata
2069        assert_blocked(
2070            "http://[::ffff:169.254.169.254]/",
2071            BlockedHostClass::LinkLocalMetadata,
2072        );
2073    }
2074
2075    #[test]
2076    fn ipv6_unique_local_and_link_local_are_blocked() {
2077        assert_blocked("http://[fc00::1]/", BlockedHostClass::PrivateNetwork);
2078        assert_blocked("http://[fd12:3456::1]/", BlockedHostClass::PrivateNetwork);
2079        assert_blocked("http://[fe80::1]/", BlockedHostClass::LinkLocalMetadata);
2080    }
2081
2082    #[test]
2083    fn disallowed_schemes_are_blocked() {
2084        assert_blocked("file:///etc/passwd", BlockedHostClass::DisallowedScheme);
2085        assert_blocked("ftp://example.com/", BlockedHostClass::DisallowedScheme);
2086        assert_blocked(
2087            "data:text/html,<h1>hi</h1>",
2088            BlockedHostClass::DisallowedScheme,
2089        );
2090    }
2091
2092    #[test]
2093    fn malformed_urls_are_blocked() {
2094        assert_eq!(
2095            classify_blocked_host("not a url"),
2096            Some(BlockedHostClass::Malformed)
2097        );
2098        assert_eq!(
2099            classify_blocked_host("http://"),
2100            Some(BlockedHostClass::Malformed)
2101        );
2102    }
2103
2104    #[test]
2105    fn resolve_path_classifies_private_targets() {
2106        // A raw-IP host with an explicit port exercises the resolve→classify
2107        // path (to_socket_addrs succeeds and yields the embedded IP). This is
2108        // the same code path a DNS-rebinding host would hit when it resolves to
2109        // a private address — deterministic in CI because no real DNS is needed.
2110        assert_blocked("http://10.1.2.3:8443/x", BlockedHostClass::PrivateNetwork);
2111        assert_blocked("http://127.0.0.1:9000/x", BlockedHostClass::Loopback);
2112        // An unresolvable non-IP host is NOT falsely reported as blocked here —
2113        // the validator lets such a request fail naturally at connect time. This
2114        // documents that pure DNS-rebinding (public name → private A-record at
2115        // request time) is only catchable at request time (see browser
2116        // request-interception deferral), not by this pre-flight check.
2117        assert_eq!(
2118            classify_blocked_host("http://nonexistent-host.invalid/"),
2119            None,
2120            "unresolvable host is not pre-flight blocked (request-time only)"
2121        );
2122    }
2123
2124    #[test]
2125    fn public_urls_are_allowed() {
2126        assert_allowed("https://example.com/");
2127        assert_allowed("https://www.rust-lang.org/learn");
2128        assert_allowed("http://93.184.216.34/"); // example.com public IP
2129        assert_allowed("https://8.8.8.8/");
2130    }
2131
2132    #[test]
2133    fn labels_are_fixed_and_leak_no_data() {
2134        // Every label is a fixed class string with no caller data.
2135        for class in [
2136            BlockedHostClass::Loopback,
2137            BlockedHostClass::PrivateNetwork,
2138            BlockedHostClass::LinkLocalMetadata,
2139            BlockedHostClass::DisallowedScheme,
2140            BlockedHostClass::Malformed,
2141            BlockedHostClass::OtherReserved,
2142        ] {
2143            let label = class.label();
2144            assert!(!label.is_empty());
2145            // No URL syntax, no scheme, no query, no credentials.
2146            for forbidden in ["://", "?", "=", "@", "127.", "169.254", "secret"] {
2147                assert!(
2148                    !label.contains(forbidden),
2149                    "label {label:?} must not contain {forbidden:?}"
2150                );
2151            }
2152        }
2153    }
2154}
2155
2156#[cfg(test)]
2157mod format_tests {
2158    use super::*;
2159
2160    #[test]
2161    fn truncated_fetch_carries_instructional_notice() {
2162        let text = "a".repeat(120);
2163        let (out, truncation) = format_fetch_result("https://example.com/page", &text, 50);
2164        assert!(out.contains("Content from https://example.com/page"));
2165        // The notice is metadata, not embedded text — text-scanning consumers
2166        // (classifiers, summaries) must see clean output.
2167        assert!(!out.contains("OUTPUT TRUNCATED"));
2168        assert!(!out.contains("[Truncated]"));
2169        let info = truncation.expect("truncation info");
2170        assert_eq!(info.total_chars, 120);
2171        assert_eq!(info.shown_chars, 50);
2172        // Remediation hint must be fetch-flavored, not terminal-flavored, and
2173        // preserved verbatim.
2174        let hint = info.remediation_hint.expect("remediation hint");
2175        assert!(hint.contains("max_chars"));
2176        assert!(!hint.contains("wc -l"));
2177    }
2178
2179    /// A synthetic download page: a short release list, one long prose
2180    /// section and a lot of navigation, shaped like real listing pages.
2181    fn listing_page() -> String {
2182        let nav: String = (0..400)
2183            .map(|i| format!("<li><a href=\"/nav/{i}\">Section {i} overview</a></li>"))
2184            .collect();
2185        let prose: String = (0..12)
2186            .map(|i| {
2187                format!(
2188                    "<p>Paragraph {i} explains how release artifacts are signed and how a \
2189                     careful user can check that a downloaded installer is genuine before \
2190                     running it on their machine, step by step.</p>"
2191                )
2192            })
2193            .collect();
2194        format!(
2195            "<html><body><nav><ul>{nav}</ul></nav>\
2196             <div class=\"releases\"><h2>Downloads</h2><ul>\
2197             <li><a href=\"/r/9.4.2\">Download Acme 9.4.2</a></li>\
2198             <li><a href=\"/r/9.4.1\">Acme 9.4.1</a></li></ul></div>\
2199             <div class=\"article\"><h2>Verifying downloads</h2>{prose}</div>\
2200             </body></html>"
2201        )
2202    }
2203
2204    /// A page whose one heading is its title keeps that heading: readability
2205    /// drops it, and the model would fetch the page again to find it.
2206    #[test]
2207    fn the_page_heading_survives_extraction() {
2208        // Shaped like example.com: a title, no heading, one paragraph.
2209        let html = "<!doctype html><html lang=en><head><meta charset=utf-8>\
2210                    <title>Example Domain</title><style>body{margin:auto}</style></head>\
2211                    <body><p>This domain is for use in synthetic documentation examples \
2212                    without needing permission.</p><script src=/s.js></script></body></html>";
2213        let text = extract_page_text(html, "https://example.com/");
2214        let first = text
2215            .lines()
2216            .find(|line| !line.trim().is_empty())
2217            .unwrap_or("");
2218        assert!(first.contains("Example Domain"), "{text}");
2219        assert!(text.contains("synthetic documentation"), "{text}");
2220        assert!(!text.contains("isReaderPage"), "{text}");
2221        // A heading in the body stays apart from the paragraph after it, and
2222        // is not added again.
2223        let html = "<html><head><title>Example Domain</title></head><body><div>\
2224                    <h1>Example Domain</h1><p>This domain is for use in synthetic \
2225                    documentation examples without needing permission.</p></div></body></html>";
2226        let text = extract_page_text(html, "https://example.com/");
2227        assert!(text.contains("# Example Domain"), "{text}");
2228        assert!(text.matches("Example Domain").count() <= 2, "{text}");
2229        assert!(!text.contains("DomainThis"), "{text}");
2230        // A title only, and a heading with markup inside.
2231        assert_eq!(
2232            page_heading("<title> Synthetic  Page </title><p>x</p>").as_deref(),
2233            Some("Synthetic Page")
2234        );
2235        assert_eq!(
2236            page_heading("<h10>no</h10><h1 class=\"t\">A <b>bold</b> &amp; plain</h1>").as_deref(),
2237            Some("A bold & plain")
2238        );
2239        assert_eq!(page_heading("<p>nothing</p>"), None);
2240    }
2241
2242    #[test]
2243    fn listing_page_keeps_content_readability_would_drop() {
2244        let text = extract_page_text(&listing_page(), "https://acme.example/downloads/");
2245        assert!(
2246            text.contains("Download Acme 9.4.2"),
2247            "{}",
2248            &text[..text.len().min(400)]
2249        );
2250    }
2251
2252    #[test]
2253    fn long_article_still_uses_readability() {
2254        let nav: String = (0..200)
2255            .map(|i| format!("<li><a href=\"/nav/{i}\">Menu entry {i}</a></li>"))
2256            .collect();
2257        let body: String = (0..120)
2258            .map(|i| {
2259                format!(
2260                    "<p>Paragraph {i} of a long synthetic article about mountain cities, \
2261                     their climate, history and the people who live there today.</p>"
2262                )
2263            })
2264            .collect();
2265        let html = format!(
2266            "<html><body><nav><ul>{nav}</ul></nav><article><h1>Mountain cities</h1>{body}</article></body></html>"
2267        );
2268        let text = extract_page_text(&html, "https://wiki.example/mountain");
2269        assert!(text.contains("Paragraph 119"));
2270        assert!(
2271            !text.contains("Menu entry 150"),
2272            "navigation leaked into an article"
2273        );
2274    }
2275
2276    #[test]
2277    fn untruncated_fetch_has_no_notice() {
2278        let (out, truncation) = format_fetch_result("https://example.com", "short content", 1000);
2279        assert!(out.contains("short content"));
2280        assert!(!out.contains("OUTPUT TRUNCATED"));
2281        assert!(truncation.is_none());
2282    }
2283
2284    #[test]
2285    fn truncation_respects_char_boundaries() {
2286        // 4-byte emoji straddling the cap must not panic.
2287        let text = format!("{}🦀🦀🦀", "x".repeat(49));
2288        let (_out, truncation) = format_fetch_result("https://example.com", &text, 51);
2289        assert!(truncation.is_some());
2290    }
2291
2292    #[test]
2293    fn fetch_result_truncation_is_metadata_not_text() {
2294        let long = "y".repeat(9000);
2295        let (text, truncation) = format_fetch_result("https://example.com", &long, 4000);
2296        assert!(!text.contains("OUTPUT TRUNCATED"));
2297        let info = truncation.expect("truncation info");
2298        assert_eq!(info.total_chars, 9000);
2299        assert!(
2300            info.remediation_hint
2301                .as_deref()
2302                .unwrap_or("")
2303                .contains("max_chars")
2304        );
2305    }
2306}
2307
2308#[cfg(test)]
2309mod extraction_tests {
2310    use super::*;
2311    use crate::semantics::ToolSemantics;
2312
2313    /// Mimics the observed Wikipedia failure: a large inline <script> block
2314    /// ahead of the real content leaked into the "extracted" text and
2315    /// consumed the whole max_chars window.
2316    fn script_heavy_page() -> String {
2317        format!(
2318            "<html><head><title>Ecuador national football team - Wikipedia</title>\
2319             <script>(function(){{var className=\"client-js vector-feature-language-{}\";}})();</script>\
2320             <style>.mw-parser{{display:none}}{}</style></head>\
2321             <body><h1>Squad</h1><p>{}</p>\
2322             <table><tr><td>Willian Pacho</td></tr><tr><td>Moises Caicedo</td></tr></table>\
2323             </body></html>",
2324            "x".repeat(8_000),
2325            "y".repeat(8_000),
2326            "The current squad was announced ahead of the tournament. ".repeat(20),
2327        )
2328    }
2329
2330    #[test]
2331    fn script_and_style_blocks_never_reach_the_model() {
2332        let (reply, _truncation) = build_fetch_reply(
2333            "https://en.wikipedia.org/wiki/X",
2334            &script_heavy_page(),
2335            2_000,
2336        );
2337        assert!(
2338            !reply.contains("var className"),
2339            "script body leaked: {}",
2340            reply
2341        );
2342        assert!(
2343            !reply.contains("display:none"),
2344            "style body leaked: {}",
2345            reply
2346        );
2347        assert!(reply.contains("Willian Pacho") || reply.contains("current squad"));
2348    }
2349
2350    #[test]
2351    fn near_empty_extraction_gets_instructional_notice() {
2352        // Big page, no readable text — the JS-rendered-page signature.
2353        let html = format!(
2354            "<html><head><script>{}</script></head><body><div id=\"root\"></div></body></html>",
2355            "z".repeat(20_000)
2356        );
2357        let (reply, truncation) = build_fetch_reply("https://spa.example.com", &html, 20_000);
2358        assert!(
2359            reply.contains("EXTRACTION FAILED"),
2360            "missing notice: {}",
2361            reply
2362        );
2363        assert!(reply.contains("different source"));
2364        // Must not pretend the page was read.
2365        assert!(!reply.contains("OUTPUT TRUNCATED"));
2366        assert!(truncation.is_none());
2367    }
2368
2369    #[test]
2370    fn normal_page_has_no_extraction_notice() {
2371        let (reply, _truncation) =
2372            build_fetch_reply("https://example.com", &script_heavy_page(), 20_000);
2373        assert!(!reply.contains("EXTRACTION FAILED"));
2374    }
2375
2376    #[test]
2377    fn small_thin_pages_are_not_flagged() {
2378        // A genuinely tiny page is not an extraction failure.
2379        let (reply, _truncation) = build_fetch_reply(
2380            "https://example.com",
2381            "<html><body><p>hi</p></body></html>",
2382            20_000,
2383        );
2384        assert!(!reply.contains("EXTRACTION FAILED"));
2385    }
2386
2387    #[test]
2388    fn append_capped_respects_byte_ceiling() {
2389        // Under the cap: whole chunk appended, not truncated.
2390        let mut buf = Vec::new();
2391        assert!(!append_capped(&mut buf, b"hello", 100));
2392        assert_eq!(buf, b"hello");
2393
2394        // Exactly at the cap: still appended fully, not truncated.
2395        let mut buf = vec![0u8; 8];
2396        assert!(!append_capped(&mut buf, &[1u8, 2u8], 10));
2397        assert_eq!(buf.len(), 10);
2398
2399        // Over the cap: partial copy up to the ceiling, truncated reported.
2400        let mut buf = vec![0u8; 8];
2401        assert!(append_capped(&mut buf, &[1, 2, 3, 4], 10));
2402        assert_eq!(buf.len(), 10);
2403
2404        // Already full: nothing copied, truncation reported.
2405        let mut buf = vec![0u8; 10];
2406        assert!(append_capped(&mut buf, b"x", 10));
2407        assert_eq!(buf.len(), 10);
2408    }
2409
2410    #[test]
2411    fn append_capped_truncation_is_utf8_safe() {
2412        // "€" is 3 bytes (E2 82 AC); capping at 3 keeps "ab" + 1 byte of it.
2413        // Decoding the capped bytes with from_utf8_lossy must not panic.
2414        let mut buf = Vec::new();
2415        assert!(append_capped(&mut buf, "ab€".as_bytes(), 3));
2416        assert_eq!(buf.len(), 3);
2417        let s = String::from_utf8_lossy(&buf);
2418        assert!(s.starts_with("ab"));
2419    }
2420
2421    #[test]
2422    fn web_fetch_declares_egress_host() {
2423        let tool = WebFetch::new();
2424        let effects =
2425            tool.call_effects(&json!({"url": "https://Docs.Example.Invalid/guide"}).to_string());
2426        assert!(effects.complete);
2427        assert_eq!(
2428            effects.keys,
2429            vec![aidaemon_core::EffectKey::egress(
2430                "https",
2431                "docs.example.invalid",
2432                None
2433            )]
2434        );
2435        let bad = tool.call_effects(&json!({"url": "::"}).to_string());
2436        assert!(!bad.complete);
2437    }
2438}