Skip to content

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

chore(deps): update Rust crate dependencies across multiple modules

Steven Enamakel0cbd5c5e7aab
diff --git a/crates/openhuman-core/src/desktop/app_state/ops/pending_session.rs b/crates/openhuman-core/src/desktop/app_state/ops/pending_session.rs
new file mode 100644
index 0000000000..ba20d6bfa5
--- /dev/null
+++ b/crates/openhuman-core/src/desktop/app_state/ops/pending_session.rs
@@ -0,0 +1,340 @@
+//! Pending-session revalidation: activating (or rejecting) an app session
+//! whose backend user id was not yet confirmed, moving it into its own
+//! user directory, and rebinding the login-gated services and memory
+//! context that go with it.
+
+use super::current_user_generation::{
+ current_user_generation, forget_current_user_caches, CURRENT_USER_SESSION_MUTATION_LOCK,
+};
+use crate::api::rest::user_id_from_profile_payload;
+use crate::config::Config;
+use crate::security::credentials::{
+ AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,
+};
+use super::LOG_PREFIX;
+use log::{debug, warn};
+use serde_json::Value;
+use std::collections::{BTreeMap, HashMap};
+use std::fs;
+use std::path::{Path, PathBuf};
+
+/// Marks a stored `current_user` payload as not yet confirmed against the
+/// backend — set on a locally-created session, cleared once `auth_get_me`
+/// confirms the user id.
+pub(super) const PENDING_BACKEND_VALIDATION_FIELD: &str = "pendingBackendValidation";
+
+pub(super) fn snapshot_user_pending_backend_validation(user: Option<&Value>) -> bool {
+ user.and_then(Value::as_object)
+ .and_then(|obj| obj.get(PENDING_BACKEND_VALIDATION_FIELD))
+ .and_then(Value::as_bool)
+ .unwrap_or(false)
+}
+
+pub(super) fn clear_pending_backend_validation_flag(mut user: Value) -> Value {
+ if let Value::Object(ref mut map) = user {
+ map.remove(PENDING_BACKEND_VALIDATION_FIELD);
+ }
+ user
+}
+
+pub(super) fn pending_session_user_id_for_cleanup(
+ stored_user: Option<&Value>,
+ metadata: &BTreeMap<String, String>,
+) -> Option<String> {
+ stored_user
+ .and_then(user_id_from_profile_payload)
+ .or_else(|| {
+ metadata
+ .get("user_id")
+ .map(String::as_str)
+ .map(str::trim)
+ .filter(|user_id| !user_id.is_empty())
+ .map(str::to_string)
+ })
+}
+
+fn config_state_dir(config: &Config) -> Option<PathBuf> {
+ config.config_path.parent().map(Path::to_path_buf)
+}
+
+pub(super) fn same_config_state_dir(a: &Config, b: &Config) -> bool {
+ config_state_dir(a) == config_state_dir(b)
+}
+
+fn config_dir_for_workspace_env() -> Option<PathBuf> {
+ let workspace = std::env::var_os("OPENHUMAN_WORKSPACE")?;
+ if workspace.as_os_str().is_empty() {
+ return None;
+ }
+
+ // Resolve through the SAME workspace→config-dir mapping `config::load` uses
+ // (`resolve_config_dir_for_workspace`), not a private reimplementation.
+ // A copy here drifts from the loader: it independently doubled
+ // `~/.openhuman/workspace` into `~/.openhuman/.openhuman`, so
+ // `config_is_workspace_env_scoped` compared that against the loader's real
+ // `~/.openhuman` and returned false, mis-scoping credentials on session
+ // revalidation (#6079). Delegating keeps the two in lockstep, including the
+ // modern-layout recognition that fixes the doubling.
+ let workspace_dir = PathBuf::from(workspace);
+ let (config_dir, _workspace_dir) =
+ crate::config::resolve_config_dir_for_workspace(&workspace_dir);
+ Some(config_dir)
+}
+
+fn config_is_workspace_env_scoped(config: &Config) -> bool {
+ let Some(config_dir) = config_state_dir(config) else {
+ return false;
+ };
+ config_dir_for_workspace_env()
+ .as_deref()
+ .is_some_and(|env_config_dir| env_config_dir == config_dir)
+}
+
+async fn activate_revalidated_user_dir(user_id: &str) -> Result<Config, String> {
+ let root_dir = crate::config::default_root_openhuman_dir()
+ .map_err(|error| format!("failed to locate default root: {error}"))?;
+ let previous_active = crate::config::read_active_user_id(&root_dir);
+ let user_dir = crate::config::user_openhuman_dir(&root_dir, user_id);
+ fs::create_dir_all(&user_dir).map_err(|error| {
+ format!("failed to create user directory for revalidated pending session user_id={user_id}: {error}")
+ })?;
+ crate::config::write_active_user_id(&root_dir, user_id).map_err(|error| {
+ format!("failed to write active_user.toml for revalidated pending session user_id={user_id}: {error}")
+ })?;
+
+ debug!(
+ "{LOG_PREFIX} activated user directory for revalidated pending session user_id={user_id}"
+ );
+ if previous_active.is_none() {
+ let pre_ws = crate::config::pre_login_user_dir(&root_dir).join("workspace");
+ if let Err(error) = crate::memory::conversations::purge_threads(pre_ws) {
+ debug!(
+ "{LOG_PREFIX} pre-login conversation purge skipped after pending session revalidation: {error}"
+ );
+ }
+ }
+
+ let config = Config::load_from_default_paths().await.map_err(|error| {
+ format!("failed to reload config after pending session user activation: {error}")
+ })?;
+
+ // The marker write above cleared the cached active workspace, and
+ // `load_from_default_paths` deliberately bypasses the runtime resolver, so
+ // nothing has refilled it. Resolve once through the authoritative path,
+ // which republishes the cache and announces the switch — otherwise a
+ // connected Event Log or notification client keeps the previous
+ // workspace's handle until some unrelated later config load happens
+ // (#5966). Publishing from `load_from_default_paths` itself would be
+ // wrong: it ignores `OPENHUMAN_WORKSPACE`, so under that override it does
+ // not know the runtime answer.
+ if let Err(error) = crate::config::active_workspace_dir().await {
+ warn!(
+ "{LOG_PREFIX} could not refresh the active workspace after pending session activation: {error}"
+ );
+ }
+
+ Ok(config)
+}
+
+async fn finish_revalidated_user_activation(
+ target_config: &Config,
+ user_id: &str,
+ service_rebind_source: Option<&Config>,
+ generation: u64,
+) {
+ if let Err(error) = crate::cron::seed::prune_retired_jobs(target_config) {
+ warn!("{LOG_PREFIX} failed to prune retired cron jobs after pending session revalidation: {error}");
+ }
+
+ // ── No explicit memory re-point here any more (#5560) ──────────────────
+ //
+ // This was `tinymemory_core::global::init(...)`, the in-process engine's
+ // process-global slot, which had to be re-pointed by hand at every
+ // activation site or it kept writing into the previous workspace.
+ // `memory::binding` is keyed on (workspace, `[subsystems.memory]`), and the
+ // context rebind immediately below re-points both — so memory follows it by
+ // construction. `CoreContext::memory_binding`'s docs state this property as
+ // the reason these sites need no memory call of their own.
+ if let Err(error) = crate::core::runtime::context::CoreContext::rebind_default_workspace(
+ &target_config.workspace_dir,
+ target_config.subsystems.memory.clone(),
+ ) {
+ warn!("{LOG_PREFIX} failed to rebind core context after pending session revalidation: {error}");
+ }
+ // No people-store rebind: people is served by the bound memory driver, and
+ // the core-context rebind above already moved that binding to the activated
+ // user's workspace.
+ crate::memory::conversations::register_conversation_persistence_subscriber(
+ target_config.workspace_dir.clone(),
+ );
+ if current_user_generation() != generation {
+ debug!("{LOG_PREFIX} skipping stale activation after pending session revalidation");
+ return;
+ }
+ if let Some(source_config) = service_rebind_source {
+ if current_user_generation() != generation {
+ debug!(
+ "{LOG_PREFIX} skipping stale login-gated service activation after pending session revalidation"
+ );
+ return;
+ }
+ crate::security::credentials::stop_login_gated_services(source_config).await;
+ if current_user_generation() != generation {
+ debug!(
+ "{LOG_PREFIX} skipping stale login-gated service restart after pending session revalidation"
+ );
+ return;
+ }
+ crate::security::credentials::start_login_gated_services(target_config).await;
+ } else {
+ debug!(
+ "{LOG_PREFIX} pending session revalidation left login-gated services running without restart"
+ );
+ }
+ crate::cron::scheduler_gate::set_signed_out(false);
+ crate::security::credentials::sentry_scope::bind(user_id);
+}
+
+async fn remove_revalidated_source_profile(config: &Config) -> Result<(), String> {
+ let config = config.clone();
+ tokio::task::spawn_blocking(move || {
+ AuthService::from_config(&config)
+ .remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ })
+ .await
+ .unwrap_or_else(|e| {
+ Err(format!(
+ "{LOG_PREFIX} revalidated source profile remove task panicked: {e}"
+ ))
+ })
+}
+
+pub(super) async fn persist_revalidated_session_user(
+ config: &Config,
+ token: &str,
+ base_metadata: BTreeMap<String, String>,
+ user: Value,
+ generation: u64,
+) -> Result<Box<Config>, String> {
+ let (target_config, user_id, source_config, source_moved) = {
+ let _session_mutation_lock = CURRENT_USER_SESSION_MUTATION_LOCK.lock().await;
+ if current_user_generation() != generation {
+ return Err("pending session persistence became stale after sign-out".to_string());
+ }
+ let user_id = user_id_from_profile_payload(&user).ok_or_else(|| {
+ "backend user id required before clearing pending validation".to_string()
+ })?;
+ let workspace_env_scoped = config_is_workspace_env_scoped(config);
+ let target_config = if !workspace_env_scoped {
+ activate_revalidated_user_dir(&user_id).await?
+ } else {
+ debug!(
+ "{LOG_PREFIX} keeping revalidated pending session in OPENHUMAN_WORKSPACE-scoped config"
+ );
+ config.clone()
+ };
+ let source_config = config.clone();
+ let source_moved = !same_config_state_dir(config, &target_config);
+ let token = token.to_string();
+ let mut metadata: HashMap<String, String> = base_metadata.into_iter().collect();
+ metadata.insert("user_id".to_string(), user_id.clone());
+ metadata.insert("user_json".to_string(), user.to_string());
+
+ let config_for_store = target_config.clone();
+ tokio::task::spawn_blocking(move || {
+ AuthService::from_config(&config_for_store)
+ .store_provider_token(
+ APP_SESSION_PROVIDER,
+ DEFAULT_AUTH_PROFILE_NAME,
+ &token,
+ metadata,
+ true,
+ )
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ })
+ .await
+ .unwrap_or_else(|e| {
+ Err(format!(
+ "{LOG_PREFIX} revalidated session persist task panicked: {e}"
+ ))
+ })?;
+
+ if source_moved {
+ if let Err(error) = remove_revalidated_source_profile(&source_config).await {
+ warn!(
+ "{LOG_PREFIX} failed to remove source pending session profile after user activation: {error}"
+ );
+ }
+ }
+
+ (target_config, user_id, source_config, source_moved)
+ };
+
+ finish_revalidated_user_activation(
+ &target_config,
+ &user_id,
+ source_moved.then_some(&source_config),
+ generation,
+ )
+ .await;
+
+ Ok(Box::new(target_config))
+}
+
+pub(super) async fn clear_deferred_session_after_backend_rejection(
+ config: &Config,
+ pending_user_id: Option<&str>,
+) -> Result<(), String> {
+ let workspace_env_scoped = config_is_workspace_env_scoped(config);
+ let config_for_remove = config.clone();
+ let clear_result = tokio::task::spawn_blocking(move || {
+ AuthService::from_config(&config_for_remove)
+ .remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME)
+ .map(|_| ())
+ .map_err(|e| e.to_string())
+ })
+ .await
+ .unwrap_or_else(|e| {
+ Err(format!(
+ "{LOG_PREFIX} deferred session clear task panicked: {e}"
+ ))
+ });
+
+ forget_current_user_caches();
+ crate::cron::scheduler_gate::set_signed_out(true);
+
+ match crate::config::default_root_openhuman_dir() {
+ Ok(root_dir) => {
+ let active_user = crate::config::read_active_user_id(&root_dir);
+ let should_clear_active_user = if workspace_env_scoped {
+ pending_user_id.is_some_and(|pending| active_user.as_deref() == Some(pending))
+ } else {
+ true
+ };
+ if should_clear_active_user {
+ if let Err(error) = crate::config::clear_active_user(&root_dir) {
+ warn!(
+ "{LOG_PREFIX} failed to clear active_user.toml for rejected pending session: {error}"
+ );
+ }
+ } else {
+ debug!(
+ "{LOG_PREFIX} preserving default active_user.toml for rejected OPENHUMAN_WORKSPACE-scoped pending session"
+ );
+ }
+ }
+ Err(error) if !workspace_env_scoped => {
+ warn!(
+ "{LOG_PREFIX} failed to locate default root while clearing rejected pending session: {error}"
+ );
+ }
+ Err(_) => {}
+ }
+ crate::security::credentials::stop_login_gated_services(config).await;
+ crate::security::credentials::sentry_scope::clear();
+
+ clear_result
+}
diff --git a/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs b/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs
index 502d5e59ea..cb7bb8c34e 100644
--- a/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs
+++ b/crates/openhuman-core/src/mcp/registry/schemas/handlers.rs
@@ -6,7 +6,10 @@ use serde_json::{Map, Value};
use crate::config::rpc as config_rpc;
use crate::core::all::ControllerFuture;
-use super::params::{read_optional, read_optional_json, read_optional_string, read_optional_u32, read_required, to_json};
+use super::params::{
+ read_optional, read_optional_json, read_optional_string, read_optional_u32, read_required,
+ to_json,
+};
// ── Handler implementations ──────────────────────────────────────────────────
@@ -30,10 +33,7 @@ pub(super) fn handle_registry_get(params: Map<String, Value>) -> ControllerFutur
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let qualified_name = read_required::<String>(&params, "qualified_name")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_registry_get(&config, qualified_name)
- .await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_registry_get(&config, qualified_name).await?)
})
}
@@ -68,10 +68,7 @@ pub(super) fn handle_update_env(params: Map<String, Value>) -> ControllerFuture
let config = config_rpc::load_config_with_timeout().await?;
let server_id = read_required::<String>(&params, "server_id")?;
let env = read_required::<std::collections::HashMap<String, String>>(&params, "env")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_update_env(&config, server_id, env)
- .await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_update_env(&config, server_id, env).await?)
})
}
@@ -79,9 +76,7 @@ pub(super) fn handle_uninstall(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let server_id = read_required::<String>(&params, "server_id")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_uninstall(&config, server_id).await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_uninstall(&config, server_id).await?)
})
}
@@ -89,10 +84,7 @@ pub(super) fn handle_detect_auth(params: Map<String, Value>) -> ControllerFuture
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let server_id = read_required::<String>(&params, "server_id")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_detect_auth(&config, server_id)
- .await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_detect_auth(&config, server_id).await?)
})
}
@@ -100,10 +92,7 @@ pub(super) fn handle_oauth_begin(params: Map<String, Value>) -> ControllerFuture
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let server_id = read_required::<String>(&params, "server_id")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_oauth_begin(&config, server_id)
- .await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_oauth_begin(&config, server_id).await?)
})
}
@@ -111,9 +100,7 @@ pub(super) fn handle_connect(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let server_id = read_required::<String>(&params, "server_id")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_connect(&config, server_id).await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_connect(&config, server_id).await?)
})
}
@@ -121,10 +108,7 @@ pub(super) fn handle_disconnect(params: Map<String, Value>) -> ControllerFuture
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let server_id = read_required::<String>(&params, "server_id")?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_disconnect(&config, server_id)
- .await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_disconnect(&config, server_id).await?)
})
}
@@ -134,10 +118,7 @@ pub(super) fn handle_set_enabled(params: Map<String, Value>) -> ControllerFuture
let server_id = read_required::<String>(&params, "server_id")?;
let enabled = read_required::<bool>(&params, "enabled")?;
to_json(
- crate::mcp::registry::ops::mcp_clients_set_enabled(
- &config, server_id, enabled,
- )
- .await?,
+ crate::mcp::registry::ops::mcp_clients_set_enabled(&config, server_id, enabled).await?,
)
})
}
@@ -173,9 +154,8 @@ pub(super) fn handle_config_assist(params: Map<String, Value>) -> ControllerFutu
let config = config_rpc::load_config_with_timeout().await?;
let qualified_name = read_required::<String>(&params, "qualified_name")?;
let user_message = read_required::<String>(&params, "user_message")?;
- let history = read_optional::<Vec<crate::mcp::registry::types::ChatTurn>>(
- &params, "history",
- )?;
+ let history =
+ read_optional::<Vec<crate::mcp::registry::types::ChatTurn>>(&params, "history")?;
to_json(
crate::mcp::registry::ops::mcp_clients_config_assist(
&config,
@@ -192,10 +172,7 @@ pub(super) fn handle_registry_settings_get(params: Map<String, Value>) -> Contro
Box::pin(async move {
let _ = params;
let config = config_rpc::load_config_with_timeout().await?;
- to_json(
- crate::mcp::registry::ops::mcp_clients_registry_settings_get(&config)
- .await?,
- )
+ to_json(crate::mcp::registry::ops::mcp_clients_registry_settings_get(&config).await?)
})
}
@@ -216,5 +193,3 @@ pub(super) fn handle_registry_settings_set(params: Map<String, Value>) -> Contro
)
})
}
-
-
diff --git a/crates/openhuman-core/src/mcp/registry/schemas/params.rs b/crates/openhuman-core/src/mcp/registry/schemas/params.rs
index 17a6422106..0f1739a972 100644
--- a/crates/openhuman-core/src/mcp/registry/schemas/params.rs
+++ b/crates/openhuman-core/src/mcp/registry/schemas/params.rs
@@ -8,7 +8,10 @@ use crate::rpc::RpcOutcome;
// ── Param helpers ─────────────────────────────────────────────────────────────
-pub(super) fn read_required<T: DeserializeOwned>(params: &Map<String, Value>, key: &str) -> Result<T, String> {
+pub(super) fn read_required<T: DeserializeOwned>(
+ params: &Map<String, Value>,
+ key: &str,
+) -> Result<T, String> {
let value = params
.get(key)
.cloned()
@@ -28,11 +31,17 @@ pub(super) fn read_optional<T: DeserializeOwned>(
}
}
-pub(super) fn read_optional_string(params: &Map<String, Value>, key: &str) -> Result<Option<String>, String> {
+pub(super) fn read_optional_string(
+ params: &Map<String, Value>,
+ key: &str,
+) -> Result<Option<String>, String> {
read_optional::<String>(params, key)
}
-pub(super) fn read_optional_u32(params: &Map<String, Value>, key: &str) -> Result<Option<u32>, String> {
+pub(super) fn read_optional_u32(
+ params: &Map<String, Value>,
+ key: &str,
+) -> Result<Option<u32>, String> {
match params.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::Number(n)) => n
@@ -47,7 +56,10 @@ pub(super) fn read_optional_u32(params: &Map<String, Value>, key: &str) -> Resul
}
}
-pub(super) fn read_optional_json(params: &Map<String, Value>, key: &str) -> Result<Option<Value>, String> {
+pub(super) fn read_optional_json(
+ params: &Map<String, Value>,
+ key: &str,
+) -> Result<Option<Value>, String> {
match params.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => Ok(Some(v.clone())),
@@ -68,4 +80,3 @@ pub(super) fn type_name(value: &Value) -> &'static str {
Value::Object(_) => "object",
}
}
-
diff --git a/crates/openhuman-core/src/mcp/registry/schemas/registry.rs b/crates/openhuman-core/src/mcp/registry/schemas/registry.rs
index 3beb0116e2..116091e5ea 100644
--- a/crates/openhuman-core/src/mcp/registry/schemas/registry.rs
+++ b/crates/openhuman-core/src/mcp/registry/schemas/registry.rs
@@ -7,9 +7,9 @@ use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
use super::handlers::{
handle_config_assist, handle_connect, handle_detect_auth, handle_disconnect, handle_install,
- handle_installed_list, handle_oauth_begin, handle_registry_get,
- handle_registry_settings_get, handle_registry_settings_set, handle_registry_search,
- handle_set_enabled, handle_status, handle_tool_call, handle_uninstall, handle_update_env,
+ handle_installed_list, handle_oauth_begin, handle_registry_get, handle_registry_search,
+ handle_registry_settings_get, handle_registry_settings_set, handle_set_enabled, handle_status,
+ handle_tool_call, handle_uninstall, handle_update_env,
};
use super::setup_handlers::{
handle_setup_get, handle_setup_install_and_connect, handle_setup_request_secret,
@@ -47,7 +47,6 @@ pub fn all_controller_schemas() -> Vec<ControllerSchema> {
]
}
-
pub fn all_registered_controllers() -> Vec<RegisteredController> {
vec![
RegisteredController {
@@ -141,7 +140,6 @@ pub fn all_registered_controllers() -> Vec<RegisteredController> {
]
}
-
pub fn schemas(function: &str) -> ControllerSchema {
match function {
"registry_search" => ControllerSchema {
@@ -677,4 +675,3 @@ pub fn schemas(function: &str) -> ControllerSchema {
},
}
}
-
diff --git a/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rs b/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rs
index 6e9ebc847d..9a1c4b9327 100644
--- a/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rs
+++ b/crates/openhuman-core/src/mcp/registry/schemas/setup_handlers.rs
@@ -15,10 +15,8 @@ pub(super) fn handle_setup_search(params: Map<String, Value>) -> ControllerFutur
let page = read_optional_u32(&params, "page")?;
let page_size = read_optional_u32(&params, "page_size")?;
to_json(
- crate::mcp::registry::setup_ops::mcp_setup_search(
- &config, query, page, page_size,
- )
- .await?,
+ crate::mcp::registry::setup_ops::mcp_setup_search(&config, query, page, page_size)
+ .await?,
)
})
}
@@ -27,10 +25,7 @@ pub(super) fn handle_setup_get(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let config = config_rpc::load_config_with_timeout().await?;
let qualified_name = read_required::<String>(&params, "qualified_name")?;
- to_json(
- crate::mcp::registry::setup_ops::mcp_setup_get(&config, qualified_name)
- .await?,
- )
+ to_json(crate::mcp::registry::setup_ops::mcp_setup_get(&config, qualified_name).await?)
})
}
@@ -40,10 +35,8 @@ pub(super) fn handle_setup_request_secret(params: Map<String, Value>) -> Control
let prompt = read_required::<String>(&params, "prompt")?;
let config = config_rpc::load_config_with_timeout().await?;
to_json(
- crate::mcp::registry::setup_ops::mcp_setup_request_secret(
- &config, key_name, prompt,
- )
- .await?,
+ crate::mcp::registry::setup_ops::mcp_setup_request_secret(&config, key_name, prompt)
+ .await?,
)
})
}
@@ -54,10 +47,8 @@ pub(super) fn handle_setup_submit_secret(params: Map<String, Value>) -> Controll
let value = read_required::<String>(&params, "value")?;
let config = config_rpc::load_config_with_timeout().await?;
to_json(
- crate::mcp::registry::setup_ops::mcp_setup_submit_secret(
- &config, ref_id, value,
- )
- .await?,
+ crate::mcp::registry::setup_ops::mcp_setup_submit_secret(&config, ref_id, value)
+ .await?,
)
})
}
@@ -95,5 +86,3 @@ pub(super) fn handle_setup_install_and_connect(params: Map<String, Value>) -> Co
)
})
}
-
-
diff --git a/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rs b/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rs
index 1c1b07037a..4e07dfa668 100644
--- a/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rs
+++ b/crates/openhuman-core/src/mcp/registry/schemas/setup_registry.rs
@@ -247,5 +247,3 @@ pub(super) fn setup_schemas(function: &str) -> ControllerSchema {
},
}
}
-
-
diff --git a/crates/openhuman-core/src/memory/guard/families/typed_ingest_and_answer.rs b/crates/openhuman-core/src/memory/guard/families/typed_ingest_and_answer.rs
new file mode 100644
index 0000000000..7a72493350
--- /dev/null
+++ b/crates/openhuman-core/src/memory/guard/families/typed_ingest_and_answer.rs
@@ -0,0 +1,301 @@
+//! Guarded `DocumentIngest`, `ConversationIngest`, `LearningIngest`,
+//! `EventIngest`, `Answer`, and `Chunks` — the typed-ingestion round the
+//! v1.13.7 contract release added, plus the sibling `Chunks` family wired
+//! alongside it.
+//!
+//! Split out of `families.rs`; see [`super::types`] for the shared decorator
+//! scaffolding these `impl` blocks build on.
+
+use crate::memory::api::capabilities::Capability;
+use crate::memory::api::chunks::Chunk;
+use crate::memory::api::error::MemoryError;
+use crate::memory::api::provider::chunks::{
+ ChunkDetail, ChunkEmbedding, ChunkListRow, ChunkQuery, ChunkScore, SourceIngestQuery,
+ SourceIngestStatus, SourceTotal,
+};
+use crate::memory::api::provider::operations::{
+ AnswerRequest, AnswerResponse, MemoryAnswer, MemoryConversationIngest, MemoryDocumentIngest,
+ MemoryEventIngest, MemoryLearningIngest, RawMemoryEvent,
+};
+use crate::memory::api::provider::types::{IngestItem, IngestOutcome};
+use crate::memory::api::provider::MemoryChunks;
+use async_trait::async_trait;
+use tinymemory_api::learning::LearningCandidate;
+
+use super::super::audit::{trace_allowed, NO_NAMESPACE};
+use super::super::policy::GuardPolicy;
+use super::types::{
+ GuardedAnswer, GuardedChunks, GuardedConversationIngest, GuardedDocumentIngest,
+ GuardedEventIngest, GuardedLearningIngest,
+};
+
+
+/// Steps 3 + 4 over one ingest item, shared by the typed-ingest decorators:
+/// stamp provenance, redact on egress — the same admission
+/// [`GuardedIngest::admit`] applies on the legacy family.
+fn admit_typed_item(policy: &GuardPolicy, mut item: IngestItem) -> IngestItem {
+ item.taint = policy.stamp_taint(item.taint);
+ item.content = policy.redact_outbound(&item.content).into_owned();
+ item
+}
+
+#[async_trait]
+impl MemoryDocumentIngest for GuardedDocumentIngest {
+ async fn ingest_document(&self, document: IngestItem) -> Result<IngestOutcome, MemoryError> {
+ let namespace = document.namespace.clone().unwrap_or_else(|| "-".to_string());
+ self.policy.admit_write(
+ Capability::DocumentIngest,
+ "document_ingest.ingest_document",
+ &namespace,
+ true,
+ )?;
+ let document = admit_typed_item(&self.policy, document);
+ trace_allowed(
+ &self.policy,
+ "document_ingest.ingest_document",
+ &namespace,
+ document.content.chars().count(),
+ );
+ self.family()?.ingest_document(document).await
+ }
+}
+
+#[async_trait]
+impl MemoryConversationIngest for GuardedConversationIngest {
+ async fn ingest_conversation(
+ &self,
+ messages: Vec<IngestItem>,
+ ) -> Result<IngestOutcome, MemoryError> {
+ self.policy.admit_write(
+ Capability::ConversationIngest,
+ "conversation_ingest.ingest_conversation",
+ NO_NAMESPACE,
+ true,
+ )?;
+ let messages: Vec<IngestItem> = messages
+ .into_iter()
+ .map(|m| admit_typed_item(&self.policy, m))
+ .collect();
+ trace_allowed(
+ &self.policy,
+ "conversation_ingest.ingest_conversation",
+ NO_NAMESPACE,
+ messages.iter().map(|m| m.content.chars().count()).sum(),
+ );
+ self.family()?.ingest_conversation(messages).await
+ }
+}
+
+#[async_trait]
+impl MemoryLearningIngest for GuardedLearningIngest {
+ async fn ingest_learning(
+ &self,
+ learning: LearningCandidate,
+ ) -> Result<IngestOutcome, MemoryError> {
+ // No content redaction: a learning candidate is already extracted
+ // structure, not raw user text — provenance is the driver's to stamp
+ // from the evidence pointer it carries.
+ self.policy.admit_write(
+ Capability::LearningIngest,
+ "learning_ingest.ingest_learning",
+ NO_NAMESPACE,
+ true,
+ )?;
+ trace_allowed(
+ &self.policy,
+ "learning_ingest.ingest_learning",
+ NO_NAMESPACE,
+ 0,
+ );
+ self.family()?.ingest_learning(learning).await
+ }
+}
+
+#[async_trait]
+impl MemoryEventIngest for GuardedEventIngest {
+ async fn ingest_event(&self, event: RawMemoryEvent) -> Result<IngestOutcome, MemoryError> {
+ self.policy.admit_write(
+ Capability::EventIngest,
+ "event_ingest.ingest_event",
+ NO_NAMESPACE,
+ true,
+ )?;
+ trace_allowed(&self.policy, "event_ingest.ingest_event", NO_NAMESPACE, 0);
+ self.family()?.ingest_event(event).await
+ }
+}
+
+#[async_trait]
+impl MemoryAnswer for GuardedAnswer {
+ async fn answer(&self, request: AnswerRequest) -> Result<AnswerResponse, MemoryError> {
+ // A read-shaped family: retrieval plus synthesis, no persistence.
+ self.policy
+ .admit_read(Capability::Answer, "answer.answer", NO_NAMESPACE, false)?;
+ trace_allowed(&self.policy, "answer.answer", NO_NAMESPACE, 0);
+ self.family()?.answer(request).await
+ }
+}
+
+#[async_trait]
+impl MemoryChunks for GuardedChunks {
+ async fn list_chunks(
+ &self,
+ query: &ChunkQuery,
+ scope: Option<&SourceScope>,
+ ) -> Result<Vec<Chunk>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.list_chunks",
+ NO_NAMESPACE,
+ false,
+ )?;
+ // Intersected with the ambient allowlist, never passed through. The
+ // ambient scope is an upper bound: forwarding the caller's scope
+ // unchanged would let a source-restricted turn widen itself back out by
+ // naming a collection the restriction excluded. See
+ // `GuardPolicy::narrow_scope`.
+ let effective = self.policy.narrow_scope(scope);
+ self.family()?.list_chunks(query, effective.as_ref()).await
+ }
+
+ /// The count that labels a [`Self::list_chunks`] page, and it must be
+ /// narrowed by exactly the same rule. A total computed against a wider
+ /// scope than the page it labels leaks the existence of rows the caller may
+ /// not read — "showing 20 of 4000" tells a source-restricted turn how much
+ /// it is not being shown.
+ async fn count_chunks(
+ &self,
+ query: &ChunkQuery,
+ scope: Option<&SourceScope>,
+ ) -> Result<u64, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.count_chunks",
+ NO_NAMESPACE,
+ false,
+ )?;
+ let effective = self.policy.narrow_scope(scope);
+ self.family()?.count_chunks(query, effective.as_ref()).await
+ }
+
+ /// Same rows as [`Self::list_chunks`] with the stored facts beside them, so
+ /// the same intersection applies for the same reason.
+ async fn list_chunk_details(
+ &self,
+ query: &ChunkQuery,
+ scope: Option<&SourceScope>,
+ ) -> Result<Vec<ChunkListRow>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.list_chunk_details",
+ NO_NAMESPACE,
+ false,
+ )?;
+ let effective = self.policy.narrow_scope(scope);
+ self.family()?
+ .list_chunk_details(query, effective.as_ref())
+ .await
+ }
+
+ /// Per-source totals are computed from the chunks the scope admits, not
+ /// filtered afterwards — so a restricted caller must not learn that a
+ /// forbidden source exists by seeing its row, nor see a permitted source
+ /// carrying a count that includes rows it cannot read.
+ async fn source_totals(
+ &self,
+ limit: usize,
+ scope: Option<&SourceScope>,
+ ) -> Result<Vec<SourceTotal>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.source_totals",
+ NO_NAMESPACE,
+ false,
+ )?;
+ let effective = self.policy.narrow_scope(scope);
+ self.family()?
+ .source_totals(limit, effective.as_ref())
+ .await
+ }
+
+ async fn get_chunk(&self, chunk_id: &str) -> Result<Option<Chunk>, MemoryError> {
+ self.policy
+ .admit_read(Capability::Chunks, "chunks.get_chunk", NO_NAMESPACE, false)?;
+ self.family()?.get_chunk(chunk_id).await
+ }
+
+ async fn chunk_detail(&self, chunk_id: &str) -> Result<Option<ChunkDetail>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.chunk_detail",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.chunk_detail(chunk_id).await
+ }
+
+ /// The catalog is not user content, so it takes no namespace and the
+ /// lightest read check — refusing it under `readonly` would stop an
+ /// operator finding out what the store can even hold.
+ async fn storage_kinds(&self) -> Result<Vec<String>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.storage_kinds",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.storage_kinds().await
+ }
+
+ /// Vectors, not content — but still a read of stored material, so it takes
+ /// the same tier check rather than being waved through as metadata.
+ async fn chunk_embeddings(
+ &self,
+ chunk_ids: &[String],
+ model_signature: &str,
+ ) -> Result<Vec<ChunkEmbedding>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.chunk_embeddings",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?
+ .chunk_embeddings(chunk_ids, model_signature)
+ .await
+ }
+
+ /// One chunk's admission verdict, read by chunk id exactly as
+ /// [`Self::chunk_detail`] is — so it takes that member's check, not
+ /// [`Self::list_chunks`]'s scope intersection. There is no scope to narrow:
+ /// the caller already holds the id.
+ async fn chunk_score(&self, chunk_id: &str) -> Result<Option<ChunkScore>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.chunk_score",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.chunk_score(chunk_id).await
+ }
+
+ /// Ingest progress for the sources the caller names, one row per query.
+ ///
+ /// Unlike [`Self::source_totals`], which enumerates the groups that exist
+ /// and therefore has to be narrowed to the ambient allowlist, this answers
+ /// only about prefixes the caller supplied — it discloses no source the
+ /// caller did not already name — and the contract member carries no
+ /// [`SourceScope`] for the guard to intersect anything into.
+ async fn source_ingest_status(
+ &self,
+ source_prefixes: &[SourceIngestQuery],
+ ) -> Result<Vec<SourceIngestStatus>, MemoryError> {
+ self.policy.admit_read(
+ Capability::Chunks,
+ "chunks.source_ingest_status",
+ NO_NAMESPACE,
+ false,
+ )?;
+ self.family()?.source_ingest_status(source_prefixes).await
+ }
+}
diff --git a/crates/openhuman-core/src/search/tools/parallel.rs b/crates/openhuman-core/src/search/tools/parallel.rs
index bf81c1c262..39024ff3b2 100644
--- a/crates/openhuman-core/src/search/tools/parallel.rs
+++ b/crates/openhuman-core/src/search/tools/parallel.rs
@@ -39,8 +39,8 @@ 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 enrich::{format_enrich_response, EnrichResponse};
+use enrich::{enrich_payload, format_enrich_response, EnrichResponse};
#[cfg(test)]
use extract::ExtractResponse;
#[cfg(test)]
-use research::{format_research_response, ResearchResponse};
+use research::{format_research_response, research_payload, ResearchResponse};
diff --git a/crates/openhuman-core/src/skills/ops_tests_part_02_tests.rs b/crates/openhuman-core/src/skills/ops_create_and_url_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/skills/ops_tests_part_02_tests.rs
rename to crates/openhuman-core/src/skills/ops_create_and_url_tests.rs
diff --git a/crates/openhuman-core/src/skills/ops_tests_part_01_tests.rs b/crates/openhuman-core/src/skills/ops_discovery_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/skills/ops_tests_part_01_tests.rs
rename to crates/openhuman-core/src/skills/ops_discovery_tests.rs
diff --git a/crates/openhuman-core/src/skills/ops_tests.rs b/crates/openhuman-core/src/skills/ops_tests.rs
index 48bfcaee97..f34cd29b3c 100644
--- a/crates/openhuman-core/src/skills/ops_tests.rs
+++ b/crates/openhuman-core/src/skills/ops_tests.rs
@@ -36,9 +36,9 @@ fn make_legacy_skill(ws: &Path, name: &str) -> PathBuf {
skill_dir
}
-#[path = "ops_tests_part_01_tests.rs"]
-mod part_01_tests;
-#[path = "ops_tests_part_02_tests.rs"]
-mod part_02_tests;
-#[path = "ops_tests_part_03_tests.rs"]
-mod part_03_tests;
+#[path = "ops_discovery_tests.rs"]
+mod discovery_tests;
+#[path = "ops_create_and_url_tests.rs"]
+mod create_and_url_tests;
+#[path = "ops_uninstall_tests.rs"]
+mod uninstall_tests;
diff --git a/crates/openhuman-core/src/skills/ops_tests_part_03_tests.rs b/crates/openhuman-core/src/skills/ops_uninstall_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/skills/ops_tests_part_03_tests.rs
rename to crates/openhuman-core/src/skills/ops_uninstall_tests.rs
diff --git a/crates/openhuman-core/src/tools/schemas.rs b/crates/openhuman-core/src/tools/schemas.rs
index b10286a2a6..b847d9b9ed 100644
--- a/crates/openhuman-core/src/tools/schemas.rs
+++ b/crates/openhuman-core/src/tools/schemas.rs
@@ -9,5 +9,10 @@
#[cfg(test)]
#[path = "schemas_tests.rs"]
mod tests;
-include!("schemas_part_01.rs");
-include!("schemas_part_02.rs");
+
+mod apify;
+mod composio;
+mod registry;
+mod web_search;
+
+pub use registry::{all_controller_schemas, all_registered_controllers, tools_schemas};
diff --git a/crates/openhuman-core/src/tools/schemas_part_01.rs b/crates/openhuman-core/src/tools/schemas_part_01.rs
deleted file mode 100644
index f6bdadd4ab..0000000000
--- a/crates/openhuman-core/src/tools/schemas_part_01.rs
+++ /dev/null
@@ -1,675 +0,0 @@
-use serde_json::{json, Map, Value};
-
-use crate::core::all::{ControllerFuture, RegisteredController};
-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};
-use crate::config::rpc as config_rpc;
-use crate::search::tools::SEARXNG_MAX_RESULTS;
-use crate::tools::traits::Tool;
-use crate::rpc::RpcOutcome;
-
-pub fn all_controller_schemas() -> Vec<ControllerSchema> {
- vec![
- tools_schemas("tools_composio_execute"),
- tools_schemas("tools_web_search"),
- tools_schemas("tools_seltz_search"),
- tools_schemas("tools_querit_search"),
- tools_schemas("tools_searxng_search"),
- tools_schemas("tools_apify_linkedin_scrape"),
- ]
-}
-
-pub fn all_registered_controllers() -> Vec<RegisteredController> {
- vec![
- RegisteredController {
- schema: tools_schemas("tools_composio_execute"),
- handler: handle_composio_execute,
- },
- RegisteredController {
- schema: tools_schemas("tools_web_search"),
- handler: handle_web_search,
- },
- RegisteredController {
- schema: tools_schemas("tools_seltz_search"),
- handler: handle_seltz_search,
- },
- RegisteredController {
- schema: tools_schemas("tools_querit_search"),
- handler: handle_querit_search,
- },
- RegisteredController {
- schema: tools_schemas("tools_searxng_search"),
- handler: handle_searxng_search,
- },
- RegisteredController {
- schema: tools_schemas("tools_apify_linkedin_scrape"),
- handler: handle_apify_linkedin_scrape,
- },
- ]
-}
-
-pub fn tools_schemas(function: &str) -> ControllerSchema {
- match function {
- "tools_composio_execute" => ControllerSchema {
- namespace: "tools",
- function: "composio_execute",
- description: "Execute a Composio action. Routes through the mode-aware \
- factory: backend mode proxies via the OpenHuman backend; \
- direct mode calls backend.composio.dev with the user's own \
- API key. Exposed for Tauri-driven flows (e.g. onboarding) \
- that orchestrate tool calls themselves.",
- inputs: vec![
- FieldSchema {
- name: "action",
- ty: TypeSchema::String,
- comment: "Composio action slug (e.g. `GMAIL_FETCH_EMAILS`).",
- required: true,
- },
- FieldSchema {
- name: "params",
- ty: TypeSchema::Json,
- comment: "Action parameters object passed straight through to Composio.",
- required: false,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "successful",
- ty: TypeSchema::Bool,
- comment: "Whether the upstream provider reported success.",
- required: true,
- },
- FieldSchema {
- name: "data",
- ty: TypeSchema::Json,
- comment: "Raw provider response.",
- required: true,
- },
- FieldSchema {
- name: "error",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Provider error message if `successful` is false.",
- required: false,
- },
- ],
- },
- "tools_web_search" => ControllerSchema {
- namespace: "tools",
- function: "web_search",
- description: "Web search via the backend Parallel proxy. Returns structured \
- results so callers can inspect titles, URLs, and excerpts \
- without parsing the agent-facing pretty text.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Search query string.",
- required: true,
- },
- FieldSchema {
- name: "objective",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional objective sent to Parallel (defaults to `query`).",
- required: false,
- },
- FieldSchema {
- name: "max_results",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max results (1-10, default 5).",
- required: false,
- },
- FieldSchema {
- name: "timeout_secs",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Request timeout in seconds (default 15).",
- required: false,
- },
- ],
- outputs: vec![
- FieldSchema {
- name: "results",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Each item: {url, title, publish_date?, excerpts[]}.",
- required: true,
- },
- FieldSchema {
- name: "provider",
- ty: TypeSchema::String,
- comment: "Upstream provider the managed backend resolved this \
- search to, for attribution. Reported by the backend when \
- it names one; falls back to the managed default.",
- required: true,
- },
- ],
- },
- "tools_seltz_search" => ControllerSchema {
- namespace: "tools",
- function: "seltz_search",
- description: "Web search via the Seltz API. Returns structured results with \
- URLs, content, and optional published dates. Supports domain \
- filtering, date ranges, and news scope.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Search query string.",
- required: true,
- },
- FieldSchema {
- name: "max_results",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max results (1-20, default 10).",
- required: false,
- },
- FieldSchema {
- name: "include_domains",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Restrict results to these domains.",
- required: false,
- },
- FieldSchema {
- name: "exclude_domains",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Exclude results from these domains.",
- required: false,
- },
- FieldSchema {
- name: "from_date",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Only results published on or after (YYYY-MM-DD).",
- required: false,
- },
- FieldSchema {
- name: "to_date",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Only results published on or before (YYYY-MM-DD).",
- required: false,
- },
- FieldSchema {
- name: "scope",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Restrict to a scope, e.g. \"news\".",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "documents",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Each item: {url, content, title?, published_date?}.",
- required: true,
- }],
- },
- "tools_querit_search" => ControllerSchema {
- namespace: "tools",
- function: "querit_search",
- description: "Web search via the Querit API. Returns current results with URLs, \
- snippets, site names, and page age. Supports site filters, \
- time ranges, country filters, and language filters.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Search query string.",
- required: true,
- },
- FieldSchema {
- name: "max_results",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max results (1-20, default 10).",
- required: false,
- },
- FieldSchema {
- name: "count",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Querit-native alias for max_results.",
- required: false,
- },
- FieldSchema {
- name: "filters",
- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),
- comment:
- "Querit-native filters object with sites, timeRange, geo, and languages.",
- required: false,
- },
- FieldSchema {
- name: "include_domains",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Only fetch results from these domains.",
- required: false,
- },
- FieldSchema {
- name: "exclude_domains",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Exclude results from these domains.",
- required: false,
- },
- FieldSchema {
- name: "time_range",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Querit date filter: d7, w2, m6, y1, or YYYY-MM-DDtoYYYY-MM-DD.",
- required: false,
- },
- FieldSchema {
- name: "from_date",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Start date for a Querit date-range filter (YYYY-MM-DD).",
- required: false,
- },
- FieldSchema {
- name: "to_date",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "End date for a Querit date-range filter (YYYY-MM-DD).",
- required: false,
- },
- FieldSchema {
- name: "countries",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Country filters, e.g. united states, japan, germany.",
- required: false,
- },
- FieldSchema {
- name: "languages",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::String,
- )))),
- comment: "Language filters, e.g. english, japanese, german.",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "results",
- ty: TypeSchema::String,
- comment: "Formatted Querit search results.",
- required: true,
- }],
- },
- "tools_searxng_search" => ControllerSchema {
- namespace: "tools",
- function: "searxng_search",
- description:
- "Web search via a user-configured SearXNG instance. Returns normalized \
- results with title, URL, snippet, and source. Intended for private, \
- self-hosted search without routing queries through the OpenHuman backend.",
- inputs: vec![
- FieldSchema {
- name: "query",
- ty: TypeSchema::String,
- comment: "Search query string.",
- required: true,
- },
- FieldSchema {
- name: "categories",
- ty: TypeSchema::Option(Box::new(TypeSchema::Array(Box::new(
- TypeSchema::Enum {
- variants: vec!["web", "general", "news", "images"],
- },
- )))),
- comment: "Optional SearXNG categories. `web` maps to SearXNG `general`.",
- required: false,
- },
- FieldSchema {
- name: "language",
- ty: TypeSchema::Option(Box::new(TypeSchema::String)),
- comment: "Optional language code, e.g. `en`, `zh-CN`, or `fr`.",
- required: false,
- },
- FieldSchema {
- name: "max_results",
- ty: TypeSchema::Option(Box::new(TypeSchema::U64)),
- comment: "Max results (1-50, default from searxng.max_results).",
- required: false,
- },
- ],
- outputs: vec![FieldSchema {
- name: "results",
- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),
- comment: "Each item: {title, url, snippet, source}.",
- required: true,
- }],
- },
- "tools_apify_linkedin_scrape" => ControllerSchema {
- namespace: "tools",
- function: "apify_linkedin_scrape",
- description: "Run the Apify LinkedIn profile scraper actor on a single profile \
- URL and return both the raw scraped item and a pre-rendered \
- markdown view of it (same layout as the legacy enrichment pipeline).",
- inputs: vec![FieldSchema {
- name: "profile_url",
- ty: TypeSchema::String,
- comment: "Canonical LinkedIn profile URL (`https://www.linkedin.com/in/<slug>`).",
- required: true,
- }],
- outputs: vec![
- FieldSchema {
- name: "data",
- ty: TypeSchema::Json,
- comment: "Raw scraped profile JSON from Apify.",
- required: true,
- },
- FieldSchema {
- name: "markdown",
- ty: TypeSchema::String,
- comment: "Markdown rendering of the scraped profile (full, pre-summary).",
- required: true,
- },
- ],
- },
- _ => ControllerSchema {
- namespace: "tools",
- function: "unknown",
- description: "Unknown tools controller.",
- inputs: vec![],
- outputs: vec![FieldSchema {
- name: "error",
- ty: TypeSchema::String,
- comment: "Lookup error details.",
- required: true,
- }],
- },
- }
-}
-
-fn handle_composio_execute(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let action = params
- .get("action")
- .and_then(Value::as_str)
- .map(str::to_string)
- .ok_or_else(|| "missing required `action`".to_string())?;
- let action_args = params.get("params").cloned();
-
- let config = config_rpc::load_config_with_timeout().await?;
- // Route through the mode-aware factory so direct-mode users
- // hit their personal Composio tenant when the Tauri shell
- // calls `tools.composio_execute` (e.g. onboarding-driven
- // flows). Pre-fix, the controller hard-bound to the
- // backend-only `build_composio_client` and silently 4xx'd for
- // direct-mode users (#1710). Mirrors
- // `composio::ops::composio_execute`.
- use crate::integrations::composio::client::{
- create_composio_client, direct_execute, ComposioClientKind,
- };
- let kind =
- create_composio_client(&config).map_err(|e| format!("tools.composio_execute: {e}"))?;
- tracing::debug!(
- action = %action,
- mode = %config.composio.mode,
- "[tools][composio_execute] executing action"
- );
- let resp = match kind {
- ComposioClientKind::Backend(client) => {
- tracing::debug!(action = %action, "[tools][composio_execute] branch=backend");
- client
- .execute_tool(&action, action_args)
- .await
- .map_err(|e| format!("composio execute_tool (backend) failed: {e:#}"))?
- }
- ComposioClientKind::Direct(direct) => {
- tracing::debug!(action = %action, "[tools][composio_execute] branch=direct");
- direct_execute(
- &direct,
- &action,
- action_args,
- &config.composio.entity_id,
- None,
- )
- .await
- .map_err(|e| format!("composio execute_tool (direct) failed: {e:#}"))?
- }
- };
- tracing::debug!(
- action = %action,
- successful = resp.successful,
- "[tools][composio_execute] complete"
- );
-
- let payload = json!({
- "successful": resp.successful,
- "data": resp.data,
- "error": resp.error,
- "cost_usd": resp.cost_usd,
- "markdown_formatted": resp.markdown_formatted,
- });
- let log = vec![format!(
- "tools.composio_execute: action={action} successful={}",
- resp.successful
- )];
- RpcOutcome::new(payload, log).into_cli_compatible_json()
- })
-}
-
-fn handle_web_search(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = params
- .get("query")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .ok_or_else(|| "missing or empty `query`".to_string())?;
- let objective = params
- .get("objective")
- .and_then(Value::as_str)
- .map(str::to_string)
- .unwrap_or_else(|| query.clone());
- let max_results = params
- .get("max_results")
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 10) as usize)
- .unwrap_or(5);
- let timeout_secs = params
- .get("timeout_secs")
- .and_then(Value::as_u64)
- .map(|n| n.max(1))
- .unwrap_or(15);
-
- let config = config_rpc::load_config_with_timeout().await?;
- let client = crate::integrations::build_client(&config).ok_or_else(|| {
- "web search unavailable — no backend session token. Sign in first.".to_string()
- })?;
-
- // Body matches `parallelSearchSchema` (backend-2/.../validators/agentIntegration.validator.ts).
- // `timeout_secs` remains accepted in our RPC schema for compatibility
- // with existing callers, but the upstream validator currently strips
- // unknown keys and Parallel governs its own per-mode deadline.
- let _ = timeout_secs;
- let body = json!({
- "objective": objective,
- "searchQueries": [query],
- "mode": "fast",
- "excerpts": {
- "maxResults": max_results,
- "maxCharsPerResult": 500
- }
- });
-
- let resp = client
- .post::<crate::search::tools::SearchResponse>(
- "/agent-integrations/parallel/search",
- &body,
- )
- .await
- .map_err(|e| format!("parallel search failed: {e:#}"))?;
-
- let count = resp.results.len();
- // Attribute the search to the provider the managed backend resolved to,
- // so this RPC surface labels a call the same way the agent-facing
- // `web_search` tool does (#5136).
- let provider = crate::search::tools::resolve_managed_provider(&resp);
- let payload = json!({ "results": resp.results, "provider": provider });
- // Log the query's length, never its text: a search query is
- // user-authored and can carry PII or credentials. This matches the
- // sibling seltz/querit handlers below, which already log `query_len`.
- let log = vec![format!(
- "tools.web_search: query_len={} results={count} provider={provider}",
- query.chars().count()
- )];
- RpcOutcome::new(payload, log).into_cli_compatible_json()
- })
-}
-
-fn handle_seltz_search(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = params
- .get("query")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .ok_or_else(|| "missing or empty `query`".to_string())?;
- let max_results = params
- .get("max_results")
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 20) as usize)
- .unwrap_or(10);
-
- let config = config_rpc::load_config_with_timeout().await?;
-
- if !config.seltz.enabled {
- tracing::debug!("[rpc][tools.seltz_search] seltz disabled — rejecting");
- return Err("Seltz search is not enabled. Set SELTZ_API_KEY to enable.".to_string());
- }
-
- let has_include_domains = params.get("include_domains").is_some();
- let has_exclude_domains = params.get("exclude_domains").is_some();
- let has_scope = params.get("scope").is_some();
-
- tracing::debug!(
- query_len = query.chars().count(),
- max_results,
- has_include_domains,
- has_exclude_domains,
- has_scope,
- "[rpc][tools.seltz_search] start"
- );
-
- let tool = crate::search::tools::SeltzSearchTool::new(
- config.seltz.api_key.clone(),
- config.seltz.api_url.clone(),
- max_results,
- config.seltz.timeout_secs,
- );
-
- // Build args JSON with all optional fields.
- let mut args = json!({ "query": query, "max_results": max_results });
- let args_map = args.as_object_mut().unwrap();
- if let Some(v) = params.get("include_domains") {
- args_map.insert("include_domains".to_string(), v.clone());
- }
- if let Some(v) = params.get("exclude_domains") {
- args_map.insert("exclude_domains".to_string(), v.clone());
- }
- if let Some(v) = params.get("from_date") {
- args_map.insert("from_date".to_string(), v.clone());
- }
- if let Some(v) = params.get("to_date") {
- args_map.insert("to_date".to_string(), v.clone());
- }
- if let Some(v) = params.get("scope") {
- args_map.insert("scope".to_string(), v.clone());
- }
-
- let result = tool
- .execute(args)
- .await
- .map_err(|e| format!("seltz search failed: {e:#}"))?;
-
- let payload = json!({ "documents": result.output() });
- let log = vec![format!(
- "[rpc][tools.seltz_search] success query_len={} max_results={}",
- query.chars().count(),
- max_results
- )];
- RpcOutcome::new(payload, log).into_cli_compatible_json()
- })
-}
-
-fn handle_querit_search(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = params
- .get("query")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .ok_or_else(|| "missing or empty `query`".to_string())?;
- let max_results = params
- .get("max_results")
- .or_else(|| params.get("count"))
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, 20) as usize)
- .unwrap_or(10);
-
- let config = config_rpc::load_config_with_timeout().await?;
- if !config.search.querit.has_key() {
- tracing::debug!("[rpc][tools.querit_search] querit not configured — rejecting");
- return Err("Querit search is not enabled. Set QUERIT_API_KEY to enable.".to_string());
- }
-
- let has_include_domains = params.get("include_domains").is_some();
- let has_exclude_domains = params.get("exclude_domains").is_some();
- let has_time_range = params.get("time_range").is_some();
- let has_countries = params.get("countries").is_some();
- let has_languages = params.get("languages").is_some();
- let has_native_filters = params.get("filters").is_some();
-
- tracing::debug!(
- query_len = query.chars().count(),
- max_results,
- has_include_domains,
- has_exclude_domains,
- has_time_range,
- has_countries,
- has_languages,
- has_native_filters,
- "[rpc][tools.querit_search] start"
- );
-
- let tool = crate::search::tools::QueritSearchTool::new(
- config.search.querit.api_key.clone(),
- None,
- max_results,
- config.search.timeout_secs,
- );
-
- let mut args = json!({ "query": query, "max_results": max_results });
- let args_map = args.as_object_mut().unwrap();
- for key in [
- "count",
- "filters",
- "include_domains",
- "exclude_domains",
- "time_range",
- "from_date",
- "to_date",
- "countries",
- "languages",
- ] {
- if let Some(v) = params.get(key) {
- args_map.insert(key.to_string(), v.clone());
- }
- }
-
- let result = tool
- .execute(args)
- .await
- .map_err(|e| format!("querit search failed: {e:#}"))?;
-
- let payload = json!({ "results": result.output() });
- let log = vec![format!(
- "[rpc][tools.querit_search] success query_len={} max_results={}",
- query.chars().count(),
- max_results
- )];
- RpcOutcome::new(payload, log).into_cli_compatible_json()
- })
-}
diff --git a/crates/openhuman-core/src/tools/schemas_part_02.rs b/crates/openhuman-core/src/tools/schemas_part_02.rs
deleted file mode 100644
index 8ecd480d3f..0000000000
--- a/crates/openhuman-core/src/tools/schemas_part_02.rs
+++ /dev/null
@@ -1,127 +0,0 @@
-
-fn handle_searxng_search(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let query = params
- .get("query")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .ok_or_else(|| "missing or empty `query`".to_string())?;
- let max_results = params
- .get("max_results")
- .and_then(Value::as_u64)
- .map(|n| n.clamp(1, SEARXNG_MAX_RESULTS as u64) as usize);
- let categories = optional_string_array(&params, "categories")?;
- let language = params
- .get("language")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string);
-
- let config = config_rpc::load_config_with_timeout().await?;
- if !config.searxng.enabled {
- tracing::debug!("[rpc][tools.searxng_search] searxng disabled — rejecting");
- return Err(
- "SearXNG search is not enabled. Set searxng.enabled=true or OPENHUMAN_SEARXNG_ENABLED=true."
- .to_string(),
- );
- }
-
- tracing::debug!(
- query_len = query.chars().count(),
- max_results = max_results.unwrap_or(config.searxng.max_results),
- category_count = categories.len(),
- has_language = language.is_some(),
- base_url = %config.searxng.base_url,
- "[rpc][tools.searxng_search] start"
- );
-
- let tool = crate::search::tools::SearxngSearchTool::new(
- config.searxng.base_url.clone(),
- config.searxng.max_results,
- config.searxng.default_language.clone(),
- config.searxng.timeout_secs,
- );
-
- let response = tool
- .search(crate::search::tools::SearxngSearchArgs {
- query,
- categories,
- language,
- max_results,
- })
- .await
- .map_err(|e| format!("searxng search failed: {e:#}"))?;
-
- let result_count = response.results.len();
- let payload = json!({
- "query": response.query,
- "results": response.results,
- });
- let log = vec![format!(
- "[rpc][tools.searxng_search] success results={result_count}"
- )];
- RpcOutcome::new(payload, log).into_cli_compatible_json()
- })
-}
-
-fn handle_apify_linkedin_scrape(params: Map<String, Value>) -> ControllerFuture {
- Box::pin(async move {
- let profile_url = params
- .get("profile_url")
- .and_then(Value::as_str)
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- .ok_or_else(|| "missing or empty `profile_url`".to_string())?;
-
- let config = config_rpc::load_config_with_timeout().await?;
- let client = crate::integrations::build_client(&config).ok_or_else(|| {
- "Apify scrape unavailable — no backend session token. Sign in first.".to_string()
- })?;
-
- let data = crate::agent::learning::linkedin_enrichment::scrape_linkedin_profile(
- &client,
- &profile_url,
- )
- .await
- .map_err(|e| format!("Apify LinkedIn scrape failed: {e:#}"))?;
-
- let markdown =
- crate::agent::learning::linkedin_enrichment::render_profile_markdown(
- &profile_url,
- &data,
- );
-
- let payload = json!({ "data": data, "markdown": markdown });
- let log = vec![format!(
- "tools.apify_linkedin_scrape: url={profile_url} markdown_chars={}",
- markdown.chars().count()
- )];
- RpcOutcome::new(payload, log).into_cli_compatible_json()
- })
-}
-
-fn optional_string_array(params: &Map<String, Value>, key: &str) -> Result<Vec<String>, String> {
- let Some(value) = params.get(key) else {
- return Ok(Vec::new());
- };
- if value.is_null() {
- return Ok(Vec::new());
- }
- let items = value
- .as_array()
- .ok_or_else(|| format!("`{key}` must be an array of strings"))?;
- items
- .iter()
- .filter_map(|item| match item.as_str() {
- Some(value) => {
- let trimmed = value.trim();
- (!trimmed.is_empty()).then(|| Ok(trimmed.to_string()))
- }
- None => Some(Err(format!("`{key}` must contain only strings"))),
- })
- .collect()
-}