Skip to content

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

chore: files changed crates/openhuman-embed/src/lib.rs,crates/openhuman-embed/src/runtime/builder.rs

Steven Enamakelf66fb820d1a7
diff --git a/crates/openhuman-embed/src/lib.rs b/crates/openhuman-embed/src/lib.rs
index b2d29e5855..c01e854783 100644
--- a/crates/openhuman-embed/src/lib.rs
+++ b/crates/openhuman-embed/src/lib.rs
@@ -90,6 +90,7 @@ mod auth;
mod call;
mod config;
mod core_agent;
+pub mod cron;
mod error;
mod harness;
pub mod memory;
@@ -104,6 +105,10 @@ pub use agent::{
pub use auth::{Auth, AuthState, Session};
pub use config::{Config, RuntimeFlags};
pub use core_agent::CoreAgent;
+pub use cron::{
+ Cron, CronError, JobRun, JobRunRecord, JobSchedule, JobSpec, JobTarget, ScheduledJob,
+ SystemJobContext,
+};
pub use error::CoreError;
pub use harness::{
Access, Harness, HarnessBuilder, HarnessCore, HarnessError, Provider, Workspace,
diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rs
index 77b506ba7f..44e831a17d 100644
--- a/crates/openhuman-embed/src/runtime/builder.rs
+++ b/crates/openhuman-embed/src/runtime/builder.rs
@@ -173,6 +173,11 @@ impl RuntimeBuilder {
/// cron, the login-gated services and the memory queue each write to the workspace on
/// their own schedule, turning a library call into a background process
/// the caller did not ask for.
+ ///
+ /// A set that selects anything beyond `harness_init` — `cron: true` to
+ /// let [`Runtime::cron`] jobs fire on their own, say — is started by
+ /// [`build`](Self::build) and stopped when the runtime drops; see
+ /// [`Runtime::start_services`] / [`Runtime::stop_services`].
pub fn services(mut self, services: ServiceSet) -> Self {
self.services = Some(services);
self
@@ -370,7 +375,7 @@ impl RuntimeBuilder {
let installed_session_store = session_store_cleanup.installed.take();
let previous_session_store = session_store_cleanup.previous.take();
- Ok(Runtime::new(
+ let runtime = Runtime::new(
core,
resolved,
installed_session_store,
@@ -381,10 +386,24 @@ impl RuntimeBuilder {
tool_groups,
self.provider,
self.access,
- ))
+ );
+ if requests_background_services(services) {
+ log::debug!("[embed][runtime] starting background services {services:?}");
+ runtime.start_services().await;
+ }
+ Ok(runtime)
}
}
+/// Whether `services` asks for any background work beyond the one-shot
+/// harness init, which a library runtime has never started on its own.
+pub(crate) fn requests_background_services(services: ServiceSet) -> bool {
+ ServiceSet {
+ harness_init: false,
+ ..services
+ } != ServiceSet::none()
+}
+
fn map_ws(err: crate::HarnessError) -> RuntimeError {
match err {
crate::HarnessError::Workspace { what, source } => RuntimeError::Workspace { what, source },
diff --git a/crates/openhuman-embed/src/runtime/host_agents.rs b/crates/openhuman-embed/src/runtime/host_agents.rs
new file mode 100644
index 0000000000..fd631dab76
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/host_agents.rs
@@ -0,0 +1,66 @@
+//! The runtime's agents, as the core's own drivers see them.
+//!
+//! The core's cron scheduler and workflow `agent` nodes only know an agent
+//! id. [`RuntimeAgents`] answers for the ids alive on this runtime with
+//! everything a session for that agent needs: its definition, its host tools
+//! (spec belt plus attachments), its config with the provider model and route
+//! applied, and its context. The runtime installs it on build and removes it
+//! when the last owner of the core drops.
+
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex, Weak};
+
+use openhuman_core::agent::host_agents::{HostAgent, HostAgentResolver};
+
+use crate::agent::AgentInner;
+
+/// The live agents of one runtime, by id.
+pub(crate) type AgentMap = Mutex<HashMap<String, Weak<AgentInner>>>;
+
+pub(crate) struct RuntimeAgents(pub(crate) Arc<AgentMap>);
+
+impl HostAgentResolver for RuntimeAgents {
+ fn resolve(&self, agent_id: &str) -> Option<HostAgent> {
+ let inner = self
+ .0
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .get(agent_id)?
+ .upgrade()?;
+ inner.host_agent()
+ }
+}
+
+impl AgentInner {
+ /// This agent as a core driver builds it. `None` when its provider route
+ /// pairs a bearer with an endpoint a turn would refuse (plain `http:` to
+ /// a remote host): the driver then fails to find the agent rather than
+ /// sending the credential in the clear.
+ pub(crate) fn host_agent(self: &Arc<Self>) -> Option<HostAgent> {
+ let mut config = self.config.clone();
+ if let Some(model) = self.provider.model_id() {
+ config.default_model = Some(model.to_string());
+ }
+ if let Some(route) = self.provider.route() {
+ if !crate::turn::is_safe_endpoint_for_bearer(&route.base_url) {
+ log::warn!(
+ "[embed][agent] id={} has an insecure route; not offered to core drivers",
+ self.id
+ );
+ return None;
+ }
+ if let Some(route) = openhuman_core::config::schema::EphemeralRoute::from_params(
+ Some(route.base_url.clone()),
+ Some(route.api_key.clone()),
+ ) {
+ openhuman_core::config::schema::ephemeral_route::apply(&mut config, route);
+ }
+ }
+ Some(HostAgent {
+ definition: self.definition.clone(),
+ config,
+ host_tools: self.composed_host_tools(),
+ context: Arc::clone(&self.ctx),
+ })
+ }
+}
diff --git a/crates/openhuman-embed/src/runtime/mod.rs b/crates/openhuman-embed/src/runtime/mod.rs
index 44e9d192cf..217f79865e 100644
--- a/crates/openhuman-embed/src/runtime/mod.rs
+++ b/crates/openhuman-embed/src/runtime/mod.rs
@@ -69,6 +69,7 @@
mod api_key;
pub(crate) mod builder;
+mod host_agents;
pub use api_key::ApiKey;
pub use builder::RuntimeBuilder;
@@ -76,7 +77,7 @@ pub use builder::RuntimeBuilder;
use std::collections::HashMap;
use std::path::Path;
use std::sync::atomic::AtomicBool;
-use std::sync::{Arc, Mutex, Weak};
+use std::sync::{Arc, Mutex};
use openhuman_core::config::Config;
use openhuman_core::core::runtime::{CoreRuntime, DomainSet, ServiceSet};
@@ -158,13 +159,28 @@ pub(crate) struct CoreGuard {
session_store: Option<Arc<dyn openhuman_core::agent::session_store::SessionStoreProvider>>,
previous_session_store:
Option<Arc<dyn openhuman_core::agent::session_store::SessionStoreProvider>>,
+ /// The resolver through which the core's cron and workflow drivers find
+ /// this runtime's agents; removed with the runtime.
+ host_agents: Arc<dyn openhuman_core::agent::host_agents::HostAgentResolver>,
+ /// Handlers registered with [`Runtime::on_system_job`], by job name.
+ system_jobs: Mutex<
+ HashMap<String, openhuman_core::cron::system_job_handlers::SystemJobRegistration>,
+ >,
}
impl Drop for CoreGuard {
fn drop(&mut self) {
+ // Stop handing this runtime's agents and handlers to the core's
+ // drivers before the core goes.
+ openhuman_core::agent::host_agents::clear_if(&self.host_agents);
+ self.system_jobs
+ .get_mut()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .clear();
// Drop the core while the process slot is still claimed. Releasing it
// first lets another builder initialize process-scoped state while
// this runtime's keyring, bearer, event bus and subscribers are live.
+ // Dropping it also stops the background services it started.
drop(self.core.take());
if let Some(installed) = self.session_store.take() {
if openhuman_core::agent::session_store::clear_if(&installed) {
@@ -218,7 +234,7 @@ pub struct Runtime {
tool_groups: ToolGroups,
provider: Provider,
access: Access,
- agents: Mutex<HashMap<String, Weak<AgentInner>>>,
+ agents: Arc<host_agents::AgentMap>,
}
impl Runtime {
@@ -259,6 +275,61 @@ impl Runtime {
Ok(Agent::from_inner(inner))
}
+ /// The runtime's scheduled jobs. See [`crate::cron`].
+ pub fn cron(&self) -> crate::cron::Cron<'_> {
+ crate::cron::Cron::new(&self.base_config)
+ }
+
+ /// Run `handler` whenever system job `name` comes due (see
+ /// [`JobSpec::system`](crate::JobSpec::system)), and record its result as
+ /// the run's: `Err` is a failed run, retried like any other. A later
+ /// registration under the same name replaces this one; handlers live as
+ /// long as the runtime.
+ pub fn on_system_job<F, Fut>(
+ &self,
+ name: impl Into<String>,
+ handler: F,
+ ) -> Result<(), crate::cron::CronError>
+ where
+ F: Fn(crate::cron::SystemJobContext) -> Fut + Send + Sync + 'static,
+ Fut: std::future::Future<Output = Result<(), String>> + Send + 'static,
+ {
+ let name = name.into();
+ if name.trim().is_empty() || name.contains(':') {
+ return Err(crate::cron::CronError::Invalid(format!(
+ "system job name {name:?} must be non-blank and contain no ':'"
+ )));
+ }
+ let registration = openhuman_core::cron::system_job_handlers::register(
+ &name,
+ crate::cron::boxed_handler(handler),
+ );
+ log::debug!("[embed][runtime] system job handler registered name={name}");
+ self.guard
+ .system_jobs
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .insert(name, registration);
+ Ok(())
+ }
+
+ /// Start the background services this runtime's [`ServiceSet`] selects
+ /// (the cron scheduler, channel listeners, …). [`RuntimeBuilder::build`]
+ /// already does this when the set asks for more than `harness_init`; call
+ /// it after [`stop_services`](Self::stop_services) to restart them.
+ /// Idempotent while they run.
+ pub async fn start_services(&self) {
+ log::debug!("[embed][runtime] start_services");
+ self.core_runtime().start_services().await;
+ }
+
+ /// Stop the background services. They also stop when the last owner of
+ /// the runtime's core (this runtime or one of its agents) drops.
+ pub fn stop_services(&self) {
+ log::debug!("[embed][runtime] stop_services");
+ self.core_runtime().stop_services();
+ }
+
/// Ids of the agents currently alive on this runtime.
pub fn agent_ids(&self) -> Vec<String> {
let mut agents = self.agents.lock().unwrap_or_else(|e| e.into_inner());
@@ -382,6 +453,10 @@ impl Runtime {
provider: Provider,
access: Access,
) -> Self {
+ let agents: Arc<host_agents::AgentMap> = Arc::new(Mutex::new(HashMap::new()));
+ let resolver: Arc<dyn openhuman_core::agent::host_agents::HostAgentResolver> =
+ Arc::new(host_agents::RuntimeAgents(Arc::clone(&agents)));
+ openhuman_core::agent::host_agents::install(Arc::clone(&resolver));
Self {
id: uuid::Uuid::new_v4().to_string(),
guard: Arc::new(CoreGuard {
@@ -389,6 +464,8 @@ impl Runtime {
workspace,
session_store,
previous_session_store,
+ host_agents: resolver,
+ system_jobs: Mutex::new(HashMap::new()),
}),
base_config,
inherited,
@@ -396,7 +473,7 @@ impl Runtime {
tool_groups,
provider,
access,
- agents: Mutex::new(HashMap::new()),
+ agents,
}
}
}
diff --git a/crates/openhuman-embed/src/turn.rs b/crates/openhuman-embed/src/turn.rs
index 1ea9f36974..8b8683c3e8 100644
--- a/crates/openhuman-embed/src/turn.rs
+++ b/crates/openhuman-embed/src/turn.rs
@@ -114,7 +114,7 @@ pub(crate) fn sanitize_url_for_display(url: &str) -> String {
/// embedder configuration. Falls back to `false` when the value does not
/// parse as an absolute URL, so an unparseable route is refused rather than
/// silently allowed.
-fn is_safe_endpoint_for_bearer(endpoint: &str) -> bool {
+pub(crate) fn is_safe_endpoint_for_bearer(endpoint: &str) -> bool {
let Ok(url) = url::Url::parse(endpoint) else {
return false;
};