Skip to content

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

feat(profiles): thread operator capabilities into hosted profile runtime

Steven Enamakel1af32ccf0bbf
diff --git a/crates/openhuman-core/src/agent/host_overrides.rs b/crates/openhuman-core/src/agent/host_overrides.rs
index 30c8d732b2..ac6477824f 100644
--- a/crates/openhuman-core/src/agent/host_overrides.rs
+++ b/crates/openhuman-core/src/agent/host_overrides.rs
@@ -15,6 +15,8 @@ pub use tinyagents_harness::cancel::CancellationToken;
/// Runtime or agent host adapters, shared by every context derived from it.
#[derive(Default)]
pub struct HostOverrides {
+ /// Immutable operator capabilities for an authenticated hosted profile.
+ pub profile_capabilities: Option<Arc<crate::profiles::capabilities::ProfileCapabilities>>,
/// Parent runtime adapters; local hook registration never edits this parent.
pub parent: Option<Arc<HostOverrides>>,
/// Approval registration barrier owned by this agent instance.
@@ -40,6 +42,11 @@ 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()))
+ }
+
/// Resolve the instance barrier inherited by derived turn contexts.
pub fn approval_scope(&self) -> Option<Arc<crate::security::approval::ApprovalScope>> {
self.approval_scope
diff --git a/crates/openhuman-core/src/core/runtime/saas.rs b/crates/openhuman-core/src/core/runtime/saas.rs
index d2b098787a..309a809f43 100644
--- a/crates/openhuman-core/src/core/runtime/saas.rs
+++ b/crates/openhuman-core/src/core/runtime/saas.rs
@@ -301,9 +301,22 @@ impl DomainSet {
/// Boot a SaaS core: check the deployment, lock the process to SaaS, and
/// build the operator plane.
pub async fn build(
+ config: SaasConfig,
+ host: Option<String>,
+ port: Option<u16>,
+) -> anyhow::Result<CoreRuntime> {
+ build_with_profile_capabilities(config, host, port, None).await
+}
+
+/// Boot with immutable operator adapters for authenticated profile turns.
+///
+/// # Errors
+/// As [`build`].
+pub async fn build_with_profile_capabilities(
mut config: SaasConfig,
host: Option<String>,
port: Option<u16>,
+ capabilities: Option<Arc<crate::profiles::capabilities::ProfileCapabilities>>,
) -> anyhow::Result<CoreRuntime> {
if CoreContext::current().is_some() {
anyhow::bail!(
@@ -409,7 +422,8 @@ pub async fn build(
}
let host = Arc::new(
crate::profiles::ProfileHost::with_backend(config, runtime.context().clone(), backend)
- .map_err(|e| anyhow::anyhow!("[saas] {e}"))?,
+ .map_err(|e| anyhow::anyhow!("[saas] {e}"))?
+ .with_capabilities(capabilities),
);
crate::profiles::host::install(Arc::clone(&host));
crate::profiles::lease::heartbeat(Arc::clone(&host), runtime.context().clone());
diff --git a/crates/openhuman-core/src/profiles/capabilities.rs b/crates/openhuman-core/src/profiles/capabilities.rs
new file mode 100644
index 0000000000..d397776f8f
--- /dev/null
+++ b/crates/openhuman-core/src/profiles/capabilities.rs
@@ -0,0 +1,128 @@
+//! Immutable operator-selected tool and memory adapters for hosted profiles.
+//!
+//! Registration is narrowed before the session receives its registry. Every
+//! 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::config::Config;
+use crate::tools::toolpacks::{GroupMode, ToolGroups};
+use tinytools::PermissionLevel;
+
+/// Capabilities fixed when the profile runtime boots.
+pub struct ProfileCapabilities {
+ host: Option<HostTools>,
+ names: Option<HashSet<String>>,
+ permission: Option<Arc<dyn ToolHook>>,
+ channels: HashMap<String, PermissionLevel>,
+ groups: Vec<super::tools::SaasToolGroup>,
+ /// The shared engine, resolved only under the forced profile memory root.
+ pub memory_engine: Option<Arc<dyn tinymemory::MemoryEngine>>,
+}
+
+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::MemoryEngine>>) -> Self {
+ Self { host, names, permission, channels, groups, memory_engine }
+ }
+
+ /// Capabilities of the ambient authenticated profile, never the operator.
+ pub fn current() -> Option<Arc<Self>> {
+ let ctx = CoreContext::current()?;
+ ctx.profile()?;
+ ctx.host_overrides()?.profile_capabilities()
+ }
+
+ /// Permission ceiling explicitly granted to this hosted channel.
+ pub fn channel_permission(&self, channel: &str) -> PermissionLevel {
+ self.channels.get(channel).copied().unwrap_or_default()
+ }
+
+ /// 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())));
+ }
+
+ /// 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")
+ && !name.starts_with("delegate_")
+ && !name.starts_with("mcp_")
+ && !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)
+ }
+
+ /// 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();
+ supplied.tools.retain(|tool| self.admits(tool.name()));
+ if let Some(names) = &self.names {
+ let mut groups = ToolGroups::none();
+ for name in names.iter().filter(|name| self.admits(name)) {
+ if let Some(pack) = crate::tools::toolpacks::pack_for_tool(name) {
+ groups = groups.with(pack.id, GroupMode::Advertised);
+ }
+ }
+ 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())));
+ }
+ }
+ // 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.permanent.clear();
+ supplied.withheld.clear();
+ supplied
+ }
+
+ /// A factory retaining these immutable adapters and this forced config.
+ pub fn factory(self: &Arc<Self>, config: &Config) -> HostTools {
+ let capabilities = Arc::clone(self);
+ let config = config.clone();
+ Arc::new(move |turn| capabilities.turn_tools(&config, turn))
+ }
+
+ /// 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 })
+ }
+}
+
+struct ProfilePermission {
+ capabilities: Arc<ProfileCapabilities>,
+ profile: String,
+ fence: Arc<crate::storage::fence::LeaseFence>,
+}
+
+#[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(()) }
+ 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 { reason: "tool is outside the hosted profile capability boundary".into() };
+ }
+ match &self.capabilities.permission {
+ Some(permission) => permission.before_tool_decision(context).await,
+ None => ToolHookDecision::Deny { reason: "this profile has no host tool permission callback".into() },
+ }
+ }
+}
diff --git a/crates/openhuman-core/src/profiles/mod.rs b/crates/openhuman-core/src/profiles/mod.rs
index b7ad05bb75..a9dc260937 100644
--- a/crates/openhuman-core/src/profiles/mod.rs
+++ b/crates/openhuman-core/src/profiles/mod.rs
@@ -24,6 +24,7 @@
//! [`CoreContext`]: crate::core::runtime::CoreContext
pub mod background;
+pub mod capabilities;
pub mod credentials;
pub mod fence;
pub mod gateway;
diff --git a/crates/openhuman-embed/src/profiles.rs b/crates/openhuman-embed/src/profiles.rs
index 0332e1704b..82aa5a2a12 100644
--- a/crates/openhuman-embed/src/profiles.rs
+++ b/crates/openhuman-embed/src/profiles.rs
@@ -61,6 +61,7 @@ use openhuman_core::profiles::ProfileHost;
use crate::error::CoreError;
mod handle;
+mod host;
pub use handle::{ChatReply, ProfileEvents, ProfileHandle, RelayAccepted};
pub use openhuman_core::channels::providers::relay::RelayInboundParams as RelayMessage;
@@ -118,6 +119,7 @@ pub enum ProfileError {
pub struct ProfileRuntimeBuilder {
config: SaasConfig,
session_store: Option<Arc<dyn SessionStoreProvider>>,
+ host_options: host::ProfileHostOptions,
}
impl ProfileRuntimeBuilder {
@@ -126,6 +128,7 @@ impl ProfileRuntimeBuilder {
Self {
config,
session_store: None,
+ host_options: Default::default(),
}
}
@@ -153,7 +156,9 @@ impl ProfileRuntimeBuilder {
let Self {
config,
session_store,
+ host_options,
} = self;
+ let capabilities = host_options.finish(&config)?;
ensure_service_token(&config.service_token_path())?;
if let Some(url) = config.resolved_storage_url() {
if openhuman_core::storage::installed().is_none() {
@@ -173,7 +178,7 @@ impl ProfileRuntimeBuilder {
None
};
- let core = match openhuman_core::core::runtime::saas::build(config, None, None).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
new file mode 100644
index 0000000000..a244f97d16
--- /dev/null
+++ b/crates/openhuman-embed/src/profiles/host.rs
@@ -0,0 +1,69 @@
+//! Operator adapters installed once, before the SaaS profile host boots.
+
+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 {
+ tools: Option<HostTools>,
+ scope: Option<ToolScopeSpec>,
+ permission: Option<Arc<dyn ToolHook>>,
+ channels: HashMap<String, PermissionLevel>,
+ memory: Option<Arc<dyn tinymemory::MemoryEngine>>,
+}
+
+impl ProfileHostOptions {
+ 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::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()));
+ }
+ 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)))
+ }
+}
+
+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
+ }
+
+ /// 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
+ }
+
+ /// 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
+ }
+
+ /// 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
+ }
+
+ /// 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::MemoryEngine>) -> Self {
+ self.host_options.memory = Some(engine); self
+ }
+}