1use super::traits::Tool;
18use crate::config::constants::tools;
19use anyhow::{Context, Result, anyhow};
20use async_trait::async_trait;
21use serde::Deserialize;
22use serde_json::{Value, json};
23use std::borrow::Cow;
24use std::collections::HashMap;
25use std::sync::{Arc, Mutex};
26use std::time::{Duration, Instant};
27use vtcode_config::WebSearchConfig;
28
29mod parser;
30mod transport;
31
32pub use parser::parse_duckduckgo_html;
33use transport::duckduckgo_search;
34
35const MAX_QUERY_CHARS: usize = 500;
36const MAX_RESULTS_CAP: usize = 20;
37
38const GITHUB_GH_FALLBACK: &str =
42 "For GitHub queries, use `gh search`/`gh api` via exec_command instead (subject to exec policy).";
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
46pub(crate) fn web_search_parameter_schema() -> Value {
48 json!({
49 "type": "object",
50 "properties": {
51 "query": {
52 "type": "string",
53 "description": "A nonblank search query (a topic, question, or keywords), up to 500 characters.",
54 "minLength": 1,
55 "maxLength": MAX_QUERY_CHARS
56 },
57 "max_results": {
58 "type": "integer",
59 "description": "Maximum number of results to return (default: 8, max: 20)."
60 }
61 },
62 "required": ["query"],
63 "additionalProperties": false
64 })
65}
66
67#[derive(Debug, Deserialize)]
68#[serde(deny_unknown_fields)]
69struct WebSearchArgs {
70 query: String,
72 #[serde(default)]
73 max_results: Option<usize>,
74}
75
76pub struct SearchResult {
77 pub title: String,
78 pub url: String,
79 pub snippet: String,
80}
81
82impl SearchResult {
83 pub fn new(title: String, url: String, snippet: String) -> Self {
84 Self { title, url, snippet }
85 }
86}
87
88#[derive(Default)]
92struct SessionState {
93 last_request_at: Option<Instant>,
94 requests_made: u32,
95 cache: HashMap<String, CachedResults>,
96}
97
98struct CachedResults {
99 stored_at: Instant,
100 payload: Value,
101}
102
103impl SessionState {
104 fn cache_get(&self, key: &str, ttl: Duration) -> Option<Value> {
105 let entry = self.cache.get(key)?;
106 if entry.stored_at.elapsed() > ttl {
107 return None;
108 }
109 Some(entry.payload.clone())
110 }
111
112 fn cache_put(&mut self, key: String, payload: Value) {
113 self.cache.insert(key, CachedResults { stored_at: Instant::now(), payload });
114 }
115}
116
117#[derive(Clone, Default)]
121pub struct WebSearchTool {
122 config: Arc<Mutex<WebSearchConfig>>,
123 state: Arc<Mutex<SessionState>>,
124}
125
126impl WebSearchTool {
127 pub fn new() -> Self {
128 Self {
129 config: Arc::new(Mutex::new(WebSearchConfig::default())),
130 state: Arc::new(Mutex::new(SessionState::default())),
131 }
132 }
133
134 pub fn with_config(config: WebSearchConfig) -> Self {
138 Self {
139 config: Arc::new(Mutex::new(config)),
140 state: Arc::new(Mutex::new(SessionState::default())),
141 }
142 }
143
144 pub fn set_config(&self, config: WebSearchConfig) {
146 if let Ok(mut guard) = self.config.lock() {
147 *guard = config;
148 }
149 }
150
151 pub fn reset(&self) {
153 if let Ok(mut guard) = self.state.lock() {
154 *guard = SessionState::default();
155 }
156 }
157
158 fn snapshot_config(&self) -> Result<WebSearchConfig> {
159 self.config
160 .lock()
161 .map(|guard| guard.clone())
162 .map_err(|error| anyhow!("web_search config lock poisoned: {error}"))
163 }
164
165 async fn run(&self, raw_args: Value) -> Result<Value> {
166 let args: WebSearchArgs =
167 serde_json::from_value(raw_args).context("Invalid arguments for web_search. Provide a 'query' string.")?;
168
169 let query = args.query.trim().to_string();
170 if query.is_empty() || query.chars().count() > MAX_QUERY_CHARS {
171 return Err(anyhow!("web_search requires a nonblank query of at most {MAX_QUERY_CHARS} characters"));
172 }
173
174 let snapshot = self.snapshot_config()?;
175 let default_max = snapshot.max_results.clamp(1, MAX_RESULTS_CAP);
176 let max_results = args.max_results.unwrap_or(default_max).clamp(1, MAX_RESULTS_CAP);
177 let cooldown = Duration::from_millis(snapshot.cooldown_ms);
178 let cache_ttl = Duration::from_secs(snapshot.cache_ttl_secs);
179 let session_cap = snapshot.session_max_requests;
180 let provider = snapshot.provider.backend_id();
181
182 let cache_key = format!("{max_results}::{query}");
188
189 let cached = self
191 .state
192 .lock()
193 .map_err(|error| anyhow!("web_search state lock poisoned: {error}"))?
194 .cache_get(&cache_key, cache_ttl);
195 if let Some(cached) = cached {
196 return Ok(mark_cached(cached, provider));
197 }
198
199 if let Some(response) = self.admit_request(&query, provider, cooldown, session_cap)? {
203 return Ok(response);
204 }
205
206 let results = duckduckgo_search(&query, max_results, snapshot.timeout_secs).await;
207
208 match results {
209 Ok(results) => {
210 let payload = results_response(&query, provider, results);
211 self.cache_put(&cache_key, &payload)?;
212 Ok(payload)
213 }
214 Err(e) => {
215 Ok(search_error_response(&query, provider, &e.to_string()))
217 }
218 }
219 }
220
221 fn cache_put(&self, key: &str, payload: &Value) -> Result<()> {
222 let mut state = self
223 .state
224 .lock()
225 .map_err(|error| anyhow!("web_search state lock poisoned: {error}"))?;
226 state.cache_put(key.to_string(), payload.clone());
227 Ok(())
228 }
229
230 fn admit_request(
231 &self,
232 query: &str,
233 provider: &str,
234 cooldown: Duration,
235 session_cap: u32,
236 ) -> Result<Option<Value>> {
237 let mut state = self.state.lock().map_err(|e| anyhow!("web_search state lock poisoned: {e}"))?;
238 if state.requests_made >= session_cap {
239 return Ok(Some(session_cap_reached_response(provider, query, session_cap)));
240 }
241 if let Some(last) = state.last_request_at {
242 let elapsed = last.elapsed();
243 if elapsed < cooldown {
244 return Ok(Some(cooldown_response(provider, query, cooldown.saturating_sub(elapsed))));
245 }
246 }
247 state.requests_made = state.requests_made.saturating_add(1);
248 state.last_request_at = Some(Instant::now());
249 Ok(None)
250 }
251}
252
253#[derive(Debug, Clone, PartialEq, Eq)]
254struct SearchErrorClassification {
255 error_type: &'static str,
256 next_action: Cow<'static, str>,
257 retryable: bool,
258}
259
260fn classify_search_error(message: &str) -> SearchErrorClassification {
264 let lower = message.to_lowercase();
265 let status = crate::tools::web_fetch::classify_helpers::extract_http_status(&lower);
266 if matches!(status, Some(202 | 403 | 429)) || lower.contains("anti-bot") || lower.contains("challenge") {
267 return SearchErrorClassification {
268 error_type: "antiban_blocked",
269 next_action: Cow::Owned(format!(
270 "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. {GITHUB_GH_FALLBACK}"
271 )),
272 retryable: false,
273 };
274 }
275 if lower.contains("response exceeds") || lower.contains("body exceeded") {
276 return SearchErrorClassification {
277 error_type: "response_too_large",
278 next_action: Cow::Borrowed(
279 "DuckDuckGo returned an oversized response. Narrow the query before explicitly retrying.",
280 ),
281 retryable: false,
282 };
283 }
284 if status.is_some_and(|status| (500..=599).contains(&status)) {
285 return SearchErrorClassification {
286 error_type: "upstream_error",
287 next_action: Cow::Borrowed(
288 "The search service is currently unavailable. Retry once after a short delay, or use web_fetch on a known URL as a fallback.",
289 ),
290 retryable: true,
291 };
292 }
293 if lower.contains("timeout") || lower.contains("timed out") {
294 return SearchErrorClassification {
295 error_type: "network_error",
296 next_action: Cow::Borrowed(
297 "DuckDuckGo timed out. Retry once after a short delay, or use web_fetch on a known URL as a fallback.",
298 ),
299 retryable: true,
300 };
301 }
302 SearchErrorClassification {
303 error_type: "network_error",
304 next_action: Cow::Borrowed(
305 "Retry once after a short delay, or use web_fetch directly if you already know a relevant URL.",
306 ),
307 retryable: true,
308 }
309}
310
311fn results_response(query: &str, provider: &str, results: Vec<SearchResult>) -> Value {
312 let count = results.len();
313 let mut payload = json!({
314 "query": query,
315 "provider": provider,
316 "count": count,
317 "cached": false,
318 "results": results
319 .into_iter()
320 .map(|result| json!({ "title": result.title, "url": result.url, "snippet": result.snippet }))
321 .collect::<Vec<_>>(),
322 });
323
324 if count == 0 {
325 payload["warning"] = json!(format!(
326 "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. {GITHUB_GH_FALLBACK}"
327 ));
328 }
329
330 payload
331}
332
333fn search_error_response(query: &str, provider: &str, message: &str) -> Value {
334 let classification = classify_search_error(message);
335 json!({
336 "error": format!("web_search failed: {message}"),
337 "query": query,
338 "provider": provider,
339 "error_type": classification.error_type,
340 "retryable": classification.retryable,
341 "next_action": classification.next_action,
342 })
343}
344
345fn mark_cached(mut payload: Value, provider: &str) -> Value {
346 if let Value::Object(map) = &mut payload {
347 map.insert("provider".to_string(), Value::String(provider.to_owned()));
348 map.insert("cached".to_string(), Value::Bool(true));
349 }
350 payload
351}
352
353fn cooldown_response(provider: &str, query: &str, wait: Duration) -> Value {
354 let retry_after_ms = wait.as_millis().clamp(1, u64::MAX as u128) as u64;
355 json!({
356 "error": "web_search cooldown active",
357 "query": query,
358 "provider": provider,
359 "error_type": "cooldown",
360 "retryable": true,
361 "retry_after_ms": retry_after_ms,
362 "next_action": format!("Wait at least {retry_after_ms} ms before the next web search to avoid being rate-limited. {GITHUB_GH_FALLBACK}")
363 })
364}
365
366fn session_cap_reached_response(provider: &str, query: &str, cap: u32) -> Value {
367 json!({
368 "error": "web_search session request cap reached",
369 "query": query,
370 "provider": provider,
371 "error_type": "session_cap",
372 "retryable": false,
373 "session_max_requests": cap,
374 "request_budget_remaining": 0,
375 "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. {GITHUB_GH_FALLBACK}")
376 })
377}
378
379fn truncate_chars(input: &str, max_chars: usize) -> String {
384 vtcode_commons::formatting::truncate_text(input.trim(), max_chars, "…")
385}
386
387#[async_trait]
388impl Tool for WebSearchTool {
389 async fn execute(&self, args: Value) -> Result<Value> {
390 self.run(args).await
391 }
392
393 fn name(&self) -> &str {
394 tools::WEB_SEARCH
395 }
396
397 fn description(&self) -> &str {
398 WEB_SEARCH_DESCRIPTION
399 }
400}
401
402#[cfg(test)]
403mod tests;