Skip to main content

vtcode_core/tools/web_search/
parser.rs

1//! Pure DuckDuckGo HTML extraction and result URL validation.
2
3use anyhow::{Result, anyhow};
4use astral_html::Token;
5use url::Url;
6
7use super::{SearchResult, truncate_chars};
8
9const MAX_TITLE_CHARS: usize = 200;
10const MAX_SNIPPET_CHARS: usize = 400;
11
12/// Parse one DDG response and reject known anti-bot pages before they can be
13/// mistaken for a legitimate empty result set. A normal no-hit page has no
14/// result anchors and no challenge markers, so it remains a valid empty
15/// response and can be cached briefly.
16pub(super) fn parse_duckduckgo_response(body: &str, max_results: usize) -> Result<Vec<SearchResult>> {
17    let results = parse_duckduckgo_html(body, max_results);
18    if results.is_empty() && is_duckduckgo_challenge_page(body) {
19        return Err(anyhow!(
20            "DuckDuckGo returned an anti-bot challenge page instead of search results; wait before retrying from this network"
21        ));
22    }
23    Ok(results)
24}
25
26fn is_duckduckgo_challenge_page(body: &str) -> bool {
27    let lower = body.to_ascii_lowercase();
28    [
29        "anomaly detected",
30        "captcha",
31        "challenge-form",
32        "unusual traffic",
33        "verify you are human",
34        "are you a robot",
35    ]
36    .iter()
37    .any(|marker| lower.contains(marker))
38}
39
40/// Extract ranked results from a DuckDuckGo HTML body. Pure function so it can
41/// be exercised in unit tests against a local fixture (no live network).
42///
43/// Single streaming pass: a result anchor opens title collection, its first
44/// `</a>` completes it, and the following `result__snippet` element (before
45/// the next result anchor) supplies the snippet. First-close-wins keeps
46/// parity with the previous extractor on well-formed markup.
47pub fn parse_duckduckgo_html(body: &str, max_results: usize) -> Vec<SearchResult> {
48    let mut results = Vec::new();
49    let mut state = DdgSection::Idle;
50    for token in astral_html::Reader::new(body) {
51        if results.len() >= max_results {
52            break;
53        }
54        match token {
55            Token::StartTag(tag) => {
56                if tag.name == "a" && has_ddg_class(&tag, "result__a") {
57                    // A new result anchor ends the pending one (keeping an
58                    // empty snippet) and drops any partial buffers.
59                    if let DdgSection::AfterTitle { url, title } = std::mem::replace(&mut state, DdgSection::Idle) {
60                        push_ddg_result(&mut results, url, title, String::new(), max_results);
61                        if results.len() >= max_results {
62                            break;
63                        }
64                    }
65                    if !tag.self_closing {
66                        if let Some(href) = ddg_attr(&tag, "href") {
67                            state = DdgSection::InTitle { href: href.to_string(), buf: String::new() };
68                        }
69                    }
70                } else if matches!(state, DdgSection::AfterTitle { .. }) && has_ddg_class(&tag, "result__snippet") {
71                    if let DdgSection::AfterTitle { url, title } = std::mem::replace(&mut state, DdgSection::Idle) {
72                        if tag.self_closing {
73                            push_ddg_result(&mut results, url, title, String::new(), max_results);
74                        } else {
75                            state = DdgSection::InSnippet {
76                                url,
77                                title,
78                                name: tag.name.to_string(),
79                                buf: String::new(),
80                            };
81                        }
82                    }
83                }
84                // All other tags are content or noise: nested formatting
85                // text arrives as Text tokens; nothing to do here.
86            }
87            Token::Text(text) => match &mut state {
88                DdgSection::InTitle { buf, .. } | DdgSection::InSnippet { buf, .. } => {
89                    buf.push_str(&text);
90                }
91                DdgSection::Idle | DdgSection::AfterTitle { .. } => {}
92            },
93            Token::EndTag(tag) => {
94                if tag.name == "a" && matches!(state, DdgSection::InTitle { .. }) {
95                    if let DdgSection::InTitle { href, buf } = std::mem::replace(&mut state, DdgSection::Idle) {
96                        let title = buf.trim().to_string();
97                        if !title.is_empty() {
98                            if let Some(url) = normalize_ddg_url(&href) {
99                                state = DdgSection::AfterTitle { url, title };
100                            }
101                        }
102                    }
103                } else if matches!(state, DdgSection::InSnippet { .. }) {
104                    let done = if let DdgSection::InSnippet { name, .. } = &state {
105                        tag.name == *name
106                    } else {
107                        false
108                    };
109                    if done {
110                        if let DdgSection::InSnippet { url, title, buf, .. } =
111                            std::mem::replace(&mut state, DdgSection::Idle)
112                        {
113                            push_ddg_result(&mut results, url, title, buf, max_results);
114                        }
115                    }
116                }
117            }
118            _ => {}
119        }
120    }
121    // Trailing result without a snippet element keeps an empty snippet.
122    if let DdgSection::AfterTitle { url, title } = state {
123        push_ddg_result(&mut results, url, title, String::new(), max_results);
124    }
125    results
126}
127
128/// Tokenizer position while extracting one result: idle, collecting the
129/// anchor title, holding a completed title, or collecting its snippet.
130enum DdgSection {
131    Idle,
132    InTitle {
133        href: String,
134        buf: String,
135    },
136    AfterTitle {
137        url: String,
138        title: String,
139    },
140    InSnippet {
141        url: String,
142        title: String,
143        name: String,
144        buf: String,
145    },
146}
147
148/// Decoded value of attribute `name` on `tag`, if present. Attribute names
149/// are ASCII-lowercased by the tokenizer, so plain equality applies.
150fn ddg_attr(tag: &astral_html::Tag<'_>, name: &str) -> Option<String> {
151    tag.attributes
152        .iter()
153        .find(|attr| attr.name == name)
154        .map(|attr| attr.value().to_string())
155}
156
157/// Whether the tag's `class` attribute carries `class` as a whitespace
158/// separated token (ASCII case-insensitive, matching DDG's lowercase).
159fn has_ddg_class(tag: &astral_html::Tag<'_>, class: &str) -> bool {
160    tag.attributes
161        .iter()
162        .find(|attr| attr.name == "class")
163        .is_some_and(|attr| attr.value().split_whitespace().any(|token| token.eq_ignore_ascii_case(class)))
164}
165
166/// Append one validated result unless the cap is reached. Callers validate
167/// the URL and require a non-empty title before reaching `AfterTitle`, so
168/// this only truncates and pushes.
169fn push_ddg_result(results: &mut Vec<SearchResult>, url: String, title: String, snippet: String, max_results: usize) {
170    if results.len() >= max_results {
171        return;
172    }
173    results.push(SearchResult {
174        title: truncate_chars(&title, MAX_TITLE_CHARS),
175        url,
176        snippet: truncate_chars(&snippet, MAX_SNIPPET_CHARS),
177    });
178}
179
180/// Resolve a DuckDuckGo result href into a real https/http URL.
181///
182/// DDG wraps targets in a redirector like `//duckduckgo.com/l/?uddg=<encoded>`.
183/// Returns `None` for non-http(s) schemes (defends against `javascript:` etc).
184fn normalize_ddg_url(href: &str) -> Option<String> {
185    let absolute = if let Some(stripped) = href.strip_prefix("//") {
186        format!("https://{stripped}")
187    } else {
188        href.to_string()
189    };
190
191    let parsed = Url::parse(&absolute).ok()?;
192    if let Some((_, target)) = parsed.query_pairs().find(|(k, _)| k == "uddg") {
193        let target = target.into_owned();
194        return validate_result_url(&target);
195    }
196    validate_result_url(&absolute)
197}
198
199/// Only allow http(s) result URLs with a host.
200fn validate_result_url(url: &str) -> Option<String> {
201    let parsed = Url::parse(url).ok()?;
202    match parsed.scheme() {
203        "http" | "https" => {}
204        _ => return None,
205    }
206    if parsed.host_str().is_none_or(str::is_empty) {
207        return None;
208    }
209    if !parsed.username().is_empty() || parsed.password().is_some() {
210        return None;
211    }
212    Some(url.to_string())
213}
214
215#[cfg(test)]
216mod tests;