Skip to content

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

feat(profiles): route hosted turns through profile capabilities

Steven Enamakel1664273fba2a
diff --git a/crates/openhuman-core/src/agent/host_agents.rs b/crates/openhuman-core/src/agent/host_agents.rs
index f3c297ce08..403e54249e 100644
--- a/crates/openhuman-core/src/agent/host_agents.rs
+++ b/crates/openhuman-core/src/agent/host_agents.rs
@@ -70,7 +70,11 @@ impl HostAgent {
"[host_agents] building session for host agent"
);
self.hooks.clone().sync_scope(|| {
- CoreContext::sync_scope(Arc::clone(&self.context), || match &self.host_tools {
+ 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);
+ }
+ match &self.host_tools {
Some(host) => OpenHumanSessionHost::from_config_with_host_tools(
config,
&self.definition,
@@ -78,6 +82,7 @@ impl HostAgent {
session_id,
),
None => OpenHumanSessionHost::from_config_with_definition(config, &self.definition),
+ }
})
})
}
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 5ea2f564d4..549f137492 100644
--- a/crates/openhuman-core/src/agent/session_host/builder/factory.rs
+++ b/crates/openhuman-core/src/agent/session_host/builder/factory.rs
@@ -78,6 +78,14 @@ impl OpenHumanSessionHost {
/// The welcome agent uses this entry point when routed from the
/// Tauri web channel (see `channels::provider::web::build_session_agent`).
pub fn from_config_for_agent(config: &Config, agent_id: &str) -> Result<Self> {
+ Self::from_config_for_agent_session(config, agent_id, None)
+ }
+
+ /// Build a config-routed agent with its caller's exact conversation key.
+ ///
+ /// # 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> {
// 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`
@@ -111,7 +119,12 @@ impl OpenHumanSessionHost {
.unwrap_or(config.default_temperature)
);
- Self::build_session_agent_inner(config, agent_id, target_def.as_ref(), false, None, None)
+ if let Some(capabilities) = crate::profiles::capabilities::ProfileCapabilities::current() {
+ 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)
}
/// Build a session agent from a definition the caller already holds,
diff --git a/crates/openhuman-core/src/channels/providers/relay/mod.rs b/crates/openhuman-core/src/channels/providers/relay/mod.rs
index 1a2ae246f7..82cd3e1765 100644
--- a/crates/openhuman-core/src/channels/providers/relay/mod.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/mod.rs
@@ -32,3 +32,15 @@ pub use params::{
MAX_ID_LEN, MAX_SENDER_NAME_CHARS, MAX_TEXT_BYTES, RESERVED_CHANNELS,
};
pub use schemas::{all_relay_controller_schemas, all_relay_registered_controllers};
+
+// The durable conversation key belongs to this inbound relay call, not a
+// process-global last sender. The dispatch future carries it to session build.
+tokio::task_local! { static RELAY_THREAD: String; }
+
+pub(crate) fn current_thread_id() -> Option<String> {
+ RELAY_THREAD.try_with(Clone::clone).ok()
+}
+
+pub(crate) async fn with_thread<F: std::future::Future>(thread: String, future: F) -> F::Output {
+ RELAY_THREAD.scope(thread, future).await
+}
diff --git a/crates/openhuman-core/src/channels/providers/relay/ops.rs b/crates/openhuman-core/src/channels/providers/relay/ops.rs
index fe267d1673..43d5a83279 100644
--- a/crates/openhuman-core/src/channels/providers/relay/ops.rs
+++ b/crates/openhuman-core/src/channels/providers/relay/ops.rs
@@ -161,7 +161,7 @@ pub(crate) async fn run_relay_turn(
request_id = %request_id,
"[channels::relay] dispatching relayed turn"
);
- process_channel_message(ctx, message).await;
+ super::with_thread(thread_id.clone(), process_channel_message(ctx, message)).await;
let replies = channel.sent();
record(&workspace_dir, &params, &thread_id, &replies).await;
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 edbb521e34..58fbbf027b 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
@@ -53,6 +53,14 @@ 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(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::Missing("profile agent".into());
+ }
let Some(agent_id) = ctx
.config
.as_deref()
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 adcbde1835..cf01b78492 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,7 +43,10 @@ pub(crate) async fn run_host_agent_turn(
progress,
} = turn;
let mut config = host.config.clone();
- if let Some(ceiling) = posture::tool_ceiling(&origin) {
+ 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);
host.host_tools = host
.host_tools
@@ -59,7 +62,7 @@ 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(&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 3e04b5207c..40d8e96d05 100644
--- a/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
+++ b/crates/openhuman-core/src/channels/runtime/startup/turn_parts.rs
@@ -141,7 +141,10 @@ pub(crate) fn build_channel_turn_parts(
config.workspace_dir.clone(),
)?;
let workspace = config.workspace_dir.clone();
- let tools_registry = Arc::new(tools::ops::all_tools_with_runtime(
+ 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,
@@ -154,17 +157,17 @@ pub(crate) fn build_channel_turn_parts(
&config.agents,
config,
None,
- ));
+ ) });
- let skills = 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)> = default_tool_descs(config)
+ 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();
+ .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 257f8e0f9f..1655d475c6 100644
--- a/crates/openhuman-core/src/memory/engine.rs
+++ b/crates/openhuman-core/src/memory/engine.rs
@@ -205,6 +205,14 @@ fn host_engine() -> Option<BoundEngine> {
/// Resolves the configured engine.
#[must_use]
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)) });
+ }
+ }
#[cfg(test)]
{
let installed = TEST_ENGINES
diff --git a/crates/openhuman-core/src/profiles/capabilities.rs b/crates/openhuman-core/src/profiles/capabilities.rs
index d397776f8f..8dbc55f9cb 100644
--- a/crates/openhuman-core/src/profiles/capabilities.rs
+++ b/crates/openhuman-core/src/profiles/capabilities.rs
@@ -21,12 +21,12 @@ pub struct ProfileCapabilities {
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>>,
+ pub memory_engine: Option<Arc<dyn tinymemory_api::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 {
+ 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 }
}
@@ -118,11 +118,11 @@ impl ToolHook for ProfilePermission {
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() };
+ 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 { reason: "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 0015eca628..8ea283e884 100644
--- a/crates/openhuman-core/src/profiles/host.rs
+++ b/crates/openhuman-core/src/profiles/host.rs
@@ -83,6 +83,7 @@ pub(super) struct Slot {
/// The open profiles of one SaaS process.
pub struct ProfileHost {
pub(super) saas: SaasConfig,
+ capabilities: Option<Arc<super::capabilities::ProfileCapabilities>>,
pub(super) operator: Arc<CoreContext>,
pub(super) node: String,
pub(super) open: Mutex<HashMap<ProfileId, Slot>>,
@@ -153,6 +154,7 @@ impl ProfileHost {
None => ProfileRegistry::files(&saas.root),
};
Ok(Self {
+ capabilities: None,
saas,
operator,
node,
@@ -165,6 +167,12 @@ impl ProfileHost {
})
}
+ /// Install immutable operator adapters before this host is shared.
+ pub fn with_capabilities(mut self, capabilities: Option<Arc<super::capabilities::ProfileCapabilities>>) -> Self {
+ self.capabilities = capabilities;
+ self
+ }
+
/// This host registering its fences in `fences` instead of the process
/// registry (tests, which must not share one).
pub fn with_fences(mut self, fences: Arc<FenceRegistry>) -> Self {
@@ -288,13 +296,8 @@ impl ProfileHost {
profile_lease::release_all(self, vec![(id.clone(), grant)]).await;
return Err(OpenError::Storage(error));
}
- let config = layout::profile_config(&layout, id);
- let context = self.operator.derive_with(
- ContextOverlay::new(config.clone(), user_domains(), ToolGroups::none())
- .without_user_skill_roots()
- .profile(id.as_str())
- .agent_policy(profile_policy(&config)),
- );
+ let mut config = layout::profile_config(&layout, id);
+ if let Some(capabilities) = &self.capabilities { capabilities.configure(&mut config); }
let fence = super::fence::for_grant(
Arc::clone(&self.leases),
&self.node,
@@ -302,6 +305,16 @@ impl ProfileHost {
&grant,
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));
+ 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))));
+ overlay = overlay.host_overrides(Arc::new(overrides));
+ }
+ let context = self.operator.derive_with(overlay);
// Registered before recovery so its writes are already guarded.
// Once fenced, it refuses writes for as long as work on this context
// could still issue them.
diff --git a/crates/openhuman-core/src/profiles/layout.rs b/crates/openhuman-core/src/profiles/layout.rs
index ca8961b2dd..82b0778993 100644
--- a/crates/openhuman-core/src/profiles/layout.rs
+++ b/crates/openhuman-core/src/profiles/layout.rs
@@ -70,6 +70,7 @@ 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())]);
let autonomy = &mut config.autonomy;
autonomy.enabled = true;
diff --git a/crates/openhuman-core/src/profiles/tools.rs b/crates/openhuman-core/src/profiles/tools.rs
index e27a5e3ce8..2c87c9d3fe 100644
--- a/crates/openhuman-core/src/profiles/tools.rs
+++ b/crates/openhuman-core/src/profiles/tools.rs
@@ -181,7 +181,9 @@ 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 = gate_verdict_with(tool, &allowlisted());
+ 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()) };
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 7c594907e2..a135837dc0 100644
--- a/crates/openhuman-core/src/web_chat/session.rs
+++ b/crates/openhuman-core/src/web_chat/session.rs
@@ -150,7 +150,7 @@ pub(super) fn build_session_agent(
thread_id
);
- let agent_result = OpenHumanSessionHost::from_config_for_agent(&effective, target_agent_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/host.rs b/crates/openhuman-embed/src/profiles/host.rs
index a244f97d16..af86894455 100644
--- a/crates/openhuman-embed/src/profiles/host.rs
+++ b/crates/openhuman-embed/src/profiles/host.rs
@@ -12,7 +12,7 @@ pub(super) struct ProfileHostOptions {
scope: Option<ToolScopeSpec>,
permission: Option<Arc<dyn ToolHook>>,
channels: HashMap<String, PermissionLevel>,
- memory: Option<Arc<dyn tinymemory::MemoryEngine>>,
+ memory: Option<Arc<dyn tinymemory_api::MemoryEngine>>,
}
impl ProfileHostOptions {
@@ -63,7 +63,7 @@ impl ProfileRuntimeBuilder {
/// 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 {
+ pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self {
self.host_options.memory = Some(engine); self
}
}