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
feat(storage): route session stores through tenant scopes
Steven Enamakel96ba3d99b015
diff --git a/Cargo.lock b/Cargo.lockindex d6b8acfd98..7490d410ad 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -266,7 +266,7 @@ version = "1.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -277,7 +277,7 @@ checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"dependencies = ["anstyle","once_cell_polyfill",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -1060,7 +1060,7 @@ dependencies = ["cap-primitives","cap-std","io-lifetimes 3.0.1",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -1077,7 +1077,7 @@ dependencies = ["maybe-owned","rustix 1.1.5","rustix-linux-procfs",- "windows-sys 0.60.2",+ "windows-sys 0.61.2","winx",]@@ -2218,7 +2218,7 @@ dependencies = ["libc","option-ext","redox_users 0.5.2",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -2494,7 +2494,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -3567,7 +3567,7 @@ dependencies = ["js-sys","log","wasm-bindgen",- "windows-core 0.58.0",+ "windows-core 0.62.2",][[package]]@@ -4841,7 +4841,7 @@ version = "0.50.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"dependencies = [- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -5447,7 +5447,7 @@ dependencies = ["tinyagents-runtime","tinyagents-session","tinyagents-tasks",- "tinybox-bus",+ "tinybox-bus 0.1.36","tinybox-core","tinybus","tinybus-module",@@ -6511,7 +6511,7 @@ dependencies = ["once_cell","socket2","tracing",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -7146,7 +7146,7 @@ dependencies = ["errno","libc","linux-raw-sys 0.12.1",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -7215,7 +7215,7 @@ dependencies = ["security-framework 3.7.0","security-framework-sys","webpki-root-certs",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -7860,7 +7860,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"dependencies = ["libc",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -8207,10 +8207,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.3.4",+ "getrandom 0.4.3","once_cell","rustix 1.1.5",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -8223,7 +8223,7 @@ dependencies = ["parking_lot","rustix 1.1.5","signal-hook",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]@@ -8430,7 +8430,6 @@ dependencies = ["futures","serde","serde_json",- "sha2 0.11.0","tinyagents-harness","tinyagents-tasks","tinyinference-llm 0.4.1",@@ -8589,24 +8588,32 @@ dependencies = [[[package]]name = "tinybox-bus"-version = "0.1.35"+version = "0.1.36"+dependencies = [+ "serde",+]++[[package]]+name = "tinybox-bus"+version = "0.1.36"+source = "git+https://github.com/tinyhumansai/tinybox?tag=v0.1.36#39fe22189431bdf787dafce5eea6d7d49d1a00f8"dependencies = ["serde",][[package]]name = "tinybox-core"-version = "0.1.35"+version = "0.1.36"dependencies = ["async-trait","serde","thiserror 2.0.20",- "tinybox-bus",+ "tinybox-bus 0.1.36",][[package]]name = "tinybox-docker"-version = "0.1.35"+version = "0.1.36"dependencies = ["async-trait","serde_json",@@ -8617,9 +8624,10 @@ dependencies = [[[package]]name = "tinybox-drivers"-version = "0.1.35"+version = "0.1.36"dependencies = ["log",+ "serde","serde_json","tinybox-core","tinybox-jail",@@ -8628,13 +8636,13 @@ dependencies = [[[package]]name = "tinybox-host"-version = "0.1.35"+version = "0.1.36"dependencies = ["async-trait","cap-std","command-group","nix 0.30.1",- "tinybox-bus",+ "tinybox-bus 0.1.36","tinybox-core","tinybox-jail","tokio",@@ -8642,20 +8650,20 @@ dependencies = [[[package]]name = "tinybox-jail"-version = "0.1.35"+version = "0.1.36"dependencies = ["landlock","log","serde","serde_json",- "tinybox-bus",+ "tinybox-bus 0.1.36","tinybox-core","windows-sys 0.61.2",][[package]]name = "tinybox-linux"-version = "0.1.35"+version = "0.1.36"dependencies = ["async-trait","tinybox-core",@@ -8663,7 +8671,7 @@ dependencies = [[[package]]name = "tinybox-microvm"-version = "0.1.35"+version = "0.1.36"dependencies = ["async-trait","serde",@@ -8673,11 +8681,12 @@ dependencies = [[[package]]name = "tinybox-module"-version = "0.1.35"+version = "0.1.36"dependencies = ["log",+ "nix 0.30.1","tempfile",- "tinybox-bus",+ "tinybox-bus 0.1.36","tinybox-core","tinybox-docker","tinybox-drivers",@@ -8696,7 +8705,7 @@ dependencies = [[[package]]name = "tinybox-ssh"-version = "0.1.35"+version = "0.1.36"dependencies = ["async-trait","tinybox-core",@@ -9501,7 +9510,7 @@ dependencies = [[[package]]name = "tinymcp"-version = "0.18.6"+version = "0.18.7"dependencies = ["base64 0.23.1","dirs 7.0.0",@@ -9512,6 +9521,7 @@ dependencies = ["serde_json","sha2 0.11.0","thiserror 2.0.20",+ "tinybox-bus 0.1.36 (git+https://github.com/tinyhumansai/tinybox?tag=v0.1.36)","tinybus","tinybus-module","tinymcp-bus",@@ -9530,7 +9540,7 @@ dependencies = [[[package]]name = "tinymcp-bus"-version = "0.18.6"+version = "0.18.7"dependencies = ["base64 0.23.1","schemars",@@ -9653,6 +9663,7 @@ name = "tinyskills-drivers"version = "0.5.1"dependencies = ["cap-std",+ "serde","serde_json","thiserror 2.0.20","tinyskills",@@ -9662,7 +9673,7 @@ dependencies = [[[package]]name = "tinystoragedrivers"-version = "0.11.0"+version = "1.0.0"dependencies = ["tinystoragedrivers-core","tinystoragedrivers-file",@@ -9674,7 +9685,7 @@ dependencies = [[[package]]name = "tinystoragedrivers-bus"-version = "0.11.0"+version = "1.0.0"dependencies = ["serde","serde_json",@@ -9683,7 +9694,7 @@ dependencies = [[[package]]name = "tinystoragedrivers-busproxy"-version = "0.11.0"+version = "1.0.0"dependencies = ["async-trait","serde",@@ -9697,7 +9708,7 @@ dependencies = [[[package]]name = "tinystoragedrivers-client"-version = "0.11.0"+version = "1.0.0"dependencies = ["async-trait","serde",@@ -9710,18 +9721,22 @@ dependencies = [[[package]]name = "tinystoragedrivers-core"-version = "0.11.0"+version = "1.0.0"dependencies = ["async-trait",+ "data-encoding","serde","serde_json",+ "sha2 0.10.9","thiserror 2.0.20","tokio",+ "ulid",+ "zstd 0.13.3",][[package]]name = "tinystoragedrivers-file"-version = "0.11.0"+version = "1.0.0"dependencies = ["async-trait","libc",@@ -9733,7 +9748,7 @@ dependencies = [[[package]]name = "tinystoragedrivers-mongodb"-version = "0.11.0"+version = "1.0.0"dependencies = ["async-trait","futures-util",@@ -9747,7 +9762,7 @@ dependencies = [[[package]]name = "tinystoragedrivers-s3"-version = "0.11.0"+version = "1.0.0"dependencies = ["bytes","futures-util",@@ -9761,7 +9776,7 @@ dependencies = [[[package]]name = "tinystoragedrivers-secrets"-version = "0.11.0"+version = "1.0.0"dependencies = ["async-trait","atomicwrites",@@ -9784,12 +9799,14 @@ dependencies = [[[package]]name = "tinystoragedrivers-sqlite"-version = "0.11.0"+version = "1.0.0"dependencies = ["rusqlite","serde_json",+ "sha2 0.10.9","tinystoragedrivers-core","tokio",+ "zstd 0.13.3",][[package]]@@ -10514,6 +10531,16 @@ version = "0.1.7"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2896d95c02a80c6d6a5d6e953d479f5ddf2dfdb6a244441010e373ac0fb88971"+[[package]]+name = "ulid"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "470dbf6591da1b39d43c14523b2b469c86879a53e8b758c8e090a470fe7b1fbe"+dependencies = [+ "rand 0.9.5",+ "web-time",+]+[[package]]name = "uname"version = "0.1.1"@@ -11310,7 +11337,7 @@ version = "0.1.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"dependencies = [- "windows-sys 0.48.0",+ "windows-sys 0.61.2",][[package]]@@ -12082,7 +12109,7 @@ dependencies = ["pbkdf2 0.11.0","sha1 0.10.7","time",- "zstd",+ "zstd 0.11.2+zstd.1.5.2",][[package]]@@ -12146,7 +12173,16 @@ version = "0.11.2+zstd.1.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4"dependencies = [- "zstd-safe",+ "zstd-safe 5.0.2+zstd.1.5.2",+]++[[package]]+name = "zstd"+version = "0.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"+dependencies = [+ "zstd-safe 7.3.0",][[package]]@@ -12159,6 +12195,15 @@ dependencies = ["zstd-sys",]+[[package]]+name = "zstd-safe"+version = "7.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "64d80649ab6db9d9f6f9c80a40becd948eda4714a0a5ac8c4d157a32231c7882"+dependencies = [+ "zstd-sys",+]+[[package]]name = "zstd-sys"version = "2.1.1+zstd.1.5.7"diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex 9faf6e1148..d8c1a64df5 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -352,7 +352,7 @@ serde = { version = "1", features = ["derive"] }tempfile = "3"tinyinference-llm = { path = "../../vendor/tinyagents/vendor/tinyinference/crates/tinyinference-llm" }# The document-port contract for failure injection in cron storage regressions.-tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v0.11.0" }+tinystoragedrivers-core = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0" }tinytools = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools" }tinytools-std = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-std" }# The completion log a detached sub-agent leaves, for the SaaS delivery-recovery e2e.diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex a4256f45f8..218bd7fd0c 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -162,15 +162,15 @@ tinyagents-registry = { path = "../../vendor/tinyagents/crates/tinyagents-registtinyagents-session = { path = "../../vendor/tinyagents/crates/tinyagents-session", features = ["storage-drivers"] }# The storage ports and the URL-to-backend facade (`storage` domain). No driver# by default: the `storage-*` features below add them.-tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v0.11.0", default-features = false, features = ["blocking", "secrets", "file", "sqlite"] }+tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, features = ["blocking", "secrets", "file", "sqlite"] }# The storage bus: the wire contract and the reference host server that the# `modules::storage_host` interface answers loaded modules with. Modules only.-tinystoragedrivers-bus = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v0.11.0", optional = true }-tinystoragedrivers-client = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v0.11.0", optional = true }+tinystoragedrivers-bus = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", optional = true }+tinystoragedrivers-client = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", optional = true }# The host half of the storage bus transport: registers the four `Storage`# objects and binds blob streams and watch signals to the calling peer# (`Connection::accept_stream_from` / `emit_to`).-tinystoragedrivers-busproxy = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v0.11.0", optional = true }+tinystoragedrivers-busproxy = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", optional = true }# The module-side export macro, used only to wrap the host's own storage server# as a *linked* module (`modules/storage_host_linked.rs`): a linked module is the# one in-process recipient the bus attests, so it is how `Secrets` can be served.diff --git a/crates/openhuman-core/src/agent/orchestration/delegation.rs b/crates/openhuman-core/src/agent/orchestration/delegation.rsindex e463323e16..391d4d72d2 100644--- a/crates/openhuman-core/src/agent/orchestration/delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/delegation.rs@@ -293,9 +293,9 @@ pub fn open_delegation_checkpointer(.and_then(|opened| opened.scoped()).map_err(|e| format!("open the storage for graph checkpoints: {e:#}"))?;Ok(Arc::new(- tinyagents_graph::checkpoint::DriverCheckpointer::<DelegationState>::with_prefix(+ tinyagents_graph::checkpoint::DriverCheckpointer::<DelegationState>::with_namespace(Arc::clone(scoped.documents()),- "delegation_graph",+ "delegation",),))}diff --git a/crates/openhuman-core/src/agent/session_store/mod.rs b/crates/openhuman-core/src/agent/session_store/mod.rsindex cc16251790..bc1f737e21 100644--- a/crates/openhuman-core/src/agent/session_store/mod.rs+++ b/crates/openhuman-core/src/agent/session_store/mod.rs@@ -21,10 +21,13 @@ use tinyagents_session::port::{AgentStores, SessionStoreProvider};pub mod ledger_sync;mod rebound;+mod tenant_router;mod workspace;pub use rebound::{rebind_all, ReboundSessionStores, StoreRegistry};+pub use tenant_router::TenantSessionStores;pub use workspace::{+ session_scope,artifact_blobs_for, attachment_stash_for, current_documents_for, default_turn_states_for,ledger_for, provider_for_workspace, release_workspace, release_workspace_defaults,require_ledger, status_store_for, stores_for, stores_or_ephemeral, turn_states_for,diff --git a/crates/openhuman-core/src/agent/session_store/rebound.rs b/crates/openhuman-core/src/agent/session_store/rebound.rsindex 30b77019bf..4070c8cecc 100644--- a/crates/openhuman-core/src/agent/session_store/rebound.rs+++ b/crates/openhuman-core/src/agent/session_store/rebound.rs@@ -5,7 +5,7 @@//! different user signs in. The session store is installed once, process-wide//! (a detached turn still writing across a rebind must keep landing in a//! store, not in a no-provider fallback), so it cannot be replaced by a new-//! provider object; it forwards to a [`DriverSessionStores`] that+//! provider object; it forwards to a [`TenantSessionStores`] that//! [`rebind_all`] points at the new workspace's backend.//!//! Handles already handed out keep the backend they were opened on, so a turn@@ -14,7 +14,7 @@use std::sync::{Arc, LazyLock, Mutex, PoisonError, RwLock, Weak};use tinyagents_session::port::{AgentStores, SessionStoreProvider};-use tinyagents_session::DriverSessionStores;+use super::tenant_router::TenantSessionStores;use tinystoragedrivers::{Blocking, StorageBackend, StorageError};/// The live [`ReboundSessionStores`] of one owner, so a rebind reaches the one@@ -63,9 +63,9 @@ impl StoreRegistry {/// The process's registry, the one [`ReboundSessionStores::new`] joins.static PROCESS: LazyLock<StoreRegistry> = LazyLock::new(StoreRegistry::default);-/// [`DriverSessionStores`] over a backend [`rebind_all`] can replace.+/// [`TenantSessionStores`] over a backend [`rebind_all`] can replace.pub struct ReboundSessionStores {- inner: RwLock<Arc<DriverSessionStores>>,+ inner: RwLock<Arc<TenantSessionStores>>,bridge: Blocking,recover_on_open: bool,}@@ -80,7 +80,7 @@ impl std::fmt::Debug for ReboundSessionStores {impl ReboundSessionStores {/// Session stores over `backend`; `recover_on_open` is- /// [`DriverSessionStores::recover_on_open`].+ /// the provider's `recover_on_open`.////// # Errors///@@ -104,8 +104,7 @@ impl ReboundSessionStores {recover_on_open: bool,) -> Result<Arc<Self>, StorageError> {let bridge = Blocking::new()?;- let inner = DriverSessionStores::with_bridge(backend, bridge.clone())- .recover_on_open(recover_on_open);+ let inner = TenantSessionStores::with_bridge(backend, bridge.clone(), recover_on_open);let this = Arc::new(Self {inner: RwLock::new(Arc::new(inner)),bridge,@@ -115,14 +114,14 @@ impl ReboundSessionStores {Ok(this)}- fn current(&self) -> Arc<DriverSessionStores> {+ fn current(&self) -> Arc<TenantSessionStores> {Arc::clone(&self.inner.read().unwrap_or_else(PoisonError::into_inner))}/// Points the store at `backend`: agents opened from now on live there.pub fn rebind(&self, backend: Arc<dyn StorageBackend>) {- let next = DriverSessionStores::with_bridge(backend, self.bridge.clone())- .recover_on_open(self.recover_on_open);+ let next =+ TenantSessionStores::with_bridge(backend, self.bridge.clone(), self.recover_on_open);*self.inner.write().unwrap_or_else(PoisonError::into_inner) = Arc::new(next);tracing::info!(target: "openhuman::storage",diff --git a/crates/openhuman-core/src/agent/session_store/tenant_router.rs b/crates/openhuman-core/src/agent/session_store/tenant_router.rsnew file mode 100644index 0000000000..19663a2908--- /dev/null+++ b/crates/openhuman-core/src/agent/session_store/tenant_router.rs@@ -0,0 +1,180 @@+//! [`TenantSessionStores`]: one [`DriverSessionStores`] per tenant.+//!+//! TinyAgents' `DriverSessionStores` serves one tenant and derives+//! `tenant.agent(id)` itself. The host keeps its flat session keys+//! ([`crate::core::runtime::session_key`]: the agent id for the desktop+//! operator, `<profile>~<agent>` for a SaaS profile), so this provider decodes+//! the key into `(profile, agent)` and forwards to the provider of that+//! tenant (`Scope::local()` or `Scope::tenant(profile)`), created on first+//! use. Every scope a session writes is therefore `local/agent:<id>` or+//! `u:<profile>/agent:<id>`, inside the tenant fence.++use std::collections::HashMap;+use std::sync::{Arc, Mutex, PoisonError};++use tinyagents_harness::store::SchemaAdmission;+use tinyagents_session::port::{AgentStores, SessionStoreProvider};+use tinyagents_session::DriverSessionStores;+use tinystoragedrivers::{Blocking, Scope, StorageBackend, StorageError};++/// Session stores over one backend, routed to a per-tenant provider.+pub struct TenantSessionStores {+ backend: Arc<dyn StorageBackend>,+ bridge: Blocking,+ recover_on_open: bool,+ admission: SchemaAdmission,+ tenants: Mutex<HashMap<Scope, Arc<DriverSessionStores>>>,+}++impl std::fmt::Debug for TenantSessionStores {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ let tenants = self.tenants.lock().unwrap_or_else(PoisonError::into_inner);+ f.debug_struct("TenantSessionStores")+ .field("driver", &self.backend.driver())+ .field("tenants", &tenants.len())+ .finish_non_exhaustive()+ }+}++impl TenantSessionStores {+ /// Stores over `backend` on a shared `bridge`.+ pub fn with_bridge(+ backend: Arc<dyn StorageBackend>,+ bridge: Blocking,+ recover_on_open: bool,+ ) -> Self {+ Self::with_admission(backend, bridge, recover_on_open, SchemaAdmission::Declare)+ }++ fn with_admission(+ backend: Arc<dyn StorageBackend>,+ bridge: Blocking,+ recover_on_open: bool,+ admission: SchemaAdmission,+ ) -> Self {+ Self {+ backend,+ bridge,+ recover_on_open,+ admission,+ tenants: Mutex::new(HashMap::new()),+ }+ }++ /// Stores over `backend` with a bridge of their own.+ ///+ /// # Errors+ ///+ /// When the blocking bridge cannot start.+ pub fn new(+ backend: Arc<dyn StorageBackend>,+ recover_on_open: bool,+ ) -> Result<Self, StorageError> {+ Ok(Self::with_bridge(backend, Blocking::new()?, recover_on_open))+ }++ /// The provider of the tenant `key` belongs to, and the agent id within it.+ fn route(&self, key: &str) -> (Arc<DriverSessionStores>, String) {+ let (profile, mut agent) = crate::core::runtime::split_session_key(key);+ if agent.is_empty() {+ agent = crate::storage::scope::DEFAULT_AGENT.to_owned();+ }+ let tenant = crate::storage::tenant_scope(profile.as_deref());+ let mut tenants = self.tenants.lock().unwrap_or_else(PoisonError::into_inner);+ if let Some(provider) = tenants.get(&tenant) {+ return (Arc::clone(provider), agent);+ }+ let provider = Arc::new(+ DriverSessionStores::with_bridge_and_schema_admission(+ Arc::clone(&self.backend),+ tenant.clone(),+ self.bridge.clone(),+ self.admission,+ )+ .recover_on_open(self.recover_on_open),+ );+ tracing::debug!(+ target: "openhuman::storage",+ tenant = tenant.as_str(),+ "[session_store] opened the tenant's session provider"+ );+ tenants.insert(tenant, Arc::clone(&provider));+ (provider, agent)+ }++ fn providers(&self) -> Vec<Arc<DriverSessionStores>> {+ self.tenants+ .lock()+ .unwrap_or_else(PoisonError::into_inner)+ .values()+ .cloned()+ .collect()+ }+}++impl SessionStoreProvider for TenantSessionStores {+ fn for_agent(&self, agent_id: &str) -> AgentStores {+ let (provider, agent) = self.route(agent_id);+ provider.for_agent(&agent)+ }++ fn try_for_agent(&self, agent_id: &str) -> Result<AgentStores, StorageError> {+ let (provider, agent) = self.route(agent_id);+ provider.try_for_agent(&agent)+ }++ fn bind_actor(+ &self,+ backend: Arc<dyn StorageBackend>,+ ) -> Result<Option<Arc<dyn SessionStoreProvider>>, StorageError> {+ self.bind_actor_with_schema_admission(backend, self.admission)+ }++ fn bind_actor_with_schema_admission(+ &self,+ backend: Arc<dyn StorageBackend>,+ admission: SchemaAdmission,+ ) -> Result<Option<Arc<dyn SessionStoreProvider>>, StorageError> {+ Ok(Some(Arc::new(Self::with_admission(+ backend,+ self.bridge.clone(),+ self.recover_on_open,+ admission,+ ))))+ }++ fn run_ledger_for_agent(+ &self,+ agent_id: &str,+ ) -> tinyagents_session::run_ledger::LedgerResult<+ Option<Arc<dyn tinyagents_session::run_ledger::RunLedgerStore>>,+ > {+ let (provider, agent) = self.route(agent_id);+ provider.run_ledger_for_agent(&agent)+ }++ fn conversations_for_agent(+ &self,+ agent_id: &str,+ ) -> tinyagents_session::threads::ConversationResult<+ Option<Arc<dyn tinyagents_session::threads::ConversationPersistence>>,+ > {+ let (provider, agent) = self.route(agent_id);+ provider.conversations_for_agent(&agent)+ }++ fn recover(&self) -> anyhow::Result<()> {+ for provider in self.providers() {+ provider.recover()?;+ }+ Ok(())+ }++ fn destination_key(&self) -> Option<String> {+ Some(format!("{}://tenants", self.backend.driver()))+ }+}++#[cfg(test)]+#[path = "tenant_router_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/agent/session_store/workspace.rs b/crates/openhuman-core/src/agent/session_store/workspace.rsindex 1af57b2d8f..ce16a4ad44 100644--- a/crates/openhuman-core/src/agent/session_store/workspace.rs+++ b/crates/openhuman-core/src/agent/session_store/workspace.rs@@ -20,13 +20,13 @@ use std::sync::{Arc, LazyLock, Mutex, PoisonError};use tinyagents_harness::multimodal::BlobAttachmentStash;use tinyagents_session::port::{AgentStores, SessionStoreProvider, TurnStates};use tinyagents_session::run_ledger::{LedgerError, LedgerResult, RunLedgerStore};-use tinyagents_session::DriverSessionStores;+use super::tenant_router::TenantSessionStores;use tinystoragedrivers::{BlobStore, DocumentStore, MemoryStorage, StorageBackend};/// One fallback provider and the backend it was built over.struct Fallback {backend: Arc<dyn StorageBackend>,- provider: Arc<DriverSessionStores>,+ provider: Arc<TenantSessionStores>,}static FALLBACKS: LazyLock<Mutex<HashMap<PathBuf, Fallback>>> = LazyLock::new(Mutex::default);@@ -57,7 +57,7 @@ pub fn release_workspace(workspace_dir: &Path) {}/// The provider for `workspace_dir`: the installed one, else a-/// `DriverSessionStores` over the workspace's default backend.+/// `TenantSessionStores` over the workspace's default backend.////// Never fails: a default that cannot be opened (a read-only workspace) is/// logged and replaced by an in-memory backend for that workspace, so a turn@@ -87,9 +87,9 @@ pub(super) fn fallback_provider(workspace_dir: &Path) -> Arc<dyn SessionStoreProreturn existing.provider.clone();}}- match DriverSessionStores::new(Arc::clone(&backend)) {+ match TenantSessionStores::new(Arc::clone(&backend), false) {Ok(provider) => {- let provider = Arc::new(provider.recover_on_open(false));+ let provider = Arc::new(provider);fallbacks.insert(workspace_dir.to_path_buf(),Fallback {@@ -114,8 +114,8 @@ fn memory_fallback(workspace_dir: &Path) -> Arc<dyn SessionStoreProvider> {.entry(workspace_dir.to_path_buf()).or_insert_with(|| {let backend: Arc<dyn StorageBackend> = Arc::new(MemoryStorage::new());- match DriverSessionStores::new(backend) {- Ok(provider) => Arc::new(provider.recover_on_open(false)),+ match TenantSessionStores::new(backend, false) {+ Ok(provider) => Arc::new(provider),Err(_) => Arc::new(tinyagents_session::port::InMemorySessionStores::new()),}})@@ -214,7 +214,7 @@ fn tenant_scope_for(return None;}};- match backend.for_scope(&crate::storage::scope_for_agent(&key)) {+ match backend.for_scope(&session_scope(&key)) {Ok(scoped) => Some((key, scoped)),Err(error) => {log::warn!("[session_store] {what} scope refused agent={key}: {error}");@@ -264,7 +264,7 @@ pub fn current_documents_for(workspace_dir: &Path) -> Option<Arc<dyn DocumentStoreturn None;}};- match backend.for_scope(&crate::storage::scope_for_agent(&key)) {+ match backend.for_scope(&session_scope(&key)) {Ok(scoped) => Some(Arc::clone(scoped.documents())),Err(error) => {log::warn!("[session_store] documents scope refused agent={key}: {error}");@@ -402,6 +402,19 @@ impl SessionStoreProvider for WorkspaceSessionStores {}}+/// The storage scope a session key (`crate::core::runtime::session_key`)+/// names: `local/agent:<id>` or `u:<profile>/agent:<id>`, the scope the+/// session store itself binds that key to.+pub fn session_scope(key: &str) -> tinystoragedrivers::Scope {+ let (profile, mut agent) = crate::core::runtime::split_session_key(key);+ if agent.is_empty() {+ agent = crate::storage::scope::DEFAULT_AGENT.to_owned();+ }+ crate::storage::tenant_scope(profile.as_deref())+ .agent(&agent)+ .unwrap_or_else(|_| unreachable!("a non-empty agent id is a valid segment"))+}+#[cfg(test)]#[path = "workspace_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/core/runtime/mod.rs b/crates/openhuman-core/src/core/runtime/mod.rsindex 8b7b4b9300..71a06f66f6 100644--- a/crates/openhuman-core/src/core/runtime/mod.rs+++ b/crates/openhuman-core/src/core/runtime/mod.rs@@ -68,7 +68,9 @@ pub use context::{ContextOverlay, CoreContext};pub use dispatch_ctx::DispatchCtx;pub use mode::{current_mode, is_saas, Mode};pub use saas::SaasConfig;-pub use tenant::{current_tenant, session_key, session_key_prefix, tenant_key, NoTenant, Tenant};+pub use tenant::{+ current_tenant, session_key, session_key_prefix, split_session_key, tenant_key, NoTenant, Tenant,+};/// Operator-owned direct inference settings.pub mod direct_profile_provider;diff --git a/crates/openhuman-core/src/core/runtime/tenant.rs b/crates/openhuman-core/src/core/runtime/tenant.rsindex 7ab4db2564..8b04124a1a 100644--- a/crates/openhuman-core/src/core/runtime/tenant.rs+++ b/crates/openhuman-core/src/core/runtime/tenant.rs@@ -237,6 +237,20 @@ fn escape_profile(profile: &str) -> String {profile.replace('%', "%25").replace('~', "%7E")}+fn unescape_profile(escaped: &str) -> String {+ escaped.replace("%7E", "~").replace("%25", "%")+}++/// The `(profile, agent)` a [`session_key`] was built from: `None` profile for+/// the desktop operator. The inverse of [`session_key`], so the session store+/// can bind `Scope::tenant(profile).agent(agent)` instead of a flat string.+pub fn split_session_key(key: &str) -> (Option<String>, String) {+ match key.split_once('~') {+ Some((profile, agent)) => (Some(unescape_profile(profile)), agent.to_owned()),+ None => (None, unescape_profile(key)),+ }+}+#[cfg(test)]#[path = "tenant_tests.rs"]mod tests;diff --git a/crates/openhuman-core/src/integrations/task_sources/store_documents.rs b/crates/openhuman-core/src/integrations/task_sources/store_documents.rsindex 44b8cda1ea..36648026a3 100644--- a/crates/openhuman-core/src/integrations/task_sources/store_documents.rs+++ b/crates/openhuman-core/src/integrations/task_sources/store_documents.rs@@ -196,6 +196,7 @@ impl Docs {id: key.clone(),version: tinystoragedrivers::Version::FIRST,doc: doc.clone(),+ meta: tinystoragedrivers::Meta::unknown(),};let mut source = to_source(&stored).ok()?;apply_patch(&mut source, patch.clone()).ok()?;diff --git a/crates/openhuman-core/src/security/approval/store_documents.rs b/crates/openhuman-core/src/security/approval/store_documents.rsindex a8d017fd49..34b79233b6 100644--- a/crates/openhuman-core/src/security/approval/store_documents.rs+++ b/crates/openhuman-core/src/security/approval/store_documents.rs@@ -514,6 +514,7 @@ async fn update(id: id.to_string(),version,doc: next,+ meta: stored.meta.clone(),}));}Err(error) if error.kind() == ErrorKind::Conflict => {}diff --git a/crates/openhuman-core/src/security/devices/store_documents.rs b/crates/openhuman-core/src/security/devices/store_documents.rsindex 9e8f7bd143..c8e1e697b6 100644--- a/crates/openhuman-core/src/security/devices/store_documents.rs+++ b/crates/openhuman-core/src/security/devices/store_documents.rs@@ -91,7 +91,12 @@ impl Docs {let version = docs.put(DEVICES, &id, doc.clone(), Precondition::None).await?;- Ok(to_device(&Versioned { id, version, doc }))+ Ok(to_device(&Versioned {+ id,+ version,+ doc,+ meta: tinystoragedrivers::Meta::unknown(),+ }))})}diff --git a/crates/openhuman-core/src/storage/documents.rs b/crates/openhuman-core/src/storage/documents.rsindex cec609bd7c..3654acfe9f 100644--- a/crates/openhuman-core/src/storage/documents.rs+++ b/crates/openhuman-core/src/storage/documents.rs@@ -264,6 +264,7 @@ pub async fn compare_and_swap(id: id.to_string(),version,doc: next,+ meta: stored.meta.clone(),}));}Err(error) if error.kind() == ErrorKind::Conflict => {}diff --git a/crates/openhuman-core/src/storage/fenced_backend.rs b/crates/openhuman-core/src/storage/fenced_backend.rsindex 0cdc805547..4630c85f83 100644--- a/crates/openhuman-core/src/storage/fenced_backend.rs+++ b/crates/openhuman-core/src/storage/fenced_backend.rs@@ -13,7 +13,7 @@//! driver refusal ([`ErrorKind::Fenced`]) latches the fence and surfaces as//! [`FenceError::Superseded`](super::fence::FenceError::Superseded). Where//! the driver cannot fence (no [`Capability::Fencing`], a write it answers-//! with `Unsupported(Fencing)`, a named database, or a lease store with no+//! with `Unsupported(Fencing)`, or a lease store with no//! record in the ports) the write runs after the host check alone.//!//! The fence is looked up per write, not when the scope is bound, because@@ -41,10 +41,6 @@ use super::{DocumentStore, Scope, ScopedStorage, StorageBackend};pub struct FencedBackend {inner: Arc<dyn StorageBackend>,fences: Arc<FenceRegistry>,- /// Whether the driver can see the lease records: true for the default- /// database (where the cluster scope's leases live), false for a named- /// database ([`Self::database`]), whose writes get the host check only.- driver_fencing: bool,}impl std::fmt::Debug for FencedBackend {@@ -61,7 +57,6 @@ impl FencedBackend {Self {inner,fences,- driver_fencing: true,}}}@@ -86,7 +81,7 @@ impl StorageBackend for FencedBackend {let guard = Guard {scope: scope.clone(),fences: Arc::clone(&self.fences),- backend: self.driver_fencing.then(|| Arc::clone(&self.inner)),+ backend: Some(Arc::clone(&self.inner)),};Ok(ScopedStorage::new(scope.clone(),@@ -113,21 +108,13 @@ impl StorageBackend for FencedBackend {self.inner.sweep_expired_blobs(scope).await}- fn database(&self, name: &str) -> Result<Arc<dyn StorageBackend>> {- Ok(Arc::new(Self {- inner: self.inner.database(name)?,- fences: Arc::clone(&self.fences),- driver_fencing: false,- }))- }}#[derive(Clone)]struct Guard {scope: Scope,fences: Arc<FenceRegistry>,- /// The inner backend, when its driver may enforce the fence (see- /// [`FencedBackend::driver_fencing`]).+ /// The inner backend, whose driver may enforce the fence.backend: Option<Arc<dyn StorageBackend>>,}diff --git a/crates/openhuman-core/src/storage/import/sessions.rs b/crates/openhuman-core/src/storage/import/sessions.rsindex 43587d2f5d..f36af3d31f 100644--- a/crates/openhuman-core/src/storage/import/sessions.rs+++ b/crates/openhuman-core/src/storage/import/sessions.rs@@ -42,7 +42,7 @@ use super::tinyflows::{finish, marked};use super::{Outcome, Report, Snapshot};use crate::agent::session_store::DEFAULT_AGENT;use crate::config::Config;-use crate::storage::StorageBackend;+use crate::storage::{Scope, StorageBackend};/// The marker name of the session import.pub const SESSIONS_DOMAIN: &str = "sessions";@@ -67,7 +67,7 @@ fn import(backend: &Arc<dyn StorageBackend>, config: &Config) -> Result<Outcome>if !db.is_file() && !raw.is_dir() && !turns.is_dir() {return Ok(None);}- let provider = DriverSessionStores::new(Arc::clone(backend))+ let provider = DriverSessionStores::new(Arc::clone(backend), Scope::local()).map_err(|error| anyhow::anyhow!("start the session store bridge: {error}"))?.recover_on_open(false);let mut found = 0usize;diff --git a/crates/openhuman-core/src/storage/mod.rs b/crates/openhuman-core/src/storage/mod.rsindex 3d64e5112b..b777434070 100644--- a/crates/openhuman-core/src/storage/mod.rs+++ b/crates/openhuman-core/src/storage/mod.rs@@ -37,8 +37,11 @@ mod lease_documents;mod lease_local;pub mod local;pub mod rebind;+pub mod scope;pub mod secrets;+pub use scope::{scope_for_agent, scope_for_module, scope_for_profile, tenant_scope};+use std::future::Future;use std::sync::{Arc, LazyLock, Mutex, OnceLock, RwLock};@@ -317,29 +320,6 @@ pub fn installed_is_shared() -> bool {installed().is_some_and(|backend| driver_is_shared(backend.driver()))}-/// The storage scope agent `agent_id`'s records live under — the same-/// mapping the session store uses, so every domain agrees on it.-pub fn scope_for_agent(agent_id: &str) -> Scope {- tinyagents_session::DriverSessionStores::scope_for(agent_id)-}--/// The storage scope profile `profile_id`'s records live under:-/// `profile:<id>`, or `profile-sha256:<hex of the id>` when that is not a-/// valid scope (too long, whitespace, control characters). Injective: a-/// literal scope always starts with `profile:`, a hashed one never does, and-/// two distinct profiles never share either form.-pub fn scope_for_profile(profile_id: &str) -> Scope {- const PREFIX: &str = "profile:";- let literal = format!("{PREFIX}{profile_id}");- if let Ok(scope) = Scope::new(&literal) {- return scope;- }- use sha2::Digest;- let digest = sha2::Sha256::digest(profile_id.as_bytes());- Scope::new(format!("profile-sha256:{}", hex::encode(digest)))- .unwrap_or_else(|_| unreachable!("a sha256 hex scope is always valid"))-}-/// A stable key for a legacy import source (a workspace directory), for the/// marker document and once-per-process key of an importer. Two workspaces/// that share one explicit backend and scope must each import their own legacydiff --git a/crates/openhuman-core/src/storage/scope.rs b/crates/openhuman-core/src/storage/scope.rsnew file mode 100644index 0000000000..e570f583fd--- /dev/null+++ b/crates/openhuman-core/src/storage/scope.rs@@ -0,0 +1,69 @@+//! The one scope grammar every domain store addresses its records by.+//!+//! The grammar is tinystoragedrivers' (`Scope::tenant`, `Scope::local`,+//! `.agent(id)`, `.module(id)`): a tenant (`local` for the desktop operator,+//! `u:<profile>` for a SaaS profile) optionally narrowed to one principal+//! (`<tenant>/agent:<id>` or `<tenant>/module:<id>`). The tenant is the fence+//! and purge boundary, so every helper here derives the principal scope from+//! the tenant scope and never from a raw string. A segment that is too long or+//! holds characters outside the grammar is hashed by tsd itself.+//!+//! The v1 shapes these replace (`profile:<id>`, `<profile>~<agent>`, a raw+//! agent id, `module:<id>@<base>`, the `*-sha256:` fallbacks) are only ever+//! parsed by the one-time scope move ([`super::scope_move`]).++use super::Scope;++/// The agent id a record with no named agent belongs to.+pub const DEFAULT_AGENT: &str = "default";++/// The tenant scope of an optional profile: `u:<profile>` for a profile,+/// [`Scope::local`] for the desktop operator.+pub fn tenant_scope(profile: Option<&str>) -> Scope {+ match profile {+ Some(profile) => scope_for_profile(profile),+ None => Scope::local(),+ }+}++/// The storage scope profile `profile_id`'s records live under: its tenant+/// scope, `u:<id>`. Injective, hashing the id when it is not a valid segment.+pub fn scope_for_profile(profile_id: &str) -> Scope {+ Scope::tenant(profile_id).unwrap_or_else(|error| {+ tracing::warn!(+ target: "openhuman::storage",+ %error,+ "[storage] unusable profile id for a scope; using the reserved empty-profile tenant"+ );+ Scope::tenant("_empty_").unwrap_or_else(|_| unreachable!("a static tenant id is valid"))+ })+}++/// The storage scope agent `agent_id`'s records live under on the desktop:+/// `local/agent:<id>` (an empty id is the [`DEFAULT_AGENT`]). A profile's+/// agents are `scope_for_profile(profile).agent(id)`, which the session store+/// derives itself.+pub fn scope_for_agent(agent_id: &str) -> Scope {+ let id = if agent_id.is_empty() {+ DEFAULT_AGENT+ } else {+ agent_id+ };+ Scope::local()+ .agent(id)+ .unwrap_or_else(|_| unreachable!("a non-empty agent id is a valid segment"))+}++/// The scope module `module_id`'s records live under for the tenant of+/// `profile` (`None` for the desktop operator): `<tenant>/module:<id>`.+///+/// # Errors+///+/// When `module_id` is empty.+pub fn scope_for_module(profile: Option<&str>, module_id: &str) -> Result<Scope, super::StorageError> {+ tenant_scope(profile).module(module_id)+}++#[cfg(test)]+#[path = "scope_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/storage/scope_tests.rs b/crates/openhuman-core/src/storage/scope_tests.rsnew file mode 100644index 0000000000..33d9e8a3c1--- /dev/null+++ b/crates/openhuman-core/src/storage/scope_tests.rs@@ -0,0 +1,33 @@+use super::*;++#[test]+fn profile_is_a_tenant_scope() {+ assert_eq!(scope_for_profile("alice").as_str(), "u:alice");+}++#[test]+fn unprofiled_agent_lives_under_local() {+ assert_eq!(scope_for_agent("asha").as_str(), "local/agent:asha");+ assert_eq!(scope_for_agent("").as_str(), "local/agent:default");+}++#[test]+fn module_scope_follows_the_tenant() {+ assert_eq!(+ scope_for_module(None, "tinymcp").unwrap().as_str(),+ "local/module:tinymcp"+ );+ assert_eq!(+ scope_for_module(Some("alice"), "tinymcp").unwrap().as_str(),+ "u:alice/module:tinymcp"+ );+}++#[test]+fn odd_ids_hash_inside_their_tenant() {+ let scope = scope_for_profile("not a valid id");+ assert!(scope.as_str().starts_with("u:~"));+ let agent = scope.agent("x").unwrap();+ assert!(agent.as_str().starts_with(scope.as_str()));+ assert_eq!(agent.tenant_scope(), Some(scope));+}diff --git a/crates/openhuman-embed/src/runtime/build.rs b/crates/openhuman-embed/src/runtime/build.rsindex bf4fa29000..b692212721 100644--- a/crates/openhuman-embed/src/runtime/build.rs+++ b/crates/openhuman-embed/src/runtime/build.rs@@ -190,9 +190,11 @@ impl RuntimeBuilder {};if self.session_store.is_none() {if let Some(backend) = &storage_backend {- let stores = tinyagents_session::DriverSessionStores::new(backend.clone())- .map_err(|e| RuntimeError::Build(e.into()))?- .recover_on_open(!openhuman_core::storage::driver_is_shared(backend.driver()));+ let stores = openhuman_core::agent::session_store::TenantSessionStores::new(+ backend.clone(),+ !openhuman_core::storage::driver_is_shared(backend.driver()),+ )+ .map_err(|e| RuntimeError::Build(e.into()))?;self.session_store = Some(Arc::new(stores));}}diff --git a/crates/openhuman-rpc/Cargo.toml b/crates/openhuman-rpc/Cargo.tomlindex ff30f85115..5e986b817f 100644--- a/crates/openhuman-rpc/Cargo.toml+++ b/crates/openhuman-rpc/Cargo.toml@@ -80,7 +80,7 @@ e2e-test-support = ["openhuman-tinyhumans/e2e-test-support"][dependencies]keyring = { version = "3", features = ["apple-native", "windows-native", "linux-native"], optional = true }-tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v0.11.0", default-features = false, features = ["secrets", "keyring"], optional = true }+tinystoragedrivers = { git = "https://github.com/tinyhumansai/tinystoragedrivers", tag = "v1.0.0", default-features = false, features = ["secrets", "keyring"], optional = true }zeroize = { version = "1", optional = true }hex = { version = "0.4", optional = true }# The only openhuman crate this layer depends on. Core internals the server