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(cron): add cron job management and device owner tracking
Steven Enamakel72260a27376f
diff --git a/crates/openhuman-core/src/cron/scheduler.rs b/crates/openhuman-core/src/cron/scheduler.rsindex ba27d2fa91..ad5f27e295 100644--- a/crates/openhuman-core/src/cron/scheduler.rs+++ b/crates/openhuman-core/src/cron/scheduler.rs@@ -75,7 +75,7 @@ pub async fn run(config: Config) -> Result<()> {loop {interval.tick().await;tick_once(&config, &security, &mut last_emitted_health).await;- tick_agents(&config, &mut last_emitted_health).await;+ tick_agents(&mut last_emitted_health).await;}}@@ -87,13 +87,13 @@ pub async fn run(config: Config) -> Result<()> {/// pass so a failure or recovery reported from an agent pass is seen by the/// next one); each agent pass authorizes its jobs with a policy built from/// that agent's own configuration.-pub(crate) async fn tick_agents(config: &Config, last_emitted_health: &mut Option<bool>) {+pub(crate) async fn tick_agents(last_emitted_health: &mut Option<bool>) {let health = std::sync::Mutex::new(*last_emitted_health);crate::storage::agents::for_each_agent("cron", || async {let mut steady = *health.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- tick_agent_scope(config, &mut steady).await;+ tick_agent_scope(&mut steady).await;*health.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = steady;@@ -106,15 +106,53 @@ pub(crate) async fn tick_agents(config: &Config, last_emitted_health: &mut Optio/// One agent's pass: the poll under the current (agent) context, with that/// agent's configuration when it has one and a policy built from it.-async fn tick_agent_scope(config: &Config, last_emitted_health: &mut Option<bool>) {- let config = crate::core::runtime::CoreContext::current_embedder_config()- .unwrap_or_else(|| config.clone());- let security = Arc::new(SecurityPolicy::from_config(+///+/// Fails closed: an agent whose context carries no configuration of its own+/// (one known only from the backend's record of it, not yet re-created by the+/// host) is skipped rather than run under another agent's workspace, settings+/// and autonomy policy. Its jobs wait for the host to derive it again.+async fn tick_agent_scope(last_emitted_health: &mut Option<bool>) {+ use crate::core::runtime::CoreContext;+ let (Some(context), Some(config)) =+ (CoreContext::current(), CoreContext::current_embedder_config())+ else {+ tracing::debug!(+ "[cron:scheduler] skipping an agent scope: its context has no configuration of its own"+ );+ return;+ };+ let security = agent_policy(&context, &config);+ tick_once(&config, &security, last_emitted_health).await;+}++/// The agent's security policy, kept across ticks so its rolling action+/// budget is not reset by every poll. Rebuilt when the host re-derives the+/// agent's context (a new context may carry new settings).+fn agent_policy(+ context: &Arc<crate::core::runtime::CoreContext>,+ config: &Config,+) -> Arc<SecurityPolicy> {+ use std::collections::HashMap;+ use std::sync::{LazyLock, Mutex};+ static POLICIES: LazyLock<Mutex<HashMap<String, (usize, Arc<SecurityPolicy>)>>> =+ LazyLock::new(Default::default);+ let identity = Arc::as_ptr(context) as usize;+ let agent = context.session_agent().unwrap_or_default().to_string();+ let mut policies = POLICIES+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some((built_for, policy)) = policies.get(&agent) {+ if *built_for == identity {+ return Arc::clone(policy);+ }+ }+ let policy = Arc::new(SecurityPolicy::from_config(&config.autonomy,&config.workspace_dir,&config.action_dir,));- tick_once(&config, &security, last_emitted_health).await;+ policies.insert(agent, (identity, Arc::clone(&policy)));+ policy}/// Single poll cycle of the scheduler loop, extracted so tests can drivediff --git a/crates/openhuman-core/src/flows/ops/run_management.rs b/crates/openhuman-core/src/flows/ops/run_management.rsindex 9c8a37592b..fc75f018e4 100644--- a/crates/openhuman-core/src/flows/ops/run_management.rs+++ b/crates/openhuman-core/src/flows/ops/run_management.rs@@ -277,8 +277,12 @@ pub async fn sweep_orphaned_running_runs_on_boot(config: &Config) -> usize {// boot floor can belong to a run another replica is still driving, and// sweeping it would drop that run's checkpoint — so the agent scopes are// left alone there, as the agent run reaper does.- if crate::storage::installed_is_shared() && !crate::core::runtime::mode::is_saas() {+ if crate::storage::installed_is_shared() {tracing::info!(target: "flows", "[flows] boot sweep: agent scopes skipped, the storage backend is shared");+ if crate::core::runtime::mode::is_saas() {+ // No `local` scope to fall back on: every row belongs to an agent.+ return 0;+ }return sweep_orphaned_running_runs_in_scope(config).await;}crate::storage::agents::for_each_scope("flows boot sweep", || {diff --git a/crates/openhuman-core/src/security/devices/bus.rs b/crates/openhuman-core/src/security/devices/bus.rsindex 2b1a829b5b..076d426478 100644--- a/crates/openhuman-core/src/security/devices/bus.rs+++ b/crates/openhuman-core/src/security/devices/bus.rs@@ -92,7 +92,12 @@ impl EventHandler<DomainEvent> for DeviceTunnelSubscriber {.unwrap_or_else(std::sync::PoisonError::into_inner).get(channel_id.as_str()).cloned();- let owner = super::owner::owner_of(channel_id, pending.as_ref()).await;+ let Ok(owner) = super::owner::owner_of(channel_id, pending.as_ref()).await else {+ log::warn!(+ "[devices/bus] dropping tunnel frame channel_id={channel_id}: owner unresolved"+ );+ return;+ };crate::storage::agents::within_agent(owner.as_deref(),handle_tunnel_frame(channel_id, payload_b64),diff --git a/crates/openhuman-core/src/security/devices/owner.rs b/crates/openhuman-core/src/security/devices/owner.rsindex 54fc515b68..bcb1ad5966 100644--- a/crates/openhuman-core/src/security/devices/owner.rs+++ b/crates/openhuman-core/src/security/devices/owner.rs@@ -40,40 +40,60 @@ fn cached(channel_id: &str) -> Option<Option<String>> {/// The agent `channel_id` belongs to, resolved as described above. A channel/// no scope knows yet (a handshake still in flight) is `local`.-pub(super) async fn owner_of(channel_id: &str, pending: Option<&PairingSession>) -> Option<String> {+///+/// # Errors+///+/// [`OwnerLookupFailed`] when no scope claimed the channel and at least one+/// could not be searched (its configuration would not load): the device may+/// well belong to that scope, so the caller must refuse the frame instead of+/// running it as `local`.+pub(super) async fn owner_of(+ channel_id: &str,+ pending: Option<&PairingSession>,+) -> Result<Option<String>, OwnerLookupFailed> {if let Some(session) = pending {- return session.agent.clone();+ return Ok(session.agent.clone());}if let Some(owner) = cached(channel_id) {- return owner;+ return Ok(owner);}// The configuration is loaded inside each scope: in SaaS mode loading it// needs an acting agent, which this tunnel task does not have.let found = crate::storage::agents::for_each_scope("device owner", || async {let Ok(config) = crate::config::rpc::load_config_with_timeout().await else {- return false;+ return None;};- super::store::get_device(&config, channel_id)- .ok()- .flatten()- .is_some()+ Some(+ super::store::get_device(&config, channel_id)+ .ok()+ .flatten()+ .is_some(),+ )})- .await- .into_iter()- .find_map(|(agent, has_device)| has_device.then_some(agent));- match found {- Some(owner) => {- log::debug!(- "[devices/owner] channel_id={channel_id} belongs to agent={}",- owner.as_deref().unwrap_or("local")- );- remember(channel_id, owner.clone());- owner- }- None => None,+ .await;+ if let Some(owner) = found+ .iter()+ .find_map(|(agent, has_device)| (*has_device == Some(true)).then(|| agent.clone()))+ {+ log::debug!(+ "[devices/owner] channel_id={channel_id} belongs to agent={}",+ owner.as_deref().unwrap_or("local")+ );+ remember(channel_id, owner.clone());+ return Ok(owner);}+ if found.iter().any(|(_, has_device)| has_device.is_none()) {+ log::warn!("[devices/owner] channel_id={channel_id} could not be searched in every scope");+ return Err(OwnerLookupFailed);+ }+ Ok(None)}+/// A scope's configuration would not load, so the owner of a channel could not+/// be ruled out there.+#[derive(Debug, PartialEq, Eq)]+pub(super) struct OwnerLookupFailed;+#[cfg(test)]#[path = "owner_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/storage/agents.rs b/crates/openhuman-core/src/storage/agents.rsindex 53f430b070..30ec2e50fc 100644--- a/crates/openhuman-core/src/storage/agents.rs+++ b/crates/openhuman-core/src/storage/agents.rs@@ -54,9 +54,15 @@ pub fn registered(context: Arc<CoreContext>) -> Arc<CoreContext> {let mut live = LIVE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- let contexts = live.entry(agent.to_string()).or_default();- contexts.retain(|existing| existing.strong_count() > 0);- contexts.push(Arc::downgrade(&context));+ // Agents come and go; forget the ones whose contexts are all gone so+ // the registry stays as small as the set of live agents.+ live.retain(|_, entries| {+ entries.retain(|entry| entry.strong_count() > 0);+ !entries.is_empty()+ });+ live.entry(agent.to_string())+ .or_default()+ .push(Arc::downgrade(&context));drop(live);record(agent);}