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
Merge branch 'crate-chain-p2' into crate-chain-p3
Steven Enamakel726541b568eb
diff --cc crates/openhuman-rpc/Cargo.tomlindex 240a4c460e,c7bba86139..262c1e42ad--- a/crates/openhuman-rpc/Cargo.toml+++ b/crates/openhuman-rpc/Cargo.toml@@@ -41,36 -38,13 +41,36 @@@ server =# `session_raw/` / `session_db/` / `tinyagents_store/` layout behind# TinyAgents' session store port. On with `server`; the TUI, which runs the# core without the server, turns it on by itself.- session-store = ["dep:tinyagents-session", "dep:tinyagents-harness", "dep:chrono", "dep:anyhow"]+ session-store = ["dep:tinyagents-session", "dep:tinyagents-harness", "dep:chrono", "dep:anyhow", "tinyagents-session/storage-drivers"]-# Forwarded so the server's Sentry-routing tests run against a core that-# reports to Sentry.-crash-reporting = ["openhuman-core/crash-reporting"]+# The Jev `tool_search` ranker the shared host boot (`host`) wires in.+jev = ["openhuman-tinyhumans/jev"]+# Product gates, forwarded down the chain.+http-server = ["openhuman-tinyhumans/http-server"]+inference = ["openhuman-tinyhumans/inference"]+documents = ["openhuman-tinyhumans/documents"]+hosting = ["openhuman-tinyhumans/hosting"]+modules = ["openhuman-tinyhumans/modules"]+voice = ["openhuman-tinyhumans/voice"]+web3 = ["openhuman-tinyhumans/web3"]+runtime-node = ["openhuman-tinyhumans/runtime-node"]+media = ["openhuman-tinyhumans/media"]+flows = ["openhuman-tinyhumans/flows"]+skills = ["openhuman-tinyhumans/skills"]+mcp = ["openhuman-tinyhumans/mcp"]+# Also lets the server's Sentry-routing tests run against a core that reports+# to Sentry.+crash-reporting = ["openhuman-tinyhumans/crash-reporting"]+channels = ["openhuman-tinyhumans/channels"]+whatsapp-web = ["openhuman-tinyhumans/whatsapp-web"]+file-logging = ["openhuman-tinyhumans/file-logging"]+scheduler-gate = ["openhuman-tinyhumans/scheduler-gate"][dependencies]-openhuman-core = { path = "../openhuman-core", package = "openhuman", default-features = false }+# The only openhuman crate this layer depends on. Core internals the server+# needs come through embed's `#[doc(hidden)]` `__host` list (reached as+# `openhuman_tinyhumans::embed::__host`); there is no direct `openhuman-core`+# edge (chain: core -> embed -> tinyhumans -> rpc -> hosts).+openhuman-tinyhumans = { path = "../openhuman-tinyhumans", default-features = false }log = "0.4"serde = { version = "1", features = ["derive"] }serde_json = "1"diff --cc crates/openhuman-rpc/README.mdindex abfd5a0b9e,fa9eb591e7..4dd9b90805--- a/crates/openhuman-rpc/README.md+++ b/crates/openhuman-rpc/README.md@@@ -100,11 -80,10 +100,11 @@@ for the hosts that still call them| Path | What it does || --- | --- |- | `src/lib.rs` | Module wiring and re-exports (`tinyhumans`, the client helpers, `unwrap_rpc`). |- | `src/host.rs` | `server` / `session-store` features: the shared host boot — `cli`, `desktop` / `serve_desktop`, `tui`, and the `*_builder` each starts from. |- | `src/envelope.rs` | `RpcRequest`, `RpcSuccess`, `RpcFailure`, `RpcError`, `JSONRPC_VERSION`, `SERVER_ERROR_CODE`, and the client half: `request_body`, `decode_response`. |- | `src/origin.rs` | `is_origin_allowed_with_extra` and `ALLOWED_ORIGINS_ENV`: the browser-origin allowlist. Pure; the caller reads the environment. |- | `src/client.rs` | `http-client` feature: `post_json_rpc`, `bearer_header`, `redact_url_for_log`, `HttpRpcResponse`. |-| [`src/lib.rs`](src/lib.rs) | Module wiring and re-exports. |++| [`src/lib.rs`](src/lib.rs) | Module wiring and re-exports (`tinyhumans`, the client helpers, `unwrap_rpc`). |++| [`src/host.rs`](src/host.rs) | `server` / `session-store` features: the shared host boot — `cli`, `desktop` / `serve_desktop`, `tui`, and the `*_builder` each starts from. |+ | [`src/envelope.rs`](src/envelope.rs) | `RpcRequest`, `RpcSuccess`, `RpcFailure`, `RpcError`, `JSONRPC_VERSION`, `SERVER_ERROR_CODE`, and the client half: `request_body`, `decode_response`. |+ | [`src/origin.rs`](src/origin.rs) | `is_origin_allowed_with_extra` and `ALLOWED_ORIGINS_ENV`: the browser-origin allowlist. Pure; the caller reads the environment. |+ | [`src/client.rs`](src/client.rs) | `http-client` feature: `post_json_rpc`, `bearer_header`, `redact_url_for_log`, `HttpRpcResponse`. || [`src/server/`](src/server/README.md) | `server` feature: the axum router, auth and CORS middleware, the `/rpc` handler, SSE and WebSocket routes, Socket.IO, `/dev/connect`, the listener (`serve`) and the `run_server*` entry points. || [`src/http_host/`](src/http_host/README.md) | `server` feature: ad-hoc Basic-auth static directory servers and their `http_host.*` controllers. || [`src/session_store/`](src/session_store/README.md) | `session-store` feature: `SqliteSessionStores`, the classic on-disk session layout behind TinyAgents' session store port. |diff --cc crates/openhuman-rpc/src/server/README.mdindex 9a718b3dea,aacca0692b..b03a62be44--- a/crates/openhuman-rpc/src/server/README.md+++ b/crates/openhuman-rpc/src/server/README.md@@@ -100,7 -93,7 +100,7 @@@ outermost to innermost| `/v1/*` | the core's OpenAI-compatible router (`inference::http`) | core bearer or the user-managed external API key |The bearer is the per-launch RPC token the core owns- (`openhuman::core::auth`); `auth.rs` is only the route policy over it.-(`openhuman_core::core::auth`); [`auth.rs`](auth.rs) is only the route policy over it.++(`openhuman::core::auth`); [`auth.rs`](auth.rs) is only the route policy over it.### A failed calldiff --cc crates/openhuman-rpc/src/server/cli.rsindex b9391694c1,4af79d465c..bf4190f6e8--- a/crates/openhuman-rpc/src/server/cli.rs+++ b/crates/openhuman-rpc/src/server/cli.rs@@@ -14,20 -14,23 +14,27 @@@ pub fn install_cli_server()install_server_launcher(launch);}-fn launch(request: ServeRequest) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {+/// The [`ServerLauncher`](openhuman_tinyhumans::embed::seams::ServerLauncher)+/// behind `run` / `serve`: the standalone server shims.+pub(crate) fn launch(+ request: ServeRequest,+) -> Pin<Box<dyn Future<Output = anyhow::Result<()>> + Send>> {Box::pin(async move {log::debug!(- "[rpc:cli] starting server host={:?} port={:?} socketio={} headless_api={}",+ "[rpc:cli] starting server host={:?} port={:?} socketio={} headless_api={} mode={}",request.host,request.port,request.socketio_enabled,- request.headless_api+ request.headless_api,+ request.mode);- if request.headless_api {- if request.mode == openhuman_core::core::runtime::Mode::Saas {++ if request.mode == crate::core_host::core::runtime::Mode::Saas {+ let config = request+ .saas_config+ .as_deref()+ .ok_or_else(|| anyhow::anyhow!("--mode saas needs --saas-config <file>"))?;+ super::run_server_saas(request.host.as_deref(), request.port, config).await+ } else if request.headless_api {super::run_server_headless(request.host.as_deref(), request.port).await} else {super::run_server(diff --cc crates/openhuman-rpc/src/server/dev_connect.rsindex 12c10be55d,6564b2a3a9..fd33d0ab89--- a/crates/openhuman-rpc/src/server/dev_connect.rs+++ b/crates/openhuman-rpc/src/server/dev_connect.rs@@@ -41,10 -41,12 +41,12 @@@ pub struct DevConnectQuery/// Whether the route is live in this process.pub fn dev_connect_enabled() -> bool {- dev_connect_enabled_with(- cfg!(debug_assertions),- std::env::var(DEV_CONNECT_ENV).ok().as_deref(),- )+ // Never on a SaaS core: the route is auth-exempt and hands out the bearer.- !openhuman_core::core::runtime::is_saas()++ !crate::core_host::core::runtime::is_saas()+ && dev_connect_enabled_with(+ cfg!(debug_assertions),+ std::env::var(DEV_CONNECT_ENV).ok().as_deref(),+ )}pub(crate) fn dev_connect_enabled_with(debug_build: bool, env: Option<&str>) -> bool {diff --cc crates/openhuman-rpc/src/server/mod.rsindex 67ed040078,cad03cd877..3367fd0423--- a/crates/openhuman-rpc/src/server/mod.rs+++ b/crates/openhuman-rpc/src/server/mod.rs@@@ -17,11 -17,12 +17,12 @@@mod auth;mod classify;-mod cli;+pub(crate) mod cli;mod dev_connect;pub(crate) mod http;+ mod saas_gateway;mod serve;-mod shims;+pub(crate) mod shims;mod socketio;#[cfg(test)]mod testing;diff --cc crates/openhuman-rpc/src/server/saas_gateway.rsindex 0000000000,eea050e85f..29da7e2b12mode 000000,100644..100644--- a/crates/openhuman-rpc/src/server/saas_gateway.rs+++ b/crates/openhuman-rpc/src/server/saas_gateway.rs@@@ -1,0 -1,113 +1,113 @@@+ //! The SaaS gateway layer: which context each request runs under.+ //!+ //! Replaces the single-context layer when the process runs in SaaS mode. For+ //! every request it:+ //!+ //! 1. answers `404` for routes a SaaS core never serves — the OpenAI-compatible+ //! `/v1`, every `/events` stream, the WebSockets, `/dev/connect` and the MCP+ //! OAuth callback;+ //! 2. with no `X-OpenHuman-User`, runs it on the operator plane (the bearer+ //! check downstream still applies);+ //! 3. with one, checks the service bearer **first** — so an unauthenticated+ //! caller learns nothing about which users exist and cannot open agents —+ //! then the signature, then runs the request under that user's agent.+ //!-//! The decision itself lives in `openhuman_core::user_agents::gateway`.++//! The decision itself lives in `crate::core_host::user_agents::gateway`.++ use std::sync::Arc;+ use std::time::{SystemTime, UNIX_EPOCH};+++use crate::core_host::core::runtime::CoreContext;++use crate::core_host::user_agents::gateway::{++ resolve_scope, GatewayScope, USER_HEADER, USER_SIG_HEADER,++};+ use axum::extract::Request;+ use axum::http::{header, StatusCode};+ use axum::middleware::Next;+ use axum::response::{IntoResponse, Response};-use openhuman_core::core::runtime::CoreContext;-use openhuman_core::user_agents::gateway::{- resolve_scope, GatewayScope, USER_HEADER, USER_SIG_HEADER,-};++ /// Route prefixes a SaaS core never serves.+ pub(crate) const CLOSED_IN_SAAS: &[&str] = &[+ "/v1",+ "/events",+ "/ws/",+ "/socket.io",+ "/dev/connect",+ "/oauth/",+ ];++ pub(crate) fn is_closed_in_saas(path: &str) -> bool {+ CLOSED_IN_SAAS.iter().any(|prefix| {+ path == prefix.trim_end_matches('/')+ || path.starts_with(prefix)+ && (prefix.ends_with('/') || path[prefix.len()..].starts_with('/'))+ })+ }++ fn refuse(status: u16, message: &str) -> Response {+ let status = StatusCode::from_u16(status).unwrap_or(StatusCode::FORBIDDEN);+ (status, axum::Json(serde_json::json!({ "error": message }))).into_response()+ }++ fn header_str<'a>(req: &'a Request, name: &str) -> Option<&'a str> {+ req.headers().get(name).and_then(|v| v.to_str().ok())+ }++ fn bearer(req: &Request) -> Option<&str> {+ header_str(req, header::AUTHORIZATION.as_str())?+ .strip_prefix("Bearer ")+ .map(str::trim)+ }++ /// The SaaS request layer; `operator` is the runtime's own context.+ pub(crate) async fn saas_gateway(operator: Arc<CoreContext>, req: Request, next: Next) -> Response {+ let path = req.uri().path();+ if is_closed_in_saas(path) {+ log::debug!("[rpc:saas] {path} is not served in SaaS mode");+ return refuse(404, "not found");+ }++ // Absent means the operator plane. Present but unreadable, or present+ // twice, is refused: falling back to the operator would skip the user+ // signature check.+ let mut user_headers = req.headers().get_all(USER_HEADER).iter();+ let Some(first) = user_headers.next() else {+ return CoreContext::scope(operator, next.run(req)).await;+ };+ if user_headers.next().is_some() {+ log::debug!("[rpc:saas] refusing a request with more than one {USER_HEADER}");+ return refuse(400, "more than one user header");+ }+ let Ok(user) = first.to_str().map(str::to_owned) else {+ log::debug!("[rpc:saas] refusing an unreadable {USER_HEADER}");+ return refuse(400, "unreadable user header");+ };+- let Some(secret) = openhuman_core::core::auth::get_rpc_token() else {++ let Some(secret) = crate::core_host::core::auth::get_rpc_token() else {+ return refuse(503, "the core is not ready");+ };- if !bearer(&req).is_some_and(openhuman_core::core::auth::verify_bearer_token) {++ if !bearer(&req).is_some_and(crate::core_host::core::auth::verify_bearer_token) {+ return refuse(401, "unauthorized");+ }+ let signature = header_str(&req, USER_SIG_HEADER).map(str::to_owned);+ let now = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or_default();+ match resolve_scope(Some(&user), signature.as_deref(), secret, now) {+ Ok(GatewayScope::User(agent)) => {+ let ctx = Arc::clone(agent.context());+ // Holding the state for the request keeps the agent from being+ // evicted under it.+ let response = CoreContext::scope(ctx, next.run(req)).await;+ drop(agent);+ response+ }+ Ok(GatewayScope::Operator) => CoreContext::scope(operator, next.run(req)).await,+ Err(refusal) => refuse(refusal.status, &refusal.message),+ }+ }++ #[cfg(test)]+ #[path = "saas_gateway_tests.rs"]+ mod tests;diff --cc crates/openhuman-rpc/src/server/serve.rsindex 6c8de907a9,288d376c27..b0de7c7f43--- a/crates/openhuman-rpc/src/server/serve.rs+++ b/crates/openhuman-rpc/src/server/serve.rs@@@ -136,16 -136,26 +136,26 @@@ pub async fn serve}let ctx = Arc::clone(runtime.context());- let app = super::http::build_core_http_router(runtime.services().socketio).layer(- axum::middleware::from_fn(+ let router = super::http::build_core_http_router(runtime.services().socketio);+ // A SaaS core scopes each request to the user the gateway names (or the+ // operator plane); a single-user core runs everything under its one+ // context.- let app = if openhuman_core::core::runtime::is_saas() {++ let app = if crate::core_host::core::runtime::is_saas() {+ router.layer(axum::middleware::from_fn(+ move |req: axum::extract::Request, next: axum::middleware::Next| {+ super::saas_gateway::saas_gateway(Arc::clone(&ctx), req, next)+ },+ ))+ } else {+ router.layer(axum::middleware::from_fn(move |req: axum::extract::Request, next: axum::middleware::Next| {let ctx = Arc::clone(&ctx);async move {- openhuman_core::core::runtime::CoreContext::scope(ctx, next.run(req)).await+ crate::core_host::core::runtime::CoreContext::scope(ctx, next.run(req)).await}},- ),- );+ ))+ };// Await startup migrations before publishing readiness or allowing// background writers to touch their crate-backed stores.diff --cc crates/openhuman-rpc/src/server/shims.rsindex 8d9be6bd75,c2f49ea775..da1a6c093e--- a/crates/openhuman-rpc/src/server/shims.rs+++ b/crates/openhuman-rpc/src/server/shims.rs@@@ -58,6 -42,24 +58,24 @@@ pub async fn run_server_headless(host:run_server_with_services(host, port, services, false, None, None, None).await}+ /// 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 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 = openhuman_core::core::runtime::SaasConfig::load(saas_config)?;++ let config = crate::core_host::core::runtime::SaasConfig::load(saas_config)?;+ crate::session_store::install();+ let runtime =- openhuman_core::core::runtime::saas::build(config, host.map(str::to_owned), port).await?;++ crate::core_host::core::runtime::saas::build(config, host.map(str::to_owned), port).await?;+ super::serve::serve(&runtime, None, None).await+ }+/// Like [`run_server`] but marks the instance as embedded.pub async fn run_server_embedded(host: Option<&str>,@@@ -136,82 -138,53 +154,89 @@@ async fn run_server_with_servicesembedded_core: bool,shutdown_token: Option<CancellationToken>,ready_tx: Option<tokio::sync::oneshot::Sender<EmbeddedReadySignal>>,- rpc_token: Option<std::sync::Arc<String>>,+ rpc_token: Option<Arc<String>>,) -> anyhow::Result<()> {- // `run_server_inner` is now a thin shim over the CoreBuilder/CoreRuntime- // composition (Phase 1). It reproduces the legacy behavior exactly: all- // background services on (`ServiceSet::desktop`), Socket.IO per the caller- // flag, and the legacy `embedded_core` → `HostKind` mapping (embedded ==- // Tauri shell; standalone splits CLI / Docker via `detect_standalone`).- // See the pluggable-core work (`core::runtime`).- let host_kind = if embedded_core {- openhuman_core::core::types::HostKind::TauriShell+ let preset = if embedded_core {+ RuntimeBuilder::desktop()} else {- openhuman_core::core::types::HostKind::detect_standalone()+ RuntimeBuilder::cli()};- let token = match rpc_token {- Some(token) => openhuman_core::core::runtime::TokenSource::Fixed(token),- None => openhuman_core::core::runtime::TokenSource::EnvOrFile,- };- let mut builder = openhuman_core::core::runtime::CoreBuilder::new(host_kind)- .token(token)- .services(services);- // The browser E2E harness scripts direct tool calls through its mock model.- // Keep production's fail-closed packed default, while making those calls- // visible in the deterministic test core without changing library hosts.- builder = apply_e2e_tool_groups(builder);+ let builder = server_builder(preset, services, host, port, rpc_token);+ build_and_serve(builder, ready_tx, shutdown_token).await+}++/// Apply a server's services, bearer and listener to a host preset.+///+/// `rpc_token` is the in-memory bearer handoff ([`TokenSource::Fixed`]);+/// `None` keeps the preset's env-or-file token. An unset host or port is left+/// to [`serve`](super::serve::serve), which falls back to+/// `OPENHUMAN_CORE_HOST` / `OPENHUMAN_CORE_PORT` and then the defaults.+pub(crate) fn server_builder(+ preset: RuntimeBuilder,+ services: ServiceSet,+ host: Option<&str>,+ port: Option<u16>,+ rpc_token: Option<Arc<String>>,+) -> RuntimeBuilder {+ let mut builder = preset.services(services);++ // The browser E2E harness scripts direct tool calls through its mock++ // model. Keep production's fail-closed packed default, while making those++ // calls visible in the deterministic test core.++ if std::env::var_os("OPENHUMAN_E2E").is_some() {++ log::debug!("[rpc:server] OPENHUMAN_E2E set; advertising every tool group");++ builder = builder.tool_groups(openhuman_tinyhumans::embed::ToolGroups::advertised());++ }+ if let Some(token) = rpc_token {+ builder = builder.token(TokenSource::Fixed(token));+ }if let Some(host) = host {- builder = builder.host(host);+ builder = builder.listen_host(host);}if let Some(port) = port {- builder = builder.port(port);+ builder = builder.listen_port(port);}+ builder+}++/// Build `builder`'s runtime and serve it until shutdown.+///+/// The on-disk session store is installed for the life of the process, as the+/// shims always did, rather than through `RuntimeBuilder::session_store`+/// (which restores the previous provider when the runtime drops). The desktop+/// restarts its in-process server in place; a detached turn still writing+/// across that gap must keep landing in the classic layout, not in the+/// core's no-provider fallback.+pub(crate) async fn build_and_serve(+ builder: RuntimeBuilder,+ ready_tx: Option<tokio::sync::oneshot::Sender<EmbeddedReadySignal>>,+ shutdown_token: Option<CancellationToken>,+) -> anyhow::Result<()> {+ let summary = builder.summary();+ log::debug!(+ "[rpc:server] building runtime host_kind={:?} services={:?} fixed_token={} \+ listen_host={:?} listen_port={:?} embedded_ready={}",+ summary.host_kind,+ summary.services,+ summary.fixed_token,+ summary.listen_host,+ summary.listen_port,+ ready_tx.is_some()+ );// The desktop app and the CLI keep conversations in the classic on-disk- // layout; the core itself carries no storage. Installed before boot so- // its recovery sweep runs.- crate::session_store::install();+ // layout unless a storage URL is configured; the core itself carries no+ // storage. Installed before boot so its recovery sweep runs.+ crate::session_store::install_for_host().await?;- let runtime = builder.build().await?;- super::serve::serve(&runtime, ready_tx, shutdown_token).await-}--fn apply_e2e_tool_groups(- builder: openhuman_core::core::runtime::CoreBuilder,-) -> openhuman_core::core::runtime::CoreBuilder {- if std::env::var_os("OPENHUMAN_E2E").is_some() {- builder.tool_groups(openhuman_core::tools::toolpacks::ToolGroups::advertised())- } else {- builder- }+ let runtime = builder.build().await.map_err(|error| {+ log::warn!("[rpc:server] runtime build failed: {error}");+ anyhow::Error::new(error)+ })?;+ let served = super::serve::serve(runtime.core_runtime(), ready_tx, shutdown_token).await;+ // Dropping the runtime releases the process's embed runtime slot, so the+ // desktop can restart its server in place.+ drop(runtime);+ log::debug!("[rpc:server] runtime released ok={}", served.is_ok());+ served}#[cfg(test)]diff --cc crates/openhuman-rpc/src/session_store/README.mdindex 9c5bd89032,041ba090e2..16258e05a7--- a/crates/openhuman-rpc/src/session_store/README.md+++ b/crates/openhuman-rpc/src/session_store/README.md@@@ -31,17 -30,13 +31,17 @@@ enables by itselfkv, journal open_session_stores```-`install()` puts a provider into the core's process slot-(`openhuman_core::agent::session_store::install`). It has to run before the-core boots, because boot calls the provider's `recover()`: turns an unclean-shutdown left in flight are marked interrupted, and run-ledger rows a dead-process left running are settled. Both `run_server*` shims in-[`../server/`](../server/README.md) call it, and the TUI calls it from-[`crates/openhuman-tui/src/runner.rs`](../../../openhuman-tui/src/runner.rs).+`install()` puts a provider into the core's process slot (the core's+`agent::session_store::install`, reached through embed's `__host`). It has to+run before the core boots, because boot calls the provider's `recover()`:+turns an unclean shutdown left in flight are marked interrupted, and+run-ledger rows a dead process left running are settled. The `run_server*`+shims in [`../server/`](../server/README.md) (and so `host::desktop`) call it+for the life of the process. `provider()` returns the same provider for a+runtime builder's `session_store` option, which installs it on build and+restores the previous one on drop; `host::tui` uses that. The TUI itself- still calls `install()` from `crates/openhuman-tui/src/runner.rs` until it++still calls `install()` from [`crates/openhuman-tui/src/runner.rs`](../../../openhuman-tui/src/runner.rs) until it+moves to `host::tui`.`install()` builds the provider with `resolving(context_workspace_dir)`,so the workspace is looked up on every `for_agent` call rather than fixed atdiff --cc crates/openhuman-rpc/src/session_store/mod.rsindex a8d2adb602,a65ef0bb3e..bd5b8cfecd--- a/crates/openhuman-rpc/src/session_store/mod.rs+++ b/crates/openhuman-rpc/src/session_store/mod.rs@@@ -134,20 -134,84 +134,93 @@@ fn stores_at(workspace: &Path) -> Agent/// sweep runs; the workspace is resolved per call because the desktop rebinds/// it when a different user signs in.pub fn install() {- openhuman_core::agent::session_store::install(Arc::new(SqliteSessionStores::resolving(- openhuman_core::agent::session_store::context_workspace_dir,- )));+ log::debug!("[rpc:session_store] installing process-wide (context workspace)");+ crate::core_host::agent::session_store::install(provider());+}++/// [`SqliteSessionStores`] over the current context's workspace, as the+/// provider a runtime builder's `session_store` option takes (what+/// [`crate::host::tui`] wires). [`install`] installs the same provider+/// process-wide instead.+pub fn provider() -> Arc<dyn SessionStoreProvider> {+ Arc::new(SqliteSessionStores::resolving(+ crate::core_host::agent::session_store::context_workspace_dir,+ ))}+ /// Installs the session store the host's configuration asks for, before the+ /// core boots.+ ///+ /// With no storage URL (`OPENHUMAN_STORAGE_URL`, else `[storage] url`) this is+ /// [`install`]: the classic on-disk layout, unchanged. With one, the backend is+ /// opened, made the process's storage backend-/// ([`openhuman_core::storage::install`]), and TinyAgents'++/// ([`crate::core_host::storage::install`]), and TinyAgents'+ /// `DriverSessionStores` is installed over it: every agent's transcripts, turn+ /// states, records and journal in that backend, one storage scope per agent.+ ///+ /// A single-process backend (SQLite, memory, files) also interrupts an+ /// agent's in-flight turns the first time it is opened, since only an earlier+ /// process can have left them. MongoDB does not: several processes may share+ /// that database, and another one may own those turns.+ ///+ /// # Errors+ ///+ /// When a URL is configured but cannot be parsed or opened. A deployment that+ /// asked for a backend must not quietly fall back to local files.+ pub async fn install_for_host() -> anyhow::Result<()> {- let url = match std::env::var(openhuman_core::storage::STORAGE_URL_VAR) {++ let url = match std::env::var(crate::core_host::storage::STORAGE_URL_VAR) {+ Ok(url) if !url.trim().is_empty() => Some(url.trim().to_string()),- _ => match openhuman_core::config::rpc::load_config_with_timeout().await {- Ok(config) => openhuman_core::storage::configured_url(&config),++ _ => match crate::core_host::config::rpc::load_config_with_timeout().await {++ Ok(config) => crate::core_host::storage::configured_url(&config),+ // An unreadable config keeps the desktop booting on the classic+ // layout, as it always has. Remote deployments pin the backend+ // with `OPENHUMAN_STORAGE_URL`, which never reads the config.+ Err(error) => {+ tracing::warn!(+ "[session_store] config unavailable ({error}); keeping the on-disk layout"+ );+ None+ }+ },+ };+ install_for_url(url).await+ }++ /// [`install_for_host`] with the URL already resolved: `None` installs the+ /// classic on-disk store, a URL opens that backend and installs+ /// `DriverSessionStores` over it.+ ///+ /// # Errors+ ///+ /// When `url` cannot be parsed or opened.+ pub async fn install_for_url(url: Option<String>) -> anyhow::Result<()> {+ use anyhow::Context as _;++ let Some(url) = url else {+ // Drop a backend an earlier call installed, so storage operations do+ // not keep writing to it while the classic layout is in force.- openhuman_core::storage::clear();++ crate::core_host::storage::clear();+ install();+ return Ok(());+ };- let backend = openhuman_core::storage::open(&url)++ let backend = crate::core_host::storage::open(&url)+ .await+ .context("opening the configured storage backend")?;- let single_process = !openhuman_core::storage::driver_is_shared(backend.driver());++ let single_process = !crate::core_host::storage::driver_is_shared(backend.driver());+ let provider = tinyagents_session::DriverSessionStores::new(Arc::clone(&backend))+ .context("starting the session store bridge")?+ .recover_on_open(single_process);+ // Only a fully working bridge makes the backend the process's storage.- openhuman_core::storage::install(backend);++ crate::core_host::storage::install(backend);+ tracing::info!(+ target: "openhuman_rpc::session_store",+ recover_on_open = single_process,+ "[session_store] installed the storage-backed session store"+ );- openhuman_core::agent::session_store::install(Arc::new(provider));++ crate::core_host::agent::session_store::install(Arc::new(provider));+ Ok(())+ }+#[cfg(test)]#[path = "mod_tests.rs"]mod tests;diff --cc crates/openhuman-rpc/src/session_store/mod_tests.rsindex 009c79c204,f1829d18d3..0c7abd73fd--- a/crates/openhuman-rpc/src/session_store/mod_tests.rs+++ b/crates/openhuman-rpc/src/session_store/mod_tests.rs@@@ -48,3 -48,131 +48,131 @@@ fn recovery_interrupts_turns_left_in_flSome(TurnLifecycle::Interrupted));}++ /// The provider and storage slots are process-wide; these tests take turns.+ static SLOTS: Mutex<()> = Mutex::new(());++ /// Puts the process-global storage backend back as a test found it.-fn restore_backend(previous: Option<Arc<dyn openhuman_core::storage::StorageBackend>>) {++fn restore_backend(previous: Option<Arc<dyn crate::core_host::storage::StorageBackend>>) {+ match previous {+ Some(backend) => {- openhuman_core::storage::install(backend);++ crate::core_host::storage::install(backend);+ }+ None => {- openhuman_core::storage::clear();++ crate::core_host::storage::clear();+ }+ }+ }++ #[tokio::test]+ async fn a_storage_url_installs_the_driver_backed_store() {+ let _turn = SLOTS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);- let previous = openhuman_core::agent::session_store::installed();- let previous_backend = openhuman_core::storage::installed();++ let previous = crate::core_host::agent::session_store::installed();++ let previous_backend = crate::core_host::storage::installed();+ install_for_url(Some("memory".into())).await.unwrap();+- let provider = openhuman_core::agent::session_store::installed().unwrap();++ let provider = crate::core_host::agent::session_store::installed().unwrap();+ assert!(+ provider+ .destination_key()+ .is_some_and(|key| key.starts_with("memory://")),+ "{:?}",+ provider.destination_key()+ );+ assert_eq!(- openhuman_core::storage::installed().map(|b| b.driver()),++ crate::core_host::storage::installed().map(|b| b.driver()),+ Some("memory")+ );+ // Agents are kept apart in the shared backend.+ let alice = provider.for_agent("alice");+ alice+ .turn_states+ .put(&TurnState::started("t", "r", 8, "2026-01-01T00:00:00Z"))+ .unwrap();+ assert!(provider+ .for_agent("bob")+ .turn_states+ .get("t")+ .unwrap()+ .is_none());++ restore_backend(previous_backend);- openhuman_core::agent::session_store::restore(previous);++ crate::core_host::agent::session_store::restore(previous);+ }++ #[tokio::test]+ async fn no_url_keeps_the_classic_layout() {+ let _turn = SLOTS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);- let previous = openhuman_core::agent::session_store::installed();- let previous_backend = openhuman_core::storage::installed();++ let previous = crate::core_host::agent::session_store::installed();++ let previous_backend = crate::core_host::storage::installed();+ install_for_url(None).await.unwrap();- let provider = openhuman_core::agent::session_store::installed().unwrap();++ let provider = crate::core_host::agent::session_store::installed().unwrap();+ assert!(+ provider.workspace_dir().is_some(),+ "the file layout is installed"+ );- assert!(openhuman_core::storage::installed().is_none());++ assert!(crate::core_host::storage::installed().is_none());+ restore_backend(previous_backend);- openhuman_core::agent::session_store::restore(previous);++ crate::core_host::agent::session_store::restore(previous);+ }++ #[tokio::test]+ async fn an_unusable_url_fails_the_boot() {+ let _turn = SLOTS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);- let previous = openhuman_core::agent::session_store::installed();++ let previous = crate::core_host::agent::session_store::installed();+ let error = install_for_url(Some("ftp://nowhere".into()))+ .await+ .unwrap_err();+ assert!(format!("{error:#}").contains("storage"), "{error:#}");- openhuman_core::agent::session_store::restore(previous);++ crate::core_host::agent::session_store::restore(previous);+ }++ #[tokio::test]+ async fn restoring_the_classic_layout_clears_a_previous_backend() {+ let _turn = SLOTS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);- let previous = openhuman_core::agent::session_store::installed();- let previous_backend = openhuman_core::storage::installed();++ let previous = crate::core_host::agent::session_store::installed();++ let previous_backend = crate::core_host::storage::installed();+ install_for_url(Some("memory".into())).await.unwrap();- assert!(openhuman_core::storage::installed().is_some());++ assert!(crate::core_host::storage::installed().is_some());+ install_for_url(None).await.unwrap();- assert!(openhuman_core::storage::installed().is_none());++ assert!(crate::core_host::storage::installed().is_none());+ restore_backend(previous_backend);- openhuman_core::agent::session_store::restore(previous);++ crate::core_host::agent::session_store::restore(previous);+ }++ #[tokio::test]+ async fn the_host_reads_the_storage_url_from_the_environment() {+ let _turn = SLOTS+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner);- let previous = openhuman_core::agent::session_store::installed();- let previous_backend = openhuman_core::storage::installed();- let var = openhuman_core::storage::STORAGE_URL_VAR;++ let previous = crate::core_host::agent::session_store::installed();++ let previous_backend = crate::core_host::storage::installed();++ let var = crate::core_host::storage::STORAGE_URL_VAR;+ let old = std::env::var_os(var);++ std::env::set_var(var, " memory ");+ let booted = install_for_host().await;- let driver = openhuman_core::storage::installed().map(|b| b.driver());++ let driver = crate::core_host::storage::installed().map(|b| b.driver());++ std::env::set_var(var, "ftp://nowhere");+ let refused = install_for_host().await;++ match old {+ Some(value) => std::env::set_var(var, value),+ None => std::env::remove_var(var),+ }+ restore_backend(previous_backend);- openhuman_core::agent::session_store::restore(previous);++ crate::core_host::agent::session_store::restore(previous);++ booted.unwrap();+ assert_eq!(driver, Some("memory"));+ assert!(refused.is_err(), "an unusable env URL fails the boot");+ }diff --cc scripts/lib/feature-forwarding.mjsindex acf5cde4a6,fa1be7ad74..bf54b770d3--- a/scripts/lib/feature-forwarding.mjs+++ b/scripts/lib/feature-forwarding.mjs@@@ -451,18 -454,8 +455,16 @@@ export const CHAIN_LOCAL_GATES ='openhuman-tinyhumans': {jev: 'This crate owns the gate: the Jev-backed `tool_search` ranker (`tinytools-jev` over the TinyHumans System One proxy).',},+ 'openhuman-rpc': {+ 'http-client':+ 'The authenticated JSON-RPC HTTP client (`post_json_rpc`); transport code this crate owns, with no core twin.',+ server:+ "The core's JSON-RPC server (router, Socket.IO, listener) and the shared host boot; lives only in this crate.",+ 'session-store':+ 'The on-disk session store (`session_store`) behind the TinyAgents port; a host-side provider, not a core gate.',+ },'openhuman-cli': {'bin-tools': 'CLI argument parsing + logger init for the `openhuman-fleet` binary.',- 'rss-bench-dhat':- 'dhat heap profiling for the `library-profile` binary; perturbs RSS, so it is opt-in and has no core twin.',},};