返回 CodeWhale
web_search.rs
根目录 / crates / engine / src / tools / web_search.rs
1 //! Bounded provider-native/configured web search with explicit fallback receipts.
2 //! Adapters include Firecrawl, Tavily, Bocha, Metaso, SearXNG, Baidu,
3 //! Volcengine, Sofya, Serply, DeepSeek, and SearchApi; browsing remains a separate `web.run` workflow.
4 //! `[search]` example:
5 //! provider = "firecrawl" # keyless on Firecrawl Cloud; optional api_key
6 //! base_url = `"https://search.example/"` # DDG-compatible URL or SearXNG instance
7
8 use super::spec::{
9 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, optional_u64,
10 };
11 use async_trait::async_trait;
12 use codewhale_net::network_policy::{Decision, NetworkPolicyDecider};
13 use codewhale_runtime::config::{SearchProvider, tavily_env_key, tavily_key_from};
14 use regex::Regex;
15 use serde::{Deserialize, Serialize};
16 use serde_json::{Value, json};
17 use std::sync::OnceLock;
18 use std::time::{Duration, Instant};
19
20 use super::web::adapter::{self, AdapterFailure, AdapterResult};
21 use super::web::backend::SearchBackendChain;
22 use super::web::cache;
23 use super::web::contract::{
24 BackendId, BackendSearch, DEFAULT_SEARCH_RESULTS, DEFAULT_SEARCH_TIMEOUT_MS, DegradedReason,
25 HonoredQueryCapabilities, MAX_SEARCH_RESULTS, MAX_SEARCH_TIMEOUT_MS, QueryKnob, Recency,
26 SearchQuery, SearchReceipt, SearchResponse, SearchResult,
27 };
28 use super::web::scrape::{
29 BROWSER_USER_AGENT as USER_AGENT, ScrapedSearchResult, is_duckduckgo_challenge,
30 parse_bing_results as scrape_bing_results,
31 parse_duckduckgo_results as scrape_duckduckgo_results,
32 };
33
34 const DUCKDUCKGO_ENDPOINT: &str = "https://html.duckduckgo.com/html/";
35 const BING_HOST: &str = "www.bing.com";
36 const BING_ENDPOINT: &str = "https://www.bing.com/search";
37 const FIRECRAWL_ENDPOINT: &str = "https://api.firecrawl.dev/v2/search";
38 const TAVILY_ENDPOINT: &str = "https://api.tavily.com/search";
39 const BOCHA_ENDPOINT: &str = "https://api.bochaai.com/v1/web-search";
40 const METASO_ENDPOINT: &str = "https://metaso.cn/api/v1";
41 const BAIDU_ENDPOINT: &str = "https://qianfan.baidubce.com/v2/ai_search/web_search";
42 const VOLCENGINE_RESPONSES_ENDPOINT: &str = "https://ark.cn-beijing.volces.com/api/v3/responses";
43 const SOFYA_ENDPOINT: &str = "https://sofya.co/v1/search";
44 const SERPLY_ENDPOINT: &str = "https://api.serply.io/v1/search";
45 const DEEPSEEK_ENDPOINT: &str = "https://api.deepseek.com/v1/tools/search";
46 const SEARCHAPI_ENDPOINT: &str = "https://www.searchapi.io/api/v1/search";
47 const ERROR_BODY_PREVIEW_BYTES: usize = 512;
48 const PROVIDER_NATIVE_MIN_TIMEOUT_MS: u64 = 45_000;
49 const KIMI_K3_FORMULA_MIN_TIMEOUT_MS: u64 = 180_000;
50 /// Time a native-search attempt allows for its search round-trips before the
51 /// answer is generated (#6508).
52 const NATIVE_SEARCH_ROUND_TRIP_ALLOWANCE_MS: u64 = 30_000;
53 /// Conservative generation rate for a native-search answer. The request is
54 /// non-streaming, so the attempt must outlast the whole generation or the
55 /// answer is lost to the timeout rather than returned whole.
56 const NATIVE_SEARCH_ASSUMED_TOKENS_PER_SEC: u64 = 40;
57 const VOLCENGINE_MIN_TIMEOUT_MS: u64 = 90_000;
58
59 /// The recency and locale knobs an adapter forwards to its backend.
60 ///
61 /// Recency is rounded *up* to the backend's nearest window (day, week, month,
62 /// year), so `recency = 10` days asks for the last month: results are never
63 /// cut tighter than requested, but may be older than asked. Locale is a BCP 47
64 /// style tag (`en`, `en-US`, `de_DE`); each backend takes the part it accepts.
65 #[derive(Debug, Clone, Copy, Default)]
66 struct QueryFilters<'a> {
67 recency: Option<Recency>,
68 locale: Option<&'a str>,
69 prepared: Option<&'a PreparedFilters>,
70 }
71
72 impl<'a> QueryFilters<'a> {
73 fn of(query: &'a SearchQuery) -> Self {
74 Self {
75 prepared: None,
76 recency: query.recency,
77 locale: query
78 .locale
79 .as_deref()
80 .map(str::trim)
81 .filter(|value| !value.is_empty()),
82 }
83 }
84
85 /// `day` / `week` / `month` / `year`, rounded up from the request.
86 fn window(self) -> Option<&'a str> {
87 if let Some(prepared) = self.prepared {
88 return prepared.window.as_deref();
89 }
90 self.recency.map(|recency| match recency.days() {
91 0..=1 => "day",
92 2..=7 => "week",
93 8..=31 => "month",
94 _ => "year",
95 })
96 }
97
98 /// Lowercase language subtag (`en` from `en-US`).
99 fn language(self) -> Option<String> {
100 if let Some(prepared) = self.prepared {
101 return prepared.language.clone();
102 }
103 let language = self.locale?.split(['-', '_']).next()?;
104 (matches!(language.len(), 2 | 3) && language.chars().all(|ch| ch.is_ascii_alphabetic()))
105 .then(|| language.to_ascii_lowercase())
106 }
107
108 /// Two-letter region subtag, uppercase (`US` from `en-US`).
109 fn region(self) -> Option<String> {
110 if let Some(prepared) = self.prepared {
111 return prepared.region.clone();
112 }
113 let region = self.locale?.split(['-', '_']).nth(1)?;
114 (region.len() == 2 && region.chars().all(|ch| ch.is_ascii_alphabetic()))
115 .then(|| region.to_ascii_uppercase())
116 }
117 }
118
119 #[derive(Debug, serde::Deserialize)]
120 #[serde(deny_unknown_fields)]
121 struct PreparedFilters {
122 kind: String,
123 window: Option<String>,
124 language: Option<String>,
125 region: Option<String>,
126 }
127
128 #[derive(Debug, serde::Deserialize)]
129 #[serde(deny_unknown_fields)]
130 struct RequestProposal {
131 kind: String,
132 payload: Value,
133 pairs: Vec<(String, String)>,
134 }
135
136 async fn host_request(
137 backend: &str,
138 query: &str,
139 filters: QueryFilters<'_>,
140 max_results: usize,
141 context: &ToolContext,
142 timeout_ms: u64,
143 ) -> AdapterResult<Option<RequestProposal>> {
144 if !adapter::search_selected(context) {
145 return Ok(None);
146 }
147 let proposal: RequestProposal = adapter::transform(
148 crate::extension_host::StockOperation::WebRequest,
149 json!({"backend":backend,"query":query,"max_results":max_results,
150 "locale":filters.locale,"filters":{"window":filters.window(),
151 "language":filters.language(),"region":filters.region()}}),
152 context,
153 Duration::from_millis(timeout_ms),
154 )
155 .await?;
156 let valid = proposal.kind == "web_request"
157 && match backend {
158 "serply" | "searchapi" | "searxng" | "bing" | "duckduckgo" => {
159 proposal.payload.is_null()
160 && proposal.pairs.first() == Some(&("q".into(), query.into()))
161 && proposal
162 .pairs
163 .iter()
164 .enumerate()
165 .all(|(index, (key, value))| {
166 !proposal.pairs[..index]
167 .iter()
168 .any(|(prior, _)| prior == key)
169 && (key != "q" || value == query)
170 && (key != "num" || value == &max_results.to_string())
171 })
172 && proposal.pairs.iter().all(|(key, value)| {
173 matches!(
174 key.as_str(),
175 "q" | "num" | "hl" | "gl" | "format" | "time_range" | "language"
176 ) || (backend == "searchapi"
177 && ((key == "engine" && value == "google") || key == "time_period"))
178 })
179 }
180 "volcengine" => {
181 proposal.pairs.is_empty()
182 && proposal
183 .payload
184 .as_object()
185 .is_some_and(|value| value.len() == 1 && value.contains_key("input"))
186 }
187 name => {
188 let (query_path, count_path) = match name {
189 "firecrawl" => ("/query", "/limit"),
190 "tavily" | "sofya" => ("/query", "/max_results"),
191 "bocha" => ("/query", "/count"),
192 "metaso" => ("/q", "/size"),
193 "baidu" => ("/messages/0/content", "/resource_type_filter/0/top_k"),
194 _ => ("", ""),
195 };
196 proposal.pairs.is_empty()
197 && proposal.payload.pointer(query_path).and_then(Value::as_str) == Some(query)
198 && proposal.payload.pointer(count_path).and_then(Value::as_u64)
199 == Some(max_results as u64)
200 && proposal.payload.as_object().is_some_and(|value| {
201 value.keys().all(|key| {
202 matches!(
203 key.as_str(),
204 "query"
205 | "q"
206 | "limit"
207 | "max_results"
208 | "count"
209 | "size"
210 | "sources"
211 | "tbs"
212 | "country"
213 | "search_depth"
214 | "time_range"
215 | "freshness"
216 | "scope"
217 | "messages"
218 | "search_source"
219 | "resource_type_filter"
220 )
221 })
222 })
223 }
224 };
225 if !valid {
226 return Err(AdapterFailure::host(ToolError::execution_failed(
227 "Web Host returned a request outside the captured query contract",
228 )));
229 }
230 Ok(Some(proposal))
231 }
232
233 #[derive(Default)]
234 pub struct OpaqueUrls(std::collections::HashMap<String, String>);
235 impl OpaqueUrls {
236 pub fn capture(&mut self, value: &str) -> String {
237 if value.trim().is_empty() {
238 return value.into();
239 }
240 let token = format!("web-url-{}", self.0.len());
241 let leading = value.len() - value.trim_start().len();
242 let trailing = value.trim_end().len();
243 let wire = format!("{}{}{}", &value[..leading], token, &value[trailing..]);
244 self.0.insert(token, value.trim().into());
245 self.0.insert(wire.clone(), value.into());
246 wire
247 }
248 pub fn restore(&self, value: &str) -> AdapterResult<String> {
249 if value.trim().is_empty() {
250 return Ok(value.into());
251 }
252 self.0.get(value).cloned().ok_or_else(|| {
253 AdapterFailure::host(ToolError::execution_failed(
254 "Web Host returned an unknown source handle",
255 ))
256 })
257 }
258 }
259
260 fn provider_projection(value: &Value, urls: &mut OpaqueUrls, secret: Option<&str>) -> Value {
261 match value {
262 Value::Object(object) => Value::Object(
263 object
264 .iter()
265 .filter_map(|(key, value)| {
266 // Only fields consumed by a registered adapter cross the process.
267 if !matches!(
268 key.as_str(),
269 "results"
270 | "organic_results"
271 | "title"
272 | "name"
273 | "url"
274 | "link"
275 | "content"
276 | "snippet"
277 | "summary"
278 | "description"
279 | "markdown"
280 | "data"
281 | "web"
282 | "webpages"
283 | "webPages"
284 | "value"
285 | "pages"
286 | "references"
287 | "success"
288 | "error"
289 | "message"
290 | "msg"
291 | "code"
292 | "error_code"
293 | "error_msg"
294 | "output"
295 | "type"
296 | "text"
297 | "score"
298 ) {
299 return None;
300 }
301 let projected = if matches!(key.as_str(), "url" | "link") && value.is_string() {
302 Value::String(urls.capture(value.as_str().expect("string")))
303 } else {
304 provider_projection(value, urls, secret)
305 };
306 Some((key.clone(), projected))
307 })
308 .collect(),
309 ),
310 Value::Array(array) => Value::Array(
311 array
312 .iter()
313 .map(|value| provider_projection(value, urls, secret))
314 .collect(),
315 ),
316 Value::String(text) => Value::String(match secret.filter(|key| !key.is_empty()) {
317 Some(key) => text.replace(key, "[redacted]"),
318 None => text.clone(),
319 }),
320 _ => value.clone(),
321 }
322 }
323
324 #[derive(serde::Deserialize)]
325 #[serde(deny_unknown_fields)]
326 struct ProviderProposal {
327 kind: String,
328 entries: Vec<WebSearchEntry>,
329 error: Option<String>,
330 }
331
332 async fn host_provider(
333 backend: &str,
334 parsed: &Value,
335 max_results: usize,
336 secret: Option<&str>,
337 context: &ToolContext,
338 timeout_ms: u64,
339 ) -> AdapterResult<Option<Vec<WebSearchEntry>>> {
340 if !adapter::search_selected(context) {
341 return Ok(None);
342 }
343 let mut urls = OpaqueUrls::default();
344 let captured;
345 let source = if backend == "volcengine" {
346 // Rust's existing JSON/scalar guard is also the privacy boundary: never
347 // forward the raw model body or an embedded credential-bearing URL.
348 captured = if let Some(error) = parsed.get("error") {
349 json!({"error":provider_projection(error,&mut urls,secret)})
350 } else if let Some(text) = volcengine_extract_text(parsed) {
351 let inner = serde_json::from_str::<Value>(extract_json_block(&text).unwrap_or(&text))
352 .ok()
353 .map(|value| provider_projection(&value, &mut urls, secret));
354 json!({"output":[{"type":"message","content":[{"text":inner.map(|value| value.to_string()).unwrap_or_default()}]}]})
355 } else {
356 json!({})
357 };
358 &captured
359 } else {
360 parsed
361 };
362 let projection = if backend == "volcengine" {
363 source.clone()
364 } else {
365 provider_projection(source, &mut urls, secret)
366 };
367 let mut numbers = serde_json::Map::new();
368 for key in ["code", "error_code"] {
369 if let Some(value) = parsed.get(key) {
370 numbers.insert(
371 format!("/{key}"),
372 json!({"i64":value.as_i64().map(|value| value.to_string())}),
373 );
374 }
375 }
376 if backend == "searxng"
377 && let Some(values) = parsed.get("results").and_then(Value::as_array)
378 {
379 for (index, value) in values.iter().enumerate() {
380 numbers.insert(
381 format!("/results/{index}/score"),
382 json!({"score":searxng_score(value).to_string()}),
383 );
384 }
385 }
386 let mut proposal: ProviderProposal = adapter::transform(crate::extension_host::StockOperation::WebProvider,
387 json!({"backend":backend,"max_results":max_results,"parsed":projection.as_object().map(|_| &projection).unwrap_or(&json!({})),"number_facts":numbers}),
388 context,Duration::from_millis(timeout_ms)).await?;
389 if proposal.kind != "web_provider" || proposal.entries.len() > max_results {
390 return Err(AdapterFailure::host(ToolError::execution_failed(
391 "Web Host returned an invalid provider proposal",
392 )));
393 }
394 if let Some(error) = proposal.error {
395 return Err(ToolError::execution_failed(error).into());
396 }
397 for entry in &mut proposal.entries {
398 entry.url = urls.restore(&entry.url)?;
399 }
400 Ok(Some(proposal.entries))
401 }
402
403 #[derive(serde::Deserialize)]
404 #[serde(deny_unknown_fields)]
405 struct EntriesProposal {
406 kind: String,
407 entries: Vec<super::web::contract::CapturedSearchEntry>,
408 }
409
410 pub async fn normalize_captured_entries(
411 entries: Vec<super::web::contract::CapturedSearchEntry>,
412 context: &ToolContext,
413 budget: Duration,
414 ) -> AdapterResult<Vec<super::web::contract::CapturedSearchEntry>> {
415 if !adapter::search_selected(context) {
416 return Ok(entries);
417 }
418 let mut urls = OpaqueUrls::default();
419 let mut captured = entries.clone();
420 for entry in &mut captured {
421 entry.url = urls.capture(&entry.url);
422 }
423 let proposal: EntriesProposal = adapter::transform(
424 crate::extension_host::StockOperation::WebEntries,
425 json!({"entries":captured}),
426 context,
427 budget,
428 )
429 .await?;
430 if proposal.kind != "web_entries" || proposal.entries.len() != entries.len() {
431 return Err(AdapterFailure::host(ToolError::execution_failed(
432 "Web Host changed the captured source count",
433 )));
434 }
435 proposal
436 .entries
437 .into_iter()
438 .map(|mut entry| {
439 entry.url = urls.restore(&entry.url)?;
440 Ok(entry)
441 })
442 .collect()
443 }
444
445 /// Credential-free endpoint selected for an explicit doctor reachability
446 /// probe. The ordinary search request builders remain the source of truth for
447 /// provider endpoints; doctor borrows those endpoints without constructing a
448 /// query or reading an API key.
449 #[derive(Debug, Clone, PartialEq, Eq)]
450 pub struct SearchProbeTarget {
451 pub url: reqwest::Url,
452 pub host: String,
453 }
454
455 /// Safe configuration failures for a search reachability probe.
456 ///
457 /// These variants deliberately carry no configured URL: userinfo, paths, and
458 /// query strings may contain credentials and must never be echoed by doctor.
459 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
460 pub enum SearchProbeTargetError {
461 Missing,
462 Unsupported,
463 Invalid,
464 }
465
466 /// Resolve the configured provider's transport endpoint for doctor.
467 ///
468 /// Built-in endpoints keep their known request path. User-configured
469 /// DuckDuckGo-compatible and SearXNG URLs are reduced to their HTTP(S)
470 /// authority so the probe cannot transmit userinfo, path/query credentials,
471 /// or a real search query.
472 pub fn search_probe_target(
473 provider: SearchProvider,
474 base_url: Option<&str>,
475 ) -> Result<SearchProbeTarget, SearchProbeTargetError> {
476 let configured_base_url = configured_search_base_url(base_url);
477 if configured_base_url.is_some()
478 && !matches!(
479 provider,
480 SearchProvider::DuckDuckGo | SearchProvider::Searxng
481 )
482 {
483 return Err(SearchProbeTargetError::Unsupported);
484 }
485
486 let (raw, configured) = match provider {
487 SearchProvider::Bing => (BING_ENDPOINT, false),
488 SearchProvider::DuckDuckGo => (
489 configured_base_url.unwrap_or(DUCKDUCKGO_ENDPOINT),
490 configured_base_url.is_some(),
491 ),
492 SearchProvider::Firecrawl => (FIRECRAWL_ENDPOINT, false),
493 SearchProvider::Tavily => (TAVILY_ENDPOINT, false),
494 SearchProvider::Bocha => (BOCHA_ENDPOINT, false),
495 SearchProvider::Metaso => (METASO_ENDPOINT, false),
496 SearchProvider::Searxng => (
497 configured_base_url.ok_or(SearchProbeTargetError::Missing)?,
498 true,
499 ),
500 SearchProvider::Baidu => (BAIDU_ENDPOINT, false),
501 SearchProvider::Volcengine => (VOLCENGINE_RESPONSES_ENDPOINT, false),
502 SearchProvider::Sofya => (SOFYA_ENDPOINT, false),
503 SearchProvider::Serply => (SERPLY_ENDPOINT, false),
504 SearchProvider::DeepSeek => (DEEPSEEK_ENDPOINT, false),
505 SearchProvider::SearchApi => (SEARCHAPI_ENDPOINT, false),
506 };
507
508 let mut url = reqwest::Url::parse(raw).map_err(|_| SearchProbeTargetError::Invalid)?;
509 if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
510 return Err(SearchProbeTargetError::Invalid);
511 }
512
513 url.set_fragment(None);
514 url.set_query(None);
515 if configured {
516 url.set_username("")
517 .map_err(|_| SearchProbeTargetError::Invalid)?;
518 url.set_password(None)
519 .map_err(|_| SearchProbeTargetError::Invalid)?;
520 url.set_path("/");
521 }
522 let host = url
523 .host_str()
524 .ok_or(SearchProbeTargetError::Invalid)?
525 .to_string();
526
527 Ok(SearchProbeTarget { url, host })
528 }
529
530 /// Returns `Ok(())` if the policy allows the call, or a `ToolError` otherwise.
531 /// Falls through silently when no policy is attached (back-compat).
532 pub fn check_policy(decider: Option<&NetworkPolicyDecider>, host: &str) -> Result<(), ToolError> {
533 let Some(decider) = decider else {
534 return Ok(());
535 };
536 match decider.evaluate(host, "web_search") {
537 Decision::Allow => Ok(()),
538 Decision::Deny => Err(ToolError::permission_denied(format!(
539 "web search to '{host}' blocked by network policy"
540 ))),
541 Decision::Prompt => Err(ToolError::permission_denied(format!(
542 "web search to '{host}' requires approval; \
543 re-run after `/network allow {host}` or set network.default = \"allow\" in config"
544 ))),
545 }
546 }
547
548 // Cached regex for secret redaction in error bodies
549 static BEARER_TOKEN_RE: OnceLock<Regex> = OnceLock::new();
550
551 fn get_bearer_token_re() -> &'static Regex {
552 BEARER_TOKEN_RE.get_or_init(|| {
553 Regex::new(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+")
554 .expect("bearer token regex pattern is valid")
555 })
556 }
557
558 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
559 #[serde(deny_unknown_fields)]
560 struct WebSearchEntry {
561 title: String,
562 url: String,
563 snippet: Option<String>,
564 }
565
566 pub struct WebSearchTool;
567
568 #[async_trait]
569 impl ToolSpec for WebSearchTool {
570 fn name(&self) -> &'static str {
571 "web_search"
572 }
573
574 fn model_visible(&self) -> bool {
575 false
576 }
577
578 fn description(&self) -> &'static str {
579 "Search the web and return ranked results with URLs, snippets, session-scoped ref_ids, and an execution receipt. `web.run` opens a result ref_id when the short summary is not enough. When the exact active route reports a documented first-party server-side search tool, it is tried first; otherwise keyless Firecrawl is the default. Configured API backends visibly degrade through DuckDuckGo then Bing when unavailable, and every hop is recorded. Configuration and network-policy errors fail closed. Explicit Bing and private DuckDuckGo-compatible routes do not cross providers. Set `[search] provider = \"firecrawl\" | \"bing\" | \"tavily\" | \"bocha\" | \"metaso\" | \"searxng\" | \"baidu\" | \"volcengine\" | \"sofya\" | \"serply\" | \"deepseek\" | \"searchapi\"` in config.toml. Firecrawl Cloud works keyless with a bounded quota. `fetch_url` retrieves a known canonical URL directly."
580 }
581
582 fn input_schema(&self) -> Value {
583 json!({
584 "type": "object",
585 "properties": {
586 "query": {
587 "type": "string",
588 "description": "Search query. Compatibility aliases: q, or search_query[0].q."
589 },
590 "q": {
591 "type": "string",
592 "description": "Search query."
593 },
594 "search_query": {
595 "type": "array",
596 "description": "Array form for advanced queries: [{\"q\":\"...\", \"max_results\": 5}]",
597 "items": {
598 "type": "object",
599 "properties": {
600 "q": { "type": "string" },
601 "query": { "type": "string" },
602 "max_results": { "type": "integer" },
603 "recency": {
604 "oneOf": [
605 { "type": "string", "enum": ["day", "week", "month", "year"] },
606 { "type": "integer", "minimum": 1, "maximum": 3650 }
607 ]
608 },
609 "domains": { "type": "array", "items": { "type": "string" } },
610 "locale": { "type": "string" }
611 }
612 }
613 },
614 "max_results": {
615 "type": "integer",
616 "description": "Maximum number of results to return (default: 5, max: 10)"
617 },
618 "timeout_ms": {
619 "type": "integer",
620 "description": "Configured/local search timeout in milliseconds (default: 15000, max: 60000). Model-backed provider-native search has a separate bounded minimum before fallback."
621 },
622 "recency": {
623 "oneOf": [
624 { "type": "string", "enum": ["day", "week", "month", "year"] },
625 { "type": "integer", "minimum": 1, "maximum": 3650 }
626 ],
627 "description": "Requested freshness window. Unsupported backends report it as degraded instead of silently ignoring it."
628 },
629 "domains": {
630 "type": "array",
631 "items": { "type": "string" },
632 "description": "Restrict returned results to these domains. Backends without native support report post-filtering."
633 },
634 "locale": {
635 "type": "string",
636 "description": "Requested result locale as a BCP 47-style tag such as zh-CN or ja-JP; malformed values are ignored. The keyless Bing scrape honors it via its mkt/setlang market parameters; the keyless DuckDuckGo scrape maps a fixed region list and reports malformed or unmapped regions as ignored; unsupported backends report it as degraded."
637 }
638 }
639 })
640 }
641
642 fn capabilities(&self) -> Vec<ToolCapability> {
643 vec![ToolCapability::ReadOnly, ToolCapability::Network]
644 }
645
646 fn approval_requirement(&self) -> ApprovalRequirement {
647 // Read-only HTTP can still disclose local data through a URL or query.
648 // Host allowlisting controls reachability, not approval of this payload.
649 ApprovalRequirement::Required
650 }
651
652 fn supports_parallel(&self) -> bool {
653 true
654 }
655
656 fn refusal_before_approval(&self, input: &Value, context: &ToolContext) -> Option<ToolResult> {
657 super::web::consent::planned_search_refusal(self.name(), input, context)
658 .map(ToolResult::success)
659 }
660
661 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
662 let query = search_query_from_input(&input)?;
663 let timeout_ms = optional_u64(&input, "timeout_ms", DEFAULT_SEARCH_TIMEOUT_MS)?
664 .min(MAX_SEARCH_TIMEOUT_MS);
665 let chosen = super::web::consent::with_chosen_search(context);
666 let context = chosen.as_ref().unwrap_or(context);
667 if let Some(refusal) = super::web::consent::search_refusal(context) {
668 return Ok(ToolResult::success(refusal));
669 }
670 let response = execute_search(query, timeout_ms, context).await?;
671 ToolResult::json(&response).map_err(|error| ToolError::execution_failed(error.to_string()))
672 }
673 }
674
675 impl WebSearchTool {
676 async fn run_firecrawl_search(
677 &self,
678 query: &str,
679 filters: QueryFilters<'_>,
680 max_results: usize,
681 timeout_ms: u64,
682 context: &ToolContext,
683 ) -> AdapterResult<(Vec<WebSearchEntry>, String)> {
684 let env_key = std::env::var("FIRECRAWL_API_KEY").ok();
685 self.run_firecrawl_search_at_for_context(
686 FIRECRAWL_ENDPOINT,
687 query,
688 filters,
689 max_results,
690 timeout_ms,
691 context.search_api_key.as_deref().or(env_key.as_deref()),
692 context,
693 )
694 .await
695 }
696
697 #[cfg(test)]
698 async fn run_firecrawl_search_at(
699 &self,
700 endpoint: &str,
701 query: &str,
702 filters: QueryFilters<'_>,
703 max_results: usize,
704 timeout_ms: u64,
705 api_key: Option<&str>,
706 ) -> Result<(Vec<WebSearchEntry>, String), ToolError> {
707 let context = ToolContext::new(
708 std::env::current_dir()
709 .map_err(|error| ToolError::execution_failed(error.to_string()))?,
710 );
711 self.run_firecrawl_search_at_for_context(
712 endpoint,
713 query,
714 filters,
715 max_results,
716 timeout_ms,
717 api_key,
718 &context,
719 )
720 .await
721 .map_err(Into::into)
722 }
723
724 async fn run_firecrawl_search_at_for_context(
725 &self,
726 endpoint: &str,
727 query: &str,
728 filters: QueryFilters<'_>,
729 max_results: usize,
730 timeout_ms: u64,
731 api_key: Option<&str>,
732 context: &ToolContext,
733 ) -> AdapterResult<(Vec<WebSearchEntry>, String)> {
734 let client = crate::platform_client_builder()
735 .timeout(Duration::from_millis(timeout_ms))
736 .user_agent(USER_AGENT)
737 .build()
738 .map_err(|e| {
739 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
740 })?;
741 let api_key = api_key.map(str::trim).filter(|key| !key.is_empty());
742 let payload = if let Some(plan) = host_request(
743 "firecrawl",
744 query,
745 filters,
746 max_results,
747 context,
748 timeout_ms,
749 )
750 .await?
751 {
752 plan.payload
753 } else {
754 {
755 let mut payload =
756 json!({"query":query,"limit":max_results,"sources":[{"type":"web"}]});
757 if let Some(window) = filters.window() {
758 payload["tbs"] = json!(format!("qdr:{}", &window[..1]));
759 }
760 if let Some(region) = filters.region() {
761 payload["country"] = json!(region);
762 }
763 payload
764 }
765 };
766 let mut request = client.post(endpoint).json(&payload);
767 if let Some(key) = api_key {
768 request = request.bearer_auth(key);
769 }
770 let response = request.send().await.map_err(|e| {
771 ToolError::execution_failed(format!("Firecrawl search request failed: {e}"))
772 })?;
773 let status = response.status();
774 let body = if adapter::search_selected(context) {
775 adapter::read_response(response, context).await?
776 } else {
777 response.text().await.map_err(|e| {
778 ToolError::execution_failed(format!("Failed to read Firecrawl response: {e}"))
779 })?
780 };
781 if !status.is_success() {
782 let message = match status.as_u16() {
783 401 | 403 if api_key.is_none() => "Firecrawl rejected keyless search; set `[search] api_key` or FIRECRAWL_API_KEY".to_string(),
784 401 | 403 => "Firecrawl authentication was rejected; check `[search] api_key` or FIRECRAWL_API_KEY".to_string(),
785 429 if api_key.is_none() => "Firecrawl keyless quota is exhausted; retry later or set `[search] api_key` / FIRECRAWL_API_KEY".to_string(),
786 429 => "Firecrawl quota is exhausted; retry later or check the configured account limits".to_string(),
787 code => format!("Firecrawl search failed: HTTP {code} — {}", truncate_error_body(&body)),
788 };
789 return Err((ToolError::execution_failed(message)).into());
790 }
791 let parsed: Value = serde_json::from_str(&body).map_err(|e| {
792 ToolError::execution_failed(format!("Failed to parse Firecrawl response: {e}"))
793 })?;
794 if let Some(entries) = host_provider(
795 "firecrawl",
796 &parsed,
797 max_results,
798 api_key,
799 context,
800 timeout_ms,
801 )
802 .await?
803 {
804 return Ok((
805 entries,
806 format!(
807 "Firecrawl {}",
808 if api_key.is_some() {
809 "authenticated"
810 } else {
811 "keyless"
812 }
813 ),
814 ));
815 }
816
817 if parsed.get("success").and_then(Value::as_bool) == Some(false) {
818 let detail = first_non_empty_string(&parsed, &["error", "message"])
819 .unwrap_or_else(|| "unknown API error".to_string());
820 return Err((ToolError::execution_failed(format!(
821 "Firecrawl search failed: {detail}"
822 )))
823 .into());
824 }
825 let mode = if api_key.is_some() {
826 "authenticated"
827 } else {
828 "keyless"
829 };
830 Ok((
831 parse_firecrawl_results(&parsed, max_results),
832 format!("Firecrawl {mode}"),
833 ))
834 }
835
836 /// Search a configured SearXNG JSON API; no public instance is assumed.
837 async fn run_searxng_search(
838 &self,
839 query: &str,
840 filters: QueryFilters<'_>,
841 max_results: usize,
842 timeout_ms: u64,
843 context: &ToolContext,
844 ) -> AdapterResult<(Vec<WebSearchEntry>, String)> {
845 let (url, host) = if let Some(plan) =
846 host_request("searxng", query, filters, max_results, context, timeout_ms).await?
847 {
848 // The configured origin/path/query are private Core authority.
849 let (base, host) = searxng_search_base(context.search_base_url.as_deref())?;
850 let mut url = base;
851 for (key, value) in plan.pairs {
852 url.query_pairs_mut().append_pair(&key, &value);
853 }
854 (url.to_string(), host)
855 } else {
856 searxng_search_url(context.search_base_url.as_deref(), query, filters)?
857 };
858 check_policy(context.network_policy.as_ref(), &host)?;
859
860 let client = crate::platform_client_builder()
861 .timeout(Duration::from_millis(timeout_ms))
862 .user_agent(USER_AGENT)
863 .build()
864 .map_err(|e| {
865 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
866 })?;
867
868 let resp = client
869 .get(&url)
870 .header("Accept", "application/json")
871 .send()
872 .await
873 .map_err(|e| {
874 ToolError::execution_failed(format!("SearXNG search request to {host} failed: {e}"))
875 })?;
876
877 let status = resp.status();
878 let body = if adapter::search_selected(context) {
879 adapter::read_response(resp, context).await?
880 } else {
881 resp.text().await.map_err(|e| {
882 ToolError::execution_failed(format!(
883 "Failed to read SearXNG response from {host}: {e}"
884 ))
885 })?
886 };
887
888 if !status.is_success() {
889 let truncated = truncate_error_body(&body);
890 let msg = match status.as_u16() {
891 403 => format!(
892 "SearXNG search failed: HTTP 403 from {host}. Check that JSON output is enabled and this instance permits API access. {truncated}"
893 ),
894 429 => format!(
895 "SearXNG search failed: HTTP 429 from {host}. The configured instance is rate-limiting requests; use a trusted/self-hosted instance or retry later. {truncated}"
896 ),
897 code => format!("SearXNG search failed: HTTP {code} from {host}. {truncated}"),
898 };
899 return Err((ToolError::execution_failed(msg)).into());
900 }
901
902 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
903 ToolError::execution_failed(format!(
904 "Failed to parse SearXNG JSON response from {host}: {e}. Ensure the instance supports format=json and JSON output is enabled."
905 ))
906 })?;
907
908 if let Some(entries) =
909 host_provider("searxng", &parsed, max_results, None, context, timeout_ms).await?
910 {
911 return Ok((entries, host));
912 }
913
914 Ok((parse_searxng_results(&parsed, max_results), host))
915 }
916
917 /// Search via Tavily AI Search API (<https://tavily.com>).
918 async fn run_tavily_search(
919 &self,
920 query: &str,
921 filters: QueryFilters<'_>,
922 max_results: usize,
923 timeout_ms: u64,
924 context: &ToolContext,
925 ) -> AdapterResult<Vec<WebSearchEntry>> {
926 let api_key = tavily_key_from(context.search_api_key.as_deref())
927 .or_else(|| {
928 // An explicit `provider = "tavily"` still accepts any
929 // non-empty generic key, so a non-`tvly-` pin keeps working.
930 // Reaching this hop at all means Tavily was the resolved
931 // provider (pinned, or selected by a `tvly-` signal), so the
932 // generic fallback is never a Firecrawl/sentinel key.
933 context
934 .search_api_key
935 .as_deref()
936 .map(str::trim)
937 .filter(|value| !value.is_empty())
938 .map(str::to_string)
939 })
940 .ok_or_else(|| {
941 ToolError::execution_failed(
942 "Tavily search requires an API key. Set `[search] api_key = \"tvly-...\"` in config.toml or the `TAVILY_API_KEY` env var.",
943 )
944 })?;
945
946 let client = crate::platform_client_builder()
947 .timeout(Duration::from_millis(timeout_ms))
948 .build()
949 .map_err(|e| {
950 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
951 })?;
952
953 let mut payload = if let Some(plan) =
954 host_request("tavily", query, filters, max_results, context, timeout_ms).await?
955 {
956 plan.payload
957 } else {
958 tavily_search_payload(&api_key, query, filters, max_results)
959 };
960 // The credential never enters a transform snapshot or its grant.
961 payload["api_key"] = json!(api_key);
962
963 let resp = client
964 .post(TAVILY_ENDPOINT)
965 .header("Content-Type", "application/json")
966 .json(&payload)
967 .send()
968 .await
969 .map_err(|e| {
970 ToolError::execution_failed(format!("Tavily search request failed: {e}"))
971 })?;
972
973 let status = resp.status();
974 let body = if adapter::search_selected(context) {
975 adapter::read_response(resp, context).await?
976 } else {
977 resp.text().await.map_err(|e| {
978 ToolError::execution_failed(format!("Failed to read Tavily response: {e}"))
979 })?
980 };
981
982 if !status.is_success() {
983 let truncated = truncate_error_body(&body);
984 return Err((ToolError::execution_failed(format!(
985 "Tavily search failed: HTTP {} — {truncated}",
986 status.as_u16()
987 )))
988 .into());
989 }
990
991 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
992 ToolError::execution_failed(format!("Failed to parse Tavily response: {e}"))
993 })?;
994
995 if let Some(entries) = host_provider(
996 "tavily",
997 &parsed,
998 max_results,
999 Some(&api_key),
1000 context,
1001 timeout_ms,
1002 )
1003 .await?
1004 {
1005 return Ok(entries);
1006 }
1007
1008 Ok(parse_tavily_results(&parsed, max_results))
1009 }
1010
1011 /// Search Sofya; it returns extracted content and accepts `SOFYA_API_KEY`.
1012 async fn run_sofya_search(
1013 &self,
1014 query: &str,
1015 max_results: usize,
1016 timeout_ms: u64,
1017 context: &ToolContext,
1018 ) -> AdapterResult<Vec<WebSearchEntry>> {
1019 let env_key = std::env::var("SOFYA_API_KEY").ok();
1020 let api_key = context
1021 .search_api_key
1022 .as_deref()
1023 .or(env_key.as_deref())
1024 .ok_or_else(|| {
1025 ToolError::execution_failed(
1026 "Sofya search requires an API key. Set `[search] api_key = \"ay_live_...\"` in config.toml or the SOFYA_API_KEY env var.",
1027 )
1028 })?;
1029
1030 let client = crate::platform_client_builder()
1031 .timeout(Duration::from_millis(timeout_ms))
1032 .build()
1033 .map_err(|e| {
1034 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1035 })?;
1036
1037 let payload = if let Some(plan) = host_request(
1038 "sofya",
1039 query,
1040 QueryFilters::default(),
1041 max_results,
1042 context,
1043 timeout_ms,
1044 )
1045 .await?
1046 {
1047 plan.payload
1048 } else {
1049 json!({
1050 "query": query,
1051 "max_results": max_results,
1052 })
1053 };
1054
1055 let resp = client
1056 .post(SOFYA_ENDPOINT)
1057 .header("Content-Type", "application/json")
1058 .bearer_auth(api_key)
1059 .json(&payload)
1060 .send()
1061 .await
1062 .map_err(|e| {
1063 ToolError::execution_failed(format!("Sofya search request failed: {e}"))
1064 })?;
1065
1066 let status = resp.status();
1067 let body = if adapter::search_selected(context) {
1068 adapter::read_response(resp, context).await?
1069 } else {
1070 resp.text().await.map_err(|e| {
1071 ToolError::execution_failed(format!("Failed to read Sofya response: {e}"))
1072 })?
1073 };
1074
1075 if !status.is_success() {
1076 let truncated = truncate_error_body(&body);
1077 return Err((ToolError::execution_failed(format!(
1078 "Sofya search failed: HTTP {} — {truncated}",
1079 status.as_u16()
1080 )))
1081 .into());
1082 }
1083
1084 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1085 ToolError::execution_failed(format!("Failed to parse Sofya response: {e}"))
1086 })?;
1087
1088 if let Some(entries) = host_provider(
1089 "sofya",
1090 &parsed,
1091 max_results,
1092 Some(api_key),
1093 context,
1094 timeout_ms,
1095 )
1096 .await?
1097 {
1098 return Ok(entries);
1099 }
1100
1101 Ok(parse_sofya_results(&parsed, max_results))
1102 }
1103
1104 /// Search Serply (<https://serply.io>); it returns Google organic results and
1105 /// accepts `SERPLY_API_KEY`.
1106 async fn run_serply_search(
1107 &self,
1108 query: &str,
1109 filters: QueryFilters<'_>,
1110 max_results: usize,
1111 timeout_ms: u64,
1112 context: &ToolContext,
1113 ) -> AdapterResult<Vec<WebSearchEntry>> {
1114 let env_key = std::env::var("SERPLY_API_KEY").ok();
1115 let api_key = context
1116 .search_api_key
1117 .as_deref()
1118 .or(env_key.as_deref())
1119 .ok_or_else(|| {
1120 ToolError::invalid_input(
1121 "Serply search requires an API key. Set `[search] api_key` in config.toml or the SERPLY_API_KEY env var.",
1122 )
1123 })?;
1124
1125 let client = crate::platform_client_builder()
1126 .timeout(Duration::from_millis(timeout_ms))
1127 .build()
1128 .map_err(|e| {
1129 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1130 })?;
1131
1132 let url = if let Some(plan) =
1133 host_request("serply", query, filters, max_results, context, timeout_ms).await?
1134 {
1135 let mut url = reqwest::Url::parse(SERPLY_ENDPOINT)
1136 .map_err(|error| ToolError::invalid_input(error.to_string()))?;
1137 for (key, value) in plan.pairs {
1138 url.query_pairs_mut().append_pair(&key, &value);
1139 }
1140 url
1141 } else {
1142 serply_search_url(query, filters, max_results)?
1143 };
1144 let resp = client
1145 .get(url)
1146 .header("X-Api-Key", api_key)
1147 .header("Accept", "application/json")
1148 .send()
1149 .await
1150 .map_err(|e| {
1151 ToolError::execution_failed(format!("Serply search request failed: {e}"))
1152 })?;
1153
1154 let status = resp.status();
1155 let body = if adapter::search_selected(context) {
1156 adapter::read_response(resp, context).await?
1157 } else {
1158 resp.text().await.map_err(|e| {
1159 ToolError::execution_failed(format!("Failed to read Serply response: {e}"))
1160 })?
1161 };
1162
1163 if !status.is_success() {
1164 let truncated = truncate_error_body(&body);
1165 return Err((ToolError::execution_failed(format!(
1166 "Serply search failed: HTTP {}: {truncated}",
1167 status.as_u16()
1168 )))
1169 .into());
1170 }
1171
1172 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1173 ToolError::execution_failed(format!("Failed to parse Serply response: {e}"))
1174 })?;
1175
1176 if let Some(entries) = host_provider(
1177 "serply",
1178 &parsed,
1179 max_results,
1180 Some(api_key),
1181 context,
1182 timeout_ms,
1183 )
1184 .await?
1185 {
1186 return Ok(entries);
1187 }
1188
1189 Ok(parse_serply_results(&parsed, max_results))
1190 }
1191
1192 async fn run_searchapi_search(
1193 &self,
1194 query: &str,
1195 filters: QueryFilters<'_>,
1196 max_results: usize,
1197 timeout_ms: u64,
1198 context: &ToolContext,
1199 ) -> AdapterResult<Vec<WebSearchEntry>> {
1200 let api_key = context
1201 .search_api_key
1202 .as_deref()
1203 .map(str::trim)
1204 .filter(|key| !key.is_empty())
1205 .map(str::to_string)
1206 .or_else(|| {
1207 std::env::var("SEARCHAPI_API_KEY")
1208 .ok()
1209 .map(|key| key.trim().to_string())
1210 .filter(|key| !key.is_empty())
1211 })
1212 .ok_or_else(|| {
1213 ToolError::invalid_input(
1214 "SearchApi search requires an API key. Set `[search] api_key` in config.toml or the SEARCHAPI_API_KEY env var.",
1215 )
1216 })?;
1217
1218 let client = crate::platform_client_builder()
1219 .timeout(Duration::from_millis(timeout_ms))
1220 .build()
1221 .map_err(|e| {
1222 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1223 })?;
1224
1225 let url = if let Some(plan) = host_request(
1226 "searchapi",
1227 query,
1228 filters,
1229 max_results,
1230 context,
1231 timeout_ms,
1232 )
1233 .await?
1234 {
1235 let mut url = reqwest::Url::parse(SEARCHAPI_ENDPOINT)
1236 .map_err(|error| ToolError::invalid_input(error.to_string()))?;
1237 for (key, value) in plan.pairs {
1238 url.query_pairs_mut().append_pair(&key, &value);
1239 }
1240 url
1241 } else {
1242 searchapi_search_url(query, filters, max_results)?
1243 };
1244 let resp = client
1245 .get(url)
1246 .bearer_auth(&api_key)
1247 .header("Accept", "application/json")
1248 .send()
1249 .await
1250 .map_err(|e| {
1251 ToolError::execution_failed(format!("SearchApi search request failed: {e}"))
1252 })?;
1253
1254 let status = resp.status();
1255 let body = if adapter::search_selected(context) {
1256 adapter::read_response(resp, context).await?
1257 } else {
1258 resp.text().await.map_err(|e| {
1259 ToolError::execution_failed(format!("Failed to read SearchApi response: {e}"))
1260 })?
1261 };
1262
1263 if !status.is_success() {
1264 let truncated = truncate_error_body(&body);
1265 return Err((ToolError::execution_failed(format!(
1266 "SearchApi search failed: HTTP {}: {truncated}",
1267 status.as_u16()
1268 )))
1269 .into());
1270 }
1271
1272 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1273 ToolError::execution_failed(format!("Failed to parse SearchApi response: {e}"))
1274 })?;
1275
1276 if let Some(entries) = host_provider(
1277 "searchapi",
1278 &parsed,
1279 max_results,
1280 Some(api_key.as_str()),
1281 context,
1282 timeout_ms,
1283 )
1284 .await?
1285 {
1286 return Ok(entries);
1287 }
1288
1289 Ok(parse_searchapi_results(&parsed, max_results))
1290 }
1291
1292 async fn run_deepseek_search(
1293 &self,
1294 query: &str,
1295 max_results: usize,
1296 timeout_ms: u64,
1297 context: &ToolContext,
1298 ) -> AdapterResult<Vec<SearchResult>> {
1299 let api_key = deepseek_search_key(context).ok_or_else(|| {
1300 ToolError::invalid_input(
1301 "DeepSeek search requires an API key. Set `[search] api_key` in config.toml or the DEEPSEEK_API_KEY env var.",
1302 )
1303 })?;
1304 let client = crate::platform_client_builder()
1305 .timeout(Duration::from_millis(timeout_ms))
1306 .build()
1307 .map_err(|e| {
1308 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1309 })?;
1310 let count = max_results.clamp(1, 50);
1311 let payload = json!({
1312 "query": query.chars().take(128).collect::<String>(),
1313 "count": count,
1314 });
1315 let resp = client
1316 .post(DEEPSEEK_ENDPOINT)
1317 .header("Content-Type", "application/json")
1318 .bearer_auth(&api_key)
1319 .json(&payload)
1320 .send()
1321 .await
1322 .map_err(|e| {
1323 ToolError::execution_failed(format!("DeepSeek search request failed: {e}"))
1324 })?;
1325 let status = resp.status();
1326 let body = if adapter::search_selected(context) {
1327 adapter::read_response(resp, context).await?
1328 } else {
1329 resp.text().await.map_err(|e| {
1330 ToolError::execution_failed(format!("Failed to read DeepSeek response: {e}"))
1331 })?
1332 };
1333 if !status.is_success() {
1334 let message = if status.as_u16() == 402 {
1335 "DeepSeek search failed: HTTP 402 — top up your DeepSeek account to continue."
1336 .to_string()
1337 } else {
1338 let truncated = truncate_error_body(&body.replace(&api_key, "[REDACTED]"));
1339 format!(
1340 "DeepSeek search failed: HTTP {}: {truncated}",
1341 status.as_u16()
1342 )
1343 };
1344 return Err(ToolError::execution_failed(message).into());
1345 }
1346 let parsed: Value = serde_json::from_str(&body).map_err(|e| {
1347 ToolError::execution_failed(format!("Failed to parse DeepSeek response: {e}"))
1348 })?;
1349 Ok(parse_deepseek_results(&parsed, count))
1350 }
1351
1352 /// Search via Bocha AI Search API (<https://bochaai.com>).
1353 async fn run_bocha_search(
1354 &self,
1355 query: &str,
1356 max_results: usize,
1357 timeout_ms: u64,
1358 context: &ToolContext,
1359 ) -> AdapterResult<Vec<WebSearchEntry>> {
1360 let api_key = context
1361 .search_api_key
1362 .as_deref()
1363 .ok_or_else(|| {
1364 ToolError::execution_failed(
1365 "Bocha search requires an API key. Set `[search] api_key = \"sk-...\"` in config.toml.",
1366 )
1367 })?;
1368
1369 let client = crate::platform_client_builder()
1370 .timeout(Duration::from_millis(timeout_ms))
1371 .build()
1372 .map_err(|e| {
1373 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1374 })?;
1375
1376 let payload = if let Some(plan) = host_request(
1377 "bocha",
1378 query,
1379 QueryFilters::default(),
1380 max_results,
1381 context,
1382 timeout_ms,
1383 )
1384 .await?
1385 {
1386 plan.payload
1387 } else {
1388 json!({
1389 "query": query,
1390 "freshness": "noLimit",
1391 "count": max_results,
1392 })
1393 };
1394
1395 let resp = client
1396 .post(BOCHA_ENDPOINT)
1397 .header("Content-Type", "application/json")
1398 .header("Authorization", format!("Bearer {api_key}"))
1399 .json(&payload)
1400 .send()
1401 .await
1402 .map_err(|e| {
1403 ToolError::execution_failed(format!("Bocha search request failed: {e}"))
1404 })?;
1405
1406 let status = resp.status();
1407 let body = if adapter::search_selected(context) {
1408 adapter::read_response(resp, context).await?
1409 } else {
1410 resp.text().await.map_err(|e| {
1411 ToolError::execution_failed(format!("Failed to read Bocha response: {e}"))
1412 })?
1413 };
1414
1415 if !status.is_success() {
1416 let truncated = truncate_error_body(&body);
1417 return Err((ToolError::execution_failed(format!(
1418 "Bocha search failed: HTTP {} — {truncated}",
1419 status.as_u16()
1420 )))
1421 .into());
1422 }
1423
1424 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1425 ToolError::execution_failed(format!("Failed to parse Bocha response: {e}"))
1426 })?;
1427
1428 if let Some(entries) = host_provider(
1429 "bocha",
1430 &parsed,
1431 max_results,
1432 Some(api_key),
1433 context,
1434 timeout_ms,
1435 )
1436 .await?
1437 {
1438 return Ok(entries);
1439 }
1440
1441 if let Some(error) = bocha_error_message(&parsed) {
1442 return Err((ToolError::execution_failed(error)).into());
1443 }
1444
1445 Ok(parse_bocha_results(&parsed, max_results))
1446 }
1447
1448 /// Search via Metaso AI Search API (<https://metaso.cn>). Falls back to
1449 /// `METASO_API_KEY` when no config key is set.
1450 async fn run_metaso_search(
1451 &self,
1452 query: &str,
1453 max_results: usize,
1454 timeout_ms: u64,
1455 context: &ToolContext,
1456 ) -> AdapterResult<Vec<WebSearchEntry>> {
1457 let env_key = std::env::var("METASO_API_KEY").ok();
1458 let api_key = context
1459 .search_api_key
1460 .as_deref()
1461 .or(env_key.as_deref())
1462 .ok_or_else(|| {
1463 ToolError::execution_failed(
1464 "Metaso search requires an API key. Set `METASO_API_KEY` or `[search] api_key` in config.toml.",
1465 )
1466 })?;
1467
1468 let client = crate::platform_client_builder()
1469 .timeout(Duration::from_millis(timeout_ms))
1470 .build()
1471 .map_err(|e| {
1472 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1473 })?;
1474
1475 let size = max_results.clamp(1, 100);
1476 let payload = if let Some(plan) = host_request(
1477 "metaso",
1478 query,
1479 QueryFilters::default(),
1480 max_results,
1481 context,
1482 timeout_ms,
1483 )
1484 .await?
1485 {
1486 plan.payload
1487 } else {
1488 json!({
1489 "q": query,
1490 "scope": "webpage",
1491 "size": size,
1492 })
1493 };
1494
1495 let resp = client
1496 .post(format!("{METASO_ENDPOINT}/search"))
1497 .header("Content-Type", "application/json")
1498 .header("Authorization", format!("Bearer {api_key}"))
1499 .json(&payload)
1500 .send()
1501 .await
1502 .map_err(|e| {
1503 ToolError::execution_failed(format!("Metaso search request failed: {e}"))
1504 })?;
1505
1506 let status = resp.status();
1507 let body = if adapter::search_selected(context) {
1508 adapter::read_response(resp, context).await?
1509 } else {
1510 resp.text().await.map_err(|e| {
1511 ToolError::execution_failed(format!("Failed to read Metaso response: {e}"))
1512 })?
1513 };
1514
1515 if !status.is_success() {
1516 let msg = match status.as_u16() {
1517 401 | 403 => "Metaso API key rejected — check METASO_API_KEY or set `[search] api_key` in config.toml, or get one at https://metaso.cn/search-api/playground".to_string(),
1518 429 => "Metaso rate-limited — wait and retry, or get your own API key at https://metaso.cn/search-api/playground".to_string(),
1519 _ => {
1520 let truncated = truncate_error_body(&body);
1521 format!("Metaso server error (HTTP {status}) — {truncated}")
1522 }
1523 };
1524 return Err((ToolError::execution_failed(msg)).into());
1525 }
1526
1527 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1528 ToolError::execution_failed(format!("Failed to parse Metaso response: {e}"))
1529 })?;
1530
1531 if let Some(entries) =
1532 host_provider("metaso", &parsed, size, Some(api_key), context, timeout_ms).await?
1533 {
1534 return Ok(entries);
1535 }
1536
1537 // Check business-logic error codes in the response body.
1538 if let Some(code) = parsed.get("code").and_then(|v| v.as_i64())
1539 && code != 0
1540 {
1541 let msg = parsed
1542 .get("message")
1543 .and_then(|v| v.as_str())
1544 .unwrap_or("unknown error");
1545 return Err((ToolError::execution_failed(match code {
1546 3003 => "Metaso: daily search limit reached — set METASO_API_KEY or get one at https://metaso.cn/search-api/playground".to_string(),
1547 2005 => "Metaso API key rejected — check METASO_API_KEY or set `[search] api_key` in config.toml".to_string(),
1548 _ => format!("Metaso API error (code {code}: {msg})"),
1549 })).into());
1550 }
1551
1552 Ok(parse_metaso_results(&parsed, size))
1553 }
1554
1555 /// Search via Baidu AI Search API (<https://qianfan.baidubce.com>).
1556 async fn run_baidu_search(
1557 &self,
1558 query: &str,
1559 max_results: usize,
1560 timeout_ms: u64,
1561 context: &ToolContext,
1562 ) -> AdapterResult<Vec<WebSearchEntry>> {
1563 let env_key = std::env::var("BAIDU_SEARCH_API_KEY").ok();
1564 let api_key = context
1565 .search_api_key
1566 .as_deref()
1567 .or(env_key.as_deref())
1568 .ok_or_else(|| {
1569 ToolError::execution_failed(
1570 "Baidu search requires an API key. Set `BAIDU_SEARCH_API_KEY` or `[search] api_key` in config.toml.",
1571 )
1572 })?;
1573
1574 let client = crate::platform_client_builder()
1575 .timeout(Duration::from_millis(timeout_ms))
1576 .build()
1577 .map_err(|e| {
1578 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1579 })?;
1580
1581 let payload = if let Some(plan) = host_request(
1582 "baidu",
1583 query,
1584 QueryFilters::default(),
1585 max_results,
1586 context,
1587 timeout_ms,
1588 )
1589 .await?
1590 {
1591 plan.payload
1592 } else {
1593 baidu_search_payload(query, max_results)
1594 };
1595
1596 // Baidu's AI Search endpoint accepts conversational messages rather
1597 // than an index-only query. Treat the entire request/response decode
1598 // as model-backed for attached-run ownership; a false negative here
1599 // could overlap Runtime Chat, while the conservative read lease only
1600 // serializes work that already belongs to the same interactive run.
1601 let _inference = acquire_model_backed_search_inference_participant().await;
1602
1603 let resp = client
1604 .post(BAIDU_ENDPOINT)
1605 .header("Authorization", format!("Bearer {api_key}"))
1606 .json(&payload)
1607 .send()
1608 .await
1609 .map_err(|e| {
1610 ToolError::execution_failed(format!("Baidu search request failed: {e}"))
1611 })?;
1612
1613 let status = resp.status();
1614 let body = if adapter::search_selected(context) {
1615 adapter::read_response(resp, context).await?
1616 } else {
1617 resp.text().await.map_err(|e| {
1618 ToolError::execution_failed(format!("Failed to read Baidu response: {e}"))
1619 })?
1620 };
1621
1622 if !status.is_success() {
1623 let msg = match status.as_u16() {
1624 401 | 403 => "Baidu search API key rejected — check BAIDU_SEARCH_API_KEY or `[search] api_key` in config.toml".to_string(),
1625 429 => "Baidu search rate-limited — wait and retry, or check your Baidu AI Search quota".to_string(),
1626 _ => {
1627 let truncated = truncate_error_body(&body);
1628 format!("Baidu search failed: HTTP {} — {truncated}", status.as_u16())
1629 }
1630 };
1631 return Err((ToolError::execution_failed(msg)).into());
1632 }
1633
1634 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1635 ToolError::execution_failed(format!("Failed to parse Baidu response: {e}"))
1636 })?;
1637
1638 if let Some(entries) = host_provider(
1639 "baidu",
1640 &parsed,
1641 max_results,
1642 Some(api_key),
1643 context,
1644 timeout_ms,
1645 )
1646 .await?
1647 {
1648 return Ok(entries);
1649 }
1650
1651 if let Some(error) = baidu_error_message(&parsed) {
1652 return Err((ToolError::execution_failed(error)).into());
1653 }
1654
1655 Ok(parse_baidu_results(&parsed, max_results))
1656 }
1657
1658 /// Search via Volcengine Ark; it needs a 90s floor and retries transport failures.
1659 async fn run_volcengine_search(
1660 &self,
1661 query: &str,
1662 max_results: usize,
1663 timeout_ms: u64,
1664 context: &ToolContext,
1665 ) -> AdapterResult<Vec<WebSearchEntry>> {
1666 let volc_key = std::env::var("VOLCENGINE_API_KEY").ok();
1667 let volc_ark_key = std::env::var("VOLCENGINE_ARK_API_KEY").ok();
1668 let ark_key = std::env::var("ARK_API_KEY").ok();
1669 let api_key = context
1670 .search_api_key
1671 .as_deref()
1672 .or(volc_key.as_deref())
1673 .or(volc_ark_key.as_deref())
1674 .or(ark_key.as_deref())
1675 .ok_or_else(|| {
1676 ToolError::execution_failed(
1677 "Volcengine search requires an API key. Set `[search] api_key`, \
1678 or VOLCENGINE_API_KEY / VOLCENGINE_ARK_API_KEY / ARK_API_KEY env var.",
1679 )
1680 })?;
1681
1682 let effective_timeout = timeout_ms.max(90_000);
1683
1684 let client = crate::platform_client_builder()
1685 .connect_timeout(Duration::from_secs(15))
1686 .timeout(Duration::from_millis(effective_timeout))
1687 .tcp_keepalive(Some(Duration::from_secs(30)))
1688 .http2_keep_alive_interval(Some(Duration::from_secs(15)))
1689 .http2_keep_alive_timeout(Duration::from_secs(20))
1690 .user_agent(USER_AGENT)
1691 .build()
1692 .map_err(|e| {
1693 ToolError::execution_failed(format!("Failed to build HTTP client: {e}"))
1694 })?;
1695
1696 let mut payload = if let Some(plan) = host_request(
1697 "volcengine",
1698 query,
1699 QueryFilters::default(),
1700 max_results,
1701 context,
1702 timeout_ms,
1703 )
1704 .await?
1705 {
1706 plan.payload
1707 } else {
1708 volcengine_search_payload(query, max_results)
1709 };
1710 // The fixed Core route/model/tool selection is never Host authority.
1711 payload["model"] = json!("doubao-seed-2-0-lite-260428");
1712 payload["stream"] = json!(false);
1713 payload["tools"] = json!([{"type":"web_search"}]);
1714
1715 // Unlike the ordinary index-search backends, Volcengine's Responses
1716 // endpoint runs a named model and returns model-generated text. Keep
1717 // that provider lifecycle inside the attached CWC run's shared read
1718 // ownership through retries and response decoding, so an isolated
1719 // Runtime Chat turn cannot be projected alongside it.
1720 let _inference = acquire_model_backed_search_inference_participant().await;
1721
1722 let mut last_err: Option<ToolError> = None;
1723 for attempt in 0..3 {
1724 if attempt > 0 {
1725 tokio::time::sleep(Duration::from_millis(1000 * (1 << (attempt - 1)))).await;
1726 }
1727
1728 match client
1729 .post(VOLCENGINE_RESPONSES_ENDPOINT)
1730 .header("Authorization", format!("Bearer {api_key}"))
1731 .json(&payload)
1732 .send()
1733 .await
1734 {
1735 Ok(resp) => {
1736 let status = resp.status();
1737 let body = if adapter::search_selected(context) {
1738 adapter::read_response(resp, context).await?
1739 } else {
1740 resp.text().await.map_err(|e| {
1741 ToolError::execution_failed(format!(
1742 "Failed to read Volcengine response: {e}"
1743 ))
1744 })?
1745 };
1746
1747 if !status.is_success() {
1748 let msg = match status.as_u16() {
1749 401 | 403 => "Volcengine API key rejected — check `[search] api_key` in config.toml or VOLCENGINE_API_KEY / VOLCENGINE_ARK_API_KEY / ARK_API_KEY".to_string(),
1750 429 => "Volcengine API rate-limited — wait and retry, or check your quota".to_string(),
1751 _ => {
1752 let truncated = truncate_error_body(&body);
1753 format!("Volcengine search failed: HTTP {} — {truncated}", status.as_u16())
1754 }
1755 };
1756 return Err((ToolError::execution_failed(msg)).into());
1757 }
1758
1759 let parsed: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
1760 ToolError::execution_failed(format!(
1761 "Failed to parse Volcengine response: {e}"
1762 ))
1763 })?;
1764
1765 if let Some(entries) = host_provider(
1766 "volcengine",
1767 &parsed,
1768 max_results,
1769 Some(api_key),
1770 context,
1771 timeout_ms,
1772 )
1773 .await?
1774 {
1775 return Ok(entries);
1776 }
1777
1778 if let Some(error) = volcengine_error_message(&parsed) {
1779 return Err((ToolError::execution_failed(error)).into());
1780 }
1781
1782 let response_text = volcengine_extract_text(&parsed).ok_or_else(|| {
1783 ToolError::execution_failed("Volcengine response contains no output text")
1784 })?;
1785
1786 return Ok(parse_volcengine_results(&response_text, max_results));
1787 }
1788 Err(e) => {
1789 let is_transient = e.is_timeout() || e.is_connect();
1790 if !is_transient || attempt == 2 {
1791 return Err((ToolError::execution_failed(format!(
1792 "Volcengine search request failed: {e}"
1793 )))
1794 .into());
1795 }
1796 last_err = Some(ToolError::execution_failed(format!(
1797 "Volcengine search request failed (attempt {}/3): {e}",
1798 attempt + 1
1799 )));
1800 }
1801 }
1802 }
1803
1804 // Unreachable — the final iteration always returns above.
1805 Err(last_err
1806 .unwrap_or_else(|| {
1807 ToolError::execution_failed("Volcengine search: unexpected retry exit")
1808 })
1809 .into())
1810 }
1811 }
1812
1813 pub async fn execute_search(
1814 query: SearchQuery,
1815 timeout_ms: u64,
1816 context: &ToolContext,
1817 ) -> Result<SearchResponse, ToolError> {
1818 if configured_search_base_url(context.search_base_url.as_deref()).is_some()
1819 && !matches!(
1820 context.search_provider,
1821 SearchProvider::DuckDuckGo | SearchProvider::Searxng
1822 )
1823 {
1824 return Err(ToolError::invalid_input(format!(
1825 "[search].base_url is only supported with provider = \"duckduckgo\" or \"searxng\"; current provider is \"{}\"",
1826 context.search_provider.as_str()
1827 )));
1828 }
1829
1830 let chain = SearchBackendChain::from_context(context);
1831 let Some(initial_backend) = chain.initial_backend() else {
1832 return Err(ToolError::permission_denied(
1833 super::web::consent::search_refusal(context)
1834 .unwrap_or(super::web::consent::WITHHELD_MESSAGE),
1835 ));
1836 };
1837 if initial_backend != BackendId::ProviderNative {
1838 debug_assert_eq!(initial_backend.as_str(), context.search_provider.as_str());
1839 preflight_search_provider(context)?;
1840 }
1841 let cache_scope = if initial_backend == BackendId::ProviderNative {
1842 context
1843 .provider_native_search
1844 .as_ref()
1845 .map(crate::client::ProviderNativeSearchClient::cache_identity)
1846 } else {
1847 normalized_search_base_url(context.search_base_url.as_deref())
1848 };
1849
1850 if let Some(mut cached) = cache::get_search(
1851 &context.state_namespace,
1852 initial_backend,
1853 cache_scope.as_deref(),
1854 &query,
1855 ) {
1856 validate_cached_search_policy(&cached, context)?;
1857 register_search_citations(&mut cached, context);
1858 cached.receipt.cache_hit = true;
1859 cached.receipt.latency_ms = 0;
1860 return Ok(cached);
1861 }
1862
1863 let started = Instant::now();
1864 let requested_timeout = Duration::from_millis(timeout_ms.max(1));
1865 let provider_native_timeout_floor = context
1866 .provider_native_search
1867 .as_ref()
1868 .and_then(provider_native_timeout_floor);
1869 let (total_timeout, first_attempt_budget, fallback_budget_after_first) = search_timeout_budgets(
1870 initial_backend,
1871 requested_timeout,
1872 provider_native_timeout_floor,
1873 );
1874 let deadline = started + total_timeout;
1875 let chained = chain
1876 .search(
1877 &query,
1878 deadline,
1879 first_attempt_budget,
1880 fallback_budget_after_first,
1881 )
1882 .await?;
1883 let mut response = finalize_search_response_for_context(
1884 query.clone(),
1885 chained.capabilities,
1886 chained.raw,
1887 started,
1888 context,
1889 deadline.saturating_duration_since(Instant::now()),
1890 )
1891 .await?;
1892 register_search_citations(&mut response, context);
1893 cache::insert_search(
1894 &context.state_namespace,
1895 initial_backend,
1896 cache_scope.as_deref(),
1897 &query,
1898 response.clone(),
1899 );
1900 Ok(response)
1901 }
1902
1903 fn search_timeout_budgets(
1904 initial_backend: BackendId,
1905 requested_timeout: Duration,
1906 provider_native_timeout_floor: Option<Duration>,
1907 ) -> (Duration, Option<Duration>, Option<Duration>) {
1908 match initial_backend {
1909 BackendId::Volcengine => {
1910 let provider_budget = Duration::from_millis(VOLCENGINE_MIN_TIMEOUT_MS);
1911 (
1912 provider_budget + requested_timeout,
1913 Some(provider_budget),
1914 None,
1915 )
1916 }
1917 BackendId::ProviderNative => {
1918 // Provider-native search performs a model-backed request. Give it
1919 // a dedicated minimum without donating unused time to the
1920 // configured/local fallback selected by the caller.
1921 let provider_budget = requested_timeout
1922 .max(Duration::from_millis(PROVIDER_NATIVE_MIN_TIMEOUT_MS))
1923 .max(provider_native_timeout_floor.unwrap_or_default());
1924 (
1925 provider_budget.saturating_add(requested_timeout),
1926 Some(provider_budget),
1927 Some(requested_timeout),
1928 )
1929 }
1930 _ => (requested_timeout, None, None),
1931 }
1932 }
1933
1934 fn provider_native_timeout_floor(
1935 client: &crate::client::ProviderNativeSearchClient,
1936 ) -> Option<Duration> {
1937 let k3_formula = codewhale_runtime::config::is_exact_direct_moonshot_k3_route(
1938 client.provider(),
1939 client.base_url(),
1940 client.model(),
1941 )
1942 .then_some(Duration::from_millis(KIMI_K3_FORMULA_MIN_TIMEOUT_MS));
1943 let answer = client
1944 .requested_answer_output_tokens()
1945 .map(native_answer_time_budget);
1946 k3_formula.max(answer)
1947 }
1948
1949 /// Time a native-search attempt needs to return an answer of `output_tokens`
1950 /// whole: the search round-trips plus generation at a conservative rate
1951 /// (#6508). Without it, raising the requested answer length only moved the
1952 /// cut from the provider's token limit to this tool's timeout.
1953 fn native_answer_time_budget(output_tokens: u32) -> Duration {
1954 let generation_ms =
1955 u64::from(output_tokens).saturating_mul(1_000) / NATIVE_SEARCH_ASSUMED_TOKENS_PER_SEC;
1956 Duration::from_millis(NATIVE_SEARCH_ROUND_TRIP_ALLOWANCE_MS.saturating_add(generation_ms))
1957 }
1958
1959 fn register_search_citations(response: &mut SearchResponse, context: &ToolContext) {
1960 let mut seen = std::collections::HashSet::new();
1961 response.results.retain_mut(|result| {
1962 let Some(citation) = super::web::citations::register(
1963 &context.state_namespace,
1964 &result.url,
1965 Some(&result.title),
1966 ) else {
1967 return false;
1968 };
1969 result.ref_id = citation.ref_id;
1970 result.url = citation.url;
1971 seen.insert(result.ref_id.clone())
1972 });
1973 if response.count != response.results.len() {
1974 rerank(&mut response.results);
1975 response.count = response.results.len();
1976 response.message = if response.count == 0 {
1977 "No usable web citations found".to_string()
1978 } else {
1979 format!("Found {} result(s)", response.count)
1980 };
1981 note_provider_native(
1982 &mut response.message,
1983 response.receipt.backend,
1984 response.count,
1985 unchecked_citations(&response.receipt.degraded),
1986 response.receipt.requested.max_results,
1987 response.unverified_synthesis.is_some(),
1988 );
1989 }
1990 }
1991
1992 fn deepseek_search_key(context: &ToolContext) -> Option<String> {
1993 context
1994 .search_api_key
1995 .as_deref()
1996 .map(str::trim)
1997 .filter(|key| !key.is_empty())
1998 .map(str::to_string)
1999 .or_else(|| {
2000 std::env::var("DEEPSEEK_API_KEY")
2001 .ok()
2002 .map(|key| key.trim().to_string())
2003 .filter(|key| !key.is_empty())
2004 })
2005 }
2006
2007 /// Reject misconfiguration before cache lookup or network access.
2008 fn preflight_search_provider(context: &ToolContext) -> Result<(), ToolError> {
2009 let configured_key = context
2010 .search_api_key
2011 .as_deref()
2012 .is_some_and(|key| !key.trim().is_empty());
2013 let env_key = |name: &str| std::env::var_os(name).is_some_and(|value| !value.is_empty());
2014 let not_configured = |message: &str| Err(ToolError::invalid_input(message));
2015
2016 match context.search_provider {
2017 SearchProvider::Tavily if !configured_key && tavily_env_key().is_none() => not_configured(
2018 "Tavily search is not configured: it requires an API key. Set `[search] api_key = \"tvly-...\"` in config.toml or the `TAVILY_API_KEY` env var.",
2019 ),
2020 SearchProvider::Bocha if !configured_key => not_configured(
2021 "Bocha search is not configured: it requires an API key. Set `[search] api_key = \"sk-...\"` in config.toml.",
2022 ),
2023 SearchProvider::Metaso if !configured_key && !env_key("METASO_API_KEY") => not_configured(
2024 "Metaso search is not configured: it requires an API key. Set `METASO_API_KEY` or `[search] api_key` in config.toml.",
2025 ),
2026 SearchProvider::Baidu if !configured_key && !env_key("BAIDU_SEARCH_API_KEY") => {
2027 not_configured(
2028 "Baidu search is not configured: it requires an API key. Set `BAIDU_SEARCH_API_KEY` or `[search] api_key` in config.toml.",
2029 )
2030 }
2031 SearchProvider::Volcengine
2032 if !configured_key
2033 && !env_key("VOLCENGINE_API_KEY")
2034 && !env_key("VOLCENGINE_ARK_API_KEY")
2035 && !env_key("ARK_API_KEY") =>
2036 {
2037 not_configured(
2038 "Volcengine search is not configured: it requires an API key. Set `[search] api_key`, or VOLCENGINE_API_KEY / VOLCENGINE_ARK_API_KEY / ARK_API_KEY env var.",
2039 )
2040 }
2041 SearchProvider::Sofya if !configured_key && !env_key("SOFYA_API_KEY") => not_configured(
2042 "Sofya search is not configured: it requires an API key. Set `[search] api_key = \"ay_live_...\"` in config.toml or the SOFYA_API_KEY env var.",
2043 ),
2044 SearchProvider::Serply if !configured_key && !env_key("SERPLY_API_KEY") => not_configured(
2045 "Serply search is not configured: it requires an API key. Set `[search] api_key` in config.toml or the SERPLY_API_KEY env var.",
2046 ),
2047 SearchProvider::SearchApi if !configured_key && !env_key("SEARCHAPI_API_KEY") => {
2048 not_configured(
2049 "SearchApi search is not configured: it requires an API key. Set `[search] api_key` in config.toml or the SEARCHAPI_API_KEY env var.",
2050 )
2051 }
2052 SearchProvider::DeepSeek if deepseek_search_key(context).is_none() => not_configured(
2053 "DeepSeek search is not configured: it requires an API key. Set `[search] api_key` in config.toml or the DEEPSEEK_API_KEY env var.",
2054 ),
2055 SearchProvider::Searxng
2056 if configured_search_base_url(context.search_base_url.as_deref()).is_none() =>
2057 {
2058 not_configured(
2059 "SearXNG search requires [search] base_url = \"https://your-searxng.example\"; no public instance is used by default.",
2060 )
2061 }
2062 _ => Ok(()),
2063 }
2064 }
2065
2066 fn normalized_search_base_url(base_url: Option<&str>) -> Option<String> {
2067 let raw = configured_search_base_url(base_url)?;
2068 let Ok(mut url) = reqwest::Url::parse(raw) else {
2069 return Some(raw.to_string());
2070 };
2071 url.set_fragment(None);
2072 Some(url.to_string())
2073 }
2074
2075 fn validate_cached_search_policy(
2076 response: &SearchResponse,
2077 context: &ToolContext,
2078 ) -> Result<(), ToolError> {
2079 let host = response
2080 .receipt
2081 .backend_detail
2082 .as_deref()
2083 .or_else(|| default_backend_host(response.receipt.backend))
2084 .ok_or_else(|| {
2085 ToolError::execution_failed("cached search receipt did not identify its backend host")
2086 })?;
2087 check_policy(context.network_policy.as_ref(), host)
2088 }
2089
2090 const fn default_backend_host(backend: BackendId) -> Option<&'static str> {
2091 match backend {
2092 BackendId::ProviderNative => None,
2093 BackendId::Bing => Some(BING_HOST),
2094 BackendId::DuckDuckGo => Some("html.duckduckgo.com"),
2095 BackendId::Firecrawl => Some("api.firecrawl.dev"),
2096 BackendId::Tavily => Some("api.tavily.com"),
2097 BackendId::Bocha => Some("api.bochaai.com"),
2098 BackendId::Metaso => Some("metaso.cn"),
2099 BackendId::Searxng => None,
2100 BackendId::Baidu => Some("qianfan.baidubce.com"),
2101 BackendId::Volcengine => Some("ark.cn-beijing.volces.com"),
2102 BackendId::Sofya => Some("sofya.co"),
2103 BackendId::Serply => Some("api.serply.io"),
2104 BackendId::DeepSeek => Some("api.deepseek.com"),
2105 BackendId::SearchApi => Some("www.searchapi.io"),
2106 }
2107 }
2108
2109 async fn finalize_search_response_for_context(
2110 query: SearchQuery,
2111 capabilities: super::web::contract::QueryCapabilities,
2112 mut raw: BackendSearch,
2113 started: Instant,
2114 context: &ToolContext,
2115 budget: Duration,
2116 ) -> AdapterResult<SearchResponse> {
2117 if !adapter::search_selected(context) {
2118 return Ok(finalize_search_response(query, capabilities, raw, started));
2119 }
2120 #[derive(serde::Deserialize)]
2121 #[serde(deny_unknown_fields)]
2122 struct Proposal {
2123 kind: String,
2124 honored: HonoredQueryCapabilities,
2125 degraded: Vec<DegradedReason>,
2126 prefix: String,
2127 suffix: String,
2128 }
2129 let initial = raw.degraded.clone();
2130 apply_domain_constraints(&query, capabilities, &mut raw);
2131 let domain_extra = raw
2132 .degraded
2133 .iter()
2134 .filter(|reason| !initial.contains(reason))
2135 .cloned()
2136 .collect::<Vec<_>>();
2137 let requested_max = usize::from(query.max_results);
2138 raw.results.truncate(requested_max);
2139 rerank(&mut raw.results);
2140 let synthesis = take_provider_native_synthesis(&mut raw);
2141 let (unverified, initial): (Vec<_>, Vec<_>) = initial.into_iter().partition(|reason| {
2142 matches!(
2143 reason,
2144 DegradedReason::CitationUnverified { .. } | DegradedReason::CitationUnchecked { .. }
2145 )
2146 });
2147 let unchecked = unverified
2148 .iter()
2149 .filter(|reason| matches!(reason, DegradedReason::CitationUnchecked { .. }))
2150 .count();
2151 let proposal:Proposal=adapter::transform(crate::extension_host::StockOperation::WebFinalize,
2152 json!({"requested":{"recency":query.recency.is_some(),"domains":!query.domains.is_empty(),"locale":query.locale.is_some()},
2153 "capabilities":capabilities,"count":raw.results.len(),"degraded":initial,"domain_extra":domain_extra,"has_note":raw.note.is_some()}),context,budget).await?;
2154 let known = |reason: &DegradedReason| {
2155 initial.contains(reason)
2156 || domain_extra.contains(reason)
2157 || matches!(
2158 reason,
2159 DegradedReason::KnobIgnored {
2160 knob: QueryKnob::Recency | QueryKnob::Locale
2161 }
2162 )
2163 };
2164 if proposal.kind != "web_finalize"
2165 || proposal.prefix.len() > 128
2166 || proposal.suffix.len() > 128
2167 || !proposal.degraded.iter().all(known)
2168 || !initial
2169 .iter()
2170 .chain(&domain_extra)
2171 .all(|reason| proposal.degraded.contains(reason))
2172 || proposal.honored.domains != !query.domains.is_empty()
2173 || (proposal.honored.recency
2174 && (!query.recency.is_some()
2175 || !matches!(
2176 capabilities.recency,
2177 super::web::contract::CapabilityState::Supported
2178 )))
2179 || (proposal.honored.locale
2180 && (!query.locale.is_some()
2181 || !matches!(
2182 capabilities.locale,
2183 super::web::contract::CapabilityState::Supported
2184 )))
2185 {
2186 return Err(AdapterFailure::host(ToolError::execution_failed(
2187 "Web Host returned an inconsistent final receipt",
2188 )));
2189 }
2190 let count = raw.results.len();
2191 // The host is not told the requested cap, so it can only speak to
2192 // capability. Core owns the fulfillment half: a backend that returned
2193 // fewer results than asked did not honor the knob, whatever it claimed.
2194 let honored = HonoredQueryCapabilities {
2195 max_results: proposal.honored.max_results && count >= requested_max,
2196 ..proposal.honored
2197 };
2198 let mut message = format!(
2199 "{}{}{}",
2200 proposal.prefix,
2201 raw.note.as_deref().unwrap_or_default(),
2202 proposal.suffix
2203 );
2204 note_provider_native(
2205 &mut message,
2206 raw.backend,
2207 count,
2208 unchecked,
2209 query.max_results,
2210 synthesis.is_some(),
2211 );
2212 Ok(SearchResponse {
2213 query: query.query.clone(),
2214 source: raw.source,
2215 count,
2216 message,
2217 results: raw.results,
2218 unverified_synthesis: synthesis,
2219 receipt: SearchReceipt {
2220 backend: raw.backend,
2221 backend_detail: raw.backend_detail,
2222 requested: query,
2223 capabilities,
2224 honored,
2225 degraded: proposal.degraded.into_iter().chain(unverified).collect(),
2226 latency_ms: u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX),
2227 cache_hit: false,
2228 },
2229 })
2230 }
2231
2232 fn finalize_search_response(
2233 query: SearchQuery,
2234 capabilities: super::web::contract::QueryCapabilities,
2235 mut raw: BackendSearch,
2236 started: Instant,
2237 ) -> SearchResponse {
2238 let mut honored = HonoredQueryCapabilities {
2239 max_results: matches!(
2240 capabilities.max_results,
2241 super::web::contract::CapabilityState::Supported
2242 ),
2243 ..HonoredQueryCapabilities::default()
2244 };
2245
2246 let adapter_ignored = |raw: &BackendSearch, knob: QueryKnob| {
2247 raw.degraded.contains(&DegradedReason::KnobIgnored { knob })
2248 };
2249 if query.recency.is_some() && !adapter_ignored(&raw, QueryKnob::Recency) {
2250 if matches!(
2251 capabilities.recency,
2252 super::web::contract::CapabilityState::Supported
2253 ) {
2254 honored.recency = true;
2255 } else {
2256 raw.degraded.push(DegradedReason::KnobIgnored {
2257 knob: QueryKnob::Recency,
2258 });
2259 }
2260 }
2261 if !query.domains.is_empty() {
2262 // The backend chain applies this before deciding whether an attempt
2263 // produced usable results. Keep finalization defensive for cached or
2264 // directly constructed responses; the helper is idempotent.
2265 apply_domain_constraints(&query, capabilities, &mut raw);
2266 honored.domains = true;
2267 }
2268 if query.locale.is_some() && !adapter_ignored(&raw, QueryKnob::Locale) {
2269 if matches!(
2270 capabilities.locale,
2271 super::web::contract::CapabilityState::Supported
2272 ) {
2273 honored.locale = true;
2274 } else {
2275 raw.degraded.push(DegradedReason::KnobIgnored {
2276 knob: QueryKnob::Locale,
2277 });
2278 }
2279 }
2280
2281 raw.results.truncate(usize::from(query.max_results));
2282 rerank(&mut raw.results);
2283 honored.max_results =
2284 honored.max_results && raw.results.len() >= usize::from(query.max_results);
2285 let synthesis = take_provider_native_synthesis(&mut raw);
2286 let latency_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
2287 let receipt = SearchReceipt {
2288 backend: raw.backend,
2289 backend_detail: raw.backend_detail,
2290 requested: query.clone(),
2291 capabilities,
2292 honored,
2293 degraded: raw.degraded,
2294 latency_ms,
2295 cache_hit: false,
2296 };
2297 let count = raw.results.len();
2298 let mut message = match (count, raw.note.as_deref()) {
2299 (0, Some(note)) => format!("No results found. {note}"),
2300 (0, None) => "No results found".to_string(),
2301 (_, Some(note)) => format!("Found {count} result(s). {note}"),
2302 (_, None) => format!("Found {count} result(s)"),
2303 };
2304 // The answer sits in `unverified_synthesis`; the message still says when
2305 // the provider cut it short (#6508).
2306 if let Some(cut) = receipt
2307 .degraded
2308 .iter()
2309 .find(|reason| matches!(reason, DegradedReason::AnswerCutByProvider))
2310 {
2311 message.push_str(&format!("\n[{}]", cut.message()));
2312 }
2313 note_provider_native(
2314 &mut message,
2315 receipt.backend,
2316 count,
2317 unchecked_citations(&receipt.degraded),
2318 receipt.requested.max_results,
2319 synthesis.is_some(),
2320 );
2321
2322 SearchResponse {
2323 query: query.query,
2324 source: raw.source,
2325 count,
2326 message,
2327 results: raw.results,
2328 unverified_synthesis: synthesis,
2329 receipt,
2330 }
2331 }
2332
2333 fn take_provider_native_synthesis(raw: &mut BackendSearch) -> Option<String> {
2334 if raw.backend == BackendId::ProviderNative {
2335 raw.note.take()
2336 } else {
2337 None
2338 }
2339 }
2340
2341 fn unchecked_citations(degraded: &[DegradedReason]) -> usize {
2342 degraded
2343 .iter()
2344 .filter(|reason| matches!(reason, DegradedReason::CitationUnchecked { .. }))
2345 .count()
2346 }
2347
2348 fn note_provider_native(
2349 message: &mut String,
2350 backend: BackendId,
2351 count: usize,
2352 unchecked: usize,
2353 requested: u8,
2354 synthesis: bool,
2355 ) {
2356 if backend != BackendId::ProviderNative {
2357 return;
2358 }
2359 if unchecked == 0 {
2360 message.push_str(&format!(
2361 "\n[provider-native search: {count} of {requested} requested source(s) passed link verification and appear in `results`; cite only those, by ref_id"
2362 ));
2363 } else {
2364 let verified = count.saturating_sub(unchecked);
2365 message.push_str(&format!(
2366 "\n[provider-native search: {count} of {requested} requested source(s) appear in `results`; {verified} passed link verification and {unchecked} were not checked because the [network] policy needs approval for their hosts; cite only those, by ref_id"
2367 ));
2368 }
2369 if synthesis {
2370 message.push_str(
2371 ". `unverified_synthesis` is the provider model's own summary: its claims and links were not checked and may name pages missing from `results`",
2372 );
2373 }
2374 message.push(']');
2375 }
2376
2377 pub fn apply_domain_constraints(
2378 query: &SearchQuery,
2379 capabilities: super::web::contract::QueryCapabilities,
2380 raw: &mut BackendSearch,
2381 ) {
2382 if query.domains.is_empty() {
2383 return;
2384 }
2385
2386 let before = raw.results.len();
2387 raw.results
2388 .retain(|result| domain_matches(&result.url, &query.domains));
2389 rerank(&mut raw.results);
2390 let provider_honored = matches!(
2391 capabilities.domains,
2392 super::web::contract::CapabilityState::Supported
2393 );
2394 let filtered_any = raw.results.len() != before;
2395 if raw.backend == BackendId::ProviderNative && (!provider_honored || filtered_any) {
2396 // Post-filtering constrains returned citations but cannot prove that a
2397 // provider-generated answer did not rely on a removed source.
2398 raw.note = None;
2399 }
2400 let already_recorded = raw.degraded.iter().any(|reason| {
2401 matches!(
2402 reason,
2403 DegradedReason::PostFiltered {
2404 knob: QueryKnob::Domains
2405 }
2406 )
2407 });
2408 if (!provider_honored || filtered_any) && !already_recorded {
2409 raw.degraded.push(DegradedReason::PostFiltered {
2410 knob: QueryKnob::Domains,
2411 });
2412 }
2413 }
2414
2415 pub async fn run_backend_search(
2416 provider: SearchProvider,
2417 query: &SearchQuery,
2418 deadline: Instant,
2419 context: &ToolContext,
2420 ) -> AdapterResult<BackendSearch> {
2421 let timeout_ms = u64::try_from(
2422 deadline
2423 .saturating_duration_since(Instant::now())
2424 .as_millis()
2425 .max(1),
2426 )
2427 .unwrap_or(u64::MAX);
2428 let max_results = usize::from(query.max_results);
2429 let prepared = if adapter::search_selected(context) {
2430 let value: PreparedFilters = adapter::transform(
2431 crate::extension_host::StockOperation::WebFilters,
2432 json!({"recency_days":query.recency.map(Recency::days),"locale":query.locale}),
2433 context,
2434 Duration::from_millis(timeout_ms),
2435 )
2436 .await?;
2437 if value.kind != "web_filters"
2438 || value
2439 .window
2440 .as_deref()
2441 .is_some_and(|value| !matches!(value, "day" | "week" | "month" | "year"))
2442 || value.language.as_deref().is_some_and(|value| {
2443 !matches!(value.len(), 2 | 3) || !value.chars().all(|c| c.is_ascii_lowercase())
2444 })
2445 || value.region.as_deref().is_some_and(|value| {
2446 value.len() != 2 || !value.chars().all(|c| c.is_ascii_uppercase())
2447 })
2448 {
2449 return Err(AdapterFailure::host(ToolError::execution_failed(
2450 "Web Host returned malformed filters",
2451 )));
2452 }
2453 Some(value)
2454 } else {
2455 None
2456 };
2457 let mut filters = QueryFilters::of(query);
2458 filters.prepared = prepared.as_ref();
2459 let tool = WebSearchTool;
2460 let simple = |backend, entries: Vec<WebSearchEntry>| BackendSearch {
2461 backend,
2462 source: backend.as_str().to_string(),
2463 backend_detail: None,
2464 results: normalize_entries(entries),
2465 degraded: Vec::new(),
2466 note: None,
2467 };
2468
2469 match provider {
2470 SearchProvider::Firecrawl => {
2471 check_policy(context.network_policy.as_ref(), "api.firecrawl.dev")?;
2472 let (results, note) = tool
2473 .run_firecrawl_search(&query.query, filters, max_results, timeout_ms, context)
2474 .await?;
2475 // Firecrawl targets a country, not a language: a bare `en` has
2476 // nothing to send and is reported as ignored.
2477 let degraded = (filters.locale.is_some() && filters.region().is_none())
2478 .then_some(DegradedReason::KnobIgnored {
2479 knob: QueryKnob::Locale,
2480 })
2481 .into_iter()
2482 .collect();
2483 Ok(BackendSearch {
2484 backend: BackendId::Firecrawl,
2485 source: "firecrawl".to_string(),
2486 backend_detail: Some("api.firecrawl.dev".to_string()),
2487 results: normalize_entries(results),
2488 degraded,
2489 note: Some(note),
2490 })
2491 }
2492 SearchProvider::Tavily => {
2493 check_policy(context.network_policy.as_ref(), "api.tavily.com")?;
2494 Ok(simple(
2495 BackendId::Tavily,
2496 tool.run_tavily_search(&query.query, filters, max_results, timeout_ms, context)
2497 .await?,
2498 ))
2499 }
2500 SearchProvider::Bocha => {
2501 check_policy(context.network_policy.as_ref(), "api.bochaai.com")?;
2502 Ok(simple(
2503 BackendId::Bocha,
2504 tool.run_bocha_search(&query.query, max_results, timeout_ms, context)
2505 .await?,
2506 ))
2507 }
2508 SearchProvider::Metaso => {
2509 check_policy(context.network_policy.as_ref(), "metaso.cn")?;
2510 Ok(simple(
2511 BackendId::Metaso,
2512 tool.run_metaso_search(&query.query, max_results, timeout_ms, context)
2513 .await?,
2514 ))
2515 }
2516 SearchProvider::Searxng => {
2517 let (entries, host) = tool
2518 .run_searxng_search(&query.query, filters, max_results, timeout_ms, context)
2519 .await?;
2520 let note = format!("Backend: searxng at {host}");
2521 Ok(BackendSearch {
2522 backend: BackendId::Searxng,
2523 source: "searxng".to_string(),
2524 backend_detail: Some(host),
2525 results: normalize_entries(entries),
2526 degraded: Vec::new(),
2527 note: Some(note),
2528 })
2529 }
2530 SearchProvider::Baidu => {
2531 check_policy(context.network_policy.as_ref(), "qianfan.baidubce.com")?;
2532 Ok(simple(
2533 BackendId::Baidu,
2534 tool.run_baidu_search(&query.query, max_results, timeout_ms, context)
2535 .await?,
2536 ))
2537 }
2538 SearchProvider::Volcengine => {
2539 check_policy(context.network_policy.as_ref(), "ark.cn-beijing.volces.com")?;
2540 let mut response = simple(
2541 BackendId::Volcengine,
2542 tool.run_volcengine_search(&query.query, max_results, timeout_ms, context)
2543 .await?,
2544 );
2545 response.degraded.push(DegradedReason::SynthesizedResults);
2546 Ok(response)
2547 }
2548 SearchProvider::Sofya => {
2549 check_policy(context.network_policy.as_ref(), "sofya.co")?;
2550 Ok(simple(
2551 BackendId::Sofya,
2552 tool.run_sofya_search(&query.query, max_results, timeout_ms, context)
2553 .await?,
2554 ))
2555 }
2556 SearchProvider::Serply => {
2557 check_policy(context.network_policy.as_ref(), "api.serply.io")?;
2558 Ok(simple(
2559 BackendId::Serply,
2560 tool.run_serply_search(&query.query, filters, max_results, timeout_ms, context)
2561 .await?,
2562 ))
2563 }
2564 SearchProvider::SearchApi => {
2565 check_policy(context.network_policy.as_ref(), "www.searchapi.io")?;
2566 Ok(simple(
2567 BackendId::SearchApi,
2568 tool.run_searchapi_search(&query.query, filters, max_results, timeout_ms, context)
2569 .await?,
2570 ))
2571 }
2572 SearchProvider::DeepSeek => {
2573 check_policy(context.network_policy.as_ref(), "api.deepseek.com")?;
2574 Ok(BackendSearch {
2575 backend: BackendId::DeepSeek,
2576 source: "deepseek".to_string(),
2577 backend_detail: None,
2578 results: tool
2579 .run_deepseek_search(&query.query, max_results, timeout_ms, context)
2580 .await?,
2581 degraded: Vec::new(),
2582 note: None,
2583 })
2584 }
2585 SearchProvider::Bing | SearchProvider::DuckDuckGo => {
2586 run_scrape_search(provider, query, timeout_ms, context).await
2587 }
2588 }
2589 }
2590
2591 /// Share of the search budget a DuckDuckGo request may use when Bing is allowed
2592 /// to answer after it (#6746).
2593 const DUCKDUCKGO_BUDGET_SHARE: f64 = 0.6;
2594
2595 #[derive(Clone, Copy)]
2596 struct ScrapeEndpoints<'a> {
2597 bing: &'a str,
2598 allow_bing_fallback: Option<bool>,
2599 }
2600
2601 impl Default for ScrapeEndpoints<'static> {
2602 fn default() -> Self {
2603 Self {
2604 bing: BING_ENDPOINT,
2605 allow_bing_fallback: None,
2606 }
2607 }
2608 }
2609
2610 async fn run_scrape_search(
2611 provider: SearchProvider,
2612 query: &SearchQuery,
2613 timeout_ms: u64,
2614 context: &ToolContext,
2615 ) -> AdapterResult<BackendSearch> {
2616 let fallback_context = (provider == SearchProvider::DuckDuckGo
2617 && context.search_provider != SearchProvider::DuckDuckGo)
2618 .then(|| {
2619 let mut cloned = context.clone();
2620 cloned.search_base_url = None;
2621 cloned
2622 });
2623 let context = fallback_context.as_ref().unwrap_or(context);
2624 run_scrape_search_with_endpoints(
2625 provider,
2626 query,
2627 timeout_ms,
2628 context,
2629 ScrapeEndpoints::default(),
2630 )
2631 .await
2632 }
2633
2634 async fn run_scrape_search_with_endpoints(
2635 provider: SearchProvider,
2636 query: &SearchQuery,
2637 timeout_ms: u64,
2638 context: &ToolContext,
2639 endpoints: ScrapeEndpoints<'_>,
2640 ) -> AdapterResult<BackendSearch> {
2641 let started = Instant::now();
2642 let budget = Duration::from_millis(timeout_ms);
2643 let decider = context.network_policy.as_ref();
2644 let client = crate::platform_client_builder()
2645 .timeout(budget)
2646 .user_agent(USER_AGENT)
2647 .build()
2648 .map_err(|error| {
2649 ToolError::execution_failed(format!("Failed to build HTTP client: {error}"))
2650 })?;
2651 let max_results = usize::from(query.max_results);
2652 let mut degraded = Vec::new();
2653
2654 if provider == SearchProvider::Bing {
2655 check_policy(decider, BING_HOST)?;
2656 if bing_locale_was_ignored(query.locale.as_deref()) {
2657 degraded.push(DegradedReason::KnobIgnored {
2658 knob: QueryKnob::Locale,
2659 });
2660 }
2661 let results = run_bing_search(
2662 &client,
2663 &query.query,
2664 query.locale.as_deref(),
2665 max_results,
2666 endpoints.bing,
2667 budget,
2668 context,
2669 )
2670 .await?;
2671 return Ok(BackendSearch {
2672 backend: BackendId::Bing,
2673 source: "bing".to_string(),
2674 backend_detail: None,
2675 results: normalize_entries(results),
2676 degraded,
2677 note: None,
2678 });
2679 }
2680
2681 let market = scrape_market(query.locale.as_deref(), &query.query);
2682 if ddg_locale_was_ignored(query.locale.as_deref(), market.as_deref()) {
2683 degraded.push(DegradedReason::KnobIgnored {
2684 knob: QueryKnob::Locale,
2685 });
2686 }
2687 let accept_language = scrape_accept_language(market.as_deref());
2688 let (url, duckduckgo_host) = if let Some(plan) = host_request(
2689 "duckduckgo",
2690 &query.query,
2691 QueryFilters::default(),
2692 max_results,
2693 context,
2694 timeout_ms,
2695 )
2696 .await?
2697 {
2698 let (mut url, host) = duckduckgo_search_base(context.search_base_url.as_deref())?;
2699 {
2700 let mut pairs = url.query_pairs_mut();
2701 for (key, value) in plan.pairs {
2702 pairs.append_pair(&key, &value);
2703 }
2704 // The scrape chain hands the host adapter default filters, so the
2705 // plan never carries the locale; the verified `kl` region pair
2706 // (see [`ddg_region_param`]) rides along in either request shape.
2707 if let Some(region) = market.as_deref().and_then(ddg_region_param) {
2708 pairs.append_pair("kl", &region);
2709 }
2710 }
2711 (url.to_string(), host)
2712 } else {
2713 duckduckgo_search_url(
2714 context.search_base_url.as_deref(),
2715 &query.query,
2716 market.as_deref(),
2717 )?
2718 };
2719 let allow_bing_fallback = endpoints
2720 .allow_bing_fallback
2721 .unwrap_or_else(|| duckduckgo_allows_bing_fallback(context.search_base_url.as_deref()));
2722 check_policy(decider, &duckduckgo_host)?;
2723 // #6746: a hanging DuckDuckGo must leave the Bing fallback time to answer.
2724 // When Bing may follow, DuckDuckGo gets a share of the budget and Bing
2725 // the remainder; without the fallback DuckDuckGo keeps the whole budget.
2726 let duckduckgo_budget = if allow_bing_fallback {
2727 budget.mul_f64(DUCKDUCKGO_BUDGET_SHARE)
2728 } else {
2729 budget
2730 };
2731 let fetched =
2732 fetch_duckduckgo_html(&client, &url, &accept_language, duckduckgo_budget, context).await;
2733 let bing_budget = || {
2734 budget
2735 .saturating_sub(started.elapsed())
2736 .max(Duration::from_millis(1))
2737 };
2738 let body = match fetched {
2739 Ok(body) => body,
2740 // #6746: an unreachable DuckDuckGo (connection error, timeout, or a
2741 // non-2xx status) must still reach the Bing fallback, not end the
2742 // chain. Only a Bing answer with results replaces the DuckDuckGo
2743 // error; otherwise the original failure is reported.
2744 Err(error)
2745 if !error.content()
2746 || matches!(
2747 error.error,
2748 ToolError::Cancelled { .. } | ToolError::Timeout { seconds: 0 }
2749 ) =>
2750 {
2751 return Err(error);
2752 }
2753 Err(error) if allow_bing_fallback => {
2754 let error = match error.error {
2755 ToolError::ExecutionFailed { message, .. } => message,
2756 other => other.to_string(),
2757 };
2758 check_policy(decider, BING_HOST)?;
2759 return match run_bing_search(
2760 &client,
2761 &query.query,
2762 query.locale.as_deref(),
2763 max_results,
2764 endpoints.bing,
2765 bing_budget(),
2766 context,
2767 )
2768 .await
2769 {
2770 Ok(results) if !results.is_empty() => {
2771 degraded.push(DegradedReason::BackendUnavailable {
2772 backend: BackendId::DuckDuckGo,
2773 });
2774 degraded.push(DegradedReason::BackendFallback {
2775 from: BackendId::DuckDuckGo,
2776 to: BackendId::Bing,
2777 });
2778 prune_fallback_locale_ignored(&mut degraded, query.locale.as_deref());
2779 Ok(BackendSearch {
2780 backend: BackendId::Bing,
2781 source: "bing".to_string(),
2782 backend_detail: None,
2783 results: normalize_entries(results),
2784 degraded,
2785 note: Some(format!("{error}; used Bing fallback")),
2786 })
2787 }
2788 Ok(_) => Err((ToolError::execution_failed(format!(
2789 "{error}; Bing fallback returned no results"
2790 )))
2791 .into()),
2792 Err(bing_error) if !bing_error.content() => Err(bing_error),
2793 Err(bing_error) => Err((ToolError::execution_failed(format!(
2794 "{error}; Bing fallback failed: {}",
2795 match &bing_error.error {
2796 ToolError::ExecutionFailed { message, .. } => message.clone(),
2797 other => other.to_string(),
2798 }
2799 )))
2800 .into()),
2801 };
2802 }
2803 Err(error) => return Err(error),
2804 };
2805
2806 let results = normalize_scraped_entries(
2807 parse_duckduckgo_results(&body, max_results),
2808 context,
2809 bing_budget(),
2810 )
2811 .await?;
2812 let blocked = is_duckduckgo_challenge(&body);
2813 if !results.is_empty() {
2814 return Ok(BackendSearch {
2815 backend: BackendId::DuckDuckGo,
2816 source: if allow_bing_fallback {
2817 "duckduckgo".to_string()
2818 } else {
2819 duckduckgo_host.clone()
2820 },
2821 backend_detail: (!allow_bing_fallback).then_some(duckduckgo_host),
2822 results: normalize_entries(results),
2823 degraded,
2824 note: None,
2825 });
2826 }
2827 if blocked {
2828 degraded.push(DegradedReason::ChallengeDetected {
2829 backend: BackendId::DuckDuckGo,
2830 });
2831 }
2832 if !allow_bing_fallback {
2833 if blocked {
2834 return Err((ToolError::execution_failed(format!(
2835 "DuckDuckGo-compatible search endpoint at {duckduckgo_host} returned a bot challenge; check the private search service, credentials, or network policy"
2836 ))).into());
2837 }
2838 return Ok(BackendSearch {
2839 backend: BackendId::DuckDuckGo,
2840 source: duckduckgo_host.clone(),
2841 backend_detail: Some(duckduckgo_host),
2842 results: Vec::new(),
2843 degraded,
2844 note: None,
2845 });
2846 }
2847
2848 check_policy(decider, BING_HOST)?;
2849 match run_bing_search(
2850 &client,
2851 &query.query,
2852 query.locale.as_deref(),
2853 max_results,
2854 endpoints.bing,
2855 bing_budget(),
2856 context,
2857 )
2858 .await
2859 {
2860 Ok(results) if !results.is_empty() => {
2861 degraded.push(DegradedReason::ScrapeFallback {
2862 from: BackendId::DuckDuckGo,
2863 to: BackendId::Bing,
2864 });
2865 prune_fallback_locale_ignored(&mut degraded, query.locale.as_deref());
2866 Ok(BackendSearch {
2867 backend: BackendId::Bing,
2868 source: "bing".to_string(),
2869 backend_detail: None,
2870 results: normalize_entries(results),
2871 degraded,
2872 note: Some(if blocked {
2873 "DuckDuckGo returned a bot challenge; used Bing fallback".to_string()
2874 } else {
2875 "DuckDuckGo returned no parseable results; used Bing fallback".to_string()
2876 }),
2877 })
2878 }
2879 Err(error) if !error.content() => Err(error),
2880 Ok(_) if blocked => Err((ToolError::execution_failed(
2881 "DuckDuckGo returned a bot challenge and Bing fallback returned no results",
2882 ))
2883 .into()),
2884 Err(error) if blocked => Err((ToolError::execution_failed(format!(
2885 "DuckDuckGo returned a bot challenge and Bing fallback failed: {error}"
2886 )))
2887 .into()),
2888 Ok(_) | Err(_) => Ok(BackendSearch {
2889 backend: BackendId::DuckDuckGo,
2890 source: "duckduckgo".to_string(),
2891 backend_detail: None,
2892 results: Vec::new(),
2893 degraded,
2894 note: None,
2895 }),
2896 }
2897 }
2898
2899 /// Fetch the DuckDuckGo HTML results page. A transport failure or a non-2xx
2900 /// status is an error so the caller can decide whether Bing may answer.
2901 async fn fetch_duckduckgo_html(
2902 client: &reqwest::Client,
2903 url: &str,
2904 accept_language: &str,
2905 timeout: Duration,
2906 context: &ToolContext,
2907 ) -> AdapterResult<String> {
2908 let resp = client
2909 .get(url)
2910 .timeout(timeout)
2911 .header(
2912 "Accept",
2913 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
2914 )
2915 .header("Accept-Language", accept_language)
2916 .send()
2917 .await
2918 .map_err(|error| {
2919 ToolError::execution_failed(format!("Web search request failed: {error}"))
2920 })?;
2921 let status = resp.status();
2922 let body = if adapter::search_selected(context) {
2923 adapter::read_response_with_limit(resp, context, super::web::fetch::HARD_MAX_BYTES).await?
2924 } else {
2925 resp.text().await.map_err(|error| {
2926 ToolError::execution_failed(format!("Failed to read response: {error}"))
2927 })?
2928 };
2929 if !status.is_success() {
2930 return Err(ToolError::execution_failed(format!(
2931 "Web search failed: HTTP {}",
2932 status.as_u16()
2933 ))
2934 .into());
2935 }
2936 Ok(body)
2937 }
2938
2939 async fn normalize_scraped_entries(
2940 entries: Vec<WebSearchEntry>,
2941 context: &ToolContext,
2942 budget: Duration,
2943 ) -> AdapterResult<Vec<WebSearchEntry>> {
2944 normalize_captured_entries(
2945 entries
2946 .into_iter()
2947 .map(|entry| super::web::contract::CapturedSearchEntry {
2948 title: entry.title,
2949 url: entry.url,
2950 snippet: entry.snippet,
2951 published: None,
2952 })
2953 .collect(),
2954 context,
2955 budget,
2956 )
2957 .await
2958 .map(|entries| {
2959 entries
2960 .into_iter()
2961 .map(|entry| WebSearchEntry {
2962 title: entry.title,
2963 url: entry.url,
2964 snippet: entry.snippet,
2965 })
2966 .collect()
2967 })
2968 }
2969
2970 fn normalize_entries(entries: Vec<WebSearchEntry>) -> Vec<SearchResult> {
2971 entries
2972 .into_iter()
2973 .enumerate()
2974 .map(|(index, entry)| {
2975 SearchResult::new(index + 1, entry.title, entry.url, entry.snippet, None)
2976 })
2977 .collect()
2978 }
2979
2980 fn rerank(results: &mut [SearchResult]) {
2981 for (index, result) in results.iter_mut().enumerate() {
2982 result.rank = u8::try_from(index + 1).unwrap_or(u8::MAX);
2983 }
2984 }
2985
2986 pub fn domain_matches(url: &str, domains: &[String]) -> bool {
2987 if domains.is_empty() {
2988 return true;
2989 }
2990 let Ok(parsed) = reqwest::Url::parse(url) else {
2991 return false;
2992 };
2993 let Some(host) = parsed.host_str() else {
2994 return false;
2995 };
2996 let host = host.trim_start_matches("www.").to_ascii_lowercase();
2997 domains.iter().any(|domain| {
2998 let domain = domain.trim_start_matches("www.").to_ascii_lowercase();
2999 host == domain || host.ends_with(&format!(".{domain}"))
3000 })
3001 }
3002
3003 fn truncate_error_body(body: &str) -> String {
3004 let stripped = sanitize_error_body(body);
3005 if stripped.len() <= ERROR_BODY_PREVIEW_BYTES {
3006 stripped
3007 } else {
3008 let mut end = ERROR_BODY_PREVIEW_BYTES;
3009 while !stripped.is_char_boundary(end) {
3010 end -= 1;
3011 }
3012 format!("{}...", &stripped[..end])
3013 }
3014 }
3015
3016 static TAG_RE: OnceLock<Regex> = OnceLock::new();
3017
3018 fn get_tag_re() -> &'static Regex {
3019 TAG_RE.get_or_init(|| Regex::new(r"<[^>]+>").expect("tag regex pattern is valid"))
3020 }
3021
3022 fn strip_html_tags(text: &str) -> String {
3023 get_tag_re().replace_all(text, "").to_string()
3024 }
3025
3026 fn sanitize_error_body(body: &str) -> String {
3027 let stripped = strip_html_tags(body);
3028 let visible: String = stripped
3029 .chars()
3030 .filter(|c| !c.is_control() || c.is_ascii_whitespace())
3031 .collect();
3032 get_bearer_token_re()
3033 .replace_all(&visible, "Bearer [REDACTED]")
3034 .to_string()
3035 }
3036
3037 fn parse_tavily_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3038 parsed
3039 .get("results")
3040 .and_then(Value::as_array)
3041 .into_iter()
3042 .flatten()
3043 .filter_map(|item| {
3044 let title = item.get("title")?.as_str()?.trim();
3045 let url = item.get("url")?.as_str()?.trim();
3046 if title.is_empty() || url.is_empty() {
3047 return None;
3048 }
3049 Some(WebSearchEntry {
3050 title: title.to_string(),
3051 url: url.to_string(),
3052 snippet: first_non_empty_string(item, &["content", "snippet"]),
3053 })
3054 })
3055 .take(max_results)
3056 .collect()
3057 }
3058
3059 fn parse_firecrawl_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3060 parsed
3061 .pointer("/data/web")
3062 .or_else(|| parsed.get("data"))
3063 .and_then(Value::as_array)
3064 .into_iter()
3065 .flatten()
3066 .filter_map(|item| {
3067 let title = item.get("title")?.as_str()?.trim();
3068 let url = item.get("url")?.as_str()?.trim();
3069 (!title.is_empty() && !url.is_empty()).then(|| WebSearchEntry {
3070 title: title.to_string(),
3071 url: url.to_string(),
3072 snippet: first_non_empty_string(item, &["description", "markdown", "content"])
3073 .map(|value| value.chars().take(1_000).collect()),
3074 })
3075 })
3076 .take(max_results)
3077 .collect()
3078 }
3079
3080 fn parse_metaso_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3081 parsed
3082 .get("webpages")
3083 .and_then(Value::as_array)
3084 .into_iter()
3085 .flatten()
3086 .filter_map(|item| {
3087 let title = item.get("title")?.as_str()?.trim();
3088 let url = item.get("link")?.as_str()?.trim();
3089 if title.is_empty() || url.is_empty() {
3090 return None;
3091 }
3092 Some(WebSearchEntry {
3093 title: title.to_string(),
3094 url: url.to_string(),
3095 snippet: first_non_empty_string(item, &["snippet", "summary"]),
3096 })
3097 })
3098 .take(max_results)
3099 .collect()
3100 }
3101
3102 fn parse_bocha_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3103 parsed
3104 .get("data")
3105 .and_then(|d| {
3106 d.get("webPages")
3107 .and_then(|w| w.get("value"))
3108 .or_else(|| d.get("pages"))
3109 })
3110 .or_else(|| parsed.get("pages"))
3111 .and_then(|v| v.as_array())
3112 .into_iter()
3113 .flat_map(|arr| arr.iter())
3114 .filter_map(|item| {
3115 let title = item
3116 .get("name")
3117 .or_else(|| item.get("title"))
3118 .and_then(|s| s.as_str())?
3119 .trim();
3120 let url = item
3121 .get("url")
3122 .or_else(|| item.get("link"))
3123 .and_then(|s| s.as_str())?
3124 .trim();
3125 if title.is_empty() || url.is_empty() {
3126 return None;
3127 }
3128 let snippet = item
3129 .get("summary")
3130 .or_else(|| item.get("snippet"))
3131 .or_else(|| item.get("description"))
3132 .and_then(|s| s.as_str())
3133 .map(str::trim)
3134 .filter(|s| !s.is_empty())
3135 .map(ToString::to_string);
3136 Some(WebSearchEntry {
3137 title: title.to_string(),
3138 url: url.to_string(),
3139 snippet,
3140 })
3141 })
3142 .take(max_results)
3143 .collect()
3144 }
3145
3146 fn bocha_error_message(parsed: &Value) -> Option<String> {
3147 let code = parsed.get("code").and_then(|v| v.as_i64())?;
3148 if code == 0 || code == 200 {
3149 return None;
3150 }
3151 let message = parsed
3152 .get("msg")
3153 .or_else(|| parsed.get("message"))
3154 .and_then(|v| v.as_str())
3155 .unwrap_or("unknown error");
3156 Some(format!("Bocha search API error (code {code}: {message})"))
3157 }
3158
3159 fn parse_baidu_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3160 parsed
3161 .get("references")
3162 .and_then(|v| v.as_array())
3163 .into_iter()
3164 .flat_map(|arr| arr.iter())
3165 .filter_map(|item| {
3166 let title = item
3167 .get("title")
3168 .or_else(|| item.get("name"))
3169 .and_then(|s| s.as_str())?
3170 .trim();
3171 let url = item
3172 .get("url")
3173 .or_else(|| item.get("link"))
3174 .and_then(|s| s.as_str())?
3175 .trim();
3176 if title.is_empty() || url.is_empty() {
3177 return None;
3178 }
3179 let snippet = item
3180 .get("content")
3181 .or_else(|| item.get("snippet"))
3182 .or_else(|| item.get("summary"))
3183 .and_then(|s| s.as_str())
3184 .map(str::trim)
3185 .filter(|s| !s.is_empty())
3186 .map(ToString::to_string);
3187 Some(WebSearchEntry {
3188 title: title.to_string(),
3189 url: url.to_string(),
3190 snippet,
3191 })
3192 })
3193 .take(max_results)
3194 .collect()
3195 }
3196
3197 /// Read a SearXNG result `score`.
3198 ///
3199 /// SearXNG emits a float, but instances and versions vary: a JSON integer, a
3200 /// numeric string, or no `score` at all are all tolerated. Unusable or
3201 /// non-finite values (`"not-a-number"`, `"NaN"`, `"inf"`, missing) read as
3202 /// `0.0`, so such rows keep their input order behind scored rows instead of
3203 /// being dropped or sorted by NaN.
3204 fn searxng_score(item: &Value) -> f64 {
3205 let raw = item.get("score");
3206 let n = raw
3207 .and_then(Value::as_f64)
3208 .or_else(|| raw.and_then(Value::as_i64).map(|i| i as f64))
3209 .or_else(|| {
3210 raw.and_then(Value::as_str)
3211 .and_then(|s| s.trim().parse().ok())
3212 })
3213 .unwrap_or(0.0);
3214 if n.is_finite() { n } else { 0.0 }
3215 }
3216
3217 /// Normalize a SearXNG JSON response into the engine-agnostic result shape.
3218 ///
3219 /// Rows without a non-empty `title` or `url` are skipped. Everything else is
3220 /// ordered by descending `score` with a stable sort (equal scores keep the
3221 /// instance's order) and only then capped, so a strong late row is not lost to
3222 /// an earlier `take` over the raw instance order.
3223 fn parse_searxng_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3224 let mut scored: Vec<(f64, WebSearchEntry)> = parsed
3225 .get("results")
3226 .and_then(|v| v.as_array())
3227 .into_iter()
3228 .flat_map(|arr| arr.iter())
3229 .filter_map(|item| {
3230 let title = item.get("title").and_then(Value::as_str)?.trim();
3231 let url = item.get("url").and_then(Value::as_str)?.trim();
3232 if title.is_empty() || url.is_empty() {
3233 return None;
3234 }
3235 let snippet = first_non_empty_string(item, &["content", "snippet"]);
3236 Some((
3237 searxng_score(item),
3238 WebSearchEntry {
3239 title: title.to_string(),
3240 url: url.to_string(),
3241 snippet,
3242 },
3243 ))
3244 })
3245 .collect();
3246
3247 scored.sort_by(|a, b| b.0.total_cmp(&a.0));
3248 scored.truncate(max_results);
3249
3250 scored.into_iter().map(|(_, entry)| entry).collect()
3251 }
3252
3253 fn baidu_error_message(parsed: &Value) -> Option<String> {
3254 let code = parsed
3255 .get("error_code")
3256 .or_else(|| parsed.get("code"))
3257 .and_then(|v| v.as_i64())?;
3258 if code == 0 {
3259 return None;
3260 }
3261 let message = parsed
3262 .get("error_msg")
3263 .or_else(|| parsed.get("message"))
3264 .and_then(|v| v.as_str())
3265 .unwrap_or("unknown error");
3266 Some(format!("Baidu search API error (code {code}: {message})"))
3267 }
3268
3269 async fn acquire_model_backed_search_inference_participant()
3270 -> crate::client::RemoteControlInferencePermit {
3271 crate::client::acquire_remote_control_inference_participant().await
3272 }
3273
3274 fn parse_sofya_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3275 parsed
3276 .get("results")
3277 .and_then(|v| v.as_array())
3278 .into_iter()
3279 .flat_map(|arr| arr.iter())
3280 .filter_map(|item| {
3281 let title = item.get("title")?.as_str()?.to_string();
3282 let url = item.get("url")?.as_str()?.to_string();
3283 let snippet = first_non_empty_string(item, &["content", "description"]);
3284 Some(WebSearchEntry {
3285 title,
3286 url,
3287 snippet,
3288 })
3289 })
3290 .take(max_results)
3291 .collect()
3292 }
3293
3294 /// Build the Serply `/v1/search` URL; `num` is the number of organic results.
3295 fn tavily_search_payload(
3296 api_key: &str,
3297 query: &str,
3298 filters: QueryFilters<'_>,
3299 max_results: usize,
3300 ) -> Value {
3301 let mut payload = json!({
3302 "api_key": api_key, // noqa: api-key-in-body
3303 "query": query,
3304 "search_depth": "basic",
3305 "max_results": max_results,
3306 });
3307 if let Some(window) = filters.window() {
3308 payload["time_range"] = json!(window);
3309 }
3310 payload
3311 }
3312
3313 /// Serply documents `gl` (country); `hl` is the Google interface-language
3314 /// parameter it forwards. Recency is not documented, so it is not sent.
3315 fn serply_search_url(
3316 query: &str,
3317 filters: QueryFilters<'_>,
3318 max_results: usize,
3319 ) -> Result<reqwest::Url, ToolError> {
3320 let mut url = reqwest::Url::parse(SERPLY_ENDPOINT)
3321 .map_err(|error| ToolError::invalid_input(format!("Invalid Serply endpoint: {error}")))?;
3322 {
3323 let mut pairs = url.query_pairs_mut();
3324 pairs
3325 .append_pair("q", query)
3326 .append_pair("num", &max_results.to_string());
3327 if let Some(language) = filters.language() {
3328 pairs.append_pair("hl", &language);
3329 }
3330 if let Some(region) = filters.region() {
3331 pairs.append_pair("gl", &region.to_ascii_lowercase());
3332 }
3333 }
3334 Ok(url)
3335 }
3336
3337 /// Parse Serply `/v1/search` output: `results[]` rows carry `title`, `link`, and
3338 /// a `description` snippet; ads, knowledge graph, and related questions are
3339 /// top-level siblings and are ignored.
3340 fn parse_serply_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3341 parsed
3342 .get("results")
3343 .and_then(|v| v.as_array())
3344 .into_iter()
3345 .flat_map(|arr| arr.iter())
3346 .filter_map(|item| {
3347 let title = item.get("title")?.as_str()?.to_string();
3348 let url = item.get("link")?.as_str()?.to_string();
3349 let snippet = first_non_empty_string(item, &["description", "snippet"]);
3350 Some(WebSearchEntry {
3351 title,
3352 url,
3353 snippet,
3354 })
3355 })
3356 .take(max_results)
3357 .collect()
3358 }
3359
3360 fn searchapi_search_url(
3361 query: &str,
3362 filters: QueryFilters<'_>,
3363 max_results: usize,
3364 ) -> Result<reqwest::Url, ToolError> {
3365 let mut url = reqwest::Url::parse(SEARCHAPI_ENDPOINT).map_err(|error| {
3366 ToolError::invalid_input(format!("Invalid SearchApi endpoint: {error}"))
3367 })?;
3368 {
3369 let mut pairs = url.query_pairs_mut();
3370 pairs
3371 .append_pair("q", query)
3372 .append_pair("engine", "google")
3373 .append_pair("num", &max_results.to_string());
3374 if let Some(window) = filters.window() {
3375 pairs.append_pair("time_period", &format!("last_{window}"));
3376 }
3377 if let Some(language) = filters.language() {
3378 pairs.append_pair("hl", &language);
3379 }
3380 if let Some(region) = filters.region() {
3381 pairs.append_pair("gl", &region.to_ascii_lowercase());
3382 }
3383 }
3384 Ok(url)
3385 }
3386
3387 fn parse_searchapi_results(parsed: &Value, max_results: usize) -> Vec<WebSearchEntry> {
3388 parsed
3389 .get("organic_results")
3390 .and_then(|v| v.as_array())
3391 .into_iter()
3392 .flat_map(|arr| arr.iter())
3393 .filter_map(|item| {
3394 let title = item.get("title")?.as_str()?.to_string();
3395 let url = item.get("link")?.as_str()?.to_string();
3396 let snippet = first_non_empty_string(item, &["snippet"]);
3397 Some(WebSearchEntry {
3398 title,
3399 url,
3400 snippet,
3401 })
3402 })
3403 .take(max_results)
3404 .collect()
3405 }
3406
3407 fn parse_deepseek_results(parsed: &Value, max_results: usize) -> Vec<SearchResult> {
3408 parsed
3409 .get("results")
3410 .and_then(Value::as_array)
3411 .into_iter()
3412 .flatten()
3413 .filter_map(|item| {
3414 let title = first_non_empty_string(item, &["title"])?;
3415 let url = first_non_empty_string(item, &["url"])?;
3416 Some((
3417 title,
3418 url,
3419 first_non_empty_string(item, &["snippet", "summary"]),
3420 first_non_empty_string(item, &["date"]),
3421 ))
3422 })
3423 .take(max_results)
3424 .enumerate()
3425 .map(|(index, (title, url, snippet, published))| {
3426 SearchResult::new(index + 1, title, url, snippet, published)
3427 })
3428 .collect()
3429 }
3430
3431 fn first_non_empty_string(item: &Value, keys: &[&str]) -> Option<String> {
3432 keys.iter().find_map(|key| {
3433 item.get(*key)
3434 .and_then(Value::as_str)
3435 .map(str::trim)
3436 .filter(|value| !value.is_empty())
3437 .map(str::to_string)
3438 })
3439 }
3440
3441 fn baidu_search_payload(query: &str, max_results: usize) -> Value {
3442 json!({
3443 "messages": [
3444 {
3445 "role": "user",
3446 "content": query,
3447 }
3448 ],
3449 "search_source": "baidu_search_v2",
3450 "resource_type_filter": [
3451 {
3452 "type": "web",
3453 "top_k": max_results,
3454 }
3455 ],
3456 })
3457 }
3458
3459 fn volcengine_search_payload(query: &str, max_results: usize) -> Value {
3460 json!({
3461 "model": "doubao-seed-2-0-lite-260428",
3462 "stream": false,
3463 "tools": [{"type": "web_search"}],
3464 "input": [{
3465 "role": "user",
3466 "content": [{
3467 "type": "input_text",
3468 "text": format!(
3469 "Search the web for: {query}\n\n\
3470 CRITICAL: Respond ONLY with a valid JSON object. No markdown, no explanation.\n\
3471 Schema: {{\"results\":[{{\"title\":\"...\",\"url\":\"https://...\",\"snippet\":\"...\"}}]}}\n\
3472 - results: 1-{max_results} most relevant pages\n\
3473 - title: page title (required)\n\
3474 - url: full URL starting with https:// (required)\n\
3475 - snippet: 1-2 sentence factual summary (required)\n\
3476 - If zero results: {{\"results\":[]}}\n\
3477 - Your entire response must be valid, parseable JSON."
3478 )
3479 }]
3480 }]
3481 })
3482 }
3483
3484 /// Extracts the model's text response from a Volcengine Responses API output.
3485 fn volcengine_extract_text(parsed: &Value) -> Option<String> {
3486 parsed
3487 .get("output")
3488 .and_then(|v| v.as_array())
3489 .into_iter()
3490 .flat_map(|arr| arr.iter().rev())
3491 .find(|item| item.get("type").and_then(|t| t.as_str()) == Some("message"))
3492 .and_then(|msg| msg.get("content").and_then(|c| c.as_array()))
3493 .and_then(|content| {
3494 content
3495 .iter()
3496 .find(|c| c.get("text").and_then(|t| t.as_str()).is_some())
3497 })
3498 .and_then(|c| c.get("text").and_then(|t| t.as_str()))
3499 .map(|s| s.to_string())
3500 }
3501
3502 /// Checks for business-logic errors in a Volcengine Responses API response.
3503 fn volcengine_error_message(parsed: &Value) -> Option<String> {
3504 let error = parsed.get("error")?;
3505 let code = error
3506 .get("code")
3507 .and_then(|v| v.as_str())
3508 .unwrap_or("unknown");
3509 let message = error
3510 .get("message")
3511 .and_then(|v| v.as_str())
3512 .unwrap_or("no details");
3513 Some(format!("Volcengine API error (code {code}: {message})"))
3514 }
3515
3516 /// Parses Volcengine model-generated JSON results into `WebSearchEntry` items.
3517 fn parse_volcengine_results(response_text: &str, max_results: usize) -> Vec<WebSearchEntry> {
3518 let json_text = extract_json_block(response_text).unwrap_or(response_text);
3519
3520 let parsed: Value = match serde_json::from_str(json_text) {
3521 Ok(v) => v,
3522 Err(_) => return Vec::new(),
3523 };
3524
3525 parsed
3526 .get("results")
3527 .and_then(|v| v.as_array())
3528 .into_iter()
3529 .flat_map(|arr| arr.iter())
3530 .filter_map(|item| {
3531 let title = item.get("title").and_then(|s| s.as_str())?.trim();
3532 let url = item.get("url").and_then(|s| s.as_str())?.trim();
3533 if title.is_empty() || url.is_empty() {
3534 return None;
3535 }
3536 let snippet = item
3537 .get("snippet")
3538 .and_then(|s| s.as_str())
3539 .map(str::trim)
3540 .filter(|s| !s.is_empty())
3541 .map(ToString::to_string);
3542 Some(WebSearchEntry {
3543 title: title.to_string(),
3544 url: url.to_string(),
3545 snippet,
3546 })
3547 })
3548 .take(max_results)
3549 .collect()
3550 }
3551
3552 /// Attempts to extract a JSON block from text that may be wrapped in
3553 /// markdown fences (```json ... ```) or contain surrounding commentary.
3554 fn extract_json_block(text: &str) -> Option<&str> {
3555 if let Some(start) = text.find("```json") {
3556 let inner = &text[start + 7..];
3557 if let Some(end) = inner.find("```") {
3558 return Some(inner[..end].trim());
3559 }
3560 }
3561 if let Some(start) = text.find('{')
3562 && let Some(end) = text.rfind('}')
3563 {
3564 return Some(&text[start..=end]);
3565 }
3566 None
3567 }
3568
3569 fn extract_search_query(input: &Value) -> Result<String, ToolError> {
3570 for key in ["query", "q"] {
3571 if let Some(value) = input.get(key) {
3572 let Some(query) = value.as_str() else {
3573 return Err(ToolError::invalid_input(format!(
3574 "Field '{key}' must be a string"
3575 )));
3576 };
3577 let query = query.trim();
3578 if !query.is_empty() {
3579 return Ok(query.to_string());
3580 }
3581 }
3582 }
3583
3584 for item in search_query_items(input) {
3585 for key in ["q", "query"] {
3586 if let Some(value) = item.get(key) {
3587 let Some(query) = value.as_str() else {
3588 return Err(ToolError::invalid_input(format!(
3589 "Field 'search_query[].{key}' must be a string"
3590 )));
3591 };
3592 let query = query.trim();
3593 if !query.is_empty() {
3594 return Ok(query.to_string());
3595 }
3596 }
3597 }
3598 }
3599
3600 Err(ToolError::missing_field("query"))
3601 }
3602
3603 fn optional_search_max_results(input: &Value) -> u64 {
3604 if let Some(value) = input.get("max_results").and_then(Value::as_u64) {
3605 return value;
3606 }
3607 search_query_items(input)
3608 .filter_map(|item| item.get("max_results").and_then(Value::as_u64))
3609 .next()
3610 .unwrap_or(DEFAULT_SEARCH_RESULTS as u64)
3611 }
3612
3613 fn search_query_from_input(input: &Value) -> Result<SearchQuery, ToolError> {
3614 let query = extract_search_query(input)?;
3615 if query.is_empty() {
3616 return Err(ToolError::invalid_input("Query cannot be empty"));
3617 }
3618 let max_results = usize::try_from(optional_search_max_results(input))
3619 .unwrap_or(DEFAULT_SEARCH_RESULTS)
3620 .clamp(1, usize::from(MAX_SEARCH_RESULTS));
3621 let recency = search_option(input, "recency")
3622 .map(parse_recency)
3623 .transpose()?;
3624 let domains = match search_option(input, "domains") {
3625 Some(value) => value
3626 .as_array()
3627 .ok_or_else(|| ToolError::invalid_input("Field 'domains' must be an array"))?
3628 .iter()
3629 .map(|value| {
3630 value.as_str().map(str::to_string).ok_or_else(|| {
3631 ToolError::invalid_input("Every 'domains' entry must be a string")
3632 })
3633 })
3634 .collect::<Result<Vec<_>, _>>()?,
3635 None => Vec::new(),
3636 };
3637 let locale = search_option(input, "locale")
3638 .map(|value| {
3639 value
3640 .as_str()
3641 .map(str::to_string)
3642 .ok_or_else(|| ToolError::invalid_input("Field 'locale' must be a string"))
3643 })
3644 .transpose()?;
3645
3646 Ok(SearchQuery::new(
3647 query,
3648 max_results,
3649 recency,
3650 domains,
3651 locale,
3652 ))
3653 }
3654
3655 fn search_option<'a>(input: &'a Value, key: &str) -> Option<&'a Value> {
3656 input
3657 .get(key)
3658 .or_else(|| search_query_items(input).find_map(|item| item.get(key)))
3659 }
3660
3661 fn parse_recency(value: &Value) -> Result<Recency, ToolError> {
3662 if let Some(days) = value.as_u64() {
3663 let days = u16::try_from(days)
3664 .ok()
3665 .filter(|days| (1..=3650).contains(days))
3666 .ok_or_else(|| {
3667 ToolError::invalid_input("Field 'recency' must be between 1 and 3650 days")
3668 })?;
3669 return Ok(Recency::Days(days));
3670 }
3671 match value.as_str() {
3672 Some("day") => Ok(Recency::Day),
3673 Some("week") => Ok(Recency::Week),
3674 Some("month") => Ok(Recency::Month),
3675 Some("year") => Ok(Recency::Year),
3676 _ => Err(ToolError::invalid_input(
3677 "Field 'recency' must be day, week, month, year, or an integer day count",
3678 )),
3679 }
3680 }
3681
3682 fn search_query_items(input: &Value) -> impl Iterator<Item = &Value> {
3683 input
3684 .get("search_query")
3685 .and_then(Value::as_array)
3686 .into_iter()
3687 .flat_map(|items| items.iter())
3688 }
3689
3690 /// Whether `query` contains Han ideographs (unified ideographs plus
3691 /// Extension A). Kana and Hangul are deliberately excluded: this heuristic
3692 /// exists only to pick a Chinese market for the keyless Bing/DuckDuckGo
3693 /// scrapes when the model omits `locale`, and forcing Japanese or Korean
3694 /// queries into the zh-CN market would be worse than sending no market
3695 /// signal at all.
3696 fn query_contains_han(query: &str) -> bool {
3697 query
3698 .chars()
3699 .any(|c| matches!(c, '\u{4E00}'..='\u{9FFF}' | '\u{3400}'..='\u{4DBF}'))
3700 }
3701
3702 /// Whether `query` carries kana or hangul — the scripts that make a
3703 /// Han-bearing query Japanese or Korean rather than Chinese. Real Japanese
3704 /// queries almost always contain kana alongside kanji, so a Han-bearing
3705 /// query with any kana or hangul must keep the no-market request instead of
3706 /// being pushed onto the zh-CN market (the inverse of the drift the
3707 /// fallback exists to fix). Only a purely Han-script query — rare for
3708 /// search and indistinguishable from Chinese — still takes the fallback,
3709 /// alongside unmarked Traditional Chinese (the accepted cost).
3710 fn query_contains_kana_or_hangul(query: &str) -> bool {
3711 query.chars().any(|c| {
3712 matches!(
3713 c,
3714 '\u{3040}'..='\u{30FF}' // hiragana + katakana
3715 | '\u{31F0}'..='\u{31FF}' // katakana phonetic extensions
3716 | '\u{AC00}'..='\u{D7AF}' // hangul syllables
3717 | '\u{1100}'..='\u{11FF}' // hangul jamo
3718 | '\u{3130}'..='\u{318F}' // hangul compatibility jamo
3719 )
3720 })
3721 }
3722
3723 /// Market tag the scrape backends should request, or `None` to keep the
3724 /// historical no-market-signal request. An explicit locale wins; otherwise a
3725 /// Han-script query without kana or hangul falls back to zh-CN because
3726 /// without any market hint (and with an English `Accept-Language`) Bing
3727 /// serves unrelated Japanese results for Chinese queries. The model-supplied
3728 /// locale is shape-checked first so a malformed value cannot become a broken
3729 /// market tag or header.
3730 fn scrape_market(locale: Option<&str>, query: &str) -> Option<String> {
3731 locale
3732 .map(str::trim)
3733 .filter(|tag| is_plausible_locale_tag(tag))
3734 .map(|tag| tag.replace('_', "-"))
3735 .or_else(|| {
3736 (query_contains_han(query) && !query_contains_kana_or_hangul(query))
3737 .then(|| "zh-CN".to_string())
3738 })
3739 }
3740
3741 /// Light shape check for a model-supplied `locale`: an alphabetic primary
3742 /// language subtag followed by alphanumeric subtags separated by `-`/`_`,
3743 /// each at most 8 characters, with no empty or separator-only edges. The
3744 /// alphabetic primary matters for receipt honesty: `12345` is not a locale,
3745 /// and transmitting it (with `honored.locale=true`) would contradict the
3746 /// schema text promising that malformed values are ignored. Anything else
3747 /// (e.g. `-CN`, `zh CN`, an injection attempt) is treated as no locale and
3748 /// keeps the historical request shape.
3749 fn is_plausible_locale_tag(tag: &str) -> bool {
3750 if tag.is_empty() || tag.len() > 35 {
3751 return false;
3752 }
3753 let mut subtags = tag.split(['-', '_']);
3754 let primary = subtags.next().unwrap_or_default();
3755 if primary.is_empty() || primary.len() > 8 || !primary.chars().all(|c| c.is_ascii_alphabetic())
3756 {
3757 return false;
3758 }
3759 subtags.all(|subtag| {
3760 !subtag.is_empty() && subtag.len() <= 8 && subtag.chars().all(|c| c.is_ascii_alphanumeric())
3761 })
3762 }
3763
3764 /// `Accept-Language` matching [`scrape_market`]. With no market resolved the
3765 /// English default is kept — the value the Bing path has always sent
3766 /// (`en-US,en;q=0.9`); the DuckDuckGo path previously sent `q=0.5` and now
3767 /// shares this one rule.
3768 fn scrape_accept_language(market: Option<&str>) -> String {
3769 match market {
3770 None => "en-US,en;q=0.9".to_string(),
3771 Some(market) => {
3772 let primary = market
3773 .split(['-', '_'])
3774 .next()
3775 .filter(|tag| !tag.is_empty())
3776 .unwrap_or("en");
3777 let mut value = if market.eq_ignore_ascii_case(primary) {
3778 format!("{market};q=0.9")
3779 } else {
3780 format!("{market},{primary};q=0.9")
3781 };
3782 // The generic `en` fallback duplicates the primary tag for
3783 // English markets (`en-US,en;q=0.9,en;q=0.8`), where two q-values
3784 // for one range have no defined precedence — only add it when it
3785 // contributes a distinct range.
3786 if !primary.eq_ignore_ascii_case("en") {
3787 value.push_str(",en;q=0.8");
3788 }
3789 value
3790 }
3791 }
3792 }
3793
3794 /// Bing request adjustments for the resolved market: the `mkt`/`setlang`
3795 /// query parameters and the `Accept-Language` header value.
3796 fn scrape_locale_params(locale: Option<&str>, query: &str) -> (Vec<(String, String)>, String) {
3797 let market = scrape_market(locale, query);
3798 let accept_language = scrape_accept_language(market.as_deref());
3799 let Some(market) = market else {
3800 return (Vec::new(), accept_language);
3801 };
3802 let primary = market
3803 .split(['-', '_'])
3804 .next()
3805 .filter(|tag| !tag.is_empty())
3806 .unwrap_or("en");
3807 // Bing expects `setlang` to carry a script tag for Chinese (a bare `zh`
3808 // is invalid and silently defaults to `en`). An explicit script subtag
3809 // wins (`zh-Hant-TW` must not degrade to Simplified); otherwise the
3810 // script is picked from the market's region subtag, defaulting to
3811 // Simplified because the heuristic that reaches this branch without an
3812 // explicit region is Han-driven.
3813 let setlang = if primary.eq_ignore_ascii_case("zh") {
3814 let segments: Vec<&str> = market.split(['-', '_']).collect();
3815 if segments
3816 .iter()
3817 .any(|segment| segment.eq_ignore_ascii_case("hant"))
3818 {
3819 "zh-Hant"
3820 } else if segments
3821 .iter()
3822 .any(|segment| segment.eq_ignore_ascii_case("hans"))
3823 {
3824 "zh-Hans"
3825 } else {
3826 match segments.get(1) {
3827 Some(region)
3828 if matches!(region.to_ascii_lowercase().as_str(), "tw" | "hk" | "mo") =>
3829 {
3830 "zh-Hant"
3831 }
3832 _ => "zh-Hans",
3833 }
3834 }
3835 } else {
3836 primary
3837 };
3838 (
3839 vec![
3840 ("mkt".to_string(), market.clone()),
3841 ("setlang".to_string(), setlang.to_string()),
3842 ],
3843 accept_language,
3844 )
3845 }
3846
3847 /// True when an explicit `locale` was supplied but cannot shape a market
3848 /// signal for the Bing scrape (`mkt`/`setlang`): the value is malformed, so
3849 /// the request proceeds with no locale signal at all and the receipt must
3850 /// say so instead of claiming the knob was honored.
3851 fn bing_locale_was_ignored(locale: Option<&str>) -> bool {
3852 locale.is_some_and(|tag| !is_plausible_locale_tag(tag.trim()))
3853 }
3854
3855 /// The Bing fallback resolves the locale through Bing's own market mapping,
3856 /// so a `KnobIgnored` flag pushed for the DuckDuckGo leg (whose verified
3857 /// `kl` list is narrow) no longer describes the backend that produced the
3858 /// results: drop it and re-derive from Bing's rule, where anything
3859 /// shape-valid was sent as `mkt`/`setlang` and only an implausible tag
3860 /// stays ignored.
3861 fn prune_fallback_locale_ignored(degraded: &mut Vec<DegradedReason>, locale: Option<&str>) {
3862 degraded.retain(|reason| {
3863 !matches!(
3864 reason,
3865 DegradedReason::KnobIgnored {
3866 knob: QueryKnob::Locale,
3867 }
3868 )
3869 });
3870 if bing_locale_was_ignored(locale) {
3871 degraded.push(DegradedReason::KnobIgnored {
3872 knob: QueryKnob::Locale,
3873 });
3874 }
3875 }
3876
3877 /// True when an explicit `locale` was supplied but the DuckDuckGo scrape
3878 /// honors no part of it as a region signal: the value is malformed (the
3879 /// shape check fails, independently of how [`scrape_market`] resolved the
3880 /// market — a pure-Han query still falls back to the `zh-CN` market for a
3881 /// malformed locale) or the resolved market is outside the verified `kl`
3882 /// region list. In the unmapped case no `kl` parameter is sent, but the
3883 /// `Accept-Language` header still carries the locale (see
3884 /// [`scrape_accept_language`]); only the missing region signal is
3885 /// receipted, so the schema's "malformed values are ignored" promise — and
3886 /// parity with the Bing leg — holds either way.
3887 fn ddg_locale_was_ignored(locale: Option<&str>, market: Option<&str>) -> bool {
3888 locale.is_some_and(|tag| {
3889 !is_plausible_locale_tag(tag.trim()) || market.and_then(ddg_region_param).is_none()
3890 })
3891 }
3892
3893 /// Translate a BCP 47-style market tag into DuckDuckGo's `kl` region value.
3894 /// DuckDuckGo's HTML endpoints take `kl` from a fixed, non-systematic list
3895 /// (`cn-zh`, `us-en`, `jp-jp`, `kr-kr`, `tw-tzh`, `hk-tzh`, ...), so a
3896 /// mechanical reversal of a BCP 47 tag produces off-list junk for most
3897 /// non-English locales. Only verified pairs are translated; anything else
3898 /// sends no `kl` at all — exactly the no-region request the scrape made
3899 /// before this knob existed. Custom DuckDuckGo-compatible services typically
3900 /// ignore `kl` entirely.
3901 fn ddg_region_param(market: &str) -> Option<String> {
3902 let normalized = market.to_ascii_lowercase().replace('_', "-");
3903 // Script+region Chinese tags reduce to their region pair: the schema
3904 // teaches BCP 47, where the script subtag is best practice for Chinese,
3905 // and the verified list maps the region form.
3906 let region = match normalized.as_str() {
3907 "zh-cn" | "zh-hans-cn" => "cn-zh",
3908 "en-us" => "us-en",
3909 "ja-jp" => "jp-jp",
3910 "ko-kr" => "kr-kr",
3911 "zh-tw" | "zh-hant-tw" => "tw-tzh",
3912 "zh-hk" | "zh-hant-hk" => "hk-tzh",
3913 _ => return None,
3914 };
3915 Some(region.to_string())
3916 }
3917
3918 async fn run_bing_search(
3919 client: &reqwest::Client,
3920 query: &str,
3921 locale: Option<&str>,
3922 max_results: usize,
3923 endpoint: &str,
3924 timeout: Duration,
3925 context: &ToolContext,
3926 ) -> AdapterResult<Vec<WebSearchEntry>> {
3927 let mut url = reqwest::Url::parse(endpoint)
3928 .map_err(|error| ToolError::invalid_input(format!("Invalid Bing endpoint: {error}")))?;
3929 let (extra_params, accept_language) = scrape_locale_params(locale, query);
3930 if let Some(plan) = host_request(
3931 "bing",
3932 query,
3933 QueryFilters::default(),
3934 max_results,
3935 context,
3936 u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX),
3937 )
3938 .await?
3939 {
3940 for (key, value) in plan.pairs {
3941 url.query_pairs_mut().append_pair(&key, &value);
3942 }
3943 } else {
3944 url.query_pairs_mut().append_pair("q", query);
3945 }
3946 // The scrape chain hands the host adapter default filters, so the plan
3947 // never carries the locale; the mkt/setlang parameters ride along in
3948 // either request shape so the receipt cannot overclaim locale support.
3949 for (key, value) in &extra_params {
3950 url.query_pairs_mut().append_pair(key, value);
3951 }
3952 let resp = client
3953 .get(url)
3954 .timeout(timeout)
3955 .header(
3956 "Accept",
3957 "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
3958 )
3959 .header("Accept-Language", accept_language)
3960 .send()
3961 .await
3962 .map_err(|e| ToolError::execution_failed(format!("Bing search request failed: {e}")))?;
3963
3964 let status = resp.status();
3965 let body = if adapter::search_selected(context) {
3966 adapter::read_response_with_limit(resp, context, super::web::fetch::HARD_MAX_BYTES).await?
3967 } else {
3968 resp.text().await.map_err(|e| {
3969 ToolError::execution_failed(format!("Failed to read Bing search response: {e}"))
3970 })?
3971 };
3972
3973 if !status.is_success() {
3974 return Err((ToolError::execution_failed(format!(
3975 "Bing search failed: HTTP {}",
3976 status.as_u16()
3977 )))
3978 .into());
3979 }
3980
3981 normalize_scraped_entries(parse_bing_results(&body, max_results), context, timeout).await
3982 }
3983
3984 fn parse_duckduckgo_results(html: &str, max_results: usize) -> Vec<WebSearchEntry> {
3985 scrape_duckduckgo_results(html, max_results)
3986 .into_iter()
3987 .map(web_search_entry_from_scraped)
3988 .collect()
3989 }
3990
3991 fn parse_bing_results(html: &str, max_results: usize) -> Vec<WebSearchEntry> {
3992 scrape_bing_results(html, max_results)
3993 .into_iter()
3994 .map(web_search_entry_from_scraped)
3995 .collect()
3996 }
3997
3998 fn web_search_entry_from_scraped(entry: ScrapedSearchResult) -> WebSearchEntry {
3999 WebSearchEntry {
4000 title: entry.title,
4001 url: entry.url,
4002 snippet: entry.snippet,
4003 }
4004 }
4005
4006 fn duckduckgo_search_base(base_url: Option<&str>) -> Result<(reqwest::Url, String), ToolError> {
4007 let raw = configured_search_base_url(base_url).unwrap_or(DUCKDUCKGO_ENDPOINT);
4008 let url = reqwest::Url::parse(raw).map_err(|err| {
4009 ToolError::invalid_input(format!(
4010 "Invalid DuckDuckGo-compatible search base_url: {err}"
4011 ))
4012 })?;
4013 let host = url.host_str().ok_or_else(|| {
4014 ToolError::invalid_input("DuckDuckGo-compatible search base_url must include a host")
4015 })?;
4016 let host = host.to_owned();
4017 Ok((url, host))
4018 }
4019
4020 fn duckduckgo_search_url(
4021 base_url: Option<&str>,
4022 query: &str,
4023 market: Option<&str>,
4024 ) -> Result<(String, String), ToolError> {
4025 let (mut url, host) = duckduckgo_search_base(base_url)?;
4026 {
4027 let mut pairs = url.query_pairs_mut();
4028 pairs.append_pair("q", query);
4029 // DuckDuckGo HTML endpoints take the market hint as `kl`; see
4030 // [`ddg_region_param`] for the verified region-language mapping.
4031 // Custom DDG-compatible services simply ignore the extra parameter.
4032 if let Some(region) = market.and_then(ddg_region_param) {
4033 pairs.append_pair("kl", &region);
4034 }
4035 }
4036 Ok((url.to_string(), host))
4037 }
4038
4039 fn searxng_search_base(base_url: Option<&str>) -> Result<(reqwest::Url, String), ToolError> {
4040 let raw = configured_search_base_url(base_url).ok_or_else(|| {
4041 ToolError::invalid_input(
4042 "SearXNG search requires [search] base_url = \"https://your-searxng.example\"; no public instance is used by default.",
4043 )
4044 })?;
4045 let mut url = reqwest::Url::parse(raw).map_err(|err| {
4046 ToolError::invalid_input(format!("Invalid SearXNG search base_url: {err}"))
4047 })?;
4048 let host = url
4049 .host_str()
4050 .ok_or_else(|| ToolError::invalid_input("SearXNG search base_url must include a host"))?
4051 .to_string();
4052
4053 let path = url.path().trim_end_matches('/');
4054 if path.is_empty() {
4055 url.set_path("search");
4056 } else if path != "/search" && !path.ends_with("/search") {
4057 url.set_path(&format!("{path}/search"));
4058 }
4059 Ok((url, host))
4060 }
4061
4062 fn searxng_search_url(
4063 base_url: Option<&str>,
4064 query: &str,
4065 filters: QueryFilters<'_>,
4066 ) -> Result<(String, String), ToolError> {
4067 let (mut url, host) = searxng_search_base(base_url)?;
4068 {
4069 let mut pairs = url.query_pairs_mut();
4070 pairs.append_pair("q", query).append_pair("format", "json");
4071 if let Some(window) = filters.window() {
4072 pairs.append_pair("time_range", window);
4073 }
4074 if let Some(locale) = filters.locale {
4075 pairs.append_pair("language", locale);
4076 }
4077 }
4078
4079 Ok((url.to_string(), host))
4080 }
4081
4082 fn configured_search_base_url(base_url: Option<&str>) -> Option<&str> {
4083 base_url.map(str::trim).filter(|value| !value.is_empty())
4084 }
4085
4086 fn duckduckgo_allows_bing_fallback(base_url: Option<&str>) -> bool {
4087 configured_search_base_url(base_url).is_none()
4088 }
4089
4090 #[cfg(test)]
4091 mod tests {
4092 use super::{
4093 ERROR_BODY_PREVIEW_BYTES, KIMI_K3_FORMULA_MIN_TIMEOUT_MS, QueryFilters, ScrapeEndpoints,
4094 SearchProbeTargetError, WebSearchTool, acquire_model_backed_search_inference_participant,
4095 baidu_search_payload, bing_locale_was_ignored, bocha_error_message, ddg_locale_was_ignored,
4096 ddg_region_param, domain_matches, duckduckgo_search_url, extract_search_query,
4097 finalize_search_response, native_answer_time_budget, optional_search_max_results,
4098 parse_baidu_results, parse_bocha_results, parse_deepseek_results, parse_metaso_results,
4099 parse_searchapi_results, parse_searxng_results, parse_serply_results, parse_sofya_results,
4100 parse_tavily_results, parse_volcengine_results, prune_fallback_locale_ignored,
4101 register_search_citations, rerank, run_scrape_search_with_endpoints, sanitize_error_body,
4102 scrape_accept_language, scrape_locale_params, scrape_market, search_probe_target,
4103 search_timeout_budgets, searchapi_search_url, searxng_score, searxng_search_url,
4104 serply_search_url, truncate_error_body, volcengine_extract_text,
4105 };
4106 use crate::tools::web::contract::{
4107 BackendId, BackendSearch, CapabilityState, DegradedReason, QueryCapabilities, QueryKnob,
4108 Recency, SearchQuery, SearchResult,
4109 };
4110 use crate::tools::web::scrape::{decode_html_entities, normalize_bing_url};
4111 use codewhale_runtime::config::SearchProvider;
4112 use serde_json::json;
4113 use std::time::{Duration, Instant};
4114
4115 #[test]
4116 fn provider_native_receives_dedicated_budget_without_extending_fallback() {
4117 let requested = Duration::from_millis(15_000);
4118 let (total, first, fallback) =
4119 search_timeout_budgets(BackendId::ProviderNative, requested, None);
4120
4121 assert_eq!(total, Duration::from_millis(60_000));
4122 assert_eq!(first, Some(Duration::from_millis(45_000)));
4123 assert_eq!(fallback, Some(requested));
4124
4125 let (total, first, fallback) = search_timeout_budgets(
4126 BackendId::ProviderNative,
4127 requested,
4128 Some(Duration::from_millis(KIMI_K3_FORMULA_MIN_TIMEOUT_MS)),
4129 );
4130 assert_eq!(total, Duration::from_millis(195_000));
4131 assert_eq!(first, Some(Duration::from_millis(180_000)));
4132 assert_eq!(fallback, Some(requested));
4133 }
4134
4135 #[test]
4136 fn provider_native_budget_covers_the_requested_answer_length() {
4137 // #6508: native search asks for up to 8,192 output tokens in one
4138 // non-streaming request. The attempt must outlast generating them at
4139 // the assumed rate, or a long answer times out instead of arriving.
4140 let requested = Duration::from_millis(15_000);
4141 for tokens in [128_u32, 2_048, 4_096, 8_192] {
4142 let floor = native_answer_time_budget(tokens);
4143 let generation = Duration::from_millis(
4144 u64::from(tokens) * 1_000 / super::NATIVE_SEARCH_ASSUMED_TOKENS_PER_SEC,
4145 );
4146 assert!(floor >= generation, "{tokens} tokens: {floor:?}");
4147 let (total, first, fallback) =
4148 search_timeout_budgets(BackendId::ProviderNative, requested, Some(floor));
4149 let first = first.expect("provider-native gets a dedicated attempt");
4150 assert!(first >= floor, "{tokens} tokens: attempt {first:?}");
4151 // The minimum never drops below the pre-#6508 floor.
4152 assert!(first >= Duration::from_millis(45_000));
4153 assert_eq!(total, first + requested);
4154 assert_eq!(fallback, Some(requested));
4155 }
4156 // 8,192 tokens at 40/s plus the round-trip allowance: ~4 minutes.
4157 assert_eq!(
4158 native_answer_time_budget(8_192),
4159 Duration::from_millis(234_800)
4160 );
4161 }
4162
4163 #[test]
4164 fn provider_native_floor_follows_what_the_client_requests() {
4165 use codewhale_runtime::config::{Config, ProviderConfig, ProvidersConfig};
4166 let config = {
4167 let __cw_config_init_0_0 = Some("anthropic".to_string());
4168 let __cw_config_init_0_1 = Some(ProvidersConfig {
4169 anthropic: ProviderConfig {
4170 api_key: Some("anthropic-test-key".to_string()),
4171 base_url: Some("https://api.anthropic.com".to_string()),
4172 model: Some("claude-opus-4-8".to_string()),
4173 ..ProviderConfig::default()
4174 },
4175 ..ProvidersConfig::default()
4176 });
4177 let mut __cw_config_init_0_value: Config = Config::default();
4178 __cw_config_init_0_value.provider = __cw_config_init_0_0;
4179 __cw_config_init_0_value.providers = __cw_config_init_0_1;
4180 __cw_config_init_0_value
4181 };
4182 let client = crate::client::ProviderNativeSearchClient::new(
4183 crate::client::CodewhaleClient::new(&config).expect("Anthropic client"),
4184 )
4185 .expect("Anthropic native adapter");
4186 let tokens = client
4187 .requested_answer_output_tokens()
4188 .expect("Anthropic requests an explicit answer length");
4189 assert!(tokens > 2_048, "catalogued model asks for more: {tokens}");
4190 assert_eq!(
4191 super::provider_native_timeout_floor(&client),
4192 Some(native_answer_time_budget(tokens))
4193 );
4194 }
4195
4196 #[test]
4197 fn doctor_search_probe_targets_cover_every_builtin_provider() {
4198 let cases = [
4199 (SearchProvider::Bing, "https://www.bing.com/search"),
4200 (
4201 SearchProvider::DuckDuckGo,
4202 "https://html.duckduckgo.com/html/",
4203 ),
4204 (
4205 SearchProvider::Firecrawl,
4206 "https://api.firecrawl.dev/v2/search",
4207 ),
4208 (SearchProvider::Tavily, "https://api.tavily.com/search"),
4209 (
4210 SearchProvider::Bocha,
4211 "https://api.bochaai.com/v1/web-search",
4212 ),
4213 (SearchProvider::Metaso, "https://metaso.cn/api/v1"),
4214 (
4215 SearchProvider::Baidu,
4216 "https://qianfan.baidubce.com/v2/ai_search/web_search",
4217 ),
4218 (
4219 SearchProvider::Volcengine,
4220 "https://ark.cn-beijing.volces.com/api/v3/responses",
4221 ),
4222 (SearchProvider::Sofya, "https://sofya.co/v1/search"),
4223 (SearchProvider::Serply, "https://api.serply.io/v1/search"),
4224 (
4225 SearchProvider::DeepSeek,
4226 "https://api.deepseek.com/v1/tools/search",
4227 ),
4228 (
4229 SearchProvider::SearchApi,
4230 "https://www.searchapi.io/api/v1/search",
4231 ),
4232 ];
4233
4234 for (provider, expected) in cases {
4235 let target = search_probe_target(provider, None).expect("built-in target");
4236 assert_eq!(target.url.as_str(), expected, "{provider:?}");
4237 assert_eq!(target.host, target.url.host_str().unwrap(), "{provider:?}");
4238 }
4239 }
4240
4241 #[test]
4242 fn doctor_search_probe_strips_every_secret_capable_custom_url_component() {
4243 let target = search_probe_target(
4244 SearchProvider::Searxng,
4245 Some(
4246 "https://URL-USER:URL-PASSWORD@search.example:8443/private/URL-PATH?URL-QUERY=secret#URL-FRAGMENT",
4247 ),
4248 )
4249 .expect("credential-free target");
4250
4251 assert_eq!(target.url.as_str(), "https://search.example:8443/");
4252 assert_eq!(target.host, "search.example");
4253 }
4254
4255 #[test]
4256 fn doctor_search_probe_rejects_configuration_that_runtime_cannot_use() {
4257 assert_eq!(
4258 search_probe_target(SearchProvider::Searxng, None),
4259 Err(SearchProbeTargetError::Missing)
4260 );
4261 assert_eq!(
4262 search_probe_target(SearchProvider::Tavily, Some("https://ignored.example")),
4263 Err(SearchProbeTargetError::Unsupported)
4264 );
4265 assert_eq!(
4266 search_probe_target(SearchProvider::DuckDuckGo, Some("file:///tmp/search")),
4267 Err(SearchProbeTargetError::Invalid)
4268 );
4269 }
4270
4271 #[test]
4272 fn bing_ckurl_with_html_entities_decodes_real_url() {
4273 let href = "https://www.bing.com/ck/a?!&amp;&amp;p=abc&amp;u=a1aHR0cHM6Ly9ydXN0LWxhbmcub3JnLw&amp;ntb=1";
4274 assert_eq!(normalize_bing_url(href), "https://rust-lang.org/");
4275 }
4276
4277 #[test]
4278 fn decode_html_entities_handles_named_entities() {
4279 assert_eq!(decode_html_entities("&amp;"), "&");
4280 assert_eq!(decode_html_entities("&lt;"), "<");
4281 assert_eq!(decode_html_entities("&gt;"), ">");
4282 assert_eq!(decode_html_entities("&quot;"), "\"");
4283 assert_eq!(decode_html_entities("&apos;"), "'");
4284 assert_eq!(decode_html_entities("&nbsp;"), " ");
4285 assert_eq!(decode_html_entities("&copy;"), "\u{00A9}");
4286 assert_eq!(decode_html_entities("&mdash;"), "\u{2014}");
4287 }
4288
4289 #[test]
4290 fn decode_html_entities_handles_decimal_numeric_references() {
4291 assert_eq!(decode_html_entities("&#65;"), "A");
4292 assert_eq!(decode_html_entities("&#60;"), "<");
4293 assert_eq!(decode_html_entities("&#8211;"), "\u{2013}");
4294 }
4295
4296 #[test]
4297 fn decode_html_entities_handles_hex_numeric_references() {
4298 assert_eq!(decode_html_entities("&#x41;"), "A");
4299 assert_eq!(decode_html_entities("&#x3C;"), "<");
4300 assert_eq!(decode_html_entities("&#x2014;"), "\u{2014}");
4301 }
4302
4303 #[test]
4304 fn decode_html_entities_passthrough_unknown() {
4305 assert_eq!(decode_html_entities("&unknown;"), "&unknown;");
4306 }
4307
4308 #[test]
4309 fn decode_html_entities_mixed_content() {
4310 let input = "Hello &amp; welcome to &quot;Rust&apos;s world&quot; &mdash; enjoy!";
4311 let expected = "Hello & welcome to \"Rust's world\" \u{2014} enjoy!";
4312 assert_eq!(decode_html_entities(input), expected);
4313 }
4314
4315 #[test]
4316 fn extract_search_query_accepts_legacy_query() {
4317 let query =
4318 extract_search_query(&json!({"query": " deepseek v4 "})).expect("query should parse");
4319 assert_eq!(query, "deepseek v4");
4320 }
4321
4322 #[test]
4323 fn extract_search_query_accepts_q_alias() {
4324 let query =
4325 extract_search_query(&json!({"q": "deepseek v4 pro"})).expect("q alias should parse");
4326 assert_eq!(query, "deepseek v4 pro");
4327 }
4328
4329 #[test]
4330 fn extract_search_query_accepts_array_form() {
4331 let input = json!({"search_query": [{"q": "deepseek api", "max_results": 3}]});
4332 let query = extract_search_query(&input).expect("array form should parse");
4333 assert_eq!(query, "deepseek api");
4334 assert_eq!(optional_search_max_results(&input), 3);
4335 }
4336
4337 #[test]
4338 fn extract_search_query_rejects_missing_query() {
4339 let err = extract_search_query(&json!({"max_results": 2}))
4340 .expect_err("missing query should fail");
4341 assert!(format!("{err}").contains("missing required field 'query'"));
4342 }
4343
4344 #[test]
4345 fn optional_max_results_prefers_top_level_value() {
4346 assert_eq!(
4347 optional_search_max_results(
4348 &json!({"query": "x", "max_results": 8, "search_query": [{"q": "y", "max_results": 2}]})
4349 ),
4350 8,
4351 );
4352 }
4353
4354 #[test]
4355 fn optional_max_results_falls_back_to_array_form() {
4356 assert_eq!(
4357 optional_search_max_results(&json!({"search_query": [{"q": "y", "max_results": 3}]})),
4358 3,
4359 );
4360 }
4361
4362 #[test]
4363 fn optional_max_results_uses_default_when_neither_set() {
4364 assert_eq!(optional_search_max_results(&json!({"query": "x"})), 5);
4365 assert_eq!(
4366 optional_search_max_results(&json!({"search_query": [{"q": "y"}]})),
4367 5,
4368 );
4369 }
4370
4371 #[test]
4372 fn optional_max_results_only_reads_first_array_entry() {
4373 assert_eq!(
4374 optional_search_max_results(
4375 &json!({"search_query": [{"q": "first", "max_results": 1}, {"q": "second", "max_results": 9}]})
4376 ),
4377 1,
4378 );
4379 }
4380
4381 #[test]
4382 fn extract_search_query_trims_whitespace_from_array_form_q_alias() {
4383 let q = extract_search_query(&json!({"search_query": [{"q": " deepseek tui "}]}))
4384 .expect("array form should parse with trim");
4385 assert_eq!(q, "deepseek tui");
4386 }
4387
4388 #[test]
4389 fn extract_search_query_rejects_empty_query() {
4390 for body in [json!({"query": ""}), json!({"q": " "}), json!({})] {
4391 let err = extract_search_query(&body).expect_err("empty query must reject");
4392 let msg = format!("{err}");
4393 assert!(
4394 msg.contains("missing required field 'query'") || msg.contains("Query"),
4395 "expected query-missing error, got `{msg}`"
4396 );
4397 }
4398 }
4399
4400 #[test]
4401 fn truncate_error_body_truncates_long_body() {
4402 let body = "a".repeat(ERROR_BODY_PREVIEW_BYTES + 100);
4403 let truncated = truncate_error_body(&body);
4404 assert!(truncated.len() <= ERROR_BODY_PREVIEW_BYTES + 3);
4405 assert!(truncated.ends_with("..."));
4406 }
4407
4408 #[test]
4409 fn truncate_error_body_keeps_short_body_intact() {
4410 let body = "short error";
4411 assert_eq!(truncate_error_body(body), body);
4412 }
4413
4414 #[test]
4415 fn sanitize_error_body_strips_html_and_control_chars() {
4416 let body = "<p>error</p>\x00\x01\x02";
4417 let sanitized = sanitize_error_body(body);
4418 assert_eq!(sanitized, "error");
4419 }
4420
4421 #[test]
4422 fn sanitize_error_body_redacts_bearer_tokens() {
4423 let body = r#"{"error":"bad token","authorization":"Bearer test-token/with+chars="}"#;
4424
4425 let sanitized = sanitize_error_body(body);
4426
4427 assert!(!sanitized.contains("test-token/with+chars="));
4428 assert!(sanitized.contains("Bearer [REDACTED]"));
4429 }
4430
4431 #[test]
4432 fn parse_bocha_web_pages_value_extracts_ranked_results() {
4433 let body = json!({
4434 "code": 200,
4435 "msg": null,
4436 "data": {
4437 "webPages": {
4438 "value": [
4439 {
4440 "name": "广州天气",
4441 "url": "https://bocha.cn/share/weather",
4442 "snippet": "广州今日雷阵雨转晴。"
4443 },
4444 {
4445 "name": "中央气象台",
4446 "url": "https://www.weather.com.cn/",
4447 "summary": "天气实况。"
4448 }
4449 ]
4450 }
4451 }
4452 });
4453
4454 let results = parse_bocha_results(&body, 10);
4455
4456 assert_eq!(results.len(), 2);
4457 assert_eq!(results[0].title, "广州天气");
4458 assert_eq!(results[0].url, "https://bocha.cn/share/weather");
4459 assert_eq!(results[0].snippet.as_deref(), Some("广州今日雷阵雨转晴。"));
4460 assert_eq!(results[1].title, "中央气象台");
4461 }
4462
4463 #[test]
4464 fn parse_bocha_keeps_legacy_pages_shape() {
4465 let body = json!({
4466 "code": 200,
4467 "data": {
4468 "pages": [
4469 {
4470 "title": "Legacy title",
4471 "link": "https://example.com/legacy",
4472 "description": "Legacy description"
4473 }
4474 ]
4475 }
4476 });
4477
4478 let results = parse_bocha_results(&body, 5);
4479
4480 assert_eq!(results.len(), 1);
4481 assert_eq!(results[0].title, "Legacy title");
4482 assert_eq!(results[0].url, "https://example.com/legacy");
4483 assert_eq!(results[0].snippet.as_deref(), Some("Legacy description"));
4484 }
4485
4486 #[test]
4487 fn bocha_error_message_flags_non_success_business_code() {
4488 let body = json!({"code": 401, "msg": "invalid api key"});
4489
4490 let error = bocha_error_message(&body).expect("non-success code should error");
4491
4492 assert!(error.contains("Bocha"));
4493 assert!(error.contains("401"));
4494 assert!(error.contains("invalid api key"));
4495 }
4496
4497 #[test]
4498 fn parse_baidu_references_extracts_ranked_results() {
4499 let body = json!({
4500 "references": [
4501 {
4502 "title": "Rust 官方文档",
4503 "url": "https://www.rust-lang.org/",
4504 "content": "Rust 是一门注重性能和可靠性的语言。"
4505 },
4506 {
4507 "title": "Cargo Book",
4508 "url": "https://doc.rust-lang.org/cargo/",
4509 "snippet": "Cargo is Rust's package manager."
4510 }
4511 ]
4512 });
4513
4514 let results = parse_baidu_results(&body, 10);
4515
4516 assert_eq!(results.len(), 2);
4517 assert_eq!(results[0].title, "Rust 官方文档");
4518 assert_eq!(results[0].url, "https://www.rust-lang.org/");
4519 assert_eq!(
4520 results[0].snippet.as_deref(),
4521 Some("Rust 是一门注重性能和可靠性的语言。")
4522 );
4523 assert_eq!(results[1].title, "Cargo Book");
4524 assert_eq!(results[1].url, "https://doc.rust-lang.org/cargo/");
4525 assert_eq!(
4526 results[1].snippet.as_deref(),
4527 Some("Cargo is Rust's package manager.")
4528 );
4529 }
4530
4531 #[test]
4532 fn parse_baidu_references_skips_incomplete_entries() {
4533 let body = json!({
4534 "references": [
4535 {"title": "No URL", "content": "missing url"},
4536 {"url": "https://example.com/no-title", "content": "missing title"},
4537 {"title": "Valid", "url": "https://example.com/valid"}
4538 ]
4539 });
4540
4541 let results = parse_baidu_results(&body, 10);
4542
4543 assert_eq!(results.len(), 1);
4544 assert_eq!(results[0].title, "Valid");
4545 assert_eq!(results[0].url, "https://example.com/valid");
4546 assert_eq!(results[0].snippet, None);
4547 }
4548
4549 #[test]
4550 fn baidu_search_payload_uses_official_search_source() {
4551 let payload = baidu_search_payload("Rust cargo workspace", 3);
4552
4553 assert_eq!(
4554 payload.get("search_source").and_then(|v| v.as_str()),
4555 Some("baidu_search_v2")
4556 );
4557 assert_eq!(
4558 payload
4559 .get("messages")
4560 .and_then(|v| v.as_array())
4561 .and_then(|messages| messages.first())
4562 .and_then(|message| message.get("content"))
4563 .and_then(|v| v.as_str()),
4564 Some("Rust cargo workspace")
4565 );
4566 assert_eq!(
4567 payload
4568 .get("resource_type_filter")
4569 .and_then(|v| v.as_array())
4570 .and_then(|filters| filters.first())
4571 .and_then(|filter| filter.get("top_k"))
4572 .and_then(|v| v.as_u64()),
4573 Some(3)
4574 );
4575 }
4576
4577 #[test]
4578 fn serply_search_url_encodes_query_and_result_count() {
4579 let url = serply_search_url("rust tui & ratatui", QueryFilters::default(), 7)
4580 .expect("serply url");
4581
4582 assert_eq!(url.host_str(), Some("api.serply.io"));
4583 assert_eq!(url.path(), "/v1/search");
4584 let pairs: Vec<(String, String)> = url
4585 .query_pairs()
4586 .map(|(k, v)| (k.into_owned(), v.into_owned()))
4587 .collect();
4588 assert_eq!(
4589 pairs,
4590 vec![
4591 ("q".to_string(), "rust tui & ratatui".to_string()),
4592 ("num".to_string(), "7".to_string()),
4593 ]
4594 );
4595 }
4596
4597 #[test]
4598 fn parse_deepseek_results_reads_title_url_snippet_and_summary_fallback() {
4599 let body = json!({
4600 "results": [
4601 {
4602 "title": "Ratatui",
4603 "url": "https://ratatui.rs/",
4604 "snippet": "Cook up delicious terminal user interfaces in Rust.",
4605 "summary": "ignored when a snippet is present",
4606 "date": "2026-10-21"
4607 },
4608 {
4609 "title": "Summary only",
4610 "url": "https://example.com/summary",
4611 "snippet": "",
4612 "summary": "Falls back to the summary field."
4613 },
4614 {
4615 "title": "Missing url",
4616 "snippet": "dropped because there is no url"
4617 },
4618 {
4619 "url": "https://example.com/no-title",
4620 "snippet": "dropped because there is no title"
4621 },
4622 "not an object",
4623 {
4624 "title": "Beyond the cap",
4625 "url": "https://example.com/beyond",
4626 "snippet": "beyond max_results"
4627 }
4628 ]
4629 });
4630
4631 let results = parse_deepseek_results(&body, 2);
4632
4633 assert_eq!(results.len(), 2);
4634 assert_eq!(results[0].rank, 1);
4635 assert_eq!(results[0].title, "Ratatui");
4636 assert_eq!(results[0].url, "https://ratatui.rs/");
4637 assert_eq!(
4638 results[0].snippet.as_deref(),
4639 Some("Cook up delicious terminal user interfaces in Rust.")
4640 );
4641 assert_eq!(results[0].published.as_deref(), Some("2026-10-21"));
4642 assert_eq!(results[1].rank, 2);
4643 assert_eq!(results[1].url, "https://example.com/summary");
4644 assert_eq!(
4645 results[1].snippet.as_deref(),
4646 Some("Falls back to the summary field.")
4647 );
4648 assert_eq!(results[1].published, None);
4649
4650 assert!(parse_deepseek_results(&json!({}), 5).is_empty());
4651 assert!(parse_deepseek_results(&json!({"results": []}), 5).is_empty());
4652 }
4653
4654 #[test]
4655 fn parse_serply_results_reads_link_and_description_and_skips_malformed_rows() {
4656 let body = json!({
4657 "results": [
4658 {
4659 "title": "Ratatui",
4660 "link": "https://ratatui.rs/",
4661 "description": "Cook up delicious terminal user interfaces in Rust.",
4662 "position": 1,
4663 "realPosition": 1
4664 },
4665 {
4666 "title": "No description",
4667 "link": "https://example.com/plain",
4668 "description": ""
4669 },
4670 {
4671 "title": "Missing link",
4672 "description": "dropped because there is no link"
4673 },
4674 "not an object",
4675 {
4676 "title": "Fourth",
4677 "link": "https://example.com/fourth",
4678 "description": "beyond max_results"
4679 }
4680 ],
4681 "knowledge_graph": {"title": "ignored sidebar"},
4682 "related_questions": [{"question": "ignored"}],
4683 "ads": [{"title": "ignored ad", "link": "https://ads.example.com"}]
4684 });
4685
4686 let results = parse_serply_results(&body, 2);
4687
4688 assert_eq!(results.len(), 2);
4689 assert_eq!(results[0].title, "Ratatui");
4690 assert_eq!(results[0].url, "https://ratatui.rs/");
4691 assert_eq!(
4692 results[0].snippet.as_deref(),
4693 Some("Cook up delicious terminal user interfaces in Rust.")
4694 );
4695 assert_eq!(results[1].url, "https://example.com/plain");
4696 assert_eq!(results[1].snippet, None);
4697
4698 assert!(parse_serply_results(&json!({"total": 0}), 5).is_empty());
4699 }
4700
4701 #[test]
4702 fn searchapi_search_url_encodes_query_engine_and_result_count() {
4703 let url = searchapi_search_url("rust tui & ratatui", QueryFilters::default(), 7)
4704 .expect("searchapi url");
4705
4706 assert_eq!(url.host_str(), Some("www.searchapi.io"));
4707 assert_eq!(url.path(), "/api/v1/search");
4708 let pairs: Vec<(String, String)> = url
4709 .query_pairs()
4710 .map(|(k, v)| (k.into_owned(), v.into_owned()))
4711 .collect();
4712 assert_eq!(
4713 pairs,
4714 vec![
4715 ("q".to_string(), "rust tui & ratatui".to_string()),
4716 ("engine".to_string(), "google".to_string()),
4717 ("num".to_string(), "7".to_string()),
4718 ]
4719 );
4720 }
4721
4722 #[test]
4723 fn parse_searchapi_results_reads_link_and_snippet_and_treats_no_organic_rows_as_empty() {
4724 let body = json!({
4725 "search_metadata": {"status": "Success"},
4726 "search_parameters": {"engine": "google", "q": "ratatui", "num": 10},
4727 "organic_results": [
4728 {
4729 "position": 1,
4730 "title": "Ratatui",
4731 "link": "https://ratatui.rs/",
4732 "domain": "ratatui.rs",
4733 "displayed_link": "https://ratatui.rs",
4734 "snippet": "Cook up delicious terminal user interfaces in Rust.",
4735 "date": "May 19, 2026"
4736 },
4737 {
4738 "position": 2,
4739 "title": "Redirected result",
4740 "link": "https://www.google.com/goto?url=https://example.com/redirected",
4741 "snippet": ""
4742 },
4743 {
4744 "title": "Missing link",
4745 "snippet": "dropped because there is no link"
4746 },
4747 "not an object",
4748 {
4749 "position": 3,
4750 "title": "Fourth",
4751 "link": "https://example.com/fourth",
4752 "snippet": "beyond max_results"
4753 }
4754 ],
4755 "knowledge_graph": {"title": "ignored sidebar"},
4756 "related_searches": [{"query": "ignored"}],
4757 "ads": [{"title": "ignored ad", "link": "https://ads.example.com"}]
4758 });
4759
4760 let results = parse_searchapi_results(&body, 2);
4761
4762 assert_eq!(results.len(), 2);
4763 assert_eq!(results[0].title, "Ratatui");
4764 assert_eq!(results[0].url, "https://ratatui.rs/");
4765 assert_eq!(
4766 results[0].snippet.as_deref(),
4767 Some("Cook up delicious terminal user interfaces in Rust.")
4768 );
4769 assert_eq!(
4770 results[1].url,
4771 "https://www.google.com/goto?url=https://example.com/redirected"
4772 );
4773 assert_eq!(results[1].snippet, None);
4774
4775 let no_results = json!({
4776 "search_metadata": {"status": "Success"},
4777 "search_parameters": {"engine": "google", "q": "nothing matches this"},
4778 "error": "Google didn't return any results."
4779 });
4780 assert!(parse_searchapi_results(&no_results, 5).is_empty());
4781 assert!(parse_searchapi_results(&json!({"error": "Invalid API key."}), 5).is_empty());
4782 }
4783
4784 #[test]
4785 fn parse_sofya_results_falls_back_to_description_for_empty_content() {
4786 let body = json!({
4787 "results": [
4788 {
4789 "title": "Full content",
4790 "url": "https://example.com/full",
4791 "content": "full extracted page content",
4792 "description": "unused description"
4793 },
4794 {
4795 "title": "Null content",
4796 "url": "https://example.com/null",
4797 "content": null,
4798 "description": "description for null content"
4799 },
4800 {
4801 "title": "Empty content",
4802 "url": "https://example.com/empty",
4803 "content": "",
4804 "description": "description for empty content"
4805 },
4806 {
4807 "title": "Whitespace content",
4808 "url": "https://example.com/blank",
4809 "content": " ",
4810 "description": "description for blank content"
4811 },
4812 {
4813 "title": "No snippet",
4814 "url": "https://example.com/no-snippet"
4815 }
4816 ]
4817 });
4818
4819 let results = parse_sofya_results(&body, 10);
4820
4821 assert_eq!(results.len(), 5);
4822 assert_eq!(
4823 results[0].snippet.as_deref(),
4824 Some("full extracted page content")
4825 );
4826 assert_eq!(
4827 results[1].snippet.as_deref(),
4828 Some("description for null content")
4829 );
4830 assert_eq!(
4831 results[2].snippet.as_deref(),
4832 Some("description for empty content")
4833 );
4834 assert_eq!(
4835 results[3].snippet.as_deref(),
4836 Some("description for blank content")
4837 );
4838 assert_eq!(results[4].snippet, None);
4839 }
4840
4841 #[test]
4842 fn tavily_metaso_and_volcengine_payloads_use_normalized_entry_shape() {
4843 let tavily = parse_tavily_results(
4844 &json!({"results": [{
4845 "title": " Tavily result ",
4846 "url": "https://tavily.example/result",
4847 "content": " content "
4848 }]}),
4849 5,
4850 );
4851 let metaso = parse_metaso_results(
4852 &json!({"webpages": [{
4853 "title": " Metaso result ",
4854 "link": "https://metaso.example/result",
4855 "summary": " summary "
4856 }]}),
4857 5,
4858 );
4859 let volcengine = parse_volcengine_results(
4860 r#"{"results":[{"title":"Volcengine result","url":"https://volc.example/result","snippet":"summary"}]}"#,
4861 5,
4862 );
4863
4864 for (entries, title, snippet) in [
4865 (tavily, "Tavily result", "content"),
4866 (metaso, "Metaso result", "summary"),
4867 (volcengine, "Volcengine result", "summary"),
4868 ] {
4869 assert_eq!(entries.len(), 1);
4870 assert_eq!(entries[0].title, title);
4871 assert_eq!(entries[0].snippet.as_deref(), Some(snippet));
4872 }
4873 }
4874
4875 #[tokio::test]
4876 async fn firecrawl_keyless_request_is_headerless_and_keyed_request_is_explicit() {
4877 use wiremock::matchers::{method, path};
4878 use wiremock::{Mock, MockServer, ResponseTemplate};
4879
4880 let server = MockServer::start().await;
4881 Mock::given(method("POST"))
4882 .and(path("/v2/search"))
4883 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
4884 "success": true,
4885 "data": {"web": [{
4886 "title": "Firecrawl result",
4887 "url": "https://example.com/firecrawl",
4888 "description": "x".repeat(1_200)
4889 }]}
4890 })))
4891 .mount(&server)
4892 .await;
4893 let endpoint = format!("{}/v2/search", server.uri());
4894 let (entries, mode) = WebSearchTool
4895 .run_firecrawl_search_at(
4896 &endpoint,
4897 "codewhale",
4898 QueryFilters::default(),
4899 5,
4900 5_000,
4901 None,
4902 )
4903 .await
4904 .expect("keyless Firecrawl search");
4905 WebSearchTool
4906 .run_firecrawl_search_at(
4907 &endpoint,
4908 "codewhale",
4909 QueryFilters::default(),
4910 5,
4911 5_000,
4912 Some("fc-secret"),
4913 )
4914 .await
4915 .expect("authenticated Firecrawl search");
4916 let requests = server.received_requests().await.expect("recorded requests");
4917 let payload: serde_json::Value =
4918 serde_json::from_slice(&requests[0].body).expect("request JSON");
4919
4920 assert_eq!(entries[0].title, "Firecrawl result");
4921 assert_eq!(entries[0].url, "https://example.com/firecrawl");
4922 assert_eq!(
4923 entries[0].snippet.as_deref().unwrap().chars().count(),
4924 1_000
4925 );
4926 assert_eq!(mode, "Firecrawl keyless");
4927 assert!(requests[0].headers.get("authorization").is_none());
4928 assert_eq!(requests[1].headers["authorization"], "Bearer fc-secret");
4929 assert!(payload.get("integration").is_none());
4930 assert_eq!(payload["sources"][0]["type"], "web");
4931 }
4932
4933 #[tokio::test]
4934 async fn firecrawl_keyless_rate_limit_is_actionable() {
4935 use wiremock::matchers::{method, path};
4936 use wiremock::{Mock, MockServer, ResponseTemplate};
4937
4938 let server = MockServer::start().await;
4939 Mock::given(method("POST"))
4940 .and(path("/v2/search"))
4941 .respond_with(ResponseTemplate::new(429))
4942 .mount(&server)
4943 .await;
4944 let error = WebSearchTool
4945 .run_firecrawl_search_at(
4946 &format!("{}/v2/search", server.uri()),
4947 "quota",
4948 QueryFilters::default(),
4949 5,
4950 5_000,
4951 None,
4952 )
4953 .await
4954 .expect_err("429 must be actionable");
4955 assert!(error.to_string().contains("keyless quota is exhausted"));
4956 assert!(error.to_string().contains("FIRECRAWL_API_KEY"));
4957 }
4958
4959 #[test]
4960 fn volcengine_extract_text_skips_non_text_content_blocks() {
4961 let body = json!({
4962 "output": [
4963 {
4964 "type": "message",
4965 "content": [
4966 {"type": "reasoning", "summary": "thinking first"},
4967 {"type": "output_text", "text": "{\"results\":[]}"}
4968 ]
4969 }
4970 ]
4971 });
4972
4973 assert_eq!(
4974 volcengine_extract_text(&body).as_deref(),
4975 Some("{\"results\":[]}")
4976 );
4977 }
4978
4979 #[tokio::test]
4980 async fn volcengine_model_search_waits_for_runtime_chat_ownership() {
4981 let ownership = crate::client::acquire_runtime_chat_inference_ownership().await;
4982 let mut participant =
4983 tokio::spawn(async { acquire_model_backed_search_inference_participant().await });
4984 assert!(
4985 tokio::time::timeout(std::time::Duration::from_millis(40), &mut participant)
4986 .await
4987 .is_err(),
4988 "model-backed web search must wait behind Runtime Chat ownership"
4989 );
4990 drop(ownership);
4991 let permit = tokio::time::timeout(std::time::Duration::from_secs(1), participant)
4992 .await
4993 .expect("model-backed search resumes after relay settlement")
4994 .expect("model-backed search participant task");
4995 drop(permit);
4996 }
4997
4998 #[tokio::test]
4999 async fn baidu_provider_without_api_key_surfaces_clear_error_not_silent_fallback() {
5000 use crate::tools::spec::{ToolContext, ToolSpec};
5001 use codewhale_runtime::config::SearchProvider;
5002
5003 let _env = crate::test_support::lock_test_env();
5004 let _baidu_key = crate::test_support::EnvVarGuard::remove("BAIDU_SEARCH_API_KEY");
5005
5006 let tmp = tempfile::tempdir().expect("tempdir");
5007 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5008 ctx.search_provider = SearchProvider::Baidu;
5009 ctx.search_api_key = None;
5010 let err = WebSearchTool
5011 .execute(json!({"query": "anything"}), &ctx)
5012 .await
5013 .expect_err("missing api_key must surface as ToolError");
5014
5015 let msg = err.to_string();
5016 assert!(
5017 msg.contains("Baidu") && msg.contains("API key"),
5018 "error must name the provider and missing key; got `{msg}`"
5019 );
5020 }
5021
5022 #[tokio::test]
5023 #[allow(clippy::await_holding_lock)]
5024 async fn serply_missing_key_is_fail_closed_inside_the_backend_chain() {
5025 use crate::tools::spec::ToolContext;
5026
5027 let _guard = crate::test_support::lock_test_env();
5028 let prev = std::env::var_os("SERPLY_API_KEY");
5029 unsafe { std::env::remove_var("SERPLY_API_KEY") };
5030
5031 let tmp = tempfile::tempdir().expect("tempdir");
5032 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5033 ctx.search_api_key = None;
5034 let err = WebSearchTool
5035 .run_serply_search("anything", QueryFilters::default(), 5, 1_000, &ctx)
5036 .await
5037 .expect_err("missing api_key must be an error");
5038
5039 match prev {
5040 Some(value) => unsafe { std::env::set_var("SERPLY_API_KEY", value) },
5041 None => unsafe { std::env::remove_var("SERPLY_API_KEY") },
5042 }
5043
5044 // A configured Serply route that reaches the adapter after a failed
5045 // provider-native attempt must stop the chain, not degrade to DuckDuckGo.
5046 assert!(
5047 matches!(
5048 err.error,
5049 crate::tools::spec::ToolError::InvalidInput { .. }
5050 ),
5051 "missing key must be classified fail-closed; got `{err:?}`"
5052 );
5053 }
5054
5055 #[tokio::test]
5056 #[allow(clippy::await_holding_lock)]
5057 async fn serply_provider_without_api_key_surfaces_clear_error_not_silent_fallback() {
5058 use crate::tools::spec::{ToolContext, ToolSpec};
5059 use codewhale_runtime::config::SearchProvider;
5060
5061 let _guard = crate::test_support::lock_test_env();
5062 let prev = std::env::var_os("SERPLY_API_KEY");
5063 unsafe { std::env::remove_var("SERPLY_API_KEY") };
5064
5065 let tmp = tempfile::tempdir().expect("tempdir");
5066 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5067 ctx.search_provider = SearchProvider::Serply;
5068 ctx.search_api_key = None;
5069 let err = WebSearchTool
5070 .execute(json!({"query": "anything"}), &ctx)
5071 .await
5072 .expect_err("missing api_key must surface as ToolError");
5073
5074 match prev {
5075 Some(value) => unsafe { std::env::set_var("SERPLY_API_KEY", value) },
5076 None => unsafe { std::env::remove_var("SERPLY_API_KEY") },
5077 }
5078
5079 let msg = err.to_string();
5080 assert!(
5081 msg.contains("Serply") && msg.contains("API key"),
5082 "error must name the provider and missing key; got `{msg}`"
5083 );
5084 }
5085
5086 #[tokio::test]
5087 #[allow(clippy::await_holding_lock)]
5088 async fn searchapi_missing_key_is_fail_closed_inside_the_backend_chain() {
5089 use crate::tools::spec::ToolContext;
5090
5091 let _guard = crate::test_support::lock_test_env();
5092 let prev = std::env::var_os("SEARCHAPI_API_KEY");
5093 unsafe { std::env::remove_var("SEARCHAPI_API_KEY") };
5094
5095 let tmp = tempfile::tempdir().expect("tempdir");
5096 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5097 ctx.search_api_key = None;
5098 let err = WebSearchTool
5099 .run_searchapi_search("anything", QueryFilters::default(), 5, 1_000, &ctx)
5100 .await
5101 .expect_err("missing api_key must be an error");
5102
5103 match prev {
5104 Some(value) => unsafe { std::env::set_var("SEARCHAPI_API_KEY", value) },
5105 None => unsafe { std::env::remove_var("SEARCHAPI_API_KEY") },
5106 }
5107
5108 assert!(
5109 matches!(
5110 err.error,
5111 crate::tools::spec::ToolError::InvalidInput { .. }
5112 ),
5113 "missing key must be classified fail-closed; got `{err:?}`"
5114 );
5115 }
5116
5117 #[tokio::test]
5118 #[allow(clippy::await_holding_lock)]
5119 async fn searchapi_provider_without_api_key_surfaces_clear_error_not_silent_fallback() {
5120 use crate::tools::spec::{ToolContext, ToolSpec};
5121 use codewhale_runtime::config::SearchProvider;
5122
5123 let _guard = crate::test_support::lock_test_env();
5124 let prev = std::env::var_os("SEARCHAPI_API_KEY");
5125 unsafe { std::env::remove_var("SEARCHAPI_API_KEY") };
5126
5127 let tmp = tempfile::tempdir().expect("tempdir");
5128 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5129 ctx.search_provider = SearchProvider::SearchApi;
5130 ctx.search_api_key = None;
5131 let err = WebSearchTool
5132 .execute(json!({"query": "anything"}), &ctx)
5133 .await
5134 .expect_err("missing api_key must surface as ToolError");
5135
5136 match prev {
5137 Some(value) => unsafe { std::env::set_var("SEARCHAPI_API_KEY", value) },
5138 None => unsafe { std::env::remove_var("SEARCHAPI_API_KEY") },
5139 }
5140
5141 let msg = err.to_string();
5142 assert!(
5143 msg.contains("SearchApi") && msg.contains("API key"),
5144 "error must name the provider and missing key; got `{msg}`"
5145 );
5146 }
5147
5148 #[tokio::test]
5149 #[allow(clippy::await_holding_lock)]
5150 async fn sofya_provider_without_api_key_surfaces_clear_error_not_silent_fallback() {
5151 use crate::tools::spec::{ToolContext, ToolSpec};
5152 use codewhale_runtime::config::SearchProvider;
5153
5154 let _guard = crate::test_support::lock_test_env();
5155 let prev = std::env::var_os("SOFYA_API_KEY");
5156 unsafe { std::env::remove_var("SOFYA_API_KEY") };
5157
5158 let tmp = tempfile::tempdir().expect("tempdir");
5159 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5160 ctx.search_provider = SearchProvider::Sofya;
5161 ctx.search_api_key = None;
5162 let err = WebSearchTool
5163 .execute(json!({"query": "anything"}), &ctx)
5164 .await
5165 .expect_err("missing api_key must surface as ToolError");
5166
5167 match prev {
5168 Some(value) => unsafe { std::env::set_var("SOFYA_API_KEY", value) },
5169 None => unsafe { std::env::remove_var("SOFYA_API_KEY") },
5170 }
5171
5172 let msg = err.to_string();
5173 assert!(
5174 msg.contains("Sofya") && msg.contains("API key"),
5175 "error must name the provider and missing key; got `{msg}`"
5176 );
5177 }
5178
5179 #[tokio::test]
5180 #[allow(clippy::await_holding_lock)]
5181 async fn volcengine_provider_without_api_key_lists_supported_env_fallbacks() {
5182 use crate::tools::spec::{ToolContext, ToolSpec};
5183 use codewhale_runtime::config::SearchProvider;
5184
5185 let _guard = crate::test_support::lock_test_env();
5186 let prev_volc = std::env::var_os("VOLCENGINE_API_KEY");
5187 let prev_volc_ark = std::env::var_os("VOLCENGINE_ARK_API_KEY");
5188 let prev_ark = std::env::var_os("ARK_API_KEY");
5189 unsafe {
5190 std::env::remove_var("VOLCENGINE_API_KEY");
5191 std::env::remove_var("VOLCENGINE_ARK_API_KEY");
5192 std::env::remove_var("ARK_API_KEY");
5193 }
5194
5195 let tmp = tempfile::tempdir().expect("tempdir");
5196 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5197 ctx.search_provider = SearchProvider::Volcengine;
5198 ctx.search_api_key = None;
5199 let err = WebSearchTool
5200 .execute(json!({"query": "anything"}), &ctx)
5201 .await
5202 .expect_err("missing api_key must surface as ToolError");
5203
5204 match prev_volc {
5205 Some(value) => unsafe { std::env::set_var("VOLCENGINE_API_KEY", value) },
5206 None => unsafe { std::env::remove_var("VOLCENGINE_API_KEY") },
5207 }
5208 match prev_volc_ark {
5209 Some(value) => unsafe { std::env::set_var("VOLCENGINE_ARK_API_KEY", value) },
5210 None => unsafe { std::env::remove_var("VOLCENGINE_ARK_API_KEY") },
5211 }
5212 match prev_ark {
5213 Some(value) => unsafe { std::env::set_var("ARK_API_KEY", value) },
5214 None => unsafe { std::env::remove_var("ARK_API_KEY") },
5215 }
5216
5217 let msg = err.to_string();
5218 assert!(msg.contains("Volcengine") && msg.contains("API key"));
5219 assert!(msg.contains("VOLCENGINE_API_KEY"));
5220 assert!(msg.contains("VOLCENGINE_ARK_API_KEY"));
5221 assert!(msg.contains("ARK_API_KEY"));
5222 assert!(!msg.contains("DEEPSEEK_SEARCH_API_KEY"));
5223 }
5224
5225 #[tokio::test]
5226 #[allow(clippy::await_holding_lock)]
5227 async fn metaso_provider_without_api_key_fails_closed_before_fallback() {
5228 use crate::tools::spec::{ToolContext, ToolSpec};
5229 use codewhale_runtime::config::SearchProvider;
5230
5231 let _guard = crate::test_support::lock_test_env();
5232 let previous = std::env::var_os("METASO_API_KEY");
5233 unsafe { std::env::remove_var("METASO_API_KEY") };
5234
5235 let tmp = tempfile::tempdir().expect("tempdir");
5236 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5237 ctx.search_provider = SearchProvider::Metaso;
5238 ctx.search_api_key = None;
5239 let error = WebSearchTool
5240 .execute(json!({"query": "anything"}), &ctx)
5241 .await
5242 .expect_err("missing Metaso key must fail before the fallback chain");
5243
5244 match previous {
5245 Some(value) => unsafe { std::env::set_var("METASO_API_KEY", value) },
5246 None => unsafe { std::env::remove_var("METASO_API_KEY") },
5247 }
5248
5249 let message = error.to_string();
5250 assert!(
5251 message.contains("Metaso")
5252 && message.contains("API key")
5253 && message.contains("METASO_API_KEY"),
5254 "got `{message}`"
5255 );
5256 assert!(
5257 !message.contains("duckduckgo"),
5258 "missing configuration must not cross providers: `{message}`"
5259 );
5260 }
5261
5262 #[test]
5263 fn duckduckgo_compatible_url_uses_custom_base_url_and_preserves_query() {
5264 let (url, host) = duckduckgo_search_url(
5265 Some("https://search.internal.example/html/?region=us"),
5266 "rust async",
5267 None,
5268 )
5269 .expect("custom duckduckgo-compatible url");
5270
5271 assert_eq!(host, "search.internal.example");
5272 assert_eq!(
5273 url,
5274 "https://search.internal.example/html/?region=us&q=rust+async"
5275 );
5276 }
5277
5278 #[test]
5279 fn custom_duckduckgo_endpoint_disables_public_bing_fallback() {
5280 assert!(super::duckduckgo_allows_bing_fallback(None));
5281 assert!(super::duckduckgo_allows_bing_fallback(Some(" ")));
5282 assert!(!super::duckduckgo_allows_bing_fallback(Some(
5283 "https://search.internal.example/html/"
5284 )));
5285 }
5286
5287 #[test]
5288 fn bing_locale_params_follow_explicit_locale() {
5289 let (params, accept_language) = scrape_locale_params(Some("zh-CN"), "rust async");
5290 assert_eq!(
5291 params,
5292 vec![
5293 ("mkt".to_string(), "zh-CN".to_string()),
5294 ("setlang".to_string(), "zh-Hans".to_string()),
5295 ]
5296 );
5297 assert_eq!(accept_language, "zh-CN,zh;q=0.9,en;q=0.8");
5298
5299 let (params, accept_language) = scrape_locale_params(Some("en-US"), "rust async");
5300 assert_eq!(
5301 params,
5302 vec![
5303 ("mkt".to_string(), "en-US".to_string()),
5304 ("setlang".to_string(), "en".to_string()),
5305 ]
5306 );
5307 assert_eq!(accept_language, "en-US,en;q=0.9");
5308
5309 // Bing's setlang table keys the Chinese script off the region:
5310 // Taiwan/Hong Kong/Macao are Traditional, everything else (including
5311 // the Han-heuristic default) is Simplified.
5312 let (params, _) = scrape_locale_params(Some("zh-TW"), "rust async");
5313 assert_eq!(params[1].1, "zh-Hant");
5314 let (params, _) = scrape_locale_params(Some("zh-HK"), "rust async");
5315 assert_eq!(params[1].1, "zh-Hant");
5316 }
5317
5318 #[test]
5319 fn bing_locale_params_fall_back_to_china_market_for_han_queries() {
5320 // Without this fallback a locale-less Chinese query used to get no
5321 // market hint plus an English Accept-Language, and Bing served
5322 // unrelated Japanese results.
5323 let (params, accept_language) = scrape_locale_params(None, "凹语言 编程");
5324 assert_eq!(
5325 params,
5326 vec![
5327 ("mkt".to_string(), "zh-CN".to_string()),
5328 ("setlang".to_string(), "zh-Hans".to_string()),
5329 ]
5330 );
5331 assert_eq!(accept_language, "zh-CN,zh;q=0.9,en;q=0.8");
5332 }
5333
5334 #[test]
5335 fn bing_locale_params_keep_english_default_without_locale_signal() {
5336 let (params, accept_language) = scrape_locale_params(None, "rust async");
5337 assert!(params.is_empty());
5338 assert_eq!(accept_language, "en-US,en;q=0.9");
5339 }
5340
5341 #[test]
5342 fn bing_locale_params_normalize_underscore_separators() {
5343 // The model often writes `zh_CN`; the underscore must not leak into
5344 // the `mkt` parameter or the `Accept-Language` ranges.
5345 let (params, accept_language) = scrape_locale_params(Some("zh_CN"), "rust async");
5346 assert_eq!(
5347 params,
5348 vec![
5349 ("mkt".to_string(), "zh-CN".to_string()),
5350 ("setlang".to_string(), "zh-Hans".to_string()),
5351 ]
5352 );
5353 assert_eq!(accept_language, "zh-CN,zh;q=0.9,en;q=0.8");
5354 }
5355
5356 #[test]
5357 fn bing_setlang_keeps_an_explicit_script_subtag() {
5358 // `zh-Hant-TW` must not degrade to Simplified: the explicit script
5359 // subtag wins over the region-derived default.
5360 let (params, _) = scrape_locale_params(Some("zh-Hant-TW"), "rust async");
5361 assert_eq!(params[1].1, "zh-Hant");
5362 let (params, _) = scrape_locale_params(Some("zh-Hans-CN"), "rust async");
5363 assert_eq!(params[1].1, "zh-Hans");
5364 let (params, _) = scrape_locale_params(Some("zh-Hant"), "rust async");
5365 assert_eq!(params[1].1, "zh-Hant");
5366 }
5367
5368 #[test]
5369 fn ddg_locale_ignored_only_when_an_explicit_locale_yields_no_region() {
5370 // Mapped regions are honored.
5371 assert!(!ddg_locale_was_ignored(Some("zh-CN"), Some("zh-CN")));
5372 // Unmapped but well-formed regions send no `kl`: the receipt must
5373 // not claim the knob was honored.
5374 assert!(ddg_locale_was_ignored(Some("fr-FR"), Some("fr-FR")));
5375 // Malformed values resolve no market at all.
5376 assert!(ddg_locale_was_ignored(Some("zh CN"), None));
5377 // Malformed values stay ignored even when a pure-Han query makes
5378 // scrape_market fall back to the zh-CN market — the shape check is
5379 // independent of the market resolution, matching the Bing leg.
5380 assert!(ddg_locale_was_ignored(Some("zh CN"), Some("zh-CN")));
5381 assert!(ddg_locale_was_ignored(Some("中文"), Some("zh-CN")));
5382 // No explicit locale: the Han fallback is the tool's own choice,
5383 // never a dropped knob.
5384 assert!(!ddg_locale_was_ignored(None, Some("zh-CN")));
5385 assert!(!ddg_locale_was_ignored(None, None));
5386 }
5387
5388 #[test]
5389 fn ddg_malformed_locale_with_han_query_receipt_stays_ignored() {
5390 // End-to-end across the DDG leg: a malformed locale plus a pure-Han
5391 // query resolves the zh-CN market via the Han heuristic, but the
5392 // receipt must keep KnobIgnored (honored.locale=false), exactly what
5393 // the Bing leg reports for the same input.
5394 let locale = Some("中文");
5395 let han_query = "凹语言 编程";
5396 let market = scrape_market(locale, han_query);
5397 assert_eq!(market.as_deref(), Some("zh-CN"));
5398 let degraded: Vec<DegradedReason> = if ddg_locale_was_ignored(locale, market.as_deref()) {
5399 vec![DegradedReason::KnobIgnored {
5400 knob: QueryKnob::Locale,
5401 }]
5402 } else {
5403 Vec::new()
5404 };
5405 let raw = BackendSearch {
5406 backend: BackendId::DuckDuckGo,
5407 source: "duckduckgo".to_string(),
5408 backend_detail: None,
5409 results: Vec::new(),
5410 degraded,
5411 note: None,
5412 };
5413 let query = SearchQuery::new(
5414 han_query.to_string(),
5415 5,
5416 None,
5417 Vec::new(),
5418 locale.map(str::to_string),
5419 );
5420 let capabilities = QueryCapabilities {
5421 max_results: CapabilityState::Supported,
5422 recency: CapabilityState::Unsupported,
5423 domains: CapabilityState::Unsupported,
5424 locale: CapabilityState::Supported,
5425 published_date: CapabilityState::Unknown,
5426 };
5427 let response = finalize_search_response(query, capabilities, raw, Instant::now());
5428 assert!(
5429 !response.receipt.honored.locale,
5430 "a malformed locale must be receipted as ignored even when the \
5431 Han heuristic supplies a market"
5432 );
5433 assert!(response.receipt.degraded.iter().any(|reason| matches!(
5434 reason,
5435 DegradedReason::KnobIgnored {
5436 knob: QueryKnob::Locale
5437 }
5438 )));
5439
5440 // fr-FR (well-formed, unmapped on the verified kl list) stays
5441 // ignored on the DDG leg, as before the fix.
5442 let market = scrape_market(Some("fr-FR"), "rust async");
5443 assert_eq!(market.as_deref(), Some("fr-FR"));
5444 assert!(ddg_locale_was_ignored(Some("fr-FR"), market.as_deref()));
5445
5446 // A mapped, well-formed value (ja-JP) is honored.
5447 let market = scrape_market(Some("ja-JP"), "rust async");
5448 assert_eq!(market.as_deref(), Some("ja-JP"));
5449 assert!(!ddg_locale_was_ignored(Some("ja-JP"), market.as_deref()));
5450 }
5451
5452 #[test]
5453 fn bing_locale_ignored_only_for_malformed_explicit_values() {
5454 assert!(!bing_locale_was_ignored(Some("zh-CN")));
5455 assert!(!bing_locale_was_ignored(None));
5456 assert!(bing_locale_was_ignored(Some("zh CN")));
5457 assert!(bing_locale_was_ignored(Some("-CN")));
5458 }
5459
5460 #[test]
5461 fn han_detection_covers_han_only_and_ignores_other_cjk_scripts() {
5462 assert!(super::query_contains_han("学 rust"));
5463 assert!(super::query_contains_han("\u{3400}")); // Extension A
5464 assert!(!super::query_contains_han("rust async 123"));
5465 assert!(!super::query_contains_han("ルスト programming")); // Katakana
5466 assert!(!super::query_contains_han("러스트 programming")); // Hangul
5467 }
5468
5469 #[test]
5470 fn duckduckgo_url_adds_kl_for_resolved_market() {
5471 let (url, _) = duckduckgo_search_url(None, "凹语言 编程", Some("zh-CN")).expect("ddg url");
5472 let parsed = reqwest::Url::parse(&url).expect("valid url");
5473 assert_eq!(
5474 parsed.query_pairs().find(|(key, _)| key == "kl").unwrap().1,
5475 "cn-zh"
5476 );
5477
5478 // A locale with no verified kl pair sends no kl at all rather than
5479 // an off-list guess.
5480 let (url, _) = duckduckgo_search_url(None, "rust async", Some("fr-FR")).expect("ddg url");
5481 let parsed = reqwest::Url::parse(&url).expect("valid url");
5482 assert!(parsed.query_pairs().all(|(key, _)| key != "kl"));
5483
5484 let (url, _) = duckduckgo_search_url(None, "rust async", None).expect("ddg url");
5485 let parsed = reqwest::Url::parse(&url).expect("valid url");
5486 assert!(parsed.query_pairs().all(|(key, _)| key != "kl"));
5487 }
5488
5489 #[test]
5490 fn ddg_region_param_translates_only_verified_pairs() {
5491 // DuckDuckGo's kl list is fixed and non-systematic; only pairs
5492 // verified against that list are translated (China, US, Japan,
5493 // Korea, Taiwan, Hong Kong). A mechanical reversal of a BCP 47 tag
5494 // produced off-list junk such as `jp-ja` (the real value is
5495 // `jp-jp`), so anything unverified sends no kl at all.
5496 assert_eq!(ddg_region_param("zh-CN").as_deref(), Some("cn-zh"));
5497 assert_eq!(ddg_region_param("en_US").as_deref(), Some("us-en"));
5498 assert_eq!(ddg_region_param("ja-JP").as_deref(), Some("jp-jp"));
5499 assert_eq!(ddg_region_param("ko-KR").as_deref(), Some("kr-kr"));
5500 assert_eq!(ddg_region_param("zh-TW").as_deref(), Some("tw-tzh"));
5501 assert_eq!(ddg_region_param("zh-HK").as_deref(), Some("hk-tzh"));
5502 // Unverified locales and script/bare tags send no region hint —
5503 // the no-kl request is the historical shape and strictly safer
5504 // than guessing an off-list value.
5505 assert_eq!(ddg_region_param("fr-FR"), None);
5506 assert_eq!(ddg_region_param("zh-Hans"), None);
5507 assert_eq!(ddg_region_param("zh"), None);
5508 // Script+region Chinese tags reduce to their verified region pair:
5509 // the schema teaches BCP 47 where the script subtag is best
5510 // practice for Chinese.
5511 assert_eq!(ddg_region_param("zh-Hans-CN").as_deref(), Some("cn-zh"));
5512 assert_eq!(ddg_region_param("zh-Hant-TW").as_deref(), Some("tw-tzh"));
5513 assert_eq!(ddg_region_param("zh-Hant-HK").as_deref(), Some("hk-tzh"));
5514 }
5515
5516 #[test]
5517 fn bing_fallback_rederives_the_locale_flag_from_bings_rule() {
5518 // A shape-valid locale the DuckDuckGo leg could not map (no kl
5519 // pair) is carried by the Bing fallback through mkt/setlang, so the
5520 // stale DDG-leg flag must not keep the receipt claiming the knob
5521 // was ignored.
5522 let mut degraded = vec![DegradedReason::KnobIgnored {
5523 knob: QueryKnob::Locale,
5524 }];
5525 prune_fallback_locale_ignored(&mut degraded, Some("fr-FR"));
5526 assert!(
5527 !degraded.iter().any(|reason| matches!(
5528 reason,
5529 DegradedReason::KnobIgnored {
5530 knob: QueryKnob::Locale,
5531 }
5532 )),
5533 "the DDG-leg ignored flag must not survive the Bing fallback: \
5534 {degraded:?}"
5535 );
5536 // An implausible tag stays ignored on the fallback too.
5537 let mut degraded = vec![DegradedReason::KnobIgnored {
5538 knob: QueryKnob::Locale,
5539 }];
5540 prune_fallback_locale_ignored(&mut degraded, Some("zh CN"));
5541 assert!(degraded.iter().any(|reason| matches!(
5542 reason,
5543 DegradedReason::KnobIgnored {
5544 knob: QueryKnob::Locale,
5545 }
5546 )));
5547 }
5548
5549 #[test]
5550 fn ddg_accept_language_unifies_with_bing_rule() {
5551 assert_eq!(scrape_accept_language(None), "en-US,en;q=0.9");
5552 assert_eq!(
5553 scrape_accept_language(Some("zh-CN")),
5554 "zh-CN,zh;q=0.9,en;q=0.8"
5555 );
5556 // A bare-language market (reachable through an explicit `locale: en`)
5557 // emits a single range and, like every English market, never appends
5558 // a duplicate `en` fallback.
5559 assert_eq!(scrape_accept_language(Some("en")), "en;q=0.9");
5560 }
5561
5562 #[test]
5563 fn implausible_locale_values_are_treated_as_no_locale() {
5564 // The locale reaches URLs and the Accept-Language header, so a
5565 // malformed model-supplied value keeps the historical no-market
5566 // request instead of becoming a broken tag or header value.
5567 assert_eq!(scrape_market(Some("-CN"), "rust async"), None);
5568 assert_eq!(scrape_market(Some("zh CN"), "rust async"), None);
5569 assert_eq!(scrape_market(Some(""), "rust async"), None);
5570 assert_eq!(scrape_market(Some("zh=CN"), "rust async"), None);
5571 assert_eq!(scrape_market(Some(" "), "rust async"), None);
5572 // Digits are not a language: the primary subtag must be alphabetic,
5573 // or the value would be transmitted (and receipted as honored)
5574 // against schema text promising malformed values are ignored.
5575 assert_eq!(scrape_market(Some("12345"), "rust async"), None);
5576 assert_eq!(scrape_market(Some("en-123456789"), "rust async"), None);
5577 // Well-formed tags survive the shape check verbatim.
5578 assert_eq!(
5579 scrape_market(Some("zh-TW"), "rust async").as_deref(),
5580 Some("zh-TW")
5581 );
5582 // The Han fallback is untouched by the shape check.
5583 assert_eq!(scrape_market(None, "凹语言 编程").as_deref(), Some("zh-CN"));
5584 }
5585
5586 #[test]
5587 fn oversized_primary_locale_is_ignored_even_with_han_fallback() {
5588 let locale = Some("abcdefghij-US");
5589 assert_eq!(scrape_market(locale, "rust async"), None);
5590 assert!(bing_locale_was_ignored(locale));
5591 assert!(ddg_locale_was_ignored(locale, None));
5592
5593 // A query-derived market must not hide the invalid explicit knob.
5594 let market = scrape_market(locale, "中国 的 首都");
5595 assert_eq!(market.as_deref(), Some("zh-CN"));
5596 assert!(ddg_locale_was_ignored(locale, market.as_deref()));
5597 }
5598
5599 #[test]
5600 fn han_fallback_vetoes_kana_and_hangul_queries() {
5601 // A Han-bearing query with kana is Japanese: pushing it onto the
5602 // zh-CN market would be the inverse of the drift the fallback
5603 // exists to fix, so it keeps the no-market request.
5604 assert_eq!(scrape_market(None, "東京の天気"), None);
5605 assert_eq!(scrape_market(None, "日本の地図"), None);
5606 // Hangul-bearing queries likewise never take the fallback.
5607 assert_eq!(scrape_market(None, "러스트 프로그래밍"), None);
5608 // Purely Han queries (indistinguishable from Chinese) and an
5609 // explicit locale keep the existing behavior.
5610 assert_eq!(
5611 scrape_market(None, "中国 的 首都").as_deref(),
5612 Some("zh-CN")
5613 );
5614 assert_eq!(
5615 scrape_market(Some("ja-JP"), "東京の天気").as_deref(),
5616 Some("ja-JP")
5617 );
5618 }
5619
5620 #[test]
5621 fn searxng_url_uses_search_path_and_json_format() {
5622 let (url, host) = searxng_search_url(
5623 Some("https://search.example/"),
5624 "rust async",
5625 QueryFilters::default(),
5626 )
5627 .expect("searxng url");
5628 let parsed = reqwest::Url::parse(&url).expect("valid url");
5629 assert_eq!(host, "search.example");
5630 assert_eq!(parsed.path(), "/search");
5631 assert_eq!(
5632 parsed.query_pairs().find(|(key, _)| key == "q").unwrap().1,
5633 "rust async"
5634 );
5635 assert_eq!(
5636 parsed
5637 .query_pairs()
5638 .find(|(key, _)| key == "format")
5639 .unwrap()
5640 .1,
5641 "json"
5642 );
5643
5644 let (subpath_url, _) = searxng_search_url(
5645 Some("https://search.example/searxng?language=en"),
5646 "codewhale",
5647 QueryFilters::default(),
5648 )
5649 .expect("searxng subpath url");
5650 let parsed = reqwest::Url::parse(&subpath_url).expect("valid subpath url");
5651 assert_eq!(parsed.path(), "/searxng/search");
5652 assert_eq!(
5653 parsed
5654 .query_pairs()
5655 .find(|(key, _)| key == "language")
5656 .unwrap()
5657 .1,
5658 "en"
5659 );
5660
5661 let (search_url, _) = searxng_search_url(
5662 Some("https://search.example/searxng/search"),
5663 "codewhale",
5664 QueryFilters::default(),
5665 )
5666 .expect("searxng search endpoint");
5667 assert_eq!(
5668 reqwest::Url::parse(&search_url)
5669 .expect("valid search url")
5670 .path(),
5671 "/searxng/search"
5672 );
5673 }
5674
5675 #[test]
5676 fn searxng_parser_normalizes_results() {
5677 let parsed = json!({
5678 "results": [
5679 {
5680 "title": " Rust async ",
5681 "url": " https://example.com/rust ",
5682 "content": " Result content "
5683 },
5684 {
5685 "title": "Empty snippet",
5686 "url": "https://example.com/empty",
5687 "content": " ",
5688 "snippet": " Fallback snippet "
5689 },
5690 {
5691 "title": "",
5692 "url": "https://example.com/missing-title",
5693 "content": "ignored"
5694 },
5695 {
5696 "title": "Missing URL",
5697 "content": "ignored"
5698 }
5699 ]
5700 });
5701
5702 let results = parse_searxng_results(&parsed, 10);
5703 assert_eq!(results.len(), 2);
5704 assert_eq!(results[0].title, "Rust async");
5705 assert_eq!(results[0].url, "https://example.com/rust");
5706 assert_eq!(results[0].snippet.as_deref(), Some("Result content"));
5707 assert_eq!(results[1].snippet.as_deref(), Some("Fallback snippet"));
5708 }
5709
5710 #[test]
5711 fn searxng_score_reads_floats_integers_strings_and_clamps_junk() {
5712 assert_eq!(searxng_score(&json!({"score": 0.75})), 0.75);
5713 assert_eq!(searxng_score(&json!({"score": 1})), 1.0);
5714 assert_eq!(searxng_score(&json!({"score": " 2.5 "})), 2.5);
5715 assert_eq!(searxng_score(&json!({"score": "-1.5"})), -1.5);
5716 assert_eq!(searxng_score(&json!({})), 0.0);
5717 assert_eq!(searxng_score(&json!({"score": null})), 0.0);
5718 assert_eq!(searxng_score(&json!({"score": true})), 0.0);
5719 assert_eq!(searxng_score(&json!({"score": ""})), 0.0);
5720 assert_eq!(searxng_score(&json!({"score": "not-a-number"})), 0.0);
5721 assert_eq!(searxng_score(&json!({"score": {"nested": 1.0}})), 0.0);
5722 assert_eq!(
5723 searxng_score(&json!({"score": "NaN"})),
5724 0.0,
5725 "a non-finite score must not reach the sort"
5726 );
5727 assert_eq!(
5728 searxng_score(&json!({"score": "inf"})),
5729 0.0,
5730 "an infinite score must not outrank every finite row"
5731 );
5732 }
5733
5734 #[test]
5735 fn searxng_parser_sorts_by_descending_score() {
5736 // The strongest row is last in the instance's own order; only the
5737 // score sort can promote it.
5738 let parsed = json!({
5739 "results": [
5740 {"title": "Low", "url": "https://example.com/low", "score": 0.25},
5741 {"title": "Middle", "url": "https://example.com/mid", "score": 1},
5742 {"title": "High", "url": "https://example.com/high", "score": "4.5"},
5743 {"title": "Zero", "url": "https://example.com/zero", "score": 0.0}
5744 ]
5745 });
5746
5747 let titles: Vec<String> = parse_searxng_results(&parsed, 10)
5748 .into_iter()
5749 .map(|entry| entry.title)
5750 .collect();
5751 assert_eq!(titles, ["High", "Middle", "Low", "Zero"]);
5752 }
5753
5754 #[test]
5755 fn searxng_parser_keeps_input_order_for_equal_scores() {
5756 let parsed = json!({
5757 "results": [
5758 {"title": "First", "url": "https://example.com/1", "score": 1.5},
5759 {"title": "Second", "url": "https://example.com/2", "score": 1.5},
5760 {"title": "Third", "url": "https://example.com/3", "score": 1.5},
5761 {"title": "Lower", "url": "https://example.com/4", "score": 1.4}
5762 ]
5763 });
5764
5765 let titles: Vec<String> = parse_searxng_results(&parsed, 10)
5766 .into_iter()
5767 .map(|entry| entry.title)
5768 .collect();
5769 assert_eq!(titles, ["First", "Second", "Third", "Lower"]);
5770 }
5771
5772 #[test]
5773 fn searxng_parser_sorts_missing_or_invalid_scores_last() {
5774 let parsed = json!({
5775 "results": [
5776 {"title": "No score", "url": "https://example.com/none"},
5777 {
5778 "title": "Garbage",
5779 "url": "https://example.com/garbage",
5780 "score": "not-a-number"
5781 },
5782 {"title": "NaN string", "url": "https://example.com/nan", "score": "NaN"},
5783 {"title": "Infinite string", "url": "https://example.com/inf", "score": "inf"},
5784 {"title": "Boolean", "url": "https://example.com/bool", "score": true},
5785 {"title": "Scored", "url": "https://example.com/scored", "score": 0.5}
5786 ]
5787 });
5788
5789 let results = parse_searxng_results(&parsed, 10);
5790 let titles: Vec<&str> = results.iter().map(|entry| entry.title.as_str()).collect();
5791 // Every row with a title and a URL survives. Unusable scores read as
5792 // 0.0 and keep their input order behind the one scored row.
5793 assert_eq!(
5794 titles,
5795 [
5796 "Scored",
5797 "No score",
5798 "Garbage",
5799 "NaN string",
5800 "Infinite string",
5801 "Boolean"
5802 ]
5803 );
5804 }
5805
5806 #[test]
5807 fn searxng_parser_caps_after_score_sort() {
5808 // A `take` before the sort would drop "Strong"; the cap must apply to
5809 // the ranked list instead.
5810 let parsed = json!({
5811 "results": [
5812 {"title": "Weak one", "url": "https://example.com/1", "score": 0.1},
5813 {"title": "Weak two", "url": "https://example.com/2", "score": 0.2},
5814 {"title": "Strong", "url": "https://example.com/3", "score": 9.0}
5815 ]
5816 });
5817
5818 let results = parse_searxng_results(&parsed, 2);
5819 assert_eq!(results.len(), 2, "max_results caps the ranked list");
5820 assert_eq!(results[0].title, "Strong");
5821 assert_eq!(results[1].title, "Weak two");
5822 }
5823
5824 #[tokio::test]
5825 async fn searxng_provider_requires_base_url() {
5826 use crate::tools::spec::{ToolContext, ToolSpec};
5827 use codewhale_runtime::config::SearchProvider;
5828
5829 let tmp = tempfile::tempdir().expect("tempdir");
5830 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5831 ctx.search_provider = SearchProvider::Searxng;
5832 ctx.search_base_url = None;
5833
5834 let err = WebSearchTool
5835 .execute(json!({"query": "rust async"}), &ctx)
5836 .await
5837 .expect_err("searxng requires explicit base_url");
5838 let msg = err.to_string();
5839 assert!(
5840 matches!(err, crate::tools::spec::ToolError::InvalidInput { .. }),
5841 "missing base_url is a configuration gap, not a transport failure: {err:?}"
5842 );
5843 assert!(
5844 msg.contains("SearXNG")
5845 && msg.contains("base_url")
5846 && msg.contains("no public instance"),
5847 "got `{msg}`"
5848 );
5849 }
5850
5851 #[tokio::test]
5852 #[allow(clippy::await_holding_lock)]
5853 async fn missing_provider_key_fails_closed_as_not_configured() {
5854 use crate::tools::spec::{ToolContext, ToolError, ToolSpec};
5855 use codewhale_runtime::config::SearchProvider;
5856
5857 let _guard = crate::test_support::lock_test_env();
5858 let prev_tavily = std::env::var_os("TAVILY_API_KEY");
5859 // "both keys empty" must mean *both*: an ambient key from the
5860 // operator's shell would otherwise satisfy the Tavily arm.
5861 unsafe { std::env::remove_var("TAVILY_API_KEY") };
5862
5863 for provider in [SearchProvider::Tavily, SearchProvider::Bocha] {
5864 let tmp = tempfile::tempdir().expect("tempdir");
5865 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5866 ctx.search_provider = provider;
5867 ctx.search_api_key = None;
5868
5869 let error = WebSearchTool
5870 .execute(json!({"query": "needs configuration"}), &ctx)
5871 .await
5872 .expect_err("a keyed provider without an API key must fail closed");
5873 assert!(
5874 matches!(error, ToolError::InvalidInput { .. }),
5875 "config gaps must stay distinguishable from transport failures: {error:?}"
5876 );
5877 let message = error.to_string();
5878 assert!(message.contains("is not configured"), "got `{message}`");
5879 assert!(message.contains("api_key"), "got `{message}`");
5880 }
5881
5882 // Sibling case: only `TAVILY_API_KEY` is set. Explicit Tavily is
5883 // configured, and the copy that names both sources is the one the
5884 // operator never sees here.
5885 unsafe { std::env::set_var("TAVILY_API_KEY", "tvly-test-env-only") };
5886 let tmp = tempfile::tempdir().expect("tempdir");
5887 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5888 ctx.search_provider = SearchProvider::Tavily;
5889 ctx.search_api_key = None;
5890 let preflight = super::preflight_search_provider(&ctx);
5891
5892 match prev_tavily {
5893 Some(value) => unsafe { std::env::set_var("TAVILY_API_KEY", value) },
5894 None => unsafe { std::env::remove_var("TAVILY_API_KEY") },
5895 }
5896
5897 assert!(
5898 preflight.is_ok(),
5899 "TAVILY_API_KEY alone must configure explicit Tavily: {preflight:?}"
5900 );
5901 }
5902
5903 #[test]
5904 fn tavily_key_from_prefers_dedicated_env_and_prefix_gates_only_the_generic_key() {
5905 let _guard = crate::test_support::lock_test_env();
5906 let prev = std::env::var_os("TAVILY_API_KEY");
5907
5908 unsafe { std::env::set_var("TAVILY_API_KEY", "tvly-a") };
5909 assert_eq!(
5910 codewhale_runtime::config::tavily_key_from(Some("tvly-b")).as_deref(),
5911 Some("tvly-a"),
5912 "the dedicated env wins over the shared generic slot"
5913 );
5914 assert_eq!(
5915 codewhale_runtime::config::tavily_env_key().as_deref(),
5916 Some("tvly-a")
5917 );
5918
5919 // A dedicated env key is never prefix-checked.
5920 unsafe { std::env::set_var("TAVILY_API_KEY", "not-a-tvly-prefix") };
5921 assert_eq!(
5922 codewhale_runtime::config::tavily_key_from(None).as_deref(),
5923 Some("not-a-tvly-prefix")
5924 );
5925
5926 unsafe { std::env::set_var("TAVILY_API_KEY", " ") };
5927 assert_eq!(codewhale_runtime::config::tavily_env_key(), None);
5928
5929 unsafe { std::env::remove_var("TAVILY_API_KEY") };
5930 assert_eq!(
5931 codewhale_runtime::config::tavily_key_from(Some("tvly-b")).as_deref(),
5932 Some("tvly-b")
5933 );
5934 assert_eq!(
5935 codewhale_runtime::config::tavily_key_from(Some("doctor-offline-search-sentinel")),
5936 None,
5937 "a non-`tvly-` generic key must never autodetect Tavily"
5938 );
5939 assert_eq!(
5940 codewhale_runtime::config::tavily_key_from(Some(" ")),
5941 None
5942 );
5943 assert!(codewhale_runtime::config::looks_like_tavily_key(" tvly-x "));
5944 assert!(!codewhale_runtime::config::looks_like_tavily_key(
5945 "fc-live-test"
5946 ));
5947
5948 match prev {
5949 Some(value) => unsafe { std::env::set_var("TAVILY_API_KEY", value) },
5950 None => unsafe { std::env::remove_var("TAVILY_API_KEY") },
5951 }
5952 }
5953
5954 #[tokio::test]
5955 async fn searxng_search_returns_json_results() {
5956 use crate::tools::spec::{ToolContext, ToolSpec};
5957 use codewhale_runtime::config::SearchProvider;
5958 use wiremock::matchers::{method, path, query_param};
5959 use wiremock::{Mock, MockServer, ResponseTemplate};
5960
5961 let server = MockServer::start().await;
5962 Mock::given(method("GET"))
5963 .and(path("/search"))
5964 .and(query_param("q", "rust async"))
5965 .and(query_param("format", "json"))
5966 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
5967 "results": [
5968 {
5969 "title": "Rust async",
5970 "url": "https://example.com/rust",
5971 "content": "Async Rust result"
5972 }
5973 ]
5974 })))
5975 .mount(&server)
5976 .await;
5977
5978 let tmp = tempfile::tempdir().expect("tempdir");
5979 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
5980 ctx.search_provider = SearchProvider::Searxng;
5981 ctx.search_base_url = Some(server.uri());
5982
5983 let result = WebSearchTool
5984 .execute(json!({"query": "rust async"}), &ctx)
5985 .await
5986 .expect("searxng endpoint should return results");
5987 let value: serde_json::Value =
5988 serde_json::from_str(&result.content).expect("web search json response");
5989
5990 assert_eq!(value["source"].as_str(), Some("searxng"));
5991 assert_eq!(value["count"].as_u64(), Some(1));
5992 assert_eq!(value["results"][0]["rank"].as_u64(), Some(1));
5993 assert_eq!(value["results"][0]["domain"], "example.com");
5994 assert_eq!(value["receipt"]["backend"], "searxng");
5995 assert_eq!(
5996 value["receipt"]["backend_detail"].as_str(),
5997 Some("127.0.0.1")
5998 );
5999 assert!(
6000 value["message"]
6001 .as_str()
6002 .expect("message")
6003 .contains("Backend: searxng at")
6004 );
6005 }
6006
6007 #[tokio::test]
6008 async fn searxng_honors_recency_and_locale_and_post_filters_domains() {
6009 use crate::tools::spec::{ToolContext, ToolSpec};
6010 use codewhale_runtime::config::SearchProvider;
6011 use wiremock::matchers::{method, path, query_param};
6012 use wiremock::{Mock, MockServer, ResponseTemplate};
6013
6014 let server = MockServer::start().await;
6015 Mock::given(method("GET"))
6016 .and(path("/search"))
6017 .and(query_param("q", "fresh rust"))
6018 .and(query_param("format", "json"))
6019 .and(query_param("time_range", "week"))
6020 .and(query_param("language", "en-US"))
6021 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
6022 "results": [
6023 {"title": "Keep", "url": "https://docs.example.com/rust", "content": "kept"},
6024 {"title": "Drop", "url": "https://other.test/rust", "content": "dropped"}
6025 ]
6026 })))
6027 .mount(&server)
6028 .await;
6029
6030 let tmp = tempfile::tempdir().expect("tempdir");
6031 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6032 ctx.search_provider = SearchProvider::Searxng;
6033 ctx.search_base_url = Some(server.uri());
6034
6035 let result = WebSearchTool
6036 .execute(
6037 json!({
6038 "query": "fresh rust",
6039 "recency": "week",
6040 "domains": ["example.com"],
6041 "locale": "en-US"
6042 }),
6043 &ctx,
6044 )
6045 .await
6046 .expect("structured query should execute");
6047 let value: serde_json::Value =
6048 serde_json::from_str(&result.content).expect("web search json response");
6049
6050 assert_eq!(value["count"], 1);
6051 assert_eq!(value["results"][0]["domain"], "docs.example.com");
6052 assert_eq!(value["receipt"]["honored"]["domains"], true);
6053 assert_eq!(value["receipt"]["honored"]["recency"], true);
6054 assert_eq!(value["receipt"]["honored"]["locale"], true);
6055 let degraded = value["receipt"]["degraded"]
6056 .as_array()
6057 .expect("degraded receipt array");
6058 assert!(
6059 degraded
6060 .iter()
6061 .any(|item| { item["kind"] == "post_filtered" && item["knob"] == "domains" })
6062 );
6063 assert!(
6064 !degraded.iter().any(|item| item["kind"] == "knob_ignored"),
6065 "SearXNG forwards both knobs: {degraded:?}"
6066 );
6067 }
6068
6069 #[test]
6070 fn finalize_reports_a_result_shortfall_instead_of_a_honored_capability() {
6071 let query = SearchQuery::new("current release".to_string(), 8, None, Vec::new(), None);
6072 let raw = BackendSearch {
6073 backend: BackendId::ProviderNative,
6074 source: "provider-native/deepseek/deepseek-flash".to_string(),
6075 backend_detail: Some("api.deepseek.com".to_string()),
6076 results: vec![SearchResult::new(
6077 1,
6078 "Only source".to_string(),
6079 "https://example.com/only".to_string(),
6080 None,
6081 None,
6082 )],
6083 degraded: Vec::new(),
6084 note: None,
6085 };
6086 let response = finalize_search_response(
6087 query,
6088 QueryCapabilities {
6089 max_results: CapabilityState::Supported,
6090 recency: CapabilityState::Unsupported,
6091 domains: CapabilityState::Unsupported,
6092 locale: CapabilityState::Unsupported,
6093 published_date: CapabilityState::Unknown,
6094 },
6095 raw,
6096 Instant::now(),
6097 );
6098
6099 assert_eq!(response.results.len(), 1);
6100 assert!(
6101 !response.receipt.honored.max_results,
6102 "one result for eight requested is a shortfall, not an honored cap"
6103 );
6104 }
6105
6106 #[test]
6107 fn provider_native_domain_filter_is_reported_as_provider_honored() {
6108 let query = SearchQuery::new(
6109 "current release".to_string(),
6110 3,
6111 Some(Recency::Week),
6112 vec!["example.com".to_string()],
6113 None,
6114 );
6115 let raw = BackendSearch {
6116 backend: BackendId::ProviderNative,
6117 source: "provider-native/xai/grok-4.5".to_string(),
6118 backend_detail: Some("api.x.ai".to_string()),
6119 results: vec![
6120 SearchResult::new(
6121 1,
6122 "Exact source".to_string(),
6123 "https://docs.example.com/release".to_string(),
6124 None,
6125 None,
6126 ),
6127 SearchResult::new(
6128 2,
6129 "Second source".to_string(),
6130 "https://docs.example.com/release-notes".to_string(),
6131 None,
6132 None,
6133 ),
6134 SearchResult::new(
6135 3,
6136 "Third source".to_string(),
6137 "https://docs.example.com/changelog".to_string(),
6138 None,
6139 None,
6140 ),
6141 ],
6142 degraded: Vec::new(),
6143 note: Some("Grounded answer.".to_string()),
6144 };
6145 let response = finalize_search_response(
6146 query,
6147 QueryCapabilities {
6148 max_results: CapabilityState::Supported,
6149 recency: CapabilityState::Unsupported,
6150 domains: CapabilityState::Supported,
6151 locale: CapabilityState::Unsupported,
6152 published_date: CapabilityState::Unknown,
6153 },
6154 raw,
6155 Instant::now(),
6156 );
6157
6158 assert!(response.receipt.honored.max_results);
6159 assert!(response.receipt.honored.domains);
6160 assert!(!response.receipt.honored.recency);
6161 assert!(response.receipt.degraded.iter().any(|reason| matches!(
6162 reason,
6163 DegradedReason::KnobIgnored {
6164 knob: QueryKnob::Recency
6165 }
6166 )));
6167 assert!(!response.receipt.degraded.iter().any(|reason| matches!(
6168 reason,
6169 DegradedReason::PostFiltered {
6170 knob: QueryKnob::Domains
6171 }
6172 )));
6173 assert_eq!(
6174 response.unverified_synthesis.as_deref(),
6175 Some("Grounded answer.")
6176 );
6177 assert!(!response.message.contains("Grounded answer."));
6178 }
6179
6180 fn native_backend_search(note: String, degraded: Vec<DegradedReason>) -> BackendSearch {
6181 BackendSearch {
6182 backend: BackendId::ProviderNative,
6183 source: "provider-native/anthropic/claude-opus-4-8".to_string(),
6184 backend_detail: Some("api.anthropic.com".to_string()),
6185 results: (1..=5)
6186 .map(|rank| {
6187 SearchResult::new(
6188 rank,
6189 format!("Source {rank}"),
6190 format!("https://example.com/{rank}"),
6191 None,
6192 None,
6193 )
6194 })
6195 .collect(),
6196 degraded,
6197 note: Some(note),
6198 }
6199 }
6200
6201 fn native_query() -> SearchQuery {
6202 SearchQuery::new("current release".to_string(), 5, None, Vec::new(), None)
6203 }
6204
6205 fn native_capabilities() -> QueryCapabilities {
6206 QueryCapabilities {
6207 max_results: CapabilityState::Supported,
6208 recency: CapabilityState::Unsupported,
6209 domains: CapabilityState::Supported,
6210 locale: CapabilityState::Unsupported,
6211 published_date: CapabilityState::Unknown,
6212 }
6213 }
6214
6215 #[test]
6216 fn native_answer_reaches_the_model_whole_under_the_route_budget() {
6217 // #6508: a 6,000-character native answer with five citations used to
6218 // reach a 128K route as a ~900-character snippet (and earlier was cut
6219 // at 4,000 characters). Now the search result is whole within the
6220 // route's one inline budget.
6221 let answer = format!("{}END OF ANSWER", "Grounded answer sentence. ".repeat(240));
6222 assert!(answer.chars().count() > 6_000);
6223 let response = finalize_search_response(
6224 native_query(),
6225 native_capabilities(),
6226 native_backend_search(answer.clone(), Vec::new()),
6227 Instant::now(),
6228 );
6229 assert!(
6230 response
6231 .unverified_synthesis
6232 .as_deref()
6233 .is_some_and(|synthesis| synthesis.ends_with("END OF ANSWER"))
6234 );
6235 assert!(!response.message.contains("output limit"));
6236
6237 let output = crate::tools::spec::ToolResult::json(&response).expect("json");
6238 let context = crate::core::engine::compact_tool_result_for_route(
6239 codewhale_config::ProviderKind::Deepseek,
6240 "deepseek-v3.2-128k",
6241 None,
6242 "web_search",
6243 &output,
6244 );
6245 assert_eq!(context, output.content.trim());
6246 assert!(context.contains("END OF ANSWER"));
6247 }
6248
6249 #[test]
6250 fn native_answer_cut_by_the_provider_says_so() {
6251 let response = finalize_search_response(
6252 native_query(),
6253 native_capabilities(),
6254 native_backend_search(
6255 "Partial answer".to_string(),
6256 vec![DegradedReason::AnswerCutByProvider],
6257 ),
6258 Instant::now(),
6259 );
6260 assert!(
6261 response
6262 .receipt
6263 .degraded
6264 .contains(&DegradedReason::AnswerCutByProvider)
6265 );
6266 assert!(
6267 response
6268 .message
6269 .contains("the provider stopped the search answer at its output limit"),
6270 "{}",
6271 response.message
6272 );
6273 }
6274
6275 #[test]
6276 fn provider_native_discards_answer_when_domain_filter_removes_a_source() {
6277 let query = SearchQuery::new(
6278 "current release".to_string(),
6279 3,
6280 None,
6281 vec!["example.com".to_string()],
6282 None,
6283 );
6284 let raw = BackendSearch {
6285 backend: BackendId::ProviderNative,
6286 source: "provider-native/xai/grok-4.5".to_string(),
6287 backend_detail: Some("api.x.ai".to_string()),
6288 results: vec![
6289 SearchResult::new(
6290 1,
6291 "Allowed source".to_string(),
6292 "https://docs.example.com/release".to_string(),
6293 None,
6294 None,
6295 ),
6296 SearchResult::new(
6297 2,
6298 "Leaked source".to_string(),
6299 "https://outside.test/release".to_string(),
6300 None,
6301 None,
6302 ),
6303 ],
6304 degraded: Vec::new(),
6305 note: Some("Answer synthesized from both sources.".to_string()),
6306 };
6307 let response = finalize_search_response(
6308 query,
6309 QueryCapabilities {
6310 max_results: CapabilityState::Supported,
6311 recency: CapabilityState::Unsupported,
6312 domains: CapabilityState::Supported,
6313 locale: CapabilityState::Unsupported,
6314 published_date: CapabilityState::Unknown,
6315 },
6316 raw,
6317 Instant::now(),
6318 );
6319
6320 assert_eq!(response.count, 1);
6321 assert_eq!(response.results[0].domain, "docs.example.com");
6322 assert!(response.message.starts_with("Found 1 result(s)\n"));
6323 assert!(response.unverified_synthesis.is_none());
6324 assert!(response.receipt.degraded.iter().any(|reason| matches!(
6325 reason,
6326 DegradedReason::PostFiltered {
6327 knob: QueryKnob::Domains
6328 }
6329 )));
6330 }
6331
6332 #[test]
6333 fn search_results_receive_session_scoped_refs_and_sanitize_credential_urls() {
6334 let query = SearchQuery::new("sources".to_string(), 5, None, Vec::new(), None);
6335 let raw = BackendSearch {
6336 backend: BackendId::DuckDuckGo,
6337 source: "duckduckgo".to_string(),
6338 backend_detail: None,
6339 results: vec![
6340 SearchResult::new(
6341 1,
6342 "Valid".to_string(),
6343 "https://example.com/source#section".to_string(),
6344 None,
6345 None,
6346 ),
6347 SearchResult::new(
6348 2,
6349 "Protected".to_string(),
6350 "https://example.com/protected?access_token=sensitive&view=full".to_string(),
6351 None,
6352 None,
6353 ),
6354 ],
6355 degraded: Vec::new(),
6356 note: None,
6357 };
6358 let mut response =
6359 finalize_search_response(query, QueryCapabilities::count_only(), raw, Instant::now());
6360 let context = crate::tools::spec::ToolContext::new(std::path::PathBuf::from("."))
6361 .with_state_namespace("search-citation-session");
6362
6363 register_search_citations(&mut response, &context);
6364
6365 assert_eq!(response.count, 2);
6366 assert_eq!(response.results[0].url, "https://example.com/source");
6367 assert_eq!(
6368 response.results[1].url,
6369 "https://example.com/protected?view=full"
6370 );
6371 assert!(!response.results[1].url.contains("sensitive"));
6372 assert!(response.results[0].ref_id.starts_with("web_"));
6373 assert!(
6374 crate::tools::web::citations::resolve(
6375 "search-citation-session",
6376 &response.results[0].ref_id
6377 )
6378 .is_some()
6379 );
6380 assert!(
6381 crate::tools::web::citations::resolve(
6382 "foreign-search-citation-session",
6383 &response.results[0].ref_id
6384 )
6385 .is_none()
6386 );
6387 }
6388
6389 #[tokio::test]
6390 async fn searxng_empty_results_report_backend() {
6391 use crate::tools::spec::ToolContext;
6392 use codewhale_runtime::config::SearchProvider;
6393 use wiremock::matchers::{method, path, query_param};
6394 use wiremock::{Mock, MockServer, ResponseTemplate};
6395
6396 let server = MockServer::start().await;
6397 Mock::given(method("GET"))
6398 .and(path("/search"))
6399 .and(query_param("q", "empty"))
6400 .and(query_param("format", "json"))
6401 .respond_with(ResponseTemplate::new(200).set_body_json(json!({"results": []})))
6402 .mount(&server)
6403 .await;
6404
6405 let tmp = tempfile::tempdir().expect("tempdir");
6406 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6407 ctx.search_provider = SearchProvider::Searxng;
6408 ctx.search_base_url = Some(server.uri());
6409
6410 let (results, host) = WebSearchTool
6411 .run_searxng_search("empty", QueryFilters::default(), 5, 5_000, &ctx)
6412 .await
6413 .expect("empty SearXNG adapter response should be successful");
6414 let expected_host = reqwest::Url::parse(&server.uri())
6415 .expect("mock URL")
6416 .host_str()
6417 .expect("mock host")
6418 .to_string();
6419
6420 assert!(results.is_empty());
6421 assert_eq!(host, expected_host);
6422 }
6423
6424 #[tokio::test]
6425 async fn searxng_http_errors_are_actionable() {
6426 use crate::tools::spec::ToolContext;
6427 use codewhale_runtime::config::SearchProvider;
6428 use wiremock::matchers::{method, path, query_param};
6429 use wiremock::{Mock, MockServer, ResponseTemplate};
6430
6431 let server = MockServer::start().await;
6432 Mock::given(method("GET"))
6433 .and(path("/search"))
6434 .and(query_param("q", "blocked"))
6435 .and(query_param("format", "json"))
6436 .respond_with(ResponseTemplate::new(403).set_body_string("json disabled"))
6437 .mount(&server)
6438 .await;
6439
6440 let tmp = tempfile::tempdir().expect("tempdir");
6441 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6442 ctx.search_provider = SearchProvider::Searxng;
6443 ctx.search_base_url = Some(server.uri());
6444
6445 let err = WebSearchTool
6446 .run_searxng_search("blocked", QueryFilters::default(), 5, 5_000, &ctx)
6447 .await
6448 .expect_err("403 should be actionable");
6449 let msg = err.to_string();
6450 assert!(
6451 msg.contains("HTTP 403")
6452 && msg.contains("JSON output")
6453 && msg.contains("permits API access"),
6454 "got `{msg}`"
6455 );
6456 }
6457
6458 #[tokio::test]
6459 async fn searxng_rate_limit_error_mentions_configured_instance() {
6460 use crate::tools::spec::ToolContext;
6461 use codewhale_runtime::config::SearchProvider;
6462 use wiremock::matchers::{method, path, query_param};
6463 use wiremock::{Mock, MockServer, ResponseTemplate};
6464
6465 let server = MockServer::start().await;
6466 Mock::given(method("GET"))
6467 .and(path("/search"))
6468 .and(query_param("q", "later"))
6469 .and(query_param("format", "json"))
6470 .respond_with(ResponseTemplate::new(429).set_body_string("too many requests"))
6471 .mount(&server)
6472 .await;
6473
6474 let tmp = tempfile::tempdir().expect("tempdir");
6475 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6476 ctx.search_provider = SearchProvider::Searxng;
6477 ctx.search_base_url = Some(server.uri());
6478
6479 let err = WebSearchTool
6480 .run_searxng_search("later", QueryFilters::default(), 5, 5_000, &ctx)
6481 .await
6482 .expect_err("429 should be actionable");
6483 let msg = err.to_string();
6484 assert!(
6485 msg.contains("HTTP 429")
6486 && msg.contains("rate-limiting")
6487 && msg.contains("trusted/self-hosted instance"),
6488 "got `{msg}`"
6489 );
6490 }
6491
6492 #[tokio::test]
6493 async fn searxng_invalid_json_is_actionable() {
6494 use crate::tools::spec::ToolContext;
6495 use codewhale_runtime::config::SearchProvider;
6496 use wiremock::matchers::{method, path, query_param};
6497 use wiremock::{Mock, MockServer, ResponseTemplate};
6498
6499 let server = MockServer::start().await;
6500 Mock::given(method("GET"))
6501 .and(path("/search"))
6502 .and(query_param("q", "html"))
6503 .and(query_param("format", "json"))
6504 .respond_with(ResponseTemplate::new(200).set_body_string("<html>not json</html>"))
6505 .mount(&server)
6506 .await;
6507
6508 let tmp = tempfile::tempdir().expect("tempdir");
6509 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6510 ctx.search_provider = SearchProvider::Searxng;
6511 ctx.search_base_url = Some(server.uri());
6512
6513 let err = WebSearchTool
6514 .run_searxng_search("html", QueryFilters::default(), 5, 5_000, &ctx)
6515 .await
6516 .expect_err("invalid JSON should be actionable");
6517 let msg = err.to_string();
6518 assert!(
6519 msg.contains("Failed to parse SearXNG JSON response")
6520 && msg.contains("format=json")
6521 && msg.contains("JSON output"),
6522 "got `{msg}`"
6523 );
6524 }
6525
6526 #[tokio::test]
6527 async fn custom_duckduckgo_results_report_custom_host_source() {
6528 use crate::tools::spec::{ToolContext, ToolSpec};
6529 use codewhale_runtime::config::SearchProvider;
6530 use wiremock::matchers::{method, path, query_param};
6531 use wiremock::{Mock, MockServer, ResponseTemplate};
6532
6533 let server = MockServer::start().await;
6534 Mock::given(method("GET"))
6535 .and(path("/html/"))
6536 .and(query_param("q", "rust async"))
6537 .respond_with(ResponseTemplate::new(200).set_body_string(
6538 r#"
6539 <html><body>
6540 <a class="result__a" href="https://example.com/rust">Rust async</a>
6541 <div class="result__snippet">Async Rust result</div>
6542 </body></html>
6543 "#,
6544 ))
6545 .mount(&server)
6546 .await;
6547
6548 let tmp = tempfile::tempdir().expect("tempdir");
6549 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6550 ctx.search_provider = SearchProvider::DuckDuckGo;
6551 let base_url = format!("{}/html/", server.uri());
6552 let expected_host = reqwest::Url::parse(&base_url)
6553 .expect("mock server url")
6554 .host_str()
6555 .expect("mock server host")
6556 .to_string();
6557 ctx.search_base_url = Some(base_url);
6558
6559 let result = WebSearchTool
6560 .execute(json!({"query": "rust async"}), &ctx)
6561 .await
6562 .expect("custom endpoint should return results");
6563 let value: serde_json::Value =
6564 serde_json::from_str(&result.content).expect("web search json response");
6565
6566 assert_eq!(value["source"].as_str(), Some(expected_host.as_str()));
6567 assert_eq!(value["count"].as_u64(), Some(1));
6568 }
6569
6570 #[tokio::test]
6571 async fn repeated_search_uses_session_cache_and_marks_receipt() {
6572 use crate::tools::spec::{ToolContext, ToolSpec};
6573 use crate::tools::web::cache;
6574 use codewhale_runtime::config::SearchProvider;
6575 use wiremock::matchers::{method, path, query_param};
6576 use wiremock::{Mock, MockServer, ResponseTemplate};
6577
6578 cache::reset_search();
6579 let server = MockServer::start().await;
6580 Mock::given(method("GET"))
6581 .and(path("/html/"))
6582 .and(query_param("q", "session cache receipt"))
6583 .respond_with(ResponseTemplate::new(200).set_body_string(
6584 r#"
6585 <html><body>
6586 <a class="result__a" href="https://example.com/cached">Cached result</a>
6587 <div class="result__snippet">Fetched once.</div>
6588 </body></html>
6589 "#,
6590 ))
6591 .mount(&server)
6592 .await;
6593
6594 let tmp = tempfile::tempdir().expect("tempdir");
6595 let mut context = ToolContext::new(tmp.path().to_path_buf())
6596 .with_state_namespace("web-search-query-cache");
6597 context.search_provider = SearchProvider::DuckDuckGo;
6598 context.search_base_url = Some(format!("{}/html/", server.uri()));
6599
6600 let first = WebSearchTool
6601 .execute(json!({"query": "session cache receipt"}), &context)
6602 .await
6603 .expect("first search should succeed");
6604 let second = WebSearchTool
6605 .execute(json!({"query": "session cache receipt"}), &context)
6606 .await
6607 .expect("second search should hit cache");
6608 let first: serde_json::Value =
6609 serde_json::from_str(&first.content).expect("first response json");
6610 let second: serde_json::Value =
6611 serde_json::from_str(&second.content).expect("second response json");
6612 let requests = server.received_requests().await.expect("recorded requests");
6613
6614 assert_eq!(requests.len(), 1);
6615 assert_eq!(first["receipt"]["cache_hit"], false);
6616 assert_eq!(second["receipt"]["cache_hit"], true);
6617 assert_eq!(second["receipt"]["latency_ms"], 0);
6618 assert_eq!(second["results"], first["results"]);
6619
6620 use codewhale_net::network_policy::{Decision, NetworkPolicy, NetworkPolicyDecider};
6621 let denied_host = reqwest::Url::parse(&server.uri())
6622 .expect("mock server URL")
6623 .host_str()
6624 .expect("mock server host")
6625 .to_string();
6626 let policy = NetworkPolicy {
6627 default: Decision::Allow.into(),
6628 allow: Vec::new(),
6629 deny: vec![denied_host],
6630 proxy: Vec::new(),
6631 proxy_fake_ip_cidrs: Vec::new(),
6632 audit: false,
6633 };
6634 let blocked = context
6635 .clone()
6636 .with_network_policy(NetworkPolicyDecider::new(policy, None));
6637 let error = WebSearchTool
6638 .execute(json!({"query": "session cache receipt"}), &blocked)
6639 .await
6640 .expect_err("tightened policy must win over the query cache");
6641 assert!(error.to_string().contains("blocked by network policy"));
6642 assert_eq!(
6643 server
6644 .received_requests()
6645 .await
6646 .expect("recorded requests")
6647 .len(),
6648 1
6649 );
6650 }
6651
6652 #[tokio::test]
6653 async fn explicit_bing_does_not_fall_back_to_duckduckgo() {
6654 use crate::tools::spec::ToolContext;
6655 use codewhale_runtime::config::SearchProvider;
6656 use wiremock::matchers::{method, path, query_param};
6657 use wiremock::{Mock, MockServer, ResponseTemplate};
6658
6659 let server = MockServer::start().await;
6660 Mock::given(method("GET"))
6661 .and(path("/bing"))
6662 .and(query_param("q", "one way fallback"))
6663 .respond_with(ResponseTemplate::new(200).set_body_string("<html></html>"))
6664 .mount(&server)
6665 .await;
6666
6667 let tmp = tempfile::tempdir().expect("tempdir");
6668 let mut context = ToolContext::new(tmp.path().to_path_buf());
6669 context.search_provider = SearchProvider::Bing;
6670 context.search_base_url = Some(format!("{}/must-not-be-used", server.uri()));
6671 let query = SearchQuery::new("one way fallback".to_string(), 5, None, Vec::new(), None);
6672 let raw = run_scrape_search_with_endpoints(
6673 SearchProvider::Bing,
6674 &query,
6675 5_000,
6676 &context,
6677 ScrapeEndpoints {
6678 bing: &format!("{}/bing", server.uri()),
6679 allow_bing_fallback: Some(true),
6680 },
6681 )
6682 .await
6683 .expect("empty Bing response is a successful empty search");
6684 let requests = server.received_requests().await.expect("recorded requests");
6685
6686 assert_eq!(raw.backend, BackendId::Bing);
6687 assert!(raw.results.is_empty());
6688 assert!(raw.degraded.is_empty());
6689 assert_eq!(requests.len(), 1);
6690 assert_eq!(requests[0].url.path(), "/bing");
6691 }
6692
6693 #[tokio::test]
6694 async fn custom_duckduckgo_challenge_returns_actionable_error() {
6695 use crate::tools::spec::{ToolContext, ToolSpec};
6696 use codewhale_runtime::config::SearchProvider;
6697 use wiremock::matchers::{method, path, query_param};
6698 use wiremock::{Mock, MockServer, ResponseTemplate};
6699
6700 let server = MockServer::start().await;
6701 Mock::given(method("GET"))
6702 .and(path("/html/"))
6703 .and(query_param("q", "rust async"))
6704 .respond_with(ResponseTemplate::new(200).set_body_string(
6705 r#"<html><body><div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too</div></body></html>"#,
6706 ))
6707 .mount(&server)
6708 .await;
6709
6710 let tmp = tempfile::tempdir().expect("tempdir");
6711 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
6712 ctx.search_provider = SearchProvider::DuckDuckGo;
6713 ctx.search_base_url = Some(format!("{}/html/", server.uri()));
6714
6715 let err = WebSearchTool
6716 .execute(json!({"query": "rust async"}), &ctx)
6717 .await
6718 .expect_err("custom endpoint challenge should error");
6719 let msg = err.to_string();
6720 assert!(
6721 msg.contains("DuckDuckGo-compatible search endpoint")
6722 && msg.contains("bot challenge")
6723 && msg.contains("private search service"),
6724 "got `{msg}`"
6725 );
6726 }
6727
6728 #[tokio::test]
6729 async fn duckduckgo_challenge_to_bing_success_populates_fallback_receipt() {
6730 use crate::tools::spec::ToolContext;
6731 use codewhale_runtime::config::SearchProvider;
6732 use std::time::Instant;
6733 use wiremock::matchers::{method, path, query_param};
6734 use wiremock::{Mock, MockServer, ResponseTemplate};
6735
6736 let server = MockServer::start().await;
6737 Mock::given(method("GET"))
6738 .and(path("/html/"))
6739 .and(query_param("q", "fallback receipt"))
6740 .respond_with(ResponseTemplate::new(200).set_body_string(
6741 r#"<html><body><div class="anomaly-modal">Unfortunately, bots use DuckDuckGo too</div></body></html>"#,
6742 ))
6743 .mount(&server)
6744 .await;
6745 Mock::given(method("GET"))
6746 .and(path("/bing"))
6747 .and(query_param("q", "fallback receipt"))
6748 .respond_with(ResponseTemplate::new(200).set_body_string(
6749 r#"
6750 <ol><li class="b_algo">
6751 <h2><a href="https://example.com/fallback">Fallback result</a></h2>
6752 <div class="b_caption"><p>Bing result after challenge.</p></div>
6753 </li></ol>
6754 "#,
6755 ))
6756 .mount(&server)
6757 .await;
6758
6759 let tmp = tempfile::tempdir().expect("tempdir");
6760 let mut context = ToolContext::new(tmp.path().to_path_buf());
6761 context.search_provider = SearchProvider::DuckDuckGo;
6762 context.search_base_url = Some(format!("{}/html/", server.uri()));
6763 let query = SearchQuery::new("fallback receipt".to_string(), 5, None, Vec::new(), None);
6764 let started = Instant::now();
6765 let raw = run_scrape_search_with_endpoints(
6766 SearchProvider::DuckDuckGo,
6767 &query,
6768 5_000,
6769 &context,
6770 ScrapeEndpoints {
6771 bing: &format!("{}/bing", server.uri()),
6772 allow_bing_fallback: Some(true),
6773 },
6774 )
6775 .await
6776 .expect("Bing fallback should succeed");
6777 let response =
6778 finalize_search_response(query, QueryCapabilities::count_only(), raw, started);
6779 let value = serde_json::to_value(&response).expect("response serializes");
6780
6781 assert_eq!(value["source"], "bing");
6782 assert_eq!(value["count"], 1);
6783 assert_eq!(value["receipt"]["backend"], "bing");
6784 assert_eq!(
6785 value["receipt"]["degraded"][0],
6786 json!({"kind": "challenge_detected", "backend": "duckduckgo"})
6787 );
6788 assert_eq!(
6789 value["receipt"]["degraded"][1],
6790 json!({"kind": "scrape_fallback", "from": "duckduckgo", "to": "bing"})
6791 );
6792 assert!(
6793 response
6794 .receipt
6795 .warning()
6796 .expect("warning")
6797 .contains("used bing fallback")
6798 );
6799 }
6800
6801 /// #6746: DuckDuckGo being unreachable (connection refused) or answering
6802 /// non-2xx must still reach the Bing fallback instead of ending the chain.
6803 #[tokio::test]
6804 async fn duckduckgo_unreachable_or_non_2xx_falls_back_to_bing() {
6805 use crate::tools::spec::ToolContext;
6806 use codewhale_runtime::config::SearchProvider;
6807 use wiremock::matchers::{method, path, query_param};
6808 use wiremock::{Mock, MockServer, ResponseTemplate};
6809
6810 let server = MockServer::start().await;
6811 Mock::given(method("GET"))
6812 .and(path("/html/"))
6813 .respond_with(ResponseTemplate::new(503))
6814 .mount(&server)
6815 .await;
6816 Mock::given(method("GET"))
6817 .and(path("/bing"))
6818 .and(query_param("q", "ddg down"))
6819 .respond_with(ResponseTemplate::new(200).set_body_string(
6820 r#"
6821 <ol><li class="b_algo">
6822 <h2><a href="https://example.com/reachable">Reachable result</a></h2>
6823 <div class="b_caption"><p>Bing answered while DuckDuckGo was down.</p></div>
6824 </li></ol>
6825 "#,
6826 ))
6827 .mount(&server)
6828 .await;
6829 // Bind then drop a listener so the port refuses connections.
6830 let refused = {
6831 let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("bind");
6832 listener.local_addr().expect("addr").port()
6833 };
6834
6835 let tmp = tempfile::tempdir().expect("tempdir");
6836 let bing = format!("{}/bing", server.uri());
6837 let query = SearchQuery::new("ddg down".to_string(), 5, None, Vec::new(), None);
6838 for ddg in [
6839 format!("http://127.0.0.1:{refused}/html/"),
6840 format!("{}/html/", server.uri()),
6841 ] {
6842 let mut context = ToolContext::new(tmp.path().to_path_buf());
6843 context.search_provider = SearchProvider::DuckDuckGo;
6844 context.search_base_url = Some(ddg.clone());
6845 let raw = run_scrape_search_with_endpoints(
6846 SearchProvider::DuckDuckGo,
6847 &query,
6848 5_000,
6849 &context,
6850 ScrapeEndpoints {
6851 bing: &bing,
6852 allow_bing_fallback: Some(true),
6853 },
6854 )
6855 .await
6856 .unwrap_or_else(|error| panic!("{ddg}: Bing fallback should answer: {error}"));
6857
6858 assert_eq!(raw.backend, BackendId::Bing, "{ddg}");
6859 assert_eq!(raw.results.len(), 1, "{ddg}");
6860 assert_eq!(raw.results[0].url, "https://example.com/reachable");
6861 assert_eq!(
6862 raw.degraded,
6863 vec![
6864 DegradedReason::BackendUnavailable {
6865 backend: BackendId::DuckDuckGo
6866 },
6867 DegradedReason::BackendFallback {
6868 from: BackendId::DuckDuckGo,
6869 to: BackendId::Bing
6870 },
6871 ],
6872 "{ddg}"
6873 );
6874 assert!(
6875 raw.note
6876 .as_deref()
6877 .is_some_and(|note| note.contains("used Bing fallback")),
6878 "{ddg}: {:?}",
6879 raw.note
6880 );
6881 }
6882
6883 // Without the Bing fallback the DuckDuckGo failure is still reported.
6884 let mut context = ToolContext::new(tmp.path().to_path_buf());
6885 context.search_provider = SearchProvider::DuckDuckGo;
6886 context.search_base_url = Some(format!("{}/html/", server.uri()));
6887 let Err(error) = run_scrape_search_with_endpoints(
6888 SearchProvider::DuckDuckGo,
6889 &query,
6890 5_000,
6891 &context,
6892 ScrapeEndpoints {
6893 bing: &bing,
6894 allow_bing_fallback: Some(false),
6895 },
6896 )
6897 .await
6898 else {
6899 panic!("no fallback means the HTTP failure surfaces");
6900 };
6901 assert!(error.to_string().contains("HTTP 503"), "{error}");
6902 }
6903
6904 /// #6746: a DuckDuckGo that accepts the connection and then hangs must not
6905 /// eat the whole budget; Bing answers inside the same total.
6906 #[tokio::test]
6907 async fn hanging_duckduckgo_leaves_bing_time_inside_the_total_budget() {
6908 use crate::tools::spec::ToolContext;
6909 use codewhale_runtime::config::SearchProvider;
6910 use wiremock::matchers::{method, path};
6911 use wiremock::{Mock, MockServer, ResponseTemplate};
6912
6913 let server = MockServer::start().await;
6914 Mock::given(method("GET"))
6915 .and(path("/html/"))
6916 .respond_with(ResponseTemplate::new(200).set_delay(Duration::from_secs(30)))
6917 .mount(&server)
6918 .await;
6919 Mock::given(method("GET"))
6920 .and(path("/bing"))
6921 .respond_with(ResponseTemplate::new(200).set_body_string(
6922 r#"
6923 <ol><li class="b_algo">
6924 <h2><a href="https://example.com/after-hang">After the hang</a></h2>
6925 <div class="b_caption"><p>Bing answered after DuckDuckGo hung.</p></div>
6926 </li></ol>
6927 "#,
6928 ))
6929 .mount(&server)
6930 .await;
6931
6932 let tmp = tempfile::tempdir().expect("tempdir");
6933 let mut context = ToolContext::new(tmp.path().to_path_buf());
6934 context.search_provider = SearchProvider::DuckDuckGo;
6935 context.search_base_url = Some(format!("{}/html/", server.uri()));
6936 let query = SearchQuery::new("hang".to_string(), 5, None, Vec::new(), None);
6937 let budget = Duration::from_millis(3_000);
6938 let started = Instant::now();
6939 let outcome = tokio::time::timeout(
6940 budget,
6941 run_scrape_search_with_endpoints(
6942 SearchProvider::DuckDuckGo,
6943 &query,
6944 3_000,
6945 &context,
6946 ScrapeEndpoints {
6947 bing: &format!("{}/bing", server.uri()),
6948 allow_bing_fallback: Some(true),
6949 },
6950 ),
6951 )
6952 .await
6953 .expect("the whole search must finish inside its budget");
6954 let raw = outcome.expect("Bing fallback should answer after DuckDuckGo hangs");
6955
6956 assert_eq!(raw.backend, BackendId::Bing);
6957 assert_eq!(raw.results.len(), 1);
6958 assert!(started.elapsed() < budget, "{:?}", started.elapsed());
6959 assert!(
6960 raw.degraded.contains(&DegradedReason::BackendUnavailable {
6961 backend: BackendId::DuckDuckGo
6962 }),
6963 "{:?}",
6964 raw.degraded
6965 );
6966 }
6967
6968 /// #6746: a custom `search_base_url` keeps no public fallback and keeps the
6969 /// whole budget: a slow private endpoint is waited for, and Bing is never
6970 /// contacted, whether the endpoint answers late or hangs.
6971 #[tokio::test]
6972 async fn custom_base_url_keeps_full_budget_and_never_reaches_bing() {
6973 use crate::tools::spec::ToolContext;
6974 use codewhale_runtime::config::SearchProvider;
6975 use wiremock::matchers::{method, path};
6976 use wiremock::{Mock, MockServer, ResponseTemplate};
6977
6978 let tmp = tempfile::tempdir().expect("tempdir");
6979 let query = SearchQuery::new("private".to_string(), 5, None, Vec::new(), None);
6980 for (delay, expect_results) in [
6981 (Duration::from_millis(1_500), true),
6982 (Duration::from_secs(30), false),
6983 ] {
6984 let server = MockServer::start().await;
6985 Mock::given(method("GET"))
6986 .and(path("/html/"))
6987 .respond_with(ResponseTemplate::new(200).set_delay(delay).set_body_string(
6988 r#"
6989 <html><body>
6990 <a class="result__a" href="https://example.com/private">Private</a>
6991 <div class="result__snippet">Private result</div>
6992 </body></html>
6993 "#,
6994 ))
6995 .mount(&server)
6996 .await;
6997 Mock::given(method("GET"))
6998 .and(path("/bing"))
6999 .respond_with(ResponseTemplate::new(200))
7000 .mount(&server)
7001 .await;
7002
7003 let mut context = ToolContext::new(tmp.path().to_path_buf());
7004 context.search_provider = SearchProvider::DuckDuckGo;
7005 context.search_base_url = Some(format!("{}/html/", server.uri()));
7006 // 60% of 2s would be 1.2s: a 1.5s answer only arrives if the
7007 // private endpoint kept the whole budget.
7008 let outcome = run_scrape_search_with_endpoints(
7009 SearchProvider::DuckDuckGo,
7010 &query,
7011 2_000,
7012 &context,
7013 ScrapeEndpoints {
7014 bing: &format!("{}/bing", server.uri()),
7015 allow_bing_fallback: None,
7016 },
7017 )
7018 .await;
7019 if expect_results {
7020 let raw = outcome.expect("a slow private endpoint keeps its full budget");
7021 assert_eq!(raw.backend, BackendId::DuckDuckGo);
7022 assert_eq!(raw.results.len(), 1);
7023 } else {
7024 assert!(outcome.is_err(), "a hanging private endpoint is an error");
7025 }
7026 let bing_requests = server
7027 .received_requests()
7028 .await
7029 .expect("recorded requests")
7030 .iter()
7031 .filter(|request| request.url.path() == "/bing")
7032 .count();
7033 assert_eq!(bing_requests, 0, "custom base URL must not reach Bing");
7034 }
7035 }
7036
7037 #[tokio::test]
7038 async fn search_base_url_with_non_duckduckgo_provider_is_explicit_error() {
7039 use crate::tools::spec::{ToolContext, ToolSpec};
7040 use codewhale_runtime::config::SearchProvider;
7041
7042 let tmp = tempfile::tempdir().expect("tempdir");
7043 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
7044 ctx.search_provider = SearchProvider::Tavily;
7045 ctx.search_base_url = Some("https://search.internal.example/html/".to_string());
7046
7047 let err = WebSearchTool
7048 .execute(json!({"query": "rust async"}), &ctx)
7049 .await
7050 .expect_err("non-duckduckgo provider with base_url should error");
7051 let msg = err.to_string();
7052 assert!(
7053 msg.contains("[search].base_url")
7054 && msg.contains("provider = \"duckduckgo\" or \"searxng\"")
7055 && msg.contains("tavily"),
7056 "got `{msg}`"
7057 );
7058 }
7059
7060 #[test]
7061 fn rerank_assigns_sequential_ranks_starting_at_one() {
7062 // Simulates the post-dedup path: ranks may be non-contiguous after a
7063 // result is dropped; rerank must restore a clean 1..N sequence.
7064 let mut results = vec![
7065 SearchResult::new(
7066 5,
7067 "C".to_string(),
7068 "https://c.example.com/".to_string(),
7069 None,
7070 None,
7071 ),
7072 SearchResult::new(
7073 3,
7074 "A".to_string(),
7075 "https://a.example.com/".to_string(),
7076 None,
7077 None,
7078 ),
7079 SearchResult::new(
7080 1,
7081 "B".to_string(),
7082 "https://b.example.com/".to_string(),
7083 None,
7084 None,
7085 ),
7086 ];
7087 rerank(&mut results);
7088 assert_eq!(results[0].rank, 1);
7089 assert_eq!(results[1].rank, 2);
7090 assert_eq!(results[2].rank, 3);
7091 }
7092
7093 #[test]
7094 fn rerank_on_empty_slice_is_a_no_op() {
7095 let mut results: Vec<SearchResult> = Vec::new();
7096 rerank(&mut results); // must not panic
7097 }
7098
7099 #[test]
7100 fn register_search_citations_deduplicates_results_with_same_canonical_url() {
7101 let namespace = "dedup-test-session-fragments";
7102 let query = SearchQuery::new("deduplicate".to_string(), 5, None, Vec::new(), None);
7103 let raw = BackendSearch {
7104 backend: BackendId::DuckDuckGo,
7105 source: "duckduckgo".to_string(),
7106 backend_detail: None,
7107 results: vec![
7108 SearchResult::new(
7109 1,
7110 "First occurrence".to_string(),
7111 "https://dedup.example.com/page#section-a".to_string(),
7112 Some("first snippet".to_string()),
7113 None,
7114 ),
7115 SearchResult::new(
7116 2,
7117 "Unique result".to_string(),
7118 "https://other.dedup.example.com/different".to_string(),
7119 None,
7120 None,
7121 ),
7122 SearchResult::new(
7123 3,
7124 "Duplicate of first".to_string(),
7125 "https://dedup.example.com/page#section-b".to_string(),
7126 Some("duplicate snippet".to_string()),
7127 None,
7128 ),
7129 ],
7130 degraded: Vec::new(),
7131 note: None,
7132 };
7133 let mut response =
7134 finalize_search_response(query, QueryCapabilities::count_only(), raw, Instant::now());
7135 let context = crate::tools::spec::ToolContext::new(std::path::PathBuf::from("."))
7136 .with_state_namespace(namespace);
7137
7138 register_search_citations(&mut response, &context);
7139
7140 assert_eq!(
7141 response.count, 2,
7142 "duplicate canonical URL must reduce the result count"
7143 );
7144 assert_eq!(response.results.len(), 2);
7145 assert_eq!(response.results[0].rank, 1);
7146 assert_eq!(response.results[1].rank, 2);
7147 assert_eq!(response.results[0].url, "https://dedup.example.com/page");
7148 assert_eq!(
7149 response.results[1].url,
7150 "https://other.dedup.example.com/different"
7151 );
7152 assert_ne!(
7153 response.results[0].ref_id, response.results[1].ref_id,
7154 "surviving results must have distinct ref_ids"
7155 );
7156 assert!(response.message.contains('2'), "{}", response.message);
7157 }
7158
7159 #[test]
7160 fn register_search_citations_preserves_title_url_and_ref_id_metadata() {
7161 let namespace = "citation-metadata-test-session";
7162 let query = SearchQuery::new("docs".to_string(), 5, None, Vec::new(), None);
7163 let raw = BackendSearch {
7164 backend: BackendId::DuckDuckGo,
7165 source: "duckduckgo".to_string(),
7166 backend_detail: None,
7167 results: vec![SearchResult::new(
7168 1,
7169 "Official Docs".to_string(),
7170 "https://docs.citation-meta.example.com/reference".to_string(),
7171 Some("Comprehensive reference documentation.".to_string()),
7172 None,
7173 )],
7174 degraded: Vec::new(),
7175 note: None,
7176 };
7177 let mut response =
7178 finalize_search_response(query, QueryCapabilities::count_only(), raw, Instant::now());
7179 let context = crate::tools::spec::ToolContext::new(std::path::PathBuf::from("."))
7180 .with_state_namespace(namespace);
7181
7182 register_search_citations(&mut response, &context);
7183
7184 assert_eq!(response.count, 1);
7185 let result = &response.results[0];
7186 assert!(
7187 result.ref_id.starts_with("web_"),
7188 "ref_id must use web_ prefix; got `{}`",
7189 result.ref_id
7190 );
7191 assert_eq!(result.title, "Official Docs");
7192 assert_eq!(
7193 result.url,
7194 "https://docs.citation-meta.example.com/reference"
7195 );
7196 assert_eq!(result.rank, 1);
7197 let citation = crate::tools::web::citations::resolve(namespace, &result.ref_id)
7198 .expect("citation must be registered and resolvable in its session");
7199 assert_eq!(citation.ref_id, result.ref_id);
7200 assert_eq!(citation.url, result.url);
7201 assert_eq!(citation.title.as_deref(), Some("Official Docs"));
7202 assert!(
7203 !citation.retrieved_at.is_empty(),
7204 "retrieved_at must be set to the retrieval timestamp"
7205 );
7206 assert!(
7207 crate::tools::web::citations::resolve("other-session", &result.ref_id).is_none(),
7208 "citation must not leak to foreign sessions"
7209 );
7210 }
7211
7212 #[test]
7213 fn finalize_search_response_truncates_to_max_results_and_reranks() {
7214 let query = SearchQuery::new("truncate me".to_string(), 2, None, Vec::new(), None);
7215 let raw = BackendSearch {
7216 backend: BackendId::DuckDuckGo,
7217 source: "duckduckgo".to_string(),
7218 backend_detail: None,
7219 results: vec![
7220 SearchResult::new(
7221 1,
7222 "A".to_string(),
7223 "https://a.trunc.example.com/".to_string(),
7224 None,
7225 None,
7226 ),
7227 SearchResult::new(
7228 2,
7229 "B".to_string(),
7230 "https://b.trunc.example.com/".to_string(),
7231 None,
7232 None,
7233 ),
7234 SearchResult::new(
7235 3,
7236 "C".to_string(),
7237 "https://c.trunc.example.com/".to_string(),
7238 None,
7239 None,
7240 ),
7241 ],
7242 degraded: Vec::new(),
7243 note: None,
7244 };
7245
7246 let response =
7247 finalize_search_response(query, QueryCapabilities::count_only(), raw, Instant::now());
7248
7249 assert_eq!(response.count, 2, "must be truncated to max_results");
7250 assert_eq!(response.results.len(), 2);
7251 assert_eq!(response.results[0].rank, 1);
7252 assert_eq!(response.results[1].rank, 2);
7253 assert_eq!(response.results[0].title, "A");
7254 assert_eq!(response.results[1].title, "B");
7255 assert!(response.message.contains('2'), "{}", response.message);
7256 }
7257
7258 #[test]
7259 fn finalize_search_response_does_not_claim_an_ignored_locale_was_honored() {
7260 // A scrape flagged the explicit locale as ignored (here: an unmapped
7261 // DuckDuckGo region): the receipt must keep `honored.locale` false
7262 // instead of claiming the knob was honored.
7263 let query = SearchQuery::new(
7264 "query".to_string(),
7265 5,
7266 None,
7267 Vec::new(),
7268 Some("fr-FR".to_string()),
7269 );
7270 let raw = BackendSearch {
7271 backend: BackendId::DuckDuckGo,
7272 source: "duckduckgo".to_string(),
7273 backend_detail: None,
7274 results: Vec::new(),
7275 degraded: vec![DegradedReason::KnobIgnored {
7276 knob: QueryKnob::Locale,
7277 }],
7278 note: None,
7279 };
7280 let scrape_capabilities = QueryCapabilities {
7281 max_results: CapabilityState::Supported,
7282 recency: CapabilityState::Unsupported,
7283 domains: CapabilityState::Unsupported,
7284 locale: CapabilityState::Supported,
7285 published_date: CapabilityState::Unknown,
7286 };
7287 let response = finalize_search_response(query, scrape_capabilities, raw, Instant::now());
7288 assert!(
7289 !response.receipt.honored.locale,
7290 "an ignored locale must not be reported as honored"
7291 );
7292 assert!(
7293 response.receipt.degraded.iter().any(|reason| matches!(
7294 reason,
7295 DegradedReason::KnobIgnored {
7296 knob: QueryKnob::Locale
7297 }
7298 )),
7299 "the degraded receipt must carry the locale flag exactly once"
7300 );
7301 assert_eq!(response.receipt.degraded.len(), 1);
7302
7303 // A mapped locale with no scrape flag stays honored.
7304 let query = SearchQuery::new(
7305 "query".to_string(),
7306 5,
7307 None,
7308 Vec::new(),
7309 Some("zh-CN".to_string()),
7310 );
7311 let raw = BackendSearch {
7312 backend: BackendId::DuckDuckGo,
7313 source: "duckduckgo".to_string(),
7314 backend_detail: None,
7315 results: Vec::new(),
7316 degraded: Vec::new(),
7317 note: None,
7318 };
7319 let response = finalize_search_response(query, scrape_capabilities, raw, Instant::now());
7320 assert!(response.receipt.honored.locale);
7321 }
7322
7323 #[test]
7324 fn domain_matches_handles_subdomains_www_prefix_and_empty_list() {
7325 assert!(
7326 domain_matches("https://any.example.com/page", &[]),
7327 "empty domain list must accept all URLs"
7328 );
7329 assert!(domain_matches(
7330 "https://example.com/page",
7331 &["example.com".to_string()]
7332 ));
7333 assert!(domain_matches(
7334 "https://docs.example.com/page",
7335 &["example.com".to_string()]
7336 ));
7337 assert!(domain_matches(
7338 "https://www.example.com/page",
7339 &["example.com".to_string()]
7340 ));
7341 assert!(domain_matches(
7342 "https://example.com/page",
7343 &["www.example.com".to_string()]
7344 ));
7345 assert!(!domain_matches(
7346 "https://other.com/page",
7347 &["example.com".to_string()]
7348 ));
7349 assert!(!domain_matches(
7350 "https://notexample.com/page",
7351 &["example.com".to_string()]
7352 ));
7353 }
7354
7355 #[test]
7356 fn finalize_search_response_domain_post_filter_reranks_survivors() {
7357 let query = SearchQuery::new(
7358 "domain filter".to_string(),
7359 5,
7360 None,
7361 vec!["keep.example.com".to_string()],
7362 None,
7363 );
7364 let raw = BackendSearch {
7365 backend: BackendId::DuckDuckGo,
7366 source: "duckduckgo".to_string(),
7367 backend_detail: None,
7368 results: vec![
7369 SearchResult::new(
7370 1,
7371 "Drop this".to_string(),
7372 "https://other.example.com/page".to_string(),
7373 None,
7374 None,
7375 ),
7376 SearchResult::new(
7377 2,
7378 "Keep this".to_string(),
7379 "https://keep.example.com/page".to_string(),
7380 None,
7381 None,
7382 ),
7383 SearchResult::new(
7384 3,
7385 "Also drop".to_string(),
7386 "https://unrelated.example.com/page".to_string(),
7387 None,
7388 None,
7389 ),
7390 ],
7391 degraded: Vec::new(),
7392 note: None,
7393 };
7394
7395 let response =
7396 finalize_search_response(query, QueryCapabilities::count_only(), raw, Instant::now());
7397
7398 assert_eq!(response.count, 1, "only the matching domain must survive");
7399 assert_eq!(
7400 response.results[0].rank, 1,
7401 "survivor must be re-ranked to 1"
7402 );
7403 assert_eq!(response.results[0].title, "Keep this");
7404 assert!(
7405 response.receipt.degraded.iter().any(|reason| matches!(
7406 reason,
7407 DegradedReason::PostFiltered {
7408 knob: QueryKnob::Domains
7409 }
7410 )),
7411 "post-filtered degraded reason must be present"
7412 );
7413 }
7414
7415 #[test]
7416 fn fallback_receipt_carries_full_backend_chain_history() {
7417 // Verifies that the machine-readable degraded vec records every hop in
7418 // the fallback chain so callers can audit exactly what happened.
7419 let receipt = crate::tools::web::contract::SearchReceipt {
7420 backend: BackendId::Bing,
7421 backend_detail: None,
7422 requested: SearchQuery::new("fallback chain".to_string(), 5, None, Vec::new(), None),
7423 capabilities: QueryCapabilities::count_only(),
7424 honored: crate::tools::web::contract::HonoredQueryCapabilities {
7425 max_results: true,
7426 ..Default::default()
7427 },
7428 degraded: vec![
7429 DegradedReason::ChallengeDetected {
7430 backend: BackendId::DuckDuckGo,
7431 },
7432 DegradedReason::ScrapeFallback {
7433 from: BackendId::DuckDuckGo,
7434 to: BackendId::Bing,
7435 },
7436 ],
7437 latency_ms: 42,
7438 cache_hit: false,
7439 };
7440
7441 let value = serde_json::to_value(&receipt).expect("receipt must serialize");
7442 assert_eq!(value["backend"], "bing");
7443 assert_eq!(value["degraded"].as_array().unwrap().len(), 2);
7444 assert_eq!(value["degraded"][0]["kind"], "challenge_detected");
7445 assert_eq!(value["degraded"][0]["backend"], "duckduckgo");
7446 assert_eq!(value["degraded"][1]["kind"], "scrape_fallback");
7447 assert_eq!(value["degraded"][1]["from"], "duckduckgo");
7448 assert_eq!(value["degraded"][1]["to"], "bing");
7449
7450 let warning = receipt
7451 .warning()
7452 .expect("degraded receipt must produce a warning");
7453 assert!(warning.contains("bot challenge"), "{warning}");
7454 assert!(warning.contains("used bing fallback"), "{warning}");
7455 }
7456
7457 fn filtered_query(recency: Option<Recency>, locale: Option<&str>) -> SearchQuery {
7458 SearchQuery::new(
7459 "whale song".to_string(),
7460 5,
7461 recency,
7462 Vec::new(),
7463 locale.map(str::to_string),
7464 )
7465 }
7466
7467 #[test]
7468 fn query_filters_round_recency_up_and_split_locale() {
7469 let query = filtered_query(Some(Recency::Days(10)), Some("pt_BR"));
7470 let filters = QueryFilters::of(&query);
7471 assert_eq!(filters.window(), Some("month"));
7472 assert_eq!(filters.language().as_deref(), Some("pt"));
7473 assert_eq!(filters.region().as_deref(), Some("BR"));
7474 for (recency, window) in [
7475 (Recency::Day, "day"),
7476 (Recency::Week, "week"),
7477 (Recency::Month, "month"),
7478 (Recency::Year, "year"),
7479 (Recency::Days(400), "year"),
7480 ] {
7481 let query = filtered_query(Some(recency), None);
7482 assert_eq!(QueryFilters::of(&query).window(), Some(window));
7483 }
7484 let bare = filtered_query(None, Some("en"));
7485 assert_eq!(QueryFilters::of(&bare).region(), None);
7486 assert_eq!(QueryFilters::of(&bare).window(), None);
7487 }
7488
7489 #[tokio::test]
7490 async fn firecrawl_sends_recency_and_country() {
7491 use wiremock::matchers::{body_partial_json, method, path};
7492 use wiremock::{Mock, MockServer, ResponseTemplate};
7493
7494 let server = MockServer::start().await;
7495 Mock::given(method("POST"))
7496 .and(path("/v2/search"))
7497 .and(body_partial_json(json!({"tbs": "qdr:w", "country": "DE"})))
7498 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
7499 "success": true,
7500 "data": {"web": [{"title": "Fresh", "url": "https://example.de/a"}]}
7501 })))
7502 .expect(1)
7503 .mount(&server)
7504 .await;
7505 let query = filtered_query(Some(Recency::Week), Some("de-DE"));
7506 let (entries, _) = WebSearchTool
7507 .run_firecrawl_search_at(
7508 &format!("{}/v2/search", server.uri()),
7509 &query.query,
7510 QueryFilters::of(&query),
7511 5,
7512 5_000,
7513 None,
7514 )
7515 .await
7516 .expect("filtered Firecrawl search");
7517 assert_eq!(entries.len(), 1);
7518 }
7519
7520 #[tokio::test]
7521 async fn searxng_sends_time_range_and_language() {
7522 use crate::tools::spec::ToolContext;
7523 use wiremock::matchers::{method, path, query_param};
7524 use wiremock::{Mock, MockServer, ResponseTemplate};
7525
7526 let server = MockServer::start().await;
7527 Mock::given(method("GET"))
7528 .and(path("/search"))
7529 .and(query_param("time_range", "day"))
7530 .and(query_param("language", "fr-FR"))
7531 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
7532 "results": [{"title": "Aujourd'hui", "url": "https://example.fr/a", "content": "x"}]
7533 })))
7534 .expect(1)
7535 .mount(&server)
7536 .await;
7537 let tmp = tempfile::tempdir().expect("tempdir");
7538 let mut ctx = ToolContext::new(tmp.path().to_path_buf());
7539 ctx.search_provider = SearchProvider::Searxng;
7540 ctx.search_base_url = Some(server.uri());
7541 let query = filtered_query(Some(Recency::Day), Some("fr-FR"));
7542
7543 let (results, _) = WebSearchTool
7544 .run_searxng_search(&query.query, QueryFilters::of(&query), 5, 5_000, &ctx)
7545 .await
7546 .expect("filtered SearXNG search");
7547 assert_eq!(results.len(), 1);
7548 }
7549
7550 #[test]
7551 fn tavily_payload_carries_time_range_only_when_requested() {
7552 let query = filtered_query(Some(Recency::Year), Some("en-US"));
7553 let payload =
7554 super::tavily_search_payload("tvly-x", &query.query, QueryFilters::of(&query), 5);
7555 assert_eq!(payload["time_range"], "year");
7556 assert!(
7557 payload.get("country").is_none(),
7558 "Tavily takes country names, not tags"
7559 );
7560 let plain = super::tavily_search_payload("tvly-x", "q", QueryFilters::default(), 5);
7561 assert!(plain.get("time_range").is_none());
7562 }
7563
7564 #[test]
7565 fn serply_url_carries_language_and_country() {
7566 let query = filtered_query(Some(Recency::Day), Some("ja-JP"));
7567 let url = serply_search_url(&query.query, QueryFilters::of(&query), 3).expect("serply url");
7568 let pairs: std::collections::BTreeMap<String, String> = url
7569 .query_pairs()
7570 .map(|(k, v)| (k.into_owned(), v.into_owned()))
7571 .collect();
7572 assert_eq!(pairs.get("hl").map(String::as_str), Some("ja"));
7573 assert_eq!(pairs.get("gl").map(String::as_str), Some("jp"));
7574 assert!(
7575 !pairs.contains_key("tbs"),
7576 "Serply documents no recency parameter"
7577 );
7578 }
7579
7580 #[test]
7581 fn searchapi_url_carries_recency_language_and_country() {
7582 let query = filtered_query(Some(Recency::Day), Some("ja-JP"));
7583 let url =
7584 searchapi_search_url(&query.query, QueryFilters::of(&query), 3).expect("searchapi url");
7585 let pairs: std::collections::BTreeMap<String, String> = url
7586 .query_pairs()
7587 .map(|(k, v)| (k.into_owned(), v.into_owned()))
7588 .collect();
7589 assert_eq!(pairs.get("engine").map(String::as_str), Some("google"));
7590 assert_eq!(
7591 pairs.get("time_period").map(String::as_str),
7592 Some("last_day")
7593 );
7594 assert_eq!(pairs.get("hl").map(String::as_str), Some("ja"));
7595 assert_eq!(pairs.get("gl").map(String::as_str), Some("jp"));
7596 }
7597
7598 #[test]
7599 fn adapter_reported_ignored_locale_is_not_counted_as_honored() {
7600 let query = filtered_query(Some(Recency::Week), Some("en"));
7601 let raw = BackendSearch {
7602 backend: BackendId::Firecrawl,
7603 source: "firecrawl".to_string(),
7604 backend_detail: None,
7605 results: Vec::new(),
7606 degraded: vec![DegradedReason::KnobIgnored {
7607 knob: QueryKnob::Locale,
7608 }],
7609 note: None,
7610 };
7611 let capabilities = QueryCapabilities {
7612 recency: CapabilityState::Supported,
7613 locale: CapabilityState::Supported,
7614 ..QueryCapabilities::count_only()
7615 };
7616 let response = finalize_search_response(query, capabilities, raw, Instant::now());
7617 assert!(response.receipt.honored.recency);
7618 assert!(!response.receipt.honored.locale);
7619 assert_eq!(
7620 response
7621 .receipt
7622 .degraded
7623 .iter()
7624 .filter(|reason| matches!(
7625 reason,
7626 DegradedReason::KnobIgnored {
7627 knob: QueryKnob::Locale
7628 }
7629 ))
7630 .count(),
7631 1
7632 );
7633 }
7634 }
7635
7636 #[cfg(test)]
7637 #[path = "web/search_host_tests.rs"]
7638 mod host_tests;
7639
7639 lines RUST