返回 CodeWhale
contract.rs
根目录 / crates / engine / src / tools / web / contract.rs
1 //! Provider-neutral web-search request, result, and receipt types.
2 //!
3 //! Search backends vary widely in what they accept and return. These types are
4 //! the model-visible honesty boundary shared by `web_search` and `web.run`:
5 //! callers can distinguish requested knobs, actually honored behavior, and
6 //! degraded/post-filtered execution without depending on provider payloads.
7
8 use serde::{Deserialize, Serialize};
9
10 pub const MAX_SEARCH_RESULTS: u8 = 10;
11
12 /// Shared retrieval defaults. `web_search` and `web.run` both derive their
13 /// search knobs from these so the surfaces cannot drift apart.
14 pub const DEFAULT_SEARCH_RESULTS: usize = 5;
15 pub const DEFAULT_SEARCH_TIMEOUT_MS: u64 = 15_000;
16 pub const MAX_SEARCH_TIMEOUT_MS: u64 = 60_000;
17
18 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
19 #[serde(rename_all = "snake_case")]
20 pub enum BackendId {
21 ProviderNative,
22 Bing,
23 #[serde(rename = "duckduckgo")]
24 DuckDuckGo,
25 Firecrawl,
26 Tavily,
27 Bocha,
28 Metaso,
29 Searxng,
30 Baidu,
31 Volcengine,
32 Sofya,
33 Serply,
34 #[serde(rename = "deepseek")]
35 DeepSeek,
36 #[serde(rename = "searchapi")]
37 SearchApi,
38 }
39
40 impl BackendId {
41 #[must_use]
42 pub const fn as_str(self) -> &'static str {
43 match self {
44 Self::ProviderNative => "provider_native",
45 Self::Bing => "bing",
46 Self::DuckDuckGo => "duckduckgo",
47 Self::Firecrawl => "firecrawl",
48 Self::Tavily => "tavily",
49 Self::Bocha => "bocha",
50 Self::Metaso => "metaso",
51 Self::Searxng => "searxng",
52 Self::Baidu => "baidu",
53 Self::Volcengine => "volcengine",
54 Self::Sofya => "sofya",
55 Self::Serply => "serply",
56 Self::DeepSeek => "deepseek",
57 Self::SearchApi => "searchapi",
58 }
59 }
60 }
61
62 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
63 #[serde(rename_all = "snake_case")]
64 pub enum Recency {
65 Day,
66 Week,
67 Month,
68 Year,
69 Days(u16),
70 }
71
72 impl Recency {
73 #[must_use]
74 pub const fn days(self) -> u16 {
75 match self {
76 Self::Day => 1,
77 Self::Week => 7,
78 Self::Month => 30,
79 Self::Year => 365,
80 Self::Days(days) => days,
81 }
82 }
83 }
84
85 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
86 pub struct SearchQuery {
87 pub query: String,
88 pub max_results: u8,
89 #[serde(skip_serializing_if = "Option::is_none")]
90 pub recency: Option<Recency>,
91 #[serde(default, skip_serializing_if = "Vec::is_empty")]
92 pub domains: Vec<String>,
93 #[serde(skip_serializing_if = "Option::is_none")]
94 pub locale: Option<String>,
95 }
96
97 impl SearchQuery {
98 #[must_use]
99 pub fn new(
100 query: String,
101 max_results: usize,
102 recency: Option<Recency>,
103 domains: Vec<String>,
104 locale: Option<String>,
105 ) -> Self {
106 let mut domains = domains
107 .into_iter()
108 .map(|domain| {
109 let domain = domain.trim().trim_end_matches('.').to_ascii_lowercase();
110 domain.trim_start_matches("www.").to_string()
111 })
112 .filter(|domain| !domain.is_empty())
113 .collect::<Vec<_>>();
114 domains.sort_unstable();
115 domains.dedup();
116 Self {
117 query,
118 max_results: u8::try_from(max_results.clamp(1, usize::from(MAX_SEARCH_RESULTS)))
119 .unwrap_or(MAX_SEARCH_RESULTS),
120 recency,
121 domains,
122 locale: locale
123 .map(|value| value.trim().to_string())
124 .filter(|value| !value.is_empty()),
125 }
126 }
127 }
128
129 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
130 #[serde(rename_all = "snake_case")]
131 pub enum CapabilityState {
132 Supported,
133 Unsupported,
134 Unknown,
135 }
136
137 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
138 pub struct QueryCapabilities {
139 pub max_results: CapabilityState,
140 pub recency: CapabilityState,
141 pub domains: CapabilityState,
142 pub locale: CapabilityState,
143 pub published_date: CapabilityState,
144 }
145
146 impl QueryCapabilities {
147 #[must_use]
148 pub const fn count_only() -> Self {
149 Self {
150 max_results: CapabilityState::Supported,
151 recency: CapabilityState::Unsupported,
152 domains: CapabilityState::Unsupported,
153 locale: CapabilityState::Unsupported,
154 published_date: CapabilityState::Unknown,
155 }
156 }
157 }
158
159 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
160 pub struct HonoredQueryCapabilities {
161 pub max_results: bool,
162 pub recency: bool,
163 pub domains: bool,
164 pub locale: bool,
165 }
166
167 #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
168 #[serde(rename_all = "snake_case")]
169 pub enum QueryKnob {
170 Recency,
171 Domains,
172 Locale,
173 }
174
175 impl QueryKnob {
176 const fn as_str(self) -> &'static str {
177 match self {
178 Self::Recency => "recency",
179 Self::Domains => "domains",
180 Self::Locale => "locale",
181 }
182 }
183 }
184
185 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186 #[serde(tag = "kind", rename_all = "snake_case")]
187 pub enum DegradedReason {
188 BackendUnavailable {
189 backend: BackendId,
190 },
191 NoUsableResults {
192 backend: BackendId,
193 },
194 BackendFallback {
195 from: BackendId,
196 to: BackendId,
197 },
198 ChallengeDetected {
199 backend: BackendId,
200 },
201 ScrapeFallback {
202 from: BackendId,
203 to: BackendId,
204 },
205 KnobIgnored {
206 knob: QueryKnob,
207 },
208 PostFiltered {
209 knob: QueryKnob,
210 },
211 SynthesizedResults,
212 /// The provider stopped a native search answer at its output limit, so
213 /// the answer is incomplete (#6508).
214 AnswerCutByProvider,
215 CitationUnverified {
216 url: String,
217 reason: String,
218 },
219 CitationUnchecked {
220 url: String,
221 reason: String,
222 },
223 }
224
225 impl DegradedReason {
226 #[must_use]
227 pub fn message(&self) -> String {
228 match self {
229 Self::BackendUnavailable { backend } => {
230 format!("{} was unavailable", backend.as_str())
231 }
232 Self::NoUsableResults { backend } => {
233 format!("{} returned no usable results", backend.as_str())
234 }
235 Self::BackendFallback { from, to } => format!(
236 "{} did not answer; tried {} next",
237 from.as_str(),
238 to.as_str()
239 ),
240 Self::ChallengeDetected { backend } => {
241 format!("{} returned a bot challenge", backend.as_str())
242 }
243 Self::ScrapeFallback { from, to } => format!(
244 "{} returned no usable results; used {} fallback",
245 from.as_str(),
246 to.as_str()
247 ),
248 Self::KnobIgnored { knob } => {
249 format!("{} filter was not enforced by this backend", knob.as_str())
250 }
251 Self::PostFiltered { knob } => {
252 format!("results were post-filtered by {}", knob.as_str())
253 }
254 Self::SynthesizedResults => {
255 "results were synthesized by a model-backed search response".to_string()
256 }
257 Self::AnswerCutByProvider => {
258 "the provider stopped the search answer at its output limit; the answer is incomplete"
259 .to_string()
260 }
261 Self::CitationUnverified { url, reason } => {
262 format!("provider citation {url} failed link verification ({reason}) and was removed")
263 }
264 Self::CitationUnchecked { url, reason } => {
265 format!("provider citation {url} was not checked ({reason}) and stays in results unverified")
266 }
267 }
268 }
269 }
270
271 #[derive(Debug, Clone, Serialize, Deserialize)]
272 #[serde(deny_unknown_fields)]
273 pub struct CapturedSearchEntry {
274 pub title: String,
275 pub url: String,
276 pub snippet: Option<String>,
277 pub published: Option<String>,
278 }
279
280 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281 pub struct SearchResult {
282 pub rank: u8,
283 /// Session-scoped citation handle. Backends leave this empty; the shared
284 /// execution surface mints it before any result crosses the tool boundary.
285 pub ref_id: String,
286 pub title: String,
287 pub url: String,
288 #[serde(skip_serializing_if = "Option::is_none")]
289 pub snippet: Option<String>,
290 #[serde(skip_serializing_if = "Option::is_none")]
291 pub published: Option<String>,
292 pub domain: String,
293 }
294
295 impl SearchResult {
296 #[must_use]
297 pub fn new(
298 rank: usize,
299 title: String,
300 url: String,
301 snippet: Option<String>,
302 published: Option<String>,
303 ) -> Self {
304 let domain = reqwest::Url::parse(&url)
305 .ok()
306 .and_then(|parsed| parsed.host_str().map(str::to_ascii_lowercase))
307 .unwrap_or_default();
308 Self {
309 rank: u8::try_from(rank.clamp(1, 255)).unwrap_or(u8::MAX),
310 ref_id: String::new(),
311 title,
312 url,
313 snippet,
314 published,
315 domain,
316 }
317 }
318 }
319
320 #[derive(Debug, Clone)]
321 pub struct BackendSearch {
322 pub backend: BackendId,
323 pub source: String,
324 pub backend_detail: Option<String>,
325 pub results: Vec<SearchResult>,
326 pub degraded: Vec<DegradedReason>,
327 pub note: Option<String>,
328 }
329
330 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331 pub struct SearchReceipt {
332 pub backend: BackendId,
333 #[serde(skip_serializing_if = "Option::is_none")]
334 pub backend_detail: Option<String>,
335 pub requested: SearchQuery,
336 pub capabilities: QueryCapabilities,
337 pub honored: HonoredQueryCapabilities,
338 #[serde(default, skip_serializing_if = "Vec::is_empty")]
339 pub degraded: Vec<DegradedReason>,
340 pub latency_ms: u32,
341 pub cache_hit: bool,
342 }
343
344 impl SearchReceipt {
345 #[must_use]
346 pub fn warning(&self) -> Option<String> {
347 if self.degraded.is_empty() {
348 None
349 } else {
350 Some(
351 self.degraded
352 .iter()
353 .map(DegradedReason::message)
354 .collect::<Vec<_>>()
355 .join("; "),
356 )
357 }
358 }
359 }
360
361 #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
362 pub struct SearchResponse {
363 pub query: String,
364 pub source: String,
365 pub count: usize,
366 pub message: String,
367 pub results: Vec<SearchResult>,
368 #[serde(default, skip_serializing_if = "Option::is_none")]
369 pub unverified_synthesis: Option<String>,
370 pub receipt: SearchReceipt,
371 }
372
373 #[cfg(test)]
374 mod tests {
375 use super::*;
376
377 #[test]
378 fn retrieval_defaults_are_coherent_across_search_and_fetch() {
379 use super::super::fetch::{DEFAULT_TIMEOUT, HARD_MAX_TIMEOUT};
380
381 // Search and fetch share one default and one hard-cap timeout so the
382 // two halves of the retrieval path behave identically by default.
383 assert_eq!(
384 u128::from(DEFAULT_SEARCH_TIMEOUT_MS),
385 DEFAULT_TIMEOUT.as_millis()
386 );
387 assert_eq!(
388 u128::from(MAX_SEARCH_TIMEOUT_MS),
389 HARD_MAX_TIMEOUT.as_millis()
390 );
391 assert!(DEFAULT_SEARCH_RESULTS <= usize::from(MAX_SEARCH_RESULTS));
392 }
393
394 #[test]
395 fn search_query_normalizes_domains_and_bounds_count() {
396 let query = SearchQuery::new(
397 "rust async".to_string(),
398 99,
399 Some(Recency::Week),
400 vec![" WWW.Example.COM. ".to_string(), "example.com".to_string()],
401 Some(" en-US ".to_string()),
402 );
403
404 assert_eq!(query.max_results, 10);
405 assert_eq!(query.domains, vec!["example.com"]);
406 assert_eq!(query.locale.as_deref(), Some("en-US"));
407 assert_eq!(query.recency.map(Recency::days), Some(7));
408 }
409
410 #[test]
411 fn normalized_result_derives_domain_and_rank() {
412 let result = SearchResult::new(
413 2,
414 "Example".to_string(),
415 "https://Docs.Example.com/path".to_string(),
416 Some("summary".to_string()),
417 None,
418 );
419
420 assert_eq!(result.rank, 2);
421 assert_eq!(result.domain, "docs.example.com");
422 }
423
424 #[test]
425 fn degraded_receipt_is_machine_readable_and_human_visible() {
426 let receipt = SearchReceipt {
427 backend: BackendId::DuckDuckGo,
428 backend_detail: None,
429 requested: SearchQuery::new(
430 "fresh result".to_string(),
431 5,
432 Some(Recency::Day),
433 Vec::new(),
434 None,
435 ),
436 capabilities: QueryCapabilities::count_only(),
437 honored: HonoredQueryCapabilities {
438 max_results: true,
439 ..HonoredQueryCapabilities::default()
440 },
441 degraded: vec![DegradedReason::KnobIgnored {
442 knob: QueryKnob::Recency,
443 }],
444 latency_ms: 4,
445 cache_hit: false,
446 };
447
448 let value = serde_json::to_value(&receipt).expect("receipt serializes");
449 assert_eq!(value["backend"], "duckduckgo");
450 assert_eq!(value["degraded"][0]["kind"], "knob_ignored");
451 assert!(receipt.warning().expect("warning").contains("recency"));
452 }
453
454 #[test]
455 fn scrape_fallback_receipt_preserves_backend_transitions() {
456 let receipt = SearchReceipt {
457 backend: BackendId::Bing,
458 backend_detail: None,
459 requested: SearchQuery::new("fallback query".to_string(), 5, None, Vec::new(), None),
460 capabilities: QueryCapabilities::count_only(),
461 honored: HonoredQueryCapabilities {
462 max_results: true,
463 ..HonoredQueryCapabilities::default()
464 },
465 degraded: vec![
466 DegradedReason::ChallengeDetected {
467 backend: BackendId::DuckDuckGo,
468 },
469 DegradedReason::ScrapeFallback {
470 from: BackendId::DuckDuckGo,
471 to: BackendId::Bing,
472 },
473 ],
474 latency_ms: 12,
475 cache_hit: false,
476 };
477
478 let value = serde_json::to_value(&receipt).expect("receipt serializes");
479 assert_eq!(value["backend"], "bing");
480 assert_eq!(value["degraded"][0]["kind"], "challenge_detected");
481 assert_eq!(value["degraded"][0]["backend"], "duckduckgo");
482 assert_eq!(value["degraded"][1]["kind"], "scrape_fallback");
483 assert_eq!(value["degraded"][1]["from"], "duckduckgo");
484 assert_eq!(value["degraded"][1]["to"], "bing");
485 let warning = receipt.warning().expect("warning");
486 assert!(warning.contains("bot challenge"));
487 assert!(warning.contains("used bing fallback"));
488 }
489 }
490
490 lines RUST