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
chore: files changed crates/openhuman-core/src/core/runtime/services.rs,crates/openhuman-core/src/co
Steven Enamakel5666361a8f48
diff --git a/crates/openhuman-core/src/core/runtime/services.rs b/crates/openhuman-core/src/core/runtime/services.rsindex 7348eda23f..a767bdeeac 100644--- a/crates/openhuman-core/src/core/runtime/services.rs+++ b/crates/openhuman-core/src/core/runtime/services.rs@@ -19,6 +19,82 @@use crate::config::Config;use crate::core::runtime::ServiceSet;+/// The long-lived background services a runtime started, so it can stop them.+///+/// The service spawns below used to be fire-and-forget: fine for a desktop+/// core that lives as long as its process, wrong for a library runtime that is+/// dropped and rebuilt in one process, whose cron loop would otherwise keep+/// polling the old workspace forever. [`CoreRuntime::start_services`]+/// (crate::core::runtime::CoreRuntime::start_services) tracks each top-level+/// service task here; [`stop`](Self::stop) and `Drop` abort them. Aborting the+/// cron loop drops its dispatcher, which aborts the jobs it was running.+///+/// Work a service spawns detached on its own (a channel listener's sockets,+/// the login-gated services' workers) is not reached by the abort; only the+/// cron loop and the other top-level spawns are guaranteed to stop.+#[derive(Default)]+pub struct ServiceTasks {+ started: std::sync::atomic::AtomicBool,+ tasks: std::sync::Mutex<Vec<(&'static str, tokio::task::AbortHandle)>>,+}++impl ServiceTasks {+ /// Claim the start; `false` when the services already started and have+ /// not been stopped since.+ pub fn begin(&self) -> bool {+ !self+ .started+ .swap(true, std::sync::atomic::Ordering::AcqRel)+ }++ /// Track a service task so [`stop`](Self::stop) can abort it.+ pub fn track(&self, name: &'static str, handle: tokio::task::JoinHandle<()>) {+ log::debug!("[runtime.services] tracking service task {name}");+ self.tasks+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .push((name, handle.abort_handle()));+ }++ /// How many service tasks are tracked.+ pub fn len(&self) -> usize {+ self.tasks+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .len()+ }++ /// Whether no service task is tracked.+ pub fn is_empty(&self) -> bool {+ self.len() == 0+ }++ /// Abort every tracked service task; the services may be started again.+ pub fn stop(&self) {+ let tasks = std::mem::take(+ &mut *self+ .tasks+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner),+ );+ for (name, handle) in &tasks {+ log::debug!("[runtime.services] stopping service task {name}");+ handle.abort();+ }+ self.started+ .store(false, std::sync::atomic::Ordering::Release);+ if !tasks.is_empty() {+ log::info!("[runtime.services] stopped {} service task(s)", tasks.len());+ }+ }+}++impl Drop for ServiceTasks {+ fn drop(&mut self) {+ self.stop();+ }+}+/// Background bootstrap for login-gated services (local AI, voice, screen/// intelligence, autocomplete).///@@ -26,7 +102,7 @@ use crate::core::runtime::ServiceSet;/// exists on disk, startup is deferred until the login handler in/// `credentials::ops::store_session()` triggers it. The autocomplete shutdown/// hook is registered unconditionally.-pub fn spawn_login_gated_services(embedded_core: bool) {+pub fn spawn_login_gated_services(embedded_core: bool) -> tokio::task::JoinHandle<()> {tokio::spawn(async move {match crate::config::Config::load_or_init().await {Ok(config) => {@@ -60,7 +136,7 @@ pub fn spawn_login_gated_services(embedded_core: bool) {}/// Periodic self-update checker (default: every 1 hour).-pub fn spawn_update_scheduler() {+pub fn spawn_update_scheduler() -> tokio::task::JoinHandle<()> {tokio::spawn(async {match crate::config::Config::load_or_init().await {Ok(config) => {@@ -119,9 +195,17 @@ pub fn spawn_flows_boot_reconcile() {/// Cron scheduler — polls `due_jobs()` every ~5s and executes them/// automatically. Gated by `config.cron.enabled`.-pub fn spawn_cron_service() {- tokio::spawn(async {- match crate::config::Config::load_or_init().await {+///+/// Runs under `ctx`, the runtime's own context: the config is read through+/// `load_config_with_timeout`, which prefers an embedder-supplied config, so a+/// library runtime's scheduler polls *its* workspace rather than the+/// operator's `~/.openhuman`, and every job it dispatches inherits that+/// context.+pub fn spawn_cron_service(+ ctx: std::sync::Arc<crate::core::runtime::CoreContext>,+) -> tokio::task::JoinHandle<()> {+ tokio::spawn(crate::core::runtime::CoreContext::scope(ctx, async {+ match crate::config::ops::load_config_with_timeout().await {Ok(config) => {if !config.cron.enabled {log::info!("[cron] scheduler disabled via config; skipping");@@ -149,7 +233,7 @@ pub fn spawn_cron_service() {log::warn!("[core] config load failed, skipping cron scheduler: {err}");}}- });+ }))}/// Realtime channel listeners (Telegram getUpdates, Discord gateway, etc.).diff --git a/crates/openhuman-core/src/core/runtime/services_tests.rs b/crates/openhuman-core/src/core/runtime/services_tests.rsindex b963f463a2..7fede9748c 100644--- a/crates/openhuman-core/src/core/runtime/services_tests.rs+++ b/crates/openhuman-core/src/core/runtime/services_tests.rs@@ -82,3 +82,52 @@ fn channels_flag_gates_no_bootstrap_job() {"dropping channels must not drop any bootstrap job");}++// ── ServiceTasks: background services a runtime can stop ─────────++#[tokio::test]+async fn stopping_service_tasks_aborts_every_tracked_task() {+ let tasks = ServiceTasks::default();+ let (tx, rx) = tokio::sync::oneshot::channel::<()>();+ let handle = tokio::spawn(async move {+ let _keep = tx;+ std::future::pending::<()>().await;+ });+ tasks.track("pending", handle);+ assert_eq!(tasks.len(), 1);+ tasks.stop();+ assert_eq!(tasks.len(), 0);+ // The sender drops when the aborted task is torn down.+ assert!(tokio::time::timeout(std::time::Duration::from_secs(5), rx)+ .await+ .expect("the aborted task is torn down")+ .is_err());+}++#[tokio::test]+async fn dropping_service_tasks_aborts_them() {+ let (tx, rx) = tokio::sync::oneshot::channel::<()>();+ {+ let tasks = ServiceTasks::default();+ tasks.track(+ "pending",+ tokio::spawn(async move {+ let _keep = tx;+ std::future::pending::<()>().await;+ }),+ );+ }+ assert!(tokio::time::timeout(std::time::Duration::from_secs(5), rx)+ .await+ .expect("the aborted task is torn down")+ .is_err());+}++#[test]+fn service_tasks_start_only_once() {+ let tasks = ServiceTasks::default();+ assert!(tasks.begin(), "the first start claims the services");+ assert!(!tasks.begin(), "a second start is a no-op");+ tasks.stop();+ assert!(tasks.begin(), "after a stop the services may start again");+}diff --git a/crates/openhuman-core/src/flows/ops/builder_gates.rs b/crates/openhuman-core/src/flows/ops/builder_gates.rsindex c4c64f1d16..e93fe59420 100644--- a/crates/openhuman-core/src/flows/ops/builder_gates.rs+++ b/crates/openhuman-core/src/flows/ops/builder_gates.rs@@ -421,12 +421,12 @@ pub(crate) async fn validate_agent_refs(config: &Config, graph: &WorkflowGraph)}match route_for_agent_ref(agent_ref) {- AgentRoute::Harness => {+ AgentRoute::Harness | AgentRoute::HostAgent => {tracing::debug!(target: "flows",node = %node.id,%agent_ref,- "[flows] agent-ref check: resolves to a harness agent definition"+ "[flows] agent-ref check: resolves to a harness or host agent definition");}AgentRoute::RegistryFallback => {diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rsindex 36ffd46ab2..28ea759b3e 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs@@ -130,6 +130,9 @@ pub(crate) enum AgentRoute {/// custom-registry fallback. Pure over the global registry so the selection is/// unit-testable with `init_global_builtins`.pub(crate) fn route_for_agent_ref(agent_ref: &str) -> AgentRoute {+ if crate::agent::host_agents::resolve(agent_ref).is_some() {+ return AgentRoute::HostAgent;+ }let has_definition = crate::agent::harness::definition::AgentDefinitionRegistry::global().map(|reg| reg.get(agent_ref).is_some()).unwrap_or(false);@@ -186,6 +189,20 @@ impl AgentRunner for OpenHumanAgentRunner {}match route_for_agent_ref(agent_ref) {+ AgentRoute::HostAgent => {+ // Resolved again rather than carried by the route so the route+ // stays a plain value; a host that dropped the agent in between+ // degrades to the registry build below.+ let host = crate::agent::host_agents::resolve(agent_ref);+ tracing::info!(+ target: "flows",+ agent_ref,+ "[flows] agent_runner: HOST AGENT path — running the host-registered agent \+ with its own tools in its own context"+ );+ self.run_via_harness(agent_ref, request, conn, None, host)+ .await+ }AgentRoute::Harness => {tracing::info!(target: "flows",@@ -195,7 +212,7 @@ impl AgentRunner for OpenHumanAgentRunner {// A shipped/TOML harness definition has no `entry.model` — the// definition's own `ModelSpec` (already applied by the session// builder) is the only model pin in play here.- self.run_via_harness(agent_ref, request, conn, None).await+ self.run_via_harness(agent_ref, request, conn, None, None).await}AgentRoute::RegistryFallback => {// `route_for_agent_ref` only consults the harness@@ -219,7 +236,7 @@ impl AgentRunner for OpenHumanAgentRunner {crate::agent::registry::find_custom_in_config(&self.config, agent_ref);let entry_model = custom_entry.as_ref().and_then(|e| e.model.clone());match route_custom_entry_lookup(custom_entry.as_ref()) {- AgentRoute::Harness => {+ AgentRoute::Harness | AgentRoute::HostAgent => {tracing::info!(target: "flows",agent_ref,@@ -235,7 +252,7 @@ impl AgentRunner for OpenHumanAgentRunner {// comment on this PR: this previously regressed to the// default chat model for a custom flow agent with no// per-node override).- self.run_via_harness(agent_ref, request, conn, entry_model.as_deref())+ self.run_via_harness(agent_ref, request, conn, entry_model.as_deref(), None).await}AgentRoute::RegistryFallback => {@@ -305,6 +322,7 @@ impl OpenHumanAgentRunner {request: Value,conn: Option<&str>,entry_model: Option<&str>,+ host: Option<crate::agent::host_agents::HostAgent>,) -> Result<Value> {use crate::agent::OpenHumanSessionHost;@@ -337,21 +355,27 @@ impl OpenHumanAgentRunner {// with a new `default_model`, so we never mutate the shared config or// invent a new Agent setter API. The tier is normalised to the// `hint:<role>` form the session builder routes on.+ // A host-registered agent starts from its own config (its provider+ // model and route), not the flow runner's.+ let base: &Config = host.as_ref().map_or(self.config.as_ref(), |host| &host.config);let effective: Cow<'_, Config> = match node_model.as_deref() {Some(model) => {- let mut config = (*self.config).clone();+ let mut config = base.clone();config.default_model = Some(harness_model_default_override(model));Cow::Owned(config)}- None => Cow::Borrowed(self.config.as_ref()),+ None => Cow::Borrowed(base),};- let mut agent = OpenHumanSessionHost::from_config_for_agent(effective.as_ref(), agent_ref)- .map_err(|e| {- EngineError::Capability(format!(- "agent node: failed to build harness agent '{agent_ref}': {e:#}"- ))- })?;+ let built = match &host {+ Some(host) => host.session_host(effective.as_ref(), None),+ None => OpenHumanSessionHost::from_config_for_agent(effective.as_ref(), agent_ref),+ };+ let mut agent = built.map_err(|e| {+ EngineError::Capability(format!(+ "agent node: failed to build harness agent '{agent_ref}': {e:#}"+ ))+ })?;agent.set_agent_definition_name(agent_ref.to_string());let prompt = build_harness_run_prompt(&request);@@ -427,6 +451,14 @@ impl OpenHumanAgentRunner {} else {Box::pin(agent.run_single(&prompt))};+ // A host agent's turn reads its own context (config, domains, tool+ // groups, session store); the origin task-local is untouched.+ let run: std::pin::Pin<+ Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send>,+ > = match host.as_ref().map(|host| std::sync::Arc::clone(&host.context)) {+ Some(context) => Box::pin(crate::core::runtime::CoreContext::scope(context, run)),+ None => run,+ };let final_text =match tokio::time::timeout(std::time::Duration::from_secs(timeout_secs), run).await {Ok(Ok(text)) => text,