The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(core): give derived agent contexts their own policy, catalogue and state (#7032)
oxoxDev97e6ab214f6d
diff --git a/crates/openhuman-core/src/core/runtime/agent_scope.rs b/crates/openhuman-core/src/core/runtime/agent_scope.rsnew file mode 100644index 0000000000..f9b8b1eb90--- /dev/null+++ b/crates/openhuman-core/src/core/runtime/agent_scope.rs@@ -0,0 +1,157 @@+//! Per-agent state owned by a [`CoreContext`].+//!+//! An embedded agent runs every turn under its own derived context+//! ([`CoreContext::derive_with`]). Core state that must not be shared between+//! agents hangs off that context instead of a process static:+//!+//! - [`AgentScopedState`]: a lazily populated, type-keyed slot map. Each+//! derived agent context owns one; the booted default context owns its own,+//! so the app and CLI keep a single instance as before.+//! - [`AgentContextRegistry`]: the live agent contexts by agent id, so work+//! that starts outside a turn (cron) can run under the agent that owns it.+//! - [`agent_scope_dir`]: where an agent's workspace-scoped stores live.++use std::any::{Any, TypeId};+use std::collections::HashMap;+use std::path::PathBuf;+use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock, Weak};++use super::CoreContext;++/// Type-keyed state slots owned by one context.+///+/// A slot is created on first use with `T::default()` and lives as long as+/// the context that owns it. Two contexts never share a slot.+#[derive(Default)]+pub struct AgentScopedState {+ slots: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,+}++impl AgentScopedState {+ /// The slot of type `T`, created on first use.+ pub fn slot<T: Default + Send + Sync + 'static>(&self) -> Arc<T> {+ let mut slots = self.slots.lock().unwrap_or_else(PoisonError::into_inner);+ let entry = slots+ .entry(TypeId::of::<T>())+ .or_insert_with(|| Arc::new(T::default()) as Arc<dyn Any + Send + Sync>);+ Arc::clone(entry)+ .downcast::<T>()+ .unwrap_or_else(|_| unreachable!("a slot is keyed by its own TypeId"))+ }++ /// Number of slots created so far.+ pub fn len(&self) -> usize {+ self.slots+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .len()+ }++ /// Whether no slot has been created yet.+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// Drops every slot.+ pub fn clear(&self) {+ self.slots+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .clear();+ }+}++impl std::fmt::Debug for AgentScopedState {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("AgentScopedState")+ .field("slots", &self.len())+ .finish()+ }+}++/// Slots used when no context exists at all.+static UNSCOPED: LazyLock<AgentScopedState> = LazyLock::new(AgentScopedState::default);++/// The ambient context's slot of type `T`, or the unscoped one when no+/// context exists.+pub fn current_slot<T: Default + Send + Sync + 'static>() -> Arc<T> {+ match CoreContext::current() {+ Some(ctx) => ctx.agent_state().slot::<T>(),+ None => UNSCOPED.slot::<T>(),+ }+}++static AGENT_CONTEXTS: LazyLock<RwLock<HashMap<String, Weak<CoreContext>>>> =+ LazyLock::new(|| RwLock::new(HashMap::new()));++/// The process's live agent contexts, by agent id.+///+/// Holds weak references: registering a context does not keep it alive, and a+/// dropped agent's entry resolves to `None` even before it is deregistered.+pub struct AgentContextRegistry;++impl AgentContextRegistry {+ /// Records `ctx` as the context of `agent_id`, replacing any dead entry.+ pub fn register(agent_id: &str, ctx: &Arc<CoreContext>) {+ let mut map = AGENT_CONTEXTS+ .write()+ .unwrap_or_else(PoisonError::into_inner);+ map.retain(|_, weak| weak.strong_count() > 0);+ map.insert(agent_id.to_string(), Arc::downgrade(ctx));+ log::debug!(+ "[core-context] agent context registered agent={agent_id} live={}",+ map.len()+ );+ }++ /// Removes `agent_id`'s entry when it still points at `ctx`.+ pub fn deregister(agent_id: &str, ctx: &Arc<CoreContext>) -> bool {+ let mut map = AGENT_CONTEXTS+ .write()+ .unwrap_or_else(PoisonError::into_inner);+ let owned = map+ .get(agent_id)+ .is_some_and(|weak| std::ptr::eq(weak.as_ptr(), Arc::as_ptr(ctx)));+ if owned {+ map.remove(agent_id);+ log::debug!("[core-context] agent context deregistered agent={agent_id}");+ }+ owned+ }++ /// The live context of `agent_id`, if that agent is still alive.+ pub fn get(agent_id: &str) -> Option<Arc<CoreContext>> {+ AGENT_CONTEXTS+ .read()+ .unwrap_or_else(PoisonError::into_inner)+ .get(agent_id)+ .and_then(Weak::upgrade)+ }++ /// Every live agent context, sorted by agent id.+ pub fn live() -> Vec<(String, Arc<CoreContext>)> {+ let mut live: Vec<(String, Arc<CoreContext>)> = AGENT_CONTEXTS+ .read()+ .unwrap_or_else(PoisonError::into_inner)+ .iter()+ .filter_map(|(id, weak)| weak.upgrade().map(|ctx| (id.clone(), ctx)))+ .collect();+ live.sort_by(|a, b| a.0.cmp(&b.0));+ live+ }+}++/// The directory an agent's workspace-scoped stores live under:+/// `<workspace>/agents/<id>` under a context derived for an agent, else the+/// workspace itself.+pub fn agent_scope_dir(config: &crate::config::Config) -> PathBuf {+ match CoreContext::current().and_then(|ctx| ctx.session_agent().map(str::to_owned)) {+ Some(agent_id) => config.workspace_dir.join("agents").join(agent_id),+ None => config.workspace_dir.clone(),+ }+}++/// The agent id of the ambient context, when it was derived for one.+pub fn current_agent_id() -> Option<String> {+ CoreContext::current().and_then(|ctx| ctx.session_agent().map(str::to_owned))+}diff --git a/crates/openhuman-core/src/core/runtime/context.rs b/crates/openhuman-core/src/core/runtime/context.rsindex a8d8981fe2..508e8c2f6c 100644--- a/crates/openhuman-core/src/core/runtime/context.rs+++ b/crates/openhuman-core/src/core/runtime/context.rs@@ -107,6 +107,17 @@ pub struct CoreContext {/// ([`crate::agent::session_store`]) hands out to work under this/// context. `None` for booted contexts, which use the shared default.session_agent: Option<String>,+ /// The security policy of the agent this context was derived for. `None`+ /// for booted contexts, which read the process live policy.+ agent_policy: Option<Arc<crate::security::SecurityPolicy>>,+ /// Whether the interactive approval gate is off for this agent.+ approvals_disabled: bool,+ /// The sub-agent catalogue of the agent this context was derived for.+ /// `None` resolves through the process registry.+ definitions: Option<Arc<crate::agent::harness::definition::AgentDefinitionRegistry>>,+ /// State slots owned by this agent. Shared by every turn context derived+ /// from the same agent context.+ agent_state: Arc<super::agent_scope::AgentScopedState>,}/// Per-agent overrides layered onto a booted context by@@ -135,8 +146,16 @@ pub struct ContextOverlay {/// Scan the operator's user-scope skill roots (`true` = today's behaviour).pub user_skill_roots: bool,/// The agent a host session store scopes this context's transcripts,- /// journal, goals and todos to. `None` keeps the parent's.+ /// journal, goals and todos to. `None` keeps the parent's. Setting it+ /// gives the derived context state slots of its own.pub session_agent: Option<String>,+ /// The agent's own security policy: autonomy tier, auto-approve list,+ /// action budget. `None` keeps the parent's.+ pub agent_policy: Option<Arc<crate::security::SecurityPolicy>>,+ /// Turn the interactive approval gate off for this agent.+ pub approvals_disabled: bool,+ /// The agent's own sub-agent catalogue. `None` keeps the parent's.+ pub definitions: Option<Arc<crate::agent::harness::definition::AgentDefinitionRegistry>>,}impl ContextOverlay {@@ -152,6 +171,9 @@ impl ContextOverlay {tool_groups,user_skill_roots: true,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,}}@@ -167,6 +189,21 @@ impl ContextOverlay {self.session_agent = Some(agent_id.into());self}++ /// Give the derived context its own security policy.+ pub fn agent_policy(mut self, policy: Arc<crate::security::SecurityPolicy>) -> Self {+ self.agent_policy = Some(policy);+ self+ }++ /// Give the derived context its own sub-agent catalogue.+ pub fn definitions(+ mut self,+ definitions: Arc<crate::agent::harness::definition::AgentDefinitionRegistry>,+ ) -> Self {+ self.definitions = Some(definitions);+ self+ }}/// The workspace a context is bound to.@@ -321,6 +358,10 @@ impl CoreContext {backend_transport,turn_origin: None,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,+ agent_state: Default::default(),});let _ = DEFAULT_CONTEXT.set(ctx.clone());@@ -426,6 +467,11 @@ impl CoreContext {})),}};+ let agent_state = if overlay.session_agent.is_some() {+ Default::default()+ } else {+ Arc::clone(&self.agent_state)+ };Arc::new(CoreContext {host_kind: self.host_kind,workspace_binding: RwLock::new(shared_binding),@@ -436,6 +482,10 @@ impl CoreContext {backend_transport: self.backend_transport.clone(),turn_origin: self.turn_origin.clone(),session_agent: overlay.session_agent.or_else(|| self.session_agent.clone()),+ agent_policy: overlay.agent_policy.or_else(|| self.agent_policy.clone()),+ approvals_disabled: overlay.approvals_disabled || self.approvals_disabled,+ definitions: overlay.definitions.or_else(|| self.definitions.clone()),+ agent_state,})}@@ -445,6 +495,44 @@ impl CoreContext {self.session_agent.as_deref()}+ /// The security policy of the agent this context was derived for.+ pub fn agent_policy(&self) -> Option<Arc<crate::security::SecurityPolicy>> {+ self.agent_policy.clone()+ }++ /// [`agent_policy`](Self::agent_policy) of the ambient context.+ pub fn current_agent_policy() -> Option<Arc<crate::security::SecurityPolicy>> {+ Self::current().and_then(|ctx| ctx.agent_policy.clone())+ }++ /// Whether the interactive approval gate is off for this context's agent.+ pub fn approvals_disabled(&self) -> bool {+ self.approvals_disabled+ }++ /// [`approvals_disabled`](Self::approvals_disabled) of the ambient context.+ pub fn current_approvals_disabled() -> bool {+ Self::current().is_some_and(|ctx| ctx.approvals_disabled)+ }++ /// The sub-agent catalogue of the agent this context was derived for.+ pub fn definitions(+ &self,+ ) -> Option<Arc<crate::agent::harness::definition::AgentDefinitionRegistry>> {+ self.definitions.clone()+ }++ /// The state slots this context owns.+ pub fn agent_state(&self) -> &super::agent_scope::AgentScopedState {+ &self.agent_state+ }++ /// The task-local context, without falling back to the process default.+ /// `None` outside any [`scope`](Self::scope).+ pub fn scoped() -> Option<Arc<CoreContext>> {+ CURRENT_CONTEXT.try_with(Arc::clone).ok()+ }+/// The backend transport bound to this context, if the host supplied one.pub fn backend_transport(&self,@@ -586,6 +674,10 @@ impl CoreContext {backend_transport: None,turn_origin: None,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,+ agent_state: Default::default(),})}@@ -616,6 +708,10 @@ impl CoreContext {backend_transport: None,turn_origin: None,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,+ agent_state: Default::default(),})}}diff --git a/crates/openhuman-core/src/core/runtime/context_tests.rs b/crates/openhuman-core/src/core/runtime/context_tests.rsindex dfaef14494..66eda25353 100644--- a/crates/openhuman-core/src/core/runtime/context_tests.rs+++ b/crates/openhuman-core/src/core/runtime/context_tests.rs@@ -14,6 +14,10 @@ fn ctx(dir: &str) -> Arc<CoreContext> {backend_transport: None,turn_origin: None,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,+ agent_state: Default::default(),})}@@ -45,6 +49,10 @@ fn ctx_with_config(config: crate::config::Config) -> Arc<CoreContext> {backend_transport: None,turn_origin: None,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,+ agent_state: Default::default(),})}@@ -366,6 +374,10 @@ fn degraded_context_rejects_workspace_bound_stores() {backend_transport: None,turn_origin: None,session_agent: None,+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,+ agent_state: Default::default(),};// `workspace_dir()` is the gate every workspace-bound store goesdiff --git a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs b/crates/openhuman-core/src/core/runtime/context_turn_origin.rsindex 781813f7d6..9af1e9481c 100644--- a/crates/openhuman-core/src/core/runtime/context_turn_origin.rs+++ b/crates/openhuman-core/src/core/runtime/context_turn_origin.rs@@ -43,6 +43,10 @@ impl CoreContext {backend_transport: ctx.backend_transport.clone(),turn_origin: origin.or_else(|| ctx.turn_origin.clone()),session_agent: ctx.session_agent.clone(),+ agent_policy: ctx.agent_policy.clone(),+ approvals_disabled: ctx.approvals_disabled,+ definitions: ctx.definitions.clone(),+ agent_state: Arc::clone(&ctx.agent_state),});CURRENT_CONTEXT.scope(context, fut).await}diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rsindex 4a8eacb11e..81d084020f 100644--- a/crates/openhuman-core/src/core/runtime/mod.rs+++ b/crates/openhuman-core/src/core/runtime/mod.rs@@ -43,11 +43,13 @@ pub const AGENT_WORKER_STACK_BYTES: usize = 20 * 1024 * 1024;/// `.thread_stack_size(AGENT_WORKER_STACK_BYTES)` on every such runtime.pub const MAX_BLOCKING_THREADS: usize = 64;+pub mod agent_scope;mod bootstrap;pub mod builder;pub mod context;pub mod services;pub(crate) mod subscribers;+pub use agent_scope::{agent_scope_dir, current_slot, AgentContextRegistry, AgentScopedState};pub use builder::{CoreBuilder, CoreRuntime, DomainSet, ServiceSet, TokenSource};pub use context::{ContextOverlay, CoreContext};diff --git a/crates/openhuman-embed/src/agent/build.rs b/crates/openhuman-embed/src/agent/build.rsindex 307fb323c9..425ca494c6 100644--- a/crates/openhuman-embed/src/agent/build.rs+++ b/crates/openhuman-embed/src/agent/build.rs@@ -164,6 +164,9 @@ pub(crate) fn instantiate(runtime: &Runtime, spec: AgentSpec) -> Result<AgentInnuser_skill_roots: parts.include_user_skills,// A host session store keeps each agent's conversations apart by id.session_agent: Some(id.to_string()),+ agent_policy: None,+ approvals_disabled: false,+ definitions: None,};let ctx = runtime.core_runtime().context().derive_with(overlay);