Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(search): restructure search engine and tool modules

Steven Enamakel54bae80d74a0
diff --git a/crates/openhuman-core/src/search/engines/brave.rs b/crates/openhuman-core/src/search/engines/brave.rs
deleted file mode 100644
index 57940b548e..0000000000
--- a/crates/openhuman-core/src/search/engines/brave.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use tinytools::Tool;
-
-pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!("[search] active engine = brave (BYO direct API)");
-
- let api_key = root_config.search.brave.api_key.clone();
- vec![
- Box::new(crate::search::tools::BraveWebSearchTool::new(
- api_key.clone(),
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::BraveNewsSearchTool::new(
- api_key.clone(),
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::BraveImageSearchTool::new(
- api_key.clone(),
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::BraveVideoSearchTool::new(
- api_key,
- params.max_results,
- params.timeout_secs,
- )),
- ]
-}
diff --git a/crates/openhuman-core/src/search/engines/disabled.rs b/crates/openhuman-core/src/search/engines/disabled.rs
deleted file mode 100644
index 88427347b4..0000000000
--- a/crates/openhuman-core/src/search/engines/disabled.rs
+++ /dev/null
@@ -1,8 +0,0 @@
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use tinytools::Tool;
-
-pub(crate) fn build(_: &Config, _: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!("[search] disabled — no search tools registered");
- Vec::new()
-}
diff --git a/crates/openhuman-core/src/search/engines/exa.rs b/crates/openhuman-core/src/search/engines/exa.rs
deleted file mode 100644
index f3e8bb0bbc..0000000000
--- a/crates/openhuman-core/src/search/engines/exa.rs
+++ /dev/null
@@ -1,37 +0,0 @@
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use tinytools::Tool;
-
-/// Exa BYOK: every tool here calls `https://api.exa.ai` directly with the
-/// user's own key. Nothing in this surface routes through the managed backend.
-pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!("[search] active engine = exa (BYO direct API)");
-
- let api_key = root_config.search.exa.api_key.clone();
- vec![
- Box::new(crate::search::tools::ExaSearchTool::new_web_search_tool(
- api_key.clone(),
- None,
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::ExaSearchTool::new(
- api_key.clone(),
- None,
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::ExaFindSimilarTool::new(
- api_key.clone(),
- None,
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::ExaGetContentsTool::new(
- api_key,
- None,
- params.max_results,
- params.timeout_secs,
- )),
- ]
-}
diff --git a/crates/openhuman-core/src/search/engines/managed.rs b/crates/openhuman-core/src/search/engines/managed.rs
deleted file mode 100644
index dc1b3a14d9..0000000000
--- a/crates/openhuman-core/src/search/engines/managed.rs
+++ /dev/null
@@ -1,18 +0,0 @@
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use std::sync::Arc;
-use tinytools::Tool;
-
-pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!(
- requested = %root_config.search.requested_engine_str(),
- "[search] active engine = managed (backend-proxied web_search)"
- );
-
- vec![Box::new(crate::search::WebSearchTool::new(
- crate::integrations::build_client(root_config),
- Some(Arc::new(root_config.clone())),
- params.max_results,
- params.timeout_secs,
- ))]
-}
diff --git a/crates/openhuman-core/src/search/engines/mod.rs b/crates/openhuman-core/src/search/engines/mod.rs
deleted file mode 100644
index a7011e3e2a..0000000000
--- a/crates/openhuman-core/src/search/engines/mod.rs
+++ /dev/null
@@ -1,11 +0,0 @@
-//! One `pub(crate) fn build(&Config, SearchToolParams) -> Vec<Box<dyn Tool>>`
-//! per search engine; `registry::build_search_tools` dispatches to exactly one
-//! based on `search.effective_engine()`.
-
-pub(crate) mod brave;
-pub(crate) mod disabled;
-pub(crate) mod exa;
-pub(crate) mod managed;
-pub(crate) mod parallel;
-pub(crate) mod querit;
-pub(crate) mod tavily;
diff --git a/crates/openhuman-core/src/search/engines/parallel.rs b/crates/openhuman-core/src/search/engines/parallel.rs
deleted file mode 100644
index 1125e4fc51..0000000000
--- a/crates/openhuman-core/src/search/engines/parallel.rs
+++ /dev/null
@@ -1,49 +0,0 @@
-use std::sync::Arc;
-
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use tinytools::Tool;
-
-pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!("[search] active engine = parallel (BYO direct API)");
-
- let client = crate::integrations::build_client(root_config);
- let Some(client) = client else {
- tracing::warn!(
- "[search] engine=parallel but no backend client — falling back to managed surface"
- );
- return vec![Box::new(crate::search::WebSearchTool::new(
- None,
- Some(Arc::new(root_config.clone())),
- params.max_results,
- params.timeout_secs,
- ))];
- };
-
- vec![
- Box::new(crate::search::tools::ParallelSearchTool::new(Arc::clone(
- &client,
- ))),
- Box::new(crate::search::tools::ParallelExtractTool::new(Arc::clone(
- &client,
- ))),
- Box::new(crate::search::tools::ParallelChatTool::new(Arc::clone(
- &client,
- ))),
- Box::new(crate::search::tools::ParallelResearchTool::new(Arc::clone(
- &client,
- ))),
- Box::new(crate::search::tools::ParallelEnrichTool::new(Arc::clone(
- &client,
- ))),
- Box::new(crate::search::tools::ParallelDatasetTool::new(Arc::clone(
- &client,
- ))),
- Box::new(crate::search::WebSearchTool::new(
- Some(Arc::clone(&client)),
- Some(Arc::new(root_config.clone())),
- params.max_results,
- params.timeout_secs,
- )),
- ]
-}
diff --git a/crates/openhuman-core/src/search/engines/querit.rs b/crates/openhuman-core/src/search/engines/querit.rs
deleted file mode 100644
index 3128e97f8e..0000000000
--- a/crates/openhuman-core/src/search/engines/querit.rs
+++ /dev/null
@@ -1,23 +0,0 @@
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use tinytools::Tool;
-
-pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!("[search] active engine = querit (BYO direct API)");
-
- let api_key = root_config.search.querit.api_key.clone();
- vec![
- Box::new(crate::search::tools::QueritSearchTool::new_web_search_tool(
- api_key.clone(),
- None,
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::QueritSearchTool::new(
- api_key,
- None,
- params.max_results,
- params.timeout_secs,
- )),
- ]
-}
diff --git a/crates/openhuman-core/src/search/engines/tavily.rs b/crates/openhuman-core/src/search/engines/tavily.rs
deleted file mode 100644
index dfb8092a28..0000000000
--- a/crates/openhuman-core/src/search/engines/tavily.rs
+++ /dev/null
@@ -1,31 +0,0 @@
-use crate::config::Config;
-use crate::search::registry::SearchToolParams;
-use tinytools::Tool;
-
-/// Tavily BYOK: every tool here calls `https://api.tavily.com` directly with the
-/// user's own key. Nothing in this surface routes through the managed backend.
-pub(crate) fn build(root_config: &Config, params: SearchToolParams) -> Vec<Box<dyn Tool>> {
- tracing::debug!("[search] active engine = tavily (BYO direct API)");
-
- let api_key = root_config.search.tavily.api_key.clone();
- vec![
- Box::new(crate::search::tools::TavilySearchTool::new_web_search_tool(
- api_key.clone(),
- None,
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::TavilySearchTool::new(
- api_key.clone(),
- None,
- params.max_results,
- params.timeout_secs,
- )),
- Box::new(crate::search::tools::TavilyExtractTool::new(
- api_key,
- None,
- params.max_results,
- params.timeout_secs,
- )),
- ]
-}
diff --git a/crates/openhuman-core/src/search/registry.rs b/crates/openhuman-core/src/search/registry.rs
deleted file mode 100644
index 51c2fe11d2..0000000000
--- a/crates/openhuman-core/src/search/registry.rs
+++ /dev/null
@@ -1,71 +0,0 @@
-use crate::config::{Config, SearchEngine};
-use std::sync::Arc;
-use tinytools::Tool;
-
-use super::engines;
-
-#[derive(Clone, Copy)]
-pub(crate) struct SearchToolParams {
- pub(crate) max_results: usize,
- pub(crate) timeout_secs: u64,
-}
-
-/// Build the complete agent-facing search tool surface for the configured
-/// search engine.
-///
-/// Exactly one engine owns the canonical `web_search_tool` slot. When search is
-/// disabled, this returns an empty list so search tools are absent from both the
-/// agent prompt context and the runtime tool map.
-pub fn build_search_tools(root_config: &Config) -> Vec<Box<dyn Tool>> {
- let search = &root_config.search;
- let params = SearchToolParams {
- max_results: search.max_results.clamp(1, 20),
- timeout_secs: search.timeout_secs.max(1),
- };
-
- let engine = search.effective_engine();
- let mut tools = match engine {
- SearchEngine::Disabled => engines::disabled::build(root_config, params),
- SearchEngine::Managed => engines::managed::build(root_config, params),
- SearchEngine::Parallel => engines::parallel::build(root_config, params),
- SearchEngine::Brave => engines::brave::build(root_config, params),
- SearchEngine::Querit => engines::querit::build(root_config, params),
- SearchEngine::Exa => engines::exa::build(root_config, params),
- SearchEngine::Tavily => engines::tavily::build(root_config, params),
- };
-
- if engine != SearchEngine::Disabled {
- tools.extend(build_backend_search_tools(root_config));
- }
-
- tools
-}
-
-fn build_backend_search_tools(root_config: &Config) -> Vec<Box<dyn Tool>> {
- let Some(client) = crate::integrations::build_client(root_config) else {
- tracing::debug!("[search] no integration client — backend search tools skipped");
- return Vec::new();
- };
-
- let mut tools: Vec<Box<dyn Tool>> = Vec::new();
- if root_config.integrations.tinyfish.is_active() {
- tools.push(Box::new(crate::search::tools::TinyFishSearchTool::new(
- Arc::clone(&client),
- )));
- tools.push(Box::new(crate::search::tools::TinyFishFetchTool::new(
- Arc::clone(&client),
- )));
- tools.push(Box::new(crate::search::tools::TinyFishAgentRunTool::new(
- Arc::clone(&client),
- )));
- tracing::debug!("[search] registered tinyfish tools");
- } else {
- tracing::debug!("[search] tinyfish disabled — skipping");
- }
-
- tools
-}
-
-#[cfg(test)]
-#[path = "registry_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/registry_tests.rs b/crates/openhuman-core/src/search/registry_tests.rs
deleted file mode 100644
index bbd33ee59d..0000000000
--- a/crates/openhuman-core/src/search/registry_tests.rs
+++ /dev/null
@@ -1,99 +0,0 @@
-use crate::config::Config;
-
-#[test]
-fn disabled_engine_registers_no_search_tools() {
- let mut cfg = Config::default();
- cfg.search.engine = "disabled".to_string();
-
- let tools = super::build_search_tools(&cfg);
-
- assert!(tools.is_empty());
-}
-
-#[test]
-fn managed_engine_registers_unified_web_search_tool() {
- let mut cfg = Config::default();
- cfg.search.engine = "managed".to_string();
-
- let tools = super::build_search_tools(&cfg);
- let names = tools.iter().map(|tool| tool.name()).collect::<Vec<_>>();
-
- assert_eq!(names, vec!["web_search_tool"]);
-}
-
-#[test]
-fn exa_engine_registers_the_byok_exa_family() {
- let mut cfg = Config::default();
- cfg.search.engine = "exa".to_string();
- cfg.search.exa.api_key = Some("test-key".to_string());
-
- let tools = super::build_search_tools(&cfg);
- let names = tools.iter().map(|tool| tool.name()).collect::<Vec<_>>();
-
- assert_eq!(
- names,
- vec![
- "web_search_tool",
- "exa_search",
- "exa_find_similar",
- "exa_get_contents"
- ]
- );
-}
-
-#[test]
-fn exa_without_a_key_falls_back_to_the_managed_surface() {
- let mut cfg = Config::default();
- cfg.search.engine = "exa".to_string();
-
- let tools = super::build_search_tools(&cfg);
- let names = tools.iter().map(|tool| tool.name()).collect::<Vec<_>>();
-
- assert_eq!(names, vec!["web_search_tool"]);
-}
-
-#[test]
-fn brave_engine_registers_brave_search_family() {
- let mut cfg = Config::default();
- cfg.search.engine = "brave".to_string();
- cfg.search.brave.api_key = Some("test-key".to_string());
-
- let tools = super::build_search_tools(&cfg);
- let names = tools.iter().map(|tool| tool.name()).collect::<Vec<_>>();
-
- assert_eq!(
- names,
- vec![
- "web_search_tool",
- "brave_news_search",
- "brave_image_search",
- "brave_video_search"
- ]
- );
-}
-
-#[test]
-fn tavily_engine_registers_the_byok_tavily_family() {
- let mut cfg = Config::default();
- cfg.search.engine = "tavily".to_string();
- cfg.search.tavily.api_key = Some("test-key".to_string());
-
- let tools = super::build_search_tools(&cfg);
- let names = tools.iter().map(|tool| tool.name()).collect::<Vec<_>>();
-
- assert_eq!(
- names,
- vec!["web_search_tool", "tavily_search", "tavily_extract"]
- );
-}
-
-#[test]
-fn tavily_without_a_key_falls_back_to_the_managed_surface() {
- let mut cfg = Config::default();
- cfg.search.engine = "tavily".to_string();
-
- let tools = super::build_search_tools(&cfg);
- let names = tools.iter().map(|tool| tool.name()).collect::<Vec<_>>();
-
- assert_eq!(names, vec!["web_search_tool"]);
-}
diff --git a/crates/openhuman-core/src/search/tools/README.md b/crates/openhuman-core/src/search/tools/README.md
deleted file mode 100644
index 1ab7f13afe..0000000000
--- a/crates/openhuman-core/src/search/tools/README.md
+++ /dev/null
@@ -1,54 +0,0 @@
-# Search Tools
-
-Agent-facing `Tool` implementations for every search provider. One file per
-provider family; `mod.rs` re-exports the full public surface with
-`pub use crate::search::tools::*` consumed from `tools/mod.rs`.
-
-## Providers
-
-| File | Exported tools | `name()` | Transport |
-| --- | --- | --- | --- |
-| `brave.rs` | `BraveWebSearchTool`, `BraveNewsSearchTool`, `BraveImageSearchTool`, `BraveVideoSearchTool` | `web_search_tool`, `brave_news_search`, `brave_image_search`, `brave_video_search` | Direct to `api.search.brave.com`, `X-Subscription-Token` header |
-| `exa.rs` | `ExaSearchTool`, `ExaFindSimilarTool`, `ExaGetContentsTool` | `exa_search` or `web_search_tool` (constructor-selected), `exa_find_similar`, `exa_get_contents` | BYOK, direct to `api.exa.ai`, `x-api-key` header — never proxied |
-| `parallel.rs` (+ `parallel/` — `search.rs`, `extract.rs`, `chat.rs`, `research.rs`, `enrich.rs`, `dataset.rs`) | `ParallelSearchTool`, `ParallelExtractTool`, `ParallelChatTool`, `ParallelResearchTool`, `ParallelEnrichTool`, `ParallelDatasetTool` | `parallel_search`, `parallel_extract`, `parallel_chat`, `parallel_research`, `parallel_enrich`, `parallel_dataset` | Backend-proxied via `crate::integrations::IntegrationClient` (`/agent-integrations/parallel/*`) |
-| `querit.rs` | `QueritSearchTool` | `querit_search` or `web_search_tool` (constructor-selected) | Direct to `api.querit.ai`, `Authorization: Bearer` header |
-| `searxng.rs` | `SearxngSearchTool`, plus `normalize_categories`, `SearxngSearchArgs`, `SearxngSearchResponse`, `MAX_RESULTS` (re-exported as `SEARXNG_MAX_RESULTS`) | `searxng_search` | Direct to a user-configured, self-hosted SearXNG instance (`GET /search?format=json`) |
-| `seltz.rs` | `SeltzSearchTool` | `seltz_search` | Direct to `api.seltz.ai`, `x-api-key` header |
-| `tavily.rs` (+ `tavily/` — `client.rs`, `search_tool.rs`, `extract_tool.rs`, `types.rs`) | `TavilySearchTool`, `TavilyExtractTool` | `tavily_search` or `web_search_tool` (constructor-selected), `tavily_extract` | BYOK, direct to `api.tavily.com`, `Authorization: Bearer` header — never proxied |
-| `tinyfish.rs` | `TinyFishSearchTool`, `TinyFishFetchTool`, `TinyFishAgentRunTool` | `tinyfish_search`, `tinyfish_fetch`, `tinyfish_agent_run` | Backend-proxied via `IntegrationClient` (`/agent-integrations/tinyfish/*`); search/fetch are read-oriented, agent-run drives goal-based browser automation |
-| `web_search.rs` | `WebSearchTool` (+ crate-internal `resolve_managed_provider`) | `web_search_tool` | Backend-proxied managed search (`POST /agent-integrations/parallel/search` via `IntegrationClient`); `resolve_managed_provider` labels the response with the provider the backend reports, falling back to `Exa`, for UI attribution. `with_direct_search(Option<SeltzSearchTool>)` can short-circuit the proxy, but only `web_search_tests.rs` uses it |
-
-Several providers construct their primary tool with a `tool_name` field so the
-same struct can register under either its own name (e.g. `exa_search`,
-`querit_search`, `tavily_search`) or the canonical `web_search_tool` slot when
-that engine is the active `search.engine` — see `exa.rs`, `querit.rs`, and
-`tavily/search_tool.rs`.
-
-## Registration
-
-Most families are selected by `search::registry::build_search_tools` based on
-`Config.search.effective_engine()`, via `search/engines/`
-([README](../README.md)). `tinyfish.rs` tools are pushed separately by
-`registry.rs` (`build_backend_search_tools`) on top of whichever engine is
-active, provided the engine is not `disabled`, an `IntegrationClient` can be
-built (user signed in), and `config.integrations.tinyfish.is_active()`.
-
-`SearxngSearchTool` and `SeltzSearchTool` are not reachable through the engine
-registry at all — they are constructed per call by the `tools.searxng_search`
-(`handle_searxng_search`) and `tools.seltz_search` (`handle_seltz_search`)
-RPC handlers, both in `crates/openhuman-core/src/tools/schemas/web_search.rs`.
-Those handlers take the query and `max_results` from the RPC
-params but read endpoint, key, timeout, and the `enabled` gate from the
-top-level `config.searxng` / `config.seltz` sections, not from
-`Config.search`. `SEARXNG_MAX_RESULTS` and `normalize_categories` are also
-reused by `mcp/server/tools/` to keep the MCP SearXNG surface consistent with
-the RPC handler.
-
-## Tests
-
-Each provider has a sibling `*_tests.rs` (`brave_tests.rs`, `exa_tests.rs`,
-etc.) wired in via `#[cfg(test)] #[path = "<provider>_tests.rs"] mod tests;`.
-No test hits the network: `web_search_tests.rs` starts an in-process axum
-router (`start_mock_backend`) and points an `IntegrationClient` at it; the
-other backend-proxied families build their client against an unreachable
-`http://test` base and only exercise schema and response parsing.
diff --git a/crates/openhuman-core/src/search/tools/brave.rs b/crates/openhuman-core/src/search/tools/brave.rs
deleted file mode 100644
index 23408c9979..0000000000
--- a/crates/openhuman-core/src/search/tools/brave.rs
+++ /dev/null
@@ -1,693 +0,0 @@
-//! Brave Search direct-API integration.
-//!
-//! **Scope**: Agent + CLI/RPC.
-//!
-//! Brave exposes several REST endpoints — we layer one tool per
-//! endpoint so the agent can pick the right surface:
-//!
-//! - `GET https://api.search.brave.com/res/v1/web/search` → `brave_web_search`
-//! - `GET https://api.search.brave.com/res/v1/news/search` → `brave_news_search`
-//! - `GET https://api.search.brave.com/res/v1/images/search` → `brave_image_search`
-//! - `GET https://api.search.brave.com/res/v1/videos/search` → `brave_video_search`
-//!
-//! **Auth**: `X-Subscription-Token: <api_key>` header.
-//!
-//! Each tool short-circuits with a clear "not configured" error when no
-//! key is wired up so the agent surfaces the misconfiguration instead
-//! of silently routing elsewhere.
-
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::{json, Value};
-use std::time::Duration;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-const DEFAULT_API_BASE: &str = "https://api.search.brave.com/res/v1";
-
-fn http_client(timeout_secs: u64) -> anyhow::Result<reqwest::Client> {
- crate::util::tls::tls_client_builder()
- .timeout(Duration::from_secs(timeout_secs.max(1)))
- .connect_timeout(Duration::from_secs(10))
- .build()
- .map_err(|e| anyhow::anyhow!("failed to build Brave HTTP client: {e}"))
-}
-
-#[derive(Debug, Clone)]
-struct BraveConfig {
- api_key: Option<String>,
- max_results: usize,
- timeout_secs: u64,
-}
-
-impl BraveConfig {
- fn require_key(&self) -> anyhow::Result<&str> {
- self.api_key
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .ok_or_else(|| {
- anyhow::anyhow!(
- "Brave Search unavailable: no API key configured. \
- Set OPENHUMAN_BRAVE_API_KEY or `search.brave.api_key` \
- in config.toml and select `search.engine = \"brave\"`."
- )
- })
- }
-}
-
-async fn brave_get(
- cfg: &BraveConfig,
- path: &str,
- query: &[(&str, String)],
-) -> anyhow::Result<Value> {
- let key = cfg.require_key()?;
- let url = format!("{DEFAULT_API_BASE}{path}");
- tracing::debug!(
- path = %path,
- timeout_secs = cfg.timeout_secs,
- key_present = true,
- param_count = query.len(),
- "[brave] GET request"
- );
- let client = http_client(cfg.timeout_secs)?;
- let started = std::time::Instant::now();
- let resp = client
- .get(&url)
- .header("X-Subscription-Token", key)
- .header("Accept", "application/json")
- .header("Accept-Encoding", "gzip")
- .query(query)
- .send()
- .await
- .map_err(|e| {
- tracing::warn!(path = %path, "[brave] request send failed: {e}");
- anyhow::anyhow!("Brave request failed: {e}")
- })?;
- let status = resp.status();
- let elapsed_ms = started.elapsed().as_millis();
- let body = resp.text().await.unwrap_or_default();
- if !status.is_success() {
- let detail = crate::util::utf8_safe_prefix_at_byte_boundary(&body, 500);
- tracing::warn!(
- path = %path,
- status = %status,
- elapsed_ms = elapsed_ms as u64,
- "[brave] non-2xx response: {detail}"
- );
- anyhow::bail!("Brave returned {status}: {detail}");
- }
- tracing::debug!(
- path = %path,
- status = %status,
- elapsed_ms = elapsed_ms as u64,
- body_bytes = body.len(),
- "[brave] response ok"
- );
- serde_json::from_str::<Value>(&body).map_err(|e| {
- tracing::warn!(path = %path, "[brave] JSON parse failed: {e}");
- anyhow::anyhow!("Brave returned malformed JSON: {e}")
- })
-}
-
-fn extract_query(args: &Value) -> anyhow::Result<String> {
- let q = args
- .get("query")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?
- .trim();
- if q.is_empty() {
- anyhow::bail!("Search query cannot be empty");
- }
- Ok(q.to_string())
-}
-
-fn clamped_count(args: &Value, default: usize, max: usize) -> usize {
- args.get("count")
- .and_then(|v| v.as_u64())
- .map(|n| (n as usize).clamp(1, max))
- .unwrap_or_else(|| default.clamp(1, max))
-}
-
-fn pub_string(args: &Value, key: &str) -> Option<String> {
- args.get(key)
- .and_then(|v| v.as_str())
- .map(|s| s.trim().to_string())
- .filter(|s| !s.is_empty())
-}
-
-// ── Web ─────────────────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct WebResp {
- web: Option<WebContainer>,
-}
-#[derive(Debug, Deserialize)]
-struct WebContainer {
- #[serde(default)]
- results: Vec<WebResult>,
-}
-#[derive(Debug, Deserialize)]
-struct WebResult {
- #[serde(default)]
- title: String,
- #[serde(default)]
- url: String,
- #[serde(default)]
- description: String,
- #[serde(default)]
- age: Option<String>,
-}
-
-pub struct BraveWebSearchTool {
- cfg: BraveConfig,
-}
-
-impl BraveWebSearchTool {
- pub fn new(api_key: Option<String>, max_results: usize, timeout_secs: u64) -> Self {
- Self {
- cfg: BraveConfig {
- api_key,
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout_secs.max(1),
- },
- }
- }
-}
-
-#[async_trait]
-impl Tool for BraveWebSearchTool {
- fn name(&self) -> &str {
- "web_search_tool"
- }
-
- fn description(&self) -> &str {
- "Search the web via Brave Search. Returns ranked results with titles, URLs, and descriptions."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": { "type": "string", "description": "Search query (concise keywords work best)." },
- "count": { "type": "integer", "description": "Max results (1-20)." },
- "country": { "type": "string", "description": "2-letter country code (e.g. 'us', 'gb')." },
- "freshness": { "type": "string", "description": "Time filter: 'pd' (past day), 'pw' (past week), 'pm' (past month), 'py' (past year), or 'YYYY-MM-DDtoYYYY-MM-DD'." }
- },
- "required": ["query"]
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let query = extract_query(&args)?;
- let count = clamped_count(&args, self.cfg.max_results, 20);
- let mut q: Vec<(&str, String)> = vec![
- ("q", query.clone()),
- ("count", count.to_string()),
- ("result_filter", "web".into()),
- ];
- if let Some(c) = pub_string(&args, "country") {
- q.push(("country", c));
- }
- if let Some(f) = pub_string(&args, "freshness") {
- q.push(("freshness", f));
- }
- let raw = brave_get(&self.cfg, "/web/search", &q).await?;
- let parsed: WebResp = serde_json::from_value(raw)
- .map_err(|e| anyhow::anyhow!("Brave web response shape changed: {e}"))?;
- let results = parsed.web.map(|w| w.results).unwrap_or_default();
- let plain = render_web_plain(&results, &query, count);
- let mut out = ToolResult::success(plain);
- if options.prefer_markdown {
- out.markdown_formatted = Some(render_web_markdown(&results, &query, count));
- }
- // Host-only structured payload for the chat UI's tool-call
- // presentation — never rendered to the model, so `render_web_plain`'s
- // text above (and the cache key that depends on it) is unaffected.
- let structured_results: Vec<crate::search::tools::WebSearchResultRef<'_>> = results
- .iter()
- .map(|r| crate::search::tools::WebSearchResultRef {
- title: if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- },
- url: r.url.as_str(),
- published: r.age.as_deref(),
- excerpt: Some(r.description.as_str()).filter(|d| !d.trim().is_empty()),
- })
- .collect();
- out.metadata = Some(crate::search::tools::web_search_metadata(
- &query,
- "Brave",
- &structured_results,
- count,
- ));
- Ok(out)
- }
-}
-
-fn render_web_plain(results: &[WebResult], query: &str, max: usize) -> String {
- if results.is_empty() {
- return format!("No results found for: {query}");
- }
- let mut lines = vec![format!("Search results for: {query} (via Brave)")];
- for (i, r) in results.iter().take(max).enumerate() {
- let title = if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- };
- lines.push(format!("{}. {}", i + 1, title));
- lines.push(format!(" {}", r.url.trim()));
- if let Some(age) = r.age.as_deref() {
- let age = age.trim();
- if !age.is_empty() {
- lines.push(format!(" {age}"));
- }
- }
- let desc = r.description.trim();
- if !desc.is_empty() {
- lines.push(format!(
- " {}",
- crate::util::truncate_with_ellipsis(desc, 500)
- ));
- }
- }
- lines.join("\n")
-}
-
-fn render_web_markdown(results: &[WebResult], query: &str, max: usize) -> String {
- if results.is_empty() {
- return format!("_No results for `{query}`_ (via Brave)");
- }
- // `(via Brave)` — the shared attribution marker every engine emits, which
- // the tool timeline reads back to label the row (#5136). The markdown
- // renderer is what production shows (`output_for_llm(true)`), so it has to
- // carry the same marker the plain-text renderer already did.
- let mut out = format!("# Search results — `{query}` (via Brave)\n");
- for r in results.iter().take(max) {
- let title = if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- };
- out.push_str(&format!("\n## [{title}]({})\n", r.url.trim()));
- if let Some(age) = r.age.as_deref() {
- let age = age.trim();
- if !age.is_empty() {
- out.push_str(&format!("_{age}_\n\n"));
- }
- }
- let desc = r.description.trim();
- if !desc.is_empty() {
- out.push_str(&format!(
- "> {}\n",
- crate::util::truncate_with_suffix(desc, 500, "…")
- ));
- }
- }
- out
-}
-
-// ── News ────────────────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct NewsResp {
- #[serde(default)]
- results: Vec<NewsResult>,
-}
-#[derive(Debug, Deserialize)]
-struct NewsResult {
- #[serde(default)]
- title: String,
- #[serde(default)]
- url: String,
- #[serde(default)]
- description: String,
- #[serde(default)]
- age: Option<String>,
- #[serde(default)]
- source: Option<String>,
-}
-
-pub struct BraveNewsSearchTool {
- cfg: BraveConfig,
-}
-
-impl BraveNewsSearchTool {
- pub fn new(api_key: Option<String>, max_results: usize, timeout_secs: u64) -> Self {
- Self {
- cfg: BraveConfig {
- api_key,
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout_secs.max(1),
- },
- }
- }
-}
-
-#[async_trait]
-impl Tool for BraveNewsSearchTool {
- fn name(&self) -> &str {
- "brave_news_search"
- }
-
- fn description(&self) -> &str {
- "Search recent news articles via Brave Search News. Returns titles, URLs, sources, and excerpts."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": { "type": "string", "description": "News topic to search for." },
- "count": { "type": "integer", "description": "Max results (1-20)." },
- "country": { "type": "string", "description": "2-letter country code." },
- "freshness": { "type": "string", "description": "Time filter: 'pd', 'pw', 'pm', 'py'." }
- },
- "required": ["query"]
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let query = extract_query(&args)?;
- let count = clamped_count(&args, self.cfg.max_results, 20);
- let mut q: Vec<(&str, String)> = vec![("q", query.clone()), ("count", count.to_string())];
- if let Some(c) = pub_string(&args, "country") {
- q.push(("country", c));
- }
- if let Some(f) = pub_string(&args, "freshness") {
- q.push(("freshness", f));
- }
- let raw = brave_get(&self.cfg, "/news/search", &q).await?;
- let parsed: NewsResp = serde_json::from_value(raw)
- .map_err(|e| anyhow::anyhow!("Brave news response shape changed: {e}"))?;
- let mut lines = if parsed.results.is_empty() {
- return Ok(ToolResult::success(format!("No news found for: {query}")));
- } else {
- vec![format!("News results for: {query} (via Brave)")]
- };
- for (i, r) in parsed.results.iter().take(count).enumerate() {
- let title = if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- };
- lines.push(format!("{}. {}", i + 1, title));
- lines.push(format!(" {}", r.url.trim()));
- if let Some(src) = r.source.as_deref() {
- let src = src.trim();
- if !src.is_empty() {
- lines.push(format!(" Source: {src}"));
- }
- }
- if let Some(age) = r.age.as_deref() {
- let age = age.trim();
- if !age.is_empty() {
- lines.push(format!(" {age}"));
- }
- }
- let desc = r.description.trim();
- if !desc.is_empty() {
- lines.push(format!(
- " {}",
- crate::util::truncate_with_ellipsis(desc, 500)
- ));
- }
- }
- let mut out = ToolResult::success(lines.join("\n"));
- // Host-only structured payload — never rendered to the model, so the
- // plain text above (and the cache key that depends on it) is
- // unaffected.
- let structured_results: Vec<crate::search::tools::WebSearchResultRef<'_>> = parsed
- .results
- .iter()
- .map(|r| crate::search::tools::WebSearchResultRef {
- title: if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- },
- url: r.url.as_str(),
- published: r.age.as_deref(),
- excerpt: Some(r.description.as_str()).filter(|d| !d.trim().is_empty()),
- })
- .collect();
- out.metadata = Some(crate::search::tools::web_search_metadata(
- &query,
- "Brave",
- &structured_results,
- count,
- ));
- Ok(out)
- }
-}
-
-// ── Images ──────────────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct ImageResp {
- #[serde(default)]
- results: Vec<ImageResult>,
-}
-#[derive(Debug, Deserialize)]
-struct ImageResult {
- #[serde(default)]
- title: String,
- #[serde(default)]
- url: String,
- #[serde(default)]
- source: Option<String>,
- #[serde(default)]
- thumbnail: Option<ImageThumb>,
- #[serde(default)]
- properties: Option<ImageProps>,
-}
-#[derive(Debug, Deserialize)]
-struct ImageThumb {
- #[serde(default)]
- src: Option<String>,
-}
-#[derive(Debug, Deserialize)]
-struct ImageProps {
- #[serde(default)]
- url: Option<String>,
-}
-
-pub struct BraveImageSearchTool {
- cfg: BraveConfig,
-}
-
-impl BraveImageSearchTool {
- pub fn new(api_key: Option<String>, max_results: usize, timeout_secs: u64) -> Self {
- Self {
- cfg: BraveConfig {
- api_key,
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout_secs.max(1),
- },
- }
- }
-}
-
-#[async_trait]
-impl Tool for BraveImageSearchTool {
- fn name(&self) -> &str {
- "brave_image_search"
- }
-
- fn description(&self) -> &str {
- "Search for images via Brave Search. Returns image URLs, source pages, and thumbnails."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": { "type": "string", "description": "Image search query." },
- "count": { "type": "integer", "description": "Max results (1-20)." },
- "country": { "type": "string", "description": "2-letter country code." }
- },
- "required": ["query"]
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let query = extract_query(&args)?;
- let count = clamped_count(&args, self.cfg.max_results, 20);
- let mut q: Vec<(&str, String)> = vec![("q", query.clone()), ("count", count.to_string())];
- if let Some(c) = pub_string(&args, "country") {
- q.push(("country", c));
- }
- let raw = brave_get(&self.cfg, "/images/search", &q).await?;
- let parsed: ImageResp = serde_json::from_value(raw)
- .map_err(|e| anyhow::anyhow!("Brave image response shape changed: {e}"))?;
- if parsed.results.is_empty() {
- return Ok(ToolResult::success(format!("No images found for: {query}")));
- }
- let mut lines = vec![format!("Image results for: {query} (via Brave)")];
- for (i, r) in parsed.results.iter().take(count).enumerate() {
- let title = if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- };
- lines.push(format!("{}. {}", i + 1, title));
- if let Some(src) = r.properties.as_ref().and_then(|p| p.url.as_deref()) {
- lines.push(format!(" Image: {}", src.trim()));
- }
- lines.push(format!(" Page: {}", r.url.trim()));
- if let Some(thumb) = r.thumbnail.as_ref().and_then(|t| t.src.as_deref()) {
- lines.push(format!(" Thumb: {}", thumb.trim()));
- }
- if let Some(src) = r.source.as_deref() {
- let src = src.trim();
- if !src.is_empty() {
- lines.push(format!(" Source: {src}"));
- }
- }
- }
- Ok(ToolResult::success(lines.join("\n")))
- }
-}
-
-// ── Videos ──────────────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct VideoResp {
- #[serde(default)]
- results: Vec<VideoResult>,
-}
-#[derive(Debug, Deserialize)]
-struct VideoResult {
- #[serde(default)]
- title: String,
- #[serde(default)]
- url: String,
- #[serde(default)]
- description: String,
- #[serde(default)]
- age: Option<String>,
- #[serde(default)]
- video: Option<VideoMeta>,
-}
-#[derive(Debug, Deserialize)]
-struct VideoMeta {
- #[serde(default)]
- duration: Option<String>,
- #[serde(default)]
- creator: Option<String>,
-}
-
-pub struct BraveVideoSearchTool {
- cfg: BraveConfig,
-}
-
-impl BraveVideoSearchTool {
- pub fn new(api_key: Option<String>, max_results: usize, timeout_secs: u64) -> Self {
- Self {
- cfg: BraveConfig {
- api_key,
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout_secs.max(1),
- },
- }
- }
-}
-
-#[async_trait]
-impl Tool for BraveVideoSearchTool {
- fn name(&self) -> &str {
- "brave_video_search"
- }
-
- fn description(&self) -> &str {
- "Search for videos via Brave Search. Returns titles, URLs, creators, durations, and excerpts."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": { "type": "string", "description": "Video search query." },
- "count": { "type": "integer", "description": "Max results (1-20)." },
- "country": { "type": "string", "description": "2-letter country code." },
- "freshness": { "type": "string", "description": "Time filter: 'pd', 'pw', 'pm', 'py'." }
- },
- "required": ["query"]
- })
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- let query = extract_query(&args)?;
- let count = clamped_count(&args, self.cfg.max_results, 20);
- let mut q: Vec<(&str, String)> = vec![("q", query.clone()), ("count", count.to_string())];
- if let Some(c) = pub_string(&args, "country") {
- q.push(("country", c));
- }
- if let Some(f) = pub_string(&args, "freshness") {
- q.push(("freshness", f));
- }
- let raw = brave_get(&self.cfg, "/videos/search", &q).await?;
- let parsed: VideoResp = serde_json::from_value(raw)
- .map_err(|e| anyhow::anyhow!("Brave video response shape changed: {e}"))?;
- if parsed.results.is_empty() {
- return Ok(ToolResult::success(format!("No videos found for: {query}")));
- }
- let mut lines = vec![format!("Video results for: {query} (via Brave)")];
- for (i, r) in parsed.results.iter().take(count).enumerate() {
- let title = if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- };
- lines.push(format!("{}. {}", i + 1, title));
- lines.push(format!(" {}", r.url.trim()));
- if let Some(meta) = r.video.as_ref() {
- if let Some(creator) = meta.creator.as_deref() {
- let creator = creator.trim();
- if !creator.is_empty() {
- lines.push(format!(" Creator: {creator}"));
- }
- }
- if let Some(dur) = meta.duration.as_deref() {
- let dur = dur.trim();
- if !dur.is_empty() {
- lines.push(format!(" Duration: {dur}"));
- }
- }
- }
- if let Some(age) = r.age.as_deref() {
- let age = age.trim();
- if !age.is_empty() {
- lines.push(format!(" {age}"));
- }
- }
- let desc = r.description.trim();
- if !desc.is_empty() {
- lines.push(format!(
- " {}",
- crate::util::truncate_with_ellipsis(desc, 500)
- ));
- }
- }
- Ok(ToolResult::success(lines.join("\n")))
- }
-}
-
-#[cfg(test)]
-#[path = "brave_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/brave_tests.rs b/crates/openhuman-core/src/search/tools/brave_tests.rs
deleted file mode 100644
index 433ac1afbe..0000000000
--- a/crates/openhuman-core/src/search/tools/brave_tests.rs
+++ /dev/null
@@ -1,85 +0,0 @@
-use super::*;
-
-#[test]
-fn require_key_rejects_blank() {
- let cfg = BraveConfig {
- api_key: Some(" ".into()),
- max_results: 5,
- timeout_secs: 5,
- };
- assert!(cfg.require_key().is_err());
-}
-
-#[test]
-fn require_key_accepts_trimmed() {
- let cfg = BraveConfig {
- api_key: Some(" abc ".into()),
- max_results: 5,
- timeout_secs: 5,
- };
- assert_eq!(cfg.require_key().unwrap(), "abc");
-}
-
-#[test]
-fn web_tool_advertises_unified_name() {
- let t = BraveWebSearchTool::new(Some("k".into()), 5, 5);
- assert_eq!(t.name(), "web_search_tool");
-}
-
-#[test]
-fn web_markdown_carries_provider_marker() {
- // The markdown renderer is what production shows
- // (`output_for_llm(true)`), so its heading must end with the shared
- // `(via <Provider>)` marker the plain-text renderer already emits —
- // that is what the tool timeline reads back to label the row (#5136).
- // It previously read `(Brave)`, which no marker parser matched.
- let results = vec![WebResult {
- title: "Example".into(),
- url: "https://example.com".into(),
- description: "Desc.".into(),
- age: None,
- }];
- let out = render_web_markdown(&results, "test", 5);
- assert!(out.lines().next().unwrap().ends_with("(via Brave)"));
- assert!(out.contains("[Example](https://example.com)"));
-
- // A completed empty search is attributed too, so the timeline does not
- // keep showing it as in-progress.
- let empty = render_web_markdown(&[], "test", 5);
- assert!(empty.trim_end().ends_with("(via Brave)"));
-}
-
-#[test]
-fn news_tool_name() {
- let t = BraveNewsSearchTool::new(Some("k".into()), 5, 5);
- assert_eq!(t.name(), "brave_news_search");
-}
-
-#[test]
-fn image_tool_name() {
- let t = BraveImageSearchTool::new(Some("k".into()), 5, 5);
- assert_eq!(t.name(), "brave_image_search");
-}
-
-#[test]
-fn video_tool_name() {
- let t = BraveVideoSearchTool::new(Some("k".into()), 5, 5);
- assert_eq!(t.name(), "brave_video_search");
-}
-
-#[tokio::test]
-async fn execute_without_key_returns_error() {
- let t = BraveWebSearchTool::new(None, 5, 5);
- let err = t
- .execute(json!({ "query": "test" }))
- .await
- .expect_err("should error without key");
- assert!(err.to_string().contains("no API key"));
-}
-
-#[test]
-fn clamped_count_respects_max() {
- assert_eq!(clamped_count(&json!({"count": 99}), 5, 20), 20);
- assert_eq!(clamped_count(&json!({"count": 0}), 5, 20), 1);
- assert_eq!(clamped_count(&json!({}), 5, 20), 5);
-}
diff --git a/crates/openhuman-core/src/search/tools/exa.rs b/crates/openhuman-core/src/search/tools/exa.rs
deleted file mode 100644
index 0918264a6f..0000000000
--- a/crates/openhuman-core/src/search/tools/exa.rs
+++ /dev/null
@@ -1,750 +0,0 @@
-//! Exa neural search integration -- direct API (BYOK, not backend-proxied).
-//!
-//! **Scope**: Agent + CLI/RPC.
-//! **Endpoints**: `POST https://api.exa.ai/search`,
-//! `POST https://api.exa.ai/findSimilar`, `POST https://api.exa.ai/contents`.
-//! **Auth**: `x-api-key: <api key>`.
-//!
-//! When the user selects `exa` as their search engine and has saved their own
-//! Exa API key, every call in this family goes straight from the desktop client
-//! to `api.exa.ai` -- the OpenHuman managed backend is never involved. The
-//! managed (`engine = "managed"`) path is untouched by this module.
-
-use async_trait::async_trait;
-use serde::{Deserialize, Serialize};
-use serde_json::{json, Value};
-use std::time::Duration;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-const DEFAULT_API_URL: &str = "https://api.exa.ai";
-
-/// One Exa document, shared by `/search`, `/findSimilar`, and `/contents`.
-#[derive(Debug, Clone, Default, Deserialize, Serialize)]
-pub struct ExaResultItem {
- #[serde(default)]
- pub id: Option<String>,
- #[serde(default)]
- pub url: String,
- #[serde(default)]
- pub title: Option<String>,
- #[serde(default)]
- pub author: Option<String>,
- #[serde(default, rename = "publishedDate")]
- pub published_date: Option<String>,
- #[serde(default)]
- pub score: Option<f64>,
- #[serde(default)]
- pub text: Option<String>,
- #[serde(default)]
- pub summary: Option<String>,
- #[serde(default)]
- pub highlights: Vec<String>,
-}
-
-impl ExaResultItem {
- /// Best available excerpt: explicit summary, then highlights, then the
- /// crawled page text.
- fn excerpt(&self) -> Option<String> {
- non_empty(self.summary.as_deref())
- .or_else(|| {
- let joined = self
- .highlights
- .iter()
- .map(|h| h.trim())
- .filter(|h| !h.is_empty())
- .collect::<Vec<_>>()
- .join(" ");
- non_empty(Some(joined.as_str()))
- })
- .or_else(|| non_empty(self.text.as_deref()))
- }
-
- fn display_title(&self) -> &str {
- self.title
- .as_deref()
- .map(str::trim)
- .filter(|t| !t.is_empty())
- .unwrap_or("Untitled")
- }
-}
-
-#[derive(Debug, Default, Deserialize, Serialize)]
-pub struct ExaSearchResponse {
- #[serde(default)]
- pub results: Vec<ExaResultItem>,
- #[serde(default, rename = "autopromptString")]
- pub autoprompt_string: Option<String>,
- #[serde(default, rename = "resolvedSearchType")]
- pub resolved_search_type: Option<String>,
-}
-
-fn non_empty(value: Option<&str>) -> Option<String> {
- value
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
-}
-
-/// Escape a remote page title for use as a markdown link label. Titles are
-/// attacker-controlled, and an unescaped `[`/`]` breaks out of the link and
-/// lets a crafted page inject markdown into the agent transcript.
-fn escape_link_text(raw: &str) -> String {
- raw.replace('\\', r"\\")
- .replace('[', r"\[")
- .replace(']', r"\]")
-}
-
-/// Render a URL as a markdown link destination. Bare parentheses (common in
-/// Wikipedia URLs) terminate the destination early, so wrap in angle brackets
-/// and drop the characters that would close them.
-fn escape_link_destination(raw: &str) -> String {
- let cleaned: String = raw
- .trim()
- .chars()
- .filter(|c| !matches!(c, '<' | '>' | ' '))
- .collect();
- format!("<{cleaned}>")
-}
-
-/// Shared HTTP plumbing for the Exa BYOK tool family. Holds the user's key and
-/// the direct `api.exa.ai` base URL (overridable in tests).
-#[derive(Clone)]
-pub(crate) struct ExaClient {
- api_key: Option<String>,
- api_url: String,
- max_results: usize,
- timeout_secs: u64,
-}
-
-impl ExaClient {
- pub(crate) fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- api_key,
- api_url: api_url.unwrap_or_else(|| DEFAULT_API_URL.to_string()),
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout_secs.max(1),
- }
- }
-
- /// Build the HTTP client at call time, like `brave.rs::http_client`, so a
- /// TLS-backend failure surfaces as a tool error instead of aborting the
- /// process while a session is being constructed.
- fn http_client(&self) -> anyhow::Result<reqwest::Client> {
- crate::util::tls::tls_client_builder()
- .timeout(Duration::from_secs(self.timeout_secs))
- .connect_timeout(Duration::from_secs(10))
- .build()
- .map_err(|e| anyhow::anyhow!("failed to build Exa HTTP client: {e}"))
- }
-
- /// Destination host for the egress descriptor, e.g. `api.exa.ai`.
- fn egress_host(&self) -> String {
- reqwest::Url::parse(&self.api_url)
- .ok()
- .and_then(|u| u.host_str().map(str::to_string))
- .unwrap_or_else(|| "api.exa.ai".to_string())
- }
-
- /// Egress descriptor for a call to Exa. The query (or the requested URLs)
- /// is user content leaving the device, so it carries `Prompt` on top of the
- /// destination `Url` that `network_fetch` supplies.
- fn egress_descriptor(&self) -> crate::security::egress::EgressDescriptor {
- crate::security::egress::EgressDescriptor::network_fetch(self.egress_host())
- .with_data_kind(crate::security::egress::DataKind::Prompt)
- }
-
- /// Privacy epic S7 (#4441): under `LocalOnly` the search is refused before
- /// anything reaches Exa. Returns the `[policy-blocked]` tool result to hand
- /// straight back from `execute`, or `None` when the transfer is permitted.
- fn local_only_block(&self) -> Option<ToolResult> {
- crate::security::egress::local_only_tool_block(&self.egress_descriptor())
- .map(ToolResult::error)
- }
-
- /// The configured key, or a user-actionable error naming exactly where to
- /// set it. Surfaced verbatim on the first search attempt.
- fn key(&self) -> anyhow::Result<&str> {
- self.api_key
- .as_deref()
- .map(str::trim)
- .filter(|k| !k.is_empty())
- .ok_or_else(|| {
- anyhow::anyhow!(
- "Exa search unavailable: no API key configured. Add your Exa API key \
- under Connections > Search engine, set EXA_API_KEY or \
- OPENHUMAN_EXA_API_KEY, or add search.exa.api_key to config.toml."
- )
- })
- }
-
- /// Requested result count, honouring both `max_results` and Exa's native
- /// `numResults` spelling. An explicit per-call value is clamped to the
- /// API's own 1..=20 range rather than to the configured `max_results` --
- /// config supplies the *default* when the call omits one, and a caller may
- /// ask for more (this matches `querit.rs`).
- fn requested_results(&self, args: &Value) -> usize {
- args.get("max_results")
- .or_else(|| args.get("num_results"))
- .or_else(|| args.get("numResults"))
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 20) as usize)
- .unwrap_or(self.max_results)
- }
-
- async fn post(&self, path: &str, body: Value) -> anyhow::Result<Value> {
- let api_key = self.key()?;
- let client = self.http_client()?;
- let url = format!("{}/{}", self.api_url.trim_end_matches('/'), path);
- tracing::debug!(
- path,
- timeout_secs = self.timeout_secs,
- "[exa] POST {url} (direct BYOK)"
- );
-
- // Egress spine (privacy epic S2, #4436): disclose the destination before
- // contacting Exa. `local_only_block` has already refused the call if the
- // live policy forbids it.
- crate::security::egress::emit_external_transfer(self.egress_descriptor());
-
- let resp = client
- .post(&url)
- .header("x-api-key", api_key)
- .header("Content-Type", "application/json")
- .header("Accept", "application/json")
- .json(&body)
- .send()
- .await
- .map_err(|e| {
- tracing::warn!("[exa] request to {path} failed: {e}");
- anyhow::anyhow!("Exa request failed: {e}")
- })?;
-
- let status = resp.status();
- if !status.is_success() {
- // Read and drop the body: Exa echoes the query back in errors and
- // the message reaches the agent transcript.
- let body_len = resp.text().await.unwrap_or_default().len();
- tracing::warn!(status = %status, body_len, "[exa] non-2xx response");
- if status == reqwest::StatusCode::UNAUTHORIZED
- || status == reqwest::StatusCode::FORBIDDEN
- {
- anyhow::bail!(
- "Exa rejected the configured API key (HTTP {status}). \
- Check your Exa API key under Connections > Search engine."
- );
- }
- if status == reqwest::StatusCode::PAYMENT_REQUIRED {
- anyhow::bail!(
- "Exa credits exhausted (HTTP 402). \
- Please top up your Exa account at dashboard.exa.ai or switch search provider."
- );
- }
- if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
- anyhow::bail!(
- "Exa rate limit exceeded (HTTP 429). \
- Please wait a moment before retrying."
- );
- }
- anyhow::bail!("Exa returned non-2xx status {status}");
- }
-
- resp.json().await.map_err(|e| {
- tracing::warn!("[exa] failed to read response JSON: {e}");
- anyhow::anyhow!("Failed to read Exa response JSON: {e}")
- })
- }
-
- async fn post_documents(&self, path: &str, body: Value) -> anyhow::Result<Vec<ExaResultItem>> {
- let value = self.post(path, body).await?;
- let parsed: ExaSearchResponse = serde_json::from_value(value).map_err(|e| {
- tracing::warn!("[exa] failed to parse {path} response: {e}");
- anyhow::anyhow!("Failed to parse Exa response: {e}")
- })?;
- tracing::debug!(path, result_count = parsed.results.len(), "[exa] call ok");
- Ok(parsed.results)
- }
-
- fn render_plain(&self, results: &[ExaResultItem], heading: &str, limit: usize) -> String {
- if results.is_empty() {
- return format!("No Exa results for: {heading}");
- }
-
- let mut lines = vec![format!("Search results for: {heading} (via Exa)")];
- for (i, item) in results.iter().take(limit).enumerate() {
- lines.push(format!("{}. {}", i + 1, item.display_title()));
- lines.push(format!(" {}", item.url.trim()));
- if let Some(date) = non_empty(item.published_date.as_deref()) {
- lines.push(format!(" Published: {date}"));
- }
- if let Some(author) = non_empty(item.author.as_deref()) {
- lines.push(format!(" Author: {author}"));
- }
- if let Some(excerpt) = item.excerpt() {
- let truncated = crate::util::truncate_with_ellipsis(&excerpt, 500);
- lines.push(format!(" {truncated}"));
- }
- }
- lines.join("\n")
- }
-
- fn render_markdown(&self, results: &[ExaResultItem], heading: &str, limit: usize) -> String {
- if results.is_empty() {
- return format!("_No Exa results for `{heading}`._");
- }
-
- let mut out = format!("# Exa results -- `{heading}`\n");
- for item in results.iter().take(limit) {
- out.push_str(&format!(
- "\n## [{}]({})\n",
- escape_link_text(item.display_title()),
- escape_link_destination(&item.url)
- ));
- if let Some(date) = non_empty(item.published_date.as_deref()) {
- out.push_str(&format!("_Published: {date}_\n\n"));
- }
- if let Some(author) = non_empty(item.author.as_deref()) {
- out.push_str(&format!("_Author: {author}_\n\n"));
- }
- if let Some(excerpt) = item.excerpt() {
- let truncated = crate::util::truncate_with_suffix(&excerpt, 500, "...");
- out.push_str(&format!("> {truncated}\n"));
- }
- }
- out
- }
-
- /// `limit` caps how many documents are rendered. Search and find-similar
- /// pass the requested result count; `exa_get_contents` passes the URL count
- /// so a large batch is never silently trimmed to `max_results`.
- fn to_result(
- &self,
- results: &[ExaResultItem],
- heading: &str,
- limit: usize,
- options: &ToolCallOptions,
- ) -> ToolResult {
- let mut result = ToolResult::success(self.render_plain(results, heading, limit));
- if options.prefer_markdown {
- result.markdown_formatted = Some(self.render_markdown(results, heading, limit));
- }
- result
- }
-}
-
-/// Copy a string array argument onto the Exa request body under its native key.
-fn copy_domain_filter(args: &Value, from: &str, to: &str, body: &mut Value) {
- if let Some(list) = args.get(from).filter(|v| v.is_array()) {
- body[to] = list.clone();
- }
-}
-
-/// `contents` sub-object shared by search and find-similar. Exa only crawls
-/// page text when asked, so this stays opt-in to keep responses small.
-fn contents_request(args: &Value) -> Option<Value> {
- let want_text = args
- .get("include_text")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let want_highlights = args
- .get("include_highlights")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- if !want_text && !want_highlights {
- return None;
- }
- let mut contents = json!({});
- if want_text {
- contents["text"] = json!(true);
- }
- if want_highlights {
- contents["highlights"] = json!(true);
- }
- Some(contents)
-}
-
-/// Neural / keyword web search via the Exa API (`POST /search`).
-pub struct ExaSearchTool {
- tool_name: &'static str,
- client: ExaClient,
-}
-
-impl ExaSearchTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- tool_name: "exa_search",
- client: ExaClient::new(api_key, api_url, max_results, timeout_secs),
- }
- }
-
- /// Same tool under the canonical `web_search_tool` slot, so selecting Exa
- /// satisfies the agent's generic "search the web" affordance.
- pub fn new_web_search_tool(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- tool_name: "web_search_tool",
- client: ExaClient::new(api_key, api_url, max_results, timeout_secs),
- }
- }
-
- fn build_body(&self, args: &Value, query: &str) -> Value {
- let mut body = json!({
- "query": query,
- "numResults": self.client.requested_results(args),
- });
- if let Some(search_type) = non_empty(args.get("type").and_then(Value::as_str)) {
- body["type"] = json!(search_type);
- }
- if let Some(category) = non_empty(args.get("category").and_then(Value::as_str)) {
- body["category"] = json!(category);
- }
- copy_domain_filter(args, "include_domains", "includeDomains", &mut body);
- copy_domain_filter(args, "exclude_domains", "excludeDomains", &mut body);
- if let Some(start) = non_empty(args.get("start_published_date").and_then(Value::as_str)) {
- body["startPublishedDate"] = json!(start);
- }
- if let Some(end) = non_empty(args.get("end_published_date").and_then(Value::as_str)) {
- body["endPublishedDate"] = json!(end);
- }
- if let Some(contents) = contents_request(args) {
- body["contents"] = contents;
- }
- body
- }
-}
-
-#[async_trait]
-impl Tool for ExaSearchTool {
- fn name(&self) -> &str {
- self.tool_name
- }
-
- fn description(&self) -> &str {
- "Search the web with Exa. Returns ranked pages with URLs, titles, publish dates, \
- and optional page text. Supports search modes from instant to deep-reasoning, \
- domain include/exclude filters, a published-date range, and result categories."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "The search query. Natural-language phrasing works well with neural search."
- },
- "max_results": {
- "type": "integer",
- "description": "Maximum number of results to return (default from config, max 20)."
- },
- "type": {
- "type": "string",
- "enum": ["auto", "instant", "fast", "deep-lite", "deep", "deep-reasoning"],
- "description": "Exa search mode, fastest to most thorough. Defaults to Exa's own 'auto' selection."
- },
- "category": {
- "type": "string",
- "description": "Restrict to an Exa category, e.g. 'company', 'research paper', 'news', 'financial report', 'personal site'."
- },
- "include_domains": { "type": "array", "items": { "type": "string" }, "description": "Only return results from these domains." },
- "exclude_domains": { "type": "array", "items": { "type": "string" }, "description": "Exclude results from these domains." },
- "start_published_date": {
- "type": "string",
- "description": "Only results published on or after this ISO-8601 date."
- },
- "end_published_date": {
- "type": "string",
- "description": "Only results published on or before this ISO-8601 date."
- },
- "include_text": {
- "type": "boolean",
- "description": "Also crawl and return the page text for each result (slower)."
- },
- "include_highlights": {
- "type": "boolean",
- "description": "Also return query-relevant highlight snippets for each result."
- }
- },
- "required": ["query"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- if let Some(blocked) = self.client.local_only_block() {
- return Ok(blocked);
- }
-
- let query = non_empty(args.get("query").and_then(Value::as_str))
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;
-
- let limit = self.client.requested_results(&args);
- let body = self.build_body(&args, &query);
- let results = self.client.post_documents("search", body).await?;
- let mut result = self.client.to_result(&results, &query, limit, &options);
- let excerpts: Vec<Option<String>> = results.iter().map(ExaResultItem::excerpt).collect();
- let structured: Vec<super::WebSearchResultRef<'_>> = results
- .iter()
- .zip(&excerpts)
- .map(|(r, e)| super::WebSearchResultRef {
- title: r.display_title(),
- url: &r.url,
- published: r.published_date.as_deref(),
- excerpt: e.as_deref(),
- })
- .collect();
- result.metadata = Some(super::web_search_metadata(
- &query,
- "Exa",
- &structured,
- limit,
- ));
- Ok(result)
- }
-}
-
-/// Find pages similar to a URL via the Exa API (`POST /findSimilar`).
-pub struct ExaFindSimilarTool {
- client: ExaClient,
-}
-
-impl ExaFindSimilarTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- client: ExaClient::new(api_key, api_url, max_results, timeout_secs),
- }
- }
-}
-
-#[async_trait]
-impl Tool for ExaFindSimilarTool {
- fn name(&self) -> &str {
- "exa_find_similar"
- }
-
- fn description(&self) -> &str {
- "Find web pages semantically similar to a given URL using Exa. Useful for expanding \
- from one good source to comparable ones (competitors, related papers, similar articles)."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "url": {
- "type": "string",
- "description": "The URL to find similar pages for."
- },
- "max_results": {
- "type": "integer",
- "description": "Maximum number of results to return (default from config, max 20)."
- },
- "exclude_source_domain": {
- "type": "boolean",
- "description": "Exclude other pages from the source URL's own domain."
- },
- "include_domains": { "type": "array", "items": { "type": "string" }, "description": "Only return results from these domains." },
- "exclude_domains": { "type": "array", "items": { "type": "string" }, "description": "Exclude results from these domains." },
- "include_text": {
- "type": "boolean",
- "description": "Also crawl and return the page text for each result (slower)."
- },
- "include_highlights": {
- "type": "boolean",
- "description": "Also return relevant highlight snippets for each result."
- }
- },
- "required": ["url"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- if let Some(blocked) = self.client.local_only_block() {
- return Ok(blocked);
- }
-
- let url = non_empty(args.get("url").and_then(Value::as_str))
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: url"))?;
-
- let limit = self.client.requested_results(&args);
- let mut body = json!({
- "url": url,
- "numResults": limit,
- });
- if let Some(exclude_source) = args.get("exclude_source_domain").and_then(Value::as_bool) {
- body["excludeSourceDomain"] = json!(exclude_source);
- }
- copy_domain_filter(&args, "include_domains", "includeDomains", &mut body);
- copy_domain_filter(&args, "exclude_domains", "excludeDomains", &mut body);
- if let Some(contents) = contents_request(&args) {
- body["contents"] = contents;
- }
-
- let results = self.client.post_documents("findSimilar", body).await?;
- Ok(self.client.to_result(
- &results,
- &format!("pages similar to {url}"),
- limit,
- &options,
- ))
- }
-}
-
-/// Retrieve full page contents for a list of URLs (`POST /contents`).
-pub struct ExaGetContentsTool {
- client: ExaClient,
-}
-
-impl ExaGetContentsTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- client: ExaClient::new(api_key, api_url, max_results, timeout_secs),
- }
- }
-
- /// Accept either a `urls` array or a single `url` string, so the agent can
- /// call this the obvious way for the one-document case.
- fn collect_urls(args: &Value) -> anyhow::Result<Vec<String>> {
- let urls: Vec<String> = match args.get("urls") {
- Some(Value::Array(items)) => items
- .iter()
- .filter_map(|v| non_empty(v.as_str()))
- .collect::<Vec<_>>(),
- Some(Value::String(single)) => non_empty(Some(single)).into_iter().collect(),
- _ => non_empty(args.get("url").and_then(Value::as_str))
- .into_iter()
- .collect(),
- };
- if urls.is_empty() {
- anyhow::bail!("Missing required parameter: urls (a non-empty list of page URLs)");
- }
- Ok(urls)
- }
-}
-
-#[async_trait]
-impl Tool for ExaGetContentsTool {
- fn name(&self) -> &str {
- "exa_get_contents"
- }
-
- fn description(&self) -> &str {
- "Retrieve the full crawled contents of one or more URLs using Exa. Returns page text \
- and, on request, a summary or query-relevant highlights per URL."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "urls": { "type": "array", "items": { "type": "string" }, "description": "The page URLs to retrieve contents for." },
- "include_summary": { "type": "boolean", "description": "Also return an Exa-generated summary of each page." },
- "include_highlights": { "type": "boolean", "description": "Also return relevant highlight snippets for each page." }
- },
- "required": ["urls"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- if let Some(blocked) = self.client.local_only_block() {
- return Ok(blocked);
- }
-
- let urls = Self::collect_urls(&args)?;
-
- // `urls` is Exa's current field name for /contents; `ids` is the
- // backwards-compatible legacy alias, and the schema rejects both at
- // once. Do not "fix" this to `ids`.
- let mut body = json!({
- "urls": urls,
- "text": true,
- });
- if args
- .get("include_summary")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- body["summary"] = json!(true);
- }
- if args
- .get("include_highlights")
- .and_then(Value::as_bool)
- .unwrap_or(false)
- {
- body["highlights"] = json!(true);
- }
-
- let results = self.client.post_documents("contents", body).await?;
- Ok(self.client.to_result(
- &results,
- &format!("{} URL(s)", urls.len()),
- urls.len(),
- &options,
- ))
- }
-}
-
-#[cfg(test)]
-#[path = "exa_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/exa_tests.rs b/crates/openhuman-core/src/search/tools/exa_tests.rs
deleted file mode 100644
index bcab696628..0000000000
--- a/crates/openhuman-core/src/search/tools/exa_tests.rs
+++ /dev/null
@@ -1,500 +0,0 @@
-//! Tests for the Exa BYOK search tool family.
-
-use super::*;
-use axum::{extract::Json, http::StatusCode, routing::post, Router};
-
-fn search_tool() -> ExaSearchTool {
- ExaSearchTool::new(None, None, 5, 15)
-}
-
-fn search_tool_with_key() -> ExaSearchTool {
- ExaSearchTool::new(Some("test-key".into()), None, 5, 15)
-}
-
-/// Spawn a local stand-in for `api.exa.ai` and return its base URL.
-async fn spawn(app: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- format!("http://127.0.0.1:{}", addr.port())
-}
-
-fn one_result_payload() -> Value {
- json!({
- "requestId": "req-1",
- "resolvedSearchType": "neural",
- "results": [
- {
- "id": "https://example.com/a",
- "url": "https://example.com/a",
- "title": "Exa Result",
- "author": "Jane Doe",
- "publishedDate": "2026-05-01T00:00:00.000Z",
- "score": 0.42,
- "text": "Body text from Exa."
- }
- ]
- })
-}
-
-#[test]
-fn tool_names_match_the_documented_byok_surface() {
- assert_eq!(search_tool().name(), "exa_search");
- assert_eq!(
- ExaSearchTool::new_web_search_tool(None, None, 5, 15).name(),
- "web_search_tool"
- );
- assert_eq!(
- ExaFindSimilarTool::new(None, None, 5, 15).name(),
- "exa_find_similar"
- );
- assert_eq!(
- ExaGetContentsTool::new(None, None, 5, 15).name(),
- "exa_get_contents"
- );
-}
-
-#[test]
-fn search_schema_exposes_the_exa_filters() {
- let schema = search_tool().parameters_schema();
- assert_eq!(schema["type"], "object");
- assert!(schema["properties"]["query"].is_object());
- assert!(schema["properties"]["type"].is_object());
- assert!(schema["properties"]["include_domains"].is_object());
- assert!(schema["properties"]["start_published_date"].is_object());
- assert_eq!(schema["required"][0], "query");
-}
-
-#[test]
-fn search_type_enum_matches_exa_current_search_modes() {
- // Exa's documented modes, fastest to most thorough. `neural` / `keyword`
- // are legacy spellings and must not be advertised to the agent.
- let schema = search_tool().parameters_schema();
- let modes = schema["properties"]["type"]["enum"]
- .as_array()
- .expect("type enum")
- .iter()
- .map(|v| v.as_str().unwrap().to_string())
- .collect::<Vec<_>>();
-
- assert_eq!(
- modes,
- vec![
- "auto",
- "instant",
- "fast",
- "deep-lite",
- "deep",
- "deep-reasoning"
- ]
- );
-}
-
-#[test]
-fn search_body_maps_snake_case_args_to_exa_camel_case() {
- let tool = search_tool_with_key();
- let body = tool.build_body(
- &json!({
- "max_results": 3,
- "type": "neural",
- "category": "research paper",
- "include_domains": ["arxiv.org"],
- "exclude_domains": ["spam.test"],
- "start_published_date": "2026-01-01",
- "end_published_date": "2026-06-30",
- "include_text": true,
- "include_highlights": true
- }),
- "quantum error correction",
- );
-
- assert_eq!(body["query"], "quantum error correction");
- assert_eq!(body["numResults"], 3);
- assert_eq!(body["type"], "neural");
- assert_eq!(body["category"], "research paper");
- assert_eq!(body["includeDomains"][0], "arxiv.org");
- assert_eq!(body["excludeDomains"][0], "spam.test");
- assert_eq!(body["startPublishedDate"], "2026-01-01");
- assert_eq!(body["endPublishedDate"], "2026-06-30");
- assert_eq!(body["contents"]["text"], true);
- assert_eq!(body["contents"]["highlights"], true);
-}
-
-#[test]
-fn search_body_omits_contents_unless_requested() {
- let body = search_tool_with_key().build_body(&json!({}), "plain query");
- assert_eq!(body["numResults"], 5);
- assert!(body.get("contents").is_none());
- assert!(body.get("type").is_none());
-}
-
-#[test]
-fn excerpt_prefers_summary_then_highlights_then_text() {
- let mut item = ExaResultItem {
- text: Some("full text".into()),
- ..Default::default()
- };
- assert_eq!(item.excerpt().as_deref(), Some("full text"));
-
- item.highlights = vec![" ".into(), "a highlight".into()];
- assert_eq!(item.excerpt().as_deref(), Some("a highlight"));
-
- item.summary = Some("the summary".into());
- assert_eq!(item.excerpt().as_deref(), Some("the summary"));
-}
-
-#[test]
-fn contents_accepts_a_urls_array_a_bare_string_or_a_single_url() {
- assert_eq!(
- ExaGetContentsTool::collect_urls(
- &json!({"urls": ["https://a.test", " ", "https://b.test"]})
- )
- .unwrap(),
- vec!["https://a.test".to_string(), "https://b.test".to_string()]
- );
- assert_eq!(
- ExaGetContentsTool::collect_urls(&json!({"urls": "https://a.test"})).unwrap(),
- vec!["https://a.test".to_string()]
- );
- assert_eq!(
- ExaGetContentsTool::collect_urls(&json!({"url": "https://a.test"})).unwrap(),
- vec!["https://a.test".to_string()]
- );
- assert!(ExaGetContentsTool::collect_urls(&json!({"urls": []})).is_err());
-}
-
-#[tokio::test]
-async fn search_without_a_key_reports_where_to_set_one() {
- let err = search_tool()
- .execute(json!({"query": "test"}))
- .await
- .expect_err("missing key must fail");
- let message = err.to_string();
-
- assert!(message.contains("no API key configured"));
- assert!(message.contains("Connections > Search engine"));
-}
-
-#[tokio::test]
-async fn search_requires_a_query() {
- assert!(search_tool_with_key().execute(json!({})).await.is_err());
-}
-
-#[tokio::test]
-async fn search_posts_directly_to_exa_and_renders_results() {
- let app = Router::new().route(
- "/search",
- post(
- |headers: axum::http::HeaderMap, Json(body): Json<Value>| async move {
- assert_eq!(headers.get("x-api-key").unwrap(), "test-key");
- assert_eq!(body["query"], "exa byok");
- assert_eq!(body["numResults"], 3);
- assert_eq!(body["includeDomains"][0], "example.com");
- Json(one_result_payload())
- },
- ),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({
- "query": "exa byok",
- "max_results": 3,
- "include_domains": ["example.com"]
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("via Exa"));
- assert!(result.output().contains("Exa Result"));
- assert!(result.output().contains("https://example.com/a"));
- assert!(result.output().contains("Author: Jane Doe"));
- assert!(result.output().contains("Body text from Exa."));
-}
-
-#[tokio::test]
-async fn find_similar_posts_the_source_url_and_renders_results() {
- let app = Router::new().route(
- "/findSimilar",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["url"], "https://example.com/seed");
- assert_eq!(body["numResults"], 2);
- assert_eq!(body["excludeSourceDomain"], true);
- Json(one_result_payload())
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaFindSimilarTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({
- "url": "https://example.com/seed",
- "max_results": 2,
- "exclude_source_domain": true
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result
- .output()
- .contains("pages similar to https://example.com/seed"));
- assert!(result.output().contains("Exa Result"));
-}
-
-#[tokio::test]
-async fn get_contents_requests_text_for_every_url() {
- let app = Router::new().route(
- "/contents",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["urls"][0], "https://example.com/a");
- assert_eq!(body["urls"][1], "https://example.com/b");
- assert_eq!(body["text"], true);
- assert_eq!(body["summary"], true);
- Json(one_result_payload())
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaGetContentsTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({
- "urls": ["https://example.com/a", "https://example.com/b"],
- "include_summary": true
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("2 URL(s)"));
- assert!(result.output().contains("Body text from Exa."));
-}
-
-#[tokio::test]
-async fn get_contents_renders_more_documents_than_the_configured_max_results() {
- // The result cap belongs to search, not to a caller-supplied URL batch.
- let app = Router::new().route(
- "/contents",
- post(|Json(_): Json<Value>| async move {
- Json(json!({
- "results": (0..4)
- .map(|i| json!({
- "url": format!("https://example.com/{i}"),
- "title": format!("Doc {i}"),
- }))
- .collect::<Vec<_>>()
- }))
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaGetContentsTool::new(Some("test-key".into()), Some(base_url), 2, 15);
- let result = tool
- .execute(json!({
- "urls": [
- "https://example.com/0",
- "https://example.com/1",
- "https://example.com/2",
- "https://example.com/3"
- ]
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("Doc 3"));
-}
-
-#[tokio::test]
-async fn unauthorized_status_names_the_key_without_leaking_the_body() {
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::UNAUTHORIZED,
- "invalid api key for query: private search",
- )
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaSearchTool::new(Some("bad-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("401 must fail");
- let message = err.to_string();
-
- assert!(message.contains("Exa rejected the configured API key"));
- assert!(message.contains("Connections > Search engine"));
- assert!(!message.contains("invalid api key for query"));
-}
-
-#[tokio::test]
-async fn payment_required_status_surfaces_actionable_credits_error() {
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::PAYMENT_REQUIRED,
- r#"{"error":"You have exceeded your credits limit for query: private search","tag":"NO_MORE_CREDITS"}"#,
- )
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("402 must fail with actionable message");
- let message = err.to_string();
-
- assert!(message.contains("Exa credits exhausted (HTTP 402)"));
- assert!(message.contains("dashboard.exa.ai"));
- assert!(!message.contains("private search"));
-}
-
-#[tokio::test]
-async fn rate_limited_status_surfaces_actionable_message() {
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::TOO_MANY_REQUESTS,
- "rate limit exceeded for query: private search",
- )
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("429 must fail with rate limit message");
- let message = err.to_string();
-
- assert!(message.contains("Exa rate limit exceeded (HTTP 429)"));
- assert!(!message.contains("private search"));
-}
-
-#[tokio::test]
-async fn non_success_status_does_not_expose_the_response_body() {
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::BAD_REQUEST,
- "sensitive query context should stay private",
- )
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("non-2xx responses should fail");
- let message = err.to_string();
-
- assert!(message.contains("Exa returned non-2xx status 400 Bad Request"));
- assert!(!message.contains("sensitive query context"));
-}
-
-/// Privacy epic S7 (#4441): `LocalOnly` must refuse every Exa call before any
-/// query or URL reaches api.exa.ai. The base URL points at a port nothing is
-/// listening on, so a request escaping the guard fails the test rather than
-/// silently passing.
-fn local_only() -> crate::security::live_policy::TestPrivacyGuard {
- crate::security::live_policy::test_privacy_scope(crate::config::PrivacyMode::LocalOnly)
-}
-
-#[tokio::test]
-async fn search_is_refused_under_local_only_privacy_mode() {
- let _mode = local_only();
- let tool = ExaSearchTool::new(
- Some("test-key".into()),
- Some("http://127.0.0.1:1".into()),
- 5,
- 15,
- );
-
- let result = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect("the block is a tool error, not a transport failure");
-
- assert!(result.is_error);
- assert!(
- result.output().contains("[policy-blocked]"),
- "got: {}",
- result.output()
- );
- assert!(
- !result.output().contains("private search"),
- "the block message must not echo the query: {}",
- result.output()
- );
-}
-
-#[tokio::test]
-async fn find_similar_and_get_contents_are_refused_under_local_only() {
- let _mode = local_only();
- let base = || Some("http://127.0.0.1:1".to_string());
-
- let similar = ExaFindSimilarTool::new(Some("k".into()), base(), 5, 15)
- .execute(json!({"url": "https://example.com/seed"}))
- .await
- .expect("blocked, not failed");
- assert!(similar.is_error);
- assert!(similar.output().contains("[policy-blocked]"));
-
- let contents = ExaGetContentsTool::new(Some("k".into()), base(), 5, 15)
- .execute(json!({"urls": ["https://example.com/a"]}))
- .await
- .expect("blocked, not failed");
- assert!(contents.is_error);
- assert!(contents.output().contains("[policy-blocked]"));
-}
-
-#[test]
-fn markdown_rendering_neutralizes_hostile_titles_and_urls() {
- // Title and URL are remote, attacker-controlled. An unescaped `]` would
- // close the link label and let a crafted page inject markdown into the
- // agent transcript.
- let client = ExaClient::new(Some("k".into()), None, 5, 15);
- let results = vec![ExaResultItem {
- url: "https://example.com/a_(b)".into(),
- title: Some("Pwned](https://evil.test) [click".into()),
- ..Default::default()
- }];
-
- let out = client.render_markdown(&results, "q", 5);
-
- // The hostile `]` is escaped, so the label never closes early and the
- // injected `(https://evil.test)` cannot become a link destination. Bare
- // parens need no escaping inside a label.
- assert!(!out.contains("[Pwned](https://evil.test)"));
- assert!(out.contains(r"[Pwned\](https://evil.test) \[click]"));
- // Parenthesised URLs survive intact inside an angle-bracket destination.
- assert!(out.contains("(<https://example.com/a_(b)>)"));
-}
-
-#[tokio::test]
-async fn empty_results_render_a_plain_no_results_line() {
- let app = Router::new().route(
- "/search",
- post(|Json(_): Json<Value>| async move { Json(json!({ "results": [] })) }),
- );
- let base_url = spawn(app).await;
-
- let tool = ExaSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({"query": "nothing here"}))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("No Exa results for: nothing here"));
-}
diff --git a/crates/openhuman-core/src/search/tools/mod.rs b/crates/openhuman-core/src/search/tools/mod.rs
deleted file mode 100644
index ecd49e60c3..0000000000
--- a/crates/openhuman-core/src/search/tools/mod.rs
+++ /dev/null
@@ -1,105 +0,0 @@
-//! Agent-facing search tool implementations, one module per provider.
-//!
-//! See `README.md` for the provider -> tool -> transport table and how each
-//! family is registered (engine registry, `IntegrationClient`, or a direct
-//! RPC handler).
-
-mod brave;
-mod exa;
-mod parallel;
-mod querit;
-mod searxng;
-mod seltz;
-mod tavily;
-mod tinyfish;
-mod web_search;
-
-pub use brave::{
- BraveImageSearchTool, BraveNewsSearchTool, BraveVideoSearchTool, BraveWebSearchTool,
-};
-pub use exa::{
- ExaFindSimilarTool, ExaGetContentsTool, ExaResultItem, ExaSearchResponse, ExaSearchTool,
-};
-pub use parallel::{
- ParallelChatTool, ParallelDatasetTool, ParallelEnrichTool, ParallelExtractTool,
- ParallelResearchTool, ParallelSearchTool, SearchResponse, SearchResultItem,
-};
-pub use querit::QueritSearchTool;
-pub use searxng::{
- normalize_categories, SearxngSearchArgs, SearxngSearchResponse, SearxngSearchTool,
- MAX_RESULTS as SEARXNG_MAX_RESULTS,
-};
-pub use seltz::SeltzSearchTool;
-pub use tavily::{
- TavilyExtractResponse, TavilyExtractResult, TavilyExtractTool, TavilyImage, TavilyResultItem,
- TavilySearchResponse, TavilySearchTool,
-};
-pub use tinyfish::{TinyFishAgentRunTool, TinyFishFetchTool, TinyFishSearchTool};
-pub use web_search::WebSearchTool;
-// Crate-internal: the `tools.web_search` RPC reuses the same provider
-// resolution so both managed-search surfaces attribute a call identically.
-pub(crate) use web_search::resolve_managed_provider;
-
-/// Maximum characters kept from a web-search result's excerpt when it is
-/// copied into [`ToolResult::metadata`][tinytools::ToolResult] for the UI
-/// (issue: tool-call presentation). Deliberately smaller than the ~500-char
-/// budget the model-facing text renders with — this metadata is for a compact
-/// result card, not the full context the model reads.
-pub(crate) const WEB_SEARCH_METADATA_EXCERPT_CHARS: usize = 300;
-
-/// One search result, borrowed from whatever provider-specific struct the
-/// caller already has, for building the structured
-/// `{"kind":"web_search",...}` metadata every model-facing web-search tool
-/// attaches to its [`tinytools::ToolResult::metadata`] (issue: tool-call
-/// presentation). Kept separate from the model-facing rendering so a change
-/// here can never perturb the byte-identical prompt text the provider's cache
-/// keys on.
-pub(crate) struct WebSearchResultRef<'a> {
- pub title: &'a str,
- pub url: &'a str,
- pub published: Option<&'a str>,
- pub excerpt: Option<&'a str>,
-}
-
-/// Build the structured web-search metadata payload:
-/// `{"kind":"web_search","query":...,"provider":...,"results":[{"title":...,
-/// "url":...,"published":...?,"excerpt":...?}]}`. `max_results` caps how many
-/// of `results` are copied in, matching whatever cap the tool's own
-/// model-facing rendering already applies so the structured payload never
-/// claims more results exist than the model was shown.
-///
-/// This is metadata (host-only, never rendered to the model) — see
-/// [`tinytools::ToolResult::metadata`]'s own docs on that boundary.
-pub(crate) fn web_search_metadata(
- query: &str,
- provider: &str,
- results: &[WebSearchResultRef<'_>],
- max_results: usize,
-) -> serde_json::Value {
- let results_json: Vec<serde_json::Value> = results
- .iter()
- .take(max_results)
- .map(|r| {
- let mut obj = serde_json::json!({
- "title": r.title,
- "url": r.url,
- });
- if let Some(published) = r.published.map(str::trim).filter(|s| !s.is_empty()) {
- obj["published"] = serde_json::json!(published);
- }
- if let Some(excerpt) = r.excerpt.map(str::trim).filter(|s| !s.is_empty()) {
- obj["excerpt"] = serde_json::json!(crate::util::truncate_with_ellipsis(
- excerpt,
- WEB_SEARCH_METADATA_EXCERPT_CHARS
- ));
- }
- obj
- })
- .collect();
- serde_json::json!({
- "kind": "web_search",
- "query": query,
- "provider": provider,
- "results": results_json,
- })
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel.rs b/crates/openhuman-core/src/search/tools/parallel.rs
deleted file mode 100644
index 2437c80708..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel.rs
+++ /dev/null
@@ -1,54 +0,0 @@
-//! Parallel web search and content extraction integration tools.
-//!
-//! **Scope**: All (agent loop + CLI/RPC).
-//!
-//! **Endpoints**:
-//! - `POST /agent-integrations/parallel/search`
-//! - `POST /agent-integrations/parallel/extract`
-//! - `POST /agent-integrations/parallel/chat`
-//! - `POST /agent-integrations/parallel/research` (async; we always wait inline)
-//! - `POST /agent-integrations/parallel/enrich`
-//! - `POST /agent-integrations/parallel/dataset` (FindAll, async)
-//!
-//! **Pricing** (fetched from backend):
-//! - Search: ~$0.01/request
-//! - Extract: ~$0.002/URL
-//! - Chat / research / enrich: per-model or per-processor (see backend `/pricing`)
-//! - Dataset: pre-charged at `match_limit × per-match`
-//!
-//! The backend handles Parallel API keys, billing, and rate limiting.
-
-mod chat;
-mod dataset;
-mod enrich;
-mod extract;
-mod research;
-mod search;
-
-#[cfg(test)]
-#[path = "parallel_tests.rs"]
-mod tests;
-
-pub use chat::ParallelChatTool;
-pub use dataset::ParallelDatasetTool;
-pub use enrich::ParallelEnrichTool;
-pub use extract::ParallelExtractTool;
-pub use research::ParallelResearchTool;
-pub use search::{ParallelSearchTool, SearchResponse, SearchResultItem};
-
-// Re-exported only for the test module (`super::*`), which asserts on the
-// raw backend response shapes and formatting helpers directly.
-#[cfg(test)]
-use crate::integrations::IntegrationClient;
-#[cfg(test)]
-use enrich::{enrich_payload, format_enrich_response, EnrichResponse};
-#[cfg(test)]
-use extract::ExtractResponse;
-#[cfg(test)]
-use research::{format_research_response, research_payload, ResearchResponse};
-#[cfg(test)]
-use serde_json::json;
-#[cfg(test)]
-use std::sync::Arc;
-#[cfg(test)]
-use tinytools::Tool;
diff --git a/crates/openhuman-core/src/search/tools/parallel/chat.rs b/crates/openhuman-core/src/search/tools/parallel/chat.rs
deleted file mode 100644
index 3d625d6495..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel/chat.rs
+++ /dev/null
@@ -1,136 +0,0 @@
-//! Chat: `ParallelChatTool` and its response types.
-
-use crate::integrations::IntegrationClient;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{Tool, ToolResult};
-
-// ── ParallelChatTool ────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct ChatResponse {
- #[serde(default)]
- choices: Vec<ChatChoice>,
- #[serde(default)]
- basis: Option<serde_json::Value>,
- #[serde(rename = "costUsd", default)]
- cost_usd: f64,
-}
-
-#[derive(Debug, Deserialize)]
-struct ChatChoice {
- #[serde(default)]
- message: ChatMessage,
- #[serde(default, rename = "finish_reason")]
- finish_reason: Option<String>,
-}
-
-#[derive(Debug, Default, Deserialize)]
-struct ChatMessage {
- #[serde(default)]
- #[allow(dead_code)]
- role: String,
- #[serde(default)]
- content: String,
-}
-
-/// AI-powered chat backed by Parallel's web-research models.
-pub struct ParallelChatTool {
- client: Arc<IntegrationClient>,
-}
-
-impl ParallelChatTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for ParallelChatTool {
- fn name(&self) -> &str {
- "parallel_chat"
- }
-
- fn description(&self) -> &str {
- "Chat with the web via Parallel's research-grounded chat models. \
- OpenAI-compatible: pass `messages` (system/user/assistant) and a `model` \
- (`speed` cheapest, `lite`, `base`, `core` most capable). Returns the \
- assistant's reply plus optional citation `basis` for research models. \
- Use this for grounded Q&A like \"summarize today's news on …\" or \
- \"what is the current price of BTC?\" — Parallel will browse and cite."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "model": {
- "type": "string",
- "enum": ["speed", "lite", "base", "core"],
- "description": "Model tier — speed (cheapest) → core (most capable)"
- },
- "messages": {
- "type": "array",
- "minItems": 1,
- "items": {
- "type": "object",
- "properties": {
- "role": { "type": "string", "enum": ["system", "user", "assistant"] },
- "content": { "type": "string" }
- },
- "required": ["role", "content"]
- }
- }
- },
- "required": ["model", "messages"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let model = args
- .get("model")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: model"))?;
- let messages = args
- .get("messages")
- .and_then(|v| v.as_array())
- .filter(|a| !a.is_empty())
- .ok_or_else(|| anyhow::anyhow!("messages must be a non-empty array"))?;
-
- tracing::info!(
- "[parallel_chat] model={} messages={}",
- model,
- messages.len()
- );
-
- let body = json!({ "model": model, "messages": messages });
- match self
- .client
- .post::<ChatResponse>("/agent-integrations/parallel/chat", &body)
- .await
- {
- Ok(resp) => {
- let mut out = String::new();
- if let Some(c) = resp.choices.first() {
- out.push_str(&c.message.content);
- if let Some(reason) = &c.finish_reason {
- out.push_str(&format!("\n\n[finish_reason: {}]", reason));
- }
- } else {
- out.push_str("(no choices returned)");
- }
- if let Some(basis) = resp.basis {
- out.push_str(&format!(
- "\n\nCitations (basis):\n{}",
- serde_json::to_string_pretty(&basis).unwrap_or_default()
- ));
- }
- out.push_str(&format!("\n\nCost: ${:.4}", resp.cost_usd));
- Ok(ToolResult::success(out))
- }
- Err(e) => Ok(ToolResult::error(format!("Parallel chat failed: {e}"))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel/dataset.rs b/crates/openhuman-core/src/search/tools/parallel/dataset.rs
deleted file mode 100644
index 875ce2a28a..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel/dataset.rs
+++ /dev/null
@@ -1,134 +0,0 @@
-//! Dataset: `ParallelDatasetTool` (FindAll, async).
-
-use crate::integrations::IntegrationClient;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{Tool, ToolResult};
-
-// ── ParallelDatasetTool ─────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct DatasetResponse {
- #[serde(rename = "findallId", default)]
- findall_id: String,
- #[serde(default)]
- status: serde_json::Value,
- #[serde(rename = "matchLimit", default)]
- match_limit: u64,
- #[serde(rename = "costUsd", default)]
- cost_usd: f64,
-}
-
-/// Generate a web dataset via Parallel's FindAll — kicks off an async run
-/// that produces structured candidate matches.
-pub struct ParallelDatasetTool {
- client: Arc<IntegrationClient>,
-}
-
-impl ParallelDatasetTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for ParallelDatasetTool {
- fn name(&self) -> &str {
- "parallel_dataset"
- }
-
- fn description(&self) -> &str {
- "Generate a web dataset via Parallel FindAll. Describe an `objective`, \
- the `entity_type` you want (e.g. \"SaaS company\", \"academic paper\"), \
- and a list of `match_conditions` — each a `name` plus an optional \
- `description`. Parallel discovers and enriches matching candidates \
- in the background. This call returns the run ID and pre-authorised cost; \
- use `match_limit` to cap how many candidates are produced. \
- Run is async — fetch results separately by `findall_id`."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "objective": { "type": "string", "description": "What dataset to build" },
- "entity_type": { "type": "string", "description": "What kind of entity to find" },
- "match_conditions": {
- "type": "array",
- "minItems": 1,
- "maxItems": 20,
- "items": {
- "type": "object",
- "properties": {
- "name": { "type": "string" },
- "description": { "type": "string" }
- },
- "required": ["name"]
- }
- },
- "generator": {
- "type": "string",
- "enum": ["preview", "base", "core", "pro"],
- "description": "Generator tier (default base)"
- },
- "match_limit": {
- "type": "integer",
- "minimum": 5,
- "maximum": 1000,
- "description": "Max candidates to produce (default 10)"
- }
- },
- "required": ["objective", "entity_type", "match_conditions"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let objective = args
- .get("objective")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: objective"))?;
- let entity_type = args
- .get("entity_type")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: entity_type"))?;
- let match_conditions = args
- .get("match_conditions")
- .and_then(|v| v.as_array())
- .filter(|a| !a.is_empty())
- .ok_or_else(|| anyhow::anyhow!("match_conditions must be a non-empty array"))?;
-
- let mut body = json!({
- "objective": objective,
- "entityType": entity_type,
- "matchConditions": match_conditions,
- });
- if let Some(g) = args.get("generator").and_then(|v| v.as_str()) {
- body["generator"] = json!(g);
- }
- if let Some(l) = args.get("match_limit").and_then(|v| v.as_u64()) {
- body["matchLimit"] = json!(l.clamp(5, 1000));
- }
-
- tracing::info!("[parallel_dataset] entity_type={}", entity_type);
-
- match self
- .client
- .post::<DatasetResponse>("/agent-integrations/parallel/dataset", &body)
- .await
- {
- Ok(resp) => {
- let out = format!(
- "Dataset run started\n findall_id: {}\n match_limit: {}\n status: {}\n\nCost (pre-authorised): ${:.4}\n\nResults are produced asynchronously — fetch them later by findall_id.",
- resp.findall_id,
- resp.match_limit,
- serde_json::to_string(&resp.status).unwrap_or_default(),
- resp.cost_usd
- );
- Ok(ToolResult::success(out))
- }
- Err(e) => Ok(ToolResult::error(format!("Parallel dataset failed: {e}"))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel/enrich.rs b/crates/openhuman-core/src/search/tools/parallel/enrich.rs
deleted file mode 100644
index 6522aaf3b6..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel/enrich.rs
+++ /dev/null
@@ -1,169 +0,0 @@
-//! Enrich: `ParallelEnrichTool` and its response types.
-
-use crate::integrations::IntegrationClient;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{Tool, ToolResult};
-
-// ── ParallelEnrichTool ──────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-pub(super) struct EnrichResponse {
- #[serde(default, rename = "runId")]
- pub(super) run_id: Option<String>,
- #[serde(default)]
- pub(super) status: Option<String>,
- #[serde(default)]
- pub(super) output: Option<serde_json::Value>,
- #[serde(rename = "costUsd", default)]
- pub(super) cost_usd: f64,
-}
-
-pub(super) fn format_enrich_response(resp: EnrichResponse) -> Result<String, String> {
- if let Some(id) = &resp.run_id {
- tracing::debug!(
- "[parallel_enrich] completed run_id={} status={:?} cost_usd={:.4}",
- id,
- resp.status,
- resp.cost_usd
- );
- } else {
- tracing::debug!(
- "[parallel_enrich] completed without run_id status={:?} cost_usd={:.4}",
- resp.status,
- resp.cost_usd
- );
- }
-
- let mut out = String::new();
- if let Some(s) = &resp.status {
- out.push_str(&format!("Status: {}\n", s));
- }
- let Some(o) = resp.output else {
- let status = resp.status.as_deref().unwrap_or("unknown");
- tracing::debug!(
- "[parallel_enrich] incomplete blocking response status={} cost_usd={:.4}",
- status,
- resp.cost_usd
- );
- return Err(format!(
- "Parallel enrich did not return output before the inline wait completed (status: {status}). Try again with a higher timeout_seconds or a cheaper processor."
- ));
- };
- out.push_str("\nOutput:\n");
- out.push_str(&serde_json::to_string_pretty(&o).unwrap_or_default());
- out.push_str(&format!("\n\nCost: ${:.4}", resp.cost_usd));
- Ok(out)
-}
-
-pub(super) fn enrich_payload(resp: &EnrichResponse, display: &str) -> serde_json::Value {
- json!({
- "display": display,
- "status": resp.status,
- "output": resp.output,
- "cost_usd": resp.cost_usd,
- })
-}
-
-/// Enrich an entity with structured web data — synchronous Task API run
-/// with a required output schema.
-pub struct ParallelEnrichTool {
- client: Arc<IntegrationClient>,
-}
-
-impl ParallelEnrichTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for ParallelEnrichTool {
- fn name(&self) -> &str {
- "parallel_enrich"
- }
-
- fn description(&self) -> &str {
- "Enrich an entity (company, person, product) with structured web data. \
- Pass an `input` (the thing to enrich) plus a JSON `output_schema` describing \
- the fields you want filled in — Parallel returns a structured object \
- conforming to that schema. Blocks until the run completes."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "input": {
- "description": "Entity to enrich — string or object",
- "oneOf": [{ "type": "string" }, { "type": "object" }]
- },
- "processor": {
- "type": "string",
- "enum": ["lite", "base", "core", "ultra"],
- "description": "Processor tier — lite (cheapest) → ultra (most thorough)"
- },
- "output_schema": {
- "type": "object",
- "description": "JSON schema for the structured output (required)"
- },
- "timeout_seconds": {
- "type": "integer",
- "minimum": 10,
- "maximum": 900,
- "description": "Max time to wait (default 600)"
- }
- },
- "required": ["input", "processor", "output_schema"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let input = args
- .get("input")
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: input"))?;
- let processor = args
- .get("processor")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: processor"))?;
- let output_schema = args
- .get("output_schema")
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: output_schema"))?;
-
- let mut body = json!({
- "input": input,
- "processor": processor,
- "outputSchema": output_schema,
- });
- if let Some(t) = args.get("timeout_seconds").and_then(|v| v.as_u64()) {
- body["timeoutSeconds"] = json!(t.clamp(10, 900));
- }
-
- tracing::info!("[parallel_enrich] processor={}", processor);
-
- match self
- .client
- .post::<EnrichResponse>("/agent-integrations/parallel/enrich", &body)
- .await
- {
- Ok(resp) => {
- let display = match format_enrich_response(EnrichResponse {
- run_id: resp.run_id.clone(),
- status: resp.status.clone(),
- output: resp.output.clone(),
- cost_usd: resp.cost_usd,
- }) {
- Ok(display) => display,
- Err(message) => return Ok(ToolResult::error(message)),
- };
- Ok(ToolResult::success_with_markdown(
- enrich_payload(&resp, &display),
- display,
- ))
- }
- Err(e) => Ok(ToolResult::error(format!("Parallel enrich failed: {e}"))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel/extract.rs b/crates/openhuman-core/src/search/tools/parallel/extract.rs
deleted file mode 100644
index 2872df0346..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel/extract.rs
+++ /dev/null
@@ -1,211 +0,0 @@
-//! Extract: `ParallelExtractTool` and its response types.
-
-use super::search::truncate_chars;
-use crate::integrations::IntegrationClient;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{Tool, ToolResult};
-
-#[derive(Debug, Deserialize)]
-pub(super) struct ExtractResponse {
- #[serde(rename = "extractId", default)]
- #[allow(dead_code)]
- pub(super) extract_id: String,
- #[serde(default)]
- pub(super) results: Vec<ExtractResultItem>,
- #[serde(default)]
- pub(super) errors: Vec<ExtractError>,
- #[serde(rename = "costUsd", default)]
- pub(super) cost_usd: f64,
-}
-
-#[derive(Debug, Deserialize)]
-pub(super) struct ExtractResultItem {
- #[serde(default)]
- pub(super) url: String,
- #[serde(default)]
- pub(super) title: Option<String>,
- #[serde(default)]
- pub(super) excerpts: Vec<String>,
- #[serde(default)]
- pub(super) full_content: Option<String>,
-}
-
-#[derive(Debug, Deserialize)]
-pub(super) struct ExtractError {
- #[serde(default)]
- pub(super) url: String,
- #[serde(default)]
- pub(super) error: String,
-}
-
-// ── ParallelExtractTool ─────────────────────────────────────────────
-
-/// Extract content from web pages via the Parallel API.
-pub struct ParallelExtractTool {
- client: Arc<IntegrationClient>,
-}
-
-impl ParallelExtractTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-/// Maximum characters of full_content to include per URL in tool output.
-const MAX_CONTENT_CHARS: usize = 5000;
-
-#[async_trait]
-impl Tool for ParallelExtractTool {
- fn name(&self) -> &str {
- "parallel_extract"
- }
-
- fn description(&self) -> &str {
- "Extract content from one or more web pages using the Parallel API. \
- Returns page titles, excerpts, and optionally full content. \
- Useful for reading articles, documentation, or structured data from URLs. \
- Cost is per URL, billed by the backend."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "urls": {
- "type": "array",
- "items": { "type": "string" },
- "description": "URLs to extract content from (1-20)",
- "minItems": 1,
- "maxItems": 20
- },
- "objective": {
- "type": "string",
- "description": "What information to focus on when extracting"
- },
- "excerpts": {
- "type": "boolean",
- "description": "Include relevant excerpts (default true)",
- "default": true
- },
- "full_content": {
- "type": "boolean",
- "description": "Include full page content (default false)",
- "default": false
- }
- },
- "required": ["urls"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let urls = args
- .get("urls")
- .and_then(|v| v.as_array())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: urls"))?;
-
- if urls.is_empty() {
- return Ok(ToolResult::error("urls must contain at least one URL"));
- }
-
- let mut url_strings: Vec<&str> = Vec::with_capacity(urls.len());
- for (i, v) in urls.iter().enumerate() {
- match v.as_str() {
- Some(s) if !s.trim().is_empty() => url_strings.push(s),
- Some(_) => {
- return Ok(ToolResult::error(format!("urls[{i}] is an empty string")));
- }
- None => {
- return Ok(ToolResult::error(format!("urls[{i}] is not a string")));
- }
- }
- }
-
- let objective = args.get("objective").and_then(|v| v.as_str());
- let excerpts = args
- .get("excerpts")
- .and_then(|v| v.as_bool())
- .unwrap_or(true);
- let full_content = args
- .get("full_content")
- .and_then(|v| v.as_bool())
- .unwrap_or(false);
-
- let mut body = json!({
- "urls": url_strings,
- "excerpts": excerpts,
- "fullContent": full_content,
- });
-
- if let Some(obj) = objective {
- body["objective"] = json!(obj);
- }
-
- tracing::info!("[parallel_extract] urls={}", url_strings.len());
-
- match self
- .client
- .post::<ExtractResponse>("/agent-integrations/parallel/extract", &body)
- .await
- {
- Ok(resp) => {
- let mut lines = Vec::new();
-
- for (i, item) in resp.results.iter().enumerate() {
- let title = item.title.as_deref().unwrap_or("(no title)");
- lines.push(format!("\n{}. {} — {}", i + 1, title, item.url));
-
- for excerpt in &item.excerpts {
- let text = excerpt.trim();
- if !text.is_empty() {
- let (slice, was_truncated) = truncate_chars(text, 500);
- let truncated = if was_truncated {
- format!("{slice}...")
- } else {
- slice.to_string()
- };
- lines.push(format!(" {}", truncated));
- }
- }
-
- if let Some(ref content) = item.full_content {
- let content = content.trim();
- if !content.is_empty() {
- let (slice, was_truncated) = truncate_chars(content, MAX_CONTENT_CHARS);
- let truncated = if was_truncated {
- format!(
- "{}... [truncated, {} chars total]",
- slice,
- content.chars().count()
- )
- } else {
- slice.to_string()
- };
- lines.push(format!(" Content:\n {}", truncated));
- }
- }
- }
-
- if !resp.errors.is_empty() {
- lines.push("\nErrors:".to_string());
- for err in &resp.errors {
- lines.push(format!(" {} — {}", err.url, err.error));
- }
- }
-
- if lines.is_empty() {
- Ok(ToolResult::success(format!(
- "No content extracted from the provided URLs.\nCost: ${:.4}",
- resp.cost_usd
- )))
- } else {
- lines.push(format!("\nCost: ${:.4}", resp.cost_usd));
- Ok(ToolResult::success(lines.join("\n")))
- }
- }
- Err(e) => Ok(ToolResult::error(format!("Parallel extract failed: {e}"))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel/research.rs b/crates/openhuman-core/src/search/tools/parallel/research.rs
deleted file mode 100644
index b8a1a00de8..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel/research.rs
+++ /dev/null
@@ -1,172 +0,0 @@
-//! Research: `ParallelResearchTool` and its response types.
-
-use crate::integrations::IntegrationClient;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{Tool, ToolResult};
-
-// ── ParallelResearchTool ────────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-pub(super) struct ResearchResponse {
- #[serde(default, rename = "runId")]
- pub(super) run_id: Option<String>,
- #[serde(default)]
- pub(super) status: Option<String>,
- #[serde(default)]
- pub(super) result: Option<serde_json::Value>,
- #[serde(rename = "costUsd", default)]
- pub(super) cost_usd: f64,
-}
-
-pub(super) fn format_research_response(resp: ResearchResponse) -> Result<String, String> {
- if let Some(id) = &resp.run_id {
- tracing::debug!(
- "[parallel_research] completed run_id={} status={:?} cost_usd={:.4}",
- id,
- resp.status,
- resp.cost_usd
- );
- } else {
- tracing::debug!(
- "[parallel_research] completed without run_id status={:?} cost_usd={:.4}",
- resp.status,
- resp.cost_usd
- );
- }
-
- let mut out = String::new();
- if let Some(s) = &resp.status {
- out.push_str(&format!("Status: {}\n", s));
- }
- let Some(r) = resp.result else {
- let status = resp.status.as_deref().unwrap_or("unknown");
- tracing::debug!(
- "[parallel_research] incomplete blocking response status={} cost_usd={:.4}",
- status,
- resp.cost_usd
- );
- return Err(format!(
- "Parallel research did not return a result before the inline wait completed (status: {status}). Try again with a higher timeout_seconds or a cheaper processor."
- ));
- };
- out.push_str("\nResult:\n");
- out.push_str(&serde_json::to_string_pretty(&r).unwrap_or_default());
- out.push_str(&format!("\n\nCost: ${:.4}", resp.cost_usd));
- Ok(out)
-}
-
-pub(super) fn research_payload(resp: &ResearchResponse, display: &str) -> serde_json::Value {
- json!({
- "display": display,
- "status": resp.status,
- "result": resp.result,
- "cost_usd": resp.cost_usd,
- })
-}
-
-/// Deep research via Parallel's Task API — multi-step web investigation
-/// with structured or freeform output.
-pub struct ParallelResearchTool {
- client: Arc<IntegrationClient>,
-}
-
-impl ParallelResearchTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for ParallelResearchTool {
- fn name(&self) -> &str {
- "parallel_research"
- }
-
- fn description(&self) -> &str {
- "Deep web research via Parallel's Task API. Submit an objective and a processor \
- tier (`lite`, `base`, `core`, `ultra`) — Parallel browses many sources, \
- synthesises, and returns a single rich answer. Optionally pass an \
- `output_schema` (JSON schema) to force structured output. \
- Blocks inline until the run completes (up to ~10 minutes). \
- Use for tasks that need more than a single search/extract pair, e.g. \
- \"compare these three companies' financials\" or \"build a competitor matrix\"."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "input": {
- "description": "The research objective — string or structured object",
- "oneOf": [{ "type": "string" }, { "type": "object" }]
- },
- "processor": {
- "type": "string",
- "enum": ["lite", "base", "core", "ultra"],
- "description": "Processor tier — lite (cheapest) → ultra (most thorough)"
- },
- "output_schema": {
- "type": "object",
- "description": "Optional JSON schema describing the desired structured output"
- },
- "timeout_seconds": {
- "type": "integer",
- "minimum": 10,
- "maximum": 900,
- "description": "Max time to wait inline (default 600)"
- }
- },
- "required": ["input", "processor"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let input = args
- .get("input")
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: input"))?;
- let processor = args
- .get("processor")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: processor"))?;
-
- let mut body = json!({
- "input": input,
- "processor": processor,
- "wait": true,
- });
- if let Some(schema) = args.get("output_schema") {
- body["outputSchema"] = schema.clone();
- }
- if let Some(t) = args.get("timeout_seconds").and_then(|v| v.as_u64()) {
- body["timeoutSeconds"] = json!(t.clamp(10, 900));
- }
-
- tracing::info!("[parallel_research] processor={}", processor);
-
- match self
- .client
- .post::<ResearchResponse>("/agent-integrations/parallel/research", &body)
- .await
- {
- Ok(resp) => {
- let display = match format_research_response(ResearchResponse {
- run_id: resp.run_id.clone(),
- status: resp.status.clone(),
- result: resp.result.clone(),
- cost_usd: resp.cost_usd,
- }) {
- Ok(display) => display,
- Err(message) => return Ok(ToolResult::error(message)),
- };
- Ok(ToolResult::success_with_markdown(
- research_payload(&resp, &display),
- display,
- ))
- }
- Err(e) => Ok(ToolResult::error(format!("Parallel research failed: {e}"))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel/search.rs b/crates/openhuman-core/src/search/tools/parallel/search.rs
deleted file mode 100644
index a0905a8533..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel/search.rs
+++ /dev/null
@@ -1,219 +0,0 @@
-//! Search: `ParallelSearchTool` and its response types.
-
-use crate::integrations::IntegrationClient;
-pub(super) use crate::util::truncate_chars_flagged as truncate_chars;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{Tool, ToolResult};
-
-// ── Response types ──────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize, serde::Serialize)]
-pub struct SearchResponse {
- #[serde(rename = "searchId")]
- #[allow(dead_code)]
- pub search_id: String,
- pub results: Vec<SearchResultItem>,
- #[serde(rename = "costUsd")]
- pub cost_usd: f64,
- /// Upstream provider the managed backend resolved this search to
- /// (e.g. "Exa"). Optional: older backends omit it, so this stays
- /// `None` and callers fall back to the managed default. Surfaced to
- /// the UI as the search attribution ("Searched with Exa", #5136).
- /// Aliased so a rename on the backend side keeps deserializing.
- #[serde(
- default,
- alias = "resolvedProvider",
- alias = "searchProvider",
- skip_serializing_if = "Option::is_none"
- )]
- pub provider: Option<String>,
-}
-
-#[derive(Debug, Deserialize, serde::Serialize)]
-pub struct SearchResultItem {
- pub url: String,
- #[serde(default)]
- pub title: String,
- #[serde(default)]
- pub publish_date: Option<String>,
- #[serde(default)]
- pub excerpts: Vec<String>,
-}
-
-// ── ParallelSearchTool ──────────────────────────────────────────────
-
-/// AI-powered web search via the Parallel API.
-pub struct ParallelSearchTool {
- client: Arc<IntegrationClient>,
-}
-
-impl ParallelSearchTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for ParallelSearchTool {
- fn name(&self) -> &str {
- "parallel_search"
- }
-
- fn description(&self) -> &str {
- "AI-powered web search via Parallel. Provide an objective and one or more search \
- queries. Returns relevant results with titles, URLs, and excerpts. \
- Supports modes: 'fast' (quickest), 'one-shot' (balanced), 'agentic' (most thorough). \
- Cost is per request, billed by the backend."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "objective": {
- "type": "string",
- "description": "What you are trying to find or learn"
- },
- "search_queries": {
- "type": "array",
- "items": { "type": "string" },
- "description": "One or more search queries (1-10)",
- "minItems": 1,
- "maxItems": 10
- },
- "mode": {
- "type": "string",
- "enum": ["fast", "one-shot", "agentic"],
- "description": "Search mode (default: fast)",
- "default": "fast"
- },
- "num_results": {
- "type": "integer",
- "description": "Number of results per query (1-50, default 10)",
- "minimum": 1,
- "maximum": 50,
- "default": 10
- },
- "max_characters_per_excerpt": {
- "type": "integer",
- "description": "Max characters per excerpt (100-10000, default 500)",
- "minimum": 100,
- "maximum": 10000,
- "default": 500
- }
- },
- "required": ["objective", "search_queries"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let objective = args
- .get("objective")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: objective"))?;
-
- if objective.trim().is_empty() {
- return Ok(ToolResult::error("objective cannot be empty"));
- }
-
- let search_queries = args
- .get("search_queries")
- .and_then(|v| v.as_array())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: search_queries"))?;
-
- if search_queries.is_empty() {
- return Ok(ToolResult::error(
- "search_queries must contain at least one query",
- ));
- }
-
- let mut queries: Vec<&str> = Vec::with_capacity(search_queries.len());
- for (i, v) in search_queries.iter().enumerate() {
- match v.as_str() {
- Some(s) if !s.trim().is_empty() => queries.push(s),
- Some(_) => {
- return Ok(ToolResult::error(format!(
- "search_queries[{i}] is an empty string"
- )));
- }
- None => {
- return Ok(ToolResult::error(format!(
- "search_queries[{i}] is not a string"
- )));
- }
- }
- }
-
- let mode = args.get("mode").and_then(|v| v.as_str()).unwrap_or("fast");
-
- let mut body = json!({
- "objective": objective,
- "searchQueries": queries,
- "mode": mode,
- });
-
- // Build excerpts config if custom values provided
- let num_results = args.get("num_results").and_then(|v| v.as_u64());
- let max_chars = args
- .get("max_characters_per_excerpt")
- .and_then(|v| v.as_u64());
-
- if num_results.is_some() || max_chars.is_some() {
- let mut excerpts = json!({});
- if let Some(n) = num_results {
- excerpts["numResults"] = json!(n.clamp(1, 50));
- }
- if let Some(c) = max_chars {
- excerpts["maxCharactersPerExcerpt"] = json!(c.clamp(100, 10000));
- }
- body["excerpts"] = excerpts;
- }
-
- tracing::info!("[parallel_search] queries={}", queries.len());
- tracing::debug!("[parallel_search] objective={:?}", objective);
-
- match self
- .client
- .post::<SearchResponse>("/agent-integrations/parallel/search", &body)
- .await
- {
- Ok(resp) => {
- if resp.results.is_empty() {
- return Ok(ToolResult::success(format!(
- "No results found for: {}",
- objective
- )));
- }
-
- let mut lines = vec![format!("Search results ({} found):", resp.results.len())];
-
- for (i, item) in resp.results.iter().enumerate() {
- lines.push(format!("\n{}. {}", i + 1, item.title));
- lines.push(format!(" {}", item.url));
- if let Some(ref date) = item.publish_date {
- lines.push(format!(" Published: {}", date));
- }
- if let Some(excerpt) = item.excerpts.first() {
- let text = excerpt.trim();
- if !text.is_empty() {
- let (slice, was_truncated) = truncate_chars(text, 500);
- let truncated = if was_truncated {
- format!("{slice}...")
- } else {
- slice.to_string()
- };
- lines.push(format!(" {}", truncated));
- }
- }
- }
-
- lines.push(format!("\nCost: ${:.4}", resp.cost_usd));
- Ok(ToolResult::success(lines.join("\n")))
- }
- Err(e) => Ok(ToolResult::error(format!("Parallel search failed: {e}"))),
- }
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/parallel_tests.rs b/crates/openhuman-core/src/search/tools/parallel_tests.rs
deleted file mode 100644
index 79eb694fad..0000000000
--- a/crates/openhuman-core/src/search/tools/parallel_tests.rs
+++ /dev/null
@@ -1,285 +0,0 @@
-use super::*;
-use crate::integrations::ToolScope;
-
-fn test_client() -> Arc<IntegrationClient> {
- Arc::new(IntegrationClient::new("http://test".into(), "tok".into()))
-}
-
-// ── ParallelSearchTool ──────────────────────────────────────────
-
-#[test]
-fn search_tool_metadata() {
- let tool = ParallelSearchTool::new(test_client());
- assert_eq!(tool.name(), "parallel_search");
- assert_eq!(tool.scope(), ToolScope::All);
- assert!(tool.description().contains("web search"));
-}
-
-#[test]
-fn search_schema_required_fields() {
- let tool = ParallelSearchTool::new(test_client());
- let schema = tool.parameters_schema();
- let required = schema["required"].as_array().unwrap();
- assert!(required.iter().any(|v| v == "objective"));
- assert!(required.iter().any(|v| v == "search_queries"));
-}
-
-#[tokio::test]
-async fn search_rejects_missing_objective() {
- let tool = ParallelSearchTool::new(test_client());
- assert!(tool
- .execute(json!({"search_queries": ["test"]}))
- .await
- .is_err());
-}
-
-#[tokio::test]
-async fn search_rejects_empty_objective() {
- let tool = ParallelSearchTool::new(test_client());
- let result = tool
- .execute(json!({"objective": "", "search_queries": ["test"]}))
- .await
- .unwrap();
- assert!(result.is_error);
-}
-
-#[tokio::test]
-async fn search_rejects_empty_queries() {
- let tool = ParallelSearchTool::new(test_client());
- let result = tool
- .execute(json!({"objective": "test", "search_queries": []}))
- .await
- .unwrap();
- assert!(result.is_error);
-}
-
-#[test]
-fn search_response_rejects_missing_search_id() {
- let json = r#"{
- "results": [],
- "costUsd": 0.01
- }"#;
- assert!(serde_json::from_str::<SearchResponse>(json).is_err());
-}
-
-#[test]
-fn search_response_rejects_missing_results() {
- let json = r#"{
- "searchId": "s123",
- "costUsd": 0.01
- }"#;
- assert!(serde_json::from_str::<SearchResponse>(json).is_err());
-}
-
-#[test]
-fn search_response_rejects_missing_cost_usd() {
- let json = r#"{
- "searchId": "s123",
- "results": []
- }"#;
- assert!(serde_json::from_str::<SearchResponse>(json).is_err());
-}
-
-#[test]
-fn search_response_deserializes() {
- let json = r#"{
- "searchId": "s123",
- "results": [
- {
- "url": "https://example.com",
- "title": "Example",
- "publish_date": "2026-01-01",
- "excerpts": ["Some text"]
- }
- ],
- "costUsd": 0.01
- }"#;
- let resp: SearchResponse = serde_json::from_str(json).unwrap();
- assert_eq!(resp.results.len(), 1);
- assert_eq!(resp.results[0].title, "Example");
- // Older backends omit the resolved provider entirely (#5136).
- assert_eq!(resp.provider, None);
-}
-
-#[test]
-fn search_response_reads_resolved_provider() {
- // The backend names the provider it routed the managed search to, so the
- // UI attribution ("Searched with Exa") is never hardcoded (#5136).
- let json = r#"{
- "searchId": "s123",
- "results": [],
- "costUsd": 0.01,
- "provider": "Exa"
- }"#;
- let resp: SearchResponse = serde_json::from_str(json).unwrap();
- assert_eq!(resp.provider.as_deref(), Some("Exa"));
-}
-
-#[test]
-fn search_response_reads_provider_aliases() {
- // Tolerate the backend naming the field differently so a rename upstream
- // does not silently drop attribution.
- for field in ["resolvedProvider", "searchProvider"] {
- let json = format!(
- r#"{{ "searchId": "s123", "results": [], "costUsd": 0.01, "{field}": "Brave" }}"#
- );
- let resp: SearchResponse = serde_json::from_str(&json).unwrap();
- assert_eq!(resp.provider.as_deref(), Some("Brave"), "field {field}");
- }
-}
-
-// ── ParallelExtractTool ─────────────────────────────────────────
-
-#[test]
-fn extract_tool_metadata() {
- let tool = ParallelExtractTool::new(test_client());
- assert_eq!(tool.name(), "parallel_extract");
- assert_eq!(tool.scope(), ToolScope::All);
- assert!(tool.description().contains("Extract content"));
-}
-
-#[test]
-fn extract_schema_required_urls() {
- let tool = ParallelExtractTool::new(test_client());
- let schema = tool.parameters_schema();
- let required = schema["required"].as_array().unwrap();
- assert!(required.iter().any(|v| v == "urls"));
-}
-
-#[tokio::test]
-async fn extract_rejects_missing_urls() {
- let tool = ParallelExtractTool::new(test_client());
- assert!(tool.execute(json!({})).await.is_err());
-}
-
-#[tokio::test]
-async fn extract_rejects_empty_urls() {
- let tool = ParallelExtractTool::new(test_client());
- let result = tool.execute(json!({"urls": []})).await.unwrap();
- assert!(result.is_error);
-}
-
-#[test]
-fn extract_response_deserializes() {
- let json = r#"{
- "extractId": "e123",
- "results": [
- {
- "url": "https://example.com",
- "title": "Example Page",
- "excerpts": ["Key info here"],
- "full_content": null
- }
- ],
- "errors": [
- {"url": "https://bad.com", "error": "timeout"}
- ],
- "costUsd": 0.002
- }"#;
- let resp: ExtractResponse = serde_json::from_str(json).unwrap();
- assert_eq!(resp.results.len(), 1);
- assert_eq!(resp.errors.len(), 1);
- assert_eq!(resp.errors[0].url, "https://bad.com");
-}
-
-#[test]
-fn extract_response_with_full_content() {
- let json = r#"{
- "extractId": "e456",
- "results": [
- {
- "url": "https://example.com",
- "title": "Full Article",
- "excerpts": [],
- "full_content": "This is the full article content."
- }
- ],
- "errors": [],
- "costUsd": 0.002
- }"#;
- let resp: ExtractResponse = serde_json::from_str(json).unwrap();
- assert_eq!(
- resp.results[0].full_content.as_deref(),
- Some("This is the full article content.")
- );
-}
-
-#[test]
-fn research_output_hides_internal_run_id() {
- let resp = ResearchResponse {
- run_id: Some("run_internal_123".into()),
- status: Some("completed".into()),
- result: Some(json!({ "summary": "useful answer" })),
- cost_usd: 0.1234,
- };
- let output = format_research_response(ResearchResponse {
- run_id: resp.run_id.clone(),
- status: resp.status.clone(),
- result: resp.result.clone(),
- cost_usd: resp.cost_usd,
- })
- .unwrap();
- let payload = research_payload(&resp, &output);
-
- assert!(output.contains("Status: completed"));
- assert!(output.contains("useful answer"));
- assert!(output.contains("Cost: $0.1234"));
- assert!(!output.contains("Run:"));
- assert!(!output.contains("run_internal_123"));
- assert!(payload.get("run_id").is_none());
-}
-
-#[test]
-fn enrich_output_hides_internal_run_id() {
- let resp = EnrichResponse {
- run_id: Some("run_internal_456".into()),
- status: Some("completed".into()),
- output: Some(json!({ "company": "OpenHuman" })),
- cost_usd: 0.5678,
- };
- let output = format_enrich_response(EnrichResponse {
- run_id: resp.run_id.clone(),
- status: resp.status.clone(),
- output: resp.output.clone(),
- cost_usd: resp.cost_usd,
- })
- .unwrap();
- let payload = enrich_payload(&resp, &output);
-
- assert!(output.contains("Status: completed"));
- assert!(output.contains("OpenHuman"));
- assert!(output.contains("Cost: $0.5678"));
- assert!(!output.contains("Run:"));
- assert!(!output.contains("run_internal_456"));
- assert!(payload.get("run_id").is_none());
-}
-
-#[test]
-fn research_incomplete_response_returns_actionable_error_without_run_id() {
- let err = format_research_response(ResearchResponse {
- run_id: Some("run_internal_789".into()),
- status: Some("running".into()),
- result: None,
- cost_usd: 0.1111,
- })
- .unwrap_err();
-
- assert!(err.contains("did not return a result"));
- assert!(err.contains("higher timeout_seconds"));
- assert!(!err.contains("run_internal_789"));
-}
-
-#[test]
-fn enrich_incomplete_response_returns_actionable_error_without_run_id() {
- let err = format_enrich_response(EnrichResponse {
- run_id: Some("run_internal_987".into()),
- status: Some("running".into()),
- output: None,
- cost_usd: 0.2222,
- })
- .unwrap_err();
-
- assert!(err.contains("did not return output"));
- assert!(err.contains("higher timeout_seconds"));
- assert!(!err.contains("run_internal_987"));
-}
diff --git a/crates/openhuman-core/src/search/tools/querit.rs b/crates/openhuman-core/src/search/tools/querit.rs
deleted file mode 100644
index 83bb7b96b6..0000000000
--- a/crates/openhuman-core/src/search/tools/querit.rs
+++ /dev/null
@@ -1,555 +0,0 @@
-//! Querit web search integration -- direct API (not backend-proxied).
-//!
-//! **Scope**: Agent + CLI/RPC.
-//!
-//! **Endpoint**: `POST https://api.querit.ai/v1/search`
-//!
-//! **Auth**: `Authorization: Bearer <api key>`.
-//!
-//! Querit exposes an AI-oriented web search endpoint with optional site,
-//! time-range, country, and language filters. This integration calls the
-//! Querit API directly using the user's configured API key.
-
-use async_trait::async_trait;
-use serde::{Deserialize, Serialize};
-use serde_json::{json, Map, Value};
-use std::time::Duration;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-const DEFAULT_API_URL: &str = "https://api.querit.ai/v1";
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct QueritSearchResponse {
- #[serde(default)]
- pub took: String,
- #[serde(default)]
- pub error_code: i64,
- #[serde(default)]
- pub error_msg: String,
- #[serde(default)]
- pub search_id: i64,
- #[serde(default)]
- pub query_context: QueritQueryContext,
- #[serde(default)]
- pub results: QueritResults,
-}
-
-#[derive(Debug, Default, Deserialize, Serialize)]
-pub struct QueritQueryContext {
- #[serde(default)]
- pub query: String,
-}
-
-#[derive(Debug, Default, Deserialize, Serialize)]
-pub struct QueritResults {
- #[serde(default)]
- pub result: Vec<QueritResultItem>,
-}
-
-#[derive(Debug, Clone, Deserialize, Serialize)]
-pub struct QueritResultItem {
- #[serde(default)]
- pub url: String,
- #[serde(default)]
- pub page_age: Option<String>,
- #[serde(default)]
- pub title: Option<String>,
- #[serde(default)]
- pub snippet: Option<String>,
- #[serde(default)]
- pub site_name: Option<String>,
- #[serde(default)]
- pub site_icon: Option<String>,
- #[serde(default)]
- pub sentence: Vec<String>,
-}
-
-/// Real-time web search via the Querit API.
-pub struct QueritSearchTool {
- tool_name: &'static str,
- api_key: Option<String>,
- api_url: String,
- max_results: usize,
- timeout_secs: u64,
- http_client: reqwest::Client,
-}
-
-impl QueritSearchTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self::with_name("querit_search", api_key, api_url, max_results, timeout_secs)
- }
-
- pub fn new_web_search_tool(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self::with_name(
- "web_search_tool",
- api_key,
- api_url,
- max_results,
- timeout_secs,
- )
- }
-
- fn with_name(
- tool_name: &'static str,
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- let timeout = timeout_secs.max(1);
- let http_client = crate::util::tls::tls_client_builder()
- .http1_only()
- .timeout(Duration::from_secs(timeout))
- .connect_timeout(Duration::from_secs(10))
- .build()
- .expect("failed to build Querit HTTP client");
-
- Self {
- tool_name,
- api_key,
- api_url: api_url.unwrap_or_else(|| DEFAULT_API_URL.to_string()),
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout,
- http_client,
- }
- }
-
- fn render_results_plain(&self, results: &[QueritResultItem], query: &str) -> String {
- if results.is_empty() {
- return format!("No results found for: {}", query);
- }
-
- let mut lines = vec![format!("Search results for: {} (via Querit)", query)];
- for (i, item) in results.iter().take(self.max_results).enumerate() {
- let title = item
- .title
- .as_deref()
- .filter(|t| !t.trim().is_empty())
- .unwrap_or("Untitled");
- lines.push(format!("{}. {}", i + 1, title));
- lines.push(format!(" {}", item.url.trim()));
-
- if let Some(age) = item.page_age.as_deref() {
- let age = age.trim();
- if !age.is_empty() {
- lines.push(format!(" Page age: {}", age));
- }
- }
- if let Some(site) = item.site_name.as_deref() {
- let site = site.trim();
- if !site.is_empty() {
- lines.push(format!(" Site: {}", site));
- }
- }
- if let Some(snippet) = item.snippet_text() {
- let truncated = crate::util::truncate_with_ellipsis(&snippet, 500);
- lines.push(format!(" {}", truncated));
- }
- }
-
- lines.join("\n")
- }
-
- fn render_results_markdown(&self, results: &[QueritResultItem], query: &str) -> String {
- if results.is_empty() {
- return format!("_No results for `{query}`_ (via Querit)");
- }
-
- // Carry the shared `(via <Provider>)` attribution marker the plain-text
- // renderer already emits, so the tool timeline can label the row
- // (#5136). Production shows the markdown rendering.
- let mut out = format!("# Search results -- `{query}` (via Querit)\n");
- for item in results.iter().take(self.max_results) {
- let title = item
- .title
- .as_deref()
- .filter(|t| !t.trim().is_empty())
- .unwrap_or("Untitled");
- out.push_str(&format!("\n## [{title}]({})\n", item.url.trim()));
- if let Some(age) = item.page_age.as_deref() {
- let age = age.trim();
- if !age.is_empty() {
- out.push_str(&format!("_Page age: {age}_\n\n"));
- }
- }
- if let Some(site) = item.site_name.as_deref() {
- let site = site.trim();
- if !site.is_empty() {
- out.push_str(&format!("_Site: {site}_\n\n"));
- }
- }
- if let Some(snippet) = item.snippet_text() {
- let truncated = crate::util::truncate_with_suffix(&snippet, 500, "...");
- out.push_str(&format!("> {truncated}\n"));
- }
- }
- out
- }
-
- fn insert_array_filter(args: &Value, key: &str, target: &mut Map<String, Value>) {
- if let Some(value) = args.get(key).filter(|v| v.is_array()) {
- target.insert("include".to_string(), value.clone());
- }
- }
-
- fn object_or_include_map(value: Option<Value>) -> Map<String, Value> {
- match value {
- Some(Value::Object(map)) => map,
- Some(Value::Array(items)) => {
- let mut map = Map::new();
- map.insert("include".to_string(), Value::Array(items));
- map
- }
- _ => Map::new(),
- }
- }
-
- fn build_filters(args: &Value) -> Option<Value> {
- let mut filters = args
- .get("filters")
- .and_then(Value::as_object)
- .cloned()
- .unwrap_or_default();
-
- let mut sites = Self::object_or_include_map(filters.remove("sites"));
- if let Some(include) = args.get("include_domains").filter(|v| v.is_array()) {
- sites.insert("include".to_string(), include.clone());
- }
- if let Some(exclude) = args.get("exclude_domains").filter(|v| v.is_array()) {
- sites.insert("exclude".to_string(), exclude.clone());
- }
- if !sites.is_empty() {
- filters.insert("sites".to_string(), Value::Object(sites));
- }
-
- let existing_time_range = filters
- .remove("timeRange")
- .or_else(|| filters.remove("time_range"));
- let mut time_range_obj = match existing_time_range.clone() {
- Some(Value::Object(map)) => map,
- Some(Value::String(date)) if !date.trim().is_empty() => {
- let mut map = Map::new();
- map.insert("date".to_string(), json!(date.trim()));
- map
- }
- _ => Map::new(),
- };
- let time_range = args
- .get("time_range")
- .or_else(|| args.get("date"))
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .or_else(|| {
- let from = args
- .get("from_date")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- let to = args
- .get("to_date")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty());
- match (from, to) {
- (Some(from), Some(to)) => Some(format!("{from}to{to}")),
- (Some(day), None) | (None, Some(day)) => Some(day.to_string()),
- (None, None) => None,
- }
- });
- if let Some(date) = time_range {
- time_range_obj.insert("date".to_string(), json!(date));
- filters.insert("timeRange".to_string(), Value::Object(time_range_obj));
- } else if !time_range_obj.is_empty() {
- filters.insert("timeRange".to_string(), Value::Object(time_range_obj));
- } else if let Some(other) = existing_time_range {
- filters.insert("timeRange".to_string(), other);
- }
-
- let mut geo = match filters.remove("geo") {
- Some(Value::Object(map)) => map,
- _ => Map::new(),
- };
- let mut countries = Self::object_or_include_map(geo.remove("countries"));
- Self::insert_array_filter(args, "countries", &mut countries);
- if !countries.is_empty() {
- geo.insert("countries".to_string(), Value::Object(countries));
- }
- if !geo.is_empty() {
- filters.insert("geo".to_string(), Value::Object(geo));
- }
-
- let mut languages = Self::object_or_include_map(filters.remove("languages"));
- Self::insert_array_filter(args, "languages", &mut languages);
- if !languages.is_empty() {
- filters.insert("languages".to_string(), Value::Object(languages));
- }
-
- if filters.is_empty() {
- None
- } else {
- Some(Value::Object(filters))
- }
- }
-
- fn decode_response(value: Value) -> anyhow::Result<QueritSearchResponse> {
- let payload = value
- .get("response_data")
- .and_then(|v| v.get("aiapi_res"))
- .or_else(|| value.get("aiapi_res"))
- .cloned()
- .unwrap_or(value);
- serde_json::from_value(payload).map_err(|e| {
- tracing::warn!("[querit] failed to parse response: {e}");
- anyhow::anyhow!("Failed to parse Querit response: {e}")
- })
- }
-}
-
-impl QueritResultItem {
- fn snippet_text(&self) -> Option<String> {
- self.snippet
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .or_else(|| {
- let joined = self
- .sentence
- .iter()
- .map(|s| s.trim())
- .filter(|s| !s.is_empty())
- .collect::<Vec<_>>()
- .join(" ");
- if joined.is_empty() {
- None
- } else {
- Some(joined)
- }
- })
- }
-}
-
-#[async_trait]
-impl Tool for QueritSearchTool {
- fn name(&self) -> &str {
- self.tool_name
- }
-
- fn description(&self) -> &str {
- "Search the web in real time using Querit. Returns current results with URLs, \
- snippets, site names, and page age. Supports site include/exclude filters, \
- time ranges, countries, and languages."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "The search query. Use concise keywords for best results."
- },
- "max_results": {
- "type": "integer",
- "description": "Maximum number of results to return (default from config, max 20)."
- },
- "count": {
- "type": "integer",
- "description": "Querit-native alias for max_results."
- },
- "filters": {
- "type": "object",
- "description": "Querit-native filters object with sites, timeRange, geo, and languages."
- },
- "include_domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Only fetch results from these domains."
- },
- "exclude_domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Exclude results from these domains."
- },
- "time_range": {
- "type": "string",
- "description": "Querit date filter: d7, w2, m6, y1, or YYYY-MM-DDtoYYYY-MM-DD."
- },
- "from_date": {
- "type": "string",
- "description": "Start date for a Querit date-range filter (YYYY-MM-DD)."
- },
- "to_date": {
- "type": "string",
- "description": "End date for a Querit date-range filter (YYYY-MM-DD)."
- },
- "countries": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Country filters, e.g. [\"united states\", \"japan\"]."
- },
- "languages": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Language filters, e.g. [\"english\", \"japanese\"]."
- }
- },
- "required": ["query"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let query = args
- .get("query")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|q| !q.is_empty())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;
-
- let api_key = self.api_key.as_deref().ok_or_else(|| {
- anyhow::anyhow!(
- "Querit search unavailable: no API key configured. \
- Set QUERIT_API_KEY or OPENHUMAN_QUERIT_API_KEY, \
- or add search.querit.api_key to config.toml."
- )
- })?;
-
- let max_results = args
- .get("max_results")
- .or_else(|| args.get("count"))
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 20) as usize)
- .unwrap_or(self.max_results);
-
- let mut body = json!({
- "query": query,
- "count": max_results,
- });
- if let Some(filters) = Self::build_filters(&args) {
- body.as_object_mut()
- .expect("querit request body object")
- .insert("filters".to_string(), filters);
- }
-
- let url = format!("{}/search", self.api_url.trim_end_matches('/'));
- tracing::debug!(
- query_len = query.chars().count(),
- max_results,
- timeout_secs = self.timeout_secs,
- "[querit] POST {url}"
- );
-
- let resp = self
- .http_client
- .post(&url)
- .bearer_auth(api_key)
- .header("Content-Type", "application/json")
- .header("Accept", "application/json")
- .json(&body)
- .send()
- .await
- .map_err(|e| {
- tracing::warn!("[querit] request failed: {e}");
- anyhow::anyhow!("Querit search request failed: {e}")
- })?;
-
- let status = resp.status();
- if !status.is_success() {
- let body_text = resp.text().await.unwrap_or_default();
- tracing::warn!(
- status = %status,
- body_len = body_text.len(),
- "[querit] non-2xx response from Querit"
- );
- anyhow::bail!("Querit returned non-2xx status {status}");
- }
-
- let search_resp = Self::decode_response(resp.json().await.map_err(|e| {
- tracing::warn!("[querit] failed to read response JSON: {e}");
- anyhow::anyhow!("Failed to read Querit response JSON: {e}")
- })?)?;
-
- if search_resp.error_code != 0 && search_resp.error_code != 200 {
- tracing::warn!(
- error_code = search_resp.error_code,
- error_msg_len = search_resp.error_msg.chars().count(),
- "[querit] application-level error from Querit"
- );
- anyhow::bail!("Querit returned error_code {}", search_resp.error_code);
- }
-
- tracing::debug!(
- result_count = search_resp.results.result.len(),
- search_id = search_resp.search_id,
- "[querit] search complete"
- );
-
- let mut result =
- ToolResult::success(self.render_results_plain(&search_resp.results.result, query));
- if options.prefer_markdown {
- result.markdown_formatted =
- Some(self.render_results_markdown(&search_resp.results.result, query));
- }
- // Host-only structured payload for the chat UI's tool-call
- // presentation — never rendered to the model, so `render_results_plain`'s
- // text above (and the cache key that depends on it) is unaffected.
- let snippets: Vec<Option<String>> = search_resp
- .results
- .result
- .iter()
- .map(QueritResultItem::snippet_text)
- .collect();
- let structured_results: Vec<crate::search::tools::WebSearchResultRef<'_>> = search_resp
- .results
- .result
- .iter()
- .zip(snippets.iter())
- .map(|(item, snippet)| crate::search::tools::WebSearchResultRef {
- title: item
- .title
- .as_deref()
- .filter(|t| !t.trim().is_empty())
- .unwrap_or("Untitled"),
- url: item.url.as_str(),
- published: item.page_age.as_deref(),
- excerpt: snippet.as_deref(),
- })
- .collect();
- result.metadata = Some(crate::search::tools::web_search_metadata(
- query,
- "Querit",
- &structured_results,
- self.max_results,
- ));
- Ok(result)
- }
-}
-
-#[cfg(test)]
-#[path = "querit_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/querit_tests.rs b/crates/openhuman-core/src/search/tools/querit_tests.rs
deleted file mode 100644
index 2787a00664..0000000000
--- a/crates/openhuman-core/src/search/tools/querit_tests.rs
+++ /dev/null
@@ -1,322 +0,0 @@
-use super::*;
-
-fn tool() -> QueritSearchTool {
- QueritSearchTool::new(None, None, 5, 15)
-}
-
-fn tool_with_key() -> QueritSearchTool {
- QueritSearchTool::new(Some("test-key".into()), None, 5, 15)
-}
-
-#[test]
-fn test_tool_name() {
- assert_eq!(tool().name(), "querit_search");
- assert_eq!(
- QueritSearchTool::new_web_search_tool(None, None, 5, 15).name(),
- "web_search_tool"
- );
-}
-
-#[test]
-fn test_parameters_schema() {
- let schema = tool().parameters_schema();
- assert_eq!(schema["type"], "object");
- assert!(schema["properties"]["query"].is_object());
- assert!(schema["properties"]["time_range"].is_object());
- assert!(schema["properties"]["countries"].is_object());
-}
-
-#[test]
-fn test_render_plain_with_data() {
- let results = vec![QueritResultItem {
- url: "https://example.com/a".into(),
- page_age: Some("2026-05-01 00:00:00".into()),
- title: Some("First Result".into()),
- snippet: Some("First result snippet.".into()),
- site_name: Some("Example".into()),
- site_icon: None,
- sentence: vec![],
- }];
-
- let result = tool().render_results_plain(&results, "test");
- assert!(result.contains("via Querit"));
- assert!(result.contains("First Result"));
- assert!(result.contains("https://example.com/a"));
- assert!(result.contains("Page age: 2026-05-01"));
- assert!(result.contains("Site: Example"));
- assert!(result.contains("First result snippet."));
-}
-
-#[test]
-fn test_render_markdown_carries_provider_marker() {
- // The markdown renderer is what production shows
- // (`output_for_llm(true)`), so it must carry the same shared
- // `(via <Provider>)` marker the plain-text renderer emits — that is
- // what the tool timeline reads back to label the row (#5136).
- let results = vec![QueritResultItem {
- url: "https://example.com/a".into(),
- page_age: None,
- title: Some("First Result".into()),
- snippet: Some("Snippet.".into()),
- site_name: None,
- site_icon: None,
- sentence: vec![],
- }];
- let result = tool().render_results_markdown(&results, "test");
- assert!(result.lines().next().unwrap().ends_with("(via Querit)"));
-
- // A completed empty search is attributed too, so the timeline does not
- // keep showing it as in-progress.
- let empty = tool().render_results_markdown(&[], "test");
- assert!(empty.trim_end().ends_with("(via Querit)"));
-}
-
-#[test]
-fn test_build_filters_maps_supported_fields() {
- let filters = QueritSearchTool::build_filters(&json!({
- "include_domains": ["example.com"],
- "exclude_domains": ["spam.test"],
- "time_range": "d7",
- "countries": ["united states"],
- "languages": ["english"]
- }))
- .expect("filters");
-
- assert_eq!(filters["sites"]["include"][0], "example.com");
- assert_eq!(filters["sites"]["exclude"][0], "spam.test");
- assert_eq!(filters["timeRange"]["date"], "d7");
- assert_eq!(filters["geo"]["countries"]["include"][0], "united states");
- assert_eq!(filters["languages"]["include"][0], "english");
-}
-
-#[test]
-fn test_build_filters_preserves_native_filters_payload() {
- let filters = QueritSearchTool::build_filters(&json!({
- "filters": {
- "sites": {
- "include": ["techcrunch.com"]
- },
- "timeRange": {
- "date": "m3"
- },
- "geo": {
- "countries": {
- "include": ["united states"]
- }
- },
- "languages": {
- "include": ["english"]
- }
- }
- }))
- .expect("filters");
-
- assert_eq!(filters["sites"]["include"][0], "techcrunch.com");
- assert_eq!(filters["timeRange"]["date"], "m3");
- assert_eq!(filters["geo"]["countries"]["include"][0], "united states");
- assert_eq!(filters["languages"]["include"][0], "english");
-}
-
-#[test]
-fn test_build_filters_normalizes_native_shorthand_values() {
- let filters = QueritSearchTool::build_filters(&json!({
- "filters": {
- "sites": ["example.com"],
- "time_range": "m3",
- "geo": {
- "countries": ["united states"]
- },
- "languages": ["english"]
- }
- }))
- .expect("filters");
-
- assert_eq!(filters["sites"]["include"][0], "example.com");
- assert_eq!(filters["timeRange"]["date"], "m3");
- assert_eq!(filters["geo"]["countries"]["include"][0], "united states");
- assert_eq!(filters["languages"]["include"][0], "english");
-}
-
-#[test]
-fn test_build_filters_combines_date_range() {
- let filters = QueritSearchTool::build_filters(&json!({
- "from_date": "2026-01-01",
- "to_date": "2026-01-31"
- }))
- .expect("filters");
- assert_eq!(filters["timeRange"]["date"], "2026-01-01to2026-01-31");
-}
-
-#[test]
-fn test_decode_response_accepts_wrapped_aiapi_shape_and_sentence() {
- let parsed = QueritSearchTool::decode_response(json!({
- "response_data": {
- "aiapi_res": {
- "error_code": 0,
- "search_id": 42,
- "results": {
- "result": [
- {
- "url": "https://example.com",
- "title": "Wrapped",
- "sentence": ["Sentence excerpt."]
- }
- ]
- }
- }
- }
- }))
- .expect("wrapped response");
-
- assert_eq!(parsed.results.result[0].title.as_deref(), Some("Wrapped"));
- assert_eq!(
- parsed.results.result[0].snippet_text().as_deref(),
- Some("Sentence excerpt.")
- );
-}
-
-#[tokio::test]
-async fn test_execute_missing_query() {
- let result = tool_with_key().execute(json!({})).await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn test_execute_without_api_key() {
- let result = tool().execute(json!({"query": "test"})).await;
- assert!(result.is_err());
- assert!(result
- .unwrap_err()
- .to_string()
- .contains("no API key configured"));
-}
-
-#[tokio::test]
-async fn test_execute_posts_to_querit_and_renders_results() {
- use axum::{extract::Json, routing::post, Router};
- use serde_json::Value;
-
- let app = Router::new().route(
- "/search",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["query"], "test query");
- assert_eq!(body["count"], 3);
- assert_eq!(body["filters"]["sites"]["include"][0], "example.com");
- Json(json!({
- "took": "12ms",
- "error_code": 200,
- "error_msg": "",
- "search_id": 42,
- "query_context": { "query": "test query" },
- "results": {
- "result": [
- {
- "url": "https://example.com/result",
- "title": "Querit Result",
- "snippet": "Content from Querit search.",
- "page_age": "2026-05-01 00:00:00",
- "site_name": "Example"
- }
- ]
- }
- }))
- }),
- );
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- let base_url = format!("http://127.0.0.1:{}", addr.port());
-
- let tool = QueritSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({
- "query": "test query",
- "max_results": 3,
- "include_domains": ["example.com"]
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("Querit Result"));
- assert!(result.output().contains("https://example.com/result"));
- assert!(result.output().contains("Content from Querit search."));
-}
-
-#[tokio::test]
-async fn test_execute_non_success_status_does_not_expose_response_body() {
- use axum::{http::StatusCode, routing::post, Router};
-
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::BAD_REQUEST,
- "sensitive query context should stay private",
- )
- }),
- );
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- let base_url = format!("http://127.0.0.1:{}", addr.port());
-
- let tool = QueritSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({
- "query": "private search",
- "max_results": 3
- }))
- .await
- .expect_err("non-2xx responses should fail");
- let message = err.to_string();
-
- assert!(message.contains("Querit returned non-2xx status 400 Bad Request"));
- assert!(!message.contains("sensitive query context"));
-}
-
-#[tokio::test]
-async fn test_execute_app_error_does_not_expose_error_msg() {
- use axum::{extract::Json, routing::post, Router};
- use serde_json::Value;
-
- let app = Router::new().route(
- "/search",
- post(|Json(_body): Json<Value>| async move {
- Json(json!({
- "took": "3ms",
- "error_code": 400,
- "error_msg": "validation failed for sensitive query context",
- "search_id": 42,
- "query_context": { "query": "sensitive query context" },
- "results": { "result": [] }
- }))
- }),
- );
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- let base_url = format!("http://127.0.0.1:{}", addr.port());
-
- let tool = QueritSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({
- "query": "sensitive query context",
- "max_results": 3
- }))
- .await
- .expect_err("application-level errors should fail");
- let message = err.to_string();
-
- assert_eq!(message, "Querit returned error_code 400");
- assert!(!message.contains("validation failed"));
- assert!(!message.contains("sensitive query context"));
-}
diff --git a/crates/openhuman-core/src/search/tools/searxng.rs b/crates/openhuman-core/src/search/tools/searxng.rs
deleted file mode 100644
index 6d1ef0b3e1..0000000000
--- a/crates/openhuman-core/src/search/tools/searxng.rs
+++ /dev/null
@@ -1,439 +0,0 @@
-//! SearXNG search integration for self-hosted, private web search.
-//!
-//! SearXNG exposes JSON results from `GET /search?format=json`. This wrapper
-//! keeps the output shape small and stable for agents and MCP clients:
-//! `{ title, url, snippet, source }`.
-
-use crate::util::utf8_safe_prefix_at_byte_boundary;
-use anyhow::Context;
-use async_trait::async_trait;
-use serde::{Deserialize, Serialize};
-use serde_json::json;
-use std::sync::OnceLock;
-use std::time::Duration;
-use tinytools::{Tool, ToolCallOptions, ToolCategory, ToolResult};
-
-const DEFAULT_SOURCE: &str = "searxng";
-/// Maximum number of SearXNG results accepted by the public tool surface.
-pub const MAX_RESULTS: usize = 50;
-
-static SHARED_HTTP_CLIENT: OnceLock<reqwest::Client> = OnceLock::new();
-
-fn shared_http_client() -> reqwest::Client {
- SHARED_HTTP_CLIENT
- .get_or_init(|| {
- tracing::debug!("[searxng] initializing shared HTTP client");
- // Platform-appropriate TLS backend — see [`crate::util::tls`].
- crate::util::tls::tls_client_builder()
- .build()
- .expect("failed to build shared SearXNG HTTP client")
- })
- .clone()
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-/// Search arguments accepted by the SearXNG tool.
-pub struct SearxngSearchArgs {
- /// Search query sent as SearXNG's `q` parameter.
- pub query: String,
- /// Optional SearXNG categories. `web` is normalized to `general`.
- pub categories: Vec<String>,
- /// Optional language code. Falls back to the configured default when absent.
- pub language: Option<String>,
- /// Optional per-call result limit, clamped to the supported maximum.
- pub max_results: Option<usize>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-/// Normalized response returned to agents, RPC callers, and MCP clients.
-pub struct SearxngSearchResponse {
- /// Trimmed query used for the search.
- pub query: String,
- /// Normalized search results.
- pub results: Vec<SearxngSearchResult>,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-/// One normalized SearXNG result.
-pub struct SearxngSearchResult {
- /// Result title, or the URL when SearXNG omits a title.
- pub title: String,
- /// Absolute result URL.
- pub url: String,
- /// Result excerpt, if SearXNG returned one.
- pub snippet: String,
- /// Search engine/source name.
- pub source: String,
-}
-
-#[derive(Debug, Deserialize)]
-struct RawSearxngResponse {
- #[serde(default)]
- results: Vec<RawSearxngResult>,
-}
-
-#[derive(Debug, Deserialize)]
-struct RawSearxngResult {
- #[serde(default)]
- title: Option<String>,
- #[serde(default)]
- url: Option<String>,
- #[serde(default)]
- content: Option<String>,
- #[serde(default)]
- snippet: Option<String>,
- #[serde(default)]
- engine: Option<String>,
- #[serde(default)]
- engines: Vec<String>,
-}
-
-pub struct SearxngSearchTool {
- base_url: String,
- max_results: usize,
- default_language: String,
- timeout_secs: u64,
- http_client: reqwest::Client,
-}
-
-impl SearxngSearchTool {
- /// Build a SearXNG search tool for a user-configured endpoint.
- pub fn new(
- base_url: String,
- max_results: usize,
- default_language: String,
- timeout_secs: u64,
- ) -> Self {
- Self::with_http_client(
- base_url,
- max_results,
- default_language,
- timeout_secs,
- shared_http_client(),
- )
- }
-
- /// Build a SearXNG search tool with a caller-provided HTTP client.
- pub fn with_http_client(
- base_url: String,
- max_results: usize,
- default_language: String,
- timeout_secs: u64,
- http_client: reqwest::Client,
- ) -> Self {
- let timeout = timeout_secs.max(1);
-
- Self {
- base_url,
- max_results: max_results.clamp(1, MAX_RESULTS),
- default_language,
- timeout_secs: timeout,
- http_client,
- }
- }
-
- /// Execute a SearXNG JSON search and normalize the returned result rows.
- pub async fn search(&self, args: SearxngSearchArgs) -> anyhow::Result<SearxngSearchResponse> {
- let query = args.query.trim();
- if query.is_empty() {
- anyhow::bail!("SearXNG search query cannot be empty");
- }
-
- let max_results = args
- .max_results
- .unwrap_or(self.max_results)
- .clamp(1, MAX_RESULTS);
- let categories = normalize_categories(args.categories)?;
- let language = args
- .language
- .as_deref()
- .map(str::trim)
- .filter(|value| !value.is_empty())
- .unwrap_or_else(|| self.default_language.trim());
-
- let mut url = self.search_endpoint_url()?;
- {
- let mut pairs = url.query_pairs_mut();
- pairs.append_pair("q", query);
- pairs.append_pair("format", "json");
- if !categories.is_empty() {
- pairs.append_pair("categories", &categories.join(","));
- }
- if !language.is_empty() {
- pairs.append_pair("language", language);
- }
- }
-
- tracing::debug!(
- query_len = query.chars().count(),
- max_results,
- categories = ?categories,
- timeout_secs = self.timeout_secs,
- "[searxng] GET /search"
- );
-
- let response = self
- .http_client
- .get(url.clone())
- .timeout(Duration::from_secs(self.timeout_secs))
- .send()
- .await
- .map_err(|err| {
- tracing::warn!(error = %err, "[searxng] request failed");
- anyhow::anyhow!("SearXNG request failed: {err}")
- })?;
-
- let status = response.status();
- if !status.is_success() {
- let body = response.text().await.unwrap_or_default();
- let detail = utf8_safe_prefix_at_byte_boundary(&body, 500);
- tracing::warn!(status = %status, "[searxng] non-2xx response: {detail}");
- anyhow::bail!("SearXNG returned {status}: {detail}");
- }
-
- let raw: RawSearxngResponse = response.json().await.map_err(|err| {
- tracing::warn!(error = %err, "[searxng] failed to parse JSON response");
- anyhow::anyhow!("Failed to parse SearXNG response: {err}")
- })?;
-
- let results = normalize_results(raw, max_results);
- tracing::debug!(result_count = results.len(), "[searxng] search complete");
-
- Ok(SearxngSearchResponse {
- query: query.to_string(),
- results,
- })
- }
-
- fn search_endpoint_url(&self) -> anyhow::Result<reqwest::Url> {
- let base = self.base_url.trim().trim_end_matches('/');
- if base.is_empty() {
- anyhow::bail!("SearXNG base_url cannot be empty");
- }
- let endpoint = if base.ends_with("/search") {
- base.to_string()
- } else {
- format!("{base}/search")
- };
- reqwest::Url::parse(&endpoint)
- .with_context(|| format!("invalid SearXNG base_url `{}`", self.base_url))
- }
-
- fn render_markdown(response: &SearxngSearchResponse) -> String {
- if response.results.is_empty() {
- return format!("No SearXNG results for `{}`.", response.query);
- }
-
- let mut out = format!("# SearXNG results for `{}`\n", response.query);
- for (index, result) in response.results.iter().enumerate() {
- out.push_str(&format!(
- "\n{}. [{}]({})\n",
- index + 1,
- result.title,
- result.url
- ));
- if !result.snippet.is_empty() {
- out.push_str(&format!(" {}\n", result.snippet));
- }
- out.push_str(&format!(" Source: {}\n", result.source));
- }
- out
- }
-}
-
-#[async_trait]
-impl Tool for SearxngSearchTool {
- fn name(&self) -> &str {
- "searxng_search"
- }
-
- fn description(&self) -> &str {
- "Search a user-configured SearXNG instance. Returns private, self-hosted web search results normalized as title, URL, snippet, and source."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "Search query string."
- },
- "categories": {
- "type": "array",
- "items": {
- "type": "string",
- "enum": ["web", "general", "news", "images"]
- },
- "description": "Optional SearXNG categories. `web` maps to SearXNG `general`."
- },
- "language": {
- "type": "string",
- "description": "Optional language code, e.g. `en`, `zh-CN`, `fr`."
- },
- "max_results": {
- "type": "integer",
- "minimum": 1,
- "maximum": MAX_RESULTS,
- "description": "Maximum number of results to return."
- }
- },
- "required": ["query"],
- "additionalProperties": false
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::Workflow
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let search_args = parse_search_args(args)?;
- let response = self.search(search_args).await?;
- let payload = json!({
- "query": response.query,
- "results": response.results,
- });
- let markdown = Self::render_markdown(&response);
- let mut result = ToolResult::json(payload);
- if options.prefer_markdown {
- result.markdown_formatted = Some(markdown);
- }
- Ok(result)
- }
-}
-
-/// Normalize user-facing category aliases into SearXNG category names.
-pub fn normalize_categories(categories: Vec<String>) -> anyhow::Result<Vec<String>> {
- let mut normalized = Vec::new();
- for category in categories {
- let trimmed = category.trim();
- if trimmed.is_empty() {
- continue;
- }
- let mapped = match trimmed.to_ascii_lowercase().as_str() {
- "web" | "general" => "general",
- "news" => "news",
- "images" => "images",
- other => anyhow::bail!(
- "unsupported SearXNG category `{other}`; expected web, news, or images"
- ),
- };
- if !normalized.iter().any(|existing| existing == mapped) {
- normalized.push(mapped.to_string());
- }
- }
- Ok(normalized)
-}
-
-fn normalize_results(raw: RawSearxngResponse, max_results: usize) -> Vec<SearxngSearchResult> {
- raw.results
- .into_iter()
- .filter_map(|item| {
- let url = item.url.unwrap_or_default().trim().to_string();
- if url.is_empty() {
- return None;
- }
- let title = item.title.unwrap_or_default().trim().to_string();
- let snippet = first_non_empty_trimmed([item.content, item.snippet]);
- let source = item
- .engine
- .filter(|value| !value.trim().is_empty())
- .or_else(|| {
- item.engines
- .into_iter()
- .find(|value| !value.trim().is_empty())
- })
- .unwrap_or_else(|| DEFAULT_SOURCE.to_string())
- .trim()
- .to_string();
- Some(SearxngSearchResult {
- title: if title.is_empty() { url.clone() } else { title },
- url,
- snippet,
- source,
- })
- })
- .take(max_results)
- .collect()
-}
-
-fn first_non_empty_trimmed(values: impl IntoIterator<Item = Option<String>>) -> String {
- values
- .into_iter()
- .flatten()
- .map(|value| value.trim().to_string())
- .find(|value| !value.is_empty())
- .unwrap_or_default()
-}
-
-fn parse_search_args(args: serde_json::Value) -> anyhow::Result<SearxngSearchArgs> {
- let object = args
- .as_object()
- .ok_or_else(|| anyhow::anyhow!("SearXNG arguments must be an object"))?;
- let query = object
- .get("query")
- .and_then(|value| value.as_str())
- .map(str::trim)
- .filter(|value| !value.is_empty())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?
- .to_string();
- let categories = match object.get("categories") {
- Some(value) if value.is_null() => Vec::new(),
- Some(value) => value
- .as_array()
- .ok_or_else(|| anyhow::anyhow!("categories must be an array of strings"))?
- .iter()
- .map(|item| {
- item.as_str()
- .map(str::to_string)
- .ok_or_else(|| anyhow::anyhow!("categories must contain only strings"))
- })
- .collect::<anyhow::Result<Vec<_>>>()?,
- None => Vec::new(),
- };
- let language = match object.get("language") {
- Some(value) => {
- let language = value
- .as_str()
- .map(str::trim)
- .filter(|value| !value.is_empty())
- .ok_or_else(|| anyhow::anyhow!("language must be a non-empty string"))?;
- Some(language.to_string())
- }
- None => None,
- };
- let max_results = match object.get("max_results") {
- Some(value) => {
- let max_results = value
- .as_u64()
- .ok_or_else(|| anyhow::anyhow!("max_results must be a positive integer"))?;
- Some(max_results.clamp(1, MAX_RESULTS as u64) as usize)
- }
- None => None,
- };
-
- Ok(SearxngSearchArgs {
- query,
- categories,
- language,
- max_results,
- })
-}
-
-#[cfg(test)]
-#[path = "searxng_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/searxng_tests.rs b/crates/openhuman-core/src/search/tools/searxng_tests.rs
deleted file mode 100644
index 26eb714157..0000000000
--- a/crates/openhuman-core/src/search/tools/searxng_tests.rs
+++ /dev/null
@@ -1,135 +0,0 @@
-use super::*;
-
-fn tool(base_url: String) -> SearxngSearchTool {
- SearxngSearchTool::new(base_url, 10, "en".into(), 5)
-}
-
-#[test]
-fn normalizes_categories_and_maps_web_to_general() {
- let categories = normalize_categories(vec![
- "web".into(),
- "news".into(),
- "general".into(),
- " images ".into(),
- ])
- .expect("categories");
- assert_eq!(categories, vec!["general", "news", "images"]);
-}
-
-#[test]
-fn rejects_unknown_category() {
- let err = normalize_categories(vec!["videos".into()]).expect_err("must reject");
- assert!(err.to_string().contains("unsupported SearXNG category"));
-}
-
-#[test]
-fn normalize_results_falls_back_to_snippet_when_content_is_blank() {
- let results = normalize_results(
- RawSearxngResponse {
- results: vec![RawSearxngResult {
- title: Some("Result".into()),
- url: Some("https://example.com".into()),
- content: Some(" ".into()),
- snippet: Some("Useful fallback snippet".into()),
- engine: Some("engine".into()),
- engines: Vec::new(),
- }],
- },
- 5,
- );
-
- assert_eq!(results[0].snippet, "Useful fallback snippet");
-}
-
-#[test]
-fn parse_search_args_rejects_malformed_optional_values() {
- let language_err = parse_search_args(json!({
- "query": "privacy search",
- "language": 1
- }))
- .expect_err("language must reject wrong type");
- assert!(language_err
- .to_string()
- .contains("language must be a non-empty string"));
-
- let max_results_err = parse_search_args(json!({
- "query": "privacy search",
- "max_results": "10"
- }))
- .expect_err("max_results must reject wrong type");
- assert!(max_results_err
- .to_string()
- .contains("max_results must be a positive integer"));
-}
-
-#[test]
-fn parameters_schema_includes_mcp_expected_fields() {
- let schema = tool("http://localhost:8080".into()).parameters_schema();
- assert_eq!(schema["type"], "object");
- assert!(schema["properties"]["query"].is_object());
- assert!(schema["properties"]["categories"].is_object());
- assert!(schema["properties"]["language"].is_object());
- assert!(schema["properties"]["max_results"].is_object());
-}
-
-#[tokio::test]
-async fn search_calls_json_endpoint_and_normalizes_results() {
- use axum::{extract::Query, routing::get, Json, Router};
- use std::collections::HashMap;
-
- let app = Router::new().route(
- "/search",
- get(|Query(params): Query<HashMap<String, String>>| async move {
- assert_eq!(params.get("q").map(String::as_str), Some("test query"));
- assert_eq!(params.get("format").map(String::as_str), Some("json"));
- assert_eq!(
- params.get("categories").map(String::as_str),
- Some("general,news")
- );
- assert_eq!(params.get("language").map(String::as_str), Some("en"));
- Json(json!({
- "results": [
- {
- "title": "First result",
- "url": "https://example.com/one",
- "content": "A useful snippet.",
- "engine": "duckduckgo"
- },
- {
- "title": "Missing URL should be skipped",
- "content": "No URL"
- },
- {
- "url": "https://example.com/two",
- "snippet": "Fallback snippet.",
- "engines": ["brave"]
- }
- ]
- }))
- }),
- );
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
-
- let response = tool(format!("http://127.0.0.1:{}", addr.port()))
- .search(SearxngSearchArgs {
- query: " test query ".into(),
- categories: vec!["web".into(), "news".into()],
- language: None,
- max_results: Some(5),
- })
- .await
- .expect("search");
-
- assert_eq!(response.query, "test query");
- assert_eq!(response.results.len(), 2);
- assert_eq!(response.results[0].title, "First result");
- assert_eq!(response.results[0].source, "duckduckgo");
- assert_eq!(response.results[1].title, "https://example.com/two");
- assert_eq!(response.results[1].snippet, "Fallback snippet.");
- assert_eq!(response.results[1].source, "brave");
-}
diff --git a/crates/openhuman-core/src/search/tools/seltz.rs b/crates/openhuman-core/src/search/tools/seltz.rs
deleted file mode 100644
index b7b780b936..0000000000
--- a/crates/openhuman-core/src/search/tools/seltz.rs
+++ /dev/null
@@ -1,327 +0,0 @@
-//! Seltz web search integration — direct API (not backend-proxied).
-//!
-//! **Scope**: Agent + CLI/RPC.
-//!
-//! **Endpoint**: `POST https://api.seltz.ai/v1/search`
-//!
-//! **Auth**: `x-api-key` header with user-provided API key.
-//!
-//! Seltz is an independent web search API optimized for AI agents, built on a
-//! custom crawler/index with sub-200ms median latency. Unlike the Parallel
-//! integration, this calls the Seltz API directly — no backend proxy needed.
-
-use crate::util::utf8_safe_prefix_at_byte_boundary;
-use async_trait::async_trait;
-use serde::{Deserialize, Serialize};
-use serde_json::json;
-use std::time::Duration;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-/// Default Seltz API base URL.
-const DEFAULT_API_URL: &str = "https://api.seltz.ai/v1";
-
-// ── Response types ──────────────────────────────────────────────────
-
-#[derive(Debug, Deserialize, Serialize)]
-pub struct SeltzSearchResponse {
- #[serde(default)]
- pub documents: Vec<SeltzDocument>,
-}
-
-#[derive(Debug, Deserialize, Serialize, Clone)]
-pub struct SeltzDocument {
- #[serde(default)]
- pub url: String,
- #[serde(default)]
- pub content: String,
- #[serde(default)]
- pub title: Option<String>,
- #[serde(default)]
- pub published_date: Option<String>,
-}
-
-// ── SeltzSearchTool ─────────────────────────────────────────────────
-
-/// Real-time web search via the Seltz API.
-///
-/// Requires a `SELTZ_API_KEY` (or `OPENHUMAN_SELTZ_API_KEY`) environment
-/// variable or `seltz.api_key` config field. When the key is absent the tool
-/// is still registered but returns a clear "not configured" error at call time
-/// so the agent can fall back to other search tools.
-pub struct SeltzSearchTool {
- api_key: Option<String>,
- api_url: String,
- max_results: usize,
- timeout_secs: u64,
- http_client: reqwest::Client,
-}
-
-impl SeltzSearchTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- let timeout = timeout_secs.max(1);
- // Platform-appropriate TLS backend — see [`crate::util::tls`].
- let http_client = crate::util::tls::tls_client_builder()
- .http1_only()
- .timeout(Duration::from_secs(timeout))
- .connect_timeout(Duration::from_secs(10))
- .build()
- .expect("failed to build Seltz HTTP client");
-
- Self {
- api_key,
- api_url: api_url.unwrap_or_else(|| DEFAULT_API_URL.to_string()),
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout,
- http_client,
- }
- }
-
- fn render_results_plain(&self, docs: &[SeltzDocument], query: &str) -> String {
- if docs.is_empty() {
- return format!("No results found for: {}", query);
- }
-
- let mut lines = vec![format!("Search results for: {} (via Seltz)", query)];
-
- for (i, doc) in docs.iter().take(self.max_results).enumerate() {
- let title = doc
- .title
- .as_deref()
- .filter(|t| !t.trim().is_empty())
- .unwrap_or("Untitled");
- let url = doc.url.trim();
-
- lines.push(format!("{}. {}", i + 1, title));
- lines.push(format!(" {}", url));
-
- if let Some(date) = doc.published_date.as_deref() {
- let date = date.trim();
- if !date.is_empty() {
- lines.push(format!(" Published: {}", date));
- }
- }
-
- let content = doc.content.trim();
- if !content.is_empty() {
- let truncated = crate::util::truncate_with_ellipsis(content, 500);
- lines.push(format!(" {}", truncated));
- }
- }
-
- lines.join("\n")
- }
-
- fn render_results_markdown(&self, docs: &[SeltzDocument], query: &str) -> String {
- if docs.is_empty() {
- return format!("_No results for `{query}`_ (via Seltz)");
- }
-
- // Carry the shared `(via <Provider>)` attribution marker the plain-text
- // renderer already emits, so the tool timeline can label the row
- // (#5136). Production shows the markdown rendering.
- let mut out = format!("# Search results — `{query}` (via Seltz)\n");
- for doc in docs.iter().take(self.max_results) {
- let title = doc
- .title
- .as_deref()
- .filter(|t| !t.trim().is_empty())
- .unwrap_or("Untitled");
- out.push_str(&format!("\n## [{title}]({})\n", doc.url.trim()));
- if let Some(date) = doc.published_date.as_deref() {
- let date = date.trim();
- if !date.is_empty() {
- out.push_str(&format!("_Published: {date}_\n\n"));
- }
- }
- let content = doc.content.trim();
- if !content.is_empty() {
- let truncated = crate::util::truncate_with_suffix(content, 500, "…");
- out.push_str(&format!("> {truncated}\n"));
- }
- }
- out
- }
-}
-
-#[async_trait]
-impl Tool for SeltzSearchTool {
- fn name(&self) -> &str {
- "seltz_search"
- }
-
- fn description(&self) -> &str {
- "Search the web in real time using Seltz. Returns current information from trusted \
- sources with URLs and extracted content. Supports domain filtering, date ranges, \
- and news scope. Fast (<200ms) and optimized for AI agent workflows."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "The search query. Use concise keywords for best results."
- },
- "max_results": {
- "type": "integer",
- "description": "Maximum number of results to return (default from config, max 20)."
- },
- "include_domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Restrict results to these domains (e.g. [\"bbc.com\", \"reuters.com\"])."
- },
- "exclude_domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Exclude results from these domains."
- },
- "from_date": {
- "type": "string",
- "description": "Only include results published on or after this date (YYYY-MM-DD)."
- },
- "to_date": {
- "type": "string",
- "description": "Only include results published on or before this date (YYYY-MM-DD)."
- },
- "scope": {
- "type": "string",
- "description": "Restrict to a specific scope. Currently supported: \"news\"."
- }
- },
- "required": ["query"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let query = args
- .get("query")
- .and_then(|q| q.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;
-
- if query.trim().is_empty() {
- anyhow::bail!("Search query cannot be empty");
- }
-
- let api_key = self.api_key.as_deref().ok_or_else(|| {
- anyhow::anyhow!(
- "Seltz search unavailable: no API key configured. \
- Set SELTZ_API_KEY or OPENHUMAN_SELTZ_API_KEY, \
- or add seltz.api_key to config.toml."
- )
- })?;
-
- let max_results = args
- .get("max_results")
- .and_then(|v| v.as_u64())
- .map(|n| n.clamp(1, 20) as usize)
- .unwrap_or(self.max_results);
-
- // Build request body — only include optional fields when set.
- let mut body = json!({
- "query": query,
- "max_results": max_results,
- });
- let body_map = body.as_object_mut().unwrap();
-
- if let Some(include) = args.get("include_domains") {
- if include.is_array() {
- body_map.insert("include_domains".to_string(), include.clone());
- }
- }
- if let Some(exclude) = args.get("exclude_domains") {
- if exclude.is_array() {
- body_map.insert("exclude_domains".to_string(), exclude.clone());
- }
- }
- if let Some(from) = args.get("from_date").and_then(|v| v.as_str()) {
- if !from.is_empty() {
- body_map.insert("from_date".to_string(), json!(from));
- }
- }
- if let Some(to) = args.get("to_date").and_then(|v| v.as_str()) {
- if !to.is_empty() {
- body_map.insert("to_date".to_string(), json!(to));
- }
- }
- if let Some(scope) = args.get("scope").and_then(|v| v.as_str()) {
- if !scope.is_empty() {
- body_map.insert("scope".to_string(), json!(scope));
- }
- }
-
- let url = format!("{}/search", self.api_url);
-
- tracing::debug!(
- query_len = query.chars().count(),
- max_results,
- timeout_secs = self.timeout_secs,
- "[seltz] POST {url}"
- );
-
- let resp = self
- .http_client
- .post(&url)
- .header("x-api-key", api_key)
- .header("Content-Type", "application/json")
- .json(&body)
- .send()
- .await
- .map_err(|e| {
- tracing::warn!("[seltz] request failed: {e}");
- anyhow::anyhow!("Seltz search request failed: {e}")
- })?;
-
- let status = resp.status();
- if !status.is_success() {
- let body_text = resp.text().await.unwrap_or_default();
- let detail = utf8_safe_prefix_at_byte_boundary(&body_text, 500);
- tracing::warn!(
- status = %status,
- "[seltz] non-2xx response: {detail}"
- );
- anyhow::bail!("Seltz returned {status}: {detail}");
- }
-
- let search_resp: SeltzSearchResponse = resp.json().await.map_err(|e| {
- tracing::warn!("[seltz] failed to parse response: {e}");
- anyhow::anyhow!("Failed to parse Seltz response: {e}")
- })?;
-
- tracing::debug!(
- doc_count = search_resp.documents.len(),
- "[seltz] search complete"
- );
-
- let mut result =
- ToolResult::success(self.render_results_plain(&search_resp.documents, query));
- if options.prefer_markdown {
- result.markdown_formatted =
- Some(self.render_results_markdown(&search_resp.documents, query));
- }
- Ok(result)
- }
-}
-
-#[cfg(test)]
-#[path = "seltz_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/seltz_tests.rs b/crates/openhuman-core/src/search/tools/seltz_tests.rs
deleted file mode 100644
index 439f307a14..0000000000
--- a/crates/openhuman-core/src/search/tools/seltz_tests.rs
+++ /dev/null
@@ -1,193 +0,0 @@
-use super::*;
-
-fn tool() -> SeltzSearchTool {
- SeltzSearchTool::new(None, None, 5, 15)
-}
-
-fn tool_with_key() -> SeltzSearchTool {
- SeltzSearchTool::new(Some("test-key".into()), None, 5, 15)
-}
-
-#[test]
-fn test_tool_name() {
- assert_eq!(tool().name(), "seltz_search");
-}
-
-#[test]
-fn test_tool_description() {
- assert!(tool().description().contains("Seltz"));
-}
-
-#[test]
-fn test_parameters_schema() {
- let schema = tool().parameters_schema();
- assert_eq!(schema["type"], "object");
- assert!(schema["properties"]["query"].is_object());
- assert!(schema["properties"]["include_domains"].is_object());
- assert!(schema["properties"]["scope"].is_object());
-}
-
-#[test]
-fn test_render_plain_empty() {
- let result = tool().render_results_plain(&[], "test query");
- assert!(result.contains("No results found"));
-}
-
-#[test]
-fn test_render_plain_with_data() {
- let docs = vec![
- SeltzDocument {
- url: "https://example.com/a".into(),
- content: "First result content.".into(),
- title: Some("First Result".into()),
- published_date: Some("2026-01-15".into()),
- },
- SeltzDocument {
- url: "https://example.com/b".into(),
- content: "Second result content.".into(),
- title: None,
- published_date: None,
- },
- ];
-
- let result = tool().render_results_plain(&docs, "test");
- assert!(result.contains("via Seltz"));
- assert!(result.contains("First Result"));
- assert!(result.contains("https://example.com/a"));
- assert!(result.contains("Published: 2026-01-15"));
- assert!(result.contains("First result content."));
- assert!(result.contains("Untitled"));
-}
-
-#[test]
-fn test_render_plain_respects_max_results() {
- let tool = SeltzSearchTool::new(None, None, 1, 15);
- let docs = vec![
- SeltzDocument {
- url: "https://a.com".into(),
- content: "A".into(),
- title: Some("A".into()),
- published_date: None,
- },
- SeltzDocument {
- url: "https://b.com".into(),
- content: "B".into(),
- title: Some("B".into()),
- published_date: None,
- },
- ];
- let result = tool.render_results_plain(&docs, "q");
- assert!(result.contains("https://a.com"));
- assert!(!result.contains("https://b.com"));
-}
-
-#[test]
-fn test_render_plain_truncates_long_content() {
- let long_content = "x".repeat(600);
- let docs = vec![SeltzDocument {
- url: "https://t.com".into(),
- content: long_content,
- title: Some("T".into()),
- published_date: None,
- }];
- let result = tool().render_results_plain(&docs, "q");
- assert!(result.contains("..."));
- let content_line = result.lines().find(|l| l.trim().starts_with('x')).unwrap();
- assert!(content_line.trim().len() <= 503);
-}
-
-#[test]
-fn test_render_markdown_empty() {
- let result = tool().render_results_markdown(&[], "test");
- assert!(result.contains("No results"));
- // A completed empty search still carries attribution, so the timeline
- // labels the row instead of leaving it as in-progress (#5136).
- assert!(result.trim_end().ends_with("(via Seltz)"));
-}
-
-#[test]
-fn test_render_markdown_with_data() {
- let docs = vec![SeltzDocument {
- url: "https://example.com".into(),
- content: "Some content.".into(),
- title: Some("Example".into()),
- published_date: Some("2026-01-01".into()),
- }];
- let result = tool().render_results_markdown(&docs, "test");
- // The markdown renderer is what production shows, so it must carry the
- // shared `(via <Provider>)` marker on its heading line (#5136).
- assert!(result.lines().next().unwrap().ends_with("(via Seltz)"));
- assert!(result.contains("[Example](https://example.com)"));
- assert!(result.contains("Published: 2026-01-01"));
- assert!(result.contains("> Some content."));
-}
-
-#[tokio::test]
-async fn test_execute_missing_query() {
- let result = tool_with_key().execute(json!({})).await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn test_execute_empty_query() {
- let result = tool_with_key().execute(json!({"query": ""})).await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn test_execute_without_api_key() {
- let result = tool().execute(json!({"query": "test"})).await;
- assert!(result.is_err());
- assert!(result
- .unwrap_err()
- .to_string()
- .contains("no API key configured"));
-}
-
-#[tokio::test]
-async fn test_execute_posts_to_seltz_and_renders_results() {
- use axum::{extract::Json, routing::post, Router};
- use serde_json::Value;
-
- let app = Router::new().route(
- "/search",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["query"], "test query");
- Json(json!({
- "documents": [
- {
- "url": "https://example.com/result",
- "title": "Seltz Result",
- "content": "Content from Seltz search.",
- "published_date": "2026-05-01"
- }
- ]
- }))
- }),
- );
-
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- let base_url = format!("http://127.0.0.1:{}", addr.port());
-
- let tool = SeltzSearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({"query": "test query"}))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("Seltz Result"));
- assert!(result.output().contains("https://example.com/result"));
- assert!(result.output().contains("Content from Seltz search."));
-}
-
-#[test]
-fn test_max_results_clamped() {
- let tool = SeltzSearchTool::new(None, None, 100, 15);
- assert_eq!(tool.max_results, 20);
- let tool = SeltzSearchTool::new(None, None, 0, 15);
- assert_eq!(tool.max_results, 1);
-}
diff --git a/crates/openhuman-core/src/search/tools/tavily.rs b/crates/openhuman-core/src/search/tools/tavily.rs
deleted file mode 100644
index 0f378955cf..0000000000
--- a/crates/openhuman-core/src/search/tools/tavily.rs
+++ /dev/null
@@ -1,38 +0,0 @@
-//! Tavily Search + Extract integration — direct API (BYOK, not backend-proxied).
-//!
-//! **Scope**: Agent + CLI/RPC.
-//!
-//! **Endpoints**: `POST https://api.tavily.com/search`,
-//! `POST https://api.tavily.com/extract`.
-//!
-//! **Auth**: `Authorization: Bearer <api key>`.
-//!
-//! When the user selects `tavily` as their search engine and has saved their own
-//! Tavily API key, every call in this family goes straight from the desktop
-//! client to `api.tavily.com` — the OpenHuman managed backend is never
-//! involved. The managed (`engine = "managed"`) path is untouched by this module.
-
-mod client;
-mod extract_tool;
-mod search_tool;
-mod types;
-
-#[cfg(test)]
-#[path = "tavily_tests.rs"]
-mod tests;
-
-pub use extract_tool::TavilyExtractTool;
-pub use search_tool::TavilySearchTool;
-pub use types::{
- TavilyExtractResponse, TavilyExtractResult, TavilyImage, TavilyResultItem, TavilySearchResponse,
-};
-
-// Re-exported only for the test module (`super::*`), which builds real
-// `TavilyClient`s and result rows to exercise the tools' HTTP-adjacent
-// formatting directly.
-#[cfg(test)]
-pub(crate) use client::TavilyClient;
-#[cfg(test)]
-use serde_json::{json, Value};
-#[cfg(test)]
-use tinytools::{Tool, ToolCallOptions};
diff --git a/crates/openhuman-core/src/search/tools/tavily/client.rs b/crates/openhuman-core/src/search/tools/tavily/client.rs
deleted file mode 100644
index 23b0859909..0000000000
--- a/crates/openhuman-core/src/search/tools/tavily/client.rs
+++ /dev/null
@@ -1,301 +0,0 @@
-//! `TavilyClient`: HTTP plumbing and markdown-formatting for both the
-//! `/search` and `/extract` Tavily endpoints.
-
-use super::types::{
- escape_link_destination, escape_link_text, non_empty, TavilyImage, TavilyResultItem,
-};
-use serde_json::Value;
-use std::time::Duration;
-use tinytools::ToolResult;
-
-const DEFAULT_API_URL: &str = "https://api.tavily.com";
-const SEARCH_EXCERPT_MAX_CHARS: usize = 500;
-const SEARCH_RAW_CONTENT_MAX_CHARS: usize = 8_000;
-const MAX_QUERY_IMAGES: usize = 10;
-const MAX_IMAGES_PER_RESULT: usize = 3;
-
-/// Shared HTTP plumbing for the Tavily BYOK tool family. Holds the user's key and
-/// the direct `api.tavily.com` base URL (overridable in tests).
-#[derive(Clone)]
-pub(crate) struct TavilyClient {
- api_key: Option<String>,
- api_url: String,
- max_results: usize,
- pub(super) timeout_secs: u64,
-}
-
-impl TavilyClient {
- pub(crate) fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- api_key,
- api_url: api_url.unwrap_or_else(|| DEFAULT_API_URL.to_string()),
- max_results: max_results.clamp(1, 20),
- timeout_secs: timeout_secs.max(1),
- }
- }
-
- /// Build the HTTP client at call time, like `brave.rs::http_client`, so a
- /// TLS-backend failure surfaces as a tool error instead of aborting the
- /// process while a session is being constructed.
- fn http_client(&self) -> anyhow::Result<reqwest::Client> {
- crate::util::tls::tls_client_builder()
- .timeout(Duration::from_secs(self.timeout_secs))
- .connect_timeout(Duration::from_secs(10))
- .build()
- .map_err(|e| anyhow::anyhow!("failed to build Tavily HTTP client: {e}"))
- }
-
- /// Destination host for the egress descriptor, e.g. `api.tavily.com`.
- fn egress_host(&self) -> String {
- reqwest::Url::parse(&self.api_url)
- .ok()
- .and_then(|u| u.host_str().map(str::to_string))
- .unwrap_or_else(|| "api.tavily.com".to_string())
- }
-
- /// Egress descriptor for a call to Tavily. The query (or the requested URLs)
- /// is user content leaving the device, so it carries `Prompt` on top of the
- /// destination `Url` that `network_fetch` supplies.
- fn egress_descriptor(&self) -> crate::security::egress::EgressDescriptor {
- crate::security::egress::EgressDescriptor::network_fetch(self.egress_host())
- .with_data_kind(crate::security::egress::DataKind::Prompt)
- }
-
- /// Privacy epic S7 (#4441): under `LocalOnly` the search is refused before
- /// anything reaches Tavily. Returns the `[policy-blocked]` tool result to hand
- /// straight back from `execute`, or `None` when the transfer is permitted.
- pub(super) fn local_only_block(&self) -> Option<ToolResult> {
- crate::security::egress::local_only_tool_block(&self.egress_descriptor())
- .map(ToolResult::error)
- }
-
- /// The configured key, or a user-actionable error naming exactly where to
- /// set it. Surfaced verbatim on the first search attempt.
- fn key(&self) -> anyhow::Result<&str> {
- self.api_key
- .as_deref()
- .map(str::trim)
- .filter(|k| !k.is_empty())
- .ok_or_else(|| {
- anyhow::anyhow!(
- "Tavily search unavailable: no API key configured. Add your Tavily API key \
- under Connections > Search engine, set TAVILY_API_KEY or \
- OPENHUMAN_TAVILY_API_KEY, or add search.tavily.api_key to config.toml."
- )
- })
- }
-
- /// Requested result count, honouring both `max_results` and Tavily's native
- /// `max_results` spelling. An explicit per-call value is clamped to the
- /// API's own 1..=20 range rather than to the configured `max_results` --
- /// config supplies the *default* when the call omits one, and a caller may
- /// ask for more (this matches `querit.rs`).
- pub(super) fn requested_results(&self, args: &Value) -> usize {
- args.get("max_results")
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 20) as usize)
- .unwrap_or(self.max_results)
- }
-
- pub(super) async fn post(&self, path: &str, body: Value) -> anyhow::Result<Value> {
- let api_key = self.key()?;
- let client = self.http_client()?;
- let url = format!("{}/{}", self.api_url.trim_end_matches('/'), path);
- tracing::debug!(
- path,
- timeout_secs = self.timeout_secs,
- "[tavily] POST {url} (direct BYOK)"
- );
-
- // Egress spine (privacy epic S2, #4436): disclose the destination before
- // contacting Tavily. `local_only_block` has already refused the call if the
- // live policy forbids it.
- crate::security::egress::emit_external_transfer(self.egress_descriptor());
-
- let resp = client
- .post(&url)
- .bearer_auth(api_key)
- .header("Content-Type", "application/json")
- .header("Accept", "application/json")
- .json(&body)
- .send()
- .await
- .map_err(|e| {
- tracing::warn!("[tavily] request to {path} failed: {e}");
- anyhow::anyhow!("Tavily request failed: {e}")
- })?;
-
- let status = resp.status();
- if !status.is_success() {
- // Read and drop the body: Tavily echoes the query back in errors and
- // the message could reach the agent transcript.
- let body_len = resp.text().await.unwrap_or_default().len();
- tracing::warn!(status = %status, body_len, "[tavily] non-2xx response");
- if status == reqwest::StatusCode::UNAUTHORIZED
- || status == reqwest::StatusCode::FORBIDDEN
- {
- anyhow::bail!(
- "Tavily rejected the configured API key (HTTP {status}). \
- Check your Tavily API key under Connections > Search engine."
- );
- }
- anyhow::bail!("Tavily returned non-2xx status {status}");
- }
-
- resp.json().await.map_err(|e| {
- tracing::warn!("[tavily] failed to read response JSON: {e}");
- anyhow::anyhow!("Failed to read Tavily response JSON: {e}")
- })
- }
-
- pub(super) fn render_plain(
- &self,
- results: &[TavilyResultItem],
- query_images: &[TavilyImage],
- heading: &str,
- limit: usize,
- include_raw_content: bool,
- include_images: bool,
- ) -> String {
- let mut lines = if results.is_empty() {
- vec![format!("No Tavily results for: {heading} (via Tavily)")]
- } else {
- vec![format!("Search results for: {heading} (via Tavily)")]
- };
- for (i, item) in results.iter().take(limit).enumerate() {
- lines.push(format!("{}. {}", i + 1, item.display_title()));
- lines.push(format!(" {}", item.url.trim()));
- if let Some(score) = item.score {
- lines.push(format!(" Score: {score:.3}"));
- }
- if let Some(excerpt) = item.excerpt() {
- let truncated =
- crate::util::truncate_with_ellipsis(&excerpt, SEARCH_EXCERPT_MAX_CHARS);
- lines.push(format!(" {truncated}"));
- }
- if include_raw_content {
- if let Some(raw_content) = non_empty(item.raw_content.as_deref()) {
- let truncated = crate::util::truncate_with_ellipsis(
- &raw_content,
- SEARCH_RAW_CONTENT_MAX_CHARS,
- );
- lines.push(format!(" Full content:\n{truncated}"));
- }
- }
- if include_images {
- for image in item.images.iter().take(MAX_IMAGES_PER_RESULT) {
- let url = image.url().trim();
- if url.is_empty() {
- continue;
- }
- let description = image
- .description()
- .map(|value| format!(" — {value}"))
- .unwrap_or_default();
- lines.push(format!(" Image: {url}{description}"));
- }
- }
- }
- if include_images && !query_images.is_empty() {
- lines.push("Query-related images:".to_string());
- for image in query_images.iter().take(MAX_QUERY_IMAGES) {
- let url = image.url().trim();
- if url.is_empty() {
- continue;
- }
- let description = image
- .description()
- .map(|value| format!(" — {value}"))
- .unwrap_or_default();
- lines.push(format!("- {url}{description}"));
- }
- }
- lines.join("\n")
- }
-
- pub(super) fn render_markdown(
- &self,
- results: &[TavilyResultItem],
- query_images: &[TavilyImage],
- heading: &str,
- limit: usize,
- answer: Option<&str>,
- include_raw_content: bool,
- include_images: bool,
- ) -> String {
- let mut out = if results.is_empty() {
- format!("_No results for `{heading}`_ (via Tavily)\n")
- } else {
- format!("# Search results -- `{heading}` (via Tavily)\n")
- };
- if let Some(answer) = answer {
- out.push_str("\n## Answer\n\n");
- out.push_str(answer);
- out.push('\n');
- }
- for item in results.iter().take(limit) {
- out.push_str(&format!(
- "\n## [{}]({})\n",
- escape_link_text(item.display_title()),
- escape_link_destination(&item.url)
- ));
- if let Some(excerpt) = item.excerpt() {
- let truncated =
- crate::util::truncate_with_suffix(&excerpt, SEARCH_EXCERPT_MAX_CHARS, "...");
- out.push_str(&format!("> {truncated}\n"));
- }
- if include_raw_content {
- if let Some(raw_content) = non_empty(item.raw_content.as_deref()) {
- let truncated = crate::util::truncate_with_suffix(
- &raw_content,
- SEARCH_RAW_CONTENT_MAX_CHARS,
- "...",
- );
- out.push_str("\n### Full content\n\n");
- out.push_str(&truncated);
- out.push('\n');
- }
- }
- if include_images {
- for image in item.images.iter().take(MAX_IMAGES_PER_RESULT) {
- let url = image.url().trim();
- if url.is_empty() {
- continue;
- }
- let description = image
- .description()
- .map(|value| format!(" — {value}"))
- .unwrap_or_default();
- out.push_str(&format!(
- "\n[Image]({}){description}\n",
- escape_link_destination(url)
- ));
- }
- }
- }
- if include_images && !query_images.is_empty() {
- out.push_str("\n## Query-related images\n");
- for image in query_images.iter().take(MAX_QUERY_IMAGES) {
- let url = image.url().trim();
- if url.is_empty() {
- continue;
- }
- let description = image
- .description()
- .map(|value| format!(" — {value}"))
- .unwrap_or_default();
- out.push_str(&format!(
- "\n- [Image]({}){description}",
- escape_link_destination(url)
- ));
- }
- out.push('\n');
- }
- out
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/tavily/extract_tool.rs b/crates/openhuman-core/src/search/tools/tavily/extract_tool.rs
deleted file mode 100644
index 83377d2e92..0000000000
--- a/crates/openhuman-core/src/search/tools/tavily/extract_tool.rs
+++ /dev/null
@@ -1,203 +0,0 @@
-//! `TavilyExtractTool`: full page content retrieval via `POST /extract`.
-
-use super::client::TavilyClient;
-use super::types::{copy_string, non_empty, TavilyExtractResponse, TavilyExtractResult};
-use crate::search::tools::tavily::types::escape_link_destination;
-use crate::search::tools::tavily::types::escape_link_text;
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-/// Retrieve full page contents for a list of URLs (`POST /extract`).
-pub struct TavilyExtractTool {
- pub(super) client: TavilyClient,
-}
-
-impl TavilyExtractTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- // Extraction transfers the full cleaned page, which can be hundreds of
- // kilobytes or more over a slow link, while search only moves small
- // excerpts. A hot folder of small search responses needs 15s; a single
- // large page commonly does not. Tavily itself allows up to 60s per
- // request, so the extract budget must never be smaller than that cap —
- // otherwise a large page dies to `operation timed out` after the server
- // already answered 200.
- Self {
- client: TavilyClient::new(api_key, api_url, max_results, timeout_secs.max(60)),
- }
- }
-
- /// Accept either a `urls` array or a single `url` string, so the agent can
- /// call this the obvious way for the one-document case.
- pub(crate) fn collect_urls(args: &Value) -> anyhow::Result<Vec<String>> {
- let urls: Vec<String> = match args.get("urls") {
- Some(Value::Array(items)) => items
- .iter()
- .filter_map(|v| non_empty(v.as_str()))
- .collect::<Vec<_>>(),
- Some(Value::String(single)) => non_empty(Some(single)).into_iter().collect(),
- _ => non_empty(args.get("url").and_then(Value::as_str))
- .into_iter()
- .collect(),
- };
- if urls.is_empty() {
- anyhow::bail!("Missing required parameter: urls (a non-empty list of page URLs)");
- }
- if urls.len() > 20 {
- anyhow::bail!(
- "Tavily extract accepts at most 20 URLs per call (got {})",
- urls.len()
- );
- }
- Ok(urls)
- }
-
- fn render_plain(&self, results: &[TavilyExtractResult]) -> String {
- if results.is_empty() {
- return "No Tavily extraction results.".to_string();
- }
- let mut lines = Vec::new();
- for (i, item) in results.iter().enumerate() {
- lines.push(format!("{}. {}", i + 1, item.url.trim()));
- match non_empty(item.raw_content.as_deref()) {
- Some(content) => {
- let truncated = crate::util::truncate_with_ellipsis(&content, 8_000);
- lines.push(format!(" {truncated}"));
- }
- None => lines.push(" (no content extracted)".to_string()),
- }
- }
- lines.join("\n")
- }
-
- fn render_markdown(&self, results: &[TavilyExtractResult]) -> String {
- if results.is_empty() {
- return "_No Tavily extraction results._".to_string();
- }
- let mut out = String::from("# Tavily extraction\n");
- for item in results {
- out.push_str(&format!(
- "\n## [{}]({})\n",
- escape_link_text(item.url.trim()),
- escape_link_destination(&item.url)
- ));
- match non_empty(item.raw_content.as_deref()) {
- Some(content) => {
- let truncated = crate::util::truncate_with_suffix(&content, 8_000, "...");
- out.push_str(&truncated);
- out.push('\n');
- }
- None => out.push_str("_No content extracted._\n"),
- }
- }
- out
- }
-}
-
-#[async_trait]
-impl Tool for TavilyExtractTool {
- fn name(&self) -> &str {
- "tavily_extract"
- }
-
- fn description(&self) -> &str {
- "Extract cleaned content from one or more web pages using Tavily. Returns \
- markdown or plain text, bounded to 8,000 characters per URL."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "urls": {
- "type": "array",
- "items": { "type": "string" },
- "minItems": 1,
- "maxItems": 20,
- "description": "The page URLs to extract content from (up to 20)."
- },
- "format": {
- "type": "string",
- "enum": ["markdown", "text"],
- "description": "Format of the extracted content. Defaults to markdown."
- },
- "extract_depth": {
- "type": "string",
- "enum": ["basic", "advanced"],
- "description": "basic is faster and cheaper; advanced also captures tables and embedded content."
- }
- },
- "required": ["urls"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- if let Some(blocked) = self.client.local_only_block() {
- return Ok(blocked);
- }
-
- let urls = Self::collect_urls(&args)?;
-
- let mut body = json!({
- "urls": urls,
- "format": "markdown",
- });
- copy_string(&args, "format", &mut body);
- copy_string(&args, "extract_depth", &mut body);
-
- let value = self.client.post("extract", body).await?;
- let parsed: TavilyExtractResponse = serde_json::from_value(value).map_err(|e| {
- tracing::warn!("[tavily] failed to parse extract response: {e}");
- anyhow::anyhow!("Failed to parse Tavily extract response: {e}")
- })?;
-
- tracing::debug!(result_count = parsed.results.len(), "[tavily] extract ok");
-
- let failed = parsed.failed_results.len();
- if failed > 0 {
- tracing::warn!(failed, "[tavily] extraction failures");
- }
- if parsed.results.is_empty() && failed > 0 {
- return Ok(ToolResult::error(format!(
- "Tavily could not extract any of the requested URLs ({failed} failed)."
- )));
- }
-
- let plain = self.render_plain(&parsed.results);
- let mut markdown = self.render_markdown(&parsed.results);
- let output = if failed == 0 {
- plain
- } else {
- // Report failures as a trailing line without echoing the remote
- // error verbatim into the transcript.
- markdown.push_str(&format!(
- "\n> {failed} URL(s) could not be extracted by Tavily.\n"
- ));
- format!("{plain}\n\n({failed} URL(s) could not be extracted by Tavily)")
- };
-
- let mut result = ToolResult::success(output);
- if options.prefer_markdown {
- result.markdown_formatted = Some(markdown);
- }
- Ok(result)
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/tavily/search_tool.rs b/crates/openhuman-core/src/search/tools/tavily/search_tool.rs
deleted file mode 100644
index 2b474216d0..0000000000
--- a/crates/openhuman-core/src/search/tools/tavily/search_tool.rs
+++ /dev/null
@@ -1,241 +0,0 @@
-//! `TavilySearchTool`: web / news / finance search via `POST /search`.
-
-use super::client::TavilyClient;
-use super::types::{copy_bool, copy_domain_filter, copy_string, non_empty, TavilySearchResponse};
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-/// Web / news / finance search via the Tavily API (`POST /search`).
-pub struct TavilySearchTool {
- tool_name: &'static str,
- client: TavilyClient,
-}
-
-impl TavilySearchTool {
- pub fn new(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- tool_name: "tavily_search",
- client: TavilyClient::new(api_key, api_url, max_results, timeout_secs),
- }
- }
-
- /// Same tool under the canonical `web_search_tool` slot, so selecting Tavily
- /// satisfies the agent's generic "search the web" affordance.
- pub fn new_web_search_tool(
- api_key: Option<String>,
- api_url: Option<String>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- tool_name: "web_search_tool",
- client: TavilyClient::new(api_key, api_url, max_results, timeout_secs),
- }
- }
-
- pub(crate) fn build_body(&self, args: &Value, query: &str) -> Value {
- let mut body = json!({
- "query": query,
- "max_results": self.client.requested_results(args),
- });
- copy_string(args, "search_depth", &mut body);
- copy_string(args, "topic", &mut body);
- copy_string(args, "time_range", &mut body);
- copy_string(args, "start_date", &mut body);
- copy_string(args, "end_date", &mut body);
- copy_bool(args, "include_answer", &mut body);
- copy_bool(args, "include_raw_content", &mut body);
- copy_bool(args, "include_images", &mut body);
- copy_domain_filter(args, "include_domains", &mut body);
- copy_domain_filter(args, "exclude_domains", &mut body);
- body
- }
-}
-
-#[async_trait]
-impl Tool for TavilySearchTool {
- fn name(&self) -> &str {
- self.tool_name
- }
-
- fn description(&self) -> &str {
- "Search the web with Tavily. Returns ranked pages with URLs, titles, and \
- snippets. Supports general, news, and finance topics; search-depth levels; \
- a publish/update time range or explicit start/end dates; domain include/ \
- exclude filters; and an optional LLM-generated answer, cleaned page content, \
- or image links."
- }
-
- fn parameters_schema(&self) -> Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "The search query. Write it in the language you want results in."
- },
- "max_results": {
- "type": "integer",
- "description": "Maximum number of results to return (default from config, max 20)."
- },
- "search_depth": {
- "type": "string",
- "enum": ["basic", "advanced", "fast", "ultra-fast"],
- "description": "Latency vs. relevance tradeoff. Advanced costs more and gives higher-relevance results; ultra-fast is the quickest."
- },
- "topic": {
- "type": "string",
- "enum": ["general", "news", "finance"],
- "description": "Category of the search. Use 'news' for real-time coverage, 'finance' for financial data."
- },
- "time_range": {
- "type": "string",
- "enum": ["day", "week", "month", "year"],
- "description": "Only results published or updated within this period back from today. Alternative to start_date/end_date."
- },
- "start_date": {
- "type": "string",
- "description": "Only results published/updated on or after this YYYY-MM-DD date."
- },
- "end_date": {
- "type": "string",
- "description": "Only results published/updated on or before this YYYY-MM-DD date."
- },
- "include_answer": {
- "type": "boolean",
- "description": "Also return an LLM-generated concise answer to the query."
- },
- "include_raw_content": {
- "type": "boolean",
- "description": "Also return cleaned page content for each result, bounded by OpenHuman to protect the agent context (larger responses)."
- },
- "include_images": {
- "type": "boolean",
- "description": "Also return query-related images in the response."
- },
- "include_domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Only return results from these domains."
- },
- "exclude_domains": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Exclude results from these domains."
- }
- },
- "required": ["query"]
- })
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute(&self, args: Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- async fn execute_with_options(
- &self,
- args: Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- if let Some(blocked) = self.client.local_only_block() {
- return Ok(blocked);
- }
-
- let query = non_empty(args.get("query").and_then(Value::as_str))
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;
-
- let limit = self.client.requested_results(&args);
- let body = self.build_body(&args, &query);
- let value = self.client.post("search", body).await?;
- let parsed: TavilySearchResponse = serde_json::from_value(value).map_err(|e| {
- tracing::warn!("[tavily] failed to parse search response: {e}");
- anyhow::anyhow!("Failed to parse Tavily search response: {e}")
- })?;
-
- tracing::debug!(result_count = parsed.results.len(), "[tavily] search ok");
-
- // A Tavily-generated answer is the provider's own synthesis of the
- // results; surface it when requested so the agent does not re-answer
- // from the scraps. Gate on the requested flag — the response can carry
- // an answer the agent never asked for.
- let include_answer = args
- .get("include_answer")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let answer = if include_answer {
- non_empty(parsed.answer.as_deref())
- } else {
- None
- };
- let include_raw_content = args
- .get("include_raw_content")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let include_images = args
- .get("include_images")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- let plain = self.client.render_plain(
- &parsed.results,
- &parsed.images,
- &query,
- limit,
- include_raw_content,
- include_images,
- );
- let markdown = self.client.render_markdown(
- &parsed.results,
- &parsed.images,
- &query,
- limit,
- answer.as_deref(),
- include_raw_content,
- include_images,
- );
- let output = match answer {
- Some(answer) => format!("Answer: {answer}\n\n{plain}"),
- None => plain,
- };
-
- let mut result = ToolResult::success(output);
- if options.prefer_markdown {
- result.markdown_formatted = Some(markdown);
- }
- // Host-only structured payload for the chat UI's tool-call
- // presentation — never rendered to the model, so the plain/markdown
- // text above (and the cache key that depends on it) is unaffected.
- let structured_results: Vec<crate::search::tools::WebSearchResultRef<'_>> = parsed
- .results
- .iter()
- .map(|r| crate::search::tools::WebSearchResultRef {
- title: r
- .title
- .as_deref()
- .map(str::trim)
- .filter(|t| !t.is_empty())
- .unwrap_or("Untitled"),
- url: r.url.as_str(),
- published: None,
- excerpt: r.content.as_deref(),
- })
- .collect();
- result.metadata = Some(crate::search::tools::web_search_metadata(
- &query,
- "Tavily",
- &structured_results,
- limit,
- ));
- Ok(result)
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/tavily/types.rs b/crates/openhuman-core/src/search/tools/tavily/types.rs
deleted file mode 100644
index 95b7c96070..0000000000
--- a/crates/openhuman-core/src/search/tools/tavily/types.rs
+++ /dev/null
@@ -1,164 +0,0 @@
-//! Tavily wire types (search/extract responses) and small string-formatting
-//! helpers shared by the client and both tools.
-
-use serde::{Deserialize, Serialize};
-use serde_json::{json, Value};
-
-const IMAGE_DESCRIPTION_MAX_CHARS: usize = 300;
-
-/// Tavily may return image entries as a bare URL or as an object with an
-/// optional description, depending on the endpoint options and API version.
-#[derive(Debug, Clone, Deserialize, Serialize)]
-#[serde(untagged)]
-pub enum TavilyImage {
- Url(String),
- Detailed {
- #[serde(default)]
- url: String,
- #[serde(default)]
- description: Option<String>,
- },
-}
-
-impl TavilyImage {
- pub(super) fn url(&self) -> &str {
- match self {
- Self::Url(url) | Self::Detailed { url, .. } => url,
- }
- }
-
- pub(super) fn description(&self) -> Option<String> {
- let description = match self {
- Self::Url(_) => None,
- Self::Detailed { description, .. } => non_empty(description.as_deref()),
- }?;
- let single_line = description.replace(['\r', '\n'], " ");
- Some(crate::util::truncate_with_ellipsis(
- &single_line,
- IMAGE_DESCRIPTION_MAX_CHARS,
- ))
- }
-}
-
-/// One Tavily search result, shared by `/search`.
-#[derive(Debug, Clone, Default, Deserialize, Serialize)]
-pub struct TavilyResultItem {
- #[serde(default)]
- pub title: Option<String>,
- #[serde(default)]
- pub url: String,
- #[serde(default)]
- pub content: Option<String>,
- #[serde(default)]
- pub score: Option<f64>,
- #[serde(default, rename = "raw_content")]
- pub raw_content: Option<String>,
- #[serde(default)]
- pub images: Vec<TavilyImage>,
-}
-
-impl TavilyResultItem {
- /// Best available excerpt: the chunked `content` first, then the full
- /// cleaned page (`raw_content`), only present when `include_raw_content`
- /// was requested.
- pub(super) fn excerpt(&self) -> Option<String> {
- non_empty(self.content.as_deref()).or_else(|| non_empty(self.raw_content.as_deref()))
- }
-
- pub(super) fn display_title(&self) -> &str {
- self.title
- .as_deref()
- .map(str::trim)
- .filter(|t| !t.is_empty())
- .unwrap_or("Untitled")
- }
-}
-
-#[derive(Debug, Default, Deserialize, Serialize)]
-pub struct TavilySearchResponse {
- #[serde(default)]
- pub query: Option<String>,
- #[serde(default)]
- pub answer: Option<String>,
- #[serde(default)]
- pub images: Vec<TavilyImage>,
- #[serde(default)]
- pub results: Vec<TavilyResultItem>,
-}
-
-/// One URL's extracted content from `/extract`.
-#[derive(Debug, Clone, Default, Deserialize, Serialize)]
-pub struct TavilyExtractResult {
- #[serde(default)]
- pub url: String,
- #[serde(default, rename = "raw_content")]
- pub raw_content: Option<String>,
-}
-
-#[derive(Debug, Default, Deserialize, Serialize)]
-pub struct TavilyExtractResponse {
- #[serde(default)]
- pub results: Vec<TavilyExtractResult>,
- #[serde(default, rename = "failed_results")]
- pub failed_results: Vec<TavilyExtractFailure>,
-}
-
-/// A URL Tavily could not process. Errors are rendered but never attributed to
-/// a template — the `error` string is remote-controlled and must not be trusted.
-#[derive(Debug, Default, Deserialize, Serialize)]
-pub struct TavilyExtractFailure {
- #[serde(default)]
- pub url: Option<String>,
- #[serde(default)]
- pub error: Option<String>,
-}
-
-pub(super) fn non_empty(value: Option<&str>) -> Option<String> {
- value
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
-}
-
-/// Escape a remote page title for use as a markdown link label. Titles are
-/// attacker-controlled, and an unescaped `[`/`]` breaks out of the link and
-/// lets a crafted page inject markdown into the agent transcript.
-pub(super) fn escape_link_text(raw: &str) -> String {
- raw.replace('\\', r"\\")
- .replace('[', r"\[")
- .replace(']', r"\]")
-}
-
-/// Render a URL as a markdown link destination. Bare parentheses (common in
-/// Wikipedia URLs) terminate the destination early, so wrap in angle brackets
-/// and drop the characters that would close them.
-pub(super) fn escape_link_destination(raw: &str) -> String {
- let cleaned: String = raw
- .trim()
- .chars()
- .filter(|c| !matches!(c, '<' | '>' | ' '))
- .collect();
- format!("<{cleaned}>")
-}
-
-/// Copy a string array argument onto the Tavily request body.
-pub(super) fn copy_domain_filter(args: &Value, from: &str, body: &mut Value) {
- if let Some(list) = args.get(from).filter(|v| v.is_array()) {
- body[from] = list.clone();
- }
-}
-
-/// Copy an optional string argument onto the Tavily request body under the
-/// same (already snake_case) key.
-pub(super) fn copy_string(args: &Value, key: &str, body: &mut Value) {
- if let Some(value) = non_empty(args.get(key).and_then(Value::as_str)) {
- body[key] = json!(value);
- }
-}
-
-/// Copy an optional boolean argument onto the Tavily request body.
-pub(super) fn copy_bool(args: &Value, key: &str, body: &mut Value) {
- if let Some(value) = args.get(key).and_then(Value::as_bool) {
- body[key] = json!(value);
- }
-}
diff --git a/crates/openhuman-core/src/search/tools/tavily_tests.rs b/crates/openhuman-core/src/search/tools/tavily_tests.rs
deleted file mode 100644
index 3672c0863c..0000000000
--- a/crates/openhuman-core/src/search/tools/tavily_tests.rs
+++ /dev/null
@@ -1,640 +0,0 @@
-//! Tests for the Tavily BYOK search + extract tool family.
-
-use super::*;
-use axum::{extract::Json, http::StatusCode, routing::post, Router};
-
-fn search_tool() -> TavilySearchTool {
- TavilySearchTool::new(None, None, 5, 15)
-}
-
-fn search_tool_with_key() -> TavilySearchTool {
- TavilySearchTool::new(Some("test-key".into()), None, 5, 15)
-}
-
-/// Spawn a local stand-in for `api.tavily.com` and return its base URL.
-async fn spawn(app: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- format!("http://127.0.0.1:{}", addr.port())
-}
-
-fn one_result_payload() -> Value {
- json!({
- "query": "tavily byok",
- "answer": "A concise answer to the query.",
- "results": [
- {
- "title": "Tavily Result",
- "url": "https://example.com/a",
- "content": "Snippet content from Tavily.",
- "score": 0.42,
- "raw_content": null
- }
- ],
- "response_time": "0.7"
- })
-}
-
-#[test]
-fn tool_names_match_the_documented_byok_surface() {
- assert_eq!(search_tool().name(), "tavily_search");
- assert_eq!(
- TavilySearchTool::new_web_search_tool(None, None, 5, 15).name(),
- "web_search_tool"
- );
- assert_eq!(
- TavilyExtractTool::new(None, None, 5, 15).name(),
- "tavily_extract"
- );
-}
-
-#[test]
-fn search_schema_exposes_the_tavily_filters() {
- let schema = search_tool().parameters_schema();
- assert_eq!(schema["type"], "object");
- assert!(schema["properties"]["query"].is_object());
- assert!(schema["properties"]["search_depth"].is_object());
- assert!(schema["properties"]["topic"].is_object());
- assert!(schema["properties"]["time_range"].is_object());
- assert!(schema["properties"]["include_answer"].is_object());
- assert!(schema["properties"]["include_domains"].is_object());
- assert!(schema["properties"]["exclude_domains"].is_object());
- assert_eq!(schema["required"][0], "query");
-}
-
-#[test]
-fn search_depth_enum_matches_tavily_documented_levels() {
- let schema = search_tool().parameters_schema();
- let levels = schema["properties"]["search_depth"]["enum"]
- .as_array()
- .expect("search_depth enum")
- .iter()
- .map(|v| v.as_str().unwrap().to_string())
- .collect::<Vec<_>>();
-
- assert_eq!(levels, vec!["basic", "advanced", "fast", "ultra-fast"]);
-}
-
-#[test]
-fn topic_enum_matches_tavily_documented_topics() {
- let schema = search_tool().parameters_schema();
- let topics = schema["properties"]["topic"]["enum"]
- .as_array()
- .expect("topic enum")
- .iter()
- .map(|v| v.as_str().unwrap().to_string())
- .collect::<Vec<_>>();
-
- assert_eq!(topics, vec!["general", "news", "finance"]);
-}
-
-#[test]
-fn search_body_maps_snake_case_args_to_tavily_params() {
- let tool = search_tool_with_key();
- let body = tool.build_body(
- &json!({
- "max_results": 3,
- "search_depth": "advanced",
- "topic": "news",
- "time_range": "week",
- "include_answer": true,
- "include_raw_content": true,
- "include_images": true,
- "include_domains": ["reuters.com"],
- "exclude_domains": ["spam.test"]
- }),
- "election updates",
- );
-
- assert_eq!(body["query"], "election updates");
- assert_eq!(body["max_results"], 3);
- assert_eq!(body["search_depth"], "advanced");
- assert_eq!(body["topic"], "news");
- assert_eq!(body["time_range"], "week");
- assert_eq!(body["include_answer"], true);
- assert_eq!(body["include_raw_content"], true);
- assert_eq!(body["include_images"], true);
- assert_eq!(body["include_domains"][0], "reuters.com");
- assert_eq!(body["exclude_domains"][0], "spam.test");
-}
-
-#[test]
-fn search_body_supports_start_and_end_dates_instead_of_time_range() {
- let body = search_tool_with_key().build_body(
- &json!({
- "start_date": "2026-01-01",
- "end_date": "2026-06-30"
- }),
- "archive piece",
- );
-
- assert_eq!(body["start_date"], "2026-01-01");
- assert_eq!(body["end_date"], "2026-06-30");
- assert!(body.get("time_range").is_none());
-}
-
-#[test]
-fn search_body_omits_unrequested_optional_params() {
- let body = search_tool_with_key().build_body(&json!({}), "plain query");
- assert_eq!(body["query"], "plain query");
- assert_eq!(body["max_results"], 5);
- assert!(body.get("topic").is_none());
- assert!(body.get("include_answer").is_none());
- assert!(body.get("include_domains").is_none());
-}
-
-#[test]
-fn web_search_tool_slot_shares_the_full_tavily_body() {
- // The canonical `web_search_tool` slot is the same tool under a different
- // name (mirrors `exa_search` -> `web_search_tool`), so the full argument
- // surface stays available to the agent on the generic affordance too.
- let tool = TavilySearchTool::new_web_search_tool(Some("test-key".into()), None, 5, 15);
- let body = tool.build_body(
- &json!({
- "topic": "news",
- "search_depth": "advanced",
- "max_results": 7
- }),
- "generic query",
- );
-
- assert_eq!(body["query"], "generic query");
- assert_eq!(body["max_results"], 7);
- assert_eq!(body["topic"], "news");
- assert_eq!(body["search_depth"], "advanced");
-}
-
-#[test]
-fn excerpt_prefers_content_then_raw_content() {
- let mut item = TavilyResultItem {
- raw_content: Some("full raw".into()),
- ..Default::default()
- };
- assert_eq!(item.excerpt().as_deref(), Some("full raw"));
-
- item.content = Some("chunk snippet".into());
- assert_eq!(item.excerpt().as_deref(), Some("chunk snippet"));
-}
-
-#[test]
-fn extract_accepts_a_urls_array_a_bare_string_or_a_single_url() {
- assert_eq!(
- TavilyExtractTool::collect_urls(
- &json!({"urls": ["https://a.test", " ", "https://b.test"]})
- )
- .unwrap(),
- vec!["https://a.test".to_string(), "https://b.test".to_string()]
- );
- assert_eq!(
- TavilyExtractTool::collect_urls(&json!({"urls": "https://a.test"})).unwrap(),
- vec!["https://a.test".to_string()]
- );
- assert_eq!(
- TavilyExtractTool::collect_urls(&json!({"url": "https://a.test"})).unwrap(),
- vec!["https://a.test".to_string()]
- );
- assert!(TavilyExtractTool::collect_urls(&json!({"urls": []})).is_err());
-}
-
-#[test]
-fn extract_rejects_a_batch_over_twenty_urls() {
- let urls: Vec<String> = (0..25)
- .map(|i| format!("https://example.com/{i}"))
- .collect();
- let error = TavilyExtractTool::collect_urls(&json!({ "urls": urls }))
- .expect_err("over-limit batches must not be silently truncated");
-
- assert!(error.to_string().contains("at most 20 URLs"));
-}
-
-#[test]
-fn extract_never_uses_a_sub_minute_http_timeout() {
- // Extraction transfers the full cleaned page, which can exceed a small
- // search-facing timeout by orders of magnitude. A config value of a few
- // seconds must not make `tavily_extract` fail on a large page after the
- // server already answered 200 (`operation timed out` while reading the
- // body). The tool floors its request budget at Tavily's own 60s cap.
- let tool = TavilyExtractTool::new(Some("test-key".into()), None, 5, 15);
- assert_eq!(tool.client.timeout_secs, 60);
-
- let tool = TavilyExtractTool::new(Some("test-key".into()), None, 5, 90);
- assert_eq!(tool.client.timeout_secs, 90);
-}
-
-#[tokio::test]
-async fn search_without_a_key_reports_where_to_set_one() {
- let err = search_tool()
- .execute(json!({"query": "test"}))
- .await
- .expect_err("missing key must fail");
- let message = err.to_string();
-
- assert!(message.contains("no API key configured"));
- assert!(message.contains("Connections > Search engine"));
-}
-
-#[tokio::test]
-async fn search_requires_a_query() {
- assert!(search_tool_with_key().execute(json!({})).await.is_err());
-}
-
-#[tokio::test]
-async fn search_posts_directly_to_tavily_with_bearer_auth_and_renders_results() {
- let app = Router::new().route(
- "/search",
- post(
- |headers: axum::http::HeaderMap, Json(body): Json<Value>| async move {
- let auth = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .unwrap_or_default();
- assert_eq!(auth, "Bearer test-key");
- assert_eq!(body["query"], "tavily byok");
- assert_eq!(body["max_results"], 3);
- assert_eq!(body["include_domains"][0], "example.com");
- Json(one_result_payload())
- },
- ),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({
- "query": "tavily byok",
- "max_results": 3,
- "include_domains": ["example.com"]
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("via Tavily"));
- assert!(result.output().contains("Tavily Result"));
- assert!(result.output().contains("https://example.com/a"));
- assert!(result.output().contains("Snippet content from Tavily."));
-}
-
-#[tokio::test]
-async fn search_surfaces_the_tavily_generated_answer_when_requested() {
- let app = Router::new().route(
- "/search",
- post(|Json(_): Json<Value>| async move { Json(one_result_payload()) }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute_with_options(
- json!({"query": "tavily byok", "include_answer": true}),
- ToolCallOptions {
- prefer_markdown: true,
- },
- )
- .await
- .expect("execute() should succeed");
-
- let production_output = result.output_for_llm(true);
- assert!(production_output.contains("## Answer"));
- assert!(production_output.contains("A concise answer to the query."));
- assert!(production_output
- .lines()
- .next()
- .unwrap_or_default()
- .ends_with("(via Tavily)"));
-}
-
-#[tokio::test]
-async fn search_drops_an_answer_the_agent_did_not_request() {
- // `one_result_payload()` always carries an `answer`; the gate must keep it
- // out of the output unless `include_answer` was requested.
- let app = Router::new().route(
- "/search",
- post(|Json(_): Json<Value>| async move { Json(one_result_payload()) }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute_with_options(
- json!({"query": "tavily byok"}),
- ToolCallOptions {
- prefer_markdown: true,
- },
- )
- .await
- .expect("execute() should succeed");
-
- let production_output = result.output_for_llm(true);
- assert!(!production_output.contains("## Answer"));
- assert!(!production_output.contains("A concise answer to the query."));
-}
-
-#[tokio::test]
-async fn search_surfaces_requested_raw_content_and_images_in_markdown() {
- let app = Router::new().route(
- "/search",
- post(|Json(_): Json<Value>| async move {
- Json(json!({
- "query": "rich result",
- "images": [{
- "url": "https://images.example.com/query.png",
- "description": "Query overview"
- }],
- "results": [{
- "title": "Rich result",
- "url": "https://example.com/rich",
- "content": "Short snippet.",
- "raw_content": "Full cleaned page content that must not be shadowed by the snippet.",
- "images": ["https://images.example.com/result.png"]
- }]
- }))
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute_with_options(
- json!({
- "query": "rich result",
- "include_raw_content": true,
- "include_images": true
- }),
- ToolCallOptions {
- prefer_markdown: true,
- },
- )
- .await
- .expect("execute() should succeed");
-
- let production_output = result.output_for_llm(true);
- assert!(production_output.contains("### Full content"));
- assert!(production_output.contains("Full cleaned page content"));
- assert!(production_output.contains("https://images.example.com/query.png"));
- assert!(production_output.contains("https://images.example.com/result.png"));
-}
-
-#[tokio::test]
-async fn extract_posts_urls_and_renders_the_cleaned_content() {
- let app = Router::new().route(
- "/extract",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["urls"][0], "https://example.com/a");
- assert_eq!(body["format"], "markdown");
- assert_eq!(body["extract_depth"], "advanced");
- Json(json!({
- "results": [{
- "url": "https://example.com/a",
- "raw_content": "Full cleaned page text."
- }],
- "failed_results": [],
- "response_time": 1.2
- }))
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilyExtractTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute(json!({
- "urls": ["https://example.com/a"],
- "format": "markdown",
- "extract_depth": "advanced"
- }))
- .await
- .expect("execute() should succeed");
-
- assert!(result.output().contains("https://example.com/a"));
- assert!(result.output().contains("Full cleaned page text."));
-}
-
-#[tokio::test]
-async fn extract_marks_a_complete_failure_as_an_error_without_echoing_remote_details() {
- let app = Router::new().route(
- "/extract",
- post(|Json(_): Json<Value>| async move {
- Json(json!({
- "results": [],
- "failed_results": [{
- "url": "https://example.com/blocked",
- "error": "403 sensitive upstream detail"
- }],
- "response_time": 0.4
- }))
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilyExtractTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute_with_options(
- json!({"urls": ["https://example.com/blocked"]}),
- ToolCallOptions {
- prefer_markdown: true,
- },
- )
- .await
- .expect("execute() should succeed");
-
- assert!(
- result.is_error,
- "a response with no extracted URLs must fail"
- );
- let production_output = result.output_for_llm(true);
- assert!(production_output.contains("could not extract any of the requested URLs"));
- assert!(
- !production_output.contains("403 sensitive upstream detail"),
- "the remote error string must not reach the transcript"
- );
-}
-
-#[tokio::test]
-async fn extract_keeps_partial_results_successful_and_reports_the_failed_count() {
- let app = Router::new().route(
- "/extract",
- post(|Json(_): Json<Value>| async move {
- Json(json!({
- "results": [{
- "url": "https://example.com/ok",
- "raw_content": "Extracted page content."
- }],
- "failed_results": [{
- "url": "https://example.com/blocked",
- "error": "403 sensitive upstream detail"
- }]
- }))
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilyExtractTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute_with_options(
- json!({"urls": ["https://example.com/ok", "https://example.com/blocked"]}),
- ToolCallOptions {
- prefer_markdown: true,
- },
- )
- .await
- .expect("partial extraction should return a tool result");
-
- assert!(
- !result.is_error,
- "one extracted URL makes this a partial success"
- );
- let production_output = result.output_for_llm(true);
- assert!(production_output.contains("Extracted page content."));
- assert!(production_output.contains("1 URL(s) could not be extracted"));
- assert!(
- !production_output.contains("403 sensitive upstream detail"),
- "the remote error string must not reach the transcript"
- );
-}
-
-#[tokio::test]
-async fn unauthorized_status_names_the_key_without_leaking_the_body() {
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::UNAUTHORIZED,
- "secret query context should stay private",
- )
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("bad-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("401 must fail");
- let message = err.to_string();
-
- assert!(message.contains("Tavily rejected the configured API key"));
- assert!(message.contains("Connections > Search engine"));
- assert!(!message.contains("secret query context"));
-}
-
-#[tokio::test]
-async fn non_success_status_does_not_expose_the_response_body() {
- let app = Router::new().route(
- "/search",
- post(|| async {
- (
- StatusCode::BAD_REQUEST,
- "sensitive query context should stay private",
- )
- }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let err = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("non-2xx responses should fail");
- let message = err.to_string();
-
- assert!(message.contains("Tavily returned non-2xx status 400 Bad Request"));
- assert!(!message.contains("sensitive query context"));
-}
-
-/// Privacy epic S7 (#4441): `LocalOnly` must refuse every Tavily call before any
-/// query or URL reaches api.tavily.com. The base URL points at a port nothing is
-/// listening on, so a request escaping the guard fails the test rather than
-/// silently passing.
-fn local_only() -> crate::security::live_policy::TestPrivacyGuard {
- crate::security::live_policy::test_privacy_scope(crate::config::PrivacyMode::LocalOnly)
-}
-
-#[tokio::test]
-async fn search_is_refused_under_local_only_privacy_mode() {
- let _mode = local_only();
- let tool = TavilySearchTool::new(
- Some("test-key".into()),
- Some("http://127.0.0.1:1".into()),
- 5,
- 15,
- );
-
- let result = tool
- .execute(json!({"query": "private search"}))
- .await
- .expect("the block is a tool error, not a transport failure");
-
- assert!(result.is_error);
- assert!(
- result.output().contains("[policy-blocked]"),
- "got: {}",
- result.output()
- );
- assert!(
- !result.output().contains("private search"),
- "the block message must not echo the query: {}",
- result.output()
- );
-}
-
-#[tokio::test]
-async fn extract_is_refused_under_local_only() {
- let _mode = local_only();
- let tool = TavilyExtractTool::new(Some("k".into()), Some("http://127.0.0.1:1".into()), 5, 15);
-
- let result = tool
- .execute(json!({"urls": ["https://example.com/a"]}))
- .await
- .expect("blocked, not failed");
- assert!(result.is_error);
- assert!(result.output().contains("[policy-blocked]"));
-}
-
-#[test]
-fn markdown_rendering_neutralizes_hostile_titles_and_urls() {
- // Title and URL are remote, attacker-controlled. An unescaped `]` would
- // close the link label and let a crafted page inject markdown into the
- // agent transcript.
- let client = TavilyClient::new(Some("k".into()), None, 5, 15);
- let results = vec![TavilyResultItem {
- url: "https://example.com/a_(b)".into(),
- title: Some("Pwned](https://evil.test) [click".into()),
- ..Default::default()
- }];
-
- let out = client.render_markdown(&results, &[], "q", 5, None, false, false);
-
- // The hostile `]` is escaped, so the label never closes early and the
- // injected `(https://evil.test)` cannot become a link destination. Bare
- // parens need no escaping inside a label.
- assert!(!out.contains("[Pwned](https://evil.test)"));
- assert!(out.contains(r"[Pwned\](https://evil.test) \[click]"));
- // Parenthesised URLs survive intact inside an angle-bracket destination.
- assert!(out.contains("(<https://example.com/a_(b)>)"));
-}
-
-#[tokio::test]
-async fn empty_results_keep_the_provider_marker_in_markdown() {
- let app = Router::new().route(
- "/search",
- post(|Json(_): Json<Value>| async move { Json(json!({ "results": [] })) }),
- );
- let base_url = spawn(app).await;
-
- let tool = TavilySearchTool::new(Some("test-key".into()), Some(base_url), 5, 15);
- let result = tool
- .execute_with_options(
- json!({"query": "nothing here"}),
- ToolCallOptions {
- prefer_markdown: true,
- },
- )
- .await
- .expect("execute() should succeed");
-
- let production_output = result.output_for_llm(true);
- assert!(production_output.contains("No results for `nothing here`"));
- assert!(production_output.ends_with("(via Tavily)\n"));
-}
diff --git a/crates/openhuman-core/src/search/tools/tinyfish.rs b/crates/openhuman-core/src/search/tools/tinyfish.rs
deleted file mode 100644
index d99f47017c..0000000000
--- a/crates/openhuman-core/src/search/tools/tinyfish.rs
+++ /dev/null
@@ -1,603 +0,0 @@
-//! TinyFish web search, page fetch, and goal-based browser automation tools.
-//!
-//! **Scope**: All (agent loop + CLI/RPC).
-//!
-//! **Endpoints**:
-//! - `POST /agent-integrations/tinyfish/search`
-//! - `POST /agent-integrations/tinyfish/fetch`
-//! - `POST /agent-integrations/tinyfish/agent/run`
-//!
-//! The OpenHuman backend proxies TinyFish calls so API keys, billing, and
-//! rate limits stay server-side. Search and Fetch are read-oriented tools;
-//! Agent runs execute browser workflows on remote websites.
-
-use crate::integrations::IntegrationClient;
-use crate::util::truncate_chars_flagged as truncate_chars;
-use async_trait::async_trait;
-use serde::Deserialize;
-use serde_json::json;
-use std::sync::Arc;
-use tinytools::{PermissionLevel, Tool, ToolCategory, ToolResult};
-
-fn non_empty_string<'a>(args: &'a serde_json::Value, key: &str) -> anyhow::Result<&'a str> {
- args.get(key)
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: {key}"))
-}
-
-fn optional_string<'a>(args: &'a serde_json::Value, key: &str) -> Option<&'a str> {
- args.get(key)
- .and_then(|v| v.as_str())
- .filter(|s| !s.trim().is_empty())
-}
-
-#[derive(Debug, Deserialize)]
-struct TinyFishSearchResponse {
- #[serde(default)]
- results: Vec<TinyFishSearchResult>,
- #[serde(default)]
- total_results: Option<u64>,
- #[serde(rename = "costUsd", default)]
- cost_usd: Option<f64>,
-}
-
-#[derive(Debug, Deserialize)]
-struct TinyFishSearchResult {
- #[serde(default)]
- position: Option<u64>,
- #[serde(default)]
- site_name: Option<String>,
- #[serde(default)]
- title: String,
- #[serde(default)]
- snippet: String,
- #[serde(default)]
- url: String,
-}
-
-#[derive(Debug, Deserialize)]
-struct TinyFishFetchResponse {
- #[serde(default)]
- results: Vec<TinyFishFetchResult>,
- #[serde(default)]
- errors: Vec<TinyFishFetchError>,
- #[serde(rename = "costUsd", default)]
- cost_usd: Option<f64>,
-}
-
-#[derive(Debug, Deserialize)]
-struct TinyFishFetchResult {
- #[serde(default)]
- url: String,
- #[serde(default)]
- final_url: Option<String>,
- #[serde(default)]
- title: Option<String>,
- #[serde(default)]
- description: Option<String>,
- #[serde(default)]
- language: Option<String>,
- #[serde(default)]
- text: serde_json::Value,
- #[serde(default)]
- links: Option<Vec<String>>,
- #[serde(default)]
- image_links: Option<Vec<String>>,
- #[serde(default)]
- latency_ms: Option<f64>,
- #[serde(default)]
- format: Option<String>,
-}
-
-#[derive(Debug, Deserialize)]
-struct TinyFishFetchError {
- #[serde(default)]
- url: String,
- #[serde(default)]
- error: String,
- #[serde(default)]
- status: Option<u16>,
-}
-
-#[derive(Debug, Deserialize)]
-struct TinyFishAgentRunResponse {
- #[serde(default)]
- run_id: Option<String>,
- #[serde(default)]
- status: String,
- #[serde(default)]
- result: Option<serde_json::Value>,
- #[serde(default)]
- error: Option<serde_json::Value>,
- #[serde(default)]
- num_of_steps: Option<u64>,
- #[serde(rename = "costUsd", default)]
- cost_usd: Option<f64>,
-}
-
-fn format_agent_run_response(mut resp: TinyFishAgentRunResponse) -> String {
- tracing::debug!(
- "[tinyfish_agent_run] formatting response status_present={} steps_present={} result_present={} error_present={} cost_present={}",
- !resp.status.is_empty(),
- resp.num_of_steps.is_some(),
- resp.result.is_some(),
- resp.error.is_some(),
- resp.cost_usd.is_some()
- );
-
- let mut lines = vec!["TinyFish automation finished.".to_string()];
- if !resp.status.is_empty() {
- tracing::debug!("[tinyfish_agent_run] adding status field");
- lines.push(format!("Status: {}", resp.status));
- }
- if let Some(steps) = resp.num_of_steps {
- tracing::debug!(steps = steps, "[tinyfish_agent_run] adding step count");
- lines.push(format!("Steps: {steps}"));
- }
- if let Some(result) = resp.result.take() {
- tracing::debug!("[tinyfish_agent_run] adding result payload");
- lines.push("Result:".to_string());
- lines.push(result.to_string());
- }
- if let Some(error) = resp.error.take() {
- tracing::debug!("[tinyfish_agent_run] adding error payload");
- lines.push("Error:".to_string());
- lines.push(error.to_string());
- }
- if let Some(cost_usd) = resp.cost_usd {
- tracing::debug!(cost_usd = cost_usd, "[tinyfish_agent_run] adding cost");
- lines.push(format!("Cost: ${cost_usd:.4}"));
- }
- lines.join("\n")
-}
-
-/// Search the web with TinyFish Search.
-pub struct TinyFishSearchTool {
- client: Arc<IntegrationClient>,
-}
-
-impl TinyFishSearchTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for TinyFishSearchTool {
- fn name(&self) -> &str {
- "tinyfish_search"
- }
-
- fn description(&self) -> &str {
- "Search the web with TinyFish and return ranked results with titles, snippets, \
- URLs, and source sites. Use this when you need search results before fetching \
- or automating a page."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "Search query"
- },
- "location": {
- "type": "string",
- "description": "Optional country code for geo-targeted results, e.g. US, GB, FR"
- },
- "language": {
- "type": "string",
- "description": "Optional language code, e.g. en, fr"
- },
- "page": {
- "type": "integer",
- "description": "Optional result page number, starting at 0",
- "minimum": 0,
- "maximum": 10
- },
- "include_thumbnail": {
- "type": "boolean",
- "description": "Whether to include thumbnail URLs when available",
- "default": false
- }
- },
- "required": ["query"]
- })
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::Workflow
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let query = non_empty_string(&args, "query")?;
- let mut body = json!({ "query": query });
- if let Some(location) = optional_string(&args, "location") {
- body["location"] = json!(location);
- }
- if let Some(language) = optional_string(&args, "language") {
- body["language"] = json!(language);
- }
- if let Some(page) = args.get("page").and_then(|v| v.as_u64()) {
- body["page"] = json!(page.min(10));
- }
- if let Some(include_thumbnail) = args.get("include_thumbnail").and_then(|v| v.as_bool()) {
- body["include_thumbnail"] = json!(include_thumbnail);
- }
-
- tracing::debug!(query = query, "[tinyfish_search] searching");
-
- match self
- .client
- .post::<TinyFishSearchResponse>("/agent-integrations/tinyfish/search", &body)
- .await
- {
- Ok(resp) => {
- if resp.results.is_empty() {
- return Ok(ToolResult::success(format!(
- "No TinyFish search results found for: {query}"
- )));
- }
-
- let mut lines = vec![format!(
- "TinyFish returned {} search result(s) for: {query}",
- resp.results.len()
- )];
- if let Some(total) = resp.total_results {
- lines.push(format!("Total results: {total}"));
- }
-
- for (idx, item) in resp.results.iter().take(10).enumerate() {
- let position = item.position.unwrap_or((idx + 1) as u64);
- lines.push(format!("\n{}. {}", position, item.title));
- if let Some(site_name) = item.site_name.as_deref() {
- if !site_name.is_empty() {
- lines.push(format!(" Site: {site_name}"));
- }
- }
- if !item.url.is_empty() {
- lines.push(format!(" URL: {}", item.url));
- }
- if !item.snippet.is_empty() {
- lines.push(format!(" Snippet: {}", item.snippet));
- }
- }
-
- if resp.results.len() > 10 {
- lines.push("Output truncated to the first 10 results.".to_string());
- }
- if let Some(cost_usd) = resp.cost_usd {
- lines.push(format!("\nCost: ${cost_usd:.4}"));
- }
-
- Ok(ToolResult::success(lines.join("\n")))
- }
- Err(e) => {
- tracing::debug!(
- query = query,
- error = %e,
- "[tinyfish_search] request failed"
- );
- Ok(ToolResult::error(format!("TinyFish search failed: {e}")))
- }
- }
- }
-}
-
-/// Render web pages with TinyFish Fetch and return extracted content.
-pub struct TinyFishFetchTool {
- client: Arc<IntegrationClient>,
-}
-
-impl TinyFishFetchTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for TinyFishFetchTool {
- fn name(&self) -> &str {
- "tinyfish_fetch"
- }
-
- fn description(&self) -> &str {
- "Render one or more URLs with TinyFish Fetch and extract clean page content. \
- Use this for JavaScript-heavy pages when you already know the URLs."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "urls": {
- "type": "array",
- "items": { "type": "string" },
- "description": "HTTP or HTTPS URLs to fetch (1-10)",
- "minItems": 1,
- "maxItems": 10
- },
- "format": {
- "type": "string",
- "enum": ["markdown", "html", "json"],
- "description": "Output format for extracted content (default markdown)",
- "default": "markdown"
- },
- "links": {
- "type": "boolean",
- "description": "Include absolute outbound links found on each page",
- "default": false
- },
- "image_links": {
- "type": "boolean",
- "description": "Include absolute image URLs found on each page",
- "default": false
- }
- },
- "required": ["urls"]
- })
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::Workflow
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let urls = args
- .get("urls")
- .and_then(|v| v.as_array())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: urls"))?;
- if urls.is_empty() {
- return Ok(ToolResult::error("urls must contain at least one URL"));
- }
-
- let mut normalized_urls = Vec::with_capacity(urls.len().min(10));
- for (idx, url) in urls.iter().take(10).enumerate() {
- match url.as_str() {
- Some(s) if !s.trim().is_empty() => normalized_urls.push(s),
- Some(_) => return Ok(ToolResult::error(format!("urls[{idx}] is empty"))),
- None => return Ok(ToolResult::error(format!("urls[{idx}] is not a string"))),
- }
- }
-
- let mut body = json!({ "urls": normalized_urls });
- if let Some(format) = optional_string(&args, "format") {
- body["format"] = json!(format);
- }
- if let Some(links) = args.get("links").and_then(|v| v.as_bool()) {
- body["links"] = json!(links);
- }
- if let Some(image_links) = args.get("image_links").and_then(|v| v.as_bool()) {
- body["image_links"] = json!(image_links);
- }
-
- tracing::debug!(
- url_count = normalized_urls.len(),
- "[tinyfish_fetch] fetching URLs"
- );
-
- match self
- .client
- .post::<TinyFishFetchResponse>("/agent-integrations/tinyfish/fetch", &body)
- .await
- {
- Ok(resp) => {
- let mut lines = vec![format!(
- "TinyFish fetched {} page(s), {} error(s).",
- resp.results.len(),
- resp.errors.len()
- )];
-
- for (idx, page) in resp.results.iter().enumerate() {
- lines.push(format!(
- "\n{}. {}",
- idx + 1,
- page.title.as_deref().unwrap_or(&page.url)
- ));
- lines.push(format!(" URL: {}", page.url));
- if let Some(final_url) = page.final_url.as_deref() {
- if final_url != page.url {
- lines.push(format!(" Final URL: {final_url}"));
- }
- }
- if let Some(description) = page.description.as_deref() {
- if !description.is_empty() {
- lines.push(format!(" Description: {description}"));
- }
- }
- if let Some(language) = page.language.as_deref() {
- lines.push(format!(" Language: {language}"));
- }
- if let Some(format) = page.format.as_deref() {
- lines.push(format!(" Format: {format}"));
- }
- if let Some(latency_ms) = page.latency_ms {
- lines.push(format!(" Latency: {latency_ms:.0}ms"));
- }
- if let Some(links) = page.links.as_ref() {
- lines.push(format!(" Links: {}", links.len()));
- }
- if let Some(image_links) = page.image_links.as_ref() {
- lines.push(format!(" Image links: {}", image_links.len()));
- }
-
- let text = match page.text.as_str() {
- Some(s) => s.to_string(),
- None => page.text.to_string(),
- };
- if !text.is_empty() && text != "null" {
- let (snippet, truncated) = truncate_chars(&text, 1200);
- lines.push(" Content:".to_string());
- lines.push(snippet.to_string());
- if truncated {
- lines.push(" Content truncated to 1200 characters.".to_string());
- }
- }
- }
-
- if !resp.errors.is_empty() {
- lines.push("\nErrors:".to_string());
- for err in &resp.errors {
- let status = err.status.map(|s| format!(" ({s})")).unwrap_or_default();
- lines.push(format!("- {}: {}{}", err.url, err.error, status));
- }
- }
- if let Some(cost_usd) = resp.cost_usd {
- lines.push(format!("\nCost: ${cost_usd:.4}"));
- }
-
- Ok(ToolResult::success(lines.join("\n")))
- }
- Err(e) => {
- tracing::debug!(
- url_count = normalized_urls.len(),
- error = %e,
- "[tinyfish_fetch] request failed"
- );
- Ok(ToolResult::error(format!("TinyFish fetch failed: {e}")))
- }
- }
- }
-}
-
-/// Run a TinyFish goal-based browser automation.
-pub struct TinyFishAgentRunTool {
- client: Arc<IntegrationClient>,
-}
-
-impl TinyFishAgentRunTool {
- pub fn new(client: Arc<IntegrationClient>) -> Self {
- Self { client }
- }
-}
-
-#[async_trait]
-impl Tool for TinyFishAgentRunTool {
- fn name(&self) -> &str {
- "tinyfish_agent_run"
- }
-
- fn description(&self) -> &str {
- "Run a TinyFish goal-based browser automation on a target website. Provide a URL \
- and a specific natural-language goal with the desired output format."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "url": {
- "type": "string",
- "description": "Target website URL to automate"
- },
- "goal": {
- "type": "string",
- "description": "Specific browser automation goal and expected output format"
- },
- "output_schema": {
- "type": "object",
- "description": "Optional structured-output JSON schema supported by TinyFish"
- },
- "browser_profile": {
- "type": "string",
- "enum": ["lite", "stealth"],
- "description": "Browser profile for the run (default lite)",
- "default": "lite"
- },
- "proxy_country_code": {
- "type": "string",
- "enum": ["US", "GB", "CA", "DE", "FR", "JP", "AU"],
- "description": "Optional TinyFish proxy country code"
- },
- "use_vault": {
- "type": "boolean",
- "description": "Allow TinyFish vault credentials for this run when configured",
- "default": false
- },
- "credential_item_ids": {
- "type": "array",
- "items": { "type": "string" },
- "description": "Optional credential item IDs scoped to this run; requires use_vault=true"
- }
- },
- "required": ["url", "goal"]
- })
- }
-
- fn permission_level(&self) -> PermissionLevel {
- PermissionLevel::Execute
- }
-
- fn category(&self) -> ToolCategory {
- ToolCategory::Workflow
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let url = non_empty_string(&args, "url")?;
- let goal = non_empty_string(&args, "goal")?;
- let mut body = json!({
- "url": url,
- "goal": goal,
- });
-
- if let Some(output_schema) = args.get("output_schema") {
- if !output_schema.is_object() {
- return Ok(ToolResult::error("output_schema must be a JSON object"));
- }
- body["output_schema"] = output_schema.clone();
- }
- if let Some(browser_profile) = optional_string(&args, "browser_profile") {
- body["browser_profile"] = json!(browser_profile);
- }
- if let Some(country_code) = optional_string(&args, "proxy_country_code") {
- body["proxy_config"] = json!({
- "enabled": true,
- "type": "tetra",
- "country_code": country_code,
- });
- }
- if let Some(use_vault) = args.get("use_vault").and_then(|v| v.as_bool()) {
- body["use_vault"] = json!(use_vault);
- }
- if let Some(ids) = args.get("credential_item_ids") {
- if !ids.is_array() {
- return Ok(ToolResult::error("credential_item_ids must be an array"));
- }
- body["credential_item_ids"] = ids.clone();
- }
-
- tracing::debug!(url = url, "[tinyfish_agent_run] starting automation");
-
- match self
- .client
- .post::<TinyFishAgentRunResponse>("/agent-integrations/tinyfish/agent/run", &body)
- .await
- {
- Ok(resp) => {
- tracing::debug!(
- run_id = resp.run_id.as_deref().unwrap_or(""),
- status = resp.status.as_str(),
- has_error = resp.error.is_some(),
- "[tinyfish_agent_run] request finished"
- );
- Ok(ToolResult::success(format_agent_run_response(resp)))
- }
- Err(e) => {
- tracing::debug!(
- url = url,
- error = %e,
- "[tinyfish_agent_run] request failed"
- );
- Ok(ToolResult::error(format!(
- "TinyFish automation failed: {e}"
- )))
- }
- }
- }
-}
-
-#[cfg(test)]
-#[path = "tinyfish_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/tinyfish_tests.rs b/crates/openhuman-core/src/search/tools/tinyfish_tests.rs
deleted file mode 100644
index 41b994c594..0000000000
--- a/crates/openhuman-core/src/search/tools/tinyfish_tests.rs
+++ /dev/null
@@ -1,199 +0,0 @@
-use super::*;
-
-fn test_client() -> Arc<IntegrationClient> {
- Arc::new(IntegrationClient::new("http://test".into(), "tok".into()))
-}
-
-#[test]
-fn search_tool_metadata_and_schema() {
- let tool = TinyFishSearchTool::new(test_client());
- assert_eq!(tool.name(), "tinyfish_search");
- assert_eq!(tool.category(), ToolCategory::Workflow);
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
- assert!(tool.description().contains("TinyFish"));
-
- let schema = tool.parameters_schema();
- assert!(schema["properties"]["query"].is_object());
- assert!(schema["required"]
- .as_array()
- .unwrap()
- .iter()
- .any(|v| v == "query"));
-}
-
-#[tokio::test]
-async fn search_rejects_missing_query() {
- let tool = TinyFishSearchTool::new(test_client());
- assert!(tool.execute(json!({})).await.is_err());
-}
-
-#[tokio::test]
-async fn search_rejects_empty_query() {
- let tool = TinyFishSearchTool::new(test_client());
- assert!(tool.execute(json!({"query": ""})).await.is_err());
-}
-
-#[test]
-fn fetch_tool_metadata_and_schema() {
- let tool = TinyFishFetchTool::new(test_client());
- assert_eq!(tool.name(), "tinyfish_fetch");
- assert_eq!(tool.category(), ToolCategory::Workflow);
- assert_eq!(tool.permission_level(), PermissionLevel::ReadOnly);
- assert!(tool.description().contains("JavaScript-heavy"));
-
- let schema = tool.parameters_schema();
- assert!(schema["properties"]["urls"].is_object());
- assert!(schema["properties"]["format"]["enum"]
- .as_array()
- .unwrap()
- .iter()
- .any(|v| v == "markdown"));
- assert!(schema["required"]
- .as_array()
- .unwrap()
- .iter()
- .any(|v| v == "urls"));
-}
-
-#[tokio::test]
-async fn fetch_rejects_empty_urls() {
- let tool = TinyFishFetchTool::new(test_client());
- let result = tool.execute(json!({"urls": []})).await.unwrap();
- assert!(result.is_error);
- assert!(result.output().contains("at least one URL"));
-}
-
-#[tokio::test]
-async fn fetch_rejects_non_string_url() {
- let tool = TinyFishFetchTool::new(test_client());
- let result = tool.execute(json!({"urls": [42]})).await.unwrap();
- assert!(result.is_error);
- assert!(result.output().contains("not a string"));
-}
-
-#[test]
-fn agent_run_tool_metadata_and_schema() {
- let tool = TinyFishAgentRunTool::new(test_client());
- assert_eq!(tool.name(), "tinyfish_agent_run");
- assert_eq!(tool.category(), ToolCategory::Workflow);
- assert_eq!(tool.permission_level(), PermissionLevel::Execute);
- assert!(tool.description().contains("browser automation"));
-
- let schema = tool.parameters_schema();
- let required = schema["required"].as_array().unwrap();
- assert!(required.iter().any(|v| v == "url"));
- assert!(required.iter().any(|v| v == "goal"));
- assert!(schema["properties"]["browser_profile"]["enum"]
- .as_array()
- .unwrap()
- .iter()
- .any(|v| v == "stealth"));
-}
-
-#[tokio::test]
-async fn agent_run_rejects_missing_goal() {
- let tool = TinyFishAgentRunTool::new(test_client());
- assert!(tool
- .execute(json!({"url": "https://example.com"}))
- .await
- .is_err());
-}
-
-#[tokio::test]
-async fn agent_run_rejects_non_object_output_schema() {
- let tool = TinyFishAgentRunTool::new(test_client());
- let result = tool
- .execute(json!({
- "url": "https://example.com",
- "goal": "Return JSON",
- "output_schema": []
- }))
- .await
- .unwrap();
- assert!(result.is_error);
- assert!(result.output().contains("output_schema"));
-}
-
-#[test]
-fn search_response_deserializes() {
- let json = r#"{
- "results": [
- {
- "position": 1,
- "site_name": "example.com",
- "title": "Example",
- "snippet": "Example snippet",
- "url": "https://example.com"
- }
- ],
- "total_results": 1,
- "costUsd": 0.0
- }"#;
- let resp: TinyFishSearchResponse = serde_json::from_str(json).unwrap();
- assert_eq!(resp.results.len(), 1);
- assert_eq!(resp.results[0].title, "Example");
- assert_eq!(resp.total_results, Some(1));
-}
-
-#[test]
-fn fetch_response_deserializes_with_errors() {
- let json = r##"{
- "results": [
- {
- "url": "https://example.com",
- "final_url": "https://example.com",
- "title": "Example",
- "text": "# Example",
- "links": ["https://example.com/a"],
- "image_links": ["https://example.com/a.png"],
- "latency_ms": 12
- }
- ],
- "errors": [
- {
- "url": "https://blocked.example",
- "error": "bot_blocked",
- "status": 403
- }
- ]
- }"##;
- let resp: TinyFishFetchResponse = serde_json::from_str(json).unwrap();
- assert_eq!(resp.results.len(), 1);
- assert_eq!(resp.errors.len(), 1);
- assert_eq!(resp.errors[0].status, Some(403));
-}
-
-#[test]
-fn agent_run_response_deserializes() {
- let json = r#"{
- "run_id": "run_123",
- "status": "COMPLETED",
- "num_of_steps": 4,
- "result": {"ok": true},
- "costUsd": 0.12
- }"#;
- let resp: TinyFishAgentRunResponse = serde_json::from_str(json).unwrap();
- assert_eq!(resp.run_id.as_deref(), Some("run_123"));
- assert_eq!(resp.status, "COMPLETED");
- assert_eq!(resp.num_of_steps, Some(4));
- assert_eq!(resp.cost_usd, Some(0.12));
-}
-
-#[test]
-fn agent_run_output_hides_internal_run_id() {
- let resp = TinyFishAgentRunResponse {
- run_id: Some("run_123".to_string()),
- status: "COMPLETED".to_string(),
- result: Some(json!({"ok": true})),
- error: None,
- num_of_steps: Some(4),
- cost_usd: Some(0.12),
- };
-
- let output = format_agent_run_response(resp);
-
- assert!(output.contains("TinyFish automation finished."));
- assert!(output.contains("Status: COMPLETED"));
- assert!(!output.contains("Run ID:"));
- assert!(!output.contains("run_123"));
-}
diff --git a/crates/openhuman-core/src/search/tools/web_search.rs b/crates/openhuman-core/src/search/tools/web_search.rs
deleted file mode 100644
index 4e0fb81c63..0000000000
--- a/crates/openhuman-core/src/search/tools/web_search.rs
+++ /dev/null
@@ -1,443 +0,0 @@
-//! `WebSearchTool` — the managed, backend-proxied `web_search_tool`.
-//!
-//! Registered by `engines/managed.rs` (the effective default, and the fallback
-//! when a BYOK engine has no key configured) and alongside the Parallel family
-//! by `engines/parallel.rs`. Requests go through
-//! `crate::integrations::IntegrationClient` to
-//! `POST /agent-integrations/parallel/search`; `resolve_managed_provider`
-//! attributes each response to the provider the backend reports, falling back
-//! to `MANAGED_DEFAULT_PROVIDER`, for UI display. `with_direct_search` can
-//! swap in a `SeltzSearchTool` that bypasses the proxy; only tests use it.
-
-use super::{
- web_search_metadata, SearchResponse, SearchResultItem, SeltzSearchTool, WebSearchResultRef,
-};
-use crate::config::Config;
-use crate::integrations::IntegrationClient;
-use async_trait::async_trait;
-use serde_json::{json, Value};
-use sha2::{Digest, Sha256};
-use std::sync::Arc;
-use tinytools::{Tool, ToolCallOptions, ToolResult};
-
-/// Provider the OpenHuman Managed search path resolves to today. Exa powers
-/// the overwhelming majority of managed search traffic, so it is the labelled
-/// default whenever the backend response does not name a provider. This is a
-/// *fallback* label, not a hardcoded one: [`resolve_managed_provider`] prefers
-/// the provider the backend actually reports, so a future routing change flows
-/// through to the UI attribution ("Searched with …", #5136) with no code edit.
-const MANAGED_DEFAULT_PROVIDER: &str = "Exa";
-
-/// Classify a managed-search backend failure that is really an upstream
-/// provider quota or rate-limit fault.
-///
-/// The managed route resolves to a search provider server-side, so an upstream
-/// 402/429 never reaches us as that status: the backend wraps it in its own
-/// 4xx and the only trace is the provider's text carried in the detail. Left
-/// unclassified it surfaces to the agent as `Backend returned 400 Bad Request
-/// for POST /agent-integrations/parallel/search: {"error":"You have exceeded
-/// your credits limit…"}`, which tells a user nothing they can act on (#5750).
-///
-/// Matching is on the *upstream* signature rather than our own status, so it
-/// keeps working if the backend changes which 4xx it wraps the fault in, and
-/// stays correct when the managed route resolves to a provider other than the
-/// current default. Returns `None` for anything else, leaving the original
-/// error — and its detail — exactly as it was.
-///
-/// The replacement text deliberately carries none of the original detail: the
-/// provider echoes the submitted query back in its error body, and that body
-/// would otherwise reach the agent transcript.
-fn managed_search_quota_error(message: &str) -> Option<&'static str> {
- // Only inspect the structured provider envelope before any echoed JSON
- // body. The body may contain the submitted query, so searching all of it
- // would let an unrelated query such as "HTTP 429" trigger this mapping.
- let envelope = message
- .split_once('{')
- .map_or(message, |(prefix, _)| prefix);
- let envelope_lowered = envelope.to_ascii_lowercase();
- let provider_json = message
- .find('{')
- .and_then(|start| serde_json::from_str::<Value>(&message[start..]).ok());
-
- // Exa tags credit exhaustion explicitly; the numeric form covers a
- // provider status in its API-error envelope. A parsed tag avoids matching
- // the same text when it appears in an echoed query or error string.
- let credits_exhausted = provider_json
- .as_ref()
- .and_then(|body| body.get("tag"))
- .and_then(Value::as_str)
- .is_some_and(|tag| tag.eq_ignore_ascii_case("NO_MORE_CREDITS"))
- || envelope_lowered.contains("api error (402)");
- if credits_exhausted {
- return Some(
- "Managed web search is temporarily unavailable: the shared search credit pool is \
- exhausted. Configure your own search API key under Connections > Search engine to \
- keep searching, or try again later.",
- );
- }
-
- // Accept only an explicit status in the outer/provider envelope. In
- // particular, do not classify prose from the response body: providers
- // commonly echo the query there verbatim.
- if envelope_lowered.contains("api error (429)")
- || envelope_lowered.contains("backend returned 429 ")
- || provider_json
- .as_ref()
- .and_then(|body| body.get("status"))
- .and_then(Value::as_u64)
- == Some(429)
- {
- return Some(
- "Managed web search is rate limited upstream. Please wait a moment before searching \
- again, or configure your own search API key under Connections > Search engine.",
- );
- }
-
- None
-}
-
-/// Resolve the provider name to attribute a managed search to. Uses the
-/// backend-reported provider when present and non-empty, otherwise falls back
-/// to [`MANAGED_DEFAULT_PROVIDER`]. Shared with the `tools.web_search` RPC so
-/// both managed-search surfaces attribute a call the same way.
-pub(crate) fn resolve_managed_provider(resp: &SearchResponse) -> &str {
- resp.provider
- .as_deref()
- .map(str::trim)
- .filter(|p| !p.is_empty())
- .unwrap_or(MANAGED_DEFAULT_PROVIDER)
-}
-
-/// Web search tool backed by the server-side Parallel integration proxy.
-pub struct WebSearchTool {
- client: Option<Arc<IntegrationClient>>,
- /// Root config held so `execute_with_options` can rebuild a fresh
- /// `IntegrationClient` when the baked-in one carries a stale JWT
- /// (i.e. when the user re-authenticated after token expiry — #5873).
- root_config: Option<Arc<Config>>,
- direct_search: Option<SeltzSearchTool>,
- max_results: usize,
- timeout_secs: u64,
-}
-
-impl WebSearchTool {
- /// The client to use for this call, preferring one whose JWT matches what
- /// the credential store holds *right now*.
- ///
- /// The tool's client is built once, when the search-tool registry is built,
- /// and its JWT is baked in at that moment; after a session refresh it is
- /// stale and posting with it 401s. That 401 is not a cheap failure. For a
- /// non-Composio path `handle_session_jwt_unauthorized` publishes
- /// `DomainEvent::SessionExpired`, and `SessionExpiredSubscriber` answers it
- /// with an unconditional `clear_session` that never compares the rejected
- /// token against the stored one. So recovering *after* the 401 races a
- /// teardown that is already in flight — a retry can succeed with the fresh
- /// JWT and the queued event then deletes that same JWT, signing the user
- /// out on a search that just worked.
- ///
- /// Refreshing *before* the request avoids that entirely: the stale-token
- /// 401 is never provoked. A genuinely dead session still 401s and still
- /// tears down, which is the correct outcome for that case and is
- /// deliberately left alone (#5873).
- ///
- /// Also covers the tool that was built while signed out: `client` is `None`
- /// there, and before this it stayed dead until the registry was rebuilt.
- fn resolve_client(&self) -> Option<Arc<IntegrationClient>> {
- let fresh = self
- .root_config
- .as_deref()
- .and_then(crate::integrations::build_client);
-
- match (fresh, self.client.as_ref()) {
- (Some(fresh), Some(cached)) => {
- if fresh.auth_token == cached.auth_token {
- Some(Arc::clone(cached))
- } else {
- tracing::debug!(
- "[web_search] cached client holds a superseded session token — using the refreshed one"
- );
- Some(fresh)
- }
- }
- (Some(fresh), None) => Some(fresh),
- // `root_config` WAS supplied and `build_client` still answered
- // `None`. That is not a transient failure to look up a token — it
- // is the store telling us there is no usable app-session JWT, and
- // `build_client` logs it as exactly that ("no auth token available
- // — user is not signed in"). Falling back to the cached client here
- // would post the pre-sign-out bearer token, so a tool that outlived
- // a local sign-out could keep making authenticated backend requests
- // with a credential the user has already revoked locally.
- //
- // The cached fallback is kept ONLY for the tool that was handed no
- // root config: there is nothing to re-resolve against, so the
- // client it was built with is the only truth available.
- (None, Some(cached)) => {
- if self.root_config.is_some() {
- tracing::debug!(
- "[web_search] no session token in the store — dropping the cached client"
- );
- None
- } else {
- Some(Arc::clone(cached))
- }
- }
- (None, None) => None,
- }
- }
-
- pub fn new(
- client: Option<Arc<IntegrationClient>>,
- root_config: Option<Arc<Config>>,
- max_results: usize,
- timeout_secs: u64,
- ) -> Self {
- Self {
- client,
- root_config,
- direct_search: None,
- max_results: max_results.clamp(1, 10),
- timeout_secs: timeout_secs.max(1),
- }
- }
-
- pub fn with_direct_search(mut self, direct_search: Option<SeltzSearchTool>) -> Self {
- self.direct_search = direct_search;
- self
- }
-
- fn parse_parallel_results(
- &self,
- results: &[SearchResultItem],
- query: &str,
- provider: &str,
- ) -> anyhow::Result<String> {
- if results.is_empty() {
- // Still attribute an empty search: the call completed, so the
- // timeline must not keep showing it as in-progress (#5136).
- return Ok(format!(
- "No results found for: {} (via {})",
- query, provider
- ));
- }
-
- let mut lines = vec![format!("Search results for: {} (via {})", query, provider)];
-
- for (i, result) in results.iter().take(self.max_results).enumerate() {
- let title = if result.title.trim().is_empty() {
- "No title"
- } else {
- result.title.trim()
- };
- let url = result.url.trim();
-
- lines.push(format!("{}. {}", i + 1, title));
- lines.push(format!(" {}", url));
-
- if let Some(date) = result.publish_date.as_deref() {
- let date = date.trim();
- if !date.is_empty() {
- lines.push(format!(" Published: {}", date));
- }
- }
-
- if let Some(first) = result.excerpts.first() {
- let excerpt = first.trim();
- if !excerpt.is_empty() {
- let truncated = crate::util::truncate_with_ellipsis(excerpt, 500);
- lines.push(format!(" {}", truncated));
- }
- }
- }
-
- Ok(lines.join("\n"))
- }
-
- fn render_results_markdown(
- &self,
- results: &[SearchResultItem],
- query: &str,
- provider: &str,
- ) -> String {
- if results.is_empty() {
- return format!("_No results for `{query}`_ (via {provider})");
- }
- let mut out = format!("# Search results — `{query}` (via {provider})\n");
- for r in results.iter().take(self.max_results) {
- let title = if r.title.trim().is_empty() {
- "Untitled"
- } else {
- r.title.trim()
- };
- out.push_str(&format!("\n## [{title}]({})\n", r.url.trim()));
- if let Some(date) = r.publish_date.as_deref() {
- let date = date.trim();
- if !date.is_empty() {
- out.push_str(&format!("_Published: {date}_\n\n"));
- }
- }
- if let Some(first) = r.excerpts.first() {
- let excerpt = first.trim();
- if !excerpt.is_empty() {
- let truncated = crate::util::truncate_with_suffix(excerpt, 500, "…");
- out.push_str(&format!("> {truncated}\n"));
- }
- }
- }
- out
- }
-}
-
-#[async_trait]
-impl Tool for WebSearchTool {
- fn name(&self) -> &str {
- "web_search_tool"
- }
-
- fn description(&self) -> &str {
- "Search the web for information via a configured direct search API or the backend search proxy. Returns relevant search results with titles, URLs, and descriptions."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "query": {
- "type": "string",
- "description": "The search query. Be specific for better results."
- },
- // Opts into a caller-steered summary; see `tokenjuice::focus`.
- "summary_focus": crate::inference::tokenjuice::focus::summary_focus_property()
- },
- "required": ["query"]
- })
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- self.execute_with_options(args, ToolCallOptions::default())
- .await
- }
-
- fn supports_markdown(&self) -> bool {
- true
- }
-
- async fn execute_with_options(
- &self,
- args: serde_json::Value,
- options: ToolCallOptions,
- ) -> anyhow::Result<ToolResult> {
- let query = args
- .get("query")
- .and_then(|q| q.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing required parameter: query"))?;
-
- if query.trim().is_empty() {
- anyhow::bail!("Search query cannot be empty");
- }
- let query = query.trim().to_string();
-
- if let Some(direct_search) = &self.direct_search {
- tracing::debug!(
- query_len = query.chars().count(),
- max_results = self.max_results,
- timeout_secs = self.timeout_secs,
- "[web_search] direct Seltz search"
- );
- let mut normalized_args = args;
- if let Some(obj) = normalized_args.as_object_mut() {
- obj.insert("query".to_string(), Value::String(query.clone()));
- }
- return direct_search
- .execute_with_options(normalized_args, options)
- .await;
- }
-
- let client = self.resolve_client().ok_or_else(|| {
- anyhow::anyhow!(
- "Web search unavailable: no backend session token. \
- Sign in to TinyHumans so the server can proxy search, \
- or configure a direct search API key under Settings → Search."
- )
- })?;
-
- let query_fingerprint = hex::encode(Sha256::digest(query.as_bytes()));
- tracing::debug!(
- query_len = query.chars().count(),
- query_fingerprint = %query_fingerprint[..16],
- max_results = self.max_results,
- timeout_secs = self.timeout_secs,
- "[web_search] backend parallel search"
- );
-
- // Body matches `parallelSearchSchema` in backend-2. The legacy
- // `numResults` / `maxCharactersPerExcerpt` aliases still work, but
- // current fields are `maxResults` / `maxCharsPerResult`. Also dropping
- // `timeoutSecs` — the validator does not declare it and Parallel's
- // per-mode deadlines drive timing on the upstream side.
- let _ = self.timeout_secs;
- let body = json!({
- "objective": query.clone(),
- "searchQueries": [query.clone()],
- "mode": "fast",
- "excerpts": {
- "maxResults": self.max_results,
- "maxCharsPerResult": 500
- }
- });
-
- let resp = client
- .post::<SearchResponse>("/agent-integrations/parallel/search", &body)
- .await
- .map_err(
- |error| match managed_search_quota_error(&error.to_string()) {
- Some(actionable) => {
- // Log the classification, never the detail — it echoes the query.
- tracing::warn!(
- "[web_search] managed search unavailable: upstream quota fault"
- );
- anyhow::anyhow!(actionable)
- }
- None => error,
- },
- )?;
-
- // Attribute the search to the provider the managed backend resolved to
- // (Exa by default). The provider name is echoed in the result text so
- // the UI can surface "Searched with <provider>" without a hardcode.
- let provider = resolve_managed_provider(&resp);
- tracing::debug!(provider, "[web_search] managed search resolved provider");
-
- let mut result =
- ToolResult::success(self.parse_parallel_results(&resp.results, &query, provider)?);
- if options.prefer_markdown {
- result.markdown_formatted =
- Some(self.render_results_markdown(&resp.results, &query, provider));
- }
- // Host-only structured payload for the chat UI's tool-call
- // presentation (issue: tool-call presentation) — never rendered to
- // the model, so `parse_parallel_results`'s text above (and the cache
- // key that depends on it) is unaffected.
- let structured_results: Vec<WebSearchResultRef<'_>> = resp
- .results
- .iter()
- .map(|r| WebSearchResultRef {
- title: &r.title,
- url: &r.url,
- published: r.publish_date.as_deref(),
- excerpt: r.excerpts.first().map(String::as_str),
- })
- .collect();
- result.metadata = Some(web_search_metadata(
- &query,
- provider,
- &structured_results,
- self.max_results,
- ));
- Ok(result)
- }
-}
-
-#[cfg(test)]
-#[path = "web_search_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/search/tools/web_search_tests.rs b/crates/openhuman-core/src/search/tools/web_search_tests.rs
deleted file mode 100644
index efa78e8fde..0000000000
--- a/crates/openhuman-core/src/search/tools/web_search_tests.rs
+++ /dev/null
@@ -1,718 +0,0 @@
-use super::*;
-use axum::{extract::State, http::HeaderMap, routing::post, Json, Router};
-use serde_json::Value;
-use std::sync::atomic::{AtomicBool, Ordering};
-
-fn tool() -> WebSearchTool {
- WebSearchTool::new(None, None, 5, 15)
-}
-
-async fn start_mock_backend(app: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- format!("http://127.0.0.1:{}", addr.port())
-}
-
-#[test]
-fn test_tool_name() {
- assert_eq!(tool().name(), "web_search_tool");
-}
-
-#[test]
-fn test_tool_description() {
- assert!(tool().description().contains("backend search proxy"));
-}
-
-#[test]
-fn the_schema_offers_an_optional_summary_focus() {
- let schema = tool().parameters_schema();
- let key = crate::inference::tokenjuice::focus::SUMMARY_FOCUS_ARG;
- assert_eq!(schema["properties"][key]["type"], "string");
- assert!(!schema["required"].as_array().unwrap().contains(&json!(key)));
-}
-
-#[test]
-fn test_parameters_schema() {
- let schema = tool().parameters_schema();
- assert_eq!(schema["type"], "object");
- assert!(schema["properties"]["query"].is_object());
-}
-
-#[test]
-fn test_parse_parallel_results_empty() {
- let result = tool()
- .parse_parallel_results(&[], "test query", "Exa")
- .unwrap();
- assert!(result.contains("No results found"));
- // A completed empty search is still attributed, so the timeline labels
- // the row instead of leaving it as in-progress (#5136).
- assert!(result.trim_end().ends_with("(via Exa)"));
-}
-
-#[test]
-fn test_render_markdown_empty_carries_provider() {
- // The markdown rendering is what production shows, so its empty form
- // needs the marker too — and it must sit at the end of the line, where
- // the timeline parser looks for it.
- let result = tool().render_results_markdown(&[], "test query", "Exa");
- assert!(result.contains("No results"));
- assert!(result.trim_end().ends_with("(via Exa)"));
-}
-
-/// A minimal `SearchResponse` carrying only the provider under test, so
-/// the resolution cases read without result/cost noise.
-fn response_with_provider(provider: Option<&str>) -> SearchResponse {
- SearchResponse {
- search_id: "search-1".into(),
- results: vec![],
- cost_usd: 0.0,
- provider: provider.map(str::to_string),
- }
-}
-
-#[test]
-fn test_resolve_managed_provider_defaults_to_exa() {
- // Backend omits the provider → fall back to the managed default.
- assert_eq!(
- resolve_managed_provider(&response_with_provider(None)),
- "Exa"
- );
- // Blank / whitespace-only provider is treated as absent.
- assert_eq!(
- resolve_managed_provider(&response_with_provider(Some(" "))),
- "Exa"
- );
-}
-
-#[test]
-fn test_resolve_managed_provider_uses_backend_value() {
- // A provider named by the backend wins over the default and is trimmed,
- // so a future routing change surfaces without a code edit.
- assert_eq!(
- resolve_managed_provider(&response_with_provider(Some(" Brave "))),
- "Brave"
- );
-}
-
-#[test]
-fn test_parse_parallel_results_attribution_is_dynamic() {
- let results = vec![SearchResultItem {
- title: "T".into(),
- url: "https://t.com".into(),
- publish_date: None,
- excerpts: vec![],
- }];
- let exa = tool().parse_parallel_results(&results, "q", "Exa").unwrap();
- assert!(exa.contains("(via Exa)"));
- assert!(!exa.contains("via backend Parallel"));
- let brave = tool()
- .parse_parallel_results(&results, "q", "Brave")
- .unwrap();
- assert!(brave.contains("(via Brave)"));
-}
-
-#[test]
-fn test_parse_parallel_results_with_data() {
- let results = vec![
- SearchResultItem {
- title: "Parallel AI Docs".into(),
- url: "https://docs.parallel.ai/home".into(),
- publish_date: None,
- excerpts: vec!["Parallel provides infrastructure for AI web search.".into()],
- },
- SearchResultItem {
- title: "Parallel Search Quickstart".into(),
- url: "https://docs.parallel.ai/search".into(),
- publish_date: Some("2024-01-01".into()),
- excerpts: vec!["Use POST /v1beta/search to retrieve results.".into()],
- },
- ];
-
- let result = tool()
- .parse_parallel_results(&results, "parallel ai", "Exa")
- .unwrap();
- assert!(result.contains("(via Exa)"));
- assert!(result.contains("Parallel AI Docs"));
- assert!(result.contains("https://docs.parallel.ai/home"));
- assert!(result.contains("Parallel Search Quickstart"));
- assert!(result.contains("Published: 2024-01-01"));
-}
-
-#[test]
-fn test_parse_parallel_results_respects_max_results() {
- let tool = WebSearchTool::new(None, None, 2, 15);
- let results = vec![
- SearchResultItem {
- title: "Result 1".into(),
- url: "https://a.com".into(),
- publish_date: None,
- excerpts: vec![],
- },
- SearchResultItem {
- title: "Result 2".into(),
- url: "https://b.com".into(),
- publish_date: None,
- excerpts: vec![],
- },
- SearchResultItem {
- title: "Result 3".into(),
- url: "https://c.com".into(),
- publish_date: None,
- excerpts: vec![],
- },
- ];
- let result = tool.parse_parallel_results(&results, "q", "Exa").unwrap();
- assert!(result.contains("Result 1"));
- assert!(result.contains("Result 2"));
- assert!(!result.contains("Result 3"));
-}
-
-#[test]
-fn test_parse_parallel_results_truncates_long_excerpt() {
- let long_excerpt = "x".repeat(600);
- let results = vec![SearchResultItem {
- title: "T".into(),
- url: "https://t.com".into(),
- publish_date: None,
- excerpts: vec![long_excerpt],
- }];
- let result = tool().parse_parallel_results(&results, "q", "Exa").unwrap();
- assert!(result.contains("..."));
- let excerpt_line = result.lines().find(|l| l.trim().starts_with('x')).unwrap();
- assert!(excerpt_line.trim().len() <= 503);
-}
-
-#[test]
-fn test_web_search_truncation_utf8() {
- let excerpt = "🦀".repeat(600);
- let results = vec![SearchResultItem {
- title: "T".into(),
- url: "https://t.com".into(),
- publish_date: None,
- excerpts: vec![excerpt],
- }];
- let result = tool().parse_parallel_results(&results, "q", "Exa").unwrap();
- assert!(result.contains("..."));
- // Should have 500 crabs + "..."
- let excerpt_line = result.lines().find(|l| l.contains('🦀')).unwrap();
- assert_eq!(
- excerpt_line.trim().chars().filter(|c| *c == '🦀').count(),
- 500
- );
-}
-
-#[tokio::test]
-async fn test_execute_missing_query() {
- let result = tool().execute(json!({})).await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn test_execute_empty_query() {
- let result = tool().execute(json!({"query": ""})).await;
- assert!(result.is_err());
-}
-
-#[tokio::test]
-async fn test_execute_without_backend_client() {
- let result = tool().execute(json!({"query": "test"})).await;
- assert!(result.is_err());
- assert!(result
- .unwrap_err()
- .to_string()
- .contains("backend session token"));
-}
-
-#[tokio::test]
-async fn test_execute_posts_to_backend_and_renders_results() {
- #[derive(Clone)]
- struct MockState {
- called: Arc<AtomicBool>,
- }
-
- let state = MockState {
- called: Arc::new(AtomicBool::new(false)),
- };
- let called = Arc::clone(&state.called);
- let app = Router::new()
- .route(
- "/agent-integrations/parallel/search",
- post(
- |State(state): State<MockState>, Json(body): Json<Value>| async move {
- state.called.store(true, Ordering::SeqCst);
- assert_eq!(body["objective"], "test success");
- assert_eq!(body["searchQueries"][0], "test success");
- Json(json!({
- "success": true,
- "data": {
- "searchId": "search-123",
- "results": [
- {
- "url": "https://example.com/result",
- "title": "Backend Search Result",
- "publish_date": "2026-04-20",
- "excerpts": ["Rendered excerpt from backend search."]
- }
- ],
- "costUsd": 0.01
- }
- }))
- },
- ),
- )
- .with_state(state);
-
- let base_url = start_mock_backend(app).await;
- let client = Arc::new(IntegrationClient::new(base_url, "test-token".into()));
- let result = WebSearchTool::new(Some(client), None, 5, 15)
- .execute(json!({"query": "test success"}))
- .await
- .expect("execute() should return rendered backend results");
-
- assert!(called.load(Ordering::SeqCst));
- assert!(result.output().contains("Backend Search Result"));
- assert!(result.output().contains("https://example.com/result"));
- assert!(result
- .output()
- .contains("Rendered excerpt from backend search."));
- // Backend omitted a provider → attribution falls back to the managed
- // default (Exa) rather than the legacy "backend Parallel" wording.
- assert!(result.output().contains("(via Exa)"));
- assert!(!result.output().contains("backend Parallel"));
-}
-
-#[tokio::test]
-async fn test_execute_attributes_backend_reported_provider() {
- // When the backend names the resolved provider, the tool result echoes
- // it verbatim — the attribution is dynamic, not a hardcoded "Exa".
- let app = Router::new().route(
- "/agent-integrations/parallel/search",
- post(|Json(_body): Json<Value>| async move {
- Json(json!({
- "success": true,
- "data": {
- "searchId": "search-xyz",
- "provider": "Brave",
- "results": [
- {
- "url": "https://example.com/r",
- "title": "Result",
- "excerpts": ["Excerpt."]
- }
- ],
- "costUsd": 0.01
- }
- }))
- }),
- );
-
- let base_url = start_mock_backend(app).await;
- let client = Arc::new(IntegrationClient::new(base_url, "test-token".into()));
- let result = WebSearchTool::new(Some(client), None, 5, 15)
- .execute(json!({"query": "anything"}))
- .await
- .expect("execute() should render backend results");
-
- assert!(result.output().contains("(via Brave)"));
- assert!(!result.output().contains("(via Exa)"));
-}
-
-#[tokio::test]
-async fn test_execute_uses_direct_search_api_when_configured() {
- #[derive(Clone)]
- struct MockState {
- called: Arc<AtomicBool>,
- }
-
- let state = MockState {
- called: Arc::new(AtomicBool::new(false)),
- };
- let called = Arc::clone(&state.called);
- let app =
- Router::new()
- .route(
- "/search",
- post(
- |State(state): State<MockState>,
- headers: HeaderMap,
- Json(body): Json<Value>| async move {
- state.called.store(true, Ordering::SeqCst);
- assert_eq!(
- headers.get("x-api-key").and_then(|v| v.to_str().ok()),
- Some("test-key")
- );
- assert_eq!(body["query"], "direct search");
- Json(json!({
- "documents": [
- {
- "url": "https://example.com/direct",
- "title": "Direct Search Result",
- "content": "Rendered excerpt from direct search.",
- "published_date": "2026-04-21"
- }
- ]
- }))
- },
- ),
- )
- .with_state(state);
-
- let base_url = start_mock_backend(app).await;
- let result = WebSearchTool::new(None, None, 5, 15)
- .with_direct_search(Some(SeltzSearchTool::new(
- Some("test-key".into()),
- Some(base_url),
- 5,
- 15,
- )))
- .execute(json!({"query": "direct search"}))
- .await
- .expect("execute() should return rendered direct search results");
-
- assert!(called.load(Ordering::SeqCst));
- assert!(result.output().contains("via Seltz"));
- assert!(result.output().contains("Direct Search Result"));
- assert!(result.output().contains("https://example.com/direct"));
-}
-
-/// Regression for #5873: a cached client whose JWT has been superseded must not
-/// be the one that talks to the backend — the token currently in the credential
-/// store is.
-///
-/// This is the assertion the fix lives or dies on. Point `resolve_client` back
-/// at `self.client` and the backend receives `stale-token`, so the recorded
-/// Authorization header below no longer matches.
-///
-/// Deliberately asserts on the header the *backend actually saw* rather than on
-/// a returned value: the whole failure mode is "the right result arrived over
-/// the wrong credential", which a result-shaped assertion cannot see.
-#[tokio::test]
-async fn test_refreshes_superseded_session_token_before_posting() {
- use crate::config::Config;
- use crate::security::credentials::profiles::{AuthProfile, AuthProfilesStore};
- use crate::security::credentials::APP_SESSION_PROVIDER;
- use std::sync::Mutex;
-
- #[derive(Clone, Default)]
- struct SeenAuth(Arc<Mutex<Option<String>>>);
-
- let seen = SeenAuth::default();
- let app = Router::new()
- .route(
- "/agent-integrations/parallel/search",
- post(
- |State(seen): State<SeenAuth>, headers: HeaderMap, Json(_): Json<Value>| async move {
- *seen.0.lock().expect("auth header mutex") = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(str::to_string);
- Json(json!({
- "success": true,
- "data": { "searchId": "s-1", "results": [], "costUsd": 0.0 }
- }))
- },
- ),
- )
- .with_state(seen.clone());
-
- let base_url = start_mock_backend(app).await;
-
- // Credential store holds the CURRENT session token.
- let tmp = tempfile::tempdir().expect("tempdir");
- AuthProfilesStore::new(tmp.path(), false)
- .upsert_profile(
- AuthProfile::new_token(APP_SESSION_PROVIDER, "default", "fresh-token".to_string()),
- true,
- )
- .expect("seed app-session profile");
-
- let mut config = Config::default();
- // Credentials resolve against `config_path`'s parent, so this is what points
- // `build_client` at the seeded store rather than the operator's real one.
- config.config_path = tmp.path().join("config.toml");
- config.api_url = Some(base_url.clone());
- config.secrets.encrypt = false;
-
- // Cached client carries the token the tool was BUILT with — now superseded.
- let stale = Arc::new(IntegrationClient::new(base_url, "stale-token".to_string()));
-
- let _ = WebSearchTool::new(Some(stale), Some(Arc::new(config)), 5, 15)
- .execute(json!({"query": "who holds the token"}))
- .await;
-
- let seen_auth = seen.0.lock().expect("auth header mutex").clone();
- assert_eq!(
- seen_auth.as_deref(),
- Some("Bearer fresh-token"),
- "the request must carry the token from the credential store, not the \
- superseded one baked into the cached client"
- );
-}
-
-/// The other half of the same branch: when the cached token is still current,
-/// no swap happens and the cached client is reused as-is.
-#[tokio::test]
-async fn test_keeps_cached_client_when_its_token_is_still_current() {
- use crate::config::Config;
- use crate::security::credentials::profiles::{AuthProfile, AuthProfilesStore};
- use crate::security::credentials::APP_SESSION_PROVIDER;
- use std::sync::Mutex;
-
- #[derive(Clone, Default)]
- struct SeenAuth(Arc<Mutex<Option<String>>>);
-
- let seen = SeenAuth::default();
- let app = Router::new()
- .route(
- "/agent-integrations/parallel/search",
- post(
- |State(seen): State<SeenAuth>, headers: HeaderMap, Json(_): Json<Value>| async move {
- *seen.0.lock().expect("auth header mutex") = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(str::to_string);
- Json(json!({
- "success": true,
- "data": { "searchId": "s-1", "results": [], "costUsd": 0.0 }
- }))
- },
- ),
- )
- .with_state(seen.clone());
-
- let base_url = start_mock_backend(app).await;
-
- let tmp = tempfile::tempdir().expect("tempdir");
- AuthProfilesStore::new(tmp.path(), false)
- .upsert_profile(
- AuthProfile::new_token(APP_SESSION_PROVIDER, "default", "same-token".to_string()),
- true,
- )
- .expect("seed app-session profile");
-
- let mut config = Config::default();
- config.config_path = tmp.path().join("config.toml");
- config.api_url = Some(base_url.clone());
- config.secrets.encrypt = false;
-
- // The cached client points at a SEPARATE backend from the one `config`
- // would rebuild against. Both would carry `Bearer same-token`, so asserting
- // on the header alone cannot tell which client was selected — the test
- // would pass even if `resolve_client` rebuilt on every request. Routing
- // them to different mock backends makes the choice observable: only the
- // cached backend may see traffic.
- let cached_seen = SeenAuth::default();
- let cached_app = Router::new()
- .route(
- "/agent-integrations/parallel/search",
- post(
- |State(seen): State<SeenAuth>, headers: HeaderMap, Json(_): Json<Value>| async move {
- *seen.0.lock().expect("cached auth mutex") = headers
- .get("authorization")
- .and_then(|v| v.to_str().ok())
- .map(str::to_string);
- Json(json!({
- "success": true,
- "data": { "searchId": "s-cached", "results": [], "costUsd": 0.0 }
- }))
- },
- ),
- )
- .with_state(cached_seen.clone());
- let cached_url = start_mock_backend(cached_app).await;
-
- let cached = Arc::new(IntegrationClient::new(cached_url, "same-token".to_string()));
-
- let _ = WebSearchTool::new(Some(cached), Some(Arc::new(config)), 5, 15)
- .execute(json!({"query": "unchanged"}))
- .await;
-
- assert_eq!(
- cached_seen.0.lock().expect("cached auth mutex").as_deref(),
- Some("Bearer same-token"),
- "a matching token must keep the CACHED client — its backend must serve the request"
- );
- assert!(
- seen.0.lock().expect("auth header mutex").is_none(),
- "the rebuilt client's backend must never be reached when the tokens match"
- );
-}
-
-/// A tool that outlives a local sign-out must NOT keep posting the bearer token
-/// it was built with.
-///
-/// `build_client` answers `None` only when the store holds no usable
-/// app-session JWT — it logs that case as "user is not signed in". Before the
-/// `root_config.is_some()` guard in `resolve_client`, the `(None, Some(cached))`
-/// arm fell back to the cached client, so a `WebSearchTool` constructed while
-/// signed in would go on making authenticated backend requests with a
-/// credential the user had since revoked locally.
-///
-/// The mock backend here fails the test if it is reached at all: after
-/// sign-out the correct behaviour is to refuse locally, not to send a request
-/// that happens to be rejected remotely.
-#[tokio::test]
-async fn test_signed_out_store_does_not_reuse_the_cached_bearer_token() {
- use crate::config::Config;
- use std::sync::Mutex;
-
- #[derive(Clone, Default)]
- struct Reached(Arc<Mutex<bool>>);
-
- let reached = Reached::default();
- let app = Router::new()
- .route(
- "/agent-integrations/parallel/search",
- post(
- |State(reached): State<Reached>, _headers: HeaderMap, Json(_): Json<Value>| async move {
- *reached.0.lock().expect("reached mutex") = true;
- Json(json!({
- "success": true,
- "data": { "searchId": "s-leak", "results": [], "costUsd": 0.0 }
- }))
- },
- ),
- )
- .with_state(reached.clone());
- let base_url = start_mock_backend(app).await;
-
- // A real config pointing at an EMPTY profile store: no app-session profile
- // is seeded, which is exactly the post-sign-out shape.
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = Config::default();
- config.config_path = tmp.path().join("config.toml");
- config.api_url = Some(base_url.clone());
- config.secrets.encrypt = false;
-
- // The tool still holds the client it was built with while signed in.
- let cached = Arc::new(IntegrationClient::new(
- base_url,
- "revoked-token".to_string(),
- ));
-
- let result = WebSearchTool::new(Some(cached), Some(Arc::new(config)), 5, 15)
- .execute(json!({"query": "after sign out"}))
- .await;
-
- assert!(
- !*reached.0.lock().expect("reached mutex"),
- "no request may be sent after sign-out — the cached bearer token must not be reused"
- );
- assert!(
- result.is_err(),
- "a signed-out tool must fail locally rather than appear to work: {result:?}"
- );
-}
-
-// ── Managed-search quota faults (#5750) ─────────────────────────────────────
-//
-// The managed route resolves to a provider server-side, so an upstream 402/429
-// arrives wrapped in the backend's own 4xx. These cover the classifier that
-// turns that into something a user can act on, and the end-to-end wiring.
-
-#[test]
-fn managed_quota_classifier_matches_exa_credit_exhaustion() {
- // The exact shape reported in #5750.
- let message = concat!(
- "Backend returned 400 Bad Request for POST ",
- "https://api.tinyhumans.ai/agent-integrations/parallel/search: ",
- r#"Exa API error (402): {"error":"You have exceeded your credits limit. "#,
- r#"Please top up to keep using Exa at dashboard.exa.ai","tag":"NO_MORE_CREDITS"}"#
- );
-
- let classified = managed_search_quota_error(message).expect("402 credits fault must classify");
- assert!(classified.contains("shared search credit pool is exhausted"));
- assert!(classified.contains("Connections > Search engine"));
-}
-
-#[test]
-fn managed_quota_classifier_matches_the_tag_alone() {
- // A provider that reports the tag without the numeric status still classifies.
- let classified = managed_search_quota_error(r#"upstream said {"tag":"NO_MORE_CREDITS"}"#)
- .expect("the credits tag alone must classify");
- assert!(classified.contains("credit pool is exhausted"));
-}
-
-#[test]
-fn managed_quota_classifier_matches_rate_limits() {
- for message in [
- "Backend returned 429 Too Many Requests for POST /agent-integrations/parallel/search: slow down",
- "Exa API error (429): {\"error\":\"temporarily unavailable\"}",
- ] {
- let classified =
- managed_search_quota_error(message).expect("rate-limit fault must classify");
- assert!(
- classified.contains("rate limited upstream"),
- "unexpected classification for {message:?}: {classified}"
- );
- }
-}
-
-#[test]
-fn managed_quota_classifier_leaves_unrelated_failures_alone() {
- // Nothing here is a quota fault; each must fall through so the original
- // error (and its detail) reaches the caller unchanged.
- for message in [
- "Backend returned 500 Internal Server Error for POST /x: upstream exploded",
- "Backend returned 404 Not Found for POST /x: no such route",
- // A bare status that happens to appear in a port or id must not match
- // on its own — the classifier requires the word `credit` alongside it.
- "POST http://127.0.0.1:40200/agent-integrations/parallel/search failed: timed out",
- "Web search unavailable: no backend session token.",
- // Quota-looking text in an echoed query must not replace the real
- // failure classification.
- "Backend returned 500 Internal Server Error for POST /x: query=NO_MORE_CREDITS",
- "Backend returned 500 Internal Server Error for POST /x: query=what is HTTP 429",
- "Backend returned 400 Bad Request for POST /x: {\"error\":\"query says rate limit\"}",
- ] {
- assert!(
- managed_search_quota_error(message).is_none(),
- "must not classify as a quota fault: {message:?}"
- );
- }
-}
-
-#[tokio::test]
-async fn test_execute_surfaces_actionable_error_when_managed_credits_are_exhausted() {
- // Replays the #5750 failure: the backend wraps Exa's 402 in a 400, so the
- // tool previously failed with `Backend returned 400 Bad Request …` plus the
- // raw provider JSON.
- let app = Router::new().route(
- "/agent-integrations/parallel/search",
- post(|| async {
- (
- axum::http::StatusCode::BAD_REQUEST,
- Json(json!({
- "success": false,
- "error": concat!(
- r#"Exa API error (402): {"error":"You have exceeded your credits "#,
- r#"limit for query: private search","tag":"NO_MORE_CREDITS"}"#
- )
- })),
- )
- }),
- );
-
- let base_url = start_mock_backend(app).await;
- let client = Arc::new(IntegrationClient::new(base_url, "test-token".into()));
- let error = WebSearchTool::new(Some(client), None, 5, 15)
- .execute(json!({"query": "private search"}))
- .await
- .expect_err("an exhausted managed credit pool must fail with an actionable message");
- let message = error.to_string();
-
- assert!(
- message.contains("shared search credit pool is exhausted"),
- "expected the actionable message, got: {message}"
- );
- assert!(message.contains("Connections > Search engine"));
- // The replacement carries none of the provider's body, which echoes the query.
- assert!(
- !message.contains("private search"),
- "the submitted query must not reach the transcript: {message}"
- );
- assert!(!message.contains("Backend returned 400"));
-}