Skip to content

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

feat: configure TinySearch module host

Steven Enamakelad75bacc178e
diff --git a/Cargo.lock b/Cargo.lock
index 837b1b7ac9..54b00ae7f6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -3936,6 +3936,7 @@ dependencies = [
"tinymemory-conformance",
"tinymemory-sources",
"tinyruntime-bus",
+ "tinysearch-bus",
"tinyskills",
"tinytools 0.4.1",
"tinytools-agent 0.4.1",
@@ -6782,6 +6783,14 @@ dependencies = [
"serde_json",
]
+[[package]]
+name = "tinysearch-bus"
+version = "0.2.1"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
[[package]]
name = "tinyskills"
version = "0.2.2"
diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.toml
index c4528cc199..3f3f120e38 100644
--- a/crates/openhuman-core/Cargo.toml
+++ b/crates/openhuman-core/Cargo.toml
@@ -332,6 +332,7 @@ tinychannels = { version = "0.1", features = ["relay-websocket"], optional = tru
# --features flows` would carry `ureq` and the archive stack for a host that
# never loads a module. The kernel-floor ratchet catches exactly that, and did.
tinybus = { path = "../../vendor/tinybus/crates/tinybus", default-features = false, features = ["macros", "uds"] }
+tinysearch-bus = { path = "../../vendor/tinysearch/crates/tinysearch-bus", optional = true }
tinydesktop-bus = { path = "../../vendor/tinydesktop/crates/tinydesktop-bus", optional = true }
tinybrowser-bus = { path = "../../vendor/tinybrowser/crates/tinybrowser-bus" }
tinybrowser-control = { path = "../../vendor/tinybrowser/crates/tinybrowser-control", default-features = false }
@@ -864,7 +865,7 @@ hosting = ["dep:tinyhosts"]
# A loaded module is trusted in-process code with this process's privileges, and
# tinybus never unloads one. See `crates/openhuman-core/src/modules/` before adding an entry
# to the registry.
-modules = ["tinybus/modules", "dep:tinydesktop-bus"]
+modules = ["tinybus/modules", "dep:tinydesktop-bus", "dep:tinysearch-bus"]
# Voice + audio_toolkit domains: STT/TTS providers, the standalone dictation
# server, always-on listening, and podcast audio generation/email delivery.
# Default-ON — the desktop app always ships with voice. Slim / headless builds
diff --git a/crates/openhuman-core/src/config/ops/README.md b/crates/openhuman-core/src/config/ops/README.md
index 14349c8cad..079ae786b3 100644
--- a/crates/openhuman-core/src/config/ops/README.md
+++ b/crates/openhuman-core/src/config/ops/README.md
@@ -23,7 +23,7 @@ fn, which returns `RpcOutcome<T>`.
Each submodule follows the same shape: a `*SettingsPatch` struct with
`Option<T>` fields (`None` = unchanged); an `apply_*(&mut Config, patch)` fn
that mutates the given config, calls `Config::save()`, and returns the
-snapshot; a `load_and_apply_*(patch)` wrapper that calls
+settings or snapshot; a `load_and_apply_*(patch)` wrapper that calls
`load_config_with_timeout` first; and a `get_*` fn that reads the relevant
section back out, usually as `RpcOutcome<serde_json::Value>`. `ui.rs`'s
dictation and voice-server mutators exist only in `load_and_apply_*` form.
@@ -56,6 +56,18 @@ dictation and voice-server mutators exist only in `load_and_apply_*` form.
`workspace_onboarding_flag_exists` / `workspace_onboarding_flag_set` /
`workspace_onboarding_flag_resolve`.
+## Search settings
+
+`apply_search_settings` accepts a global `enabled` switch, an explicit
+`enabled_providers` set, a presentation mode (`all_tools`, `router`, or
+`one_provider`), and direct/backend routes for Parallel and Gemini. Omitting
+`enabled_providers` migrates from saved keys, a current backend credential,
+and the separate TinyFish, Seltz, and SearXNG toggles. An explicit empty list
+selects no providers. The old `engine = "disabled"` setting still disables
+search. Both `get_search_settings` and the update response report only key
+presence booleans, never raw credentials. After saving, an already loaded
+TinySearch module is refreshed with a private configuration payload.
+
## Security-relevant behavior
- `apply_autonomy_settings` is the single write path for `[autonomy]`: after
diff --git a/crates/openhuman-core/src/config/ops/loader/snapshot.rs b/crates/openhuman-core/src/config/ops/loader/snapshot.rs
index 343f78e007..dd5738a8e4 100644
--- a/crates/openhuman-core/src/config/ops/loader/snapshot.rs
+++ b/crates/openhuman-core/src/config/ops/loader/snapshot.rs
@@ -8,7 +8,13 @@ use crate::rpc::RpcOutcome;
/// Serializes the current configuration into a JSON snapshot for the UI.
pub fn snapshot_config_json(config: &Config) -> Result<serde_json::Value, String> {
- let value = serde_json::to_value(config).map_err(|e| e.to_string())?;
+ let mut value = serde_json::to_value(config).map_err(|e| e.to_string())?;
+ // The full snapshot is sent over RPC. Keep search settings visible while
+ // removing credentials, including the legacy Seltz key.
+ for provider in ["parallel", "brave", "querit", "exa", "tavily", "gemini"] {
+ value["search"][provider]["api_key"] = serde_json::Value::Null;
+ }
+ value["seltz"]["api_key"] = serde_json::Value::Null;
#[cfg(feature = "modules")]
let browser_billing_route = match crate::modules::browser_task::billing_route(config) {
crate::modules::browser_task::BillingRoute::DirectOpenRouter => "direct_openrouter",
diff --git a/crates/openhuman-core/src/config/ops/ui.rs b/crates/openhuman-core/src/config/ops/ui.rs
index ad3a20a727..d5adb269fc 100644
--- a/crates/openhuman-core/src/config/ops/ui.rs
+++ b/crates/openhuman-core/src/config/ops/ui.rs
@@ -30,6 +30,13 @@ pub struct AnalyticsSettingsPatch {
#[derive(Debug, Clone, Default)]
pub struct SearchSettingsPatch {
+ pub enabled: Option<bool>,
+ pub enabled_providers: Option<Vec<String>>,
+ pub presentation: Option<String>,
+ pub presentation_provider: Option<String>,
+ pub parallel_route: Option<String>,
+ pub gemini_route: Option<String>,
+ pub gemini_api_key: Option<String>,
/// One of `disabled` | `managed` | `parallel` | `brave` | `querit` |
/// `exa` | `tavily`.
/// Empty/unknown values are rejected by `apply_search_settings`.
@@ -228,6 +235,9 @@ pub async fn apply_search_settings(
match trimmed {
"disabled" | "managed" | "parallel" | "brave" | "querit" | "exa" | "tavily" => {
config.search.engine = trimmed.to_string();
+ if update.enabled.is_none() {
+ config.search.enabled = Some(trimmed != "disabled");
+ }
}
other => {
return Err(format!(
@@ -236,6 +246,49 @@ pub async fn apply_search_settings(
}
}
}
+ if let Some(enabled) = update.enabled {
+ config.search.enabled = Some(enabled);
+ }
+ if let Some(providers) = update.enabled_providers {
+ let mut selected = std::collections::BTreeSet::new();
+ for raw in providers {
+ let name = raw.trim().to_ascii_lowercase();
+ if !crate::config::schema::SEARCH_PROVIDERS.contains(&name.as_str()) {
+ return Err(format!("unknown search provider: {name}"));
+ }
+ selected.insert(name);
+ }
+ config.search.enabled_providers = Some(selected);
+ }
+ if let Some(mode) = update.presentation {
+ if !["all_tools", "router", "one_provider"].contains(&mode.as_str()) {
+ return Err("presentation must be all_tools/router/one_provider".into());
+ }
+ config.search.presentation = mode;
+ }
+ if let Some(provider) = update.presentation_provider {
+ let provider = provider.trim().to_ascii_lowercase();
+ if !provider.is_empty()
+ && !crate::config::schema::SEARCH_PROVIDERS.contains(&provider.as_str())
+ {
+ return Err(format!("unknown search presentation provider: {provider}"));
+ }
+ config.search.presentation_provider = (!provider.is_empty()).then_some(provider);
+ }
+ for (route, target) in [
+ (update.parallel_route, &mut config.search.parallel_route),
+ (update.gemini_route, &mut config.search.gemini_route),
+ ] {
+ if let Some(route) = route {
+ if route != "direct" && route != "backend" {
+ return Err("search route must be direct or backend".into());
+ }
+ *target = route;
+ }
+ }
+ if let Some(key) = update.gemini_api_key {
+ config.search.gemini.api_key = nonempty(key);
+ }
if let Some(n) = update.max_results {
if !(1..=20).contains(&n) {
return Err(format!("max_results must be between 1 and 20 (got {n})"));
@@ -322,7 +375,9 @@ pub async fn apply_search_settings(
);
}
config.save().await.map_err(|e| e.to_string())?;
- let snapshot = snapshot_config_json(config)?;
+ #[cfg(feature = "modules")]
+ crate::modules::search::refresh_loaded(config).await?;
+ let snapshot = search_settings_json(config);
Ok(RpcOutcome::new(
snapshot,
vec![format!(
@@ -339,22 +394,28 @@ pub async fn load_and_apply_search_settings(
apply_search_settings(&mut config, update).await
}
-/// Read the current search engine settings (with API keys redacted to a
-/// presence boolean so the UI can show "configured" without ever rendering
-/// the raw secret).
-pub async fn get_search_settings() -> Result<RpcOutcome<serde_json::Value>, String> {
- let config = load_config_with_timeout().await?;
- let result = serde_json::json!({
+fn search_settings_json(config: &Config) -> serde_json::Value {
+ let credential_available =
+ crate::security::credentials::session_support::resolve_backend_credential(config).is_ok();
+ serde_json::json!({
+ "enabled": config.search.is_enabled(),
+ "enabled_providers": config.search.providers(credential_available, config.integrations.tinyfish.is_active(), config.seltz.enabled && config.seltz.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()), config.searxng.enabled),
"engine": config.search.requested_engine_str(),
- "effective_engine": match config.search.effective_engine() {
- crate::config::SearchEngine::Disabled => "disabled",
- crate::config::SearchEngine::Managed => "managed",
- crate::config::SearchEngine::Parallel => "parallel",
- crate::config::SearchEngine::Brave => "brave",
- crate::config::SearchEngine::Querit => "querit",
- crate::config::SearchEngine::Exa => "exa",
- crate::config::SearchEngine::Tavily => "tavily",
- },
+ "effective_engine": if config.search.is_enabled() {
+ match config.search.effective_engine() {
+ crate::config::SearchEngine::Disabled => "disabled",
+ crate::config::SearchEngine::Managed => "managed",
+ crate::config::SearchEngine::Parallel => "parallel",
+ crate::config::SearchEngine::Brave => "brave",
+ crate::config::SearchEngine::Querit => "querit",
+ crate::config::SearchEngine::Exa => "exa",
+ crate::config::SearchEngine::Tavily => "tavily",
+ }
+ } else { "disabled" },
+ "presentation": config.search.presentation,
+ "presentation_provider": config.search.presentation_provider,
+ "parallel_route": config.search.parallel_route,
+ "gemini_route": config.search.gemini_route,
"max_results": config.search.max_results,
"timeout_secs": config.search.timeout_secs,
"parallel_configured": config.search.parallel.has_key(),
@@ -362,9 +423,22 @@ pub async fn get_search_settings() -> Result<RpcOutcome<serde_json::Value>, Stri
"querit_configured": config.search.querit.has_key(),
"exa_configured": config.search.exa.has_key(),
"tavily_configured": config.search.tavily.has_key(),
+ "gemini_configured": config.search.gemini.has_key(),
+ "managed_configured": credential_available,
+ "tinyfish_enabled": config.integrations.tinyfish.is_active(),
+ "seltz_configured": config.seltz.api_key.as_deref().is_some_and(|key| !key.trim().is_empty()),
+ "searxng_configured": !config.searxng.base_url.trim().is_empty(),
"allowed_domains": config.http_request.allowed_domains,
"allow_all": config.http_request.allowed_domains.iter().any(|d| d == "*"),
- });
+ })
+}
+
+/// Read the current search engine settings (with API keys redacted to a
+/// presence boolean so the UI can show "configured" without ever rendering
+/// the raw secret).
+pub async fn get_search_settings() -> Result<RpcOutcome<serde_json::Value>, String> {
+ let config = load_config_with_timeout().await?;
+ let result = search_settings_json(&config);
Ok(RpcOutcome::new(
result,
vec!["search settings read".to_string()],
diff --git a/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs b/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs
index b23f2a4808..865c090020 100644
--- a/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs
+++ b/crates/openhuman-core/src/config/ops_loader_and_search_tests.rs
@@ -331,6 +331,27 @@ fn snapshot_config_json_emits_config_and_workspace_and_config_path() {
assert!(ws.contains(tmp.path().to_str().unwrap_or("")));
}
+#[test]
+fn snapshot_config_json_redacts_every_search_key_but_keeps_settings() {
+ let mut cfg = Config::default();
+ cfg.search.max_results = 13;
+ cfg.search.parallel.api_key = Some("parallel-sentinel".into());
+ cfg.search.brave.api_key = Some("brave-sentinel".into());
+ cfg.search.querit.api_key = Some("querit-sentinel".into());
+ cfg.search.exa.api_key = Some("exa-sentinel".into());
+ cfg.search.tavily.api_key = Some("tavily-sentinel".into());
+ cfg.search.gemini.api_key = Some("gemini-sentinel".into());
+ cfg.seltz.api_key = Some("seltz-sentinel".into());
+ let snapshot = snapshot_config_json(&cfg).unwrap();
+ let serialized = snapshot.to_string();
+ assert!(!serialized.contains("-sentinel"));
+ assert_eq!(snapshot["config"]["search"]["max_results"], 13);
+ for provider in ["parallel", "brave", "querit", "exa", "tavily", "gemini"] {
+ assert!(snapshot["config"]["search"][provider]["api_key"].is_null());
+ }
+ assert!(snapshot["config"]["seltz"]["api_key"].is_null());
+}
+
// ── agent_server_status ────────────────────────────────────────
#[test]
@@ -613,7 +634,7 @@ async fn apply_search_settings_stores_and_clears_tavily_key() {
let tmp = tempdir().unwrap();
let mut cfg = tmp_config(&tmp);
- apply_search_settings(
+ let result = apply_search_settings(
&mut cfg,
SearchSettingsPatch {
engine: Some("tavily".to_string()),
@@ -623,6 +644,8 @@ async fn apply_search_settings_stores_and_clears_tavily_key() {
)
.await
.expect("save Tavily settings");
+ assert_eq!(result.value["tavily_configured"], true);
+ assert!(!result.value.to_string().contains("tvly-test-key"));
assert_eq!(cfg.search.engine, "tavily");
assert_eq!(cfg.search.tavily.api_key.as_deref(), Some("tvly-test-key"));
diff --git a/crates/openhuman-core/src/config/schema/README.md b/crates/openhuman-core/src/config/schema/README.md
index 77e63cba36..5ad3f75b70 100644
--- a/crates/openhuman-core/src/config/schema/README.md
+++ b/crates/openhuman-core/src/config/schema/README.md
@@ -62,6 +62,12 @@ is mounted as a submodule of `load/dirs.rs` via `#[path]`.
`mcp.rs` (`McpServerConfig`, `McpClientConfig`, `GitbooksConfig`),
`multimodal.rs` (`MultimodalConfig`, `MultimodalFileConfig`), `search.rs`
(`SearchConfig`, `WebSearchConfig`, `SearxngConfig`, `SeltzConfig`).
+`SearchConfig.enabled_providers` is an explicit provider set. When omitted,
+legacy settings enable providers with saved keys, the managed backend when a
+credential is available, and the separate TinyFish/Seltz/SearXNG toggles.
+`engine = "disabled"` still disables search. TinySearch uses one route per
+provider: explicit direct Parallel wins over managed backend Parallel when
+both are selected.
Most sections have a matching `*_tests.rs` (some further split into several
`*_tests.rs` siblings, e.g. `types_model_pin_tests.rs`); this is the repo's
diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs
index cc490f9f1f..b9747099f1 100644
--- a/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs
+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/search.rs
@@ -65,6 +65,39 @@ impl Config {
}
}
+ if let Some(flag) = env.get_any(&["OPENHUMAN_SEARCH_ENABLED"]) {
+ if let Some(enabled) = parse_env_bool("OPENHUMAN_SEARCH_ENABLED", &flag) {
+ self.search.enabled = Some(enabled);
+ }
+ }
+ if let Some(names) = env.get_any(&["OPENHUMAN_SEARCH_PROVIDERS"]) {
+ let selected: std::collections::BTreeSet<String> = names
+ .split(',')
+ .map(|name| name.trim().to_ascii_lowercase())
+ .filter(|name| crate::config::schema::SEARCH_PROVIDERS.contains(&name.as_str()))
+ .collect();
+ self.search.enabled_providers = Some(selected);
+ }
+ if let Some(mode) = env.get_any(&["OPENHUMAN_SEARCH_PRESENTATION"]) {
+ if ["all_tools", "router", "one_provider"].contains(&mode.as_str()) {
+ self.search.presentation = mode;
+ }
+ }
+ for (name, route) in [
+ ("OPENHUMAN_PARALLEL_ROUTE", &mut self.search.parallel_route),
+ ("OPENHUMAN_GEMINI_ROUTE", &mut self.search.gemini_route),
+ ] {
+ if let Some(value) = env.get_any(&[name]) {
+ if value == "direct" || value == "backend" {
+ *route = value;
+ }
+ }
+ }
+ if let Some(key) = env.get_any(&["OPENHUMAN_GEMINI_API_KEY", "GEMINI_API_KEY"]) {
+ if !key.trim().is_empty() {
+ self.search.gemini.api_key = Some(key);
+ }
+ }
if let Some(engine) = env.get_any(&["OPENHUMAN_SEARCH_ENGINE", "SEARCH_ENGINE"]) {
let engine = engine.trim().to_ascii_lowercase();
if !engine.is_empty() {
diff --git a/crates/openhuman-core/src/config/schema/load/secrets.rs b/crates/openhuman-core/src/config/schema/load/secrets.rs
index 4eccd81a0b..dabb975fc3 100644
--- a/crates/openhuman-core/src/config/schema/load/secrets.rs
+++ b/crates/openhuman-core/src/config/schema/load/secrets.rs
@@ -123,6 +123,11 @@ pub(super) fn decrypt_config_secrets(config: &mut Config, openhuman_dir: &Path)
&mut config.search.tavily.api_key,
"search.tavily.api_key",
)?;
+ decrypt_optional_secret(
+ &store,
+ &mut config.search.gemini.api_key,
+ "search.gemini.api_key",
+ )?;
let ch = &mut config.channels_config;
if let Some(ref mut tg) = ch.telegram {
@@ -232,6 +237,11 @@ pub(super) fn encrypt_config_secrets(config: &mut Config) -> Result<()> {
&mut config.search.tavily.api_key,
"search.tavily.api_key",
)?;
+ encrypt_optional_secret(
+ &store,
+ &mut config.search.gemini.api_key,
+ "search.gemini.api_key",
+ )?;
let ch = &mut config.channels_config;
if let Some(ref mut tg) = ch.telegram {
@@ -302,3 +312,27 @@ pub(super) fn encrypt_config_secrets(config: &mut Config) -> Result<()> {
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn gemini_key_round_trips_with_encryption_enabled() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = Config::default();
+ config.config_path = dir.path().join("config.toml");
+ config.secrets.encrypt = true;
+ config.search.gemini.api_key = Some("gemini-sentinel".into());
+
+ encrypt_config_secrets(&mut config).unwrap();
+ let ciphertext = config.search.gemini.api_key.as_deref().unwrap();
+ assert!(ciphertext.starts_with("enc2:"));
+ assert!(!ciphertext.contains("gemini-sentinel"));
+ assert!(!decrypt_config_secrets(&mut config, dir.path()).unwrap());
+ assert_eq!(
+ config.search.gemini.api_key.as_deref(),
+ Some("gemini-sentinel")
+ );
+ }
+}
diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rs
index 2e1a613ea6..65f9511222 100644
--- a/crates/openhuman-core/src/config/schema/mod.rs
+++ b/crates/openhuman-core/src/config/schema/mod.rs
@@ -123,7 +123,7 @@ pub use tools::{
BrowserComputerUseConfig, BrowserConfig, ComposioConfig, CurlConfig, GitbooksConfig,
HttpHeader, HttpRequestConfig, IntegrationToggle, IntegrationsConfig, McpAuthConfig,
McpClientConfig, McpClientIdentityConfig, McpServerConfig, MultimodalConfig,
- MultimodalFileConfig, SearchConfig, SearchEngine, SearchEngineCredentials, SearxngConfig,
+ MultimodalFileConfig, SearchConfig, SearchEngine, SearchEngineCredentials, SearxngConfig, SEARCH_PROVIDERS,
SecretsConfig, SeltzConfig, WebSearchConfig, COMPOSIO_MODE_BACKEND, COMPOSIO_MODE_DIRECT,
SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA, SEARCH_ENGINE_MANAGED,
SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY,
diff --git a/crates/openhuman-core/src/config/schema/tools/mod.rs b/crates/openhuman-core/src/config/schema/tools/mod.rs
index 65cd794298..0c496115aa 100644
--- a/crates/openhuman-core/src/config/schema/tools/mod.rs
+++ b/crates/openhuman-core/src/config/schema/tools/mod.rs
@@ -22,4 +22,5 @@ pub use search::{
SearchConfig, SearchEngine, SearchEngineCredentials, SearxngConfig, SeltzConfig,
WebSearchConfig, SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA,
SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY,
+ SEARCH_PROVIDERS,
};
diff --git a/crates/openhuman-core/src/config/schema/tools/search.rs b/crates/openhuman-core/src/config/schema/tools/search.rs
index 3e83b5dd5a..cf866aa74c 100644
--- a/crates/openhuman-core/src/config/schema/tools/search.rs
+++ b/crates/openhuman-core/src/config/schema/tools/search.rs
@@ -1,7 +1,8 @@
-//! Search engine config: Seltz, SearXNG, web search, and unified search selector.
+//! Search settings, legacy engine migration, and separate Seltz/SearXNG options.
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
+use std::collections::BTreeSet;
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
@@ -179,11 +180,9 @@ impl SearchEngineCredentials {
}
}
-/// Unified search-engine configuration. Exactly one engine drives tool
-/// registration at a time. `disabled` suppresses all search tools; `managed` is
-/// the backend-proxied default and requires no key; `parallel`, `brave`,
-/// `querit`, `exa`, and `tavily` are BYO and require their own API key in the
-/// matching sub-block.
+/// Search configuration. New settings select a provider set; an omitted set
+/// derives available providers from saved keys, the backend credential, and
+/// the separate TinyFish toggle. The legacy engine remains for migration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct SearchConfig {
@@ -195,6 +194,30 @@ pub struct SearchConfig {
#[serde(default = "default_search_engine")]
pub engine: String,
+ /// Explicit global switch. Missing in older config files, where `engine`
+ /// still decides whether search was disabled.
+ #[serde(default)]
+ pub enabled: Option<bool>,
+ /// Explicit provider selection. Missing migrates from saved credentials
+ /// and the legacy TinyFish integration toggle. When present, this set is
+ /// authoritative, including for TinyFish.
+ /// Managed and direct Parallel share one module route; explicit Parallel
+ /// selection takes precedence when both are selected.
+ #[serde(default)]
+ pub enabled_providers: Option<BTreeSet<String>>,
+ /// `all_tools`, `router`, or `one_provider`.
+ #[serde(default = "default_search_presentation")]
+ pub presentation: String,
+ /// Provider used by `one_provider`, or router default.
+ #[serde(default)]
+ pub presentation_provider: Option<String>,
+ /// `direct` or `backend` for Parallel.
+ #[serde(default = "default_direct_route")]
+ pub parallel_route: String,
+ /// `direct` or `backend` for Gemini.
+ #[serde(default = "default_direct_route")]
+ pub gemini_route: String,
+
/// Max results per query (1–20, default 5).
#[serde(default = "default_search_max_results")]
pub max_results: usize,
@@ -225,12 +248,34 @@ pub struct SearchConfig {
/// the managed backend.
#[serde(default)]
pub tavily: SearchEngineCredentials,
+
+ /// Gemini direct API credential.
+ #[serde(default)]
+ pub gemini: SearchEngineCredentials,
}
+fn default_search_presentation() -> String {
+ "all_tools".into()
+}
+fn default_direct_route() -> String {
+ "direct".into()
+}
+
+pub const SEARCH_PROVIDERS: &[&str] = &[
+ "managed", "parallel", "brave", "querit", "exa", "tavily", "gemini", "tinyfish", "seltz",
+ "searxng",
+];
+
impl Default for SearchConfig {
fn default() -> Self {
Self {
engine: default_search_engine(),
+ enabled: None,
+ enabled_providers: None,
+ presentation: default_search_presentation(),
+ presentation_provider: None,
+ parallel_route: default_direct_route(),
+ gemini_route: default_direct_route(),
max_results: default_search_max_results(),
timeout_secs: default_search_timeout_secs(),
parallel: SearchEngineCredentials::default(),
@@ -238,6 +283,7 @@ impl Default for SearchConfig {
querit: SearchEngineCredentials::default(),
exa: SearchEngineCredentials::default(),
tavily: SearchEngineCredentials::default(),
+ gemini: SearchEngineCredentials::default(),
}
}
}
@@ -257,6 +303,53 @@ pub enum SearchEngine {
}
impl SearchConfig {
+ pub fn is_enabled(&self) -> bool {
+ self.enabled
+ .unwrap_or(self.engine.trim() != SEARCH_ENGINE_DISABLED)
+ }
+
+ /// Resolve provider selections. `None` is the old single-engine format.
+ pub fn providers(
+ &self,
+ managed_available: bool,
+ tinyfish_enabled: bool,
+ seltz_enabled: bool,
+ searxng_enabled: bool,
+ ) -> BTreeSet<String> {
+ if !self.is_enabled() {
+ return BTreeSet::new();
+ }
+ if let Some(selected) = &self.enabled_providers {
+ return selected.clone();
+ }
+ let mut providers = BTreeSet::new();
+ if managed_available {
+ providers.insert("managed".into());
+ }
+ for (name, credentials) in [
+ ("parallel", &self.parallel),
+ ("brave", &self.brave),
+ ("querit", &self.querit),
+ ("exa", &self.exa),
+ ("tavily", &self.tavily),
+ ("gemini", &self.gemini),
+ ] {
+ if credentials.has_key() {
+ providers.insert(name.into());
+ }
+ }
+ if tinyfish_enabled {
+ providers.insert("tinyfish".into());
+ }
+ if seltz_enabled {
+ providers.insert("seltz".into());
+ }
+ if searxng_enabled {
+ providers.insert("searxng".into());
+ }
+ providers
+ }
+
/// Resolve the *effective* engine after gating on API-key
/// availability. A BYO engine without a key silently falls back to
/// managed so the agent never ends up with zero search tools — the
diff --git a/crates/openhuman-core/src/config/schema/tools/search_search_config_tests_tests.rs b/crates/openhuman-core/src/config/schema/tools/search_search_config_tests_tests.rs
index efff62090f..f4912c0e98 100644
--- a/crates/openhuman-core/src/config/schema/tools/search_search_config_tests_tests.rs
+++ b/crates/openhuman-core/src/config/schema/tools/search_search_config_tests_tests.rs
@@ -112,3 +112,38 @@ fn unknown_engine_falls_back_to_managed() {
};
assert_eq!(cfg.effective_engine(), SearchEngine::Managed);
}
+
+#[test]
+fn legacy_disabled_and_key_migration() {
+ let cfg: SearchConfig =
+ toml::from_str("engine = 'disabled'\n[parallel]\napi_key = 'secret'").unwrap();
+ assert!(!cfg.is_enabled());
+ assert!(cfg.providers(true, false, false, false).is_empty());
+ let cfg: SearchConfig = toml::from_str("[parallel]\napi_key = 'secret'").unwrap();
+ assert_eq!(
+ cfg.providers(true, true, false, false),
+ ["managed", "parallel", "tinyfish"]
+ .into_iter()
+ .map(str::to_string)
+ .collect()
+ );
+}
+
+#[test]
+fn explicit_provider_selection_overrides_migration() {
+ let cfg: SearchConfig = toml::from_str(
+ "enabled = true\nenabled_providers = ['gemini']\n[parallel]\napi_key = 'secret'",
+ )
+ .unwrap();
+ assert_eq!(
+ cfg.providers(true, false, false, false),
+ ["gemini".to_string()].into()
+ );
+}
+
+#[test]
+fn separate_legacy_providers_migrate_when_enabled() {
+ let cfg = SearchConfig::default();
+ assert!(cfg.providers(false, false, true, true).contains("seltz"));
+ assert!(cfg.providers(false, false, true, true).contains("searxng"));
+}
diff --git a/crates/openhuman-core/src/config/schemas/controllers/integrations.rs b/crates/openhuman-core/src/config/schemas/controllers/integrations.rs
index 70a1380503..04216f101c 100644
--- a/crates/openhuman-core/src/config/schemas/controllers/integrations.rs
+++ b/crates/openhuman-core/src/config/schemas/controllers/integrations.rs
@@ -20,6 +20,13 @@ pub(super) fn handle_update_search_settings(params: Map<String, Value>) -> Contr
}
};
let patch = config_rpc::SearchSettingsPatch {
+ enabled: update.enabled,
+ enabled_providers: update.enabled_providers,
+ presentation: update.presentation,
+ presentation_provider: update.presentation_provider,
+ parallel_route: update.parallel_route,
+ gemini_route: update.gemini_route,
+ gemini_api_key: update.gemini_api_key,
engine: update.engine,
max_results: update.max_results,
timeout_secs: update.timeout_secs,
diff --git a/crates/openhuman-core/src/config/schemas/helpers.rs b/crates/openhuman-core/src/config/schemas/helpers.rs
index 4cf41fc8cd..47ad87cadf 100644
--- a/crates/openhuman-core/src/config/schemas/helpers.rs
+++ b/crates/openhuman-core/src/config/schemas/helpers.rs
@@ -113,6 +113,13 @@ pub(super) struct AnalyticsSettingsUpdate {
#[derive(Debug, Deserialize)]
pub(super) struct SearchSettingsUpdate {
+ pub(super) enabled: Option<bool>,
+ pub(super) enabled_providers: Option<Vec<String>>,
+ pub(super) presentation: Option<String>,
+ pub(super) presentation_provider: Option<String>,
+ pub(super) parallel_route: Option<String>,
+ pub(super) gemini_route: Option<String>,
+ pub(super) gemini_api_key: Option<String>,
pub(super) engine: Option<String>,
pub(super) max_results: Option<usize>,
pub(super) timeout_secs: Option<u64>,
diff --git a/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rs b/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rs
index 49ff42f734..2769cb1e88 100644
--- a/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rs
+++ b/crates/openhuman-core/src/config/schemas/schema_defs/integrations.rs
@@ -9,11 +9,18 @@ pub(super) fn lookup(function: &str) -> Option<ControllerSchema> {
"update_search_settings" => Some( ControllerSchema {
namespace: "config",
function: "update_search_settings",
- description: "Update search engine selection and BYO API credentials.",
+ description: "Update search providers, presentation, routes, and private API credentials.",
inputs: vec![
+ optional_bool("enabled", "Whether TinySearch is enabled globally."),
+ FieldSchema { name: "enabled_providers", ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(TypeSchema::String)))), comment: "Selected search providers; empty list disables all providers. Managed and direct Parallel share one route; explicit Parallel takes precedence.", required: false },
+ optional_string("presentation", "all_tools | router | one_provider."),
+ optional_string("presentation_provider", "Provider selected for one_provider or router default."),
+ optional_string("parallel_route", "direct | backend."),
+ optional_string("gemini_route", "direct | backend."),
+ optional_string("gemini_api_key", "Gemini direct API key (empty string clears)."),
optional_string(
"engine",
- "Active engine: disabled | managed | parallel | brave | querit | exa | tavily.",
+ "Legacy engine selector; disabled still disables search.",
),
FieldSchema {
name: "max_results",
diff --git a/crates/openhuman-core/src/modules/README.md b/crates/openhuman-core/src/modules/README.md
index c841f340f4..5f13777d56 100644
--- a/crates/openhuman-core/src/modules/README.md
+++ b/crates/openhuman-core/src/modules/README.md
@@ -3,7 +3,7 @@
The native loadable-module host. A module is a first-party `cdylib` — `tinydocs`,
`tinywallet`, `tinymemory`, `tinyjuice`, `tinyvoice`, `tinyruntime` (+
`tinyruntime-nodejs` / `tinyruntime-python`), `tinymcp`, `tinyconnectors`,
-`tinybox`, `tinychannels`, `tinyhosts` — that
+`tinybox`, `tinychannels`, `tinyhosts`, `tinysearch` — that
speaks the tinybus module ABI. It is downloaded from a pinned GitHub release,
verified against a digest compiled into [`registry.rs`](registry.rs), admitted
through tinybus's ABI/manifest gates, and attached to a private in-process
@@ -25,7 +25,7 @@ directory on `modules`.
| Path | Purpose |
| --- | --- |
| `mod.rs` | Module rustdoc for the whole loading model; re-exports |
-| `registry.rs` (+ `registry/records_browser.rs`, `registry/records_docs_wallet.rs`, `registry/records_extra.rs`, `registry/records_mcp_connectors.rs`, `registry/records_memory_juice.rs`, `registry/records_runtime.rs`, `registry/records_voice.rs`) | The compiled-in table: every `ModuleRecord`, its published per-platform digests, and `find`/`ALL` |
+| `registry.rs` (+ `registry/records_browser.rs`, `registry/records_docs_wallet.rs`, `registry/records_extra.rs`, `registry/records_mcp_connectors.rs`, `registry/records_memory_juice.rs`, `registry/records_runtime.rs`, `registry/records_voice.rs`, `registry/records_search.rs`) | The compiled-in table: every `ModuleRecord`, its published per-platform digests, and `find`/`ALL` |
| `platform.rs` | Which published artifact (`ubuntu-24.04-x86_64`, `macos-15-arm64`, ...) belongs to this host, newest-compatible first |
| `types.rs` | `LoadPolicy`, `ModuleRecord`, `ModuleSource`, `ModuleState`, `ModuleStatus`, `PlatformAsset` |
| `host.rs` | The module broker: a dedicated process-lifetime tokio runtime, its `ModuleHost`, and the host's own `Connection` for calling into loaded modules |
@@ -42,6 +42,7 @@ directory on `modules`.
| `memory_host.rs` | Host-owned callbacks served *to* the TinyMemory module: `EmbeddingHost`, `ChatHost`, `ComposioHost`, and `RuntimeHost` (event publishing, error reporting, scheduler policy, spaCy); sole survivor of the `host_impls` pair after the in-process engine left (openhuman#6161) |
| `runtime.rs` | Host half of `tinyruntime`: resolving a language runtime (via `tinyruntime-nodejs`/`-python`) and running code on it |
| `connectors.rs` | Reaching `tinyconnectors`; egress policy, route selection, and webhook delivery stay in this crate even though scope enforcement moved into the module |
+| `search.rs` | Private TinySearch configuration, synchronous tool declarations from `tinysearch-bus`, and confidential execution calls; reloads persisted settings and refreshes a loaded module before invocation |
| `tokenjuice_host.rs` | Host-owned ML callback served to the `tinyjuice` module |
| `*_tests.rs` | Focused tests beside each file above |
@@ -82,6 +83,23 @@ are installed first). It never fails the boot. Everything else is
`LoadPolicy::Lazy` and resolves on first `ensure_loaded` call — deliberately
not eager, so a user who never touches a feature never pays its download.
+## TinySearch development pin
+
+The `tinysearch` registry record has no platform assets until a published
+release provides verified checksums. Use `[[modules.overrides]]` with
+`id = "tinysearch"` and an absolute local library `path` during development.
+The host sends provider keys and the typed backend credential only in private
+module initialization and reinitialization payloads. Settings changes refresh
+a loaded module; `search::list_tools` and `search::execute_tool` reload current
+settings before each call so a captured config cannot keep old credentials.
+`search::configured_tool_specs` uses the bus contract to declare tools
+synchronously during registration.
+
+TinySearch has one route per provider. Managed search maps to backend Parallel;
+when direct Parallel is explicitly selected, it takes precedence. Gemini
+Deep Research remains direct with a Gemini key even when grounded Gemini search
+uses the backend route.
+
## Contract crates
Each loadable module has a small `*-bus` contract crate for interface names,
@@ -95,6 +113,7 @@ method constants, request/response types, and its contract version:
| `tinyruntime-bus` | runtime clients |
| `tinywallet-bus` | `web3` |
| `tinymcp-bus` | `mcp` |
+| `tinysearch-bus` | search provider declarations and bus payloads |
| `tinychannels-bus` | channel vocabulary |
| `tinymemory-api` | memory (selectively re-exported as `crate::memory::api`, not copied or widened) |
| `tinymemory-bus` | memory method names (`names::methods`, used throughout `memory/`, e.g. `memory/provider.rs`) |
diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rs
index 552df0755f..2e2977ad48 100644
--- a/crates/openhuman-core/src/modules/mod.rs
+++ b/crates/openhuman-core/src/modules/mod.rs
@@ -56,6 +56,7 @@ pub mod registry;
mod resolution;
pub mod runtime;
pub mod schemas;
+pub mod search;
mod tokenjuice_host;
pub mod types;
#[cfg(feature = "voice")]
diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rs
index ec23335913..c982aa03bc 100644
--- a/crates/openhuman-core/src/modules/ops.rs
+++ b/crates/openhuman-core/src/modules/ops.rs
@@ -458,6 +458,10 @@ pub(super) fn load_local(
/// Credentials are intentionally absent. TinyMemory calls back into the host
/// for embedding and chat compute; the other modules need no host config.
fn module_config(config: &Config, id: &str) -> serde_json::Value {
+ if id == super::search::MODULE_ID {
+ return serde_json::to_value(super::search::module_config(config))
+ .expect("TinySearch config serializes");
+ }
if id == super::desktop::MODULE_ID {
return super::desktop::module_config(config);
}
diff --git a/crates/openhuman-core/src/modules/registry.rs b/crates/openhuman-core/src/modules/registry.rs
index f61367dc2d..c34c3d8a53 100644
--- a/crates/openhuman-core/src/modules/registry.rs
+++ b/crates/openhuman-core/src/modules/registry.rs
@@ -41,6 +41,7 @@ mod records_extra;
mod records_mcp_connectors;
mod records_memory_juice;
mod records_runtime;
+mod records_search;
mod records_voice;
use crate::modules::types::ModuleRecord;
@@ -51,12 +52,14 @@ use records_extra::{TINYBOX, TINYCHANNELS, TINYHOSTS};
use records_mcp_connectors::{TINYCONNECTORS, TINYMCP};
use records_memory_juice::{TINYJUICE, TINYMEMORY};
use records_runtime::{TINYRUNTIME, TINYRUNTIME_NODEJS, TINYRUNTIME_PYTHON};
+use records_search::TINYSEARCH;
use records_voice::TINYVOICE;
/// Every module this build can load.
pub const ALL: &[ModuleRecord] = &[
TINYDESKTOP,
TINYBROWSER,
+ TINYSEARCH,
TINYDOCS,
TINYWALLET,
TINYMEMORY,
diff --git a/crates/openhuman-core/src/modules/registry/records_search.rs b/crates/openhuman-core/src/modules/registry/records_search.rs
new file mode 100644
index 0000000000..03220ce583
--- /dev/null
+++ b/crates/openhuman-core/src/modules/registry/records_search.rs
@@ -0,0 +1,14 @@
+//! Development-only TinySearch registration. Published archive pins are added
+//! only after a verified release; local overrides work meanwhile.
+use crate::modules::types::{LoadPolicy, ModuleRecord};
+
+pub(crate) const TINYSEARCH: ModuleRecord = ModuleRecord {
+ id: "tinysearch",
+ description: "Search provider tools through TinySearch",
+ bus_name: tinysearch_bus::names::INTERFACE,
+ object_path: tinysearch_bus::names::OBJECT_PATH,
+ version: "0.2.1",
+ release_url: "https://github.com/tinyhumansai/tinysearch/releases/tag/v0.2.1",
+ assets: &[],
+ load: LoadPolicy::Lazy,
+};
diff --git a/crates/openhuman-core/src/modules/search.rs b/crates/openhuman-core/src/modules/search.rs
new file mode 100644
index 0000000000..e693e01a43
--- /dev/null
+++ b/crates/openhuman-core/src/modules/search.rs
@@ -0,0 +1,458 @@
+//! Host adapter for the TinySearch module. Secrets enter only through private
+//! TinyBus initialization and reinitialization payloads.
+
+use std::{
+ collections::BTreeMap,
+ future::Future,
+ hash::{Hash, Hasher},
+ sync::OnceLock,
+};
+use tinysearch_bus::{
+ names, BackendAuthMode, BackendConfig, ExecuteToolRequest, ExecuteToolResponse,
+ ListToolsResponse, PresentationConfig, PresentationMode, ProviderConfig, ProviderRoute,
+ SearchConfig as ModuleSearchConfig,
+};
+
+use crate::config::Config;
+
+pub const MODULE_ID: &str = "tinysearch";
+
+fn provider(
+ enabled: bool,
+ credential: Option<&str>,
+ route: ProviderRoute,
+ max_results: Option<u64>,
+ timeout_secs: Option<u64>,
+) -> ProviderConfig {
+ ProviderConfig {
+ enabled,
+ credential: credential.map(str::to_owned),
+ route,
+ max_results,
+ timeout_secs,
+ ..Default::default()
+ }
+}
+
+/// The complete private configuration for TinySearch. No credentials are
+/// returned over settings RPC or sent on ordinary bus method calls.
+pub fn module_config(config: &Config) -> ModuleSearchConfig {
+ let credential =
+ crate::security::credentials::session_support::resolve_backend_credential(config).ok();
+ let selected = config.search.providers(
+ credential.is_some(),
+ config.integrations.tinyfish.is_active(),
+ config.seltz.enabled
+ && config
+ .seltz
+ .api_key
+ .as_deref()
+ .is_some_and(|key| !key.trim().is_empty()),
+ config.searxng.enabled,
+ );
+ let backend = BackendConfig {
+ base_url: Some(crate::api::effective_backend_api_url(&config.api_url)),
+ auth_mode: if credential.as_ref().is_some_and(|c| c.is_api_key()) {
+ BackendAuthMode::ApiKey
+ } else {
+ BackendAuthMode::Session
+ },
+ credential: credential.map(|c| c.into_secret()),
+ sdk_name: Some(crate::api::product_identity().as_str().to_owned()),
+ };
+ let mut providers = BTreeMap::new();
+ let limits = (
+ Some(config.search.max_results as u64),
+ Some(config.search.timeout_secs),
+ );
+ for (name, key) in [
+ ("brave", config.search.brave.key()),
+ ("querit", config.search.querit.key()),
+ ("exa", config.search.exa.key()),
+ ("tavily", config.search.tavily.key()),
+ ("gemini", config.search.gemini.key()),
+ ("parallel", config.search.parallel.key()),
+ ] {
+ let route = if (name == "parallel" && config.search.parallel_route == "backend")
+ || (name == "gemini" && config.search.gemini_route == "backend")
+ {
+ ProviderRoute::Backend
+ } else {
+ ProviderRoute::Direct
+ };
+ let enabled = selected.contains(name)
+ && (key.is_some() || (route == ProviderRoute::Backend && backend.credential.is_some()));
+ providers.insert(
+ name.into(),
+ provider(enabled, key, route, limits.0, limits.1),
+ );
+ }
+ // TinySearch names managed search `parallel` with its backend route.
+ // A usable direct Parallel route takes precedence until the bus can
+ // represent both routes of that provider at once. If no direct key is
+ // present, preserve the managed backend route.
+ if selected.contains("managed")
+ && (!selected.contains("parallel")
+ || (config.search.parallel_route != "backend" && !config.search.parallel.has_key()))
+ {
+ providers.insert(
+ "parallel".into(),
+ provider(
+ backend.credential.is_some(),
+ None,
+ ProviderRoute::Backend,
+ limits.0,
+ limits.1,
+ ),
+ );
+ }
+ providers.insert(
+ "tinyfish".into(),
+ provider(
+ selected.contains("tinyfish")
+ && (config.search.enabled_providers.is_some()
+ || config.integrations.tinyfish.is_active()),
+ None,
+ ProviderRoute::Backend,
+ limits.0,
+ limits.1,
+ ),
+ );
+ // Deep Research is direct-only even when grounded Gemini search takes
+ // the managed backend route.
+ providers.insert(
+ "gemini_deep_research".into(),
+ provider(
+ selected.contains("gemini") && config.search.gemini.has_key(),
+ config.search.gemini.key(),
+ ProviderRoute::Direct,
+ limits.0,
+ limits.1,
+ ),
+ );
+ providers.insert(
+ "seltz".into(),
+ ProviderConfig {
+ enabled: selected.contains("seltz")
+ && config
+ .seltz
+ .api_key
+ .as_deref()
+ .is_some_and(|key| !key.trim().is_empty()),
+ credential: config.seltz.api_key.clone(),
+ base_url: config.seltz.api_url.clone(),
+ max_results: Some(config.seltz.max_results as u64),
+ timeout_secs: Some(config.seltz.timeout_secs),
+ ..Default::default()
+ },
+ );
+ providers.insert(
+ "searxng".into(),
+ ProviderConfig {
+ enabled: selected.contains("searxng"),
+ base_url: Some(config.searxng.base_url.clone()),
+ max_results: Some(config.searxng.max_results as u64),
+ timeout_secs: Some(config.searxng.timeout_secs),
+ default_language: Some(config.searxng.default_language.clone()),
+ ..Default::default()
+ },
+ );
+ ModuleSearchConfig {
+ enabled: config.search.is_enabled(),
+ backend,
+ providers,
+ presentation: PresentationConfig {
+ mode: match config.search.presentation.as_str() {
+ "router" => PresentationMode::Router,
+ "one_provider" => PresentationMode::OneProvider,
+ _ => PresentationMode::AllTools,
+ },
+ provider: config.search.presentation_provider.as_deref().map(|name| {
+ if name == "managed" {
+ "parallel".to_owned()
+ } else {
+ name.to_owned()
+ }
+ }),
+ },
+ }
+}
+
+/// Deterministic declarations for synchronous tool registration. Invocation
+/// still refreshes the module and lets it validate the current tool set.
+pub fn configured_tool_specs(config: &Config) -> Vec<tinysearch_bus::ToolSpec> {
+ let module = module_config(config);
+ let available =
+ tinysearch_bus::configured_provider_tools(&module, &tinysearch_bus::provider_tool_specs());
+ tinysearch_bus::select_tools(&available, &module.presentation).tools
+}
+
+fn last_config() -> &'static tokio::sync::Mutex<Option<u64>> {
+ static LAST: OnceLock<tokio::sync::Mutex<Option<u64>>> = OnceLock::new();
+ LAST.get_or_init(|| tokio::sync::Mutex::new(None))
+}
+
+fn fingerprint(value: &serde_json::Value) -> u64 {
+ let mut hasher = std::collections::hash_map::DefaultHasher::new();
+ value.to_string().hash(&mut hasher);
+ hasher.finish()
+}
+
+async fn proxy(config: &Config) -> Result<tinybus::Proxy, String> {
+ super::ops::ensure_loaded_within(config, MODULE_ID, Some(std::time::Duration::from_secs(8)))
+ .await
+ .map_err(super::ops::LoadError::into_message)?;
+ let runtime = super::host::runtime()
+ .await
+ .map_err(|error| format!("search module bus unavailable: {error}"))?;
+ let configuration =
+ serde_json::to_value(module_config(config)).map_err(|error| error.to_string())?;
+ let current = fingerprint(&configuration);
+ // Caller holds the module call lock through the subsequent bus call.
+ let mut previous = last_config().lock().await;
+ if *previous != Some(current) {
+ runtime
+ .connection()
+ .reinitialize_module(MODULE_ID, configuration)
+ .await
+ .map_err(|error| format!("search module configuration refresh failed: {error}"))?;
+ *previous = Some(current);
+ }
+ runtime
+ .proxy(names::INTERFACE, names::OBJECT_PATH)
+ .map_err(|error| format!("search module proxy unavailable: {error}"))
+}
+
+async fn with_module_lock<T, F, Fut>(operation: F) -> Result<T, String>
+where
+ F: FnOnce() -> Fut,
+ Fut: Future<Output = Result<T, String>>,
+{
+ static CALL_LOCK: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
+ let guard = CALL_LOCK
+ .get_or_init(|| tokio::sync::Mutex::new(()))
+ .lock()
+ .await;
+ let result = operation().await;
+ drop(guard);
+ result
+}
+
+async fn current_config(config: &Config) -> Result<Config, String> {
+ crate::config::ops::reload_config_from_paths(&config.config_path, &config.workspace_dir).await
+}
+
+/// Refresh a loaded module after a settings or login change. An unloaded
+/// module gets the current configuration during its first initialization.
+pub async fn refresh_loaded(config: &Config) -> Result<(), String> {
+ if matches!(
+ super::ops::state_of(MODULE_ID),
+ super::types::ModuleState::Ready
+ ) {
+ let current = current_config(config).await?;
+ with_module_lock(|| async {
+ let _ = proxy(&current).await?;
+ Ok(())
+ })
+ .await?;
+ }
+ Ok(())
+}
+
+pub async fn list_tools(config: &Config) -> Result<ListToolsResponse, String> {
+ let current = current_config(config).await?;
+ with_module_lock(|| async {
+ proxy(&current)
+ .await?
+ .call(names::methods::LIST_TOOLS, ())
+ .await
+ .map_err(|error| format!("search ListTools failed: {error}"))
+ })
+ .await
+}
+
+pub async fn execute_tool(
+ config: &Config,
+ request: ExecuteToolRequest,
+) -> Result<ExecuteToolResponse, String> {
+ let current = current_config(config).await?;
+ with_module_lock(|| async {
+ proxy(&current)
+ .await?
+ .call_confidential(names::methods::EXECUTE_TOOL, (request,))
+ .await
+ .map_err(|error| format!("search ExecuteTool failed: {error}"))
+ })
+ .await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn config_in(dir: &std::path::Path) -> Config {
+ let mut config = Config::default();
+ config.config_path = dir.join("config.toml");
+ config.workspace_dir = dir.join("workspace");
+ config.secrets.encrypt = false;
+ config
+ }
+
+ #[test]
+ fn direct_provider_config_keeps_limits_and_private_key() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.search.enabled_providers = Some(["parallel".to_owned()].into());
+ config.search.parallel.api_key = Some("test-secret".into());
+ config.search.max_results = 12;
+ config.search.timeout_secs = 22;
+ let payload = module_config(&config);
+ let parallel = &payload.providers["parallel"];
+ assert!(parallel.enabled);
+ assert_eq!(parallel.route, ProviderRoute::Direct);
+ assert_eq!(parallel.credential.as_deref(), Some("test-secret"));
+ assert_eq!(parallel.max_results, Some(12));
+ assert_eq!(parallel.timeout_secs, Some(22));
+ assert!(!format!("{payload:?}").contains("test-secret"));
+ }
+
+ #[test]
+ fn synchronous_tool_specs_follow_provider_selection() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.search.enabled_providers = Some(["parallel".to_owned()].into());
+ config.search.parallel.api_key = Some("test-secret".into());
+ let specs = configured_tool_specs(&config);
+ assert!(specs.iter().any(|spec| spec.name == "parallel_search"));
+ config.search.enabled_providers = Some(Default::default());
+ assert!(configured_tool_specs(&config).is_empty());
+ }
+
+ #[test]
+ fn managed_presentation_targets_backend_parallel() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.search.presentation = "one_provider".into();
+ config.search.presentation_provider = Some("managed".into());
+ let payload = module_config(&config);
+ assert_eq!(payload.presentation.provider.as_deref(), Some("parallel"));
+ }
+
+ #[test]
+ fn managed_route_survives_parallel_selection_without_direct_key() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ crate::security::credentials::api_key::store_api_key(&config, "backend-sentinel").unwrap();
+ config.search.enabled_providers = Some(["managed".into(), "parallel".into()].into());
+ let payload = module_config(&config);
+ assert!(payload.providers["parallel"].enabled);
+ assert_eq!(payload.providers["parallel"].route, ProviderRoute::Backend);
+ assert!(payload.providers["parallel"].credential.is_none());
+ }
+
+ #[test]
+ fn explicit_tinyfish_selection_overrides_legacy_toggle() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.integrations.tinyfish.enabled = false;
+ config.search.enabled_providers = Some(["tinyfish".into()].into());
+ assert!(module_config(&config).providers["tinyfish"].enabled);
+ config.search.enabled_providers = None;
+ assert!(!module_config(&config).providers["tinyfish"].enabled);
+ }
+
+ #[tokio::test]
+ async fn configured_calls_keep_the_lock_through_invocation() {
+ use std::sync::{Arc, Mutex};
+ let active = Arc::new(Mutex::new(String::new()));
+ let (a_entered_tx, a_entered_rx) = tokio::sync::oneshot::channel();
+ let (release_a_tx, release_a_rx) = tokio::sync::oneshot::channel();
+ let a_active = active.clone();
+ let a = tokio::spawn(async move {
+ with_module_lock(|| async move {
+ *a_active.lock().unwrap() = "A".into();
+ a_entered_tx.send(()).unwrap();
+ release_a_rx.await.unwrap();
+ assert_eq!(*a_active.lock().unwrap(), "A");
+ Ok::<_, String>(())
+ })
+ .await
+ .unwrap();
+ });
+ a_entered_rx.await.unwrap();
+ let b_active = active.clone();
+ let (b_started_tx, b_started_rx) = tokio::sync::oneshot::channel();
+ let b = tokio::spawn(async move {
+ b_started_tx.send(()).unwrap();
+ with_module_lock(|| async move {
+ *b_active.lock().unwrap() = "B".into();
+ Ok::<_, String>(())
+ })
+ .await
+ .unwrap();
+ });
+ b_started_rx.await.unwrap();
+ tokio::task::yield_now().await;
+ assert_eq!(*active.lock().unwrap(), "A");
+ release_a_tx.send(()).unwrap();
+ a.await.unwrap();
+ b.await.unwrap();
+ assert_eq!(*active.lock().unwrap(), "B");
+ }
+
+ #[test]
+ fn gemini_deep_research_keeps_direct_key_on_backend_grounded_route() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.search.enabled_providers = Some(["gemini".to_owned()].into());
+ config.search.gemini_route = "backend".into();
+ config.search.gemini.api_key = Some("test-secret".into());
+ let payload = module_config(&config);
+ let deep = &payload.providers["gemini_deep_research"];
+ assert!(deep.enabled);
+ assert_eq!(deep.route, ProviderRoute::Direct);
+ assert_eq!(deep.credential.as_deref(), Some("test-secret"));
+ }
+
+ #[test]
+ fn backend_api_key_uses_x_api_key_mode() {
+ let dir = tempfile::tempdir().unwrap();
+ let config = config_in(dir.path());
+ crate::security::credentials::api_key::store_api_key(&config, "test-backend-key").unwrap();
+ let payload = module_config(&config);
+ assert_eq!(payload.backend.auth_mode, BackendAuthMode::ApiKey);
+ assert_eq!(
+ payload.backend.credential.as_deref(),
+ Some("test-backend-key")
+ );
+ assert!(!format!("{payload:?}").contains("test-backend-key"));
+ }
+
+ #[test]
+ fn explicit_provider_set_controls_separate_search_engines() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.seltz.enabled = true;
+ config.seltz.api_key = Some("test-secret".into());
+ config.searxng.enabled = true;
+ config.search.enabled_providers = Some(Default::default());
+ let payload = module_config(&config);
+ assert!(!payload.providers["seltz"].enabled);
+ assert!(!payload.providers["searxng"].enabled);
+ config.search.enabled_providers = Some(["seltz".to_owned()].into());
+ let payload = module_config(&config);
+ assert!(payload.providers["seltz"].enabled);
+ assert!(!payload.providers["searxng"].enabled);
+ }
+
+ #[test]
+ fn legacy_disabled_removes_all_module_tools() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut config = config_in(dir.path());
+ config.search.engine = "disabled".into();
+ config.search.parallel.api_key = Some("test-secret".into());
+ let payload = module_config(&config);
+ assert!(!payload.enabled);
+ assert!(payload.providers.values().all(|provider| !provider.enabled));
+ }
+}
diff --git a/vendor/tinysearch b/vendor/tinysearch
index 6cb5fc7a51..be27e90661 160000
--- a/vendor/tinysearch
+++ b/vendor/tinysearch
@@ -1 +1 @@
-Subproject commit 6cb5fc7a51eb4c55033f7c00f17bcf21e0dc95f2
+Subproject commit be27e906618fff2b2517ffc315a9012262bcfa49