Skip to content

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

refactor(profiles): thread profile capabilities through host agent construction

Steven Enamakel9b454a05f98c
diff --git a/crates/openhuman-core/src/agent/host_agents.rs b/crates/openhuman-core/src/agent/host_agents.rs
index 403e54249e..7bad89cccd 100644
--- a/crates/openhuman-core/src/agent/host_agents.rs
+++ b/crates/openhuman-core/src/agent/host_agents.rs
@@ -72,16 +72,23 @@ impl HostAgent {
self.hooks.clone().sync_scope(|| {
CoreContext::sync_scope(Arc::clone(&self.context), || {
if crate::profiles::capabilities::ProfileCapabilities::current().is_some() {
- return OpenHumanSessionHost::from_config_host_only(config, &self.definition, self.host_tools.as_ref(), session_id);
+ return OpenHumanSessionHost::from_config_host_only(
+ config,
+ &self.definition,
+ self.host_tools.as_ref(),
+ session_id,
+ );
}
match &self.host_tools {
- Some(host) => OpenHumanSessionHost::from_config_with_host_tools(
- config,
- &self.definition,
- host,
- session_id,
- ),
- None => OpenHumanSessionHost::from_config_with_definition(config, &self.definition),
+ Some(host) => OpenHumanSessionHost::from_config_with_host_tools(
+ config,
+ &self.definition,
+ host,
+ session_id,
+ ),
+ None => {
+ OpenHumanSessionHost::from_config_with_definition(config, &self.definition)
+ }
}
})
})
diff --git a/crates/openhuman-core/src/agent/host_overrides.rs b/crates/openhuman-core/src/agent/host_overrides.rs
index ac6477824f..a25ab02f2a 100644
--- a/crates/openhuman-core/src/agent/host_overrides.rs
+++ b/crates/openhuman-core/src/agent/host_overrides.rs
@@ -43,8 +43,14 @@ impl std::fmt::Debug for HostOverrides {
impl HostOverrides {
/// Resolve inherited profile adapters without installing process globals.
- pub fn profile_capabilities(&self) -> Option<Arc<crate::profiles::capabilities::ProfileCapabilities>> {
- self.profile_capabilities.clone().or_else(|| self.parent.as_ref().and_then(|parent| parent.profile_capabilities()))
+ pub fn profile_capabilities(
+ &self,
+ ) -> Option<Arc<crate::profiles::capabilities::ProfileCapabilities>> {
+ self.profile_capabilities.clone().or_else(|| {
+ self.parent
+ .as_ref()
+ .and_then(|parent| parent.profile_capabilities())
+ })
}
/// Resolve the instance barrier inherited by derived turn contexts.
diff --git a/crates/openhuman-core/src/agent/session_host/builder/factory.rs b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
index 549f137492..596198b53e 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -85,7 +85,11 @@ impl OpenHumanSessionHost {
///
/// # Errors
/// As [`Self::from_config_for_agent`].
- pub fn from_config_for_agent_session(config: &Config, agent_id: &str, session_id: Option<&str>) -> Result<Self> {
+ pub fn from_config_for_agent_session(
+ config: &Config,
+ agent_id: &str,
+ session_id: Option<&str>,
+ ) -> Result<Self> {
// Look up the target definition up front so we can fail fast
// with a clear error instead of building half an agent and then
// discovering the id is unknown. See `resolve_target_definition`
@@ -120,11 +124,19 @@ impl OpenHumanSessionHost {
);
if let Some(capabilities) = crate::profiles::capabilities::ProfileCapabilities::current() {
- let definition = target_def.ok_or_else(|| anyhow::anyhow!("profile agent definition is unavailable"))?;
+ let definition = target_def
+ .ok_or_else(|| anyhow::anyhow!("profile agent definition is unavailable"))?;
let factory = capabilities.factory(config);
return Self::from_config_host_only(config, &definition, Some(&factory), session_id);
}
- Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false, None, session_id)
+ Self::build_session_agent_inner(
+ config,
+ agent_id,
+ target_def.as_ref(),
+ false,
+ None,
+ session_id,
+ )
}
/// Build a session agent from a definition the caller already holds,
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs
index 58fbbf027b..c4e5d3b2a5 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/mod.rs
@@ -54,9 +54,19 @@ pub(crate) fn bound_agent_id<'a>(config: &'a Config, channel: &str) -> Option<&'
/// Resolve `channel`'s binding against the installed host agents.
pub(crate) fn route(ctx: &ChannelRuntimeContext, channel: &str) -> HostRoute {
if let Some(capabilities) = crate::profiles::capabilities::ProfileCapabilities::current() {
- if let (Some(context), Some(config), Some(definitions)) = (crate::core::runtime::CoreContext::current(), ctx.config.as_ref(), crate::agent::harness::definition::AgentDefinitionRegistry::current()) {
+ if let (Some(context), Some(config), Some(definitions)) = (
+ crate::core::runtime::CoreContext::current(),
+ ctx.config.as_ref(),
+ crate::agent::harness::definition::AgentDefinitionRegistry::current(),
+ ) {
if let Some(definition) = definitions.get("orchestrator") {
- return HostRoute::Agent(Box::new(HostAgent { definition: definition.clone(), config: config.as_ref().clone(), host_tools: Some(capabilities.factory(config)), context, hooks: Default::default() }));
+ return HostRoute::Agent(Box::new(HostAgent {
+ definition: definition.clone(),
+ config: config.as_ref().clone(),
+ host_tools: Some(capabilities.factory(config)),
+ context,
+ hooks: Default::default(),
+ }));
}
}
return HostRoute::Missing("profile agent".into());
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
index cf01b78492..d98c6fa629 100644
--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/turn.rs
@@ -43,8 +43,14 @@ pub(crate) async fn run_host_agent_turn(
progress,
} = turn;
let mut config = host.config.clone();
- let profile_ceiling = host.context.host_overrides().and_then(|host| host.profile_capabilities()).map(|caps| caps.channel_permission(&channel));
- if let Some(ceiling) = profile_ceiling.filter(|level| *level > tinytools::PermissionLevel::ReadOnly) {
+ let profile_ceiling = host
+ .context
+ .host_overrides()
+ .and_then(|host| host.profile_capabilities())
+ .map(|caps| caps.channel_permission(&channel));
+ if let Some(ceiling) =
+ profile_ceiling.filter(|level| *level > tinytools::PermissionLevel::ReadOnly)
+ {
posture::cap_channel(&mut config, &channel, ceiling);
} else if let Some(ceiling) = posture::tool_ceiling(&origin) {
posture::cap_channel(&mut config, &channel, ceiling);
@@ -62,7 +68,14 @@ pub(crate) async fn run_host_agent_turn(
"[channels::dispatch::host_agent] running channel turn as host agent"
);
- let mut session = host.session_host(&config, Some(crate::channels::providers::relay::current_thread_id().as_deref().unwrap_or(&history_key)))?;
+ let mut session = host.session_host(
+ &config,
+ Some(
+ crate::channels::providers::relay::current_thread_id()
+ .as_deref()
+ .unwrap_or(&history_key),
+ ),
+ )?;
// The channel names the session, which also selects the channel's
// permission ceiling in the session's tool policy.
session.set_event_context(history_key, channel);
diff --git a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
index 40d8e96d05..ea3452e1c2 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
@@ -142,32 +142,47 @@ pub(crate) fn build_channel_turn_parts(
)?;
let workspace = config.workspace_dir.clone();
let capabilities = crate::profiles::capabilities::ProfileCapabilities::current();
- let tools_registry = Arc::new(if let Some(caps) = &capabilities {
- caps.turn_tools(config, crate::agent::TurnContext::new("orchestrator", crate::channels::providers::relay::current_thread_id().as_deref())).tools
- } else { tools::ops::all_tools_with_runtime(
- Arc::new(config.clone()),
- security,
- runtime,
- audit,
- // `all_tools_with_runtime` no longer takes a memory handle — the two
- // tools that needed one resolve the guarded driver per call.
- &config.browser,
- &config.http_request,
- &config.action_dir,
- &config.agents,
- config,
- None,
- ) });
+ let tools_registry = Arc::new(if capabilities.is_some() {
+ // The profile host route builds the selected belt once with the exact
+ // durable thread. No second, unnamed factory invocation is needed here.
+ Vec::new()
+ } else {
+ tools::ops::all_tools_with_runtime(
+ Arc::new(config.clone()),
+ security,
+ runtime,
+ audit,
+ // `all_tools_with_runtime` no longer takes a memory handle — the two
+ // tools that needed one resolve the guarded driver per call.
+ &config.browser,
+ &config.http_request,
+ &config.action_dir,
+ &config.agents,
+ config,
+ None,
+ )
+ });
- let skills = if capabilities.is_some() { Vec::new() } else { crate::skills::load_workflow_metadata(&workspace) };
+ let skills = if capabilities.is_some() {
+ Vec::new()
+ } else {
+ crate::skills::load_workflow_metadata(&workspace)
+ };
- let tool_descs: Vec<(String, String)> = if capabilities.is_some() { tools_registry.iter().map(|tool| (tool.name().to_owned(), tool.description().to_owned())).collect() } else { default_tool_descs(config)
- .into_iter()
- .filter(|(name, _)| {
- descs == PromptToolDescs::Fixed || tools_registry.iter().any(|t| t.name() == *name)
- })
- .map(|(name, desc)| (name.to_string(), desc.to_string()))
- .collect() };
+ let tool_descs: Vec<(String, String)> = if capabilities.is_some() {
+ tools_registry
+ .iter()
+ .map(|tool| (tool.name().to_owned(), tool.description().to_owned()))
+ .collect()
+ } else {
+ default_tool_descs(config)
+ .into_iter()
+ .filter(|(name, _)| {
+ descs == PromptToolDescs::Fixed || tools_registry.iter().any(|t| t.name() == *name)
+ })
+ .map(|(name, desc)| (name.to_string(), desc.to_string()))
+ .collect()
+ };
let bootstrap_max_chars = if config.agent.compact_context {
Some(6000)
diff --git a/crates/openhuman-core/src/memory/engine.rs b/crates/openhuman-core/src/memory/engine.rs
index 1655d475c6..1b5e849f3b 100644
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@ -207,10 +207,25 @@ fn host_engine() -> Option<BoundEngine> {
pub fn resolve(config: &Config) -> Binding {
if let Some(capabilities) = crate::profiles::capabilities::ProfileCapabilities::current() {
if let Some(engine) = &capabilities.memory_engine {
- let profile = crate::core::runtime::current_tenant().ok().and_then(|tenant| tenant.profile);
- let valid = profile.as_ref().is_some_and(|id| config.memory.agent_id.as_ref() == Some(id) && config.memory.root.as_deref() == Some(format!("user:{id}").as_str()));
- if !valid { return off(None, None, "profile memory binding requires its forced namespace"); }
- return Binding::On(BoundEngine { id: engine.descriptor().id.to_string(), endpoint: HOST_ENGINE_ENDPOINT.to_string(), engine: super::guard::ScrubbingEngine::wrap(Arc::clone(engine)) });
+ let profile = crate::core::runtime::current_tenant()
+ .ok()
+ .and_then(|tenant| tenant.profile);
+ let valid = profile.as_ref().is_some_and(|id| {
+ config.memory.agent_id.as_ref() == Some(id)
+ && config.memory.root.as_deref() == Some(format!("user:{id}").as_str())
+ });
+ if !valid {
+ return off(
+ None,
+ None,
+ "profile memory binding requires its forced namespace",
+ );
+ }
+ return Binding::On(BoundEngine {
+ id: engine.descriptor().id.to_string(),
+ endpoint: HOST_ENGINE_ENDPOINT.to_string(),
+ engine: super::guard::ScrubbingEngine::wrap(Arc::clone(engine)),
+ });
}
}
#[cfg(test)]
diff --git a/crates/openhuman-core/src/profiles/capabilities.rs b/crates/openhuman-core/src/profiles/capabilities.rs
index 8dbc55f9cb..5d085f94b9 100644
--- a/crates/openhuman-core/src/profiles/capabilities.rs
+++ b/crates/openhuman-core/src/profiles/capabilities.rs
@@ -4,13 +4,13 @@
//! call additionally passes the profile lease fence and the host permission
//! callback. These adapters never install process-wide user capabilities.
-use std::collections::{HashMap, HashSet};
-use std::sync::Arc;
-use crate::agent::{HostTools, HostTurnTools, TurnContext};
use crate::agent::hooks::{ToolHook, ToolHookContext, ToolHookDecision};
-use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+use crate::agent::{HostTools, HostTurnTools, TurnContext};
use crate::config::Config;
+use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
use crate::tools::toolpacks::{GroupMode, ToolGroups};
+use std::collections::{HashMap, HashSet};
+use std::sync::Arc;
use tinytools::PermissionLevel;
/// Capabilities fixed when the profile runtime boots.
@@ -26,8 +26,22 @@ pub struct ProfileCapabilities {
impl ProfileCapabilities {
/// Construct immutable adapters. `None` names select only supplied host tools.
- pub fn new(host: Option<HostTools>, names: Option<HashSet<String>>, permission: Option<Arc<dyn ToolHook>>, channels: HashMap<String, PermissionLevel>, groups: Vec<super::tools::SaasToolGroup>, memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>) -> Self {
- Self { host, names, permission, channels, groups, memory_engine }
+ pub fn new(
+ host: Option<HostTools>,
+ names: Option<HashSet<String>>,
+ permission: Option<Arc<dyn ToolHook>>,
+ channels: HashMap<String, PermissionLevel>,
+ groups: Vec<super::tools::SaasToolGroup>,
+ memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,
+ ) -> Self {
+ Self {
+ host,
+ names,
+ permission,
+ channels,
+ groups,
+ memory_engine,
+ }
}
/// Capabilities of the ambient authenticated profile, never the operator.
@@ -44,27 +58,44 @@ impl ProfileCapabilities {
/// Overlay the operator's explicit ceilings; unknown channels stay read-only.
pub fn configure(&self, config: &mut Config) {
- config.agent.channel_permissions.extend(self.channels.iter().map(|(name, level)| (name.clone(), level.to_string().to_lowercase())));
+ config.agent.channel_permissions.extend(
+ self.channels
+ .iter()
+ .map(|(name, level)| (name.clone(), level.to_string().to_lowercase())),
+ );
}
/// Whether a selected name may reach the host permission decision.
pub fn admits(&self, name: &str) -> bool {
super::tools::admits_with(name, true, &self.groups)
- && !matches!(name, "http_request" | "spawn_agent" | "spawn_async_subagent" | "use_skill")
+ && !matches!(
+ name,
+ "http_request" | "spawn_agent" | "spawn_async_subagent" | "use_skill"
+ )
&& !name.starts_with("delegate_")
&& !name.starts_with("mcp_")
- && !crate::tools::toolpacks::pack_for_tool(name).is_some_and(|pack| pack.id == "workflows")
+ && !crate::tools::toolpacks::pack_for_tool(name)
+ .is_some_and(|pack| pack.id == "workflows")
&& self.names.as_ref().is_none_or(|names| names.contains(name))
}
/// An explicitly named operation can pass the supervised gate only with a host callback.
pub fn authorizes_approval(&self, name: &str) -> bool {
- self.permission.is_some() && self.names.as_ref().is_some_and(|names| names.contains(name)) && self.admits(name)
+ self.permission.is_some()
+ && self
+ .names
+ .as_ref()
+ .is_some_and(|names| names.contains(name))
+ && self.admits(name)
}
/// Build the exact selected belt for this profile and session.
pub fn turn_tools(&self, config: &Config, turn: TurnContext<'_>) -> HostTurnTools {
- let mut supplied = self.host.as_ref().map(|host| host(turn)).unwrap_or_default();
+ let mut supplied = self
+ .host
+ .as_ref()
+ .map(|host| host(turn))
+ .unwrap_or_default();
supplied.tools.retain(|tool| self.admits(tool.name()));
if let Some(names) = &self.names {
let mut groups = ToolGroups::none();
@@ -76,16 +107,45 @@ impl ProfileCapabilities {
if let Some(ctx) = CoreContext::current() {
// Domain selection here is local to native construction. It neither
// enables profile RPCs nor adds an unselected tool to the session.
- let assembly = ctx.derive_with(ContextOverlay::new(config.clone(), DomainSet::full(), groups));
- let security = Arc::new(crate::security::SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir));
- let native = CoreContext::sync_scope(assembly, || crate::tools::ops::all_tools(Arc::new(config.clone()), &security, crate::security::AuditLogger::disabled(), &config.browser, &config.http_request, &config.action_dir, &config.agents, config));
- let supplied_names: HashSet<_> = supplied.tools.iter().map(|t| t.name().to_string()).collect();
- supplied.tools.extend(native.into_iter().filter(|tool| self.admits(tool.name()) && !supplied_names.contains(tool.name())));
+ let assembly = ctx.derive_with(ContextOverlay::new(
+ config.clone(),
+ DomainSet::full(),
+ groups,
+ ));
+ let security = Arc::new(crate::security::SecurityPolicy::from_config(
+ &config.autonomy,
+ &config.workspace_dir,
+ &config.action_dir,
+ ));
+ let native = CoreContext::sync_scope(assembly, || {
+ crate::tools::ops::all_tools(
+ Arc::new(config.clone()),
+ &security,
+ crate::security::AuditLogger::disabled(),
+ &config.browser,
+ &config.http_request,
+ &config.action_dir,
+ &config.agents,
+ config,
+ )
+ });
+ let supplied_names: HashSet<_> = supplied
+ .tools
+ .iter()
+ .map(|t| t.name().to_string())
+ .collect();
+ supplied.tools.extend(native.into_iter().filter(|tool| {
+ self.admits(tool.name()) && !supplied_names.contains(tool.name())
+ }));
}
}
// Metadata from the host cannot widen registration or hide a registered
// tool from the catalogue: the selected belt is advertised exactly.
- supplied.visible = supplied.tools.iter().map(|tool| tool.name().to_string()).collect();
+ supplied.visible = supplied
+ .tools
+ .iter()
+ .map(|tool| tool.name().to_string())
+ .collect();
supplied.permanent.clear();
supplied.withheld.clear();
supplied
@@ -99,8 +159,16 @@ impl ProfileCapabilities {
}
/// Bind the permission callback to the owning profile's lease.
- pub fn hook(self: &Arc<Self>, profile: &super::ProfileId, fence: Arc<crate::storage::fence::LeaseFence>) -> Arc<dyn ToolHook> {
- Arc::new(ProfilePermission { capabilities: Arc::clone(self), profile: profile.as_str().to_owned(), fence })
+ pub fn hook(
+ self: &Arc<Self>,
+ profile: &super::ProfileId,
+ fence: Arc<crate::storage::fence::LeaseFence>,
+ ) -> Arc<dyn ToolHook> {
+ Arc::new(ProfilePermission {
+ capabilities: Arc::clone(self),
+ profile: profile.as_str().to_owned(),
+ fence,
+ })
}
}
@@ -112,17 +180,32 @@ struct ProfilePermission {
#[async_trait::async_trait]
impl ToolHook for ProfilePermission {
- fn name(&self) -> &str { "profile.can_use_tool" }
- async fn before_tool(&self, _: &ToolHookContext) -> anyhow::Result<()> { Ok(()) }
- async fn after_tool(&self, _: &ToolHookContext) -> anyhow::Result<()> { Ok(()) }
+ fn name(&self) -> &str {
+ "profile.can_use_tool"
+ }
+ async fn before_tool(&self, _: &ToolHookContext) -> anyhow::Result<()> {
+ Ok(())
+ }
+ async fn after_tool(&self, _: &ToolHookContext) -> anyhow::Result<()> {
+ Ok(())
+ }
async fn before_tool_decision(&self, context: &ToolHookContext) -> ToolHookDecision {
- let tenant = crate::core::runtime::current_tenant().ok().and_then(|tenant| tenant.profile);
- if tenant.as_deref() != Some(self.profile.as_str()) || self.fence.check_local(super::lease::now_ms()).is_err() || !self.capabilities.admits(&context.tool_name) {
- return ToolHookDecision::Deny("tool is outside the hosted profile capability boundary".into());
+ let tenant = crate::core::runtime::current_tenant()
+ .ok()
+ .and_then(|tenant| tenant.profile);
+ if tenant.as_deref() != Some(self.profile.as_str())
+ || self.fence.check_local(super::lease::now_ms()).is_err()
+ || !self.capabilities.admits(&context.tool_name)
+ {
+ return ToolHookDecision::Deny(
+ "tool is outside the hosted profile capability boundary".into(),
+ );
}
match &self.capabilities.permission {
Some(permission) => permission.before_tool_decision(context).await,
- None => ToolHookDecision::Deny("this profile has no host tool permission callback".into()),
+ None => {
+ ToolHookDecision::Deny("this profile has no host tool permission callback".into())
+ }
}
}
}
diff --git a/crates/openhuman-core/src/profiles/host.rs b/crates/openhuman-core/src/profiles/host.rs
index 8ea283e884..6f006126f2 100644
--- a/crates/openhuman-core/src/profiles/host.rs
+++ b/crates/openhuman-core/src/profiles/host.rs
@@ -168,7 +168,10 @@ impl ProfileHost {
}
/// Install immutable operator adapters before this host is shared.
- pub fn with_capabilities(mut self, capabilities: Option<Arc<super::capabilities::ProfileCapabilities>>) -> Self {
+ pub fn with_capabilities(
+ mut self,
+ capabilities: Option<Arc<super::capabilities::ProfileCapabilities>>,
+ ) -> Self {
self.capabilities = capabilities;
self
}
@@ -297,7 +300,9 @@ impl ProfileHost {
return Err(OpenError::Storage(error));
}
let mut config = layout::profile_config(&layout, id);
- if let Some(capabilities) = &self.capabilities { capabilities.configure(&mut config); }
+ if let Some(capabilities) = &self.capabilities {
+ capabilities.configure(&mut config);
+ }
let fence = super::fence::for_grant(
Arc::clone(&self.leases),
&self.node,
@@ -306,12 +311,17 @@ impl ProfileHost {
self.saas.lease_ttl(),
);
let mut overlay = ContextOverlay::new(config.clone(), user_domains(), ToolGroups::none())
- .without_user_skill_roots().profile(id.as_str()).agent_policy(profile_policy(&config));
+ .without_user_skill_roots()
+ .profile(id.as_str())
+ .agent_policy(profile_policy(&config));
if let Some(capabilities) = &self.capabilities {
let mut overrides = crate::agent::host_overrides::HostOverrides::default();
overrides.parent = self.operator.host_overrides();
overrides.profile_capabilities = Some(Arc::clone(capabilities));
- overrides.tool_hook("profile.can_use_tool", Some(capabilities.hook(id, Arc::clone(&fence))));
+ overrides.tool_hook(
+ "profile.can_use_tool",
+ Some(capabilities.hook(id, Arc::clone(&fence))),
+ );
overlay = overlay.host_overrides(Arc::new(overrides));
}
let context = self.operator.derive_with(overlay);
diff --git a/crates/openhuman-core/src/profiles/layout.rs b/crates/openhuman-core/src/profiles/layout.rs
index 82b0778993..84f9684ec5 100644
--- a/crates/openhuman-core/src/profiles/layout.rs
+++ b/crates/openhuman-core/src/profiles/layout.rs
@@ -70,7 +70,8 @@ pub fn profile_config(layout: &ProfileLayout, id: &ProfileId) -> Config {
config.memory.agent_id = Some(id.to_string());
config.memory.root = Some(memory_root(id));
config.memory.layout = MemoryLayoutMode::Legacy;
- config.agent.channel_permissions = std::collections::HashMap::from([("profile".into(), "readonly".into())]);
+ config.agent.channel_permissions =
+ std::collections::HashMap::from([("profile".into(), "readonly".into())]);
let autonomy = &mut config.autonomy;
autonomy.enabled = true;
diff --git a/crates/openhuman-core/src/profiles/layout_tests.rs b/crates/openhuman-core/src/profiles/layout_tests.rs
index 6b2e7552d2..029b9456a6 100644
--- a/crates/openhuman-core/src/profiles/layout_tests.rs
+++ b/crates/openhuman-core/src/profiles/layout_tests.rs
@@ -116,11 +116,9 @@ fn profiles_never_use_the_unrestricted_empty_channel_permission_map() {
let layout = profile_layout(Path::new("/srv/oh"), &id());
let config = profile_config(&layout, &id());
assert!(!config.agent.channel_permissions.is_empty());
- assert!(
- config
- .agent
- .channel_permissions
- .values()
- .all(|v| v == "readonly")
- );
+ assert!(config
+ .agent
+ .channel_permissions
+ .values()
+ .all(|v| v == "readonly"));
}
diff --git a/crates/openhuman-core/src/profiles/tools.rs b/crates/openhuman-core/src/profiles/tools.rs
index 2c87c9d3fe..952d7ccd9a 100644
--- a/crates/openhuman-core/src/profiles/tools.rs
+++ b/crates/openhuman-core/src/profiles/tools.rs
@@ -181,9 +181,13 @@ pub fn gate_verdict_with(tool: &str, groups: &[SaasToolGroup]) -> Result<(), Str
/// [`gate_verdict_with`] for the running deployment.
pub fn gate_verdict(tool: &str) -> Result<(), String> {
- let verdict = if super::capabilities::ProfileCapabilities::current().is_some_and(|caps| caps.authorizes_approval(tool)) {
+ let verdict = if super::capabilities::ProfileCapabilities::current()
+ .is_some_and(|caps| caps.authorizes_approval(tool))
+ {
super::host::ensure_hosted()
- } else { gate_verdict_with(tool, &allowlisted()) };
+ } else {
+ gate_verdict_with(tool, &allowlisted())
+ };
log::debug!(
"[profiles][tools] approval gate tool={tool} allowed={}",
verdict.is_ok()
diff --git a/crates/openhuman-core/src/web_chat/session.rs b/crates/openhuman-core/src/web_chat/session.rs
index a135837dc0..8f5de8817c 100644
--- a/crates/openhuman-core/src/web_chat/session.rs
+++ b/crates/openhuman-core/src/web_chat/session.rs
@@ -150,7 +150,11 @@ pub(super) fn build_session_agent(
thread_id
);
- let agent_result = OpenHumanSessionHost::from_config_for_agent_session(&effective, target_agent_id, Some(thread_id));
+ let agent_result = OpenHumanSessionHost::from_config_for_agent_session(
+ &effective,
+ target_agent_id,
+ Some(thread_id),
+ );
agent_result
.map(|mut agent| {
diff --git a/crates/openhuman-embed/src/profiles.rs b/crates/openhuman-embed/src/profiles.rs
index 82aa5a2a12..b55b66d2c8 100644
--- a/crates/openhuman-embed/src/profiles.rs
+++ b/crates/openhuman-embed/src/profiles.rs
@@ -178,7 +178,14 @@ impl ProfileRuntimeBuilder {
None
};
- let core = match openhuman_core::core::runtime::saas::build_with_profile_capabilities(config, None, None, Some(capabilities)).await {
+ let core = match openhuman_core::core::runtime::saas::build_with_profile_capabilities(
+ config,
+ None,
+ None,
+ Some(capabilities),
+ )
+ .await
+ {
Ok(core) => core,
Err(e) => {
// Boot failed; restore the previous session store if we installed one.
diff --git a/crates/openhuman-embed/src/profiles/host.rs b/crates/openhuman-embed/src/profiles/host.rs
index af86894455..84ba36e289 100644
--- a/crates/openhuman-embed/src/profiles/host.rs
+++ b/crates/openhuman-embed/src/profiles/host.rs
@@ -1,10 +1,12 @@
//! Operator adapters installed once, before the SaaS profile host boots.
+use super::{ProfileError, ProfileRuntimeBuilder, SaasConfig};
+use crate::seams::{ToolHook, ToolHookContext};
+use crate::{
+ HostTools, HostTurnTools, PermissionFuture, PermissionLevel, ToolScopeSpec, TurnContext,
+};
use std::collections::HashMap;
use std::sync::Arc;
-use crate::{HostTools, HostTurnTools, TurnContext, PermissionLevel, ToolScopeSpec, PermissionFuture};
-use crate::seams::{ToolHook, ToolHookContext};
-use super::{ProfileError, ProfileRuntimeBuilder, SaasConfig};
#[derive(Default)]
pub(super) struct ProfileHostOptions {
@@ -16,16 +18,39 @@ pub(super) struct ProfileHostOptions {
}
impl ProfileHostOptions {
- pub(super) fn finish(self, config: &SaasConfig) -> Result<Arc<openhuman_core::profiles::capabilities::ProfileCapabilities>, ProfileError> {
+ pub(super) fn finish(
+ self,
+ config: &SaasConfig,
+ ) -> Result<Arc<openhuman_core::profiles::capabilities::ProfileCapabilities>, ProfileError>
+ {
let names = match self.scope {
- Some(ToolScopeSpec::Wildcard) => return Err(ProfileError::Boot("profile tools require a named or host-only scope".into())),
+ Some(ToolScopeSpec::Wildcard) => {
+ return Err(ProfileError::Boot(
+ "profile tools require a named or host-only scope".into(),
+ ))
+ }
Some(ToolScopeSpec::Named(names)) => Some(names.into_iter().collect()),
_ => None,
};
- if self.channels.values().any(|level| *level == PermissionLevel::Dangerous) {
- return Err(ProfileError::Boot("profile channel permissions cannot be dangerous".into()));
+ if self
+ .channels
+ .values()
+ .any(|level| *level == PermissionLevel::Dangerous)
+ {
+ return Err(ProfileError::Boot(
+ "profile channel permissions cannot be dangerous".into(),
+ ));
}
- Ok(Arc::new(openhuman_core::profiles::capabilities::ProfileCapabilities::new(self.tools, names, self.permission, self.channels, openhuman_core::profiles::tools::parse_allowlist(&config.tool_allowlist), self.memory)))
+ Ok(Arc::new(
+ openhuman_core::profiles::capabilities::ProfileCapabilities::new(
+ self.tools,
+ names,
+ self.permission,
+ self.channels,
+ openhuman_core::profiles::tools::parse_allowlist(&config.tool_allowlist),
+ self.memory,
+ ),
+ ))
}
}
@@ -33,37 +58,58 @@ impl ProfileRuntimeBuilder {
/// Supply a per-turn host tool factory. Hard SaaS denies remain stronger.
/// The factory receives the exact chat or relay thread in `session_id`.
#[must_use]
- pub fn tools(mut self, factory: impl for<'a> Fn(TurnContext<'a>) -> HostTurnTools + Send + Sync + 'static) -> Self {
- self.host_options.tools = Some(Arc::new(factory)); self
+ pub fn tools(
+ mut self,
+ factory: impl for<'a> Fn(TurnContext<'a>) -> HostTurnTools + Send + Sync + 'static,
+ ) -> Self {
+ self.host_options.tools = Some(Arc::new(factory));
+ self
}
/// Select exactly these native and host names, or only the host belt.
/// Wildcard scopes are refused at build time.
#[must_use]
pub fn tool_scope(mut self, scope: ToolScopeSpec) -> Self {
- self.host_options.scope = Some(scope); self
+ self.host_options.scope = Some(scope);
+ self
}
/// Decide each admitted call under its owning, lease-fenced profile.
/// Without this callback all tool executions are denied.
#[must_use]
pub fn can_use_tool<F>(mut self, callback: F) -> Self
- where F: for<'a> Fn(&'a ToolHookContext) -> PermissionFuture<'a> + Send + Sync + 'static {
- self.host_options.permission = Some(Arc::new(crate::permission::PermissionHook::new(callback))); self
+ where
+ F: for<'a> Fn(&'a ToolHookContext) -> PermissionFuture<'a> + Send + Sync + 'static,
+ {
+ self.host_options.permission =
+ Some(Arc::new(crate::permission::PermissionHook::new(callback)));
+ self
}
/// Grant explicit ceilings to hosted profile channels. Unknown channels
/// remain read-only. Write or Execute is needed for native memory and cron
/// mutation; Dangerous is refused. This never widens ordinary channel turns.
#[must_use]
- pub fn channel_permissions(mut self, channels: impl IntoIterator<Item = (impl Into<String>, PermissionLevel)>) -> Self {
- self.host_options.channels = channels.into_iter().map(|(name, level)| (name.into(), level)).collect(); self
+ pub fn channel_permissions(
+ mut self,
+ channels: impl IntoIterator<Item = (impl Into<String>, PermissionLevel)>,
+ ) -> Self {
+ self.host_options.channels = channels
+ .into_iter()
+ .map(|(name, level)| (name.into(), level))
+ .collect();
+ self
}
/// Bind an existing engine through each profile's forced memory namespace.
/// The binding is profile-local; the global SaaS engine refusal stays intact.
#[must_use]
pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self {
- self.host_options.memory = Some(engine); self
+ self.host_options.memory = Some(engine);
+ self
}
}
+
+#[cfg(test)]
+#[path = "host_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-embed/src/profiles/host_tests.rs b/crates/openhuman-embed/src/profiles/host_tests.rs
new file mode 100644
index 0000000000..164396d410
--- /dev/null
+++ b/crates/openhuman-embed/src/profiles/host_tests.rs
@@ -0,0 +1,52 @@
+//! Immutable profile host configuration rejects broader capability requests.
+
+use super::*;
+
+#[test]
+fn wildcard_profile_scope_is_refused_before_boot() {
+ let config = SaasConfig::new("/srv/openhuman");
+ let options = ProfileHostOptions {
+ scope: Some(ToolScopeSpec::Wildcard),
+ ..Default::default()
+ };
+ assert!(
+ matches!(options.finish(&config), Err(ProfileError::Boot(message)) if message.contains("named or host-only"))
+ );
+}
+
+#[test]
+fn destructive_channel_ceiling_is_refused_before_boot() {
+ let config = SaasConfig::new("/srv/openhuman");
+ let options = ProfileHostOptions {
+ channels: HashMap::from([("telegram".into(), PermissionLevel::Dangerous)]),
+ ..Default::default()
+ };
+ assert!(
+ matches!(options.finish(&config), Err(ProfileError::Boot(message)) if message.contains("dangerous"))
+ );
+}
+
+#[test]
+fn named_selection_never_overrides_hard_denies_or_default_readonly() {
+ let config = SaasConfig::new("/srv/openhuman");
+ let options = ProfileHostOptions {
+ scope: Some(ToolScopeSpec::Named(vec![
+ "memory".into(),
+ "shell".into(),
+ "delegate".into(),
+ "curl".into(),
+ "run_workflow".into(),
+ ])),
+ ..Default::default()
+ };
+ let capabilities = options.finish(&config).unwrap();
+ assert!(capabilities.admits("memory"));
+ for name in ["shell", "delegate", "curl", "run_workflow", "hidden"] {
+ assert!(!capabilities.admits(name), "{name}");
+ }
+ assert_eq!(
+ capabilities.channel_permission("telegram"),
+ PermissionLevel::ReadOnly
+ );
+ assert!(!capabilities.authorizes_approval("memory"));
+}
diff --git a/crates/openhuman-embed/tests/profile_host_capabilities.rs b/crates/openhuman-embed/tests/profile_host_capabilities.rs
index 54dad3f742..09f63f19ca 100644
--- a/crates/openhuman-embed/tests/profile_host_capabilities.rs
+++ b/crates/openhuman-embed/tests/profile_host_capabilities.rs
@@ -7,8 +7,8 @@ use std::sync::{Arc, Mutex};
use std::time::Duration;
use common::{
- PointedTransport, chat_completion, chat_requests, runtime_without_master_key,
- tool_call_completion, tool_names, tool_results,
+ chat_completion, chat_requests, runtime_without_master_key, tool_call_completion, tool_names,
+ tool_results, PointedTransport,
};
use openhuman_embed::memory::api::conformance::ReferenceEngine;
use openhuman_embed::memory::api::{LearningKind, MemoryEngine, MemoryMeta, StoreItem};
@@ -18,7 +18,7 @@ use openhuman_embed::{
HostTurnTools, PermissionLevel, ProfileRuntime, RelayMessage, SaasConfig, Tool, ToolResult,
ToolScopeSpec,
};
-use serde_json::{Value, json};
+use serde_json::{json, Value};
use wiremock::{Mock, Request, Respond, ResponseTemplate};
struct TenantTool {
@@ -96,9 +96,19 @@ async fn scenario() {
let root = tempfile::tempdir().unwrap();
let calls = Arc::new(Mutex::new(Vec::new()));
let factory_calls = calls.clone();
+ let sessions = Arc::new(Mutex::new(Vec::new()));
+ let factory_sessions = sessions.clone();
let engine = Arc::new(ReferenceEngine::new());
let runtime = ProfileRuntime::builder(SaasConfig::new(root.path()))
- .tools(move |_| {
+ .tools(move |turn| {
+ let profile = openhuman_core::core::runtime::current_tenant()
+ .unwrap()
+ .profile
+ .unwrap();
+ factory_sessions
+ .lock()
+ .unwrap()
+ .push((profile, turn.session_id().map(str::to_owned)));
HostTurnTools::advertised(
[
"tenant_probe",
@@ -204,7 +214,20 @@ async fn scenario() {
"tenant_probe:bob"
]
);
- for request in chat_requests(&inference).await {
+ assert_eq!(
+ *sessions.lock().unwrap(),
+ [
+ ("alice".into(), Some("t1".into())),
+ ("bob".into(), Some("t1".into())),
+ ("alice".into(), Some("channel:telegram/sender/chat".into())),
+ ("bob".into(), Some("channel:telegram/sender/chat".into())),
+ ]
+ );
+ let requests = chat_requests(&inference).await;
+ assert!(requests
+ .iter()
+ .any(|request| !tool_names(request).is_empty()));
+ for request in requests {
let mut names = tool_names(&request);
names.sort();
if !names.is_empty() {
@@ -244,7 +267,10 @@ async fn scenario() {
text.contains(&format!("{}-secret", handle.id())),
"{response}"
);
- assert!(text.contains(&format!("{}-native-learning", handle.id())), "native memory mutation was persisted: {response}");
+ assert!(
+ text.contains(&format!("{}-native-learning", handle.id())),
+ "native memory mutation was persisted: {response}"
+ );
let other = if handle.id().as_str() == "alice" {
"bob"
} else {