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(server): replace `crate::` paths with `openhuman_core::` and `crate::server::` equivalents
Steven Enamakelbfcf722ebbee
diff --git a/crates/openhuman-rpc/src/server/classify.rs b/crates/openhuman-rpc/src/server/classify.rsnew file mode 100644index 0000000000..766c5a8af1--- /dev/null+++ b/crates/openhuman-rpc/src/server/classify.rs@@ -0,0 +1,132 @@+//! How the `/rpc` handler reports a failed call.+//!+//! [`classify_failure`] is pure so the routing can be tested without a server.+//! Whether an error is a session expiry is core's call+//! ([`openhuman_core::core::session_expiry`]); this module only decides how+//! loudly the transport reports it.++use openhuman_core::core::session_expiry::is_session_expired_error;++/// Returns `true` when the error is the wallet's "not configured yet" message.+///+/// Wallet-backed RPCs return+/// [`openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE`] before+/// setup. That is expected user state, not an internal failure.+///+/// Matched against the shared wallet constant (exact equality) so a wording+/// change in the wallet layer fails the coupling test in `classify_tests.rs`+/// rather than silently letting the noise back into Sentry.+pub(super) fn is_wallet_not_configured_error(msg: &str) -> bool {+ msg == openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE+}++/// How the `/rpc` handler reports a failed call, in priority order.+///+/// Only [`FailureDisposition::Unexpected`] is an error-level Sentry event. The+/// rest are either expected boundary conditions or already reported elsewhere.+/// The JSON-RPC error returned to the caller is the same for every variant,+/// except that [`FailureDisposition::UsageProbeBackoff`] replaces the message.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(super) enum FailureDisposition {+ /// The controller's structured envelope set `expected_user_state` (stale+ /// thread refs and similar). Domains that surface their own expected+ /// user-state errors skip Sentry here uniformly.+ ExpectedUserState,+ /// A wallet-backed RPC cannot run before wallet setup. This is expected+ /// user state, not an internal failure.+ WalletNotConfigured,+ /// Param-validation failures ("unknown param 'x' for ns.fn", "missing+ /// required param 'x'", "invalid params: …") are pure boundary+ /// mismatches: either the caller is a frontend on a different release than+ /// the running core (OPENHUMAN-TAURI-20: v0.53.22 UI shipped `api_key`+ /// before the matching schema input landed in #1467) or it is straight+ /// client-bug input. Sentry cannot help — we can neither retro-fix+ /// already-shipped installs nor learn anything from the noise.+ ///+ /// Logged structurally with the body redacted: these messages embed+ /// caller-supplied param names and, for the `invalid params: …` shape, can+ /// carry deserialized values.+ ParamValidation,+ /// Session-expired bubbles up as an "error" but is an expected boundary+ /// condition (the auth handler clears the local token and the UI+ /// re-auths). Its messages are a small set of fixed strings with no+ /// caller-supplied content, so the full text is safe to log.+ SessionExpired,+ /// A `/teams/me/usage` probe that the failure-backoff in `team::ops`+ /// short-circuited within its window — i.e. an already-reported repeat.+ /// The first failure of the streak already hit the backend and reported+ /// normally; demoting the repeats is the flood control GH #4153 asks for+ /// (backpressure, not silent drop).+ ///+ /// The internal demotion marker must never reach the RPC client as the+ /// error message (CodeRabbit on #4153), so the handler replaces it with+ /// [`USAGE_BACKOFF_CLIENT_MESSAGE`].+ UsageProbeBackoff,+ /// A downstream call (backend_api / integrations / provider) already+ /// demoted the underlying transient failure to a warn. Re-reporting at+ /// error level would re-create the Sentry noise the lower-layer demote was+ /// meant to avoid (#8Z, #93, #8W, #96).+ ///+ /// The message is upstream-derived (backend / provider response) and can+ /// carry URL fragments, query params, or provider error text that+ /// includes tokens, so it is logged only after `sanitize_api_error`.+ TransientDownstream,+ /// An unrecognised RPC method is a transport-boundary mismatch (infra+ /// probe traffic, or a client on a different release than the running+ /// core), not an actionable core defect (#3567).+ ///+ /// Known external probes (`probe == true`) never become real methods, so+ /// they are debug-only and never reach Sentry. Any other unknown method is+ /// still recorded for triage, at warn severity (captured, no page).+ UnknownMethod { probe: bool },+ /// The caller submitted an ingest payload that does not match the+ /// canonicaliser schema for its `source_kind` (#5169). The handler already+ /// returned a precise error naming the missing or malformed field, and no+ /// core-side change can fix a producer sending the wrong shape. Still+ /// captured for triage (a spike means a producer regressed), but at warn+ /// severity so it does not page.+ InvalidIngestPayload,+ /// Everything else: reported through+ /// `observability::report_error_or_expected`.+ Unexpected,+}++/// What the caller sees instead of the usage-probe backoff marker.+pub(super) const USAGE_BACKOFF_CLIENT_MESSAGE: &str =+ "Usage temporarily unavailable — the last fetch failed and is backing off; \+ it will refresh shortly.";++/// Classify a failed call's display message. `expected_user_state` is the+/// flag from the controller's structured envelope, when it emitted one.+///+/// The order is significant: the first matching rule wins, exactly as the+/// handler's `if`/`else` chain did before it was extracted.+pub(super) fn classify_failure(message: &str, expected_user_state: bool) -> FailureDisposition {+ use openhuman_core::core::observability;++ if expected_user_state {+ FailureDisposition::ExpectedUserState+ } else if is_wallet_not_configured_error(message) {+ FailureDisposition::WalletNotConfigured+ } else if openhuman_core::core::params::is_param_validation_error(message) {+ FailureDisposition::ParamValidation+ } else if is_session_expired_error(message) {+ FailureDisposition::SessionExpired+ } else if observability::is_suppressed_usage_probe_backoff(message) {+ FailureDisposition::UsageProbeBackoff+ } else if observability::is_transient_message_failure(message) {+ FailureDisposition::TransientDownstream+ } else if let Some(unknown_method) = openhuman_core::core::dispatch::unknown_method_name(message) {+ FailureDisposition::UnknownMethod {+ probe: openhuman_core::core::dispatch::is_known_probe_method(unknown_method),+ }+ } else if openhuman_core::memory::tree::tree::rpc::is_invalid_ingest_payload_message(message) {+ FailureDisposition::InvalidIngestPayload+ } else {+ FailureDisposition::Unexpected+ }+}++#[cfg(test)]+#[path = "classify_tests.rs"]+mod tests;diff --git a/crates/openhuman-rpc/src/server/classify_tests.rs b/crates/openhuman-rpc/src/server/classify_tests.rsnew file mode 100644index 0000000000..ea6b480fb2--- /dev/null+++ b/crates/openhuman-rpc/src/server/classify_tests.rs@@ -0,0 +1,95 @@+use super::{classify_failure, is_wallet_not_configured_error, FailureDisposition};++#[test]+fn is_wallet_not_configured_error_matches_wallet_constant() {+ // The classifier keys off the wallet layer's exact "not configured"+ // message so wallet-backed RPCs stay out of Sentry.+ assert!(is_wallet_not_configured_error(+ openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE+ ));+}++#[test]+fn is_wallet_not_configured_error_is_coupled_to_the_wallet_constant() {+ // Drift guard: if the wallet wording changes without updating the shared+ // constant the classifier matches, this fails — preventing the noise from+ // silently returning to Sentry. Mirrors the param-validation prefix locks.+ assert_eq!(+ openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE,+ "wallet is not configured; run wallet setup first"+ );+}++#[test]+fn is_wallet_not_configured_error_does_not_match_other_errors() {+ // Other wallet/seed-derivation failures (decrypt, key derivation, locked+ // keychain) are real defects and must keep reaching Sentry.+ assert!(!is_wallet_not_configured_error(+ "wallet signer init: bad seed"+ ));+ assert!(!is_wallet_not_configured_error(+ "decrypt secret: kms timeout"+ ));+ assert!(!is_wallet_not_configured_error(""));+ // Substring-only must not qualify — exact equality is required.+ assert!(!is_wallet_not_configured_error(+ "rpc failed: wallet is not configured; run wallet setup first"+ ));+}++#[test]+fn classify_failure_expected_user_state_flag_wins() {+ // The envelope flag outranks every message-based rule, even a message+ // that would otherwise read as a session expiry.+ assert_eq!(+ classify_failure("Session expired", true),+ FailureDisposition::ExpectedUserState+ );+}++#[test]+fn classify_failure_routes_each_boundary_class() {+ assert_eq!(+ classify_failure(openhuman_core::web3::wallet::WALLET_NOT_CONFIGURED_MESSAGE, false),+ FailureDisposition::WalletNotConfigured+ );+ assert_eq!(+ classify_failure(+ &openhuman_core::core::params::unknown_param_message("api_key", "config", "update_model_settings"),+ false+ ),+ FailureDisposition::ParamValidation+ );+ assert_eq!(+ classify_failure("GET /teams failed (401 Unauthorized): {}", false),+ FailureDisposition::SessionExpired+ );+ assert_eq!(+ classify_failure(+ &format!(+ "{}totally.made.up.method",+ openhuman_core::core::dispatch::UNKNOWN_METHOD_PREFIX+ ),+ false+ ),+ FailureDisposition::UnknownMethod { probe: false }+ );+ assert_eq!(+ classify_failure("config.update_model_settings: store write failed", false),+ FailureDisposition::Unexpected+ );+}++#[test]+fn classify_failure_param_validation_outranks_session_expiry() {+ // A param description that happens to contain a session marker is still a+ // params mismatch: validation runs before the handler, so no backend call+ // could have expired anything.+ assert_eq!(+ classify_failure(+ &openhuman_core::core::params::missing_required_param_message("token", "Session expired token"),+ false+ ),+ FailureDisposition::ParamValidation+ );+}diff --git a/crates/openhuman-rpc/src/server/dev_connect.rs b/crates/openhuman-rpc/src/server/dev_connect.rsindex 30dab6c788..52b4dffdb5 100644--- a/crates/openhuman-rpc/src/server/dev_connect.rs+++ b/crates/openhuman-rpc/src/server/dev_connect.rs@@ -1,7 +1,7 @@//! `GET /dev/connect` — hand this core to a browser-hosted dev renderer.//!//! The desktop shell mints the RPC bearer per launch and keeps it in memory-//! (see [`crate::core::auth`]), so nothing on disk lets a browser tab reach the+//! (see [`openhuman_core::core::auth`]), so nothing on disk lets a browser tab reach the//! running desktop core. This route closes that gap for development: it//! redirects to a loopback Vite dev server's `/__dev-connect` page with the//! RPC URL and bearer in the URL **fragment**, and that page seeds them into@@ -141,7 +141,7 @@ pub async fn dev_connect_handler();};- let Some(token) = crate::core::auth::get_rpc_token() else {+ let Some(token) = openhuman_core::core::auth::get_rpc_token() else {return refuse(StatusCode::SERVICE_UNAVAILABLE, "core has no RPC token yet");};diff --git a/crates/openhuman-rpc/src/server/http/cors.rs b/crates/openhuman-rpc/src/server/http/cors.rsindex da2ec9f230..be3b1d44a6 100644--- a/crates/openhuman-rpc/src/server/http/cors.rs+++ b/crates/openhuman-rpc/src/server/http/cors.rs@@ -1,7 +1,7 @@//! CORS for the core's HTTP API.//!//! The origin allowlist itself is the shared wire rule in-//! [`crate::rpc::is_origin_allowed_with_extra`]; this module reads the+//! [`crate::is_origin_allowed_with_extra`]; this module reads the//! operator's extra origins from the environment and shapes the headers.use axum::extract::Request;@@ -10,10 +10,10 @@ use axum::middleware::Next;use axum::response::{IntoResponse, Response};/// Decides whether a browser `Origin` header value is allowed, including the-/// operator's extra origins from [`crate::rpc::ALLOWED_ORIGINS_ENV`].+/// operator's extra origins from [`crate::ALLOWED_ORIGINS_ENV`].pub(crate) fn is_origin_allowed(origin: &str) -> bool {- let extra_origins = std::env::var(crate::rpc::ALLOWED_ORIGINS_ENV).ok();- crate::rpc::is_origin_allowed_with_extra(origin, extra_origins.as_deref())+ let extra_origins = std::env::var(crate::ALLOWED_ORIGINS_ENV).ok();+ crate::is_origin_allowed_with_extra(origin, extra_origins.as_deref())}/// Middleware for handling Cross-Origin Resource Sharing (CORS).diff --git a/crates/openhuman-rpc/src/server/http/dictation.rs b/crates/openhuman-rpc/src/server/http/dictation.rsindex 9ddb979cd7..c28cf2435f 100644--- a/crates/openhuman-rpc/src/server/http/dictation.rs+++ b/crates/openhuman-rpc/src/server/http/dictation.rs@@ -42,7 +42,7 @@ pub(super) async fn dictation_ws_handler(.get(header::ORIGIN).and_then(|v| v.to_str().ok()).map(str::trim);- if !crate::core::socketio::origin_is_allowed(origin) {+ if !crate::server::socketio::origin_is_allowed(origin) {log::warn!("[ws] dictation upgrade rejected: disallowed origin {origin:?}");return (StatusCode::FORBIDDEN,@@ -63,7 +63,7 @@ pub(super) async fn dictation_ws_handler(.map(str::trim).filter(|s| !s.is_empty());let bearer_ok = header_token- .map(crate::core::auth::verify_bearer_token)+ .map(openhuman_core::core::auth::verify_bearer_token).unwrap_or(false);let bearer_ok = bearer_ok|| query@@ -71,7 +71,7 @@ pub(super) async fn dictation_ws_handler(.as_deref().map(str::trim).filter(|s| !s.is_empty())- .map(crate::core::auth::verify_bearer_token)+ .map(openhuman_core::core::auth::verify_bearer_token).unwrap_or(false);if !bearer_ok {log::warn!("[ws] dictation upgrade rejected: missing or invalid bearer token");@@ -87,13 +87,13 @@ pub(super) async fn dictation_ws_handler(}ws.on_upgrade(|socket| async move {- let config = match crate::config::rpc::load_config_with_timeout().await {+ let config = match openhuman_core::config::rpc::load_config_with_timeout().await {Ok(c) => Arc::new(c),Err(e) => {log::error!("[ws] failed to load config for dictation: {e}");return;}};- crate::voice::streaming::handle_dictation_ws(socket, config).await;+ openhuman_core::voice::streaming::handle_dictation_ws(socket, config).await;})}diff --git a/crates/openhuman-rpc/src/server/http/events.rs b/crates/openhuman-rpc/src/server/http/events.rsindex 88ec2e292a..8d113e42dd 100644--- a/crates/openhuman-rpc/src/server/http/events.rs+++ b/crates/openhuman-rpc/src/server/http/events.rs@@ -47,7 +47,7 @@ pub(super) async fn events_handler(.map(str::trim).filter(|s| !s.is_empty());let bearer_ok = bearer- .map(crate::core::auth::verify_bearer_token)+ .map(openhuman_core::core::auth::verify_bearer_token).unwrap_or(false);if !bearer_ok {@@ -71,7 +71,7 @@ pub(super) async fn events_handler().into_response();};- if !crate::core::event_bind_tokens::consume(&query.client_id, supplied_token) {+ if !openhuman_core::core::event_bind_tokens::consume(&query.client_id, supplied_token) {log::warn!("[events] reject subscribe: bind token invalid or expired (client_id_len={})",query.client_id.len()@@ -89,7 +89,7 @@ pub(super) async fn events_handler(}let client_id = query.client_id;- let rx = crate::web_chat::subscribe_web_channel_events();+ let rx = openhuman_core::web_chat::subscribe_web_channel_events();let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(move |item| -> Option<Result<Event, std::convert::Infallible>> {let event = match item {@@ -136,7 +136,7 @@ pub(super) async fn domain_events_handler(headers: axum::http::HeaderMap) -> Res.map(str::trim).filter(|s| !s.is_empty());let bearer_ok = bearer- .map(crate::core::auth::verify_bearer_token)+ .map(openhuman_core::core::auth::verify_bearer_token).unwrap_or(false);if !bearer_ok {@@ -153,7 +153,7 @@ pub(super) async fn domain_events_handler(headers: axum::http::HeaderMap) -> Res}// Read dashboard config for event stream settings.- let es_cfg = crate::config::rpc::load_config_with_timeout()+ let es_cfg = openhuman_core::config::rpc::load_config_with_timeout().await.map(|c| c.dashboard.event_stream).unwrap_or_default();@@ -166,7 +166,7 @@ pub(super) async fn domain_events_handler(headers: axum::http::HeaderMap) -> Res.into_response();}- let bus = match crate::core::bus::BUS.get() {+ let bus = match openhuman_core::core::bus::BUS.get() {Some(bus) => bus,None => {log::warn!("[events/domain] event bus not initialized");@@ -186,9 +186,9 @@ pub(super) async fn domain_events_handler(headers: axum::http::HeaderMap) -> Res// in this handler that can afford the authoritative read — it happens// per connection, not per event — and it refills the cache the row// stamping below relies on.- let active_workspace = crate::config::active_workspace_dir()+ let active_workspace = openhuman_core::config::active_workspace_dir().await- .map(|dir| crate::config::workspace_handle(&dir))+ .map(|dir| openhuman_core::config::workspace_handle(&dir)).map_err(|error| {log::warn!("[events/domain] could not resolve the active workspace ({error}); \@@ -245,9 +245,9 @@ pub(super) async fn domain_events_handler(headers: axum::http::HeaderMap) -> Res// publishes, so it should not want to. `None` means "not resolved// since the last workspace marker write", which the client treats as// unknown rather than as a mismatch.- let workspace = event.workspace_dir().map(crate::config::workspace_handle);- let active = crate::config::active_workspace_dir_cached()- .map(|dir| crate::config::workspace_handle(&dir));+ let workspace = event.workspace_dir().map(openhuman_core::config::workspace_handle);+ let active = openhuman_core::config::active_workspace_dir_cached()+ .map(|dir| openhuman_core::config::workspace_handle(&dir));let data = json!({"domain": domain,"event": event_name,diff --git a/crates/openhuman-rpc/src/server/http/health.rs b/crates/openhuman-rpc/src/server/http/health.rsindex b392242dc1..a8b5bf54f0 100644--- a/crates/openhuman-rpc/src/server/http/health.rs+++ b/crates/openhuman-rpc/src/server/http/health.rs@@ -6,7 +6,7 @@ use axum::response::IntoResponse;use axum::Json;use serde::Serialize;-use crate::core::types::AppState;+use openhuman_core::core::types::AppState;/// Handler for the health check endpoint.///@@ -17,8 +17,8 @@ use crate::core::types::AppState;/// flag and per-component buckets in the body so readiness probes and operators/// can still see partial failures.pub(super) async fn health_handler() -> impl IntoResponse {- let snapshot = crate::platform::health::snapshot();- let verdict = crate::platform::health::verdict(&snapshot);+ let snapshot = openhuman_core::platform::health::snapshot();+ let verdict = openhuman_core::platform::health::verdict(&snapshot);let status = if verdict.healthy {StatusCode::OK@@ -79,16 +79,16 @@ struct HttpMethodSchema {/// Human-readable description of what the method does.description: String,/// List of input parameters.- inputs: Vec<crate::core::FieldSchema>,+ inputs: Vec<openhuman_core::core::FieldSchema>,/// List of output fields.- outputs: Vec<crate::core::FieldSchema>,+ outputs: Vec<openhuman_core::core::FieldSchema>,}/// Aggregates schemas from all registered controllers into a single dump.////// Also includes built-in core methods like `core.ping` and `core.version`.fn build_http_schema_dump() -> HttpSchemaDump {- let mut methods: Vec<HttpMethodSchema> = crate::core::all::all_http_method_schemas()+ let mut methods: Vec<HttpMethodSchema> = openhuman_core::core::all::all_http_method_schemas().into_iter().map(|method| HttpMethodSchema {method: method.method,diff --git a/crates/openhuman-rpc/src/server/http/mod.rs b/crates/openhuman-rpc/src/server/http/mod.rsindex 418547a165..ba34f4b0d1 100644--- a/crates/openhuman-rpc/src/server/http/mod.rs+++ b/crates/openhuman-rpc/src/server/http/mod.rs@@ -2,7 +2,7 @@//!//! [`build_core_http_router`] assembles every route; each route family has its//! own module. Binding the listener and running the server belongs to-//! [`CoreRuntime::serve`](crate::core::runtime::CoreRuntime::serve).+//! [`CoreRuntime::serve`](openhuman_core::core::runtime::CoreRuntime::serve).use axum::extract::{DefaultBodyLimit, Request};use axum::http::StatusCode;@@ -12,7 +12,7 @@ use axum::routing::{get, post};use axum::{Json, Router};use serde_json::json;-use crate::core::types::AppState;+use openhuman_core::core::types::AppState;pub(crate) mod cors;mod dictation;@@ -71,10 +71,10 @@ pub fn build_core_http_router(socketio_enabled: bool) -> Router {// Dev-only: hand this core (URL + bearer) to a loopback Vite renderer..route("/dev/connect",- get(crate::core::dev_connect::dev_connect_handler),+ get(crate::server::dev_connect::dev_connect_handler),)// OpenAI-compatible inference endpoint (/v1/chat/completions, /v1/models)- .nest("/v1", crate::inference::http::router())+ .nest("/v1", openhuman_core::inference::http::router())// Apply `AppState` here so the outer router becomes `Router<()>` and// matches any state-less sub-router merged into it..with_state(AppState {@@ -84,12 +84,12 @@ pub fn build_core_http_router(socketio_enabled: bool) -> Router {let router = router.fallback(not_found_handler).layer(middleware::from_fn(http_request_log_middleware))- .layer(middleware::from_fn(crate::core::auth::rpc_auth_middleware))+ .layer(middleware::from_fn(crate::server::auth::rpc_auth_middleware)).layer(middleware::from_fn(cors::cors_middleware));if socketio_enabled {- let (socket_layer, io) = crate::core::socketio::attach_socketio();- crate::core::socketio::spawn_web_channel_bridge(io);+ let (socket_layer, io) = crate::server::socketio::attach_socketio();+ crate::server::socketio::spawn_web_channel_bridge(io);return router.layer(socket_layer);}@@ -126,9 +126,9 @@ async fn http_request_log_middleware(req: Request, next: Next) -> Response {/// Handler for the root endpoint, returning server information and available endpoints.async fn root_handler() -> impl IntoResponse {- let api_server = match crate::config::Config::load_or_init().await {- Ok(cfg) => crate::api::config::effective_backend_api_url(&cfg.api_url),- Err(_) => crate::api::config::effective_backend_api_url(&None),+ let api_server = match openhuman_core::config::Config::load_or_init().await {+ Ok(cfg) => openhuman_core::api::config::effective_backend_api_url(&cfg.api_url),+ Err(_) => openhuman_core::api::config::effective_backend_api_url(&None),};(diff --git a/crates/openhuman-rpc/src/server/http/oauth_mcp.rs b/crates/openhuman-rpc/src/server/http/oauth_mcp.rsindex 1739aca70e..a7cc5b64de 100644--- a/crates/openhuman-rpc/src/server/http/oauth_mcp.rs+++ b/crates/openhuman-rpc/src/server/http/oauth_mcp.rs@@ -63,7 +63,7 @@ pub(super) async fn oauth_mcp_callback_handler(log::info!("[oauth:mcp] callback received (state present); completing exchange");- let config = match crate::config::Config::load_or_init().await {+ let config = match openhuman_core::config::Config::load_or_init().await {Ok(c) => c,Err(e) => {log::warn!("[oauth:mcp] config load failed: {e}");@@ -74,7 +74,7 @@ pub(super) async fn oauth_mcp_callback_handler(}};- match crate::mcp::registry::oauth::complete(&config, &state, &code).await {+ match openhuman_core::mcp::registry::oauth::complete(&config, &state, &code).await {Ok(server_id) => {log::info!("[oauth:mcp] completed sign-in for server_id={server_id}");html(diff --git a/crates/openhuman-rpc/src/server/http/rpc_handler.rs b/crates/openhuman-rpc/src/server/http/rpc_handler.rsindex 71b685b385..1f6eb22aa4 100644--- a/crates/openhuman-rpc/src/server/http/rpc_handler.rs+++ b/crates/openhuman-rpc/src/server/http/rpc_handler.rs@@ -6,9 +6,9 @@ use axum::response::{IntoResponse, Response};use axum::Json;use super::super::classify::{classify_failure, FailureDisposition, USAGE_BACKOFF_CLIENT_MESSAGE};-use super::super::invoke_method;-use crate::core::types::AppState;-use crate::rpc::{+use openhuman_core::core::invoke::invoke_method;+use openhuman_core::core::types::AppState;+use crate::{RpcError, RpcFailure, RpcRequest, RpcSuccess, StructuredRpcError, JSONRPC_VERSION,SERVER_ERROR_CODE,};@@ -114,7 +114,7 @@ pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcReque}FailureDisposition::UnknownMethod { probe: false }| FailureDisposition::InvalidIngestPayload => {- crate::core::observability::report_warning_message(+ openhuman_core::core::observability::report_warning_message(display_message.as_str(),"rpc","invoke_method",@@ -122,7 +122,7 @@ pub async fn rpc_handler(State(state): State<AppState>, Json(req): Json<RpcReque);}FailureDisposition::Unexpected => {- crate::core::observability::report_error_or_expected(+ openhuman_core::core::observability::report_error_or_expected(display_message.as_str(),"rpc","invoke_method",diff --git a/crates/openhuman-rpc/src/server/http/rpc_handler_tests.rs b/crates/openhuman-rpc/src/server/http/rpc_handler_tests.rsindex 885d4fa126..9e209d1c8e 100644--- a/crates/openhuman-rpc/src/server/http/rpc_handler_tests.rs+++ b/crates/openhuman-rpc/src/server/http/rpc_handler_tests.rs@@ -3,8 +3,8 @@ use serde_json::json;use std::sync::Arc;use super::rpc_handler;-use crate::core::jsonrpc::default_state;-use crate::core::jsonrpc::testing::EnvVarGuard;+use openhuman_core::core::invoke::default_state;+use crate::server::testing::EnvVarGuard;#[tokio::test(flavor = "current_thread")]async fn structured_rpc_error_envelope_passes_through_generic_dispatch() {@@ -23,7 +23,7 @@ async fn structured_rpc_error_envelope_passes_through_generic_dispatch() {workspace.path().as_os_str().to_os_string(),)]);- let stale_thread_request = crate::rpc::RpcRequest {+ let stale_thread_request = crate::RpcRequest {jsonrpc: "2.0".to_string(),id: json!(7),method: "openhuman.threads_generate_title".to_string(),@@ -80,7 +80,7 @@ async fn thread_not_found_rpc_error_does_not_report_to_sentry() {// `report_error_message` are captured directly via// `sentry::capture_message` and must not be picked up here too// (otherwise this test sees double events).- if metadata.target() == crate::core::observability::REPORT_ERROR_TRACING_TARGET {+ if metadata.target() == openhuman_core::core::observability::REPORT_ERROR_TRACING_TARGET {return sentry::integrations::tracing::EventFilter::Ignore;}match *metadata.level() {@@ -92,7 +92,7 @@ async fn thread_not_found_rpc_error_does_not_report_to_sentry() {);let _subscriber_guard = tracing::subscriber::set_default(subscriber);- let stale_thread_request = crate::rpc::RpcRequest {+ let stale_thread_request = crate::RpcRequest {jsonrpc: "2.0".to_string(),id: json!(1),method: "openhuman.threads_message_append".to_string(),@@ -119,7 +119,7 @@ async fn thread_not_found_rpc_error_does_not_report_to_sentry() {"ThreadNotFound should not reach Sentry");- let unrelated_error_request = crate::rpc::RpcRequest {+ let unrelated_error_request = crate::RpcRequest {jsonrpc: "2.0".to_string(),id: json!(2),method: "core.not_a_real_method".to_string(),@@ -197,7 +197,7 @@ async fn unknown_method_severity_split_by_probe_allow_list() {// Mirror production: diagnostics from the report_* helpers are// captured directly via `sentry::capture_message`, so the bridge// must ignore their marker target to avoid double events.- if metadata.target() == crate::core::observability::REPORT_ERROR_TRACING_TARGET {+ if metadata.target() == openhuman_core::core::observability::REPORT_ERROR_TRACING_TARGET {return sentry::integrations::tracing::EventFilter::Ignore;}match *metadata.level() {@@ -210,7 +210,7 @@ async fn unknown_method_severity_split_by_probe_allow_list() {let _subscriber_guard = tracing::subscriber::set_default(subscriber);// (1) Allow-listed probe → debug-only, never reaches Sentry.- let probe_request = crate::rpc::RpcRequest {+ let probe_request = crate::RpcRequest {jsonrpc: "2.0".to_string(),id: json!(1),method: "rpc.discover".to_string(),@@ -234,7 +234,7 @@ async fn unknown_method_severity_split_by_probe_allow_list() {);// (2) Genuinely-unknown method → still captured, but at warn for triage.- let unknown_request = crate::rpc::RpcRequest {+ let unknown_request = crate::RpcRequest {jsonrpc: "2.0".to_string(),id: json!(2),method: "totally.made.up.method".to_string(),@@ -306,7 +306,7 @@ async fn invalid_ingest_payload_is_captured_at_warn_not_error() {let subscriber = tracing_subscriber::registry().with(sentry::integrations::tracing::layer().event_filter(|metadata| {- if metadata.target() == crate::core::observability::REPORT_ERROR_TRACING_TARGET {+ if metadata.target() == openhuman_core::core::observability::REPORT_ERROR_TRACING_TARGET {return sentry::integrations::tracing::EventFilter::Ignore;}match *metadata.level() {@@ -321,7 +321,7 @@ async fn invalid_ingest_payload_is_captured_at_warn_not_error() {// `platform` is genuinely required by `ChatBatch` (unlike `timestamp`,// which now defaults — see `chat_payload_without_timestamp_is_accepted`),// so this reaches the invalid-payload branch rather than succeeding.- let request = crate::rpc::RpcRequest {+ let request = crate::RpcRequest {jsonrpc: "2.0".to_string(),id: json!(1),method: "openhuman.memory_tree_ingest".to_string(),diff --git a/crates/openhuman-rpc/src/server/shims.rs b/crates/openhuman-rpc/src/server/shims.rsindex d11a32aa33..7ba8513f3d 100644--- a/crates/openhuman-rpc/src/server/shims.rs+++ b/crates/openhuman-rpc/src/server/shims.rs@@ -1,13 +1,12 @@//! Server entry points kept for the hosts that predate-//! [`CoreBuilder`](crate::core::runtime::CoreBuilder).+//! [`CoreBuilder`](openhuman_core::core::runtime::CoreBuilder).//!//! Each `run_server*` function is a thin shim that composes a `CoreBuilder`-//! and calls [`CoreRuntime::serve`](crate::core::runtime::CoreRuntime::serve).+//! and calls [`CoreRuntime::serve`](openhuman_core::core::runtime::CoreRuntime::serve).use tokio_util::sync::CancellationToken;/// Resolves the port for the core server from environment variables or defaults.-#[cfg(feature = "http-server")]pub(crate) fn core_port() -> u16 {std::env::var("OPENHUMAN_CORE_PORT").ok()@@ -16,7 +15,6 @@ pub(crate) fn core_port() -> u16 {}/// Resolves the bind address host for the core server from environment variables or defaults.-#[cfg(feature = "http-server")]pub(crate) fn core_host() -> String {std::env::var("OPENHUMAN_CORE_HOST").ok()@@ -46,7 +44,7 @@ pub async fn run_server(/// Runs the request/response-only HTTP API without detached background jobs.pub async fn run_server_headless(host: Option<&str>, port: Option<u16>) -> anyhow::Result<()> {- let services = crate::core::runtime::ServiceSet::headless_api();+ let services = openhuman_core::core::runtime::ServiceSet::headless_api();run_server_with_services(host, port, services, false, None, None, None).await}@@ -74,7 +72,7 @@ pub async fn run_server_embedded(/// When the caller already holds the per-launch RPC bearer in memory (the/// Tauri shell now that the core runs in-process — PR #1061), it should/// pass `Some(token)` so the embedded server can seed its auth subsystem-/// via [`crate::core::auth::init_rpc_token_with_value`] without ever+/// via [`openhuman_core::core::auth::init_rpc_token_with_value`] without ever/// reading `OPENHUMAN_CORE_TOKEN` from the process environment. Passing/// `None` preserves the env-as-config fallback (CLI / docker / cloud).pub async fn run_server_embedded_with_ready(@@ -107,7 +105,7 @@ async fn run_server_inner(ready_tx: Option<tokio::sync::oneshot::Sender<EmbeddedReadySignal>>,rpc_token: Option<std::sync::Arc<String>>,) -> anyhow::Result<()> {- let mut services = crate::core::runtime::ServiceSet::desktop();+ let mut services = openhuman_core::core::runtime::ServiceSet::desktop();services.socketio = socketio_enabled;run_server_with_services(host,@@ -124,7 +122,7 @@ async fn run_server_inner(async fn run_server_with_services(host: Option<&str>,port: Option<u16>,- services: crate::core::runtime::ServiceSet,+ services: openhuman_core::core::runtime::ServiceSet,embedded_core: bool,shutdown_token: Option<CancellationToken>,ready_tx: Option<tokio::sync::oneshot::Sender<EmbeddedReadySignal>>,@@ -137,15 +135,15 @@ async fn run_server_with_services(// Tauri shell; standalone splits CLI / Docker via `detect_standalone`).// See the pluggable-core work (`core::runtime`).let host_kind = if embedded_core {- crate::core::types::HostKind::TauriShell+ openhuman_core::core::types::HostKind::TauriShell} else {- crate::core::types::HostKind::detect_standalone()+ openhuman_core::core::types::HostKind::detect_standalone()};let token = match rpc_token {- Some(token) => crate::core::runtime::TokenSource::Fixed(token),- None => crate::core::runtime::TokenSource::EnvOrFile,+ Some(token) => openhuman_core::core::runtime::TokenSource::Fixed(token),+ None => openhuman_core::core::runtime::TokenSource::EnvOrFile,};- let mut builder = crate::core::runtime::CoreBuilder::new(host_kind)+ 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.@@ -164,10 +162,10 @@ async fn run_server_with_services(}fn apply_e2e_tool_groups(- builder: crate::core::runtime::CoreBuilder,-) -> crate::core::runtime::CoreBuilder {+ builder: openhuman_core::core::runtime::CoreBuilder,+) -> openhuman_core::core::runtime::CoreBuilder {if std::env::var_os("OPENHUMAN_E2E").is_some() {- builder.tool_groups(crate::tools::toolpacks::ToolGroups::advertised())+ builder.tool_groups(openhuman_core::tools::toolpacks::ToolGroups::advertised())} else {builder}diff --git a/crates/openhuman-rpc/src/server/shims_tests.rs b/crates/openhuman-rpc/src/server/shims_tests.rsindex 2a49bfbc54..25c807b8b9 100644--- a/crates/openhuman-rpc/src/server/shims_tests.rs+++ b/crates/openhuman-rpc/src/server/shims_tests.rs@@ -3,12 +3,12 @@ use std::time::Duration;use tokio_util::sync::CancellationToken;-use crate::core::jsonrpc::testing::EnvVarGuard;+use crate::server::testing::EnvVarGuard;#[test]fn e2e_environment_enables_advertised_tool_groups() {let _guard = EnvVarGuard::set_many(vec![("OPENHUMAN_E2E", "1".into())]);- let builder = crate::core::runtime::CoreBuilder::new(crate::core::types::HostKind::Cli);+ let builder = openhuman_core::core::runtime::CoreBuilder::new(openhuman_core::core::types::HostKind::Cli);let _ = super::apply_e2e_tool_groups(builder);}@@ -70,7 +70,7 @@ async fn wait_until_port_released(port: u16) {#[tokio::test]#[ignore = "calls full server bootstrap; leaks process-global state into sibling tests (#1552). Re-cover via integration test."]async fn shutdown_token_stops_axum_listener_within_timeout() {- let _signed_out_restore = crate::cron::scheduler_gate::SignedOutTestGuard::set(false);+ let _signed_out_restore = openhuman_core::cron::scheduler_gate::SignedOutTestGuard::set(false);let workspace = tempfile::tempdir().expect("workspace tempdir");diff --git a/crates/openhuman-rpc/src/server/socketio.rs b/crates/openhuman-rpc/src/server/socketio.rsindex c8454e9a39..fec8549f84 100644--- a/crates/openhuman-rpc/src/server/socketio.rs+++ b/crates/openhuman-rpc/src/server/socketio.rs@@ -1,12 +1,12 @@//! Socket.IO live-event bridge to the desktop shell.//!//! `spawn_web_channel_bridge` spawns one forwarding task per source. Domain-//! broadcast channels: web-chat events (`crate::web_chat`), dictation hotkeys-//! and transcription results (`crate::voice::dictation_listener`), overlay-//! attention bubbles (`crate::desktop::overlay::subscribe_attention_events`,+//! broadcast channels: web-chat events (`openhuman_core::web_chat`), dictation hotkeys+//! and transcription results (`openhuman_core::voice::dictation_listener`), overlay+//! attention bubbles (`openhuman_core::desktop::overlay::subscribe_attention_events`,//! see `desktop/overlay/README.md`), core notifications-//! (`crate::desktop::notifications`), and shell companion state-//! (`COMPANION_STATE_BUS`). `DomainEvent`s read off `crate::core::bus::BUS`:+//! (`openhuman_core::desktop::notifications`), and shell companion state+//! (`COMPANION_STATE_BUS`). `DomainEvent`s read off `openhuman_core::core::bus::BUS`://! session expiry, MCP setup secret requests, memory sync and tree-build//! progress, channel listener health, and active-workspace changes. Web-chat//! events go to the initiating client's room and the `thread:<id>` room@@ -41,11 +41,8 @@ use serde_json::Value;// construct them — so `serde` stays ungated and only the transport surface is// gated (type carve-out; see AGENTS.md and this module's `pub mod` in// `core::mod`, which is intentionally NOT gated).-#[cfg(feature = "http-server")]use serde_json::json;-#[cfg(feature = "http-server")]use socketioxide::extract::{AckSender, Data, SocketRef, TryData};-#[cfg(feature = "http-server")]use socketioxide::SocketIo;/// Shell-originated companion lifecycle events that still need to reach@@ -66,7 +63,6 @@ pub fn publish_companion_state_changed(payload: Value) -> usize {COMPANION_STATE_BUS.send(payload).unwrap_or_default()}-#[cfg(feature = "http-server")]fn subscribe_companion_state_changed() -> tokio::sync::broadcast::Receiver<Value> {COMPANION_STATE_BUS.subscribe()}@@ -78,7 +74,6 @@ fn subscribe_companion_state_changed() -> tokio::sync::broadcast::Receiver<Value/// into the JSON-RPC dispatcher or the web-chat orchestrator: an unauthenticated/// socket that never picked up the marker is allowed to receive broadcast-style/// events (read-only) but cannot trigger executable work.-#[cfg(feature = "http-server")]#[derive(Clone, Copy, Debug)]struct AuthedConnection;@@ -88,7 +83,6 @@ struct AuthedConnection;/// headers, so the handshake `auth` map is the only header-equivalent slot/// available for our per-process bearer. The socket-IO Node/JS clients all/// surface `io(url, { auth: { token: "<hex>" } })` for this.-#[cfg(feature = "http-server")]#[derive(Debug, Default, Deserialize)]struct HandshakeAuth {#[serde(default)]@@ -116,11 +110,10 @@ struct HandshakeAuth {/// A missing `Origin` header is treated as a native (non-browser) client/// and accepted — only the cross-origin browser-page case is the targeted/// bad actor here.-#[cfg(feature = "http-server")]pub(crate) fn origin_is_allowed(origin: Option<&str>) -> bool {origin_is_allowed_with_extra(origin,- std::env::var(crate::rpc::ALLOWED_ORIGINS_ENV)+ std::env::var(crate::ALLOWED_ORIGINS_ENV).ok().as_deref(),)@@ -135,7 +128,6 @@ pub(crate) fn origin_is_allowed(origin: Option<&str>) -> bool {/// still dropped here: the page loaded and every read RPC succeeded, but the/// socket was disconnected at handshake and pressing Send did nothing, with no/// error surfaced to the user.-#[cfg(feature = "http-server")]pub(crate) fn origin_is_allowed_with_extra(origin: Option<&str>,extra_origins: Option<&str>,@@ -180,7 +172,6 @@ pub(crate) fn origin_is_allowed_with_extra(}/// True when `socket` finished the handshake with a valid bearer token.-#[cfg(feature = "http-server")]fn socket_is_authed(socket: &SocketRef) -> bool {socket.extensions.get::<AuthedConnection>().is_some()}@@ -188,7 +179,6 @@ fn socket_is_authed(socket: &SocketRef) -> bool {/// Best-effort disconnect. Called when we discover an unauthenticated socket/// inside an event handler — the connect path already disconnects the bad/// origins / wrong tokens, so this is purely a defense-in-depth path.-#[cfg(feature = "http-server")]fn drop_unauthed(socket: &SocketRef, reason: &'static str) {log::warn!("[socketio] dropping unauthenticated socket id={} reason={}",@@ -198,7 +188,6 @@ fn drop_unauthed(socket: &SocketRef, reason: &'static str) {let _ = socket.clone().disconnect();}-#[cfg(feature = "http-server")]#[derive(Debug, Deserialize)]struct SocketRpcRequest {id: serde_json::Value,@@ -207,7 +196,6 @@ struct SocketRpcRequest {params: serde_json::Value,}-#[cfg(feature = "http-server")]#[derive(Debug, Deserialize)]struct ChatStartPayload {thread_id: String,@@ -231,7 +219,6 @@ struct ChatStartPayload {run_mode: Option<String>,}-#[cfg(feature = "http-server")]#[derive(Debug, Deserialize)]struct ChatCancelPayload {thread_id: String,@@ -242,14 +229,12 @@ struct ChatCancelPayload {request_id: Option<String>,}-#[cfg(feature = "http-server")]#[derive(Debug, Deserialize)]struct ThreadSubscribePayload {thread_id: String,}/// Reply to `thread:subscribe`, so a client can order a read after the join.-#[cfg(feature = "http-server")]#[derive(Debug, Serialize)]struct ThreadSubscribeAck {joined: bool,@@ -262,7 +247,6 @@ struct ThreadSubscribeAck {/// - `rpc:request`: Invoking JSON-RPC methods over WebSocket./// - `chat:start`: Initiating a new chat turn./// - `chat:cancel`: Aborting an active chat turn.-#[cfg(feature = "http-server")]pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {let (layer, io) = SocketIo::new_layer();@@ -300,7 +284,7 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {// `TryData` lets us treat a missing/malformed `auth` payload as a// soft failure (no panic) and reject the connect cleanly.let supplied = handshake.ok().and_then(|h| h.token).unwrap_or_default();- if !crate::core::auth::verify_bearer_token(&supplied) {+ if !openhuman_core::core::auth::verify_bearer_token(&supplied) {log::warn!("[socketio] rejecting connect: missing or invalid bearer client={}",client_id@@ -341,9 +325,9 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {let socket = socket.clone();let client_id = client_id.clone();tokio::spawn(async move {- match crate::config::active_workspace_snapshot().await {+ match openhuman_core::config::active_workspace_snapshot().await {Ok((dir, revision)) => {- let handle = crate::config::workspace_handle(&dir);+ let handle = openhuman_core::config::workspace_handle(&dir);// One snapshot, not two reads: resolved// separately, a switch between them would pair// this workspace with the *next* one's revision,@@ -383,8 +367,8 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {);// Invoke the method through the same logic used by the HTTP RPC endpoint.- let response = match crate::core::jsonrpc::invoke_method(- crate::core::jsonrpc::default_state(),+ let response = match openhuman_core::core::invoke::invoke_method(+ openhuman_core::core::invoke::default_state(),payload.method.as_str(),payload.params,)@@ -425,9 +409,9 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {payload.message.len());if let Some(run_mode) = payload.run_mode.as_deref() {- match crate::agent::tinyagents::run_mode::parse_mode_label(run_mode) {+ match openhuman_core::agent::tinyagents::run_mode::parse_mode_label(run_mode) {Some(mode) => {- crate::agent::tinyagents::run_mode::set_mode(&thread_id, mode);+ openhuman_core::agent::tinyagents::run_mode::set_mode(&thread_id, mode);}None => log::warn!("[socketio] chat:start thread_id={thread_id} ignoring unrecognized run_mode={run_mode}"@@ -436,7 +420,7 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {}// Trigger the web channel's chat logic.- match crate::web_chat::start_chat(+ match openhuman_core::web_chat::start_chat(&client_id,&payload.thread_id,&payload.message,@@ -444,7 +428,7 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {payload.temperature,payload.locale,payload.queue_mode,- crate::web_chat::ChatRequestMetadata::default(),+ openhuman_core::web_chat::ChatRequestMetadata::default(),).await{@@ -472,7 +456,7 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {// every other `chat_error`: by `error_type`, plus// a typed `guardrail` payload it doesn't have to// parse out of `message`.- if let crate::web_chat::StartChatError::Guardrail {+ if let openhuman_core::web_chat::StartChatError::Guardrail {verdict,score,reasons,@@ -505,7 +489,7 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {client_id,payload.thread_id);- let _ = crate::web_chat::cancel_chat_scoped(+ let _ = openhuman_core::web_chat::cancel_chat_scoped(&client_id,&payload.thread_id,payload.request_id.as_deref(),@@ -577,12 +561,11 @@ pub fn attach_socketio() -> (socketioxide::layer::SocketIoLayer, SocketIo) {/// 3. **Overlay Bridge**: Forwards attention bubble events to all clients./// 4. **Core Notification Bridge**: Forwards core notification events to all clients./// 5. **Transcription Bridge**: Forwards real-time speech-to-text results to all clients.-#[cfg(feature = "http-server")]pub fn spawn_web_channel_bridge(io: SocketIo) {// 1. Web channel events → per-client rooms.let io_web = io.clone();tokio::spawn(async move {- let mut rx = crate::web_chat::subscribe_web_channel_events();+ let mut rx = openhuman_core::web_chat::subscribe_web_channel_events();loop {let event = match rx.recv().await {Ok(event) => event,@@ -609,7 +592,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// 2. Dictation hotkey events → broadcast to all connected clients.tokio::spawn(async move {- let mut rx = crate::voice::dictation_listener::subscribe_dictation_events();+ let mut rx = openhuman_core::voice::dictation_listener::subscribe_dictation_events();loop {let event = match rx.recv().await {Ok(event) => event,@@ -659,7 +642,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// 3. Overlay attention events → broadcast to all clients.tokio::spawn(async move {- let mut rx = crate::desktop::overlay::subscribe_attention_events();+ let mut rx = openhuman_core::desktop::overlay::subscribe_attention_events();loop {let event = match rx.recv().await {Ok(event) => event,@@ -687,7 +670,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// chat session is active. Pattern mirrors the overlay attention// bridge above — fire-and-forget, no per-client routing.tokio::spawn(async move {- let mut rx = crate::desktop::notifications::subscribe_core_notifications();+ let mut rx = openhuman_core::desktop::notifications::subscribe_core_notifications();loop {let event = match rx.recv().await {Ok(event) => event,@@ -730,7 +713,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let max_attempts = (MAX_WAIT_SECS * 1000) / RETRY_INTERVAL_MS;let mut attempts: u64 = 0;loop {- if let Some(bus) = crate::core::bus::BUS.get() {+ if let Some(bus) = openhuman_core::core::bus::BUS.get() {break bus;}attempts += 1;@@ -749,13 +732,13 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let Some(event) = rx.recv().await else {break;};- if let crate::core::events::DomainEvent::SessionExpired { source, reason } = event {+ if let openhuman_core::core::events::DomainEvent::SessionExpired { source, reason } = event {// Other publishers may emit a backend 401 while this core is// using its offline local credential. The auth subscriber// correctly keeps that credential, so the UI must not receive// a contradictory sign-out event from this independent bus// consumer. Real JWT expiry still broadcasts as before.- if crate::security::credentials::session_support::current_session_is_local().await {+ if openhuman_core::security::credentials::session_support::current_session_is_local().await {log::info!("[socketio] suppress auth:session_expired for local offline credential source={}",source@@ -798,7 +781,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let max_attempts = (MAX_WAIT_SECS * 1000) / RETRY_INTERVAL_MS;let mut attempts: u64 = 0;loop {- if let Some(bus) = crate::core::bus::BUS.get() {+ if let Some(bus) = openhuman_core::core::bus::BUS.get() {break bus;}attempts += 1;@@ -817,12 +800,12 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let Some(event) = rx.recv().await else {break;};- if let crate::core::events::DomainEvent::ActiveWorkspaceChanged {+ if let openhuman_core::core::events::DomainEvent::ActiveWorkspaceChanged {workspace_dir,revision,} = event{- let handle = crate::config::workspace_handle(&workspace_dir);+ let handle = openhuman_core::config::workspace_handle(&workspace_dir);log::info!("[socketio] broadcast workspace_changed workspace={handle} revision={revision}");@@ -836,7 +819,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// 5. Transcription results → broadcast to all connected clients.tokio::spawn(async move {- let mut rx = crate::voice::dictation_listener::subscribe_transcription_results();+ let mut rx = openhuman_core::voice::dictation_listener::subscribe_transcription_results();loop {let text = match rx.recv().await {Ok(text) => text,@@ -869,7 +852,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let max_attempts = (MAX_WAIT_SECS * 1000) / RETRY_INTERVAL_MS;let mut attempts: u64 = 0;loop {- if let Some(bus) = crate::core::bus::BUS.get() {+ if let Some(bus) = openhuman_core::core::bus::BUS.get() {break bus;}attempts += 1;@@ -889,7 +872,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {break;};match event {- crate::core::events::DomainEvent::MemorySyncStageChanged {+ openhuman_core::core::events::DomainEvent::MemorySyncStageChanged {trigger,stage,provider,@@ -910,7 +893,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {});let _ = io_memory_sync.emit("memory:sync_stage", &payload);}- crate::core::events::DomainEvent::TreeSummarizerPropagated {+ openhuman_core::core::events::DomainEvent::TreeSummarizerPropagated {namespace,node_id,level,@@ -924,7 +907,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {});let _ = io_memory_sync.emit("memory:tree_progress", &payload);}- crate::core::events::DomainEvent::TreeSummarizerRebuildCompleted {+ openhuman_core::core::events::DomainEvent::TreeSummarizerRebuildCompleted {namespace,total_nodes,} => {@@ -934,7 +917,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {});let _ = io_memory_sync.emit("memory:tree_completed", &payload);}- crate::core::events::DomainEvent::MemoryTreeBuildProgress {+ openhuman_core::core::events::DomainEvent::MemoryTreeBuildProgress {phase,step,tree_scope,@@ -952,7 +935,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {});let _ = io_memory_sync.emit("memory:build_progress", &payload);}- crate::core::events::DomainEvent::HarnessInitProgress {+ openhuman_core::core::events::DomainEvent::HarnessInitProgress {step_id,state,message,@@ -966,7 +949,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {});let _ = io_memory_sync.emit("init:progress", &payload);}- crate::core::events::DomainEvent::HarnessInitCompleted {+ openhuman_core::core::events::DomainEvent::HarnessInitCompleted {overall,failed_required,} => {@@ -981,7 +964,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// truth and the Workflows UI keeps a 2s poller as fallback, so// a dropped event here (broadcast lag) only delays the live// update, never corrupts run history.- crate::core::events::DomainEvent::FlowRunProgress {+ openhuman_core::core::events::DomainEvent::FlowRunProgress {run_id,node_id,status,@@ -1006,7 +989,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// instead of waiting for the blocking `flows_run` RPC to// resolve or the first `FlowRunProgress` step. Best-effort,// same rationale as `flow:run_progress` above.- crate::core::events::DomainEvent::FlowRunStarted { flow_id, run_id } => {+ openhuman_core::core::events::DomainEvent::FlowRunStarted { flow_id, run_id } => {let payload = serde_json::json!({"flow_id": flow_id,"run_id": run_id,@@ -1025,7 +1008,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// canvas/sidebar can flip a run to Completed/Failed live// instead of relying on a poll to notice. Best-effort, same// rationale as the other `flow:*` bridges.- crate::core::events::DomainEvent::FlowRunFinished {+ openhuman_core::core::events::DomainEvent::FlowRunFinished {flow_id,run_id,status,@@ -1049,7 +1032,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// — most importantly, so an agent `save_workflow` becomes// visible in a canvas the user has open (audit F6). Best-effort;// the UI's refetch-on-focus is the backstop.- crate::core::events::DomainEvent::FlowChanged {+ openhuman_core::core::events::DomainEvent::FlowChanged {flow_id,kind,actor,@@ -1074,7 +1057,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {// bridge — because a flow run has no chat thread/client to// target; the Workflows UI listens process-wide and filters// by `flow_id`/`run_id` client-side.- crate::core::events::DomainEvent::FlowApprovalRequested {+ openhuman_core::core::events::DomainEvent::FlowApprovalRequested {request_id,flow_id,run_id,@@ -1119,7 +1102,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {let max_attempts = (MAX_WAIT_SECS * 1000) / RETRY_INTERVAL_MS;let mut attempts: u64 = 0;loop {- if let Some(bus) = crate::core::bus::BUS.get() {+ if let Some(bus) = openhuman_core::core::bus::BUS.get() {break bus;}attempts += 1;@@ -1139,7 +1122,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {break;};let payload = match event {- crate::core::events::DomainEvent::ChannelConnected { channel } => {+ openhuman_core::core::events::DomainEvent::ChannelConnected { channel } => {log::debug!("[socketio] broadcast channel:connection-updated {channel} -> connected");@@ -1149,7 +1132,7 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {None,))}- crate::core::events::DomainEvent::ChannelDisconnected { channel, reason } => {+ openhuman_core::core::events::DomainEvent::ChannelDisconnected { channel, reason } => {log::debug!("[socketio] broadcast channel:connection-updated {channel} -> error reason_len={}",reason.len()@@ -1178,7 +1161,6 @@ pub fn spawn_web_channel_bridge(io: SocketIo) {/// listener for telegram/discord); `last_error` carries the disconnect reason./// Matches the shape consumed by the frontend/// `normalizeChannelConnectionUpdatePayload`.-#[cfg(feature = "http-server")]pub(crate) fn channel_connection_update_payload(channel: &str,status: &str,@@ -1209,7 +1191,6 @@ pub(crate) fn channel_connection_update_payload(/// client told it is in a room it never joined reads the thread, waits for/// events that will never be routed to it, and reproduces the invisible-reply/// bug this room exists to prevent (#6034).-#[cfg(feature = "http-server")]fn join_room_logged(socket: &SocketRef, room: &str, client_id: &str) -> bool {match socket.join(room.to_string()) {Ok(()) => {@@ -1223,7 +1204,6 @@ fn join_room_logged(socket: &SocketRef, room: &str, client_id: &str) -> bool {}}-#[cfg(feature = "http-server")]fn emit_web_channel_event(io: &SocketIo, event: WebChannelEvent) {let name = event.event.clone();// Deliver to the initiating client's own room AND the per-thread room. The@@ -1286,10 +1266,8 @@ fn emit_web_channel_event(io: &SocketIo, event: WebChannelEvent) {/// is suppressed for exactly these. Enumerated explicitly rather than matched by/// a `*_delta` suffix, so a future *discrete* event whose name happens to end in/// `_delta` still gets its compat alias instead of being silently dropped.-#[cfg(feature = "http-server")]const STREAMING_DELTA_EVENTS: &[&str] = &["text_delta", "thinking_delta", "tool_args_delta"];-#[cfg(feature = "http-server")]fn event_alias(name: &str) -> Option<String> {// Match against the canonical underscore form after stripping a `subagent_`// prefix (subagent streaming mirrors the parent's deltas), so `text_delta`,@@ -1327,9 +1305,8 @@ fn event_alias(name: &str) -> Option<String> {/// safe to repeat: the client keys the card by `request_id` and a decided/// request is no longer parked, so a socket that already has the card just/// re-renders the same one.-#[cfg(feature = "http-server")]fn replay_parked_approval(socket: &SocketRef, thread_id: &str) {- let Some(gate) = crate::security::approval::ApprovalGate::try_global() else {+ let Some(gate) = openhuman_core::security::approval::ApprovalGate::try_global() else {return;};let Some(row) = gate.parked_request_for_thread(thread_id) else {@@ -1337,7 +1314,7 @@ fn replay_parked_approval(socket: &SocketRef, thread_id: &str) {};let client_id = socket.id.to_string();let expires_at = row.expires_at.map(|t| t.to_rfc3339());- let mut event = crate::web_chat::approval_request_event(+ let mut event = openhuman_core::web_chat::approval_request_event(&row.request_id,&row.tool_name,&row.action_summary,@@ -1350,7 +1327,7 @@ fn replay_parked_approval(socket: &SocketRef, thread_id: &str) {// Replay is a fresh emit to a newly-joined socket, not a resend of the// original event, so stamp `ts` with "now" (same clock as// `publish_web_channel_event`) rather than leaving it unset.- event.ts = Some(crate::web_chat::progress_bridge::unix_epoch_ms());+ event.ts = Some(openhuman_core::web_chat::progress_bridge::unix_epoch_ms());let Ok(payload) = serde_json::to_value(&event) else {return;};@@ -1366,14 +1343,13 @@ fn replay_parked_approval(socket: &SocketRef, thread_id: &str) {/// just joined that thread's room. Mirrors [`replay_parked_approval`] — a/// plan review is a live, in-memory park (no SQLite row), but it reaches the/// UI the same fire-and-forget way, so the same reconciliation applies.-#[cfg(feature = "http-server")]fn replay_parked_plan_review(socket: &SocketRef, thread_id: &str) {- let Some(row) = crate::agent::plan_review::gate::global().parked_review_for_thread(thread_id)+ let Some(row) = openhuman_core::agent::plan_review::gate::global().parked_review_for_thread(thread_id)else {return;};let client_id = socket.id.to_string();- let mut event = crate::web_chat::plan_review_request_event(+ let mut event = openhuman_core::web_chat::plan_review_request_event(&row.request_id,&row.summary,&row.steps,@@ -1382,7 +1358,7 @@ fn replay_parked_plan_review(socket: &SocketRef, thread_id: &str) {row.tool_call_id.as_deref(),row.expires_at.as_deref(),);- event.ts = Some(crate::web_chat::progress_bridge::unix_epoch_ms());+ event.ts = Some(openhuman_core::web_chat::progress_bridge::unix_epoch_ms());let Ok(payload) = serde_json::to_value(&event) else {return;};@@ -1393,7 +1369,6 @@ fn replay_parked_plan_review(socket: &SocketRef, thread_id: &str) {emit_with_aliases(socket, "plan_review_request", &payload);}-#[cfg(feature = "http-server")]fn emit_with_aliases(socket: &SocketRef, name: &str, payload: &serde_json::Value) {let _ = socket.emit(name, payload);if let Some(alias) = event_alias(name) {@@ -1403,6 +1378,6 @@ fn emit_with_aliases(socket: &SocketRef, name: &str, payload: &serde_json::Value// Every test here names a gated fn (`channel_connection_update_payload`,// `event_alias`, `origin_is_allowed`), so the module gates in lockstep (#5048).-#[cfg(all(test, feature = "http-server"))]+#[cfg(test)]#[path = "socketio_tests.rs"]mod tests;diff --git a/crates/openhuman-rpc/src/server/testing.rs b/crates/openhuman-rpc/src/server/testing.rsindex 0d5b161b3f..03f8b4f1fe 100644--- a/crates/openhuman-rpc/src/server/testing.rs+++ b/crates/openhuman-rpc/src/server/testing.rs@@ -10,7 +10,7 @@ pub(crate) struct EnvVarGuard {impl EnvVarGuard {pub(crate) fn set_many(vars: Vec<(&'static str, OsString)>) -> Self {- let lock = crate::config::TEST_ENV_LOCK+ let lock = openhuman_core::config::TEST_ENV_LOCK.lock().expect("test env lock poisoned");let mut old_values = Vec::with_capacity(vars.len());