1use async_trait::async_trait;
2use bamboo_agent_core::{Tool, ToolClass, ToolCtx, ToolError, ToolOutcome, ToolResult};
3use parking_lot::RwLock;
4use regex::Regex;
5use serde::Deserialize;
6use serde_json::json;
7use std::collections::{HashMap, HashSet};
8use std::sync::OnceLock;
9use std::time::{Duration, Instant};
10
11const CACHE_TTL: Duration = Duration::from_secs(15 * 60);
12const DEFAULT_MAX_RESULTS: usize = 10;
13const ABSOLUTE_MAX_RESULTS: usize = 20;
14const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
15
16#[derive(Debug, Deserialize)]
17struct WebSearchArgs {
18 query: String,
19 #[serde(default)]
20 allowed_domains: Option<Vec<String>>,
21 #[serde(default)]
22 blocked_domains: Option<Vec<String>>,
23 #[serde(default)]
24 max_results: Option<usize>,
25}
26
27struct CachedSearch {
28 results: serde_json::Value,
29 expires_at: Instant,
30}
31
32static SEARCH_CACHE: OnceLock<RwLock<HashMap<String, CachedSearch>>> = OnceLock::new();
33
34fn search_cache() -> &'static RwLock<HashMap<String, CachedSearch>> {
35 SEARCH_CACHE.get_or_init(|| RwLock::new(HashMap::new()))
36}
37
38static LINK_RE: OnceLock<Regex> = OnceLock::new();
41static TAG_RE: OnceLock<Regex> = OnceLock::new();
42static SNIPPET_RE: OnceLock<Regex> = OnceLock::new();
43static HREF_RE: OnceLock<Regex> = OnceLock::new();
44
45pub struct WebSearchTool;
46
47impl WebSearchTool {
48 pub fn new() -> Self {
49 Self
50 }
51
52 fn cache_key(
53 query: &str,
54 allowed: &Option<Vec<String>>,
55 blocked: &Option<Vec<String>>,
56 ) -> String {
57 let mut key = query.to_string();
58 if let Some(domains) = allowed {
59 key.push('|');
60 key.push_str(&domains.join(","));
61 }
62 key.push('|');
63 if let Some(domains) = blocked {
64 key.push_str(&domains.join(","));
65 }
66 key
67 }
68
69 fn try_cache(key: &str) -> Option<serde_json::Value> {
70 let cache = search_cache().read();
71 let entry = cache.get(key)?;
72 if entry.expires_at > Instant::now() {
73 Some(entry.results.clone())
74 } else {
75 None
76 }
77 }
78
79 fn put_cache(key: String, results: serde_json::Value) {
80 let mut cache = search_cache().write();
81 cache.insert(
82 key,
83 CachedSearch {
84 results,
85 expires_at: Instant::now() + CACHE_TTL,
86 },
87 );
88 }
89
90 fn decode_duckduckgo_url(raw: &str) -> Option<String> {
91 if let Ok(url) = url::Url::parse(raw) {
92 if let Some(value) = url
93 .query_pairs()
94 .find(|(key, _)| key == "uddg")
95 .map(|(_, value)| value.to_string())
96 {
97 return Some(value);
98 }
99 }
100
101 Some(raw.to_string())
102 }
103
104 fn host_of(url: &str) -> Option<String> {
105 url::Url::parse(url)
106 .ok()
107 .and_then(|parsed| parsed.host_str().map(|host| host.to_ascii_lowercase()))
108 }
109
110 fn domain_matches(host: &str, domain: &str) -> bool {
111 host == domain || host.ends_with(&format!(".{}", domain))
112 }
113}
114
115impl Default for WebSearchTool {
116 fn default() -> Self {
117 Self::new()
118 }
119}
120
121#[async_trait]
122impl Tool for WebSearchTool {
123 fn name(&self) -> &str {
124 "WebSearch"
125 }
126
127 fn description(&self) -> &str {
128 "Search DuckDuckGo and return up to 10 filtered results (title, url, domain, snippet) with optional allow/block domain filters."
129 }
130
131 fn classify(&self, _args: &serde_json::Value) -> ToolClass {
132 ToolClass::READONLY_PARALLEL.promotable()
133 }
134
135 fn parameters_schema(&self) -> serde_json::Value {
136 json!({
137 "type": "object",
138 "properties": {
139 "query": {
140 "type": "string",
141 "minLength": 2,
142 "description": "The search query to use"
143 },
144 "allowed_domains": {
145 "type": "array",
146 "items": { "type": "string" },
147 "description": "Only include results from these domains"
148 },
149 "blocked_domains": {
150 "type": "array",
151 "items": { "type": "string" },
152 "description": "Never include results from these domains"
153 },
154 "max_results": {
155 "type": "number",
156 "description": "Maximum results to return (default 10, max 20)"
157 }
158 },
159 "required": ["query"],
160 "additionalProperties": false
161 })
162 }
163
164 async fn invoke(&self, args: serde_json::Value, ctx: ToolCtx) -> Result<ToolOutcome, ToolError> {
165 let parsed: WebSearchArgs = serde_json::from_value(args)
166 .map_err(|e| ToolError::InvalidArguments(format!("Invalid WebSearch args: {}", e)))?;
167
168 let query = parsed.query.trim();
169 if query.len() < 2 {
170 return Err(ToolError::InvalidArguments(
171 "query must be at least 2 characters".to_string(),
172 ));
173 }
174
175 let allowed_domains = parsed.allowed_domains.filter(|v| !v.is_empty());
176 let blocked_domains = parsed.blocked_domains.filter(|v| !v.is_empty());
177
178 if allowed_domains.is_some() && blocked_domains.is_some() {
180 return Err(ToolError::InvalidArguments(
181 "Cannot specify both allowed_domains and blocked_domains in the same request"
182 .to_string(),
183 ));
184 }
185
186 let max_results = parsed
187 .max_results
188 .unwrap_or(DEFAULT_MAX_RESULTS)
189 .min(ABSOLUTE_MAX_RESULTS);
190
191 let cache_key = Self::cache_key(query, &allowed_domains, &blocked_domains);
193 if let Some(cached) = Self::try_cache(&cache_key) {
194 ctx.emit_tool_token("Using cached search results\n").await;
195 return Ok(ToolOutcome::Completed(ToolResult {
196 success: true,
197 result: cached.to_string(),
198 display_preference: Some("Collapsible".to_string()),
199 images: Vec::new(),
200 }));
201 }
202
203 ctx.emit_tool_token(format!("Searching: {}\n", query)).await;
204
205 let client = reqwest::Client::builder()
206 .timeout(Duration::from_secs(30))
207 .build()
208 .map_err(|e| ToolError::Execution(format!("Failed to build HTTP client: {}", e)))?;
209
210 let response = client
211 .get("https://duckduckgo.com/html/")
212 .header("User-Agent", USER_AGENT)
213 .query(&[("q", query)])
214 .send()
215 .await
216 .map_err(|e| ToolError::Execution(format!("Web search request failed: {}", e)))?;
217
218 let html = response.text().await.map_err(|e| {
219 ToolError::Execution(format!("Failed to decode web search body: {}", e))
220 })?;
221
222 if html.contains("Unfortunately, bots use DuckDuckGo too") || html.contains("anomaly-modal")
224 {
225 return Err(ToolError::Execution(
226 "Search blocked by anti-bot protection. Please retry.".to_string(),
227 ));
228 }
229
230 let allowed: Option<HashSet<String>> = allowed_domains.map(|domains| {
231 domains
232 .into_iter()
233 .map(|value| value.to_ascii_lowercase())
234 .collect()
235 });
236 let blocked: HashSet<String> = blocked_domains
237 .unwrap_or_default()
238 .into_iter()
239 .map(|value| value.to_ascii_lowercase())
240 .collect();
241
242 let link_re = LINK_RE.get_or_init(|| {
243 Regex::new(r#"<a[^>]*class="result__a"[^>]*href="([^"]+)"[^>]*>(.*?)</a>"#)
244 .expect("valid static regex")
245 });
246 let tag_re =
247 TAG_RE.get_or_init(|| Regex::new(r"(?is)<[^>]+>").expect("valid static regex"));
248 let snippet_re = SNIPPET_RE.get_or_init(|| {
249 Regex::new(r#"<a[^>]*class="result__snippet"[^>]*href="[^"]*"[^>]*>(.*?)</a>"#)
250 .expect("valid static regex")
251 });
252
253 let href_re =
255 HREF_RE.get_or_init(|| Regex::new(r#"href="([^"]+)""#).expect("valid static regex"));
256 let mut snippets: HashMap<String, String> = HashMap::new();
257 for cap in snippet_re.captures_iter(&html) {
258 if let Some(href_cap) = cap.get(0) {
259 let href_text = href_cap.as_str();
260 if let Some(url_match) = href_re.find(href_text) {
262 let raw_href = &href_text[url_match.start() + 6..url_match.end() - 1];
263 if let Some(decoded) = Self::decode_duckduckgo_url(raw_href) {
264 let snippet_text = cap
265 .get(1)
266 .map(|m| tag_re.replace_all(m.as_str(), "").trim().to_string())
267 .unwrap_or_default();
268 if !snippet_text.is_empty() {
269 snippets.insert(decoded, snippet_text);
270 }
271 }
272 }
273 }
274 }
275
276 let mut results = Vec::new();
277 for capture in link_re.captures_iter(&html) {
278 let Some(raw_url) = capture.get(1).map(|m| m.as_str()) else {
279 continue;
280 };
281 let Some(url) = Self::decode_duckduckgo_url(raw_url) else {
282 continue;
283 };
284 let Some(host) = Self::host_of(&url) else {
285 continue;
286 };
287
288 if blocked
289 .iter()
290 .any(|blocked_domain| Self::domain_matches(&host, blocked_domain))
291 {
292 continue;
293 }
294 if let Some(allowed_set) = &allowed {
295 if !allowed_set
296 .iter()
297 .any(|allowed_domain| Self::domain_matches(&host, allowed_domain))
298 {
299 continue;
300 }
301 }
302
303 let title = capture
304 .get(2)
305 .map(|m| tag_re.replace_all(m.as_str(), "").trim().to_string())
306 .unwrap_or_else(|| url.clone());
307
308 let snippet = snippets.get(&url).cloned().unwrap_or_default();
309
310 let mut result = json!({
311 "title": title,
312 "url": url,
313 "domain": host,
314 });
315 if !snippet.is_empty() {
316 result["snippet"] = json!(snippet);
317 }
318 results.push(result);
319
320 if results.len() >= max_results {
321 break;
322 }
323 }
324
325 ctx.emit_tool_token(format!(
326 "Found {} results for \"{}\"\n",
327 results.len(),
328 query
329 ))
330 .await;
331
332 let result_value = if results.is_empty() {
333 json!({
334 "query": parsed.query,
335 "results": [],
336 "note": "No results found for this query.",
337 })
338 } else {
339 json!({
340 "query": parsed.query,
341 "results": results,
342 })
343 };
344
345 Self::put_cache(cache_key, result_value.clone());
347
348 let mut result_string = result_value.to_string();
349 result_string.push_str("\n\nREMINDER: You MUST include a Sources section at the end of your response, listing all relevant URLs as markdown hyperlinks: [Title](URL)");
350
351 Ok(ToolOutcome::Completed(ToolResult {
352 success: true,
353 result: result_string,
354 display_preference: Some("Collapsible".to_string()),
355 images: Vec::new(),
356 }))
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363
364 #[test]
365 fn domain_matches_supports_subdomains() {
366 assert!(WebSearchTool::domain_matches("example.com", "example.com"));
367 assert!(WebSearchTool::domain_matches(
368 "docs.example.com",
369 "example.com"
370 ));
371 assert!(!WebSearchTool::domain_matches(
372 "notexample.com",
373 "example.com"
374 ));
375 assert!(!WebSearchTool::domain_matches(
376 "evil-example.com",
377 "example.com"
378 ));
379 }
380
381 #[test]
382 fn host_of_normalizes_case() {
383 let host = WebSearchTool::host_of("https://Docs.Example.Com/path").unwrap();
384 assert_eq!(host, "docs.example.com");
385 }
386
387 #[test]
388 fn decode_duckduckgo_url_extracts_uddg_param() {
389 let raw = "https://duckduckgo.com/l/?uddg=https%3A%2F%2Fexample.com%2Fpage&rut=whatever";
390 let decoded = WebSearchTool::decode_duckduckgo_url(raw).unwrap();
391 assert_eq!(decoded, "https://example.com/page");
392 }
393
394 #[test]
395 fn cache_key_is_stable() {
396 let k1 =
397 WebSearchTool::cache_key("rust", &Some(vec!["doc.rust-lang.org".to_string()]), &None);
398 let k2 =
399 WebSearchTool::cache_key("rust", &Some(vec!["doc.rust-lang.org".to_string()]), &None);
400 assert_eq!(k1, k2);
401
402 let k3 = WebSearchTool::cache_key("rust", &None, &Some(vec!["bad.com".to_string()]));
403 assert_ne!(k1, k3);
404 }
405}