Skip to content

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

refactor(harness): delegate to runtime and agent instead of owning core directly

Steven Enamakel4008228717cd
diff --git a/crates/openhuman-embed/src/harness/mod.rs b/crates/openhuman-embed/src/harness/mod.rs
index 6ab0099479..8c45026b9c 100644
--- a/crates/openhuman-embed/src/harness/mod.rs
+++ b/crates/openhuman-embed/src/harness/mod.rs
@@ -30,25 +30,26 @@
//!
//! # What this is, relative to the rest of `embed`
//!
-//! [`Core`](crate::Core) is the typed facade over a [`CoreRuntime`] the
-//! caller already built. `Harness` is the layer above: it *builds* that runtime
-//! from typed inputs, owns the workspace's lifetime, and applies the harness's
-//! own provider and access defaults to every turn. A host that already has a
-//! `CoreRuntime` — the desktop shell, an existing embedder — wants
-//! `Core::agent()` and should skip this module entirely.
+//! `Harness` is the one-agent convenience: a [`Runtime`](crate::Runtime)
+//! plus exactly one [`Agent`](crate::Agent) named `harness`, built from one
+//! set of inputs. Every method delegates to those two — [`Harness::runtime`]
+//! and [`Harness::agent`] hand them out — so a host that outgrows one agent
+//! creates more on the same runtime rather than a second harness.
+//! [`Core`](crate::Core) is the layer below both: the typed facade over a
+//! [`CoreRuntime`] the caller built themselves.
//!
//! # Running on your own endpoint
//!
//! A harness identifies as [`HostKind::Library`](openhuman_core::core::types::HostKind::Library)
//! by default. Supplying a [`Provider`] is therefore enough for inference: the
//! library host is trusted to supply its endpoint and credentials, without an
-//! OpenHuman app login.
+//! OpenHuman app login. Managed TinyHumans inference needs the runtime's
+//! API key instead — [`RuntimeBuilder::api_key`](crate::RuntimeBuilder::api_key).
//!
//! The core can still make non-inference backend calls (integrations,
-//! telemetry, managed services). Those need their own real session when the
-//! endpoint requires one. [`HarnessBuilder::backend_url`] points them at the
-//! embedding product's backend; [`HarnessBuilder::session`] installs a backend
-//! identity when required.
+//! telemetry, managed services). [`HarnessBuilder::backend_url`] points them
+//! at the embedding product's backend; [`HarnessBuilder::session`] installs a
+//! backend identity when required.
//!
//! Neither applies to [`Provider::inherit`] with [`Workspace::Inherit`], which
//! runs exactly as the installed app does, session included.
@@ -73,23 +74,22 @@
//! .expect("tokio runtime");
//! ```
//!
-//! **One harness per process.** The keyring master key, the RPC bearer, the
+//! **One runtime per process.** The keyring master key, the RPC bearer, the
//! global event bus and the `Once`-guarded domain subscribers are all
-//! process-scoped, so two harnesses would silently share them while believing
-//! they had separate workspaces. [`HarnessBuilder::build`] returns
-//! [`HarnessError::AlreadyRunning`] rather than letting that happen.
-//! [`CoreContext::init`](openhuman_core::core::runtime::context::CoreContext::init)
-//! is the sequence that seeds that process-scoped state.
+//! process-scoped. A harness owns a runtime, so a second harness is a second
+//! runtime and [`HarnessBuilder::build`] returns
+//! [`HarnessError::AlreadyRunning`]. Agents multiplex inside one runtime; see
+//! [`Runtime`](crate::Runtime).
mod access;
mod builder;
mod error;
#[cfg(feature = "mcp")]
mod mcp;
-mod provider;
+pub(crate) mod provider;
#[cfg(feature = "skills")]
-mod skills;
-mod workspace;
+pub(crate) mod skills;
+pub(crate) mod workspace;
pub use access::Access;
pub use builder::HarnessBuilder;
@@ -100,41 +100,37 @@ pub use provider::Provider;
pub use workspace::Workspace;
use std::path::Path;
-use std::sync::atomic::AtomicBool;
-use workspace::ResolvedWorkspace;
-
-use crate::agent::{Turn, TurnOutcome};
+use crate::agent::Agent;
+use crate::runtime::Runtime;
+use crate::turn::{Turn, TurnOutcome};
use crate::Core;
-/// Guards the process-scoped core state described in the module docs.
-static HARNESS_LIVE: AtomicBool = AtomicBool::new(false);
-
-/// An embedded OpenHuman agent harness.
+/// An embedded OpenHuman agent harness: one runtime, one agent.
///
/// Build once with [`Harness::builder`], then run as many turns as you like.
-/// Dropping it releases the process slot and, for
-/// [`Workspace::Ephemeral`], removes the workspace.
+/// Dropping it tears the runtime down and, for [`Workspace::Ephemeral`],
+/// removes the workspace.
pub struct Harness {
- core: Option<Core>,
- provider: Provider,
- access: Access,
- /// Held for its `Drop`: an ephemeral workspace lives exactly as long as the
- /// harness that owns it.
- _workspace: ResolvedWorkspace,
+ /// Dropped before the runtime: the agent holds the core alive.
+ agent: Option<Agent>,
+ runtime: Option<Runtime>,
}
-/// Borrowed access to the core owned by a [`Harness`].
+/// Borrowed access to the core owned by a [`Harness`] or a [`Runtime`].
///
/// Unlike [`Core`], this facade is deliberately not cloneable and exposes
-/// neither the unconfigured agent facade nor the raw runtime: either path
-/// could start a turn without the harness's caller-supplied provider route.
-/// Share an `Arc<Harness>` when several agents need concurrent turn access.
+/// neither the orchestrator agent facade nor the raw runtime: either path
+/// could start a turn without an agent's provider route and access tier.
pub struct HarnessCore<'a> {
core: &'a Core,
}
-impl HarnessCore<'_> {
+impl<'a> HarnessCore<'a> {
+ pub(crate) fn new(core: &'a Core) -> Self {
+ Self { core }
+ }
+
pub fn config(&self) -> crate::Config<'_> {
self.core.config()
}
@@ -155,6 +151,28 @@ impl Harness {
HarnessBuilder::new()
}
+ pub(crate) fn from_parts(runtime: Runtime, agent: Agent) -> Self {
+ Self {
+ agent: Some(agent),
+ runtime: Some(runtime),
+ }
+ }
+
+ /// The runtime this harness built. Create further agents on it with
+ /// [`Runtime::agent`].
+ pub fn runtime(&self) -> &Runtime {
+ self.runtime
+ .as_ref()
+ .expect("harness runtime is present until drop")
+ }
+
+ /// The harness's own agent (id `harness`).
+ pub fn agent(&self) -> &Agent {
+ self.agent
+ .as_ref()
+ .expect("harness agent is present until drop")
+ }
+
/// Run one turn and get the reply.
///
/// Each call starts a **new** conversation. Pass the returned
@@ -168,89 +186,35 @@ impl Harness {
///
/// The harness's provider route and access origin are pre-applied; anything
/// set on the returned [`Turn`] overrides them for that turn alone.
- pub fn turn(&self, message: impl Into<String>) -> Turn<'_> {
- let mut turn = self
- .core
- .as_ref()
- .expect("harness core is present until drop")
- .agent()
- .turn(message);
- if let Some(route) = self.provider.route() {
- turn = turn.route(route.clone());
- }
- if let Some(model) = self.provider.model_id() {
- turn = turn.model(model);
- }
- if let Some(origin) = self.access.turn_origin() {
- turn = turn.origin(origin.clone());
- }
- turn
+ pub fn turn(&self, message: impl Into<String>) -> Turn {
+ self.agent().turn(message)
}
/// Safe typed access to non-turn core domains. Agent turns intentionally
/// remain on [`Harness::turn`], which always applies the harness provider
/// route and access origin.
pub fn core(&self) -> HarnessCore<'_> {
- HarnessCore {
- core: self
- .core
- .as_ref()
- .expect("harness core is present until drop"),
- }
+ self.runtime().core()
}
/// The workspace this harness is rooted at.
- ///
- /// Empty for [`Workspace::Inherit`], where the operator's own resolution
- /// decides and the harness never computes a path of its own.
pub fn workspace_dir(&self) -> &Path {
- &self._workspace.workspace_dir
+ self.runtime().workspace_dir()
}
/// The agent's read/write root for acting tools.
pub fn action_dir(&self) -> &Path {
- &self._workspace.action_dir
+ self.agent().action_dir()
}
}
impl Drop for Harness {
fn drop(&mut self) {
- // Drop the old 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.
- drop(self.core.take());
- // For an ephemeral workspace, take ownership of the temp path and
- // remove it with a short retry. The core's memory/session writers keep
- // running a moment after the harness returns from a turn and can
- // recreate workspace subdirectories while `TempDir`'s own drop-time
- // removal is racing them, leaving an empty directory behind and
- // breaking the documented "removed with its harness" guarantee. A
- // bounded retry lets those writes settle before we give up.
- if let Some(temp) = self._workspace._temp.take() {
- // `keep()` hands back the path without removing the directory so
- // we can do the retried removal ourselves.
- let root = temp.keep();
- // Require a short quiet period rather than trusting one successful
- // removal: a detached session writer can recreate the directory
- // immediately afterward. Most drops finish in ~200 ms; repeated
- // writes retain the one-second hard cap.
- let mut quiet_passes = 0;
- for _ in 0..20 {
- match std::fs::remove_dir_all(&root) {
- Ok(()) => quiet_passes += 1,
- Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
- quiet_passes += 1;
- }
- Err(_) => quiet_passes = 0,
- }
- if quiet_passes >= 5 {
- break;
- }
- std::thread::sleep(std::time::Duration::from_millis(50));
- }
- let _ = std::fs::remove_dir_all(&root);
- }
- HARNESS_LIVE.store(false, std::sync::atomic::Ordering::Release);
+ // The agent holds an `Arc` to the core; release it first so the
+ // runtime's drop can tear the core down and remove an ephemeral
+ // workspace with nothing still referencing it.
+ drop(self.agent.take());
+ drop(self.runtime.take());
log::debug!("[embed][harness] released");
}
}