Skip to main content

tea_coding_tools/
web_search.rs

1use std::collections::BTreeSet;
2use std::fmt::{self, Write as _};
3use std::future::Future;
4use std::net::IpAddr;
5use std::pin::Pin;
6use std::str::FromStr;
7use std::sync::Arc;
8use std::time::Duration;
9
10use futures_util::{StreamExt as _, stream};
11use serde::Deserialize;
12use serde_json::{Map, Value, json};
13use tea_control::CancellationScope;
14use tea_model::WebSearchOptions;
15use tea_protocol::{
16    ContentBlock, ExternalSource, MAX_EXTERNAL_SOURCE_TEXT_BYTES, MAX_EXTERNAL_SOURCE_TITLE_BYTES,
17    ProtocolMetadata, ToolIdempotency,
18};
19use tea_provider_http::ProviderHttpConfig;
20use tea_tools::{
21    BoxToolExecutionStream, ToolConcurrency, ToolEffect, ToolExecutionEvent, ToolExecutionFailure,
22    ToolExecutionSemantics, ToolExecutor, ToolName, ToolResource, ToolResourceAccess,
23    ToolResourceError, ToolResult, ToolRetrySafety, ToolSpec, ToolSpecError, ToolTimeout,
24    ToolVersion, ValidatedToolInvocation,
25};
26use thiserror::Error;
27use url::Url;
28
29/// Default number of client search results requested from a backend.
30pub const DEFAULT_WEB_SEARCH_RESULT_LIMIT: usize = 5;
31/// Maximum number of client search results retained in one invocation.
32pub const MAX_WEB_SEARCH_RESULT_LIMIT: usize = 20;
33/// Maximum UTF-8 bytes accepted in one client search query.
34pub const MAX_WEB_SEARCH_QUERY_BYTES: usize = 2_048;
35/// Maximum encoded response body accepted from a client search backend.
36pub const MAX_WEB_SEARCH_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
37/// Default production endpoint for the Tavily Search API.
38pub const DEFAULT_TAVILY_SEARCH_ENDPOINT: &str = "https://api.tavily.com/search";
39
40const MAX_WEB_SEARCH_SNIPPET_BYTES: usize = 4 * 1024;
41const MAX_TAVILY_API_KEY_BYTES: usize = 512;
42const MAX_TAVILY_TIMEOUT: Duration = Duration::from_mins(1);
43
44/// Invalid provider-neutral search request.
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
46pub enum SearchRequestError {
47    /// Query text is empty, oversized, or control-containing.
48    #[error("web search query is invalid")]
49    InvalidQuery,
50    /// Domain policy is invalid or internally conflicting.
51    #[error("web search domain policy is invalid")]
52    InvalidDomains,
53    /// Result limit is outside the portable contract.
54    #[error("web search result limit is invalid")]
55    InvalidLimit,
56}
57
58/// Bounded provider-neutral request passed to a client search backend.
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub struct SearchRequest {
61    query: String,
62    options: WebSearchOptions,
63    limit: usize,
64}
65
66impl SearchRequest {
67    /// Creates and validates one client search request.
68    ///
69    /// # Errors
70    ///
71    /// Rejects invalid queries, conflicting domain filters, and result limits
72    /// outside `1..=20`.
73    pub fn new<I, S, J, T>(
74        query: impl Into<String>,
75        allowed_domains: I,
76        blocked_domains: J,
77        limit: usize,
78    ) -> Result<Self, SearchRequestError>
79    where
80        I: IntoIterator<Item = S>,
81        S: Into<String>,
82        J: IntoIterator<Item = T>,
83        T: Into<String>,
84    {
85        let query = validate_query_and_limit(query.into(), limit)?;
86        let allowed_domains = allowed_domains
87            .into_iter()
88            .map(Into::into)
89            .collect::<Vec<_>>();
90        let blocked_domains = blocked_domains
91            .into_iter()
92            .map(Into::into)
93            .collect::<Vec<_>>();
94        if !allowed_domains.is_empty() && !blocked_domains.is_empty() {
95            return Err(SearchRequestError::InvalidDomains);
96        }
97        let options = if !allowed_domains.is_empty() {
98            WebSearchOptions::new()
99                .with_allowed_domains(allowed_domains)
100                .map_err(|_| SearchRequestError::InvalidDomains)?
101        } else if !blocked_domains.is_empty() {
102            WebSearchOptions::new()
103                .with_blocked_domains(blocked_domains)
104                .map_err(|_| SearchRequestError::InvalidDomains)?
105        } else {
106            WebSearchOptions::new()
107        };
108        Ok(Self {
109            query,
110            options,
111            limit,
112        })
113    }
114
115    /// Creates a request from the complete validated portable search options.
116    ///
117    /// This constructor preserves optional location data for client backends
118    /// that can implement location-aware search without changing the provider
119    /// port.
120    ///
121    /// # Errors
122    ///
123    /// Rejects invalid queries and result limits outside `1..=20`.
124    pub fn from_options(
125        query: impl Into<String>,
126        options: WebSearchOptions,
127        limit: usize,
128    ) -> Result<Self, SearchRequestError> {
129        let query = validate_query_and_limit(query.into(), limit)?;
130        Ok(Self {
131            query,
132            options,
133            limit,
134        })
135    }
136
137    /// Returns the exact validated query.
138    #[must_use]
139    pub fn query(&self) -> &str {
140        &self.query
141    }
142
143    /// Returns the deterministic domain allowlist.
144    #[must_use]
145    pub fn allowed_domains(&self) -> &[String] {
146        self.options.allowed_domains()
147    }
148
149    /// Returns the deterministic domain blocklist.
150    #[must_use]
151    pub fn blocked_domains(&self) -> &[String] {
152        self.options.blocked_domains()
153    }
154
155    /// Returns the optional approximate location for capable client backends.
156    #[must_use]
157    pub const fn location(&self) -> Option<&tea_model::WebSearchLocation> {
158        self.options.location()
159    }
160
161    /// Returns the requested result limit.
162    #[must_use]
163    pub const fn limit(&self) -> usize {
164        self.limit
165    }
166}
167
168fn validate_query_and_limit(query: String, limit: usize) -> Result<String, SearchRequestError> {
169    if query.trim().is_empty()
170        || query.len() > MAX_WEB_SEARCH_QUERY_BYTES
171        || query.chars().any(char::is_control)
172    {
173        return Err(SearchRequestError::InvalidQuery);
174    }
175    if !(1..=MAX_WEB_SEARCH_RESULT_LIMIT).contains(&limit) {
176        return Err(SearchRequestError::InvalidLimit);
177    }
178    Ok(query)
179}
180
181/// Stable failure category returned by a client search backend.
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum SearchProviderErrorCode {
184    /// Backend or credential configuration is invalid.
185    InvalidConfiguration,
186    /// The backend rejected the normalized request.
187    InvalidRequest,
188    /// Credentials were rejected.
189    Authentication,
190    /// The backend rate limit was reached.
191    RateLimited,
192    /// The account quota or plan limit was reached.
193    QuotaExceeded,
194    /// The backend timed out.
195    Timeout,
196    /// The backend could not be reached.
197    Transport,
198    /// The backend was temporarily unavailable.
199    Unavailable,
200    /// The backend returned an invalid or oversized success response.
201    MalformedResponse,
202    /// Cooperative cancellation was requested.
203    Cancelled,
204}
205
206/// Secret-independent client search failure.
207#[derive(Clone, Copy, PartialEq, Eq)]
208pub struct SearchProviderError {
209    code: SearchProviderErrorCode,
210    message: &'static str,
211}
212
213impl SearchProviderError {
214    /// Creates a failure with a stable, non-sensitive message.
215    #[must_use]
216    pub const fn new(code: SearchProviderErrorCode) -> Self {
217        Self {
218            code,
219            message: provider_error_message(code),
220        }
221    }
222
223    /// Creates a cooperative cancellation failure.
224    #[must_use]
225    pub const fn cancelled() -> Self {
226        Self::new(SearchProviderErrorCode::Cancelled)
227    }
228
229    /// Returns the stable category.
230    #[must_use]
231    pub const fn code(&self) -> SearchProviderErrorCode {
232        self.code
233    }
234
235    /// Returns a bounded secret-independent technical message.
236    #[must_use]
237    pub const fn message(&self) -> &'static str {
238        self.message
239    }
240}
241
242impl fmt::Debug for SearchProviderError {
243    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
244        formatter
245            .debug_struct("SearchProviderError")
246            .field("code", &self.code)
247            .field("message", &self.message)
248            .finish()
249    }
250}
251
252impl fmt::Display for SearchProviderError {
253    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
254        formatter.write_str(self.message)
255    }
256}
257
258impl std::error::Error for SearchProviderError {}
259
260const fn provider_error_message(code: SearchProviderErrorCode) -> &'static str {
261    match code {
262        SearchProviderErrorCode::InvalidConfiguration => {
263            "web search backend configuration is invalid"
264        }
265        SearchProviderErrorCode::InvalidRequest => "web search request is invalid",
266        SearchProviderErrorCode::Authentication => "web search credentials were rejected",
267        SearchProviderErrorCode::RateLimited => "web search backend rate limit was reached",
268        SearchProviderErrorCode::QuotaExceeded => "web search backend quota was exceeded",
269        SearchProviderErrorCode::Timeout => "web search backend timed out",
270        SearchProviderErrorCode::Transport => "web search backend transport failed",
271        SearchProviderErrorCode::Unavailable => "web search backend is unavailable",
272        SearchProviderErrorCode::MalformedResponse => "web search backend response is invalid",
273        SearchProviderErrorCode::Cancelled => "web search was cancelled",
274    }
275}
276
277/// One normalized client search result.
278#[derive(Debug, Clone, PartialEq)]
279pub struct SearchResult {
280    source: ExternalSource,
281    score: Option<f64>,
282}
283
284impl SearchResult {
285    /// Creates a source result with an optional normalized relevance score.
286    ///
287    /// # Errors
288    ///
289    /// Rejects non-finite scores or scores outside `0.0..=1.0`.
290    pub fn new(source: ExternalSource, score: Option<f64>) -> Result<Self, SearchProviderError> {
291        if score.is_some_and(|score| !score.is_finite() || !(0.0..=1.0).contains(&score)) {
292            return Err(SearchProviderError::new(
293                SearchProviderErrorCode::MalformedResponse,
294            ));
295        }
296        Ok(Self { source, score })
297    }
298
299    /// Returns the normalized source.
300    #[must_use]
301    pub const fn source(&self) -> &ExternalSource {
302        &self.source
303    }
304
305    /// Returns the optional relevance score.
306    #[must_use]
307    pub const fn score(&self) -> Option<f64> {
308        self.score
309    }
310}
311
312/// Bounded provider-neutral client search response.
313#[derive(Debug, Clone, PartialEq)]
314pub struct SearchResponse {
315    results: Vec<SearchResult>,
316    truncated: bool,
317}
318
319impl SearchResponse {
320    /// Creates a response containing no more than the portable result limit.
321    ///
322    /// # Errors
323    ///
324    /// Rejects responses containing more than 20 results.
325    pub fn new(results: Vec<SearchResult>, truncated: bool) -> Result<Self, SearchProviderError> {
326        if results.len() > MAX_WEB_SEARCH_RESULT_LIMIT {
327            return Err(SearchProviderError::new(
328                SearchProviderErrorCode::MalformedResponse,
329            ));
330        }
331        Ok(Self { results, truncated })
332    }
333
334    /// Returns normalized results in backend relevance order.
335    #[must_use]
336    pub fn results(&self) -> &[SearchResult] {
337        &self.results
338    }
339
340    /// Returns whether the backend returned more results than retained.
341    #[must_use]
342    pub const fn truncated(&self) -> bool {
343        self.truncated
344    }
345}
346
347/// Object-safe future returned by [`SearchProvider`].
348pub type SearchFuture<'a> =
349    Pin<Box<dyn Future<Output = Result<SearchResponse, SearchProviderError>> + Send + 'a>>;
350
351/// Object-safe client web-search backend port.
352pub trait SearchProvider: fmt::Debug + Send + Sync {
353    /// Returns the configured disclosure destination used for policy resources.
354    fn destination(&self) -> &str;
355
356    /// Executes one bounded request with cooperative cancellation.
357    fn search(&self, request: SearchRequest, cancellation: CancellationScope) -> SearchFuture<'_>;
358}
359
360/// Redacted Tavily API credential.
361#[derive(Clone, PartialEq, Eq)]
362pub struct TavilyApiKey(String);
363
364impl TavilyApiKey {
365    /// Creates a bounded visible-ASCII API key.
366    ///
367    /// # Errors
368    ///
369    /// Rejects empty, oversized, whitespace-containing, and control-containing keys.
370    pub fn new(value: impl Into<String>) -> Result<Self, SearchProviderError> {
371        let value = value.into();
372        if value.is_empty()
373            || value.len() > MAX_TAVILY_API_KEY_BYTES
374            || !value.bytes().all(|byte| byte.is_ascii_graphic())
375        {
376            return Err(SearchProviderError::new(
377                SearchProviderErrorCode::InvalidConfiguration,
378            ));
379        }
380        Ok(Self(value))
381    }
382
383    fn expose(&self) -> &str {
384        &self.0
385    }
386}
387
388impl fmt::Debug for TavilyApiKey {
389    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
390        formatter.write_str("TavilyApiKey(**REDACTED**)")
391    }
392}
393
394/// Validated Tavily HTTP endpoint and timeout policy.
395#[derive(Debug, Clone, PartialEq, Eq)]
396pub struct TavilySearchConfig {
397    endpoint: String,
398    timeout: Duration,
399}
400
401impl TavilySearchConfig {
402    /// Creates a Tavily backend configuration.
403    ///
404    /// HTTPS is required except for loopback HTTP endpoints used by local
405    /// gateways and deterministic contract tests. User information, query
406    /// strings, and fragments are rejected so credentials cannot be embedded in
407    /// a displayable destination.
408    ///
409    /// # Errors
410    ///
411    /// Rejects invalid endpoints and timeouts outside `1ms..=60s`.
412    pub fn new(endpoint: impl AsRef<str>, timeout: Duration) -> Result<Self, SearchProviderError> {
413        let endpoint = Url::parse(endpoint.as_ref())
414            .map_err(|_| SearchProviderError::new(SearchProviderErrorCode::InvalidConfiguration))?;
415        let loopback_http =
416            endpoint.scheme() == "http" && endpoint.host_str().is_some_and(is_loopback_host);
417        let valid = (endpoint.scheme() == "https" || loopback_http)
418            && endpoint.host_str().is_some()
419            && endpoint.username().is_empty()
420            && endpoint.password().is_none()
421            && endpoint.query().is_none()
422            && endpoint.fragment().is_none()
423            && endpoint.path() != "/"
424            && !timeout.is_zero()
425            && timeout <= MAX_TAVILY_TIMEOUT;
426        if !valid {
427            return Err(SearchProviderError::new(
428                SearchProviderErrorCode::InvalidConfiguration,
429            ));
430        }
431        Ok(Self {
432            endpoint: endpoint.to_string(),
433            timeout,
434        })
435    }
436
437    /// Creates the production endpoint with a caller-selected timeout.
438    ///
439    /// # Errors
440    ///
441    /// Rejects an invalid timeout.
442    pub fn production(timeout: Duration) -> Result<Self, SearchProviderError> {
443        Self::new(DEFAULT_TAVILY_SEARCH_ENDPOINT, timeout)
444    }
445
446    /// Returns the canonical endpoint.
447    #[must_use]
448    pub fn endpoint(&self) -> &str {
449        &self.endpoint
450    }
451
452    /// Returns the request timeout.
453    #[must_use]
454    pub const fn timeout(&self) -> Duration {
455        self.timeout
456    }
457}
458
459fn is_loopback_host(host: &str) -> bool {
460    host == "localhost"
461        || host
462            .parse::<IpAddr>()
463            .is_ok_and(|address| address.is_loopback())
464}
465
466/// Production Tavily implementation of [`SearchProvider`].
467#[derive(Debug, Clone)]
468pub struct TavilySearchProvider {
469    config: TavilySearchConfig,
470    api_key: TavilyApiKey,
471    client: reqwest::Client,
472}
473
474impl TavilySearchProvider {
475    /// Builds a reusable Tavily client under the shared provider HTTP policy.
476    ///
477    /// # Errors
478    ///
479    /// Returns an error when the HTTP client cannot be constructed.
480    pub fn new(
481        config: TavilySearchConfig,
482        api_key: TavilyApiKey,
483        http: &ProviderHttpConfig,
484    ) -> Result<Self, SearchProviderError> {
485        let client = http
486            .build_client_without_redirects(config.timeout())
487            .map_err(|_| SearchProviderError::new(SearchProviderErrorCode::InvalidConfiguration))?;
488        Ok(Self {
489            config,
490            api_key,
491            client,
492        })
493    }
494
495    async fn execute(
496        &self,
497        request: SearchRequest,
498        cancellation: CancellationScope,
499    ) -> Result<SearchResponse, SearchProviderError> {
500        let mut body = Map::new();
501        body.insert("query".to_owned(), json!(request.query()));
502        body.insert("search_depth".to_owned(), json!("basic"));
503        body.insert("max_results".to_owned(), json!(request.limit()));
504        body.insert("include_answer".to_owned(), Value::Bool(false));
505        body.insert("include_raw_content".to_owned(), Value::Bool(false));
506        body.insert("include_images".to_owned(), Value::Bool(false));
507        if !request.allowed_domains().is_empty() {
508            body.insert(
509                "include_domains".to_owned(),
510                json!(request.allowed_domains()),
511            );
512        }
513        if !request.blocked_domains().is_empty() {
514            body.insert(
515                "exclude_domains".to_owned(),
516                json!(request.blocked_domains()),
517            );
518        }
519        let send = self
520            .client
521            .post(self.config.endpoint())
522            .bearer_auth(self.api_key.expose())
523            .json(&Value::Object(body))
524            .send();
525        let response = tokio::select! {
526            biased;
527            () = cancellation.cancelled() => return Err(SearchProviderError::cancelled()),
528            response = send => response.map_err(|error| map_reqwest_error(&error))?,
529        };
530        if !response.status().is_success() {
531            return Err(SearchProviderError::new(status_code(response.status())));
532        }
533        let bytes = read_bounded_body(response, &cancellation).await?;
534        let raw = serde_json::from_slice::<TavilyResponse>(&bytes)
535            .map_err(|_| SearchProviderError::new(SearchProviderErrorCode::MalformedResponse))?;
536        normalize_tavily_response(raw, request.limit())
537    }
538}
539
540impl SearchProvider for TavilySearchProvider {
541    fn destination(&self) -> &str {
542        self.config.endpoint()
543    }
544
545    fn search(&self, request: SearchRequest, cancellation: CancellationScope) -> SearchFuture<'_> {
546        Box::pin(self.execute(request, cancellation))
547    }
548}
549
550fn map_reqwest_error(error: &reqwest::Error) -> SearchProviderError {
551    let code = if error.is_timeout() {
552        SearchProviderErrorCode::Timeout
553    } else {
554        SearchProviderErrorCode::Transport
555    };
556    SearchProviderError::new(code)
557}
558
559fn status_code(status: reqwest::StatusCode) -> SearchProviderErrorCode {
560    match status.as_u16() {
561        400 | 404 | 422 => SearchProviderErrorCode::InvalidRequest,
562        401 | 403 => SearchProviderErrorCode::Authentication,
563        429 => SearchProviderErrorCode::RateLimited,
564        432 | 433 => SearchProviderErrorCode::QuotaExceeded,
565        500..=599 => SearchProviderErrorCode::Unavailable,
566        _ => SearchProviderErrorCode::Transport,
567    }
568}
569
570async fn read_bounded_body(
571    response: reqwest::Response,
572    cancellation: &CancellationScope,
573) -> Result<Vec<u8>, SearchProviderError> {
574    if response
575        .content_length()
576        .is_some_and(|length| length > MAX_WEB_SEARCH_RESPONSE_BYTES as u64)
577    {
578        return Err(SearchProviderError::new(
579            SearchProviderErrorCode::MalformedResponse,
580        ));
581    }
582    let mut stream = response.bytes_stream();
583    let mut bytes = Vec::new();
584    loop {
585        let chunk = tokio::select! {
586            biased;
587            () = cancellation.cancelled() => return Err(SearchProviderError::cancelled()),
588            chunk = stream.next() => chunk,
589        };
590        let Some(chunk) = chunk else {
591            break;
592        };
593        let chunk = chunk.map_err(|error| map_reqwest_error(&error))?;
594        if bytes.len().saturating_add(chunk.len()) > MAX_WEB_SEARCH_RESPONSE_BYTES {
595            return Err(SearchProviderError::new(
596                SearchProviderErrorCode::MalformedResponse,
597            ));
598        }
599        bytes.extend_from_slice(&chunk);
600    }
601    Ok(bytes)
602}
603
604#[derive(Debug, Deserialize)]
605struct TavilyResponse {
606    results: Vec<TavilyResult>,
607}
608
609#[derive(Debug, Deserialize)]
610struct TavilyResult {
611    title: String,
612    url: String,
613    content: String,
614    score: Option<f64>,
615}
616
617fn normalize_tavily_response(
618    raw: TavilyResponse,
619    limit: usize,
620) -> Result<SearchResponse, SearchProviderError> {
621    let truncated = raw.results.len() > limit;
622    let results = raw
623        .results
624        .into_iter()
625        .take(limit)
626        .map(|result| {
627            let title = truncate_utf8(&result.title, MAX_EXTERNAL_SOURCE_TITLE_BYTES);
628            let mut source = ExternalSource::new(result.url)
629                .and_then(|source| source.with_title(title))
630                .map_err(|_| {
631                    SearchProviderError::new(SearchProviderErrorCode::MalformedResponse)
632                })?;
633            if !result.content.is_empty() {
634                let snippet_limit =
635                    MAX_WEB_SEARCH_SNIPPET_BYTES.min(MAX_EXTERNAL_SOURCE_TEXT_BYTES);
636                source = source
637                    .with_snippet(truncate_utf8(&result.content, snippet_limit))
638                    .map_err(|_| {
639                        SearchProviderError::new(SearchProviderErrorCode::MalformedResponse)
640                    })?;
641            }
642            SearchResult::new(source, result.score)
643        })
644        .collect::<Result<Vec<_>, _>>()?;
645    SearchResponse::new(results, truncated)
646}
647
648fn truncate_utf8(value: &str, max_bytes: usize) -> &str {
649    if value.len() <= max_bytes {
650        return value;
651    }
652    let mut end = max_bytes;
653    while !value.is_char_boundary(end) {
654        end -= 1;
655    }
656    &value[..end]
657}
658
659/// Client executor for the stable `web_search` tool contract.
660#[derive(Debug, Clone)]
661pub struct WebSearchTool {
662    provider: Arc<dyn SearchProvider>,
663    configured_options: WebSearchOptions,
664}
665
666impl WebSearchTool {
667    /// Creates a client search executor with static product domain policy.
668    #[must_use]
669    pub fn new(provider: Arc<dyn SearchProvider>, configured_options: WebSearchOptions) -> Self {
670        Self {
671            provider,
672            configured_options,
673        }
674    }
675
676    /// Builds the portable client/hosted search tool contract.
677    ///
678    /// # Errors
679    ///
680    /// Returns an error only if the static contract violates tool bounds.
681    pub fn spec() -> Result<ToolSpec, ToolSpecError> {
682        ToolSpec::new(
683            ToolName::from_str("web_search").map_err(|_| ToolSpecError::InvalidDescription)?,
684            ToolVersion::from_str("1.0.0").map_err(|_| ToolSpecError::InvalidDescription)?,
685            "Search the public web and return bounded normalized sources.",
686            json!({
687                "type":"object",
688                "properties":{
689                    "query":{"type":"string","minLength":1,"maxLength":MAX_WEB_SEARCH_QUERY_BYTES},
690                    "allowed_domains":{
691                        "type":"array","maxItems":tea_model::MAX_WEB_SEARCH_DOMAINS,
692                        "uniqueItems":true,"items":{"type":"string","minLength":1,"maxLength":tea_model::MAX_WEB_SEARCH_DOMAIN_BYTES}
693                    },
694                    "blocked_domains":{
695                        "type":"array","maxItems":tea_model::MAX_WEB_SEARCH_DOMAINS,
696                        "uniqueItems":true,"items":{"type":"string","minLength":1,"maxLength":tea_model::MAX_WEB_SEARCH_DOMAIN_BYTES}
697                    },
698                    "limit":{"type":"integer","minimum":1,"maximum":MAX_WEB_SEARCH_RESULT_LIMIT}
699                },
700                "required":["query"],
701                "additionalProperties":false
702            }),
703            json!({
704                "type":"object",
705                "properties":{
706                    "results":{
707                        "type":"array","maxItems":MAX_WEB_SEARCH_RESULT_LIMIT,
708                        "items":{
709                            "type":"object",
710                            "properties":{
711                                "url":{"type":"string"},
712                                "title":{"type":"string"},
713                                "snippet":{"type":"string"},
714                                "score":{"type":"number","minimum":0,"maximum":1}
715                            },
716                            "required":["url"],
717                            "additionalProperties":false
718                        }
719                    },
720                    "truncated":{"type":"boolean"}
721                },
722                "required":["results","truncated"],
723                "additionalProperties":false
724            }),
725            [ToolEffect::NetworkRequest],
726            ToolExecutionSemantics::new(
727                ToolIdempotency::Idempotent,
728                ToolRetrySafety::ExplicitOnly,
729                ToolConcurrency::Parallel,
730                ToolTimeout::from_millis(60_000)?,
731            )?,
732        )?
733        .with_prompt_hint(
734            "Use web_search for current public information and cite returned source URLs.",
735        )
736    }
737
738    /// Returns the fixed external destination declared to policy before execution.
739    ///
740    /// # Errors
741    ///
742    /// Returns an error when a custom provider exposes an invalid destination.
743    pub fn resource(&self) -> Result<ToolResource, ToolResourceError> {
744        ToolResource::new("url", self.provider.destination(), ToolResourceAccess::Read)
745    }
746
747    fn request(
748        &self,
749        invocation: &ValidatedToolInvocation,
750    ) -> Result<SearchRequest, SearchRequestError> {
751        let query = invocation
752            .arguments()
753            .get("query")
754            .and_then(Value::as_str)
755            .ok_or(SearchRequestError::InvalidQuery)?;
756        let limit = invocation
757            .arguments()
758            .get("limit")
759            .and_then(Value::as_u64)
760            .map(usize::try_from)
761            .transpose()
762            .map_err(|_| SearchRequestError::InvalidLimit)?
763            .unwrap_or(DEFAULT_WEB_SEARCH_RESULT_LIMIT);
764        let requested_allowed = domain_argument(invocation, "allowed_domains")?;
765        let requested_blocked = domain_argument(invocation, "blocked_domains")?;
766        let (allowed, blocked) = effective_domains(
767            &self.configured_options,
768            requested_allowed,
769            requested_blocked,
770        )?;
771        let mut options = if !allowed.is_empty() {
772            WebSearchOptions::new()
773                .with_allowed_domains(allowed)
774                .map_err(|_| SearchRequestError::InvalidDomains)?
775        } else if !blocked.is_empty() {
776            WebSearchOptions::new()
777                .with_blocked_domains(blocked)
778                .map_err(|_| SearchRequestError::InvalidDomains)?
779        } else {
780            WebSearchOptions::new()
781        };
782        if let Some(location) = self.configured_options.location() {
783            options = options.with_location(location.clone());
784        }
785        SearchRequest::from_options(query, options, limit)
786    }
787
788    async fn run(
789        &self,
790        invocation: &ValidatedToolInvocation,
791        cancellation: CancellationScope,
792    ) -> ToolExecutionEvent {
793        if cancellation.is_cancelled() {
794            return ToolExecutionEvent::Failed(ToolExecutionFailure::cancelled());
795        }
796        let Ok(request) = self.request(invocation) else {
797            return provider_failure(SearchProviderError::new(
798                SearchProviderErrorCode::InvalidRequest,
799            ));
800        };
801        match self.provider.search(request, cancellation).await {
802            Ok(response) => search_success(&response),
803            Err(error) => provider_failure(error),
804        }
805    }
806}
807
808impl ToolExecutor for WebSearchTool {
809    fn execute(
810        &self,
811        invocation: ValidatedToolInvocation,
812        cancellation: CancellationScope,
813    ) -> BoxToolExecutionStream {
814        let executor = self.clone();
815        Box::pin(stream::once(async move {
816            executor.run(&invocation, cancellation).await
817        }))
818    }
819}
820
821fn domain_argument(
822    invocation: &ValidatedToolInvocation,
823    name: &str,
824) -> Result<Vec<String>, SearchRequestError> {
825    invocation
826        .arguments()
827        .get(name)
828        .map(|domains| {
829            domains
830                .as_array()
831                .ok_or(SearchRequestError::InvalidDomains)?
832                .iter()
833                .map(|domain| {
834                    domain
835                        .as_str()
836                        .map(str::to_owned)
837                        .ok_or(SearchRequestError::InvalidDomains)
838                })
839                .collect()
840        })
841        .transpose()
842        .map(Option::unwrap_or_default)
843}
844
845fn effective_domains(
846    configured: &WebSearchOptions,
847    requested_allowed: Vec<String>,
848    requested_blocked: Vec<String>,
849) -> Result<(Vec<String>, Vec<String>), SearchRequestError> {
850    if !requested_allowed.is_empty() && !requested_blocked.is_empty() {
851        return Err(SearchRequestError::InvalidDomains);
852    }
853    if !configured.allowed_domains().is_empty() {
854        if !requested_blocked.is_empty()
855            || requested_allowed.iter().any(|domain| {
856                !configured
857                    .allowed_domains()
858                    .iter()
859                    .any(|configured| configured == domain)
860            })
861        {
862            return Err(SearchRequestError::InvalidDomains);
863        }
864        let allowed = if requested_allowed.is_empty() {
865            configured.allowed_domains().to_vec()
866        } else {
867            requested_allowed
868        };
869        return Ok((allowed, Vec::new()));
870    }
871    if !configured.blocked_domains().is_empty() {
872        if !requested_allowed.is_empty() {
873            return Err(SearchRequestError::InvalidDomains);
874        }
875        let blocked = configured
876            .blocked_domains()
877            .iter()
878            .cloned()
879            .chain(requested_blocked)
880            .collect::<BTreeSet<_>>()
881            .into_iter()
882            .collect();
883        return Ok((Vec::new(), blocked));
884    }
885    Ok((requested_allowed, requested_blocked))
886}
887
888fn search_success(response: &SearchResponse) -> ToolExecutionEvent {
889    let results = response
890        .results()
891        .iter()
892        .map(|result| {
893            let mut value = Map::new();
894            value.insert("url".to_owned(), json!(result.source().url()));
895            if let Some(title) = result.source().title() {
896                value.insert("title".to_owned(), json!(title));
897            }
898            if let Some(snippet) = result.source().snippet() {
899                value.insert("snippet".to_owned(), json!(snippet));
900            }
901            if let Some(score) = result.score() {
902                value.insert("score".to_owned(), json!(score));
903            }
904            Value::Object(value)
905        })
906        .collect::<Vec<_>>();
907    let mut visible = String::new();
908    if results.is_empty() {
909        visible.push_str("No web search results found.");
910    } else {
911        visible.push_str("Web search results:\n");
912        for (index, result) in response.results().iter().enumerate() {
913            let source = result.source();
914            let title = source.title().unwrap_or(source.url());
915            write!(visible, "{}. {title}\n   {}\n", index + 1, source.url())
916                .expect("writing to a String cannot fail");
917            if let Some(snippet) = source.snippet() {
918                visible.push_str("   ");
919                visible.push_str(snippet);
920                visible.push('\n');
921            }
922        }
923    }
924    let output = json!({"results":results,"truncated":response.truncated()});
925    let Ok(content) = ContentBlock::text(visible) else {
926        return ToolExecutionEvent::Failed(ToolExecutionFailure::internal_contract());
927    };
928    let Ok(result) = ToolResult::new(vec![content], output) else {
929        return ToolExecutionEvent::Failed(ToolExecutionFailure::internal_contract());
930    };
931    ToolExecutionEvent::Finished(result)
932}
933
934fn provider_failure(error: SearchProviderError) -> ToolExecutionEvent {
935    if error.code() == SearchProviderErrorCode::Cancelled {
936        return ToolExecutionEvent::Failed(ToolExecutionFailure::cancelled());
937    }
938    let details = ProtocolMetadata::from_entries([(
939        "dev.tea-rs.web-search",
940        json!({"code":provider_error_code(error.code())}),
941    )])
942    .unwrap_or_default();
943    let failure = ToolExecutionFailure::execution(error.message())
944        .unwrap_or_else(|_| ToolExecutionFailure::internal_contract())
945        .with_details(details);
946    ToolExecutionEvent::Failed(failure)
947}
948
949const fn provider_error_code(code: SearchProviderErrorCode) -> &'static str {
950    match code {
951        SearchProviderErrorCode::InvalidConfiguration => "invalid_configuration",
952        SearchProviderErrorCode::InvalidRequest => "invalid_request",
953        SearchProviderErrorCode::Authentication => "authentication",
954        SearchProviderErrorCode::RateLimited => "rate_limited",
955        SearchProviderErrorCode::QuotaExceeded => "quota_exceeded",
956        SearchProviderErrorCode::Timeout => "timeout",
957        SearchProviderErrorCode::Transport => "transport",
958        SearchProviderErrorCode::Unavailable => "unavailable",
959        SearchProviderErrorCode::MalformedResponse => "malformed_response",
960        SearchProviderErrorCode::Cancelled => "cancelled",
961    }
962}