Skip to main content

vtcode_core/tools/web_search/
mod.rs

1//! WebSearch tool: query -> ranked web results (title, url, snippet).
2//!
3//! The keyless DuckDuckGo HTML endpoint provides best-effort ranked results and
4//! may be rate-limited or challenged by anti-bot defenses.
5//!
6//! Safety/rate-limit guard rails:
7//! - A **cooldown** between consecutive network requests (default 3s) prevents
8//!   hammering DDG and triggering anti-bot challenges.
9//! - A short **result cache** (default 5min TTL) means repeated identical
10//!   queries are answered from memory without any network call.
11//! - A **session-wide cap** (default 12 requests) ensures the tool cannot
12//!   run away with varied queries. This is a conservative VTCode budget, not
13//!   a DuckDuckGo-published quota.
14//!
15//! All three are configurable via `WebSearchConfig` and turned off in tests.
16
17use super::traits::Tool;
18use crate::config::constants::tools;
19use anyhow::{Context, Result, anyhow};
20use astral_html::Token;
21use async_trait::async_trait;
22use futures::stream::StreamExt;
23use reqwest::header::{ACCEPT, HeaderMap, HeaderValue, USER_AGENT};
24use serde::Deserialize;
25use serde_json::{Value, json};
26use std::collections::HashMap;
27use std::sync::{Arc, Mutex};
28use std::time::{Duration, Instant};
29use url::Url;
30use vtcode_config::WebSearchConfig;
31
32const MIN_TIMEOUT_SECS: u64 = 1;
33const MAX_TIMEOUT_SECS: u64 = 60;
34const MAX_QUERY_CHARS: usize = 500;
35const MAX_RESULTS_CAP: usize = 20;
36const MAX_TITLE_CHARS: usize = 200;
37const MAX_SNIPPET_CHARS: usize = 400;
38
39/// Browser-like user agent. DuckDuckGo's HTML endpoint blocks obvious bots, so a
40/// realistic UA reduces (but does not eliminate) the chance of being challenged.
41const BROWSER_USER_AGENT: &str =
42    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36";
43
44pub(crate) const WEB_SEARCH_DESCRIPTION: &str = "Searches the web with keyless DuckDuckGo HTML search and returns ranked results (title, url, snippet). Accepts { query: string (up to 500 characters), max_results?: number }. Results are cached briefly to reduce rate limiting; cooldown and session caps bound requests. Use web_fetch on a promising result URL to read full content, subject to separate approval. Returns { query, provider, count, cached, results: [{ title, url, snippet }] } or a structured error with error_type, retryable, and next_action.";
45
46#[derive(Debug, Deserialize)]
47#[serde(deny_unknown_fields)]
48struct WebSearchArgs {
49    /// Search query.
50    query: String,
51    #[serde(default)]
52    max_results: Option<usize>,
53}
54
55pub struct SearchResult {
56    pub title: String,
57    pub url: String,
58    pub snippet: String,
59}
60
61impl SearchResult {
62    pub fn new(title: String, url: String, snippet: String) -> Self {
63        Self { title, url, snippet }
64    }
65}
66
67/// Lightweight in-process state shared between calls on the same tool
68/// instance. Owns the cooldown clock, the request counter, and the result
69/// cache.
70#[derive(Default)]
71struct SessionState {
72    last_request_at: Option<Instant>,
73    requests_made: u32,
74    cache: HashMap<String, CachedResults>,
75}
76
77struct CachedResults {
78    stored_at: Instant,
79    payload: Value,
80}
81
82impl SessionState {
83    fn cache_get(&self, key: &str, ttl: Duration) -> Option<Value> {
84        let entry = self.cache.get(key)?;
85        if entry.stored_at.elapsed() > ttl {
86            return None;
87        }
88        Some(entry.payload.clone())
89    }
90
91    fn cache_put(&mut self, key: String, payload: Value) {
92        self.cache.insert(key, CachedResults { stored_at: Instant::now(), payload });
93    }
94}
95
96/// WebSearch tool. Stateless over the network (DDG) but tracks per-instance
97/// cooldown, request cap, and short-lived result cache to avoid hammering
98/// DDG's HTML endpoint and triggering anti-bot challenges.
99#[derive(Clone, Default)]
100pub struct WebSearchTool {
101    config: Arc<Mutex<WebSearchConfig>>,
102    state: Arc<Mutex<SessionState>>,
103}
104
105impl WebSearchTool {
106    pub fn new() -> Self {
107        Self {
108            config: Arc::new(Mutex::new(WebSearchConfig::default())),
109            state: Arc::new(Mutex::new(SessionState::default())),
110        }
111    }
112
113    /// Construct a tool with an explicit configuration. The config drives the
114    /// result-count default, request timeout, cooldown, cache TTL, and
115    /// session-wide request cap.
116    pub fn with_config(config: WebSearchConfig) -> Self {
117        Self {
118            config: Arc::new(Mutex::new(config)),
119            state: Arc::new(Mutex::new(SessionState::default())),
120        }
121    }
122
123    /// Apply a new configuration (e.g., after `vtcode.toml` reload).
124    pub fn set_config(&self, config: WebSearchConfig) {
125        if let Ok(mut guard) = self.config.lock() {
126            *guard = config;
127        }
128    }
129
130    /// Reset the in-process state (cooldown, counter, cache). Tests use this.
131    pub fn reset(&self) {
132        if let Ok(mut guard) = self.state.lock() {
133            *guard = SessionState::default();
134        }
135    }
136
137    fn snapshot_config(&self) -> Result<WebSearchConfig> {
138        self.config
139            .lock()
140            .map(|guard| guard.clone())
141            .map_err(|error| anyhow!("web_search config lock poisoned: {error}"))
142    }
143
144    async fn run(&self, raw_args: Value) -> Result<Value> {
145        let args: WebSearchArgs =
146            serde_json::from_value(raw_args).context("Invalid arguments for web_search. Provide a 'query' string.")?;
147
148        let query = args.query.trim().to_string();
149        if query.is_empty() || query.chars().count() > MAX_QUERY_CHARS {
150            return Err(anyhow!("web_search requires a nonblank query of at most {MAX_QUERY_CHARS} characters"));
151        }
152
153        let snapshot = self.snapshot_config()?;
154        let default_max = snapshot.max_results.clamp(1, MAX_RESULTS_CAP);
155        let max_results = args.max_results.unwrap_or(default_max).clamp(1, MAX_RESULTS_CAP);
156        let cooldown = Duration::from_millis(snapshot.cooldown_ms);
157        let cache_ttl = Duration::from_secs(snapshot.cache_ttl_secs);
158        let session_cap = snapshot.session_max_requests;
159        let provider = snapshot.provider.backend_id();
160
161        // Include `max_results` in the key so a repeat query with a
162        // different cap gets a fresh, larger or smaller result set. With the
163        // hard 20-result cap this is rarely observable, but it keeps the
164        // cache semantics tight: the value the agent sees was produced for
165        // the same `max_results` it asked for.
166        let cache_key = format!("{max_results}::{query}");
167
168        // Fast path: cache hit. Avoid the network entirely.
169        let cached = self
170            .state
171            .lock()
172            .map_err(|error| anyhow!("web_search state lock poisoned: {error}"))?
173            .cache_get(&cache_key, cache_ttl);
174        if let Some(cached) = cached {
175            return Ok(mark_cached(cached, provider));
176        }
177
178        // Reserve the request before touching the network. The reservation is
179        // atomic with the cap/cooldown check, so concurrent calls cannot all
180        // pass admission and exceed the session budget.
181        if let Some(response) = self.admit_request(&query, provider, cooldown, session_cap)? {
182            return Ok(response);
183        }
184
185        let results = duckduckgo_search(&query, max_results, snapshot.timeout_secs).await;
186
187        match results {
188            Ok(results) => {
189                let payload = results_response(&query, provider, results);
190                self.cache_put(&cache_key, &payload)?;
191                Ok(payload)
192            }
193            Err(e) => {
194                // Categorize the error so the agent can act on it.
195                Ok(search_error_response(&query, provider, &e.to_string()))
196            }
197        }
198    }
199
200    fn cache_put(&self, key: &str, payload: &Value) -> Result<()> {
201        let mut state = self
202            .state
203            .lock()
204            .map_err(|error| anyhow!("web_search state lock poisoned: {error}"))?;
205        state.cache_put(key.to_string(), payload.clone());
206        Ok(())
207    }
208
209    fn admit_request(
210        &self,
211        query: &str,
212        provider: &str,
213        cooldown: Duration,
214        session_cap: u32,
215    ) -> Result<Option<Value>> {
216        let mut state = self.state.lock().map_err(|e| anyhow!("web_search state lock poisoned: {e}"))?;
217        if state.requests_made >= session_cap {
218            return Ok(Some(session_cap_reached_response(provider, query, session_cap)));
219        }
220        if let Some(last) = state.last_request_at {
221            let elapsed = last.elapsed();
222            if elapsed < cooldown {
223                return Ok(Some(cooldown_response(provider, query, cooldown.saturating_sub(elapsed))));
224            }
225        }
226        state.requests_made = state.requests_made.saturating_add(1);
227        state.last_request_at = Some(Instant::now());
228        Ok(None)
229    }
230}
231
232#[derive(Debug, Clone, Copy, PartialEq, Eq)]
233struct SearchErrorClassification {
234    error_type: &'static str,
235    next_action: &'static str,
236    retryable: bool,
237}
238
239/// Classify a search-provider error into the stable fields exposed to the
240/// agent. Anti-bot blocks are deliberately non-retryable; ordinary transport
241/// and upstream 5xx failures remain explicitly retryable.
242fn classify_search_error(message: &str) -> SearchErrorClassification {
243    let lower = message.to_lowercase();
244    let status = crate::tools::web_fetch::classify_helpers::extract_http_status(&lower);
245    if matches!(status, Some(202 | 403 | 429)) || lower.contains("anti-bot") || lower.contains("challenge") {
246        return SearchErrorClassification {
247            error_type: "antiban_blocked",
248            next_action: "DuckDuckGo declined this request (likely an anti-bot challenge for this network). Do not retry immediately from this network; pick a result URL from this session's earlier searches and use web_fetch on it instead, or ask the user to confirm a different search provider.",
249            retryable: false,
250        };
251    }
252    if lower.contains("response exceeds") || lower.contains("body exceeded") {
253        return SearchErrorClassification {
254            error_type: "response_too_large",
255            next_action: "DuckDuckGo returned an oversized response. Narrow the query before explicitly retrying.",
256            retryable: false,
257        };
258    }
259    if status.is_some_and(|status| (500..=599).contains(&status)) {
260        return SearchErrorClassification {
261            error_type: "upstream_error",
262            next_action: "The search service is currently unavailable. Retry once after a short delay, or use web_fetch on a known URL as a fallback.",
263            retryable: true,
264        };
265    }
266    if lower.contains("timeout") || lower.contains("timed out") {
267        return SearchErrorClassification {
268            error_type: "network_error",
269            next_action: "DuckDuckGo timed out. Retry once after a short delay, or use web_fetch on a known URL as a fallback.",
270            retryable: true,
271        };
272    }
273    SearchErrorClassification {
274        error_type: "network_error",
275        next_action: "Retry once after a short delay, or use web_fetch directly if you already know a relevant URL.",
276        retryable: true,
277    }
278}
279
280fn results_response(query: &str, provider: &str, results: Vec<SearchResult>) -> Value {
281    let count = results.len();
282    let mut payload = json!({
283        "query": query,
284        "provider": provider,
285        "count": count,
286        "cached": false,
287        "results": results
288            .into_iter()
289            .map(|result| json!({ "title": result.title, "url": result.url, "snippet": result.snippet }))
290            .collect::<Vec<_>>(),
291    });
292
293    if count == 0 {
294        payload["warning"] = json!(
295            "No results were returned. DuckDuckGo may have rate-limited the request or matched nothing. Try a different query, or wait a few seconds and try again."
296        );
297    }
298
299    payload
300}
301
302fn search_error_response(query: &str, provider: &str, message: &str) -> Value {
303    let classification = classify_search_error(message);
304    json!({
305        "error": format!("web_search failed: {message}"),
306        "query": query,
307        "provider": provider,
308        "error_type": classification.error_type,
309        "retryable": classification.retryable,
310        "next_action": classification.next_action,
311    })
312}
313
314fn mark_cached(mut payload: Value, provider: &str) -> Value {
315    if let Value::Object(map) = &mut payload {
316        map.insert("provider".to_string(), Value::String(provider.to_owned()));
317        map.insert("cached".to_string(), Value::Bool(true));
318    }
319    payload
320}
321
322fn cooldown_response(provider: &str, query: &str, wait: Duration) -> Value {
323    let retry_after_ms = wait.as_millis().clamp(1, u64::MAX as u128) as u64;
324    json!({
325        "error": "web_search cooldown active",
326        "query": query,
327        "provider": provider,
328        "error_type": "cooldown",
329        "retryable": true,
330        "retry_after_ms": retry_after_ms,
331        "next_action": format!("Wait at least {retry_after_ms} ms before the next web search to avoid being rate-limited.")
332    })
333}
334
335fn session_cap_reached_response(provider: &str, query: &str, cap: u32) -> Value {
336    json!({
337        "error": "web_search session request cap reached",
338        "query": query,
339        "provider": provider,
340        "error_type": "session_cap",
341        "retryable": false,
342        "session_max_requests": cap,
343        "request_budget_remaining": 0,
344        "next_action": format!("This session has used its {cap} web searches. Use web_fetch on a known URL or restart the session to search again.")
345    })
346}
347
348/// Build the HTTP client for the DuckDuckGo provider. Follow only HTTPS
349/// redirects that stay on the known DuckDuckGo HTML host; a compromised or
350/// misconfigured upstream must not turn search into an SSRF relay.
351fn build_client(timeout_secs: u64) -> Result<reqwest::Client> {
352    reqwest::Client::builder()
353        .timeout(Duration::from_secs(effective_timeout_secs(timeout_secs)))
354        .retry(reqwest::retry::never())
355        .redirect(reqwest::redirect::Policy::custom(|attempt| {
356            if attempt.previous().len() >= 3 {
357                return attempt.stop();
358            }
359            if is_allowed_ddg_redirect(attempt.url()) {
360                attempt.follow()
361            } else {
362                attempt.stop()
363            }
364        }))
365        .build()
366        .context("failed to build HTTP client for web_search")
367}
368
369fn effective_timeout_secs(timeout_secs: u64) -> u64 {
370    timeout_secs.clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS)
371}
372
373fn is_allowed_ddg_redirect(url: &Url) -> bool {
374    url.scheme() == "https" && url.host_str() == Some("html.duckduckgo.com")
375}
376
377// ---------------------------------------------------------------------------
378// DuckDuckGo (keyless, best-effort HTML scraping)
379//
380// Result extraction is tokenized with `astral-html`'s streaming `Reader`
381// (pinned pilot dependency, vtcode-core only): tag and attribute names
382// arrive ASCII-lowercased, text in `script`/`style` stays raw text instead
383// of spurious tags, and each snippet is collected from its own anchor's
384// window so a missing snippet yields empty rather than the next result's.
385// ---------------------------------------------------------------------------
386
387async fn duckduckgo_search(query: &str, max_results: usize, timeout_secs: u64) -> Result<Vec<SearchResult>> {
388    let client = build_client(timeout_secs)?;
389    let mut headers = HeaderMap::new();
390    headers.insert(USER_AGENT, HeaderValue::from_static(BROWSER_USER_AGENT));
391    headers.insert(ACCEPT, HeaderValue::from_static("text/html,application/xhtml+xml"));
392
393    // The HTML endpoint expects the query as a POST form field `q`.
394    let response = client
395        .post("https://html.duckduckgo.com/html/")
396        .headers(headers)
397        .form(&[("q", query)])
398        .send()
399        .await
400        .context("DuckDuckGo request failed")?;
401
402    let status = response.status();
403    // HTTP 202, 403, and 429 are common anti-bot responses. Treat them as a
404    // block rather than letting parsing or generic retry logic hide the cause.
405    if matches!(status.as_u16(), 202 | 403 | 429) {
406        return Err(anyhow!(
407            "DuckDuckGo declined the request (HTTP {status}), likely an anti-bot challenge for this network. Wait a few seconds and retry."
408        ));
409    }
410    if !status.is_success() {
411        return Err(anyhow!("DuckDuckGo returned HTTP {status}"));
412    }
413
414    let body = read_capped_ddg_body(response).await?;
415
416    parse_duckduckgo_response(&body, max_results)
417}
418
419/// Upper bound for a DuckDuckGo HTML answer body. Result pages are a few
420/// hundred kilobytes; the cap only bites on adversarial responses, and the
421/// streaming parser stops at `max_results` well before it anyway.
422const MAX_DDG_BODY_BYTES: usize = 1_000_000;
423
424/// Read a DDG response body with an explicit byte cap. Decoding is lossy
425/// rather than fallible: DuckDuckGo serves UTF-8, and a corrupt byte must
426/// not turn into a hard error when partial results will do.
427async fn read_capped_ddg_body(response: reqwest::Response) -> Result<String> {
428    if response
429        .content_length()
430        .is_some_and(|length| length > MAX_DDG_BODY_BYTES as u64)
431    {
432        return Err(anyhow!("DuckDuckGo response exceeds the {MAX_DDG_BODY_BYTES}-byte limit"));
433    }
434
435    let mut bytes = Vec::with_capacity(MAX_DDG_BODY_BYTES.min(64 * 1024));
436    let mut stream = response.bytes_stream();
437    while let Some(chunk) = stream.next().await {
438        let chunk = chunk.context("failed to read DuckDuckGo response body")?;
439        let remaining = MAX_DDG_BODY_BYTES.saturating_sub(bytes.len());
440        if chunk.len() > remaining {
441            return Err(anyhow!("DuckDuckGo response body exceeded the {MAX_DDG_BODY_BYTES}-byte limit"));
442        }
443        bytes.extend_from_slice(&chunk);
444    }
445    Ok(capped_body_text(&bytes))
446}
447
448/// Pure, testable core of [`read_capped_ddg_body`]: cap at
449/// `MAX_DDG_BODY_BYTES`, then lossy-decode (never panics, even on a split
450/// trailing char or leading garbage).
451fn capped_body_text(bytes: &[u8]) -> String {
452    let end = bytes.len().min(MAX_DDG_BODY_BYTES);
453    String::from_utf8_lossy(&bytes[..end]).into_owned()
454}
455
456/// Parse one DDG response and reject known anti-bot pages before they can be
457/// mistaken for a legitimate empty result set. A normal no-hit page has no
458/// result anchors and no challenge markers, so it remains a valid empty
459/// response and can be cached briefly.
460fn parse_duckduckgo_response(body: &str, max_results: usize) -> Result<Vec<SearchResult>> {
461    let results = parse_duckduckgo_html(body, max_results);
462    if results.is_empty() && is_duckduckgo_challenge_page(body) {
463        return Err(anyhow!(
464            "DuckDuckGo returned an anti-bot challenge page instead of search results; wait before retrying from this network"
465        ));
466    }
467    Ok(results)
468}
469
470fn is_duckduckgo_challenge_page(body: &str) -> bool {
471    let lower = body.to_ascii_lowercase();
472    [
473        "anomaly detected",
474        "captcha",
475        "challenge-form",
476        "unusual traffic",
477        "verify you are human",
478        "are you a robot",
479    ]
480    .iter()
481    .any(|marker| lower.contains(marker))
482}
483
484/// Extract ranked results from a DuckDuckGo HTML body. Pure function so it can
485/// be exercised in unit tests against a local fixture (no live network).
486///
487/// Single streaming pass: a result anchor opens title collection, its first
488/// `</a>` completes it, and the following `result__snippet` element (before
489/// the next result anchor) supplies the snippet. First-close-wins keeps
490/// parity with the previous extractor on well-formed markup.
491pub fn parse_duckduckgo_html(body: &str, max_results: usize) -> Vec<SearchResult> {
492    let mut results = Vec::new();
493    let mut state = DdgSection::Idle;
494    for token in astral_html::Reader::new(body) {
495        if results.len() >= max_results {
496            break;
497        }
498        match token {
499            Token::StartTag(tag) => {
500                if tag.name == "a" && has_ddg_class(&tag, "result__a") {
501                    // A new result anchor ends the pending one (keeping an
502                    // empty snippet) and drops any partial buffers.
503                    if let DdgSection::AfterTitle { url, title } = std::mem::replace(&mut state, DdgSection::Idle) {
504                        push_ddg_result(&mut results, url, title, String::new(), max_results);
505                        if results.len() >= max_results {
506                            break;
507                        }
508                    }
509                    if !tag.self_closing {
510                        if let Some(href) = ddg_attr(&tag, "href") {
511                            state = DdgSection::InTitle { href: href.to_string(), buf: String::new() };
512                        }
513                    }
514                } else if matches!(state, DdgSection::AfterTitle { .. }) && has_ddg_class(&tag, "result__snippet") {
515                    if let DdgSection::AfterTitle { url, title } = std::mem::replace(&mut state, DdgSection::Idle) {
516                        if tag.self_closing {
517                            push_ddg_result(&mut results, url, title, String::new(), max_results);
518                        } else {
519                            state = DdgSection::InSnippet {
520                                url,
521                                title,
522                                name: tag.name.to_string(),
523                                buf: String::new(),
524                            };
525                        }
526                    }
527                }
528                // All other tags are content or noise: nested formatting
529                // text arrives as Text tokens; nothing to do here.
530            }
531            Token::Text(text) => match &mut state {
532                DdgSection::InTitle { buf, .. } | DdgSection::InSnippet { buf, .. } => {
533                    buf.push_str(&text);
534                }
535                DdgSection::Idle | DdgSection::AfterTitle { .. } => {}
536            },
537            Token::EndTag(tag) => {
538                if tag.name == "a" && matches!(state, DdgSection::InTitle { .. }) {
539                    if let DdgSection::InTitle { href, buf } = std::mem::replace(&mut state, DdgSection::Idle) {
540                        let title = buf.trim().to_string();
541                        if !title.is_empty() {
542                            if let Some(url) = normalize_ddg_url(&href) {
543                                state = DdgSection::AfterTitle { url, title };
544                            }
545                        }
546                    }
547                } else if matches!(state, DdgSection::InSnippet { .. }) {
548                    let done = if let DdgSection::InSnippet { name, .. } = &state {
549                        tag.name == *name
550                    } else {
551                        false
552                    };
553                    if done {
554                        if let DdgSection::InSnippet { url, title, buf, .. } =
555                            std::mem::replace(&mut state, DdgSection::Idle)
556                        {
557                            push_ddg_result(&mut results, url, title, buf, max_results);
558                        }
559                    }
560                }
561            }
562            _ => {}
563        }
564    }
565    // Trailing result without a snippet element keeps an empty snippet.
566    if let DdgSection::AfterTitle { url, title } = state {
567        push_ddg_result(&mut results, url, title, String::new(), max_results);
568    }
569    results
570}
571
572/// Tokenizer position while extracting one result: idle, collecting the
573/// anchor title, holding a completed title, or collecting its snippet.
574enum DdgSection {
575    Idle,
576    InTitle {
577        href: String,
578        buf: String,
579    },
580    AfterTitle {
581        url: String,
582        title: String,
583    },
584    InSnippet {
585        url: String,
586        title: String,
587        name: String,
588        buf: String,
589    },
590}
591
592/// Decoded value of attribute `name` on `tag`, if present. Attribute names
593/// are ASCII-lowercased by the tokenizer, so plain equality applies.
594fn ddg_attr(tag: &astral_html::Tag<'_>, name: &str) -> Option<String> {
595    tag.attributes
596        .iter()
597        .find(|attr| attr.name == name)
598        .map(|attr| attr.value().to_string())
599}
600
601/// Whether the tag's `class` attribute carries `class` as a whitespace
602/// separated token (ASCII case-insensitive, matching DDG's lowercase).
603fn has_ddg_class(tag: &astral_html::Tag<'_>, class: &str) -> bool {
604    tag.attributes
605        .iter()
606        .find(|attr| attr.name == "class")
607        .is_some_and(|attr| attr.value().split_whitespace().any(|token| token.eq_ignore_ascii_case(class)))
608}
609
610/// Append one validated result unless the cap is reached. Callers validate
611/// the URL and require a non-empty title before reaching `AfterTitle`, so
612/// this only truncates and pushes.
613fn push_ddg_result(results: &mut Vec<SearchResult>, url: String, title: String, snippet: String, max_results: usize) {
614    if results.len() >= max_results {
615        return;
616    }
617    results.push(SearchResult {
618        title: truncate_chars(&title, MAX_TITLE_CHARS),
619        url,
620        snippet: truncate_chars(&snippet, MAX_SNIPPET_CHARS),
621    });
622}
623
624/// Resolve a DuckDuckGo result href into a real https/http URL.
625///
626/// DDG wraps targets in a redirector like `//duckduckgo.com/l/?uddg=<encoded>`.
627/// Returns `None` for non-http(s) schemes (defends against `javascript:` etc).
628fn normalize_ddg_url(href: &str) -> Option<String> {
629    let absolute = if let Some(stripped) = href.strip_prefix("//") {
630        format!("https://{stripped}")
631    } else {
632        href.to_string()
633    };
634
635    let parsed = Url::parse(&absolute).ok()?;
636    if let Some((_, target)) = parsed.query_pairs().find(|(k, _)| k == "uddg") {
637        let target = target.into_owned();
638        return validate_result_url(&target);
639    }
640    validate_result_url(&absolute)
641}
642
643/// Only allow http(s) result URLs with a host.
644fn validate_result_url(url: &str) -> Option<String> {
645    let parsed = Url::parse(url).ok()?;
646    match parsed.scheme() {
647        "http" | "https" => {}
648        _ => return None,
649    }
650    if parsed.host_str().is_none_or(str::is_empty) {
651        return None;
652    }
653    if !parsed.username().is_empty() || parsed.password().is_some() {
654        return None;
655    }
656    Some(url.to_string())
657}
658
659// ---------------------------------------------------------------------------
660// Helpers
661// ---------------------------------------------------------------------------
662
663fn truncate_chars(input: &str, max_chars: usize) -> String {
664    vtcode_commons::formatting::truncate_text(input.trim(), max_chars, "…")
665}
666
667#[async_trait]
668impl Tool for WebSearchTool {
669    async fn execute(&self, args: Value) -> Result<Value> {
670        self.run(args).await
671    }
672
673    fn name(&self) -> &str {
674        tools::WEB_SEARCH
675    }
676
677    fn description(&self) -> &str {
678        WEB_SEARCH_DESCRIPTION
679    }
680}
681
682#[cfg(test)]
683mod tests {
684    use super::*;
685    use crate::tools::web_fetch::classify_helpers::decode_html_entities;
686    use vtcode_config::WebSearchProvider;
687
688    #[test]
689    fn normalize_ddg_url_extracts_uddg_target() {
690        let href = "//duckduckgo.com/l/?uddg=https%3A%2F%2Fgithub.com%2Fvinhnx&rut=abc";
691        assert_eq!(normalize_ddg_url(href).as_deref(), Some("https://github.com/vinhnx"));
692    }
693
694    #[test]
695    fn normalize_ddg_url_passes_through_direct_https() {
696        let href = "https://example.com/page";
697        assert_eq!(normalize_ddg_url(href).as_deref(), Some("https://example.com/page"));
698    }
699
700    #[test]
701    fn validate_result_url_rejects_non_http_schemes() {
702        assert!(validate_result_url("javascript:alert(1)").is_none());
703        assert!(validate_result_url("data:text/html,hi").is_none());
704        assert!(validate_result_url("file:///etc/passwd").is_none());
705        assert!(validate_result_url("https://user:secret@example.com/").is_none());
706        assert!(validate_result_url("https://example.com").is_some());
707    }
708
709    #[test]
710    fn missing_query_is_rejected() {
711        let tool = WebSearchTool::new();
712        let result = tokio::runtime::Runtime::new()
713            .unwrap()
714            .block_on(tool.run(json!({ "max_results": 5 })));
715        assert!(result.is_err());
716    }
717
718    #[test]
719    fn oversized_query_is_rejected_before_network_admission() {
720        let tool = WebSearchTool::new();
721        let result = tokio::runtime::Runtime::new()
722            .unwrap()
723            .block_on(tool.run(json!({ "query": "x".repeat(MAX_QUERY_CHARS + 1) })));
724        assert!(result.is_err());
725        assert_eq!(tool.state.lock().unwrap().requests_made, 0);
726    }
727
728    #[test]
729    fn pattern_is_rejected_as_an_unknown_field() {
730        let result = serde_json::from_value::<WebSearchArgs>(json!({
731            "query": "vinhnx",
732            "pattern": "legacy"
733        }));
734        assert!(result.is_err());
735    }
736
737    #[test]
738    fn canonical_query_and_max_results_are_accepted() {
739        let args = serde_json::from_value::<WebSearchArgs>(json!({
740            "query": "vinhnx",
741            "max_results": 5
742        }))
743        .expect("canonical web_search arguments");
744        assert_eq!(args.query, "vinhnx");
745        assert_eq!(args.max_results, Some(5));
746    }
747
748    #[test]
749    fn truncate_chars_appends_ellipsis() {
750        assert_eq!(truncate_chars("hello world", 5), "hello…");
751        assert_eq!(truncate_chars("hi", 5), "hi");
752    }
753
754    /// A small fixture that matches the markup the live DuckDuckGo HTML
755    /// endpoint emits. We do not assert on whitespace; we just need a stable
756    /// shape so the parser logic is exercised end-to-end without network.
757    const DDG_FIXTURE: &str = r#"
758        <a class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fgithub.com%2Fvinhnx&rut=abc">vinhnx (vinhnguyenxuan) · GitHub</a>
759        <a class="result__snippet" href="https://github.com/vinhnx">Personal GitHub profile of Vinh Nguyen Xuan.</a>
760        <a class="result__a" href="https://example.com/page">Example Page</a>
761        <a class="result__snippet" href="https://example.com/page">An example page used in tests.</a>
762        <a class="result__a" href="javascript:alert(1)">Should be skipped</a>
763    "#;
764
765    #[test]
766    fn parse_duckduckgo_html_extracts_results_from_fixture() {
767        let results = parse_duckduckgo_html(DDG_FIXTURE, 10);
768        assert_eq!(results.len(), 2);
769
770        assert_eq!(results[0].title, "vinhnx (vinhnguyenxuan) · GitHub");
771        assert_eq!(results[0].url, "https://github.com/vinhnx");
772        assert_eq!(results[0].snippet, "Personal GitHub profile of Vinh Nguyen Xuan.");
773
774        assert_eq!(results[1].title, "Example Page");
775        assert_eq!(results[1].url, "https://example.com/page");
776        assert_eq!(results[1].snippet, "An example page used in tests.");
777    }
778
779    #[test]
780    fn parse_duckduckgo_html_respects_max_results() {
781        let results = parse_duckduckgo_html(DDG_FIXTURE, 1);
782        assert_eq!(results.len(), 1);
783        assert_eq!(results[0].url, "https://github.com/vinhnx");
784    }
785
786    #[test]
787    fn parse_duckduckgo_html_returns_empty_for_challenge_page() {
788        // A real DuckDuckGo anti-bot challenge returns the homepage shell with
789        // no `result__a` anchors. The parser should return an empty vec, not
790        // panic or fabricate results; the response wrapper turns the marker
791        // into a structured blocked-search error.
792        let challenge = r#"<html><body>Anomaly detected.</body></html>"#;
793        assert!(parse_duckduckgo_html(challenge, 10).is_empty());
794    }
795
796    #[test]
797    fn challenge_response_is_rejected_before_empty_results_are_cached() {
798        let challenge = r#"<html><body>Anomaly detected.</body></html>"#;
799        let error = match parse_duckduckgo_response(challenge, 10) {
800            Ok(_) => panic!("challenge pages must be rejected"),
801            Err(error) => error,
802        };
803        assert!(error.to_string().contains("anti-bot challenge"));
804
805        let empty = "<html><body><p>No results found.</p></body></html>";
806        assert!(parse_duckduckgo_response(empty, 10).unwrap().is_empty());
807    }
808
809    #[test]
810    fn parse_accepts_href_before_class_and_single_quotes() {
811        // Asymmetric attribute order + quote style: the old regex required
812        // `class="result__a"` before `href="..."` with double quotes.
813        let body = r#"
814            <a href='https://example.com/b-first' class='result__a'>B first</a>
815            <a class="result__snippet">Snippet B.</a>
816            <a href="https://example.com/a-second" class="result__a extra">A second</a>
817            <a class="result__snippet">Snippet A.</a>
818        "#;
819        let results = parse_duckduckgo_html(body, 10);
820        assert_eq!(results.len(), 2);
821        assert_eq!(results[0].url, "https://example.com/b-first");
822        assert_eq!(results[0].snippet, "Snippet B.");
823        assert_eq!(results[1].url, "https://example.com/a-second");
824        assert_eq!(results[1].snippet, "Snippet A.");
825    }
826
827    #[test]
828    fn parse_accepts_uppercase_tags_and_classes() {
829        let body = r#"
830            <A CLASS="RESULT__A" HREF="https://example.com/upper">Upper Title</A>
831            <A CLASS="RESULT__SNIPPET">Upper snippet.</A>
832        "#;
833        let results = parse_duckduckgo_html(body, 10);
834        assert_eq!(results.len(), 1);
835        assert_eq!(results[0].title, "Upper Title");
836        assert_eq!(results[0].snippet, "Upper snippet.");
837    }
838
839    #[test]
840    fn parse_missing_first_snippet_does_not_shift_second() {
841        // Regression for index-aligned snippet lookup: a missing snippet for
842        // the first result must yield empty, not the second result's snippet.
843        let body = r#"
844            <a class="result__a" href="https://example.com/no-snippet">No Snippet</a>
845            <a class="result__a" href="https://example.com/with-snippet">With Snippet</a>
846            <a class="result__snippet">Second snippet.</a>
847        "#;
848        let results = parse_duckduckgo_html(body, 10);
849        assert_eq!(results.len(), 2);
850        assert_eq!(results[0].snippet, "");
851        assert_eq!(results[1].snippet, "Second snippet.");
852    }
853
854    #[test]
855    fn parse_skipped_anchors_do_not_steal_snippets() {
856        // Asymmetric: [bad, good] vs [good, bad]. A skipped `javascript:`
857        // anchor must not consume or shift the good result's snippet.
858        let bad_first = r#"
859            <a class="result__a" href="javascript:alert(1)">Bad</a>
860            <a class="result__snippet">Bad snippet.</a>
861            <a class="result__a" href="https://example.com/good">Good</a>
862            <a class="result__snippet">Good snippet.</a>
863        "#;
864        let results = parse_duckduckgo_html(bad_first, 10);
865        assert_eq!(results.len(), 1);
866        assert_eq!(results[0].url, "https://example.com/good");
867        assert_eq!(results[0].snippet, "Good snippet.");
868
869        let good_first = r#"
870            <a class="result__a" href="https://example.com/good">Good</a>
871            <a class="result__snippet">Good snippet.</a>
872            <a class="result__a" href="javascript:alert(1)">Bad</a>
873            <a class="result__snippet">Bad snippet.</a>
874        "#;
875        let results = parse_duckduckgo_html(good_first, 10);
876        assert_eq!(results.len(), 1);
877        assert_eq!(results[0].snippet, "Good snippet.");
878    }
879
880    #[test]
881    fn parse_ignores_anchors_inside_script() {
882        // Tokenizer advantage over regex: `script` content is raw text, so
883        // a fake anchor inside JavaScript never becomes a result.
884        let body = concat!(
885            "<script>var x = '<a class=\"result__a\" href=\"https://example.com/evil\">Evil</a>';</script>",
886            "<a class=\"result__a\" href=\"https://example.com/good\">Good</a>",
887            "<a class=\"result__snippet\">Good snippet.</a>",
888        );
889        let results = parse_duckduckgo_html(body, 10);
890        assert_eq!(results.len(), 1);
891        assert_eq!(results[0].url, "https://example.com/good");
892        assert_eq!(results[0].snippet, "Good snippet.");
893    }
894
895    #[test]
896    fn parse_collects_nested_formatting_text_in_title() {
897        let body = concat!(
898            "<a class=\"result__a\" href=\"https://example.com/fmt\">Hello <b>Bold</b> tail</a>",
899            "<a class=\"result__snippet\">S.</a>",
900        );
901        let results = parse_duckduckgo_html(body, 10);
902        assert_eq!(results.len(), 1);
903        assert_eq!(results[0].title, "Hello Bold tail");
904    }
905
906    #[test]
907    fn capped_body_text_passes_small_bodies_through() {
908        assert_eq!(capped_body_text(b"<html>hi</html>"), "<html>hi</html>");
909        assert_eq!(capped_body_text(b""), "");
910    }
911
912    #[test]
913    fn capped_body_text_truncates_huge_bodies_without_panicking_on_split_chars() {
914        // 999_999 ASCII bytes + one 2-byte `é`: the 1MB cap lands mid-char.
915        // The ASCII prefix survives; the split tail becomes U+FFFD.
916        let mut bytes = vec![b'a'; 999_999];
917        bytes.extend_from_slice("é".as_bytes());
918        let text = capped_body_text(&bytes);
919        assert!(text[..999_999].bytes().all(|b| b == b'a'));
920
921        let huge = vec![b'a'; MAX_DDG_BODY_BYTES + 5];
922        assert_eq!(capped_body_text(&huge).len(), MAX_DDG_BODY_BYTES);
923    }
924
925    #[test]
926    fn capped_body_text_is_lossy_not_panicky_on_invalid_utf8() {
927        let text = capped_body_text(b"\xff\xfe<html></html>");
928        assert!(text.contains("<html>"), "got: {text}");
929    }
930
931    #[test]
932    fn decode_numeric_hex_and_named_entities() {
933        assert_eq!(decode_html_entities("&#65;&#x42;&#X43;"), "ABC");
934        assert_eq!(decode_html_entities("&rsquo;&ldquo;&mdash;"), "’“—");
935        assert_eq!(decode_html_entities("&amp;lt;"), "&lt;");
936        assert_eq!(decode_html_entities("&#9999999;"), "&#9999999;");
937    }
938
939    #[test]
940    fn parse_accepts_unquoted_href_and_td_closed_snippet() {
941        let body = r#"
942            <a class=result__a href=https://example.com/unquoted>Unquoted</a>
943            <td class="result__snippet">TD snippet.</td>
944            <abbr title="abbreviation">abbr</abbr>
945            <a class="result__a" href="https://example.com/second">Second</a>
946            <a class="result__snippet">Second snippet.</a>
947        "#;
948        let results = parse_duckduckgo_html(body, 10);
949        assert_eq!(results.len(), 2);
950        assert_eq!(results[0].url, "https://example.com/unquoted");
951        assert_eq!(results[0].snippet, "TD snippet.");
952        assert_eq!(results[1].url, "https://example.com/second");
953        assert_eq!(results[1].snippet, "Second snippet.");
954    }
955
956    #[test]
957    fn session_cap_short_circuits_with_structured_error() {
958        let config = WebSearchConfig {
959            provider: Default::default(),
960            max_results: 5,
961            timeout_secs: 20,
962            cooldown_ms: 0,
963            cache_ttl_secs: 300,
964            session_max_requests: 2,
965        };
966        let tool = WebSearchTool::with_config(config);
967        // Bump the counter without going to the network.
968        {
969            let mut state = tool.state.lock().unwrap();
970            state.requests_made = 2;
971            state.last_request_at = Some(Instant::now());
972        }
973        let payload = tokio::runtime::Runtime::new()
974            .unwrap()
975            .block_on(tool.run(json!({ "query": "rust" })))
976            .expect("cap should be a structured JSON, not a runtime error");
977        assert_eq!(payload["error"], "web_search session request cap reached");
978        assert_eq!(payload["provider"], WebSearchProvider::Auto.backend_id());
979        assert_eq!(payload["error_type"], "session_cap");
980        assert_eq!(payload["retryable"], false);
981        assert_eq!(payload["session_max_requests"], 2);
982        assert_eq!(payload["request_budget_remaining"], 0);
983    }
984
985    #[test]
986    fn request_admission_reserves_before_network_and_enforces_cap() {
987        let tool = WebSearchTool::new();
988        let provider = WebSearchProvider::Auto.backend_id();
989        assert!(tool.admit_request("first", provider, Duration::ZERO, 1).unwrap().is_none());
990
991        let response = tool
992            .admit_request("second", provider, Duration::ZERO, 1)
993            .unwrap()
994            .expect("the second concurrent admission must hit the cap");
995        assert_eq!(response["error"], "web_search session request cap reached");
996        assert_eq!(response["provider"], provider);
997        assert_eq!(response["error_type"], "session_cap");
998        assert_eq!(response["retryable"], false);
999        assert_eq!(response["session_max_requests"], 1);
1000        assert_eq!(response["request_budget_remaining"], 0);
1001    }
1002
1003    #[test]
1004    fn cooldown_short_circuits_with_retry_after() {
1005        let config = WebSearchConfig {
1006            provider: Default::default(),
1007            max_results: 5,
1008            timeout_secs: 20,
1009            cooldown_ms: 5_000,
1010            cache_ttl_secs: 300,
1011            session_max_requests: 100,
1012        };
1013        let tool = WebSearchTool::with_config(config);
1014        {
1015            let mut state = tool.state.lock().unwrap();
1016            state.requests_made = 0;
1017            state.last_request_at = Some(Instant::now());
1018        }
1019        let payload = tokio::runtime::Runtime::new()
1020            .unwrap()
1021            .block_on(tool.run(json!({ "query": "rust" })))
1022            .expect("cooldown should be a structured JSON");
1023        assert_eq!(payload["error"], "web_search cooldown active");
1024        assert_eq!(payload["provider"], WebSearchProvider::Auto.backend_id());
1025        assert_eq!(payload["error_type"], "cooldown");
1026        assert_eq!(payload["retryable"], true);
1027        assert!(payload["retry_after_ms"].as_u64().unwrap() > 0);
1028    }
1029
1030    #[test]
1031    fn result_payloads_report_the_canonical_backend() {
1032        let provider = WebSearchProvider::Auto.backend_id();
1033        let success = results_response(
1034            "rust",
1035            provider,
1036            vec![SearchResult::new(
1037                "Rust Book".to_owned(),
1038                "https://doc.rust-lang.org/book/".to_owned(),
1039                "Ownership and borrowing".to_owned(),
1040            )],
1041        );
1042        let empty = results_response("no matching result", provider, Vec::new());
1043
1044        assert_eq!(success["provider"], WebSearchProvider::Duckduckgo.backend_id());
1045        assert_eq!(success["count"], 1);
1046        assert!(success.get("warning").is_none());
1047        assert_eq!(empty["provider"], WebSearchProvider::Duckduckgo.backend_id());
1048        assert_eq!(empty["count"], 0);
1049        assert_eq!(empty["results"], json!([]));
1050        assert_eq!(
1051            empty["warning"],
1052            "No results were returned. DuckDuckGo may have rate-limited the request or matched nothing. Try a different query, or wait a few seconds and try again."
1053        );
1054    }
1055
1056    #[test]
1057    fn cache_serves_repeat_queries_without_network() {
1058        // Pin max_results so the cache key matches the one the tool builds.
1059        let tool = WebSearchTool::with_config(WebSearchConfig {
1060            provider: Default::default(),
1061            max_results: 5,
1062            ..WebSearchConfig::default()
1063        });
1064        let cached_payload = json!({
1065            "query": "rust",
1066            "provider": WebSearchProvider::Duckduckgo.backend_id(),
1067            "count": 1,
1068            "results": [{
1069                "title": "Cached Result",
1070                "url": "https://example.com/cached",
1071                "snippet": "from cache"
1072            }]
1073        });
1074        {
1075            let mut state = tool.state.lock().unwrap();
1076            state.cache_put("5::rust".to_string(), cached_payload.clone());
1077        }
1078        let payload = tokio::runtime::Runtime::new()
1079            .unwrap()
1080            .block_on(tool.run(json!({ "query": "rust" })))
1081            .expect("cache hit must not error");
1082        assert_eq!(payload["cached"], json!(true));
1083        assert_eq!(payload["provider"], WebSearchProvider::Auto.backend_id());
1084        assert_eq!(payload["count"], 1);
1085        assert_eq!(payload["results"][0]["title"], "Cached Result");
1086    }
1087
1088    #[test]
1089    fn timeout_is_clamped_to_a_usable_range() {
1090        assert_eq!(effective_timeout_secs(0), MIN_TIMEOUT_SECS);
1091        assert_eq!(effective_timeout_secs(15), 15);
1092        assert_eq!(effective_timeout_secs(MAX_TIMEOUT_SECS + 1), MAX_TIMEOUT_SECS);
1093    }
1094
1095    #[test]
1096    fn redirects_stay_on_the_https_ddg_html_host() {
1097        assert!(is_allowed_ddg_redirect(&Url::parse("https://html.duckduckgo.com/html/").unwrap()));
1098        assert!(!is_allowed_ddg_redirect(&Url::parse("http://html.duckduckgo.com/html/").unwrap()));
1099        assert!(!is_allowed_ddg_redirect(&Url::parse("https://duckduckgo.com/html/").unwrap()));
1100        assert!(!is_allowed_ddg_redirect(&Url::parse("https://127.0.0.1/html/").unwrap()));
1101    }
1102
1103    #[test]
1104    fn classify_search_error_flags_antiban_statuses() {
1105        for status in [202, 403, 429] {
1106            let classification = classify_search_error(&format!(
1107                "DuckDuckGo declined the request (HTTP {status}), likely an anti-bot challenge for this network."
1108            ));
1109            assert_eq!(classification.error_type, "antiban_blocked");
1110            assert!(!classification.retryable);
1111            assert!(classification.next_action.contains("Do not retry immediately"));
1112        }
1113    }
1114
1115    #[test]
1116    fn challenge_html_is_antiban_and_non_retryable() {
1117        let error = match parse_duckduckgo_response("<html><body><div class=\"captcha\">verify</div></body></html>", 10)
1118        {
1119            Ok(_) => panic!("challenge HTML must not become an empty success"),
1120            Err(error) => error,
1121        };
1122        let classification = classify_search_error(&error.to_string());
1123        assert_eq!(classification.error_type, "antiban_blocked");
1124        assert!(!classification.retryable);
1125    }
1126
1127    #[test]
1128    fn classify_search_error_flags_timeout_as_network_error() {
1129        let classification = classify_search_error("request timed out after 20s");
1130        assert_eq!(classification.error_type, "network_error");
1131        assert!(classification.retryable);
1132        assert!(classification.next_action.contains("Retry once"));
1133
1134        let payload =
1135            search_error_response("rust", WebSearchProvider::Auto.backend_id(), "request timed out after 20s");
1136        assert_eq!(payload["provider"], WebSearchProvider::Duckduckgo.backend_id());
1137        assert_eq!(payload["error_type"], "network_error");
1138        assert_eq!(payload["retryable"], true);
1139    }
1140
1141    #[test]
1142    fn classify_search_error_flags_five_hundred_as_retryable_upstream_error() {
1143        let classification = classify_search_error("DuckDuckGo returned HTTP 503");
1144        assert_eq!(classification.error_type, "upstream_error");
1145        assert!(classification.retryable);
1146    }
1147
1148    #[test]
1149    fn classify_search_error_flags_oversized_response() {
1150        let classification = classify_search_error("DuckDuckGo response body exceeded the 1000000-byte limit");
1151        assert_eq!(classification.error_type, "response_too_large");
1152        assert!(!classification.retryable);
1153        assert!(classification.next_action.contains("Narrow the query"));
1154    }
1155}