vtcode_core/tools/web_search/
parser.rs1use 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
12pub(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
40pub 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 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 }
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 if let DdgSection::AfterTitle { url, title } = state {
123 push_ddg_result(&mut results, url, title, String::new(), max_results);
124 }
125 results
126}
127
128enum 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
148fn 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
157fn 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
166fn 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
180fn 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
199fn 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;