use super::http::build_browser_client;
use super::{Tool, ToolDefinition, FunctionDefinition, arg_str, arg_usize};
use std::io;
use serde_json::Value;
use atlas_http::HttpSyncClient;
use scraper::{Html, Selector};
use url::Url;
const DDG_ENDPOINT: &str = "https://duckduckgo.com/html/";
const MARGINALIA_ENDPOINT: &str = "https://old-search.marginalia.nu/search";
const MARGINALIA_MAX_ATTEMPTS: usize = 4;
const DEFAULT_COUNT: usize = 8;
const MAX_COUNT: usize = 15;
const OLLAMA_ENDPOINT: &str = "https://ollama.com/api/web_search";
const TAVILY_ENDPOINT: &str = "https://api.tavily.com/search";
#[derive(Clone)]
pub struct SearchHit {
pub title: String,
pub url: String,
pub snippet: String,
}
pub trait SearchBackend {
fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error>;
}
pub struct DuckDuckGoBackend;
impl SearchBackend for DuckDuckGoBackend {
fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
let mut url = Url::parse(DDG_ENDPOINT).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
url.query_pairs_mut().append_pair("q", query);
let url_str = url.to_string();
let mut client = build_browser_client();
let res = client.get(&url_str).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if res.status_code() != 200 {
return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
}
match parse_results(&res.body()) {
Some(hits) => Ok(hits.into_iter().take(count).collect()),
None => Err(io::Error::new(io::ErrorKind::Other, "unexpected page".to_string())),
}
}
}
pub struct MarginaliaBackend;
impl SearchBackend for MarginaliaBackend {
fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
let mut url = Url::parse(MARGINALIA_ENDPOINT).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
url.query_pairs_mut().append_pair("query", query);
let mut client = build_browser_client();
let html = fetch_marginalia(&mut client, url.as_str())?;
match parse_marginalia(&html) {
Some(hits) => Ok(hits.into_iter().take(count).collect()),
None => Err(io::Error::new(io::ErrorKind::Other, "unexpected page".to_string())),
}
}
}
fn fetch_marginalia(client: &mut HttpSyncClient, url: &str) -> Result<String, io::Error> {
let base = Url::parse(url).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
let query = base.query_pairs().find(|(k, _)| k == "query").map(|(_, v)| v.into_owned()).unwrap_or_default();
let mut current = base;
for _ in 0..MARGINALIA_MAX_ATTEMPTS {
let res = client.get(current.as_str()).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if res.status_code() != 200 {
return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
}
let body = res.body();
if parse_marginalia(&body).is_some() {
return Ok(body);
}
match extract_sst_token(&body) {
Some(token) => {
std::thread::sleep(std::time::Duration::from_millis(1500));
let mut next = Url::parse(MARGINALIA_ENDPOINT).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
next.query_pairs_mut().append_pair("query", &query);
next.query_pairs_mut().append_pair("sst", &token);
current = next;
}
None => return Ok(body),
}
}
Err(io::Error::new(io::ErrorKind::Other, "search engine rate limit".to_string()))
}
fn extract_sst_token(html: &str) -> Option<String> {
for part in html.split("sst=").skip(1) {
let token: String = part.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '-').collect();
if !token.is_empty() {
return Some(token);
}
}
None
}
fn parse_marginalia(html: &str) -> Option<Vec<SearchHit>> {
let document = Html::parse_document(html);
let card = Selector::parse("section.search-result").expect("static selector is valid");
if document.select(&card).next().is_none() {
return None;
}
let title = Selector::parse("h2 a.title").expect("static selector is valid");
let desc = Selector::parse("p.description").expect("static selector is valid");
let mut hits = Vec::new();
for res in document.select(&card) {
let anchor = match res.select(&title).next() {
Some(a) => a,
None => continue,
};
let title_text = node_text(anchor);
let url = anchor.attr("href").unwrap_or("").to_string();
if title_text.is_empty() || url.is_empty() {
continue;
}
let snippet = res.select(&desc).next().map(node_text).unwrap_or_default();
hits.push(SearchHit { title: title_text, url, snippet });
}
Some(hits)
}
pub struct OllamaSearchBackend {
api_key: String,
api_url: String,
}
impl SearchBackend for OllamaSearchBackend {
fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
let body = serde_json::json!({
"query": query,
"max_results": count.min(10),
});
let mut client = build_browser_client();
let auth_header = format!("Authorization: Bearer {}", self.api_key);
let headers: Vec<&str> = vec![
"Content-Type: application/json",
&auth_header,
];
let req_body = atlas_http::HttpBody::from_raw_str(&body.to_string());
let req = atlas_http::HttpRequest::new("POST", &self.api_url, &headers, &req_body);
let res = client.send(&req).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if res.status_code() != 200 {
return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
}
let v: Value = serde_json::from_str(&res.body()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
let results = match v.get("results") {
Some(Value::Array(arr)) => arr.iter().map(|r| SearchHit {
title: r.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
url: r.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string(),
snippet: r.get("content").and_then(|v| v.as_str()).unwrap_or("").to_string(),
}).filter(|h| !h.title.is_empty()).collect(),
_ => Vec::new(),
};
Ok(results)
}
}
pub struct TavilySearchBackend {
api_key: String,
}
impl SearchBackend for TavilySearchBackend {
fn search(&self, query: &str, count: usize) -> Result<Vec<SearchHit>, io::Error> {
let body = serde_json::json!({
"query": query,
"max_results": count,
"search_depth": "basic",
});
let mut client = build_browser_client();
let headers: Vec<&str> = vec!["Content-Type: application/json"];
let req_body = atlas_http::HttpBody::from_raw_str(&body.to_string());
let req = atlas_http::HttpRequest::new("POST", TAVILY_ENDPOINT, &headers, &req_body);
let res = client.send(&req).map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
if res.status_code() != 200 {
return Err(io::Error::new(io::ErrorKind::Other, format!("search failed with status {}", res.status_code())));
}
let v: Value = serde_json::from_str(&res.body()).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
let results = match v.get("results") {
Some(Value::Array(arr)) => arr.iter().map(|r| SearchHit {
title: r.get("title").and_then(|v| v.as_str()).unwrap_or("").to_string(),
url: r.get("url").and_then(|v| v.as_str()).unwrap_or("").to_string(),
snippet: r.get("content").and_then(|v| v.as_str()).unwrap_or("").to_string(),
}).filter(|h| !h.title.is_empty()).collect(),
_ => Vec::new(),
};
Ok(results)
}
}
pub struct WebSearchTool {
backends: Vec<Box<dyn SearchBackend>>,
}
impl WebSearchTool {
pub fn new(ollama_api_key: String) -> Self {
let mut backends: Vec<Box<dyn SearchBackend>> = Vec::new();
if !ollama_api_key.is_empty() {
backends.push(Box::new(OllamaSearchBackend { api_key: ollama_api_key, api_url: OLLAMA_ENDPOINT.to_string() }));
}
backends.push(Box::new(DuckDuckGoBackend));
backends.push(Box::new(MarginaliaBackend));
Self { backends }
}
pub fn get_definition(&self) -> ToolDefinition {
ToolDefinition {
tool_type: "function".to_string(),
function: FunctionDefinition {
name: self.name().to_string(),
description: self.description().to_string(),
parameters: serde_json::json!({
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query."
},
"count": {
"type": "integer",
"description": "Maximum number of results (default 8, max 15)."
}
},
"required": ["query"]
}),
},
}
}
}
impl Tool for WebSearchTool {
fn name(&self) -> &str {
"web_search"
}
fn description(&self) -> &str {
"Search the web for a query and return a list of results. Supports operators such as site: and \"quoted phrases\". The count argument is optional."
}
fn execute(&self, arguments: &str) -> Result<String, io::Error> {
let data: Value = serde_json::from_str(arguments).map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, format!("Invalid arguments: {}", e)))?;
let query = arg_str(&data, "query")?;
let count = arg_usize(&data, "count", DEFAULT_COUNT).clamp(1, MAX_COUNT);
let mut last_err: Option<String> = None;
for backend in &self.backends {
match backend.search(query, count) {
Ok(hits) if !hits.is_empty() => return Ok(format_results(&hits)),
Ok(_) => last_err = Some("no results found".to_string()),
Err(e) => last_err = Some(e.to_string()),
}
}
match last_err {
Some(msg) => Ok(format!("search failed: {}. Try again later or use web_fetch on a known URL.", msg)),
None => Ok("search failed.".to_string()),
}
}
}
fn parse_results(html: &str) -> Option<Vec<SearchHit>> {
let document = Html::parse_document(html);
let container = Selector::parse("div.results").expect("static selector is valid");
if document.select(&container).next().is_none() {
return None;
}
let result = Selector::parse("div.result").expect("static selector is valid");
let link = Selector::parse("a.result__a").expect("static selector is valid");
let snippet = Selector::parse(".result__snippet").expect("static selector is valid");
let mut hits = Vec::new();
for res in document.select(&result) {
let href = match res.select(&link).next().and_then(|a| a.attr("href")) {
Some(h) => h,
None => continue,
};
let title = res.select(&link).next().map(node_text).unwrap_or_default();
let url = unwrap_uddg(href);
if is_ad_url(&url) {
continue;
}
if url.is_empty() || title.is_empty() {
continue;
}
let snippet_text = res.select(&snippet).next().map(node_text).unwrap_or_default();
hits.push(SearchHit { title, url, snippet: snippet_text });
}
Some(hits)
}
fn node_text(el: scraper::ElementRef<'_>) -> String {
el.text().collect::<Vec<_>>().join(" ").split_whitespace().collect::<Vec<_>>().join(" ")
}
fn unwrap_uddg(href: &str) -> String {
let candidate = if href.starts_with("//") {
format!("https:{}", href)
} else {
href.to_string()
};
let Ok(url) = Url::parse(&candidate) else {
return href.to_string();
};
if let Some(real) = url.query_pairs().find_map(|(k, v)| (k == "uddg").then(|| v.into_owned())) {
return real;
}
candidate
}
fn is_ad_url(url: &str) -> bool {
let Ok(parsed) = Url::parse(url) else {
return false;
};
let is_ddg = parsed.host_str().map(|h| h == "duckduckgo.com" || h.ends_with(".duckduckgo.com")).unwrap_or(false);
is_ddg && parsed.path().contains("/y.js")
}
fn format_results(hits: &[SearchHit]) -> String {
let mut out = String::new();
for (i, hit) in hits.iter().enumerate() {
if i > 0 {
out.push('\n');
}
out.push_str(&format!("{}. {}\n {}\n {}", i + 1, hit.title, hit.url, hit.snippet));
}
out
}
#[cfg(test)]
mod tests {
use super::*;
const DDG_FIXTURE: &str = r#"<html><body>
<div class="results" id="links">
<div class="result results_links results_links_deep web-result">
<a rel="nofollow" class="result__a" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpage&rut=abc">Example Title</a>
<a class="result__snippet" href="//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpage&rut=abc">This is a snippet.</a>
</div>
<div class="result result--ad">
<a class="result__a" href="//duckduckgo.com/y.js?u3=ad&u2=example.com">Ad Title</a>
<a class="result__snippet" href="//duckduckgo.com/y.js">Ad snippet</a>
</div>
</div>
</body></html>"#;
#[test]
fn parses_ddg_results_page() {
let hits = parse_results(DDG_FIXTURE).expect("fixture should be a results page");
assert_eq!(hits.len(), 1);
assert_eq!(hits[0].title, "Example Title");
assert_eq!(hits[0].url, "https://example.com/page");
assert_eq!(hits[0].snippet, "This is a snippet.");
}
#[test]
fn detects_unexpected_page() {
let hits = parse_results("<html><body>Challenge required</body></html>");
assert!(hits.is_none());
}
#[test]
fn empty_results_container_is_no_results() {
let hits = parse_results("<html><body><div class=\"results\"></div></body></html>");
assert!(hits.is_some());
assert!(hits.unwrap().is_empty());
}
#[test]
fn unwraps_uddg() {
let real = unwrap_uddg("//duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpath%3Fx%3D1");
assert_eq!(real, "https://example.com/path?x=1");
}
#[test]
fn uddg_passthrough_when_no_uddg_param() {
let url = unwrap_uddg("https://example.com/plain");
assert_eq!(url, "https://example.com/plain");
}
#[test]
fn detects_ad_links() {
assert!(is_ad_url("https://duckduckgo.com/y.js?u3=x"));
assert!(!is_ad_url("https://example.com/y.js"));
}
#[test]
fn formats_results_with_blank_lines() {
let hits = vec![
SearchHit { title: "A".into(), url: "https://a.example".into(), snippet: "snippet a".into() },
SearchHit { title: "B".into(), url: "https://b.example".into(), snippet: "snippet b".into() },
];
let out = format_results(&hits);
assert_eq!(out, "1. A\n https://a.example\n snippet a\n2. B\n https://b.example\n snippet b");
}
const MARGINALIA_FIXTURE: &str = r#"<html><body>
<section data-ms-rank="1" class="card search-result">
<div class="url"><a rel="nofollow external" href="https://example.com/page">https://example.com/page</a></div>
<h2> <a tabindex="-1" class="title" rel="nofollow external" href="https://example.com/page">Example Title</a> </h2>
<p class="description">This is a description snippet.</p>
</section>
<section data-ms-rank="2" class="card search-result">
<div class="url"><a rel="nofollow external" href="https://second.example/x">https://second.example/x</a></div>
<h2> <a tabindex="-1" class="title" rel="nofollow external" href="https://second.example/x">Second Result</a> </h2>
<p class="description">Another snippet.</p>
</section>
</body></html>"#;
#[test]
fn parses_marginalia_results_page() {
let hits = parse_marginalia(MARGINALIA_FIXTURE).expect("fixture should be a results page");
assert_eq!(hits.len(), 2);
assert_eq!(hits[0].title, "Example Title");
assert_eq!(hits[0].url, "https://example.com/page");
assert_eq!(hits[0].snippet, "This is a description snippet.");
}
#[test]
fn marginalia_detects_unexpected_page() {
let hits = parse_marginalia("<html><body>Wait a moment</body></html>");
assert!(hits.is_none());
}
#[test]
fn extracts_sst_token_from_wait_page() {
let html = "window.setTimeout(()=> { location.replace('/search?query=rust&sst=S-082e652404d5c7a7'); }, 1*1000);";
assert_eq!(extract_sst_token(html).as_deref(), Some("S-082e652404d5c7a7"));
}
#[test]
fn ignores_empty_sst_pagination_params() {
let html = "<a href=\"/search?query=rust&page=2&sst=\" class=\"page-link\">2</a>";
assert!(extract_sst_token(html).is_none());
}
}