Skip to content

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

Merge main into pr/7044

Steven Enamakele558c90918c6
diff --cc crates/openhuman-core/src/agent/session_store/mod.rs
index 440895347f,0000000000..09c48b1a23
mode 100644,000000..100644
--- a/crates/openhuman-core/src/agent/session_store/mod.rs
+++ b/crates/openhuman-core/src/agent/session_store/mod.rs
@@@ -1,161 -1,0 +1,168 @@@
+//! The host-installed session store.
+//!
+//! A host that keeps conversations in its own database (a cloud deployment
+//! serving many users from one process) installs a
+//! [`SessionStoreProvider`] here once, before agents run. From then on every
+//! agent's transcripts, turn journal, run status, goals and todos go through
+//! that agent's [`AgentStores`] instead of files under `workspace_dir`. For a
+//! store that is not file-backed ([`replaces_files`]) the file-era mirrors
+//! (the session dual-write and its shadow reads) stand down: the host store
+//! is the only record.
+//!
+//! Like the memory engine's host binding
+//! ([`crate::memory::engine::install_host_engine`]), this is process-wide:
+//! OpenHuman runs one runtime per process. With nothing installed, the core
+//! keeps today's on-disk layout.
+
+use std::sync::{Arc, LazyLock, PoisonError, RwLock};
+
+pub use tinyagents_session::port::{AgentStores, SessionStoreProvider};
+
+static PROVIDER: LazyLock<RwLock<Option<Arc<dyn SessionStoreProvider>>>> =
+ LazyLock::new(|| RwLock::new(None));
+
+tokio::task_local! {
+ /// A provider for one task tree only, ahead of the process-wide one; how
+ /// tests in a shared binary use a store without touching each other.
+ static SCOPED: Arc<dyn SessionStoreProvider>;
+}
+
+/// Runs `future` with `provider` as the session store, for that task only.
+/// Tasks it spawns do not inherit it.
+pub async fn scope<F: std::future::Future>(
+ provider: Arc<dyn SessionStoreProvider>,
+ future: F,
+) -> F::Output {
+ SCOPED.scope(provider, future).await
+}
+
+/// Routes every agent's session state through `provider`, replacing any
+/// earlier one.
- pub fn install(provider: Arc<dyn SessionStoreProvider>) {
++pub fn install(provider: Arc<dyn SessionStoreProvider>) -> Option<Arc<dyn SessionStoreProvider>> {
+ tracing::info!(
+ destination = ?provider.destination_key(),
+ "[session_store] host session store installed"
+ );
- *PROVIDER.write().unwrap_or_else(PoisonError::into_inner) = Some(provider);
++ PROVIDER
++ .write()
++ .unwrap_or_else(PoisonError::into_inner)
++ .replace(provider)
+}
+
+/// Removes the installed provider; the on-disk layout applies again. Returns
+/// whether one was installed.
+pub fn clear() -> bool {
+ let had = PROVIDER
+ .write()
+ .unwrap_or_else(PoisonError::into_inner)
+ .take()
+ .is_some();
+ if had {
+ tracing::info!("[session_store] host session store removed");
+ }
+ had
+}
+
++pub fn restore(provider: Option<Arc<dyn SessionStoreProvider>>) {
++ *PROVIDER.write().unwrap_or_else(PoisonError::into_inner) = provider;
++}
++
+/// The provider in effect: the task's [`scope`]d one, else the installed
+/// one, if any.
+#[must_use]
+pub fn installed() -> Option<Arc<dyn SessionStoreProvider>> {
+ SCOPED.try_with(Arc::clone).ok().or_else(|| {
+ PROVIDER
+ .read()
+ .unwrap_or_else(PoisonError::into_inner)
+ .clone()
+ })
+}
+
+/// Whether a host session store is in effect.
+#[must_use]
+pub fn is_installed() -> bool {
+ installed().is_some()
+}
+
+/// Whether the store in effect keeps conversations somewhere other than the
+/// classic workspace files ([`SessionStoreProvider::workspace_dir`] is
+/// `None`), so companions that read those files back have nothing to read.
+#[must_use]
+pub fn replaces_files() -> bool {
+ installed().is_some_and(|provider| provider.workspace_dir().is_none())
+}
+
+/// `agent_id`'s stores from the installed provider, or `None` when the core
+/// keeps the on-disk layout.
+#[must_use]
+pub fn for_agent(agent_id: &str) -> Option<AgentStores> {
+ installed().map(|provider| provider.for_agent(agent_id))
+}
+
+/// `agent_id`'s transcripts from the store in effect, or `None` when the core
+/// keeps them as workspace files.
+#[must_use]
+pub fn transcripts_for(
+ agent_id: &str,
+) -> Option<Arc<dyn tinyagents_session::transcript::TranscriptLocator>> {
+ let stores = for_agent(agent_id)?;
+ log::debug!("[session_store] transcripts via the host store agent={agent_id}");
+ Some(stores.transcripts)
+}
+
+/// [`transcripts_for`] `agent_id`, or the transcript files under
+/// `workspace_dir` when no store is in effect — the session host's resolution.
+#[must_use]
+pub fn transcripts_or_files(
+ agent_id: &str,
+ workspace_dir: &std::path::Path,
+) -> Arc<dyn tinyagents_session::transcript::TranscriptLocator> {
+ transcripts_for(agent_id).unwrap_or_else(|| {
+ Arc::new(tinyagents_session::transcript::FileTranscriptLocator::new(
+ workspace_dir,
+ ))
+ })
+}
+
+/// The stores of the agent the current [`CoreContext`] works for — the one
+/// it was derived for ([`CoreContext::session_agent`]), else
+/// [`DEFAULT_AGENT`] — or `None` when the core keeps the on-disk layout.
+///
+/// For code that has a workspace path but no agent id of its own (goals,
+/// todos, the turn journal): under an embedded agent's context it lands in
+/// that agent's stores.
+///
+/// [`CoreContext`]: crate::core::runtime::CoreContext
+/// [`CoreContext::session_agent`]: crate::core::runtime::CoreContext::session_agent
+#[must_use]
+pub fn current() -> Option<AgentStores> {
+ let provider = installed()?;
+ let agent = crate::core::runtime::CoreContext::current()
+ .and_then(|context| context.session_agent().map(str::to_owned))
+ .unwrap_or_else(|| DEFAULT_AGENT.to_string());
+ Some(provider.for_agent(&agent))
+}
+
+/// The workspace the current [`CoreContext`](crate::core::runtime::CoreContext)
+/// is bound to, for a file-backed store that must follow it (the desktop
+/// rebinds it when a different user signs in). Before the core has booted —
+/// when no store is asked for anything — the default config's workspace.
+#[must_use]
+pub fn context_workspace_dir() -> std::path::PathBuf {
+ crate::core::runtime::CoreContext::current()
+ .and_then(|context| context.workspace_dir().ok())
+ .unwrap_or_else(|| {
+ log::warn!("[session_store] no booted context; using the default workspace");
+ crate::config::Config::default().workspace_dir
+ })
+}
+
+/// The agent whose stores a turn without a definition id uses. Root turns of
+/// the desktop app have no per-user agent; a single shared bucket keeps them
+/// together, as the shared workspace always did.
+pub const DEFAULT_AGENT: &str = "default";
+
+#[cfg(test)]
+#[path = "mod_tests.rs"]
+mod tests;
diff --cc crates/openhuman-core/src/agent/tinyagents/reaper.rs
index 82b91d91f5,4b9edaa044..91fe6a7ec4
--- a/crates/openhuman-core/src/agent/tinyagents/reaper.rs
+++ b/crates/openhuman-core/src/agent/tinyagents/reaper.rs
@@@ -18,12 -18,6 +18,12 @@@ pub(crate) async fn reap_orphaned_runs(
"[agent] startup run sweep workspace={}",
workspace.display()
);
+ // With a host session store the status records live in its stores: sweep
+ // the ones this process's own (default-agent) work wrote there.
+ if let Some(stores) = crate::agent::session_store::current() {
- let store = FileStatusStore::over(stores.kv);
++ let store = FileStatusStore::new(stores.kv);
+ return tinyagents_harness::observability::reap_orphaned_runs(&store).await;
+ }
let store = FileStatusStore::new(open_session_stores(workspace).kv);
tinyagents_harness::observability::reap_orphaned_runs(&store).await
}
diff --cc crates/openhuman-embed/src/runtime/builder.rs
index d465fe882d,b2da9c1501..69ae19c561
--- a/crates/openhuman-embed/src/runtime/builder.rs
+++ b/crates/openhuman-embed/src/runtime/builder.rs
@@@ -244,11 -222,6 +244,7 @@@ impl RuntimeBuilder
if let Some(engine) = self.memory_engine.clone() {
openhuman_core::memory::engine::install_host_engine(engine);
}
- // Before the core boots: boot-time recovery runs against it.
+ let session_store = self.session_store.is_some();
- if let Some(provider) = self.session_store.clone() {
- openhuman_core::agent::session_store::install(provider);
- }
let inherit = self.workspace.is_operator_owned();
let resolved = ResolvedWorkspace::resolve(&self.workspace, None).map_err(map_ws)?;
@@@ -315,6 -288,6 +311,13 @@@
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 previous_session_store = self
++ .session_store
++ .clone()
++ .and_then(openhuman_core::agent::session_store::install);
++
log::debug!(
"[embed][runtime] building host_kind={:?} inherit_workspace={inherit} \
routed_provider={} api_key={has_api_key} domains={domains:?} tool_groups={tool_groups:?}",
@@@ -331,15 -304,7 +334,16 @@@
if let Some(transport) = self.backend_transport {
builder = builder.backend_transport(transport);
}
- let runtime = builder.build().await.map_err(RuntimeError::Build)?;
+ let runtime = match builder.build().await {
+ Ok(runtime) => runtime,
+ Err(error) => {
+ if session_store {
+ openhuman_core::agent::session_store::clear();
++ openhuman_core::agent::session_store::restore(previous_session_store);
+ }
+ return Err(RuntimeError::Build(error));
+ }
+ };
let core = Core::from_runtime(Arc::new(runtime));
if let Some(session) = self.session {
@@@ -349,7 -314,6 +353,8 @@@
Ok(Runtime::new(
core,
resolved,
+ session_store,
++ previous_session_store,
config,
inherit,
domains,
diff --cc crates/openhuman-embed/src/runtime/mod.rs
index fec83e2cc8,f52e1a93c0..55a07a5c25
--- a/crates/openhuman-embed/src/runtime/mod.rs
+++ b/crates/openhuman-embed/src/runtime/mod.rs
@@@ -153,9 -146,6 +153,10 @@@ pub(crate) struct CoreGuard
/// Held for its `Drop`: an ephemeral workspace lives exactly as long as
/// the last owner of this guard.
workspace: ResolvedWorkspace,
+ /// Whether this runtime installed the process's session store, which is
+ /// removed with it.
+ session_store: bool,
++ previous_session_store: Option<Arc<dyn openhuman_core::agent::session_store::SessionStoreProvider>>,
}
impl Drop for CoreGuard {
@@@ -164,9 -154,6 +165,10 @@@
// first lets another builder initialize process-scoped state while
// this runtime's keyring, bearer, event bus and subscribers are live.
drop(self.core.take());
+ if self.session_store {
+ openhuman_core::agent::session_store::clear();
++ openhuman_core::agent::session_store::restore(self.previous_session_store.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 a turn returns and can recreate workspace