Skip to main content

vtcode_core/tools/web_fetch/
classify_helpers.rs

1//! Shared error classification helpers used by `web_fetch` and `web_search`.
2//!
3//! Each tool produces a different response shape, so the helpers here
4//! focus on the lower-level primitives: pulling an HTTP status code out
5//! of a reqwest error string, mapping a status / keyword to a
6//! category, and decoding HTML entities in scraped text. The per-tool
7//! `next_action` text lives next to the tool's own response builder.
8
9use regex::Regex;
10use std::sync::{LazyLock, OnceLock};
11
12/// Pull an HTTP status code out of a reqwest error string.
13///
14/// reqwest error messages take a few shapes:
15///
16/// - `error sending request for url (https://example.com/): ...`
17/// - `HTTP status server error (503 Service Unavailable) for url (...)`
18/// - `... status: 403 Forbidden ...` (custom errors that include a status)
19/// - `request timed out after 30s` (no status; caller should treat as
20///   network error)
21///
22/// A regex that matches either the `HTTP ... <3-digit>` shape (the
23/// reqwest server-error format) or the `status: <3-digit>` shape
24/// (custom errors that surface the status code) is the most robust
25/// shape we can support without depending on reqwest's internals.
26pub fn extract_http_status(message: &str) -> Option<u16> {
27    static RE: OnceLock<Regex> = OnceLock::new();
28    let re = RE.get_or_init(|| {
29        // Two alternations:
30        //   1. `\bhttp` (case-insensitive) followed by non-digits and a
31        //      3-digit number — matches "HTTP status server error
32        //      (503 ...", "http 500 ...", etc.
33        //   2. `status:` (case-insensitive) followed by a 3-digit
34        //      number — matches "error: status: 403 Forbidden", custom
35        //      error chains, and so on.
36        // The non-digit gap on the first branch is bounded at 64 chars
37        // to keep the match cheap while still covering the longest
38        // realistic reqwest format.
39        Regex::new(r"(?i)\bhttp[^0-9]{0,64}(\d{3})\b|\bstatus:\s*(\d{3})\b").expect("valid status regex")
40    });
41    let caps = re.captures(message)?;
42    // The matched number is in either capture group 1 or 2 depending
43    // on which alternation fired.
44    caps.get(1).or_else(|| caps.get(2)).and_then(|m| m.as_str().parse().ok())
45}
46
47static HTML_DEC_ENTITY: LazyLock<Regex> =
48    LazyLock::new(|| Regex::new(r"&#([0-9]{1,7});").expect("valid decimal entity regex"));
49static HTML_HEX_ENTITY: LazyLock<Regex> =
50    LazyLock::new(|| Regex::new(r"(?i)&#x([0-9a-f]{1,6});").expect("valid hex entity regex"));
51
52/// Decode one numeric character reference (`caps[1]` in `radix`); keep the
53/// original text when the digits are invalid or not a Unicode scalar value.
54fn decode_numeric_entity(caps: &regex::Captures, radix: u32) -> String {
55    let parsed = caps.get(1).and_then(|m| {
56        if radix == 16 {
57            u32::from_str_radix(m.as_str(), 16).ok()
58        } else {
59            m.as_str().parse::<u32>().ok()
60        }
61    });
62    parsed
63        .and_then(char::from_u32)
64        .map(|ch| ch.to_string())
65        .unwrap_or_else(|| caps.get(0).map(|m| m.as_str()).unwrap_or_default().to_string())
66}
67
68/// Decode HTML character references (numeric decimal/hex plus common named
69/// entities) in scraped text. Invalid code points keep their original text.
70/// `&amp;` decodes last so `&amp;lt;` yields `&lt;`, not `<`.
71pub(crate) fn decode_html_entities(input: &str) -> String {
72    // Numeric references first (decimal + hex); invalid code points keep
73    // their original text rather than panicking or emitting replacement.
74    let hex_decoded = HTML_HEX_ENTITY.replace_all(input, |caps: &regex::Captures| decode_numeric_entity(caps, 16));
75    let num_decoded =
76        HTML_DEC_ENTITY.replace_all(&hex_decoded, |caps: &regex::Captures| decode_numeric_entity(caps, 10));
77    // Named references next, with `&amp;` last so `&amp;lt;` decodes to
78    // `&lt;` (single pass) rather than `<` (double decode).
79    num_decoded
80        .replace("&lt;", "<")
81        .replace("&gt;", ">")
82        .replace("&quot;", "\"")
83        .replace("&#39;", "'")
84        .replace("&apos;", "'")
85        .replace("&#x27;", "'")
86        .replace("&#x2F;", "/")
87        .replace("&nbsp;", " ")
88        .replace("&hellip;", "…")
89        .replace("&rsquo;", "’")
90        .replace("&lsquo;", "‘")
91        .replace("&rdquo;", "”")
92        .replace("&ldquo;", "“")
93        .replace("&ndash;", "–")
94        .replace("&mdash;", "—")
95        .replace("&copy;", "©")
96        .replace("&reg;", "®")
97        .replace("&times;", "×")
98        .replace("&middot;", "·")
99        .replace("&amp;", "&")
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn extract_status_handles_common_shapes() {
108        assert_eq!(
109            extract_http_status("HTTP status server error (503 Service Unavailable) for url (https://example.com/)"),
110            Some(503)
111        );
112        assert_eq!(extract_http_status("error sending request: status: 403 Forbidden"), Some(403));
113        // Bare `<num>` without an `http` / `status:` prefix is not a
114        // status code; the parser should not match. (Real reqwest error
115        // chains always include a sentinel word before the code.)
116        assert_eq!(extract_http_status("server returned 404"), None);
117        assert_eq!(extract_http_status("request timed out after 30s"), None);
118        assert_eq!(extract_http_status("no error here"), None);
119    }
120
121    #[test]
122    fn extract_status_ignores_non_three_digit_numbers() {
123        // The regex requires exactly 3 digits. Larger numbers that happen
124        // to appear in error text (e.g. a timeout duration, a chunk
125        // size) must not be misread.
126        assert_eq!(extract_http_status("timed out after 30000ms"), None);
127        assert_eq!(extract_http_status("response body 1234 bytes"), None);
128    }
129
130    #[test]
131    fn extract_status_handles_status_with_spaces() {
132        // `status:` followed by whitespace and a 3-digit code.
133        assert_eq!(extract_http_status("error: status:    429 Too Many Requests"), Some(429));
134    }
135}