The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(session_store): drop the saas refusal path from store resolution
Steven Enamakele92907667a55
diff --git a/crates/openhuman-core/src/agent/goals/store.rs b/crates/openhuman-core/src/agent/goals/store.rsindex 1ae82ca8ec..ffd2ac0fd0 100644--- a/crates/openhuman-core/src/agent/goals/store.rs+++ b/crates/openhuman-core/src/agent/goals/store.rs@@ -24,8 +24,8 @@ use tinyagents_session::transcript::import::ops::open_session_stores;/// The store thread goals live in: the current agent's host session store/// when one is installed, else the workspace's `tinyagents_store/kv`.pub(crate) fn goals_store(workspace_dir: &Path) -> Arc<dyn Store> {- if let Some(kv) = crate::agent::session_store::current_kv() {- return kv;+ if let Some(stores) = crate::agent::session_store::current() {+ return stores.kv;}Arc::new(open_session_stores(workspace_dir).kv)}diff --git a/crates/openhuman-core/src/agent/session_import/live.rs b/crates/openhuman-core/src/agent/session_import/live.rsindex 7a9262c725..de4e3cfb21 100644--- a/crates/openhuman-core/src/agent/session_import/live.rs+++ b/crates/openhuman-core/src/agent/session_import/live.rs@@ -95,9 +95,9 @@ pub fn dual_write_enabled(config_enabled: bool) -> bool {/// agent's key-value store, whatever the dual-write flag says: there are no/// files to mirror.pub async fn session_kv_store() -> Option<Arc<dyn Store>> {- if let Some(kv) = crate::agent::session_store::current_kv() {+ if let Some(stores) = crate::agent::session_store::current() {log::debug!("[session-store] registering the host session store's kv on RunContext.stores");- return Some(kv);+ return Some(stores.kv);}let cfg = match crate::config::ops::load_current_or_init().await {Ok(cfg) => cfg,diff --git a/crates/openhuman-core/src/agent/session_store/mod.rs b/crates/openhuman-core/src/agent/session_store/mod.rsindex 8f6cfc6853..fddcdafd95 100644--- a/crates/openhuman-core/src/agent/session_store/mod.rs+++ b/crates/openhuman-core/src/agent/session_store/mod.rs@@ -171,127 +171,29 @@ pub fn transcript_root(workspace_dir: &std::path::Path) -> std::path::PathBuf {/// todos, the turn journal): under an embedded agent's context it lands in/// that agent's stores.///-/// # Errors-///-/// In SaaS mode, when the context names no agent: the shared-/// [`DEFAULT_AGENT`] bucket would mix every user's records, so the call is-/// refused instead.-////// [`CoreContext`]: crate::core::runtime::CoreContext/// [`CoreContext::session_agent`]: crate::core::runtime::CoreContext::session_agent-pub fn try_current() -> Result<Option<AgentStores>, String> {- let Some(provider) = installed() else {- return Ok(None);- };- let agent = crate::core::runtime::CoreContext::current()- .and_then(|context| context.session_agent().map(str::to_owned));- let agent = current_agent_from(agent, crate::core::runtime::mode::is_saas())?;- Ok(Some(provider.for_agent(&agent)))-}--/// [`try_current`]'s agent rule with its inputs made explicit: the acting-/// agent, else [`DEFAULT_AGENT`] — except in SaaS mode, which has no shared-/// bucket and refuses.-///-/// # Errors-///-/// When `saas` and there is no `agent`.-pub fn current_agent_from(agent: Option<String>, saas: bool) -> Result<String, String> {- match agent {- Some(agent) => Ok(agent),- None if saas => Err(- "no acting agent in SaaS mode; refusing the shared default session store".to_string(),- ),- None => Ok(DEFAULT_AGENT.to_string()),- }-}--/// [`try_current`]'s key-value store for callers that have no error channel-/// (goals, todos): the store itself, or a store that refuses every operation-/// with the SaaS error, or `None` for the on-disk layout.#[must_use]-pub fn current_kv() -> Option<Arc<dyn tinyagents_harness::store::Store>> {- match try_current() {- Ok(stores) => stores.map(|stores| stores.kv),- Err(error) => {- tracing::warn!("[session_store] {error}");- Some(Arc::new(RefusedStore(error)))- }- }-}--/// A key-value store that fails every call, standing in for the shared bucket-/// a SaaS call with no acting agent must not reach.-struct RefusedStore(String);--impl RefusedStore {- fn refuse<T>(&self) -> tinyagents_harness::error::Result<T> {- Err(tinyagents_harness::error::TinyAgentsError::Storage(- self.0.clone(),- ))- }-}--#[async_trait::async_trait]-impl tinyagents_harness::store::Store for RefusedStore {- async fn get(- &self,- _namespace: &str,- _key: &str,- ) -> tinyagents_harness::error::Result<Option<serde_json::Value>> {- self.refuse()- }- async fn put(- &self,- _namespace: &str,- _key: &str,- _value: serde_json::Value,- ) -> tinyagents_harness::error::Result<()> {- self.refuse()- }- async fn delete(&self, _namespace: &str, _key: &str) -> tinyagents_harness::error::Result<()> {- self.refuse()- }- async fn list(&self, _namespace: &str) -> tinyagents_harness::error::Result<Vec<String>> {- self.refuse()- }+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.-///-/// # Errors-///-/// In SaaS mode, when the context has no workspace: the default workspace-/// would be the operator's, shared by every user.-pub fn context_workspace_dir() -> Result<std::path::PathBuf, String> {- let workspace = crate::core::runtime::CoreContext::current()- .and_then(|context| context.workspace_dir().ok());- context_workspace_from(workspace, crate::core::runtime::mode::is_saas())-}--/// [`context_workspace_dir`]'s rule with its inputs made explicit.-///-/// # Errors-///-/// When `saas` and there is no `workspace`.-pub fn context_workspace_from(- workspace: Option<std::path::PathBuf>,- saas: bool,-) -> Result<std::path::PathBuf, String> {- match workspace {- Some(workspace) => Ok(workspace),- None if saas => Err(- "no context workspace in SaaS mode; refusing the operator's default workspace"- .to_string(),- ),- None => {- tracing::warn!("[session_store] no booted context; using the default workspace");- Ok(crate::config::Config::default().workspace_dir)- }- }+#[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 ofdiff --git a/crates/openhuman-core/src/agent/session_store/mod_tests.rs b/crates/openhuman-core/src/agent/session_store/mod_tests.rsindex 3dbc3258ed..b95ab62e18 100644--- a/crates/openhuman-core/src/agent/session_store/mod_tests.rs+++ b/crates/openhuman-core/src/agent/session_store/mod_tests.rs@@ -19,9 +19,7 @@ async fn a_scoped_provider_serves_only_its_own_task() {async fn work_outside_an_agent_context_uses_the_default_agent() {let provider: Arc<dyn SessionStoreProvider> = Arc::new(InMemorySessionStores::new());let key = scope(provider.clone(), async {- try_current()- .unwrap()- .map(|stores| stores.transcripts.destination_key())+ current().map(|stores| stores.transcripts.destination_key())}).await;// No agent context in a unit test: the shared default bucket.@@ -34,7 +32,7 @@ async fn work_outside_an_agent_context_uses_the_default_agent() {.destination_key()));- assert!(try_current().unwrap().is_none() || is_installed());+ assert!(current().is_none() || is_installed());}#[tokio::test]@@ -73,37 +71,3 @@ async fn without_a_store_transcripts_are_workspace_files() {.await;assert_eq!(found, expected);}--#[test]-fn saas_refuses_the_shared_default_agent_and_single_user_keeps_it() {- assert_eq!(- current_agent_from(Some("u1".into()), true).as_deref(),- Ok("u1")- );- assert!(current_agent_from(None, true).is_err());- assert_eq!(- current_agent_from(None, false).as_deref(),- Ok(DEFAULT_AGENT)- );-}--#[test]-fn saas_refuses_the_operators_default_workspace() {- let dir = std::path::PathBuf::from("/tmp/ws");- assert_eq!(- context_workspace_from(Some(dir.clone()), true),- Ok(dir.clone())- );- assert!(context_workspace_from(None, true).is_err());- assert!(context_workspace_from(None, false).is_ok());-}--#[tokio::test]-async fn a_refused_kv_fails_every_operation() {- use tinyagents_harness::store::Store;- let store = RefusedStore("nope".into());- assert!(store.get("ns", "k").await.is_err());- assert!(store.put("ns", "k", serde_json::json!(1)).await.is_err());- assert!(store.delete("ns", "k").await.is_err());- assert!(store.list("ns").await.is_err());-}diff --git a/crates/openhuman-core/src/agent/tinyagents/journal.rs b/crates/openhuman-core/src/agent/tinyagents/journal.rsindex ef137e8730..3e719fa573 100644--- a/crates/openhuman-core/src/agent/tinyagents/journal.rs+++ b/crates/openhuman-core/src/agent/tinyagents/journal.rs@@ -104,12 +104,10 @@ async fn resolve_workspace() -> anyhow::Result<PathBuf> {/// The journal and key-value stores a turn's events and status go to: the/// current agent's host session store when one is installed-/// ([`crate::agent::session_store::try_current`]), else the workspace's+/// ([`crate::agent::session_store::current`]), else the workspace's/// `tinyagents_store/`.async fn journal_stores() -> anyhow::Result<(Arc<dyn AppendStore>, Arc<dyn Store>)> {- if let Some(stores) =- crate::agent::session_store::try_current().map_err(|e| anyhow::anyhow!(e))?- {+ if let Some(stores) = crate::agent::session_store::current() {log::debug!("[journal] using the host session store");return Ok((stores.journal, stores.kv));}diff --git a/crates/openhuman-core/src/agent/tinyagents/reaper.rs b/crates/openhuman-core/src/agent/tinyagents/reaper.rsindex 0a57e31aca..5b66fbb538 100644--- a/crates/openhuman-core/src/agent/tinyagents/reaper.rs+++ b/crates/openhuman-core/src/agent/tinyagents/reaper.rs@@ -40,16 +40,9 @@ async fn reap_unless_shared(workspace: &Path, shared: bool) -> usize {);// With a host session store the status records live in its stores: sweep// the ones this process's own (default-agent) work wrote there.- match crate::agent::session_store::try_current() {- Ok(Some(stores)) => {- let store = FileStatusStore::over(stores.kv);- return tinyagents_harness::observability::reap_orphaned_runs(&store).await;- }- Ok(None) => {}- Err(error) => {- log::warn!("[agent] startup run sweep skipped: {error}");- return 0;- }+ if let Some(stores) = crate::agent::session_store::current() {+ let store = FileStatusStore::over(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).awaitdiff --git a/crates/openhuman-core/src/agent/tinyagents/todos.rs b/crates/openhuman-core/src/agent/tinyagents/todos.rsindex cf8dc0336c..f3fd21b156 100644--- a/crates/openhuman-core/src/agent/tinyagents/todos.rs+++ b/crates/openhuman-core/src/agent/tinyagents/todos.rs@@ -23,8 +23,8 @@ use tinyagents_session::transcript::import::ops::open_session_stores;/// With a host session store installed, the current agent's key-value store/// instead.pub fn session_todos_store(workspace_dir: &Path) -> Arc<dyn Store> {- if let Some(kv) = crate::agent::session_store::current_kv() {- return kv;+ if let Some(stores) = crate::agent::session_store::current() {+ return stores.kv;}Arc::new(open_session_stores(workspace_dir).kv)}diff --git a/crates/openhuman-rpc/src/server/shims.rs b/crates/openhuman-rpc/src/server/shims.rsindex f07fe5515f..da1a6c093e 100644--- a/crates/openhuman-rpc/src/server/shims.rs+++ b/crates/openhuman-rpc/src/server/shims.rs@@ -61,21 +61,16 @@ pub async fn run_server_headless(host: Option<&str>, port: Option<u16>) -> anyho/// Runs a SaaS core: many users behind a trusted gateway, booted from the/// operator's config file and refused unless its boot guard passes.///-/// The session store is installed before boot through the same host path the-/// other servers use ([`crate::session_store::install_for_host`]). With a-/// storage URL (`OPENHUMAN_STORAGE_URL` / `[storage] url`) every user agent's-/// records live in that backend under the agent's own scope; without one the-/// on-disk store resolves the workspace of the context each call runs under, so-/// every user agent keeps its sessions, transcripts and turn states in its own-/// workspace. A call with no acting agent (the operator plane) is refused by-/// the storage domains instead of reaching a shared scope.+/// The on-disk session store is installed before boot. It resolves the+/// workspace of the context each call runs under, so every user agent keeps+/// its sessions, transcripts and turn states in its own workspace.pub async fn run_server_saas(host: Option<&str>,port: Option<u16>,saas_config: &std::path::Path,) -> anyhow::Result<()> {let config = crate::core_host::core::runtime::SaasConfig::load(saas_config)?;- crate::session_store::install_for_host().await?;+ crate::session_store::install();let runtime =crate::core_host::core::runtime::saas::build(config, host.map(str::to_owned), port).await?;super::serve::serve(&runtime, None, None).awaitdiff --git a/crates/openhuman-rpc/src/session_store/mod.rs b/crates/openhuman-rpc/src/session_store/mod.rsindex 23de5fc49d..637aa51519 100644--- a/crates/openhuman-rpc/src/session_store/mod.rs+++ b/crates/openhuman-rpc/src/session_store/mod.rs@@ -45,11 +45,7 @@ use tinyagents_session::transcript::FileTranscriptLocator;use tinyagents_session::turn_state::TurnStateStore;/// Resolves the workspace the stores live in, at the moment they are needed.-type WorkspaceResolver = dyn Fn() -> Result<PathBuf, String> + Send + Sync;--/// Where a refused workspace resolves: a path under a file, which nothing can-/// create or open.-pub const REFUSED_WORKSPACE: &str = "/dev/null/openhuman-refused-workspace";+type WorkspaceResolver = dyn Fn() -> PathBuf + Send + Sync;/// OpenHuman's on-disk session layout as a session store provider.#[derive(Clone)]@@ -60,7 +56,7 @@ pub struct SqliteSessionStores {impl std::fmt::Debug for SqliteSessionStores {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("SqliteSessionStores")- .field("workspace", &(self.workspace)().ok())+ .field("workspace", &(self.workspace)()).finish()}}@@ -72,29 +68,16 @@ impl SqliteSessionStores {Self::resolving(move || workspace.clone())}- /// Like [`resolving`](Self::resolving), for a resolver that can refuse- /// (a SaaS call with no workspace). A refused call is logged and served- /// from [`REFUSED_WORKSPACE`], which no store can open, so it fails- /// instead of reaching another tenant's files.- pub fn try_resolving(- resolve: impl Fn() -> Result<PathBuf, String> + Send + Sync + 'static,- ) -> Self {- Self {- workspace: Arc::new(resolve),- }- }-/// Stores under whichever workspace `resolve` names when asked — for a/// host whose workspace can change while it runs.pub fn resolving(resolve: impl Fn() -> PathBuf + Send + Sync + 'static) -> Self {- Self::try_resolving(move || Ok(resolve()))+ Self {+ workspace: Arc::new(resolve),+ }}fn current(&self) -> PathBuf {- (self.workspace)().unwrap_or_else(|error| {- log::error!("[rpc:session_store] workspace refused: {error}");- PathBuf::from(REFUSED_WORKSPACE)- })+ (self.workspace)()}}@@ -160,7 +143,7 @@ pub fn install() {/// [`crate::host::tui`] wires). [`install`] installs the same provider/// process-wide instead.pub fn provider() -> Arc<dyn SessionStoreProvider> {- Arc::new(SqliteSessionStores::try_resolving(+ Arc::new(SqliteSessionStores::resolving(crate::core_host::agent::session_store::context_workspace_dir,))}diff --git a/tests/saas_mode_e2e.rs b/tests/saas_mode_e2e.rsindex 0a78945e03..6271310b50 100644--- a/tests/saas_mode_e2e.rs+++ b/tests/saas_mode_e2e.rs@@ -171,17 +171,8 @@ fn rpc_with(/// Start a SaaS core on deployment `d` and wait until it is healthy.fn start(d: &Deployment) -> (Server, String, reqwest::blocking::Client) {- start_with_env(d, &[])-}--/// [`start`] with extra environment for the child.-fn start_with_env(- d: &Deployment,- env: &[(&str, &str)],-) -> (Server, String, reqwest::blocking::Client) {let port = free_port();let child = core_command(d, &["--port", &port.to_string()])- .envs(env.iter().copied()).stdout(Stdio::null()).stderr(Stdio::null()).spawn()@@ -437,6 +428,24 @@ fn gateway_requests_run_under_the_named_users_agent() {assert_eq!(status, 401, "alice's signature does not cover bob: {body}");let (status, body) = user_rpc(&client, &base, BEARER, "bob", None, "core.ping");assert_eq!(status, 403, "bob is not provisioned: {body}");+ // A repeated signature header is refused, not resolved to the first value.+ {+ use openhuman_core::user_agents::gateway::{sign, USER_HEADER, USER_SIG_HEADER};+ let response = client+ .post(format!("{base}/rpc"))+ .bearer_auth(BEARER)+ .header(USER_HEADER, "alice")+ .header(USER_SIG_HEADER, sign(BEARER, "alice", now()))+ .header(USER_SIG_HEADER, sign(BEARER, "alice", now()))+ .json(&json!({ "jsonrpc": "2.0", "id": 1, "method": "core.ping", "params": {} }))+ .send()+ .expect("POST /rpc");+ assert_eq!(+ response.status().as_u16(),+ 400,+ "a repeated signature header"+ );+ }// Single-user surfaces are closed.for path in ["/events", "/events/domain", "/v1/models", "/dev/connect"] {@@ -902,44 +911,3 @@ fn a_duplicate_or_unreadable_user_header_is_refused() {assert_eq!(status, 400);drop(server);}--#[test]-fn a_configured_storage_url_that_cannot_be_opened_refuses_the_saas_boot() {- let d = deployment(true);- let output = core_command(&d, &["--port", &free_port().to_string()])- .env("OPENHUMAN_STORAGE_URL", "nonsense://nowhere")- .output()- .expect("run openhuman-core");- assert!(- !output.status.success(),- "a SaaS core must not ignore a storage url it cannot open"- );- let stderr = String::from_utf8_lossy(&output.stderr);- assert!(stderr.contains("storage"), "{stderr}");-}--#[test]-fn a_saas_core_boots_on_a_storage_backend_and_users_reach_it_by_agent() {- let d = deployment(true);- let (server, base, client) = start_with_env(&d, &[("OPENHUMAN_STORAGE_URL", "memory")]);- let call = |user: &str, method: &str, params: Value| {- user_rpc_with(&client, &base, BEARER, user, None, method, params)- };- provision(&client, &base, "alice");- provision(&client, &base, "bob");-- // The operator plane keeps working beside the backend.- let (status, body) = rpc(&client, &base, Some(BEARER), "core.ping");- assert_eq!(status, 200, "{body}");-- // Each user's goal and todos read from their own agent scope of the- // backend (the operator has no agent, so it would be refused instead).- for user in ["alice", "bob"] {- for method in ["openhuman.threads_goal_get", "openhuman.threads_todos_get"] {- let (status, body) = call(user, method, json!({ "thread_id": "t1" }));- assert_eq!(status, 200, "{user} {method}: {body}");- assert!(body.get("error").is_none(), "{user} {method}: {body}");- }- }- drop(server);-}