Skip to content

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

Merge upstream/main into oh-embed-cron-resolver

Steven Enamakele8eabc8a23e6
diff --cc crates/openhuman-core/src/cron/mod.rs
index c89de2dead,639e5fe035..a84a6f84e4
--- a/crates/openhuman-core/src/cron/mod.rs
+++ b/crates/openhuman-core/src/cron/mod.rs
@@@ -14,12 -14,9 +14,12 @@@ pub mod channel_bridge
pub mod job_builder;
pub mod ops;
pub mod origin;
+/// Per-job run policy (retry budget, single-flight) kept beside the job store.
+pub mod policy;
mod schemas;
pub mod seed;
- mod store;
+ pub(crate) mod store;
+pub mod system_job_handlers;
pub mod system_jobs;
pub mod tools;
diff --cc crates/openhuman-core/src/cron/scheduler.rs
index fe1793ea4f,dbf6ce99af..e0f6949fd9
--- a/crates/openhuman-core/src/cron/scheduler.rs
+++ b/crates/openhuman-core/src/cron/scheduler.rs
@@@ -87,13 -74,47 +87,54 @@@ pub async fn run(config: Config) -> Res
loop {
interval.tick().await;
- tick_once(&config, &security, &mut last_emitted_health).await;
- tick_live_agents().await;
+ tick_once(
+ &config,
+ &security,
+ &mut last_emitted_health,
+ &mut dispatcher,
+ )
+ .await;
++ tick_live_agents(&mut dispatcher).await;
+ }
+ }
+
+ /// Runs the due jobs of every live embedded agent, each under that agent's
+ /// own context: its config, provider route, policy and job database. An
+ /// agent that is not live has no context to run under, so its jobs stay
+ /// dormant until it is instantiated again.
-pub(crate) async fn tick_live_agents() {
++pub(crate) async fn tick_live_agents(dispatcher: &mut JobDispatcher) {
+ for (agent_id, ctx) in crate::core::runtime::AgentContextRegistry::live() {
+ let agent = agent_id.clone();
++ let dispatcher = &mut *dispatcher;
+ crate::core::runtime::CoreContext::scope(ctx, async move {
+ let config = match crate::config::ops::load_current_or_init().await {
+ Ok(config) => config,
+ Err(error) => {
+ tracing::debug!(agent = %agent, %error, "[cron:scheduler] agent config unavailable");
+ return;
+ }
+ };
+ if !crate::cron::store::db_path(&config).exists() {
+ return;
+ }
+ let jobs = match due_jobs(&config, Utc::now()) {
+ Ok(jobs) => jobs,
+ Err(error) => {
+ tracing::warn!(agent = %agent, "[cron:scheduler] agent poll db_error: {error}");
+ return;
+ }
+ };
+ if jobs.is_empty() {
+ return;
+ }
+ let Some(security) = crate::security::live_policy::effective() else {
+ tracing::warn!(agent = %agent, "[cron:scheduler] agent has no policy; jobs skipped");
+ return;
+ };
+ tracing::debug!(agent = %agent, due_count = jobs.len(), "[cron:scheduler] running agent jobs");
- process_due_jobs(&config, &security, jobs).await;
++ dispatcher.dispatch(&config, &security, jobs).await;
+ })
+ .await;
}
}
diff --cc crates/openhuman-core/src/cron/scheduler/agent_run.rs
index 84911d1696,cbae4fb0ea..f416e98acb
--- a/crates/openhuman-core/src/cron/scheduler/agent_run.rs
+++ b/crates/openhuman-core/src/cron/scheduler/agent_run.rs
@@@ -46,22 -46,10 +46,23 @@@ pub(super) async fn run_agent_job_for_r
// runs with the definition's constraints instead of the generic
// OpenHumanSessionHost::from_config defaults.
let selected_agent_id = job.agent_id.as_deref().unwrap_or("orchestrator");
- {
+ // A host-registered agent (`agent::host_agents`) carries its own
+ // definition, model and route; the registry overrides below are for
+ // registry agents only.
+ let is_host_agent = job
+ .agent_id
+ .as_deref()
+ .is_some_and(|id| crate::agent::host_agents::resolve(id).is_some());
+ if is_host_agent {
+ tracing::debug!(
+ job_id = %job.id,
+ agent_id = %selected_agent_id,
+ "[cron] job targets a host-registered agent"
+ );
+ } else {
let agent_id = selected_agent_id;
- if let Some(registry) = crate::agent::harness::definition::AgentDefinitionRegistry::global()
+ if let Some(registry) =
+ crate::agent::harness::definition::AgentDefinitionRegistry::current()
{
if let Some(def) = registry.get(agent_id) {
tracing::debug!(
diff --cc crates/openhuman-core/src/cron/store_tests.rs
index 4e241a19e5,9bb577eecc..c1e9683861
--- a/crates/openhuman-core/src/cron/store_tests.rs
+++ b/crates/openhuman-core/src/cron/store_tests.rs
@@@ -48,3 -48,77 +48,79 @@@ fn run_history_cap_follows_cron_max_run
}
assert_eq!(list_runs(&config, &job.id, 10).unwrap().len(), 2);
}
+
+ fn agent_context(
+ config: &Config,
+ agent: &str,
+ ) -> std::sync::Arc<crate::core::runtime::CoreContext> {
+ use crate::core::runtime::{ContextOverlay, CoreContext, DomainSet};
+ CoreContext::for_test_with_config(DomainSet::full(), config.clone()).derive_with(
+ ContextOverlay::new(
+ config.clone(),
+ DomainSet::full(),
+ crate::tools::toolpacks::ToolGroups::none(),
+ )
+ .session_agent(agent),
+ )
+ }
+
+ #[tokio::test]
+ async fn an_agents_jobs_live_in_its_own_database() {
+ use crate::core::runtime::CoreContext;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+
+ let job = CoreContext::scope(agent_context(&config, "alpha"), async {
+ add_job(&config, "*/5 * * * *", "echo alpha").unwrap()
+ })
+ .await;
+
+ assert!(tmp
+ .path()
+ .join("workspace/agents/alpha/cron/jobs.db")
+ .is_file());
+ let alpha_ids = CoreContext::scope(agent_context(&config, "alpha"), async {
+ list_jobs(&config)
+ .unwrap()
+ .into_iter()
+ .map(|job| job.id)
+ .collect::<Vec<_>>()
+ })
+ .await;
+ assert_eq!(alpha_ids, std::slice::from_ref(&job.id));
+ let beta_jobs = CoreContext::scope(agent_context(&config, "beta"), async {
+ list_jobs(&config).unwrap()
+ })
+ .await;
+ assert!(beta_jobs.is_empty());
+ assert!(
+ list_jobs(&config).unwrap().is_empty(),
+ "the workspace store stays empty"
+ );
+ }
+
+ #[tokio::test]
+ async fn a_job_whose_agent_is_not_live_stays_dormant() {
+ use crate::core::runtime::CoreContext;
+ let tmp = TempDir::new().unwrap();
+ let config = test_config(&tmp);
+ let ctx = agent_context(&config, "dormant-agent");
+ let job = CoreContext::scope(std::sync::Arc::clone(&ctx), async {
+ add_job(&config, "* * * * *", "echo dormant").unwrap()
+ })
+ .await;
+ drop(ctx);
+
- crate::cron::scheduler::tick_live_agents().await;
++ let mut dispatcher = crate::cron::scheduler::JobDispatcher::new(1);
++ crate::cron::scheduler::tick_live_agents(&mut dispatcher).await;
++ dispatcher.drain().await;
+
+ let after = CoreContext::scope(agent_context(&config, "dormant-agent"), async {
+ get_job(&config, &job.id).unwrap()
+ })
+ .await;
+ assert!(
+ after.last_run.is_none(),
+ "nothing ran the dormant agent's job"
+ );
+ }
diff --cc crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
index 2a9f1b54b7,8ec8484795..27c98bc205
--- a/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
+++ b/crates/openhuman-core/src/flows/tinyflows/caps/agent.rs
@@@ -130,10 -127,7 +130,10 @@@ 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()
+ let has_definition = crate::agent::harness::definition::AgentDefinitionRegistry::current()
.map(|reg| reg.get(agent_ref).is_some())
.unwrap_or(false);
if has_definition {
diff --cc crates/openhuman-embed/src/runtime/build.rs
index fc232a866e,6d041e2717..5fba574cf9
--- a/crates/openhuman-embed/src/runtime/build.rs
+++ b/crates/openhuman-embed/src/runtime/build.rs
@@@ -257,12 -257,8 +257,13 @@@ impl RuntimeBuilder
tool_groups,
self.provider,
self.access,
+ self.max_agents,
- ))
+ );
+ if requests_background_services(services) {
+ log::debug!("[embed][runtime] starting background services {services:?}");
+ runtime.start_services().await;
+ }
+ Ok(runtime)
}
/// The config a [`ConfigSource::Resolved`] runtime hands the core.
diff --cc crates/openhuman-embed/src/runtime/mod.rs
index 575f3ded50,8ba949bf94..1f869d3598
--- a/crates/openhuman-embed/src/runtime/mod.rs
+++ b/crates/openhuman-embed/src/runtime/mod.rs
@@@ -70,7 -69,7 +69,8 @@@
mod api_key;
mod build;
pub(crate) mod builder;
+mod host_agents;
+ mod lifecycle;
mod presets;
mod run;
mod seams;
@@@ -248,7 -234,8 +249,8 @@@ pub struct Runtime
tool_groups: ToolGroups,
provider: Provider,
access: Access,
- agents: Mutex<HashMap<String, Weak<AgentInner>>>,
+ agents: Arc<host_agents::AgentMap>,
+ max_agents: usize,
}
impl Runtime {
@@@ -493,11 -434,8 +504,12 @@@
tool_groups: ToolGroups,
provider: Provider,
access: Access,
+ max_agents: usize,
) -> 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 {
@@@ -516,7 -452,8 +528,8 @@@
tool_groups,
provider,
access,
- agents: Mutex::new(HashMap::new()),
+ agents,
+ max_agents,
}
}
}
diff --cc crates/openhuman-embed/tests/public_api.rs
index c62730628d,dcb19c5f48..623c12de97
--- a/crates/openhuman-embed/tests/public_api.rs
+++ b/crates/openhuman-embed/tests/public_api.rs
@@@ -1,11 -1,11 +1,12 @@@
use std::sync::Arc;
use openhuman_embed::{
- Access, Agent, AgentDefinitionSpec, AgentSpec, AgentTurnOrigin, ApiKey, Core, CoreBuilder,
- CoreRuntime, Cron, CronError, DomainSet, GroupMode, Harness, HostKind, JobRun, JobRunRecord,
- JobSchedule, JobSpec, JobTarget, Provider, Runtime, RuntimeBuilder, RuntimeConfig,
+ Access, Agent, AgentDefinitionSpec, AgentError, AgentSpec, AgentTurnOrigin, ApiKey,
- ApprovalDecision, Approvals, ApprovalsError, Core, CoreBuilder, CoreError, CoreRuntime,
- DomainSet, GroupMode, Harness, HostKind, PendingApproval, Provider, RemoveAgent, Runtime,
- RuntimeBuilder, RuntimeConfig, SandboxModeSpec, ServiceSet, ToolGroups, ToolScopeSpec,
++ ApprovalDecision, Approvals, ApprovalsError, Core, CoreBuilder, CoreError, CoreRuntime, Cron,
++ CronError, DomainSet, GroupMode, Harness, HostKind, JobRun, JobRunRecord, JobSchedule, JobSpec,
++ JobTarget, PendingApproval, Provider, RemoveAgent, Runtime, RuntimeBuilder, RuntimeConfig,
+ SandboxModeSpec, ScheduledJob, ServiceSet, SystemJobContext, ToolGroups, ToolScopeSpec,
- TrustedAccess, TrustedAutomationSource, Workspace,
+ TrustedAccess, TrustedAutomationSource, Workspace, DEFAULT_MAX_AGENTS,
};
#[test]