Skip to content

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

chore(openhuman-embed): add build script for runtime

Steven Enamakel1019e5a13d58
diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rs
new file mode 100644
index 0000000000..553ed7d1ca
--- /dev/null
+++ b/crates/openhuman-embed/src/runtime/build.rs
@@ -0,0 +1,340 @@
+//! [`RuntimeBuilder::build`]: the boot sequence.
+
+use std::path::Path;
+use std::sync::Arc;
+
+use openhuman_core::agent::session_store::SessionStoreProvider;
+use openhuman_core::config::Config;
+use openhuman_core::core::runtime::CoreBuilder;
+use openhuman_core::core::types::HostKind;
+
+use super::builder::ConfigSource;
+use super::presets::{default_domains, default_services};
+use super::{ApiKey, Runtime, RuntimeBuilder, RuntimeError, RUNTIME_LIVE};
+use crate::harness::workspace::ResolvedWorkspace;
+use crate::harness::{Provider, Workspace};
+use crate::Core;
+
+struct SessionStoreCleanup {
+ installed: Option<Arc<dyn SessionStoreProvider>>,
+ previous: Option<Arc<dyn SessionStoreProvider>>,
+}
+
+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());
+ }
+ }
+}
+
+impl RuntimeBuilder {
+ /// 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;
+ /// [`RuntimeError::Invalid`] for a knob the [`ConfigSource`] cannot
+ /// honour or a refused controller extension.
+ 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)
+ }
+ }
+ }
+
+ /// Refuse combinations the chosen [`ConfigSource`] cannot honour.
+ pub(super) fn validate(&self) -> Result<(), 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 self.config_source == ConfigSource::Discovered {
+ if !matches!(self.workspace, Workspace::Inherit) {
+ return Err(RuntimeError::Invalid(
+ "ConfigSource::Discovered needs Workspace::Inherit: the core discovers \
+ the operator's install"
+ .into(),
+ ));
+ }
+ let edits = [
+ ("config", self.config.is_some()),
+ ("backend_url", self.backend_url.is_some()),
+ ("workspace_dir", self.workspace_dir.is_some()),
+ ("action_dir", self.action_dir.is_some()),
+ ("api_key", self.api_key.is_some()),
+ ];
+ if let Some((knob, _)) = edits.iter().find(|(_, set)| *set) {
+ return Err(RuntimeError::Invalid(format!(
+ "`{knob}` edits the boot config, which ConfigSource::Discovered leaves \
+ to the core; use ConfigSource::Resolved"
+ )));
+ }
+ }
+ Ok(())
+ }
+
+ async fn build_inner(mut self) -> Result<Runtime, RuntimeError> {
+ self.validate()?;
+ let discovered = self.config_source == ConfigSource::Discovered;
+ let inherit = self.workspace.is_operator_owned();
+ let resolved = ResolvedWorkspace::resolve(&self.workspace, self.action_dir.as_deref())
+ .map_err(map_ws)?;
+
+ // Discovered: the core loads its own config during boot; nothing to
+ // assemble here. Resolved: `Inherit` starts from the operator's own
+ // config — loaded here rather than left to the core to discover,
+ // because the other knobs are applied *on top* of it.
+ let mut config = if discovered {
+ None
+ } else {
+ Some(self.resolve_config(&resolved).await?)
+ };
+
+ // 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 = match (self.api_key.as_ref(), config.as_ref()) {
+ (Some(key), Some(config)) => {
+ store_api_key(config, key)?;
+ true
+ }
+ _ => 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
+ .as_ref()
+ .and_then(|config| 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.clone().unwrap_or_default();
+ let services = self.services.unwrap_or_else(default_services);
+
+ if let Some(engine) = self.memory_engine.clone() {
+ openhuman_core::memory::engine::install_host_engine(engine);
+ }
+
+ // 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,
+ };
+
+ // Restorable seams are undone by this guard if the boot below fails.
+ let mut seams = std::mem::take(&mut self.seams)
+ .install()
+ .map_err(RuntimeError::Invalid)?;
+
+ log::debug!(
+ "[embed][runtime] building host_kind={host_kind:?} config_source={:?} \
+ inherit_workspace={inherit} routed_provider={} api_key={has_api_key} \
+ domains={domains:?} services={services:?} tool_groups={tool_groups:?} \
+ listen_host={:?} listen_port={:?}",
+ self.config_source,
+ self.provider.is_routed(),
+ self.listen_host,
+ self.listen_port,
+ );
+
+ let mut builder = CoreBuilder::new(host_kind)
+ .domains(domains)
+ .tool_groups(tool_groups.clone())
+ .services(services)
+ .token(std::mem::replace(
+ &mut self.token,
+ openhuman_core::core::runtime::TokenSource::EnvOrFile,
+ ));
+ if let Some(config) = config.clone() {
+ builder = builder.config(config);
+ }
+ if let Some(host) = self.listen_host.take() {
+ builder = builder.host(host);
+ }
+ if let Some(port) = self.listen_port {
+ builder = builder.port(port);
+ }
+ if let Some(transport) = self.backend_transport.take() {
+ builder = builder.backend_transport(transport);
+ }
+ let runtime = builder.build().await.map_err(|error| {
+ log::warn!("[embed][runtime] core build failed: {error:#}");
+ RuntimeError::Build(error)
+ })?;
+ let core = Core::from_runtime(Arc::new(runtime));
+
+ // Discovered: agents start from the config the core just loaded.
+ let mut base_config = match config.take() {
+ Some(config) => config,
+ None => discovered_base_config().await,
+ };
+ if discovered {
+ // Agent defaults only — the core's own config is not edited.
+ self.access.apply(&mut base_config);
+ apply_provider(&mut base_config, &self.provider);
+ }
+
+ if seams.has_pending_live_policy() {
+ seams.install_live_policy(&base_config.workspace_dir, &base_config.action_dir);
+ }
+
+ if let Some(session) = self.session.take() {
+ core.auth().store(session).await?;
+ }
+
+ let installed_session_store = session_store_cleanup.installed.take();
+ let previous_session_store = session_store_cleanup.previous.take();
+ log::debug!("[embed][runtime] built host_kind={host_kind:?}");
+
+ Ok(Runtime::new(
+ core,
+ resolved,
+ installed_session_store,
+ previous_session_store,
+ Some(seams),
+ base_config,
+ inherit,
+ domains,
+ tool_groups,
+ self.provider,
+ self.access,
+ ))
+ }
+
+ /// The config a [`ConfigSource::Resolved`] runtime hands the core.
+ async fn resolve_config(&mut self, resolved: &ResolvedWorkspace) -> Result<Config, RuntimeError> {
+ let mut config = match (&self.workspace, self.config.take()) {
+ (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
+ }
+ };
+ // Raw paths refine the resolved workspace field by field; the
+ // credential root (`config_path`) is left to the `Workspace`.
+ if let Some(dir) = self.workspace_dir.clone() {
+ create_dir(&dir, "create the workspace_dir")?;
+ log::debug!("[embed][runtime] workspace_dir override applied");
+ config.workspace_dir = dir;
+ }
+ if let Some(dir) = self.action_dir.clone() {
+ create_dir(&dir, "create the action_dir")?;
+ log::debug!("[embed][runtime] action_dir override applied");
+ config.action_dir = dir;
+ }
+ if let Some(url) = self.backend_url.clone() {
+ config.api_url = Some(url);
+ }
+ self.access.apply(&mut config);
+ apply_provider(&mut config, &self.provider);
+ Ok(config)
+ }
+}
+
+/// The base config for agents of a runtime whose core discovered its own:
+/// the same `load_or_init` the core just ran, so the two agree.
+async fn discovered_base_config() -> Config {
+ match Config::load_or_init().await {
+ Ok(config) => config,
+ Err(error) => {
+ // The core logged the same failure and skipped its workspace-bound
+ // stores; agents fall back to defaults rather than failing a host
+ // that may never create one.
+ log::warn!("[embed][runtime] discovered config failed to load: {error:#}");
+ Config::default()
+ }
+ }
+}
+
+fn store_api_key(config: &Config, key: &ApiKey) -> Result<(), RuntimeError> {
+ let state_dir = config
+ .config_path
+ .parent()
+ .map(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)
+}
+
+fn create_dir(dir: &Path, what: &'static str) -> Result<(), RuntimeError> {
+ std::fs::create_dir_all(dir).map_err(|source| RuntimeError::Workspace { what, source })
+}
+
+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());
+ }
+}