Skip to content

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

refactor(embed): simplify runtime builder construction

Steven Enamakel7cd2131be2fc
diff --git a/crates/openhuman-embed/src/runtime/builder.rs b/crates/openhuman-embed/src/runtime/builder.rs
index 77b506ba7f..8da190c16f 100644
--- a/crates/openhuman-embed/src/runtime/builder.rs
+++ b/crates/openhuman-embed/src/runtime/builder.rs
@@ -1,57 +1,88 @@
-//! Assembling a [`Runtime`].
+//! Assembling a [`Runtime`](super::Runtime): the builder and its knobs.
//!
//! The builder turns typed inputs into one in-memory base [`Config`] plus a
//! [`DomainSet`]/[`ServiceSet`]/[`ToolGroups`] triple, installs the API key
-//! into the credential store, and hands everything to [`CoreBuilder`].
+//! into the credential store, installs the host's process-global seams, and
+//! hands everything to [`CoreBuilder`](openhuman_core::core::runtime::CoreBuilder).
//! Nothing here mutates the process environment.
+//!
+//! The pieces live beside this file: [`presets`](super::presets) (the
+//! per-host starting points), [`seams`](super::seams) (process-global
+//! installers restored on drop), `build.rs` (the boot sequence) and `run.rs`
+//! (the CLI entry).
+use std::path::PathBuf;
use std::sync::Arc;
+use openhuman_core::agent::session_store::SessionStoreProvider;
use openhuman_core::backend::BackendTransport;
use openhuman_core::config::Config;
-use openhuman_core::core::runtime::{CoreBuilder, DomainSet, ServiceSet, TokenSource};
+use openhuman_core::core::runtime::{DomainSet, ServiceSet, TokenSource};
use openhuman_core::core::types::HostKind;
use openhuman_core::tools::toolpacks::ToolGroups;
-use openhuman_core::agent::session_store::SessionStoreProvider;
-
-use super::{ApiKey, Runtime, RuntimeError, RUNTIME_LIVE};
-use crate::harness::workspace::ResolvedWorkspace;
+use super::seams::HostSeams;
+use super::ApiKey;
use crate::harness::{Access, Provider, Workspace};
-use crate::{Core, Session};
+use crate::Session;
-struct SessionStoreCleanup {
- installed: Option<Arc<dyn SessionStoreProvider>>,
- previous: Option<Arc<dyn SessionStoreProvider>>,
-}
+// Re-exported for the sibling test module and older call sites that reached
+// the default triples through this module.
+pub(crate) use super::build::{apply_provider, effective_host_kind};
+pub(crate) use super::presets::{default_domains, default_services};
+#[cfg(test)]
+pub(crate) use super::{RuntimeError, RUNTIME_LIVE};
-impl Drop for SessionStoreCleanup {
- fn drop(&mut self) {
- let Some(installed) = self.installed.take() else {
- return;
- };
- if openhuman_core::agent::session_store::clear_if(&installed) {
- openhuman_core::agent::session_store::restore(self.previous.take());
- }
- }
+/// Who produces the [`Config`] the core boots with.
+///
+/// The choice is not cosmetic. A config the core is *handed* makes it a
+/// scoped embedder: credentials live under that config's root, the operator's
+/// `active_user.toml` is never read or written, and handlers see that exact
+/// config for the life of the process. A config the core *discovers* is the
+/// operator's install, re-read from `config.toml` and the environment, with
+/// per-user activation — what the desktop app, the CLI and the TUI run.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum ConfigSource {
+ /// The builder resolves the config — from the [`Workspace`], a supplied
+ /// [`RuntimeBuilder::config`], and the other knobs — and hands it to the
+ /// core verbatim. The library default.
+ #[default]
+ Resolved,
+ /// The core discovers its config itself, exactly as a desktop, CLI or TUI
+ /// host does. Requires [`Workspace::Inherit`]; refuses the knobs that
+ /// would edit a config (`config`, `backend_url`, `workspace_dir`,
+ /// `action_dir`, `api_key`), because there is no config in hand to edit.
+ /// [`RuntimeBuilder::access`] and [`RuntimeBuilder::provider`] then only
+ /// set the defaults of agents created with [`Runtime::agent`](super::Runtime::agent).
+ Discovered,
}
-/// Builder for a [`Runtime`]. Obtain with [`Runtime::builder`].
+/// Builder for a [`Runtime`](super::Runtime). Obtain with
+/// [`Runtime::builder`](super::Runtime::builder) or one of the host presets
+/// ([`RuntimeBuilder::library`], [`desktop`](RuntimeBuilder::desktop),
+/// [`cli`](RuntimeBuilder::cli), [`tui`](RuntimeBuilder::tui)).
pub struct RuntimeBuilder {
- workspace: Workspace,
- provider: Provider,
- access: Access,
- services: Option<ServiceSet>,
- domains: Option<DomainSet>,
- tool_groups: Option<ToolGroups>,
- host_kind: HostKind,
- config: Option<Config>,
- session: Option<Session>,
- backend_url: Option<String>,
- api_key: Option<ApiKey>,
- backend_transport: Option<Arc<dyn BackendTransport>>,
- memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,
- session_store: Option<Arc<dyn SessionStoreProvider>>,
+ pub(super) workspace: Workspace,
+ pub(super) workspace_dir: Option<PathBuf>,
+ pub(super) action_dir: Option<PathBuf>,
+ pub(super) config_source: ConfigSource,
+ pub(super) provider: Provider,
+ pub(super) access: Access,
+ pub(super) services: Option<ServiceSet>,
+ pub(super) domains: Option<DomainSet>,
+ pub(super) tool_groups: Option<ToolGroups>,
+ pub(super) host_kind: HostKind,
+ pub(super) token: TokenSource,
+ pub(super) listen_host: Option<String>,
+ pub(super) listen_port: Option<u16>,
+ pub(super) config: Option<Config>,
+ pub(super) session: Option<Session>,
+ pub(super) backend_url: Option<String>,
+ pub(super) api_key: Option<ApiKey>,
+ pub(super) backend_transport: Option<Arc<dyn BackendTransport>>,
+ pub(super) memory_engine: Option<Arc<dyn tinymemory_api::MemoryEngine>>,
+ pub(super) session_store: Option<Arc<dyn SessionStoreProvider>>,
+ pub(super) seams: HostSeams,
}
impl Default for RuntimeBuilder {
@@ -63,16 +94,23 @@ impl Default for RuntimeBuilder {
impl RuntimeBuilder {
/// A builder with safe defaults: an ephemeral workspace, the machine's
/// configured inference, the supervised access tier, no background
- /// services, and every domain a library agent can use.
+ /// services, and every domain a library agent can use. Same as
+ /// [`RuntimeBuilder::library`].
pub fn new() -> Self {
Self {
workspace: Workspace::default(),
+ workspace_dir: None,
+ action_dir: None,
+ config_source: ConfigSource::Resolved,
provider: Provider::inherit(),
access: Access::default(),
services: None,
domains: None,
tool_groups: None,
host_kind: HostKind::Library,
+ token: TokenSource::EnvOrFile,
+ listen_host: None,
+ listen_port: None,
config: None,
session: None,
backend_url: None,
@@ -80,6 +118,7 @@ impl RuntimeBuilder {
backend_transport: None,
memory_engine: None,
session_store: None,
+ seams: HostSeams::default(),
}
}
@@ -97,14 +136,15 @@ impl RuntimeBuilder {
self
}
- /// The memory engine every agent and [`Runtime::memory`] use, in place of
- /// the configured `[memory]` engine (TinyHumans over the backend
- /// credential, or CortexDB with a stored key).
+ /// The memory engine every agent and [`Runtime::memory`](super::Runtime::memory)
+ /// use, in place of the configured `[memory]` engine (TinyHumans over the
+ /// backend credential, or CortexDB with a stored key).
///
/// For a host that owns its memory store, or a test that wants
/// TinyMemory's in-memory reference engine: memory then runs without a
/// TinyHumans credential. The engine's writes are scrubbed like any
- /// other's. It is process-wide, as the runtime is.
+ /// other's. It is process-wide, as the runtime is, and the core has no
+ /// uninstall for it: it stays installed for the life of the process.
pub fn memory_engine(mut self, engine: Arc<dyn tinymemory_api::MemoryEngine>) -> Self {
self.memory_engine = Some(engine);
self
@@ -127,11 +167,49 @@ impl RuntimeBuilder {
/// Where the runtime keeps its credential store, session database and
/// every agent's memory, transcripts and skills.
+ ///
+ /// [`workspace_dir`](Self::workspace_dir) and
+ /// [`action_dir`](Self::action_dir) refine the paths this resolves to.
pub fn workspace(mut self, workspace: Workspace) -> Self {
self.workspace = workspace;
self
}
+ /// Put the core's internal state (`config.workspace_dir`: session
+ /// database, memory, attachments, every agent's `agents/<id>/` home) at
+ /// exactly `dir`, created if absent.
+ ///
+ /// Applied **after** the [`Workspace`] is resolved and only to that one
+ /// field: the credential root (`config_path`'s parent) stays where the
+ /// `Workspace` put it, so this splits state from credentials rather than
+ /// moving both. Use [`Workspace::Dir`] to move everything together.
+ /// Not available with [`ConfigSource::Discovered`].
+ pub fn workspace_dir(mut self, dir: impl Into<PathBuf>) -> Self {
+ self.workspace_dir = Some(dir.into());
+ self
+ }
+
+ /// The runtime-wide read/write root for acting tools (`config.action_dir`),
+ /// created if absent. Agents may still name their own.
+ ///
+ /// Overrides the sibling `action/` directory an ephemeral or `Dir`
+ /// workspace would otherwise create, and the operator's configured
+ /// `action_dir` under [`Workspace::Inherit`]. Keep it outside the
+ /// workspace: acting tools are refused inside it. Not available with
+ /// [`ConfigSource::Discovered`].
+ pub fn action_dir(mut self, dir: impl Into<PathBuf>) -> Self {
+ self.action_dir = Some(dir.into());
+ self
+ }
+
+ /// Who produces the boot [`Config`]; see [`ConfigSource`]. The host
+ /// presets other than [`library`](Self::library) pick
+ /// [`ConfigSource::Discovered`].
+ pub fn config_source(mut self, source: ConfigSource) -> Self {
+ self.config_source = source;
+ self
+ }
+
/// The TinyHumans API key — the runtime's only credential.
///
/// Installed into the runtime's credential store before the core boots.
@@ -169,10 +247,14 @@ impl RuntimeBuilder {
/// Override which background services run.
///
- /// The default is deliberately minimal (only the harness init step):
- /// 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.
+ /// The library default is deliberately minimal (only the harness init
+ /// step): 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.
+ ///
+ /// The runtime itself starts none of them: a transport that serves the
+ /// runtime (`openhuman-rpc`) calls `start_services` once its listener is
+ /// bound.
pub fn services(mut self, services: ServiceSet) -> Self {
self.services = Some(services);
self
@@ -181,10 +263,10 @@ impl RuntimeBuilder {
/// Override which domain families exist at runtime.
///
/// Families are registered once, at boot, so an agent can only *narrow*
- /// this set. The default is [`DomainSet::embedded`] plus `mcp` and
- /// `skills` when those features are compiled in — the runtime cannot know
- /// yet which agents will declare servers or skills, and an agent that
- /// declares none narrows them back off for itself.
+ /// this set. The library default is [`DomainSet::embedded`] plus `mcp`
+ /// and `skills` when those features are compiled in — the runtime cannot
+ /// know yet which agents will declare servers or skills, and an agent
+ /// that declares none narrows them back off for itself.
pub fn domains(mut self, domains: DomainSet) -> Self {
self.domains = Some(domains);
self
@@ -207,6 +289,39 @@ impl RuntimeBuilder {
self
}
+ /// How the per-process RPC bearer is seeded. Defaults to
+ /// [`TokenSource::EnvOrFile`]: `OPENHUMAN_CORE_TOKEN` when set, otherwise
+ /// a fresh token written to `core.token` beside the config. A host that
+ /// already holds the bearer in memory (the desktop shell) passes
+ /// [`TokenSource::Fixed`] so it never crosses the environment.
+ pub fn token(mut self, token: TokenSource) -> Self {
+ self.token = token;
+ self
+ }
+
+ /// The address a transport serving this runtime binds.
+ ///
+ /// Recorded on the core runtime only: the runtime binds nothing itself.
+ /// A piece left unset falls back, at serve time, to `OPENHUMAN_CORE_HOST`
+ /// / `OPENHUMAN_CORE_PORT` and then `127.0.0.1:7788`. See also
+ /// [`listen_host`](Self::listen_host) and [`listen_port`](Self::listen_port)
+ /// for setting one half.
+ pub fn listen(self, host: impl Into<String>, port: u16) -> Self {
+ self.listen_host(host).listen_port(port)
+ }
+
+ /// The bind host alone; see [`listen`](Self::listen).
+ pub fn listen_host(mut self, host: impl Into<String>) -> Self {
+ self.listen_host = Some(host.into());
+ self
+ }
+
+ /// The bind port alone; see [`listen`](Self::listen).
+ pub fn listen_port(mut self, port: u16) -> Self {
+ self.listen_port = Some(port);
+ self
+ }
+
/// Install an app session before the first turn.
///
/// Kept for hosts that drive authenticated backend features on behalf of
@@ -226,225 +341,6 @@ impl RuntimeBuilder {
self.config = Some(config);
self
}
-
- /// Build the core and return a runtime ready to host agents.
- ///
- /// # Errors
- ///
- /// [`RuntimeError::AlreadyRunning`] if this process already has one;
- /// [`RuntimeError::BlankApiKey`] for an empty key.
- pub async fn build(self) -> Result<Runtime, RuntimeError> {
- // Claim the process slot before doing any work, so a losing racer
- // neither creates a temp dir nor half-initializes global state.
- if RUNTIME_LIVE.swap(true, std::sync::atomic::Ordering::AcqRel) {
- return Err(RuntimeError::AlreadyRunning);
- }
- // From here on every early return must release the slot, or a failed
- // build would permanently poison the process against retrying.
- match self.build_inner().await {
- Ok(runtime) => Ok(runtime),
- Err(e) => {
- RUNTIME_LIVE.store(false, std::sync::atomic::Ordering::Release);
- Err(e)
- }
- }
- }
-
- async fn build_inner(self) -> Result<Runtime, RuntimeError> {
- if self.api_key.as_ref().is_some_and(ApiKey::is_blank) {
- return Err(RuntimeError::BlankApiKey);
- }
- if matches!(self.workspace, Workspace::Stateless) && self.session_store.is_none() {
- return Err(RuntimeError::NoSessionStore);
- }
- if let Some(engine) = self.memory_engine.clone() {
- openhuman_core::memory::engine::install_host_engine(engine);
- }
- let inherit = self.workspace.is_operator_owned();
- let resolved = ResolvedWorkspace::resolve(&self.workspace, None).map_err(map_ws)?;
-
- // `Inherit` starts from the operator's own config — loaded here rather
- // than left to `build()` to discover, because the builder's other
- // knobs (access tier, backend URL, API key) are applied *on top* of it.
- let mut config = match (&self.workspace, self.config) {
- (Workspace::Inherit, Some(config)) => config,
- (Workspace::Inherit, None) => {
- Config::load_or_init().await.map_err(RuntimeError::Build)?
- }
- (_, supplied) => {
- let mut config = supplied.unwrap_or_default();
- config.workspace_dir = resolved.workspace_dir.clone();
- config.action_dir = resolved.action_dir.clone();
- // Credential state, auth profiles and the keyring file backend
- // all resolve against this path's parent, not `workspace_dir`.
- config.config_path = resolved.config_path.clone();
- config
- }
- };
-
- if let Some(url) = self.backend_url.clone() {
- config.api_url = Some(url);
- }
- self.access.apply(&mut config);
- apply_provider(&mut config, &self.provider);
-
- // Before `CoreBuilder::build()`: the scheduler gate reads the credential
- // store exactly once, at boot, to decide whether it is signed in.
- let has_api_key = if let Some(key) = self.api_key.as_ref() {
- let state_dir = config
- .config_path
- .parent()
- .map(std::path::Path::to_path_buf)
- .unwrap_or_else(|| config.config_path.clone());
- openhuman_core::security::credentials::api_key::store_api_key_in(
- &state_dir,
- config.secrets.encrypt,
- key.expose(),
- )
- .map_err(RuntimeError::Build)?;
- true
- } else {
- false
- };
-
- // An endpoint without a model is deliberately ignored by the route
- // applicator, so host policy follows the effective behaviour: only a
- // *usable* runtime-default route exempts an inherited install from
- // its session gate. An API key is a credential in its own right.
- let routed_provider_effective = self.provider.has_usable_route()
- && config
- .default_model
- .as_deref()
- .is_some_and(|model| !model.trim().is_empty());
- let host_kind = effective_host_kind(
- self.host_kind,
- inherit,
- routed_provider_effective || has_api_key,
- );
-
- let domains = self.domains.unwrap_or_else(default_domains);
- let tool_groups = self.tool_groups.unwrap_or_default();
- let services = self.services.unwrap_or_else(default_services);
-
- // Install only after all fallible workspace/config resolution has
- // completed; core boot performs recovery against this provider.
- let installed_session_store = self.session_store.clone();
- let previous_session_store = installed_session_store
- .clone()
- .and_then(openhuman_core::agent::session_store::install);
- let mut session_store_cleanup = SessionStoreCleanup {
- installed: installed_session_store,
- previous: previous_session_store,
- };
-
- log::debug!(
- "[embed][runtime] building host_kind={:?} inherit_workspace={inherit} \
- routed_provider={} api_key={has_api_key} domains={domains:?} tool_groups={tool_groups:?}",
- host_kind,
- self.provider.is_routed(),
- );
-
- let mut builder = CoreBuilder::new(host_kind)
- .domains(domains)
- .tool_groups(tool_groups.clone())
- .services(services)
- .token(TokenSource::EnvOrFile)
- .config(config.clone());
- if let Some(transport) = self.backend_transport {
- builder = builder.backend_transport(transport);
- }
- let runtime = match builder.build().await {
- Ok(runtime) => runtime,
- Err(error) => {
- return Err(RuntimeError::Build(error));
- }
- };
- let core = Core::from_runtime(Arc::new(runtime));
-
- if let Some(session) = self.session {
- if let Err(error) = core.auth().store(session).await {
- return Err(error.into());
- }
- }
-
- let installed_session_store = session_store_cleanup.installed.take();
- let previous_session_store = session_store_cleanup.previous.take();
-
- Ok(Runtime::new(
- core,
- resolved,
- installed_session_store,
- previous_session_store,
- config,
- inherit,
- domains,
- tool_groups,
- self.provider,
- self.access,
- ))
- }
-}
-
-fn map_ws(err: crate::HarnessError) -> RuntimeError {
- match err {
- crate::HarnessError::Workspace { what, source } => RuntimeError::Workspace { what, source },
- crate::HarnessError::Invalid(msg) => RuntimeError::Invalid(msg),
- crate::HarnessError::Build(e) => RuntimeError::Build(e),
- crate::HarnessError::Call(e) => RuntimeError::Call(e),
- crate::HarnessError::AlreadyRunning => RuntimeError::AlreadyRunning,
- }
-}
-
-/// Preserve the installed application's authentication policy when the
-/// runtime borrows both its workspace and provider. `Library` means the host
-/// supplied inference (a route or an API key); it must not become a blanket
-/// way to bypass the session gate around an operator-installed provider.
-pub(crate) fn effective_host_kind(
- requested: HostKind,
- inherit_workspace: bool,
- host_supplied_credential: bool,
-) -> HostKind {
- if requested == HostKind::Library && inherit_workspace && !host_supplied_credential {
- HostKind::Cli
- } else {
- requested
- }
-}
-
-/// Apply a [`Provider`]'s model to the config.
-///
-/// Only the model: the *route* is a per-turn parameter, never a config write,
-/// because config routes persist. See the [`provider`](crate::harness::provider)
-/// module docs.
-pub(crate) fn apply_provider(config: &mut Config, provider: &Provider) {
- if let Some(model) = provider.model_id() {
- config.default_model = Some(model.to_string());
- }
-}
-
-/// Domain families a runtime registers by default: the embedded set plus
-/// whichever of `mcp` / `skills` this build compiles in, because agents can
-/// only narrow what the runtime registered.
-pub(crate) fn default_domains() -> DomainSet {
- #[allow(unused_mut)]
- let mut domains = DomainSet::embedded();
- #[cfg(feature = "mcp")]
- {
- domains.mcp = true;
- }
- #[cfg(feature = "skills")]
- {
- domains.skills = true;
- }
- domains
-}
-
-/// Background services a runtime runs by default: only `harness_init`.
-pub(crate) fn default_services() -> ServiceSet {
- ServiceSet {
- harness_init: true,
- ..ServiceSet::none()
- }
}
#[cfg(test)]