Skip to main content

aidaemon_tools/
web_search.rs

1use std::collections::HashMap;
2use std::time::Duration;
3
4use async_trait::async_trait;
5use reqwest::Client;
6use serde_json::{Value, json};
7
8use serde::Deserialize;
9
10use crate::OutcomeTool as Tool;
11use crate::semantics::ToolCapabilities;
12use crate::web::{MAX_FETCH_BODY_BYTES, build_browser_client, read_body_capped};
13
14/// Which search backends `web_search` uses (`[search]` in the daemon's config).
15#[derive(Deserialize, Clone)]
16pub struct SearchConfig {
17    #[serde(default)]
18    pub backend: SearchBackendKind,
19    #[serde(default)]
20    pub api_key: String,
21    /// Base URL of a self-hosted SearxNG instance, wherever the user hosts it
22    /// (e.g. "http://localhost:8080" for the default Docker setup).
23    /// When set, SearxNG becomes available as a search backend.
24    #[serde(default)]
25    pub searxng_url: String,
26    /// When true (default), web_search queries every configured backend in
27    /// parallel and merges the results. When false, only `backend` is used.
28    #[serde(default = "default_true")]
29    pub parallel: bool,
30}
31
32fn default_true() -> bool {
33    true
34}
35
36impl Default for SearchConfig {
37    fn default() -> Self {
38        Self {
39            backend: SearchBackendKind::default(),
40            api_key: String::new(),
41            searxng_url: String::new(),
42            parallel: true,
43        }
44    }
45}
46
47impl std::fmt::Debug for SearchConfig {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        let redacted = if self.api_key.is_empty() {
50            "\"\""
51        } else {
52            "[REDACTED]"
53        };
54        f.debug_struct("SearchConfig")
55            .field("backend", &self.backend)
56            .field("api_key", &redacted)
57            .field("searxng_url", &self.searxng_url)
58            .field("parallel", &self.parallel)
59            .finish()
60    }
61}
62
63/// The primary search backend.
64#[derive(Debug, Deserialize, Clone, Default, PartialEq, Eq)]
65#[serde(rename_all = "snake_case")]
66pub enum SearchBackendKind {
67    #[default]
68    #[serde(alias = "duckduckgo")]
69    DuckDuckGo,
70    Brave,
71    Searxng,
72}
73
74const DEFAULT_MAX_RESULTS: usize = 8;
75const MAX_MAX_RESULTS: usize = 20;
76/// Per-backend wall-clock budget during parallel fan-out; a slow backend is
77/// dropped rather than stalling the whole search.
78const BACKEND_TIMEOUT: Duration = Duration::from_secs(12);
79/// Reciprocal-rank-fusion constant (standard value from the RRF literature).
80const RRF_K: f64 = 60.0;
81
82// ---------------------------------------------------------------------------
83// SearchBackend trait + result type
84// ---------------------------------------------------------------------------
85
86pub struct SearchResult {
87    pub title: String,
88    pub url: String,
89    pub snippet: String,
90    /// Publication age/date when the backend provides one (e.g. "2 days ago").
91    pub age: Option<String>,
92}
93
94/// Recency window for time-sensitive queries, mapped to each backend's
95/// native freshness parameter.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum Freshness {
98    Day,
99    Week,
100    Month,
101    Year,
102}
103
104impl Freshness {
105    fn parse(raw: &str) -> Option<Self> {
106        match raw.trim().to_ascii_lowercase().as_str() {
107            "day" | "d" => Some(Self::Day),
108            "week" | "w" => Some(Self::Week),
109            "month" | "m" => Some(Self::Month),
110            "year" | "y" => Some(Self::Year),
111            _ => None,
112        }
113    }
114
115    fn ddg_param(self) -> &'static str {
116        match self {
117            Self::Day => "d",
118            Self::Week => "w",
119            Self::Month => "m",
120            Self::Year => "y",
121        }
122    }
123
124    fn brave_param(self) -> &'static str {
125        match self {
126            Self::Day => "pd",
127            Self::Week => "pw",
128            Self::Month => "pm",
129            Self::Year => "py",
130        }
131    }
132
133    fn searxng_param(self) -> &'static str {
134        match self {
135            Self::Day => "day",
136            Self::Week => "week",
137            Self::Month => "month",
138            Self::Year => "year",
139        }
140    }
141}
142
143const DUCKDUCKGO_ENDPOINT: &str = "https://lite.duckduckgo.com/lite/";
144const BRAVE_ENDPOINT: &str = "https://api.search.brave.com/res/v1/web/search";
145
146#[async_trait]
147pub trait SearchBackend: Send + Sync {
148    fn name(&self) -> &'static str;
149    /// The URL this backend sends queries to, for the call's declared egress.
150    /// `None` when it is not known (the call is then undeclared).
151    fn endpoint(&self) -> Option<&str> {
152        None
153    }
154    async fn search(
155        &self,
156        query: &str,
157        max_results: usize,
158        freshness: Option<Freshness>,
159    ) -> anyhow::Result<Vec<SearchResult>>;
160}
161
162/// Build a single backend of the given kind from config.
163pub fn build_backend(kind: &SearchBackendKind, config: &SearchConfig) -> Box<dyn SearchBackend> {
164    match kind {
165        SearchBackendKind::Brave => Box::new(BraveBackend::new(&config.api_key)),
166        SearchBackendKind::DuckDuckGo => Box::new(DuckDuckGoBackend::new()),
167        SearchBackendKind::Searxng => Box::new(SearxngBackend::new(&config.searxng_url)),
168    }
169}
170
171/// All backends that should serve a search: the configured primary first,
172/// then (when `parallel` is enabled) every other backend that has the
173/// credentials/endpoint it needs. DuckDuckGo needs nothing, so it is always
174/// available as a supplementary source.
175fn configured_backends(config: &SearchConfig) -> Vec<Box<dyn SearchBackend>> {
176    let mut kinds = vec![config.backend.clone()];
177    if config.parallel {
178        for kind in [
179            SearchBackendKind::Brave,
180            SearchBackendKind::Searxng,
181            SearchBackendKind::DuckDuckGo,
182        ] {
183            if kinds.contains(&kind) {
184                continue;
185            }
186            let available = match kind {
187                SearchBackendKind::Brave => !config.api_key.is_empty(),
188                SearchBackendKind::Searxng => !config.searxng_url.is_empty(),
189                SearchBackendKind::DuckDuckGo => true,
190            };
191            if available {
192                kinds.push(kind);
193            }
194        }
195    }
196    kinds.iter().map(|k| build_backend(k, config)).collect()
197}
198
199// ---------------------------------------------------------------------------
200// DuckDuckGo backend (default, no API key)
201// ---------------------------------------------------------------------------
202
203pub struct DuckDuckGoBackend {
204    client: Client,
205}
206
207impl Default for DuckDuckGoBackend {
208    fn default() -> Self {
209        Self::new()
210    }
211}
212
213impl DuckDuckGoBackend {
214    pub fn new() -> Self {
215        Self {
216            client: build_browser_client(),
217        }
218    }
219}
220
221#[async_trait]
222impl SearchBackend for DuckDuckGoBackend {
223    fn name(&self) -> &'static str {
224        "duckduckgo"
225    }
226
227    fn endpoint(&self) -> Option<&str> {
228        Some(DUCKDUCKGO_ENDPOINT)
229    }
230
231    async fn search(
232        &self,
233        query: &str,
234        max_results: usize,
235        freshness: Option<Freshness>,
236    ) -> anyhow::Result<Vec<SearchResult>> {
237        let mut params = vec![("q", query.to_string())];
238        if let Some(f) = freshness {
239            params.push(("df", f.ddg_param().to_string()));
240        }
241        let url = reqwest::Url::parse_with_params(
242            DUCKDUCKGO_ENDPOINT,
243            params.iter().map(|(k, v)| (*k, v.as_str())),
244        )?
245        .to_string();
246        let resp = self.client.get(&url).send().await?;
247        let status = resp.status();
248        let (body, _truncated) = read_body_capped(resp, MAX_FETCH_BODY_BYTES).await?;
249        let html = String::from_utf8_lossy(&body).into_owned();
250
251        if !status.is_success() {
252            anyhow::bail!("DuckDuckGo returned HTTP {}", status);
253        }
254        if is_ddg_challenge(&html) {
255            anyhow::bail!("DuckDuckGo blocked the request with a bot challenge");
256        }
257
258        Ok(parse_ddg_lite_html(&html, max_results))
259    }
260}
261
262/// Detect DuckDuckGo's anti-bot challenge page, which returns HTTP 200 with
263/// no results. Without this check a block is indistinguishable from a query
264/// that genuinely has no matches. Only the page's DOM class/id markers are
265/// read (structure), never its sentences, which change with locale.
266fn is_ddg_challenge(html: &str) -> bool {
267    html.contains("anomaly-modal") || html.contains("challenge-form")
268}
269
270/// Parse the DuckDuckGo lite HTML page into results.
271///
272/// DuckDuckGo lite returns a simple HTML page with results in a table.
273/// Each result has: a link (<a> tag with href) and snippet text.
274/// We parse it with simple string scanning since it's a minimal page.
275fn parse_ddg_lite_html(html: &str, max_results: usize) -> Vec<SearchResult> {
276    let mut results = Vec::new();
277
278    // Find all result links: <a rel="nofollow" href="..." class="result-link">Title</a>
279    // and their snippets in <td class="result-snippet">...</td>
280    let mut pos = 0;
281    while results.len() < max_results {
282        // Find next result link
283        let link_start = match html[pos..].find("class=\"result-link\"") {
284            Some(p) => pos + p,
285            None => break,
286        };
287
288        // Extract href from the <a> tag — scan backward for href="
289        let tag_start = html[..link_start].rfind("<a ").unwrap_or(link_start);
290        let href = extract_attr(&html[tag_start..], "href").unwrap_or_default();
291
292        // Extract title (text between > and </a>)
293        let title_start = match html[link_start..].find('>') {
294            Some(p) => link_start + p + 1,
295            None => {
296                pos = link_start + 20;
297                continue;
298            }
299        };
300        let title_end = match html[title_start..].find("</a>") {
301            Some(p) => title_start + p,
302            None => {
303                pos = title_start;
304                continue;
305            }
306        };
307        let title = strip_tags(&html[title_start..title_end]);
308
309        // Find snippet after this link
310        let snippet = if let Some(sn_pos) = html[title_end..].find("class=\"result-snippet\"") {
311            let sn_start = title_end + sn_pos;
312            let sn_content_start = match html[sn_start..].find('>') {
313                Some(p) => sn_start + p + 1,
314                None => sn_start,
315            };
316            let sn_end = match html[sn_content_start..].find("</td>") {
317                Some(p) => sn_content_start + p,
318                None => sn_content_start,
319            };
320            strip_tags(&html[sn_content_start..sn_end])
321                .trim()
322                .to_string()
323        } else {
324            String::new()
325        };
326
327        if !href.is_empty() && !title.is_empty() {
328            results.push(SearchResult {
329                title,
330                url: decode_ddg_redirect(&href),
331                snippet,
332                age: None,
333            });
334        }
335
336        pos = title_end + 1;
337    }
338
339    results
340}
341
342/// DuckDuckGo lite wraps result URLs in a tracking redirect:
343/// `//duckduckgo.com/l/?uddg=<percent-encoded target>&rut=...`.
344/// Unwrap it to the real destination so the LLM (and web_fetch) get a
345/// usable URL instead of a protocol-relative redirect.
346fn decode_ddg_redirect(href: &str) -> String {
347    let absolute = if let Some(rest) = href.strip_prefix("//") {
348        format!("https://{}", rest)
349    } else if href.starts_with('/') {
350        format!("https://duckduckgo.com{}", href)
351    } else {
352        href.to_string()
353    };
354
355    if let Ok(url) = reqwest::Url::parse(&absolute) {
356        let is_ddg_redirect = url
357            .host_str()
358            .is_some_and(|h| h == "duckduckgo.com" || h.ends_with(".duckduckgo.com"))
359            && url.path() == "/l/";
360        if is_ddg_redirect && let Some((_, target)) = url.query_pairs().find(|(k, _)| k == "uddg") {
361            return target.into_owned();
362        }
363        return absolute;
364    }
365
366    href.to_string()
367}
368
369/// Extract an attribute value from an HTML tag fragment.
370fn extract_attr(tag: &str, attr: &str) -> Option<String> {
371    let pattern = format!("{}=\"", attr);
372    let start = tag.find(&pattern)? + pattern.len();
373    let end = tag[start..].find('"')? + start;
374    Some(html_decode(&tag[start..end]))
375}
376
377/// Strip HTML tags from a string.
378fn strip_tags(s: &str) -> String {
379    let mut out = String::with_capacity(s.len());
380    let mut in_tag = false;
381    for ch in s.chars() {
382        match ch {
383            '<' => in_tag = true,
384            '>' => in_tag = false,
385            _ if !in_tag => out.push(ch),
386            _ => {}
387        }
388    }
389    html_decode(&out)
390}
391
392/// Decode common HTML entities.
393fn html_decode(s: &str) -> String {
394    s.replace("&amp;", "&")
395        .replace("&lt;", "<")
396        .replace("&gt;", ">")
397        .replace("&quot;", "\"")
398        .replace("&#39;", "'")
399        .replace("&#x27;", "'")
400        .replace("&nbsp;", " ")
401}
402
403// ---------------------------------------------------------------------------
404// Brave backend (API key required)
405// ---------------------------------------------------------------------------
406
407pub struct BraveBackend {
408    client: Client,
409    api_key: String,
410}
411
412impl BraveBackend {
413    pub fn new(api_key: &str) -> Self {
414        Self {
415            client: Client::builder()
416                .timeout(std::time::Duration::from_secs(30))
417                .build()
418                .expect("failed to build HTTP client"),
419            api_key: api_key.to_string(),
420        }
421    }
422}
423
424#[async_trait]
425impl SearchBackend for BraveBackend {
426    fn name(&self) -> &'static str {
427        "brave"
428    }
429
430    fn endpoint(&self) -> Option<&str> {
431        Some(BRAVE_ENDPOINT)
432    }
433
434    async fn search(
435        &self,
436        query: &str,
437        max_results: usize,
438        freshness: Option<Freshness>,
439    ) -> anyhow::Result<Vec<SearchResult>> {
440        let mut params = vec![("q", query.to_string()), ("count", max_results.to_string())];
441        if let Some(f) = freshness {
442            params.push(("freshness", f.brave_param().to_string()));
443        }
444        let url = reqwest::Url::parse_with_params(
445            BRAVE_ENDPOINT,
446            params.iter().map(|(k, v)| (*k, v.as_str())),
447        )?
448        .to_string();
449
450        // Retry with exponential backoff for rate limiting (429)
451        let max_retries = 3;
452        let mut last_status = reqwest::StatusCode::OK;
453
454        for attempt in 0..max_retries {
455            let resp = self
456                .client
457                .get(&url)
458                .header("X-Subscription-Token", &self.api_key)
459                .header("Accept", "application/json")
460                .send()
461                .await?;
462
463            last_status = resp.status();
464
465            if resp.status().is_success() {
466                let (body, _truncated) = read_body_capped(resp, MAX_FETCH_BODY_BYTES).await?;
467                let data: Value = serde_json::from_slice(&body)?;
468                let empty = vec![];
469                let web_results = data["web"]["results"].as_array().unwrap_or(&empty);
470
471                let results = web_results
472                    .iter()
473                    .take(max_results)
474                    .filter_map(|r| {
475                        let mut snippet = r["description"].as_str().unwrap_or("").to_string();
476                        // Paid plans return extra_snippets with more page context;
477                        // fold a couple in so the LLM sees more than one sentence.
478                        if let Some(extra) = r["extra_snippets"].as_array() {
479                            for s in extra.iter().take(2).filter_map(|s| s.as_str()) {
480                                if !snippet.is_empty() {
481                                    snippet.push_str(" … ");
482                                }
483                                snippet.push_str(s);
484                            }
485                        }
486                        Some(SearchResult {
487                            title: r["title"].as_str()?.to_string(),
488                            url: r["url"].as_str()?.to_string(),
489                            snippet,
490                            age: r["age"]
491                                .as_str()
492                                .or_else(|| r["page_age"].as_str())
493                                .map(|s| s.to_string()),
494                        })
495                    })
496                    .collect();
497
498                return Ok(results);
499            }
500
501            // Retry on 429 (rate limited) with exponential backoff
502            if resp.status() == reqwest::StatusCode::TOO_MANY_REQUESTS && attempt < max_retries - 1
503            {
504                let delay = crate::backoff::exponential_backoff(
505                    Duration::from_secs(1),
506                    attempt as u32,
507                    Duration::MAX,
508                ); // 1s, 2s, 4s
509                tokio::time::sleep(delay).await;
510                continue;
511            }
512
513            // Non-retryable error or exhausted retries
514            break;
515        }
516
517        anyhow::bail!("Brave search API error: HTTP {}", last_status)
518    }
519}
520
521// ---------------------------------------------------------------------------
522// SearxNG backend (self-hosted metasearch, no API key)
523// ---------------------------------------------------------------------------
524
525pub struct SearxngBackend {
526    client: Client,
527    base_url: String,
528}
529
530impl SearxngBackend {
531    pub fn new(base_url: &str) -> Self {
532        Self {
533            client: Client::builder()
534                .timeout(std::time::Duration::from_secs(20))
535                .build()
536                .expect("failed to build HTTP client"),
537            base_url: base_url.trim_end_matches('/').to_string(),
538        }
539    }
540}
541
542#[async_trait]
543impl SearchBackend for SearxngBackend {
544    fn name(&self) -> &'static str {
545        "searxng"
546    }
547
548    fn endpoint(&self) -> Option<&str> {
549        (!self.base_url.is_empty()).then_some(self.base_url.as_str())
550    }
551
552    async fn search(
553        &self,
554        query: &str,
555        max_results: usize,
556        freshness: Option<Freshness>,
557    ) -> anyhow::Result<Vec<SearchResult>> {
558        anyhow::ensure!(
559            !self.base_url.is_empty(),
560            "SearxNG backend selected but search.searxng_url is not configured"
561        );
562        let mut params = vec![("q", query.to_string()), ("format", "json".to_string())];
563        if let Some(f) = freshness {
564            params.push(("time_range", f.searxng_param().to_string()));
565        }
566        let url = reqwest::Url::parse_with_params(
567            &format!("{}/search", self.base_url),
568            params.iter().map(|(k, v)| (*k, v.as_str())),
569        )?;
570
571        let resp = self.client.get(url).send().await?;
572        anyhow::ensure!(
573            resp.status().is_success(),
574            "SearxNG returned HTTP {} (ensure 'json' is in search.formats in the SearxNG settings)",
575            resp.status()
576        );
577        let (body, _truncated) = read_body_capped(resp, MAX_FETCH_BODY_BYTES).await?;
578        let data: Value = serde_json::from_slice(&body)?;
579        let empty = vec![];
580        let results = data["results"]
581            .as_array()
582            .unwrap_or(&empty)
583            .iter()
584            .take(max_results)
585            .filter_map(|r| {
586                Some(SearchResult {
587                    title: r["title"].as_str()?.to_string(),
588                    url: r["url"].as_str()?.to_string(),
589                    snippet: r["content"].as_str().unwrap_or("").to_string(),
590                    age: r["publishedDate"]
591                        .as_str()
592                        .and_then(|s| s.split('T').next())
593                        .map(|s| s.to_string()),
594                })
595            })
596            .collect();
597
598        Ok(results)
599    }
600}
601
602// ---------------------------------------------------------------------------
603// Result merging (reciprocal rank fusion across backends)
604// ---------------------------------------------------------------------------
605
606struct MergedResult {
607    title: String,
608    url: String,
609    snippet: String,
610    age: Option<String>,
611    sources: Vec<&'static str>,
612    score: f64,
613}
614
615/// Normalize a URL for cross-backend deduplication: scheme-insensitive,
616/// fragment stripped, trailing slash stripped.
617fn normalize_url(url: &str) -> String {
618    if let Ok(mut u) = reqwest::Url::parse(url) {
619        u.set_fragment(None);
620        let s = u.to_string();
621        let s = s
622            .strip_prefix("https://")
623            .or_else(|| s.strip_prefix("http://"))
624            .unwrap_or(&s);
625        return s.trim_end_matches('/').to_ascii_lowercase();
626    }
627    url.trim_end_matches('/').to_ascii_lowercase()
628}
629
630/// Merge ranked result lists from multiple backends using reciprocal rank
631/// fusion: each result scores sum(1 / (k + rank)) across the backends that
632/// returned it, so results confirmed by several sources rank highest. Ties
633/// keep primary-backend order (stable sort, primary list is inserted first).
634fn merge_ranked(
635    lists: &[(&'static str, Vec<SearchResult>)],
636    max_results: usize,
637) -> Vec<MergedResult> {
638    let mut map: HashMap<String, MergedResult> = HashMap::new();
639    let mut order: Vec<String> = Vec::new();
640
641    for (backend, results) in lists {
642        for (rank, r) in results.iter().enumerate() {
643            let key = normalize_url(&r.url);
644            let entry = map.entry(key.clone()).or_insert_with(|| {
645                order.push(key.clone());
646                MergedResult {
647                    title: r.title.clone(),
648                    url: r.url.clone(),
649                    snippet: String::new(),
650                    age: None,
651                    sources: Vec::new(),
652                    score: 0.0,
653                }
654            });
655            entry.score += 1.0 / (RRF_K + rank as f64 + 1.0);
656            if r.snippet.len() > entry.snippet.len() {
657                entry.snippet = r.snippet.clone();
658            }
659            if entry.age.is_none() {
660                entry.age = r.age.clone();
661            }
662            if !entry.sources.contains(backend) {
663                entry.sources.push(backend);
664            }
665        }
666    }
667
668    let mut merged: Vec<MergedResult> = order
669        .into_iter()
670        .filter_map(|key| map.remove(&key))
671        .collect();
672    merged.sort_by(|a, b| {
673        b.score
674            .partial_cmp(&a.score)
675            .unwrap_or(std::cmp::Ordering::Equal)
676    });
677    merged.truncate(max_results);
678    merged
679}
680
681// ---------------------------------------------------------------------------
682// WebSearch
683// ---------------------------------------------------------------------------
684
685/// The `web_search` tool: every configured backend in parallel, results
686/// merged by reciprocal rank fusion.
687pub struct WebSearch {
688    backends: Vec<Box<dyn SearchBackend>>,
689    description: String,
690}
691
692/// The description [`WebSearch::new`] gives the model.
693pub const DEFAULT_DESCRIPTION: &str = "Search the web. Queries all configured search backends in parallel and returns merged, deduplicated results (titles, URLs, snippets, publication age when known). Use to find current information, research topics, check facts. One focused search is almost always enough; for single-fact lookups do NOT re-search with rephrased queries — synthesize promptly. Results are snippet previews, NOT full pages: never assemble complete lists, rosters, or enumerations from snippets — fetch a source page with web_fetch and answer from its text. Set 'freshness' for time-sensitive queries (news, prices, releases). If results are consistently empty, the search backend may be blocked — configure Brave Search (an API key) or a self-hosted SearxNG instance.";
694
695impl WebSearch {
696    pub fn new(config: &SearchConfig) -> Self {
697        Self {
698            backends: configured_backends(config),
699            description: DEFAULT_DESCRIPTION.to_string(),
700        }
701    }
702
703    /// Replace the description the model sees, for example to name where
704    /// the host's users configure search.
705    pub fn with_description(mut self, description: impl Into<String>) -> Self {
706        self.description = description.into();
707        self
708    }
709}
710
711#[async_trait]
712impl Tool for WebSearch {
713    fn name(&self) -> &str {
714        "web_search"
715    }
716
717    fn description(&self) -> &str {
718        &self.description
719    }
720
721    fn schema(&self) -> Value {
722        json!({
723            "name": "web_search",
724            "description": self.description(),
725            "parameters": {
726                "type": "object",
727                "properties": {
728                    "query": {
729                        "type": "string",
730                        "description": "The search query"
731                    },
732                    "max_results": {
733                        "type": "integer",
734                        "description": "Maximum number of merged results (default 8, max 20)"
735                    },
736                    "freshness": {
737                        "type": "string",
738                        "enum": ["day", "week", "month", "year"],
739                        "description": "Only return results published within this window. Use for time-sensitive queries."
740                    }
741                },
742                "required": ["query"],
743                "additionalProperties": false
744            }
745        })
746    }
747
748    async fn execute(
749        &self,
750        arguments: &str,
751        _facts: &crate::semantics::ToolCallContext,
752    ) -> anyhow::Result<crate::semantics::ToolCallOutcome> {
753        let output: anyhow::Result<String> = async move {
754            let args: Value = serde_json::from_str(arguments)?;
755            let query = args["query"]
756                .as_str()
757                .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;
758            let max_results = args["max_results"]
759                .as_u64()
760                .map(|n| n as usize)
761                .unwrap_or(DEFAULT_MAX_RESULTS)
762                .clamp(1, MAX_MAX_RESULTS);
763            let freshness = args["freshness"].as_str().and_then(Freshness::parse);
764
765            // Fan out to every backend concurrently; tolerate individual failures.
766            let searches = self.backends.iter().map(|backend| async move {
767                let name = backend.name();
768                match tokio::time::timeout(
769                    BACKEND_TIMEOUT,
770                    backend.search(query, max_results, freshness),
771                )
772                .await
773                {
774                    Ok(Ok(results)) => (name, Ok(results)),
775                    Ok(Err(e)) => (name, Err(e.to_string())),
776                    Err(_) => (
777                        name,
778                        Err(format!("timed out after {}s", BACKEND_TIMEOUT.as_secs())),
779                    ),
780                }
781            });
782            let outcomes = futures::future::join_all(searches).await;
783
784            let mut successes: Vec<(&'static str, Vec<SearchResult>)> = Vec::new();
785            let mut failures: Vec<String> = Vec::new();
786            for (name, outcome) in outcomes {
787                match outcome {
788                    Ok(results) => successes.push((name, results)),
789                    Err(err) => failures.push(format!("{}: {}", name, err)),
790                }
791            }
792
793            if successes.is_empty() {
794                anyhow::bail!("All search backends failed — {}", failures.join("; "));
795            }
796
797            let merged = merge_ranked(&successes, max_results);
798
799            if merged.is_empty() {
800                let mut msg = format!("No results found for: {}", query);
801                if !failures.is_empty() {
802                    msg.push_str(&format!(
803                        "\n(Note: some backends were unavailable — {})",
804                        failures.join("; ")
805                    ));
806                }
807                return Ok(msg);
808            }
809
810            let multi_source = self.backends.len() > 1;
811            Ok(format_search_output(&merged, multi_source, &failures))
812        }
813        .await;
814        output.map(crate::semantics::ToolCallOutcome::from_output)
815    }
816}
817
818impl crate::semantics::ToolSemantics for WebSearch {
819    fn dispatch_facts(&self) -> crate::semantics::ToolDispatchFacts {
820        crate::semantics::ToolDispatchFacts {
821            offering: crate::semantics::Offering::Core,
822            same_tool_streak: crate::semantics::SameToolStreak::Versatile,
823            recap: crate::semantics::RecapKind::Search,
824            activity: crate::semantics::ToolActivity::Fixed(aidaemon_core::card::ActivityKind::Web),
825            channel_reach: crate::semantics::ChannelReach::Public,
826            evidence: crate::semantics::EvidenceSource::WebSearch,
827            semantic_scope: Some(crate::semantics::ToolSemanticScope::ExternalRemote),
828            status_label: Some("searching the web"),
829            ..Default::default()
830        }
831    }
832
833    fn capabilities(&self) -> ToolCapabilities {
834        ToolCapabilities::READ_ONLY_EXTERNAL
835    }
836
837    /// The query is text the model wrote.
838    fn call_outbound(&self, _arguments: &str) -> aidaemon_core::Outbound {
839        aidaemon_core::Outbound::Composed
840    }
841
842    /// The query goes to every configured backend's host, so the egress
843    /// policy scans it and a declined host binds the search.
844    fn call_effects(&self, _arguments: &str) -> aidaemon_core::CallEffects {
845        let mut keys = Vec::new();
846        for backend in &self.backends {
847            let Some(key) = backend
848                .endpoint()
849                .and_then(|endpoint| reqwest::Url::parse(endpoint).ok())
850                .and_then(|url| crate::command_effects::url_host_effect(&url))
851            else {
852                return aidaemon_core::CallEffects::unknown();
853            };
854            if !keys.contains(&key) {
855                keys.push(key);
856            }
857        }
858        if keys.is_empty() {
859            return aidaemon_core::CallEffects::unknown();
860        }
861        aidaemon_core::CallEffects {
862            keys,
863            complete: true,
864            understood: false,
865        }
866    }
867}
868
869/// Appended to every non-empty result set. Snippets are previews — without an
870/// explicit guard the model assembles "complete" enumerations (rosters, member
871/// lists, counts) out of 8 partial snippets, inventing the entries it cannot
872/// see. Same failure mode as passive truncation markers (see
873/// truncation_notice patterns in similar tools).
874const SNIPPET_GUARD_FOOTER: &str = "[⚠ SNIPPETS ONLY — the entries above are search-result \
875     previews, not full page content. Do NOT enumerate lists, rosters, members, or counts \
876     assembled from snippets, and do NOT present a \"complete\" answer built from them — \
877     inventing entries that are not literally visible is an error. For enumeration or \
878     list-type questions, fetch a source page with web_fetch and answer only from text you \
879     can see; corroborate factual answers with a second independent source when possible, \
880     and name the sources you used. If a fetch fails, try the next result URL — do not \
881     retry the same one. If no fetched page contains the full answer, say it is incomplete \
882     instead of filling the gaps.]";
883
884fn format_search_output(
885    merged: &[MergedResult],
886    multi_source: bool,
887    failures: &[String],
888) -> String {
889    let formatted: Vec<String> = merged
890        .iter()
891        .enumerate()
892        .map(|(i, r)| {
893            let mut entry = format!("{}. [{}]({})", i + 1, r.title, r.url);
894            if !r.snippet.is_empty() {
895                entry.push_str(&format!("\n   {}", r.snippet));
896            }
897            let mut meta = Vec::new();
898            if let Some(age) = &r.age {
899                meta.push(age.clone());
900            }
901            if multi_source {
902                meta.push(format!("via {}", r.sources.join(", ")));
903            }
904            if !meta.is_empty() {
905                entry.push_str(&format!("\n   ({})", meta.join(" — ")));
906            }
907            entry
908        })
909        .collect();
910
911    let mut output = formatted.join("\n\n");
912    if !failures.is_empty() {
913        output.push_str(&format!(
914            "\n\n(Note: some backends were unavailable — {})",
915            failures.join("; ")
916        ));
917    }
918    output.push_str("\n\n");
919    output.push_str(SNIPPET_GUARD_FOOTER);
920
921    output
922}
923
924#[cfg(test)]
925mod tests {
926    use super::*;
927
928    #[test]
929    fn decodes_protocol_relative_ddg_redirect() {
930        let href = "//duckduckgo.com/l/?uddg=https%3A%2F%2Fdocs.rs%2Ftokio%2Flatest%2Ftokio%2Fruntime%2F&rut=904d86ad457b";
931        assert_eq!(
932            decode_ddg_redirect(href),
933            "https://docs.rs/tokio/latest/tokio/runtime/"
934        );
935    }
936
937    #[test]
938    fn decodes_relative_ddg_redirect() {
939        let href = "/l/?uddg=https%3A%2F%2Ftokio.rs%2F&rut=abc";
940        assert_eq!(decode_ddg_redirect(href), "https://tokio.rs/");
941    }
942
943    #[test]
944    fn passes_through_direct_urls() {
945        assert_eq!(
946            decode_ddg_redirect("https://example.com/page"),
947            "https://example.com/page"
948        );
949        // Protocol-relative non-DDG URLs become absolute.
950        assert_eq!(
951            decode_ddg_redirect("//example.com/page"),
952            "https://example.com/page"
953        );
954    }
955
956    #[test]
957    fn parses_ddg_lite_fixture_and_unwraps_redirects() {
958        let html = r#"
959        <table>
960        <tr><td>1.&nbsp;</td><td><a rel="nofollow" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Ftokio.rs%2F&amp;rut=abc" class="result-link">Tokio - An asynchronous Rust runtime</a></td></tr>
961        <tr><td>&nbsp;</td><td class="result-snippet">Tokio is an asynchronous runtime for the Rust programming language.</td></tr>
962        <tr><td>2.&nbsp;</td><td><a rel="nofollow" href="https://docs.rs/tokio" class="result-link">tokio - Rust</a></td></tr>
963        <tr><td>&nbsp;</td><td class="result-snippet">API documentation for the tokio crate.</td></tr>
964        </table>
965        "#;
966        let results = parse_ddg_lite_html(html, 10);
967        assert_eq!(results.len(), 2);
968        assert_eq!(results[0].url, "https://tokio.rs/");
969        assert_eq!(results[0].title, "Tokio - An asynchronous Rust runtime");
970        assert!(results[0].snippet.contains("asynchronous runtime"));
971        assert_eq!(results[1].url, "https://docs.rs/tokio");
972    }
973
974    #[test]
975    fn detects_ddg_challenge_page() {
976        assert!(is_ddg_challenge(
977            "<html><div class=\"anomaly-modal\">...</div></html>"
978        ));
979        assert!(is_ddg_challenge("<form id=\"challenge-form\"></form>"));
980        // A result snippet quoting the challenge sentence is not a challenge.
981        assert!(!is_ddg_challenge(
982            "<td class=\"result-snippet\">Unfortunately, bots use DuckDuckGo too.</td>"
983        ));
984        assert!(!is_ddg_challenge("<td class=\"result-snippet\">ok</td>"));
985    }
986
987    #[test]
988    fn normalizes_urls_for_dedup() {
989        assert_eq!(
990            normalize_url("https://Example.com/Page/"),
991            normalize_url("http://example.com/page")
992        );
993        assert_eq!(
994            normalize_url("https://example.com/page#section"),
995            normalize_url("https://example.com/page")
996        );
997        assert_ne!(
998            normalize_url("https://example.com/page?a=1"),
999            normalize_url("https://example.com/page")
1000        );
1001    }
1002
1003    #[test]
1004    fn merge_dedups_and_boosts_multi_source_results() {
1005        let lists = vec![
1006            (
1007                "brave",
1008                vec![
1009                    SearchResult {
1010                        title: "Only Brave".into(),
1011                        url: "https://a.example/".into(),
1012                        snippet: "short".into(),
1013                        age: Some("2 days ago".into()),
1014                    },
1015                    SearchResult {
1016                        title: "Both".into(),
1017                        url: "https://b.example/".into(),
1018                        snippet: "brave snippet".into(),
1019                        age: None,
1020                    },
1021                ],
1022            ),
1023            (
1024                "duckduckgo",
1025                vec![SearchResult {
1026                    title: "Both (ddg)".into(),
1027                    url: "http://b.example".into(),
1028                    snippet: "a much longer duckduckgo snippet".into(),
1029                    age: None,
1030                }],
1031            ),
1032        ];
1033        let merged = merge_ranked(&lists, 10);
1034        assert_eq!(merged.len(), 2);
1035        // b.example appears in both backends → ranks above a.example despite
1036        // being rank 2 in the brave list.
1037        assert_eq!(merged[0].url, "https://b.example/");
1038        assert_eq!(merged[0].sources, vec!["brave", "duckduckgo"]);
1039        // Longest snippet wins.
1040        assert_eq!(merged[0].snippet, "a much longer duckduckgo snippet");
1041        assert_eq!(merged[1].sources, vec!["brave"]);
1042        assert_eq!(merged[1].age.as_deref(), Some("2 days ago"));
1043    }
1044
1045    #[test]
1046    fn merge_respects_max_results() {
1047        let lists = vec![(
1048            "brave",
1049            (0..5)
1050                .map(|i| SearchResult {
1051                    title: format!("r{}", i),
1052                    url: format!("https://example.com/{}", i),
1053                    snippet: String::new(),
1054                    age: None,
1055                })
1056                .collect::<Vec<_>>(),
1057        )];
1058        assert_eq!(merge_ranked(&lists, 3).len(), 3);
1059    }
1060
1061    #[test]
1062    fn freshness_parses_and_maps() {
1063        assert_eq!(Freshness::parse("day"), Some(Freshness::Day));
1064        assert_eq!(Freshness::parse("WEEK"), Some(Freshness::Week));
1065        assert_eq!(Freshness::parse("m"), Some(Freshness::Month));
1066        assert_eq!(Freshness::parse("bogus"), None);
1067        assert_eq!(Freshness::Day.brave_param(), "pd");
1068        assert_eq!(Freshness::Week.ddg_param(), "w");
1069        assert_eq!(Freshness::Year.searxng_param(), "year");
1070    }
1071
1072    #[test]
1073    fn backend_selection_respects_config() {
1074        // DDG only (no key, no searxng).
1075        let cfg = SearchConfig::default();
1076        let names: Vec<&str> = configured_backends(&cfg).iter().map(|b| b.name()).collect();
1077        assert_eq!(names, vec!["duckduckgo"]);
1078
1079        // Brave primary + key → brave first, ddg supplements.
1080        let cfg = SearchConfig {
1081            backend: SearchBackendKind::Brave,
1082            api_key: "k".into(),
1083            ..Default::default()
1084        };
1085        let names: Vec<&str> = configured_backends(&cfg).iter().map(|b| b.name()).collect();
1086        assert_eq!(names, vec!["brave", "duckduckgo"]);
1087
1088        // parallel=false → primary only.
1089        let cfg = SearchConfig {
1090            backend: SearchBackendKind::Brave,
1091            api_key: "k".into(),
1092            parallel: false,
1093            ..Default::default()
1094        };
1095        let names: Vec<&str> = configured_backends(&cfg).iter().map(|b| b.name()).collect();
1096        assert_eq!(names, vec!["brave"]);
1097
1098        // Everything configured → primary first, then brave, searxng, ddg order.
1099        let cfg = SearchConfig {
1100            backend: SearchBackendKind::DuckDuckGo,
1101            api_key: "k".into(),
1102            searxng_url: "http://localhost:8888".into(),
1103            parallel: true,
1104        };
1105        let names: Vec<&str> = configured_backends(&cfg).iter().map(|b| b.name()).collect();
1106        assert_eq!(names, vec!["duckduckgo", "brave", "searxng"]);
1107    }
1108}
1109
1110#[cfg(test)]
1111mod format_output_tests {
1112    use super::*;
1113    use crate::semantics::ToolSemantics;
1114
1115    fn merged(title: &str, snippet: &str) -> MergedResult {
1116        MergedResult {
1117            title: title.to_string(),
1118            url: format!("https://example.com/{}", title),
1119            snippet: snippet.to_string(),
1120            age: None,
1121            sources: vec!["duckduckgo"],
1122            score: 1.0,
1123        }
1124    }
1125
1126    #[test]
1127    fn search_output_carries_snippet_honesty_guard() {
1128        let results = vec![merged("squad", "Ecuador announced its 26-man roster...")];
1129        let out = format_search_output(&results, false, &[]);
1130        assert!(out.contains("Ecuador announced"));
1131        // Snippets are previews — the model must not assemble "complete"
1132        // enumerations (rosters, lists, counts) out of them.
1133        assert!(out.contains("SNIPPETS ONLY"));
1134        assert!(out.contains("Do NOT enumerate"));
1135        assert!(out.contains("web_fetch"));
1136        // Factual answers should be corroborated, not single-sourced.
1137        assert!(out.contains("second independent source"));
1138        assert!(out.contains("name the sources"));
1139    }
1140
1141    #[test]
1142    fn backend_failures_still_noted_in_output() {
1143        let results = vec![merged("a", "snippet a")];
1144        let out = format_search_output(&results, false, &["brave: timeout".to_string()]);
1145        assert!(out.contains("some backends were unavailable"));
1146        assert!(out.contains("brave: timeout"));
1147    }
1148
1149    #[test]
1150    fn schema_description_scopes_synthesis_to_non_enumeration() {
1151        let tool = WebSearch::new(&SearchConfig::default());
1152        let schema = tool.schema();
1153        let desc = schema["description"].as_str().unwrap();
1154        // "synthesize promptly" must not invite assembling full lists from snippets.
1155        assert!(desc.contains("previews"));
1156        assert!(desc.contains("web_fetch"));
1157    }
1158
1159    /// A read-only search still sends the query out: it declares each
1160    /// configured backend's host so the egress policy sees it.
1161    #[test]
1162    fn web_search_declares_backend_hosts() {
1163        use aidaemon_core::EffectKey;
1164        let default = WebSearch::new(&SearchConfig::default());
1165        let effects = default.call_effects(r#"{"query":"acme"}"#);
1166        assert!(effects.complete);
1167        assert_eq!(
1168            effects.keys,
1169            vec![EffectKey::egress("https", "lite.duckduckgo.com", None)]
1170        );
1171        let config = SearchConfig {
1172            backend: SearchBackendKind::Searxng,
1173            searxng_url: "http://localhost:8080".to_string(),
1174            parallel: false,
1175            ..SearchConfig::default()
1176        };
1177        let searxng = WebSearch::new(&config).call_effects(r#"{"query":"acme"}"#);
1178        assert!(searxng.complete);
1179        assert_eq!(searxng.keys[0].target, "localhost:8080");
1180    }
1181}