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 remote-tracking branch 'refs/remotes/upstream/main' into pr/6703
Steven Enamakelbc24f956677a
diff --cc crates/openhuman-core/Cargo.tomlindex 72044fce1b,ecbd58ff1b..11a3da8d85--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@@ -61,8 -59,9 +61,8 @@@ path = "src/lib.rscrate-type = ["rlib"][dependencies]-openhuman-rpc.workspace = true# The TinyHumans SDK is deliberately NOT a dependency of the core. The core- # reaches the hosted backend only through `api::transport::BackendTransport`;+ # reaches the hosted backend only through `backend::transport::BackendTransport`;# the SDK-backed implementation is `crates/openhuman-tinyhumans`, which hosts# install at boot. `scripts/assert-shed.sh` / `cargo tree -i tinyhumans-sdk`# must stay empty for this package.diff --cc crates/openhuman-core/src/channels/controllers/backend.rsindex c2d2daf0c2,a28ac0e99d..2022c4fc65--- a/crates/openhuman-core/src/channels/controllers/backend.rs+++ b/crates/openhuman-core/src/channels/controllers/backend.rs@@@ -39,7 -39,19 +39,19 @@@ impl OpenHumanChannelBackend}}+ /// The managed-bot link flows need a TinyHumans account, so the core does not+ /// serve them: `openhuman-tinyhumans` registers `channels.telegram_login_*` /+ /// `channels.discord_link_*` itself (`hosted::channel_link`). The contract+ /// still requires these methods; nothing in the core dispatches them.+ fn hosted_link_unavailable<T>(method: &str) -> anyhow::Result<T> {+ log::debug!("[channels][backend] {method} is served by openhuman-tinyhumans, not the core");+ anyhow::bail!(+ "{}channels.{method} is provided by the hosted TinyHumans layer",+ crate::core::observability::BACKEND_UNAVAILABLE_PREFIX+ )+ }+-fn into_anyhow<T>(result: Result<RpcOutcome<T>, String>) -> anyhow::Result<T> {+fn into_anyhow<T>(result: Result<Outcome<T>, String>) -> anyhow::Result<T> {result.map(|outcome| outcome.value).map_err(anyhow::Error::msg)diff --cc crates/openhuman-core/src/channels/controllers/ops/discord.rsindex 7b1411bca2,8f077f12a1..39921b252d--- a/crates/openhuman-core/src/channels/controllers/ops/discord.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/discord.rs@@@ -1,12 -1,10 +1,10 @@@- //! Discord managed link flow and guild/channel discovery.+ //! Discord guild/channel discovery for the bot-token connection.+ //!+ //! The managed link flow (`channels.discord_link_*`) needs a TinyHumans+ //! account and lives in `openhuman-tinyhumans` (`hosted::channel_link`).- use serde_json::Value;-- use crate::api::config::effective_backend_api_url;- use crate::api::jwt::get_session_token;- use crate::api::rest::BackendOAuthClient;use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;use crate::security::credentials;use super::super::definitions::ChannelAuthMode;diff --cc crates/openhuman-core/src/channels/controllers/ops/messaging.rsindex d4c73385bf,cf417d3e38..ebb5773fcf--- a/crates/openhuman-core/src/channels/controllers/ops/messaging.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/messaging.rs@@@ -2,19 -2,18 +2,18 @@@use serde_json::Value;- use crate::api::config::effective_backend_api_url;- use crate::api::jwt::get_session_token;- use crate::api::rest::BackendOAuthClient;+ use crate::backend::BackendClient;use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;+ use crate::security::credentials::jwt::get_session_token;/// Send a rich message to a channel via the backend API.pub async fn channel_send_message(config: &Config,channel: &str,message: Value,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;let jwt = get_session_token(config)?.ok_or_else(|| "session JWT required; complete login first".to_string())?;@@@ -40,8 -44,8 +44,8 @@@ pub async fn channel_send_reactionconfig: &Config,channel: &str,reaction: Value,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;let jwt = get_session_token(config)?.ok_or_else(|| "session JWT required; complete login first".to_string())?;@@@ -67,8 -76,8 +76,8 @@@ pub async fn channel_create_threadconfig: &Config,channel: &str,title: &str,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;let jwt = get_session_token(config)?.ok_or_else(|| "session JWT required; complete login first".to_string())?;@@@ -96,8 -110,8 +110,8 @@@ pub async fn channel_update_threadchannel: &str,thread_id: &str,action: &str,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;let jwt = get_session_token(config)?.ok_or_else(|| "session JWT required; complete login first".to_string())?;@@@ -125,8 -144,8 +144,8 @@@ pub async fn channel_list_threadsconfig: &Config,channel: &str,active: Option<bool>,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);+ let api_url = crate::backend::require_base_url(&config.api_url)?;let jwt = get_session_token(config)?.ok_or_else(|| "session JWT required; complete login first".to_string())?;diff --cc crates/openhuman-core/src/channels/controllers/schemas.rsindex 7c91480049,55e3a67ebf..f24c9d66d7--- a/crates/openhuman-core/src/channels/controllers/schemas.rs+++ b/crates/openhuman-core/src/channels/controllers/schemas.rs@@@ -7,8 -7,8 +7,8 @@@ use serde_json::{Map, Value}use crate::config::rpc as config_rpc;use crate::config::Config;use crate::core::all::{ControllerFuture, RegisteredController};+ use crate::core::ControllerSchema;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;- use crate::core::{ControllerSchema, FieldSchema, TypeSchema};use super::backend::OpenHumanChannelBackend;use super::definitions::ChannelAuthMode;diff --cc crates/openhuman-core/src/config/ops/model.rsindex eab63b6f00,5d21212f1d..cc8bde3869--- a/crates/openhuman-core/src/config/ops/model.rs+++ b/crates/openhuman-core/src/config/ops/model.rs@@@ -715,17 -715,20 +715,20 @@@ pub async fn get_composio_trigger_setti))}- /// Resolve the hosted backend URL, excluding local or third-party inference- /// overrides that must never receive OpenHuman session credentials.- pub(crate) fn resolve_backend_api_url(config: &Config) -> String {- crate::api::config::effective_backend_api_url(&config.api_url)+ /// Resolve the hosted backend URL through the installed backend transport,+ /// which excludes local or third-party inference overrides that must never+ /// receive OpenHuman session credentials. `None` when no transport is+ /// installed (no hosted backend).+ pub(crate) fn resolve_backend_api_url(config: &Config) -> Option<String> {+ crate::backend::base_url(&config.api_url).ok()}- /// Resolves the effective backend API URL from configuration or defaults.+ /// Resolves the effective backend API URL from configuration or defaults;+ /// `api_url` is `null` when the core has no hosted backend.-pub async fn load_and_resolve_api_url() -> Result<RpcOutcome<serde_json::Value>, String> {+pub async fn load_and_resolve_api_url() -> Result<Outcome<serde_json::Value>, String> {let config = load_config_with_timeout().await?;let resolved = resolve_backend_api_url(&config);- Ok(RpcOutcome::new(+ Ok(Outcome::new(serde_json::json!({ "api_url": resolved }),Vec::new(),))diff --cc crates/openhuman-core/src/core/runtime/subscribers.rsindex bdd0f00fc6,0000000000..df0bb73913mode 100644,000000..100644--- a/crates/openhuman-core/src/core/runtime/subscribers.rs+++ b/crates/openhuman-core/src/core/runtime/subscribers.rs@@@ -1,503 -1,0 +1,503 @@@+//! Process-wide event-bus subscriber registration for the core boot.+//!+//! [`register_domain_subscribers`] runs from+//! [`bootstrap_core_runtime`](super::bootstrap::bootstrap_core_runtime) on every+//! boot. Ungated infrastructure registers once per process; each gated+//! [`DomainGroup`](crate::core::all::DomainGroup) registers the first time a+//! boot enables it.++/// Per-`DomainGroup` gating decision for each event-bus subscriber that+/// [`register_domain_subscribers`] conditionally registers. Extracted as a+/// pure value so the subscriber→group mapping has a single source of truth+/// that the registrar consumes and tests assert directly — without registering+/// real subscribers or touching the process-global event bus (#4796 DoD item 3).+///+/// Unlisted subscribers (health, scheduler-gate, TokenJuice content-router,+/// session-token seeding, `SessionExpired`, service restart/shutdown) are+/// always registered as core/platform infra and intentionally absent here.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct DomainSubscriberPlan {+ /// Reserved for subscribers with no family of their own. Currently none:+ /// the reorg gave every subscriber that used to live here a real family+ /// (see the fields below), so this stays for future kernel-level ones.+ pub platform: bool,+ /// composio trigger archive + trigger subscriber + task-sources poller.+ pub integrations: bool,+ /// device tunnel handshake/peer-status subscriber.+ pub security: bool,+ /// notification bridge (desktop-shell delivery).+ pub desktop: bool,+ /// webhook request subscriber (skills own inbound webhook routing).+ pub skills: bool,+ /// channel-inbound + web-only proactive.+ pub channels: bool,+ /// flows trigger dispatch.+ pub flows: bool,+ /// memory conversation-persistence + sync-stage bridge.+ pub memory: bool,+ /// agent handlers + background delivery + run-ledger finalizer + orchestration ingest.+ pub agent: bool,+ /// hosted orchestration ingest.+ pub hosted: bool,+ /// mcp::registry lifecycle bus init.+ pub mcp: bool,+}++impl DomainSubscriberPlan {+ /// The subscriber-registration plan for `domains`. Pure: no side effects.+ pub fn for_domains(domains: crate::core::runtime::DomainSet) -> Self {+ use crate::core::all::DomainGroup;+ Self {+ platform: domains.allows(DomainGroup::Platform),+ integrations: domains.allows(DomainGroup::Integrations),+ security: domains.allows(DomainGroup::Security),+ desktop: domains.allows(DomainGroup::Desktop),+ skills: domains.allows(DomainGroup::Skills),+ channels: domains.allows(DomainGroup::Channels),+ flows: domains.allows(DomainGroup::Flows),+ memory: domains.allows(DomainGroup::Memory),+ agent: domains.allows(DomainGroup::Agent),+ hosted: domains.allows(DomainGroup::Hosted),+ mcp: domains.allows(DomainGroup::Mcp),+ }+ }+}++/// Consume a domain's registration token only when the global event bus is+/// ready. An early bus-unavailable attempt therefore remains retryable.+fn group_first_time_when_bus_ready(+ completed: &std::sync::Mutex<std::collections::HashSet<crate::core::all::DomainGroup>>,+ group: crate::core::all::DomainGroup,+ bus_ready: bool,+) -> bool {+ if !bus_ready {+ log::warn!("[event_bus] deferred {group:?} subscriber registration - bus not initialized");+ return false;+ }++ completed+ .lock()+ .expect("domain-subscriber registry lock poisoned")+ .insert(group)+}++fn group_first_time(group: crate::core::all::DomainGroup) -> bool {+ use std::collections::HashSet;+ use std::sync::{Mutex, OnceLock};++ static DONE: OnceLock<Mutex<HashSet<crate::core::all::DomainGroup>>> = OnceLock::new();+ group_first_time_when_bus_ready(+ DONE.get_or_init(|| Mutex::new(HashSet::new())),+ group,+ crate::core::bus::BUS.get().is_some(),+ )+}++/// Consume the learning-subscriber token only when the global event bus is+/// ready. Learning has a separate token from the Agent group because both+/// registration blocks must run exactly once.+fn learning_first_time_when_bus_ready(completed: &std::sync::Mutex<bool>, bus_ready: bool) -> bool {+ if !bus_ready {+ log::warn!(+ "[event_bus] deferred Agent learning subscriber registration - bus not initialized"+ );+ return false;+ }++ let mut completed = completed+ .lock()+ .expect("learning-subscriber registry lock poisoned");+ if *completed {+ false+ } else {+ *completed = true;+ true+ }+}++fn learning_first_time() -> bool {+ static DONE: std::sync::OnceLock<std::sync::Mutex<bool>> = std::sync::OnceLock::new();+ learning_first_time_when_bus_ready(+ DONE.get_or_init(|| std::sync::Mutex::new(false)),+ crate::core::bus::BUS.get().is_some(),+ )+}++/// Registers all long-lived domain event-bus subscribers, each group at most+/// once per process.+///+/// Ungated core/platform infra runs exactly once behind `INFRA: Once`; each+/// gated [`DomainGroup`](crate::core::all::DomainGroup) installs the first time+/// it is enabled after the event bus is ready, so widening the ambient+/// `DomainSet` on a later call (`harness()` → `full()`) still installs the+/// newly-enabled groups without double-subscribing the ones already registered.+pub(super) fn register_domain_subscribers(+ workspace_dir: std::path::PathBuf,+ config: crate::config::Config,+ embedded_core: bool,+ domains: crate::core::runtime::DomainSet,+) {+ use crate::core::all::DomainGroup;+ use std::sync::{Arc, Once};++ let plan = DomainSubscriberPlan::for_domains(domains);+ log::debug!("[event_bus] register_domain_subscribers: domains={domains:?} plan={plan:?}");++ // `subscribe_global` returns `None` only before the process-global bus is+ // initialized. Because that bus is a monotonic `OnceLock`, checking it here+ // guarantees the registrations in the guarded block cannot later lose bus+ // availability. A premature call leaves the group absent from `DONE`, so a+ // later bootstrap retries it instead of permanently skipping subscribers.++ // Seed the live tool-execution timeout from the persisted `[agent]` config+ // so a user-configured value (Settings → Agent OS access → Action timeout)+ // is in effect from the first tool call. `OPENHUMAN_TOOL_TIMEOUT_SECS`, when+ // set, still overrides this inside `set_tool_timeout_secs`. This lives on+ // the always-on boot path (not `channels::runtime::startup::start_channels`,+ // which is skipped for channel-less / web-chat-only cores) so the timeout+ // seeds for every install regardless of DomainSet — it is DomainSet-+ // independent process-global state, not a gated subscriber (#5027).+ //+ // Deliberately OUTSIDE the `INFRA: Once` below: `bootstrap_core_runtime`+ // re-runs on an in-process core restart (`CoreProcessHandle::restart` →+ // `ensure_running`, and `reset_local_data`/Clear-Local-Data) with a freshly+ // reloaded `Config`, but `INFRA` is already consumed — so a seed gated by it+ // would leave the process-global timeout pinned to the previous config's+ // value until Settings is re-saved. `set_tool_timeout_secs` is idempotent+ // (a plain atomic store honouring the env override), so re-seeding on every+ // call is correct and cheap and re-applies the current config each boot.+ let effective_timeout =+ crate::tools::timeout::set_tool_timeout_secs(config.agent.agent_timeout_secs);+ log::debug!(+ "[tool_timeout] seeded tool-execution timeout from config: configured={}s effective={}s",+ config.agent.agent_timeout_secs,+ effective_timeout+ );++ // Ungated core/platform infra — health, scheduler-gate, TokenJuice+ // content-router, session-token seeding, the SessionExpired handler, and+ // service restart/shutdown. These are DomainSet-independent, so they run+ // exactly once on the first call regardless of which composition boots+ // first. Registered BEFORE any gated subscriber so the SessionExpired+ // handler is live before a gated subscriber could publish a 401-derived+ // event. Leaked `SubscriptionHandle`s live for the whole process+ // (`SubscriptionHandle::drop` aborts the task).+ static INFRA: Once = Once::new();+ INFRA.call_once(|| {+ crate::platform::health::bus::register_health_subscriber();++ // Initialise the scheduler gate before any background AI workers start+ // so they observe a real policy on their first iteration (otherwise they+ // fall back to `Policy::Normal` and miss the initial throttle decision on+ // battery-powered hosts).+ crate::cron::scheduler_gate::init_global(&config);++ // A headless host (Docker / VPS / CI) has no interactive login; it+ // hands the core a credential through the environment instead. The+ // API key is a plain profile write, so it lands before the gate is+ // seeded from the store below; a session token runs the full+ // `set_credential` path and seeds the gate itself when it finishes.+ crate::security::credentials::seed_api_key_from_env(&config);+ if std::env::var_os(crate::security::credentials::BACKEND_SESSION_TOKEN_ENV).is_some() {+ let config = config.clone();+ tokio::spawn(async move {+ crate::security::credentials::seed_session_from_env(&config).await;+ });+ }++ // Seed the scheduler-gate signed-out override from the on-disk+ // credential — an API key (library runtime) or the app session.+ // Without this, a sidecar that boots with no stored credential would+ // happily spin up cron / channel loops and fire LLM requests that all+ // 401.+ if crate::security::credentials::api_key::has_api_key(&config) {+ log::info!("[auth] api-key credential present at startup — scheduler gate signed in");+ crate::cron::scheduler_gate::set_signed_out(false);+ } else {- match crate::api::jwt::get_session_token(&config) {++ match crate::security::credentials::jwt::get_session_token(&config) {+ Ok(Some(_)) => {+ crate::cron::scheduler_gate::set_signed_out(false);+ }+ Ok(None) => {+ log::info!(+ "[auth] no session token at startup — scheduler gate set to signed_out \+ (config_path={}, keyring_backend={})",+ config.config_path.display(),+ crate::security::keyring::backend_name(),+ );+ crate::cron::scheduler_gate::set_signed_out(true);+ }+ Err(err) => {+ log::warn!(+ "[auth] failed to read session token at startup ({err}) — assuming signed_out \+ (config_path={}, keyring_backend={})",+ config.config_path.display(),+ crate::security::keyring::backend_name(),+ );+ crate::cron::scheduler_gate::set_signed_out(true);+ }+ }+ }++ // Register the SessionExpired handler before any subscribers that might+ // publish 401-derived events, so the very first 401 is routed through+ // `clear_session` + the scheduler-gate override.+ if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(+ crate::security::credentials::bus::SessionExpiredSubscriber::new(),+ )) {+ std::mem::forget(handle);+ } else {+ log::warn!(+ "[event_bus] failed to register SessionExpired subscriber — bus not initialized"+ );+ }++ // Restart requests go through a subscriber so every trigger path shares+ // the same respawn logic.+ crate::platform::service::bus::register_restart_subscriber();+ if embedded_core {+ log::info!(+ "[event_bus] embedded core: service shutdown subscriber not registered; Tauri cancellation token owns shutdown"+ );+ } else {+ // Shutdown requests use the same pattern; the standalone CLI+ // subscriber exits the current process after a short grace period.+ crate::platform::service::bus::register_shutdown_subscriber();+ }+ });++ // ---- Gated domain subscribers — each group installed at most once, the+ // first time its owning DomainGroup is enabled. -------------------------++ // Carved-out families: webhook (Skills), notification bridge (Desktop),+ // composio + task-sources (Integrations), and device tunnel (Security).+ if plan.skills {+ if group_first_time(DomainGroup::Skills) {+ if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(+ crate::skills::webhooks::bus::WebhookRequestSubscriber::new(),+ )) {+ std::mem::forget(handle);+ } else {+ log::warn!(+ "[event_bus] failed to register webhook subscriber — bus not initialized"+ );+ }+ }+ } else {+ log::debug!("[event_bus] webhook subscriber SKIPPED — Skills domain disabled");+ }++ if plan.desktop {+ if group_first_time(DomainGroup::Desktop) {+ crate::desktop::notifications::register_notification_bridge_subscriber(config.clone());+ }+ } else {+ log::debug!("[event_bus] notification bridge SKIPPED — Desktop domain disabled");+ }++ if plan.integrations {+ if group_first_time(DomainGroup::Integrations) {+ if let Err(error) =+ crate::integrations::composio::init_composio_trigger_history(workspace_dir.clone())+ {+ log::warn!("[composio][history] failed to initialize trigger archive: {error}");+ }+ crate::integrations::composio::register_composio_trigger_subscriber();+ crate::integrations::task_sources::bus::register_task_sources_subscriber();+ }+ } else {+ log::debug!(+ "[event_bus] composio + task-sources subscribers SKIPPED — Integrations domain disabled"+ );+ }++ if plan.security {+ if group_first_time(DomainGroup::Security) {+ // Device tunnel subscriber: handles tunnel:frame handshakes,+ // peer-status events, and register acks. Must be live before any+ // tunnel:frame events can arrive.+ crate::security::devices::bus::register_device_tunnel_subscriber();+ }+ } else {+ log::debug!("[event_bus] device-tunnel subscriber SKIPPED — Security domain disabled");+ }++ if plan.agent {+ if learning_first_time() {+ // Always-on learning subscribers (email-signature producer, rebuild+ // trigger + periodic loop, ProfileMdRenderer). Previously wired only+ // in `channels::runtime::startup::start_channels`, which is skipped+ // when no channel is configured — silently dropping ALL learning for+ // channel-less users (#5003). `agent::learning` is an Agent-family+ // domain; it sat on the Platform boot path only because `learning`+ // used to be a top-level directory. Idempotent.+ crate::agent::learning::startup::register_learning_subscribers(workspace_dir.clone());+ }+ } else {+ log::debug!("[event_bus] learning subscribers SKIPPED — Agent domain disabled");+ }++ // Channels: inbound dispatch + web-only proactive messaging.+ // The `plan.channels` runtime guard cannot stand in for the compile-time+ // gate: the `channels::bus::ChannelInboundSubscriber` ++ // `channels::proactive` type paths below must still resolve for this to+ // compile, so the whole block is `#[cfg]`-gated too (mirrors the flows+ // dual-gate below).+ #[cfg(feature = "channels")]+ if plan.channels {+ if group_first_time(DomainGroup::Channels) {+ if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(+ crate::channels::bus::ChannelInboundSubscriber::new(),+ )) {+ std::mem::forget(handle);+ } else {+ log::warn!(+ "[event_bus] failed to register channel subscriber — bus not initialized"+ );+ }+ // Web-only proactive message subscriber (no external channel+ // instances are registered here in the desktop runtime).+ crate::channels::proactive::register_web_only_proactive_subscriber();+ }+ } else {+ log::debug!(+ "[event_bus] Channels subscribers (inbound + web-only proactive) SKIPPED — Channels domain disabled"+ );+ }+ #[cfg(not(feature = "channels"))]+ log::debug!(+ "[event_bus] Channels subscribers (inbound + web-only proactive) SKIPPED — channels feature disabled at compile time"+ );++ // Flows trigger dispatch (issue B2): maps FlowScheduleTick /+ // ComposioTriggerReceived / WebhookIncomingRequest onto enabled flows and+ // runs `flows::ops::flows_run`, so schedule/app-event workflows still+ // dispatch when no realtime channel is configured or+ // `OPENHUMAN_DISABLE_CHANNEL_LISTENERS` short-circuits `start_channels`.+ // The `plan.flows` runtime guard cannot stand in for the compile-time gate:+ // the `flows::bus::FlowTriggerSubscriber` type path below must still resolve+ // for this to compile, so the whole block is `#[cfg]`-gated too.+ #[cfg(feature = "flows")]+ if plan.flows {+ if group_first_time(DomainGroup::Flows) {+ if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(+ crate::flows::bus::FlowTriggerSubscriber::new(Arc::new(config.clone())),+ )) {+ std::mem::forget(handle);+ } else {+ log::warn!(+ "[event_bus] failed to register flows trigger subscriber — bus not initialized"+ );+ }+ // Post-run memory digest (issue #5173): on a successful+ // `FlowRunFinished`, writes a compact summary into the flow's own+ // private memory namespace so a later run can `flow_memory_recall`+ // it (e.g. a scheduled digest flow deduping what it already sent).+ // Registered in the same `group_first_time(DomainGroup::Flows)`+ // block as the trigger subscriber above — that guard only returns+ // `true` once per process, so a second, separate call here would+ // never register.+ if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(+ crate::flows::bus::FlowRunDigestSubscriber::new(Arc::new(config.clone())),+ )) {+ std::mem::forget(handle);+ } else {+ log::warn!(+ "[event_bus] failed to register flows run-digest subscriber — bus not initialized"+ );+ }+ // Dedup commit-on-success (issue #5263 PR2): on every terminal+ // `FlowRunFinished`, settles each `dedup` node in the flow's graph+ // — unions tentative keys into committed on success, releases+ // (clears) tentative on failure/cancel/interrupt. This is the+ // host half of the `dedup` node's exactly-once contract; the node+ // itself (`tinyflows::nodes::control_flow::dedup`) only ever+ // reads `committed` and writes `tentative`. Registered in the+ // same `group_first_time(DomainGroup::Flows)` block as the other+ // two flows subscribers above — see the digest subscriber's+ // comment just above for why a second `group_first_time` guard+ // here would be redundant.+ if let Some(handle) = crate::core::bus::BUS.subscribe(Arc::new(+ crate::flows::bus::DedupCommitSubscriber::new(Arc::new(config.clone())),+ )) {+ std::mem::forget(handle);+ } else {+ log::warn!(+ "[event_bus] failed to register flows dedup-commit subscriber — bus not initialized"+ );+ }+ }+ } else {+ log::debug!("[event_bus] flows trigger subscriber SKIPPED — Flows domain disabled");+ }+ #[cfg(not(feature = "flows"))]+ log::debug!(+ "[event_bus] flows trigger subscriber SKIPPED — flows feature disabled at compile time"+ );++ // Memory: conversation-persistence + sync-stage bridge.+ if plan.memory {+ if group_first_time(DomainGroup::Memory) {+ crate::memory::conversations::register_conversation_persistence_subscriber(+ workspace_dir.clone(),+ );+ crate::memory::sync_events_bridge::register_sync_stage_bridge(&config);+ }+ } else {+ log::debug!(+ "[event_bus] memory conversation-persistence + sync bridge SKIPPED — Memory domain disabled"+ );+ }++ // Agent: native agent handlers + background-completion delivery ++ // run-ledger finalizer.+ if plan.agent {+ if group_first_time(DomainGroup::Agent) {+ // Native request handlers — the agent `agent.run_turn` handler is+ // what channel dispatch calls instead of importing+ // `run_tool_call_loop` directly.+ crate::agent::bus::register_agent_handlers();+ // Background-completion delivery: when a detached sub-agent+ // (spawn_async_subagent) finishes, surface its result back into the+ // originating chat as an idle-gated, batched, system-injected turn.+ crate::agent::orchestration::background_delivery::register_background_delivery();+ // Run-ledger finalizer: detached `spawn_async_subagent` runs outlive+ // their parent turn, so their terminal `AgentProgress` never reaches+ // the per-turn progress bridge that settles the ledger. This+ // global-bus subscriber settles `agent_runs` from+ // `DomainEvent::Subagent{Completed,Failed}`, preventing rows from+ // leaking as perpetual `running` timeline entries on thread reopen.+ crate::agent::orchestration::run_ledger_finalize::register_run_ledger_finalize_subscriber(&config);+ }+ } else {+ log::debug!(+ "[event_bus] agent handlers + background delivery + run-ledger finalizer SKIPPED — Agent domain disabled"+ );+ }++ // MCP clients lifecycle subscriber: logs McpServer{Installed,Connected,+ // Disconnected} + McpClientToolExecuted for observability. The boot-time+ // spawn of installed servers (boot::spawn_installed_servers) runs later in+ // bootstrap_core_runtime; this subscriber must be live before then so those+ // connect events are observed (issue #3039 gap A1).+ //+ // What bringing the domain up means is the domain's own; this only says+ // when. The service it opens is wanted here rather than later for the same+ // reason as the subscriber: every RPC handler in the domain reaches for it,+ // and opening it from the boot-connect job would leave a window where a+ // handler answers "still starting" to a caller whose domain is, as far as+ // anything else can tell, already up.+ if plan.mcp {+ if group_first_time(DomainGroup::Mcp) {+ crate::mcp::start(&config);+ }+ } else {+ log::debug!("[event_bus] mcp_registry bus init SKIPPED — Mcp domain disabled");+ }++ log::info!("[event_bus] domain subscriber registration complete: plan={plan:?}");+}++#[cfg(test)]+#[path = "subscribers_tests.rs"]+mod tests;diff --cc crates/openhuman-core/src/core/runtime/subscribers_tests.rsindex 23fd5a9a04,0000000000..819a01c619mode 100644,000000..100644--- a/crates/openhuman-core/src/core/runtime/subscribers_tests.rs+++ b/crates/openhuman-core/src/core/runtime/subscribers_tests.rs@@@ -1,268 -1,0 +1,275 @@@+use std::ffi::OsString;+use std::sync::MutexGuard;++use super::{+ group_first_time_when_bus_ready, learning_first_time_when_bus_ready, DomainSubscriberPlan,+};++// ---- domain-subscriber gating (#4796 DoD item 3) ----------------------------+// `register_domain_subscribers` registers on the process-global event bus behind+// a `Once`, so its gating is proven via the pure `DomainSubscriberPlan` the+// registrar consumes — no real subscribers, no bus mutation.++#[test]+fn domain_subscriber_plan_full_registers_every_gated_subscriber() {+ let plan = DomainSubscriberPlan::for_domains(crate::core::runtime::DomainSet::full());+ assert_eq!(+ plan,+ DomainSubscriberPlan {+ platform: true,+ integrations: true,+ security: true,+ desktop: true,+ skills: true,+ channels: true,+ flows: true,+ memory: true,+ agent: true,+ hosted: true,+ mcp: true,+ },+ "full() must register every gated domain subscriber"+ );+}++#[test]+fn domain_subscriber_plan_none_registers_no_gated_subscriber() {+ let plan = DomainSubscriberPlan::for_domains(crate::core::runtime::DomainSet::none());+ assert_eq!(+ plan,+ DomainSubscriberPlan {+ platform: false,+ integrations: false,+ security: false,+ desktop: false,+ skills: false,+ channels: false,+ flows: false,+ memory: false,+ agent: false,+ hosted: false,+ mcp: false,+ },+ "none() must register no gated domain subscriber (core infra still runs, ungated)"+ );+}++#[test]+fn domain_subscriber_plan_harness_gates_by_owning_group() {+ let plan = DomainSubscriberPlan::for_domains(crate::core::runtime::DomainSet::harness());+ // harness() = agent + memory + threads + config + security.+ assert!(plan.agent, "harness keeps agent subscribers");+ assert!(+ plan.memory,+ "harness keeps memory conversation-persistence + sync bridge"+ );- // Platform / Channels / Flows / Meet / Mcp are NOT in harness.++ // Skills, Desktop and Integrations own the subscribers omitted by harness.++ assert!(!plan.skills, "harness must skip the webhook subscriber");++ assert!(!plan.desktop, "harness must skip the notification bridge");+ assert!(- !plan.platform,- "harness must skip webhook/notification/composio/task-sources/device-tunnel"++ !plan.integrations,++ "harness must skip composio and task-source subscribers"+ );++ assert!(++ plan.security,++ "harness retains the device-tunnel subscriber"++ );++ assert!(!plan.platform, "harness excludes the platform domain");+ assert!(+ !plan.channels,+ "harness must skip channel-inbound + web-only proactive"+ );+ assert!(!plan.flows, "harness must skip flows trigger dispatch");+ assert!(+ !plan.hosted,+ "harness must skip hosted orchestration ingest"+ );+ assert!(!plan.mcp, "harness must skip mcp_registry bus init");+}++#[test]+fn domain_subscriber_registration_retries_after_bus_becomes_ready() {+ use crate::core::all::DomainGroup;+ use std::collections::HashSet;+ use std::sync::Mutex;++ let completed = Mutex::new(HashSet::new());++ assert!(!group_first_time_when_bus_ready(+ &completed,+ DomainGroup::Flows,+ false,+ ));+ assert!(+ completed.lock().expect("registry lock").is_empty(),+ "a deferred attempt must not mark the group complete"+ );++ assert!(group_first_time_when_bus_ready(+ &completed,+ DomainGroup::Flows,+ true,+ ));+ assert!(+ completed+ .lock()+ .expect("registry lock")+ .contains(&DomainGroup::Flows),+ "the ready retry must mark the group complete"+ );+}++#[test]+fn domain_subscriber_registration_is_idempotent_after_success() {+ use crate::core::all::DomainGroup;+ use std::collections::HashSet;+ use std::sync::Mutex;++ let completed = Mutex::new(HashSet::new());++ assert!(group_first_time_when_bus_ready(+ &completed,+ DomainGroup::Channels,+ true,+ ));+ assert!(!group_first_time_when_bus_ready(+ &completed,+ DomainGroup::Channels,+ true,+ ));+ assert_eq!(+ completed.lock().expect("registry lock").len(),+ 1,+ "a completed group must be recorded exactly once"+ );+}++#[test]+fn learning_subscriber_registration_retries_after_bus_becomes_ready() {+ let completed = std::sync::Mutex::new(false);++ assert!(!learning_first_time_when_bus_ready(&completed, false));+ assert!(+ !*completed.lock().expect("registry lock"),+ "a deferred learning attempt must not consume its token"+ );++ assert!(learning_first_time_when_bus_ready(&completed, true));+ assert!(+ *completed.lock().expect("registry lock"),+ "the ready retry must consume the learning token"+ );+}++#[test]+fn learning_subscriber_registration_is_idempotent_after_success() {+ let completed = std::sync::Mutex::new(false);++ assert!(learning_first_time_when_bus_ready(&completed, true));+ assert!(!learning_first_time_when_bus_ready(&completed, true));+}++#[test]+fn domain_subscriber_registration_readiness_helper_is_idempotent() {+ use crate::core::all::DomainGroup;+ use std::collections::HashSet;+ use std::sync::Mutex;++ let completed = Mutex::new(HashSet::new());+ assert!(group_first_time_when_bus_ready(+ &completed,+ DomainGroup::Media,+ true+ ));+ assert!(!group_first_time_when_bus_ready(+ &completed,+ DomainGroup::Media,+ true+ ));+}+/// #5027 — the tool-execution timeout must be seeded on the always-on core boot+/// path (`register_domain_subscribers`), NOT inside+/// `channels::runtime::startup::start_channels`, which is skipped for+/// channel-less / web-chat-only cores (and when `OPENHUMAN_DISABLE_CHANNEL_LISTENERS`+/// is set). A minimal `DomainSet::none()` must still seed, because the seed is+/// DomainSet-independent.+///+/// The seed sits just *before* the ungated `INFRA: Once` block, so it re-runs on+/// every `register_domain_subscribers` call (each `bootstrap_core_runtime`),+/// re-applying the freshly reloaded config on an in-process restart — a seed gated+/// by the process-global `Once` would only fire on the first boot. `TEST_ENV_LOCK`+/// (via `EnvVarGuard`) serializes with `OPENHUMAN_TOOL_TIMEOUT_SECS` cleared so the+/// operator env override cannot mask the config-derived value. Runs under a tokio+/// runtime like the real boot paths — the INFRA block calls `subscribe_global`,+/// which `tokio::spawn`s when the global bus is already initialized by another test+/// in the binary.+#[tokio::test]+async fn tool_timeout_seeds_on_channelless_core_boot() {+ // Clear the operator override behind a panic-safe RAII guard: if any assertion+ // below panics, `Drop` still restores the previous value, so sibling tests that+ // share `TEST_ENV_LOCK` never inherit the cleared var.+ let _env = EnvVarGuard::remove_many(vec!["OPENHUMAN_TOOL_TIMEOUT_SECS"]);++ // Distinctive, in-range (1..=3600) value so the assertion can only pass on a+ // real seed, never on the default. Channel-less: `channels_config` stays empty,+ // which is exactly the config for which `start_channels` is skipped.+ let mut config = crate::config::Config::default();+ config.agent.agent_timeout_secs = 1234;+ assert!(+ config.channels_config.active_channel.is_none(),+ "test premise: channel-less config, so start_channels would be skipped"+ );++ let tmp = tempfile::tempdir().expect("tempdir");+ // Minimal DomainSet — INFRA (and thus the timeout seed) is DomainSet-independent,+ // so even `none()` must seed. `embedded_core = true` skips the standalone+ // process-exit shutdown subscriber.+ super::register_domain_subscribers(+ tmp.path().to_path_buf(),+ config,+ true,+ crate::core::runtime::DomainSet::none(),+ );++ assert_eq!(+ crate::tools::timeout::tool_execution_timeout_secs(),+ 1234,+ "channel-less core boot must seed the tool-execution timeout from [agent].agent_timeout_secs"+ );+}++struct EnvVarGuard {+ old_values: Vec<(&'static str, Option<OsString>)>,+ _lock: MutexGuard<'static, ()>,+}++impl EnvVarGuard {+ /// Remove the named vars (capturing their prior values) for the guard's+ /// lifetime, restoring each on `Drop`.+ fn remove_many(keys: Vec<&'static str>) -> Self {+ let lock = crate::config::TEST_ENV_LOCK+ .lock()+ .expect("test env lock poisoned");+ let mut old_values = Vec::with_capacity(keys.len());+ for key in keys {+ let old = std::env::var_os(key);+ std::env::remove_var(key);+ old_values.push((key, old));+ }+ Self {+ old_values,+ _lock: lock,+ }+ }+}++impl Drop for EnvVarGuard {+ fn drop(&mut self) {+ for (key, old) in self.old_values.iter().rev() {+ match old {+ Some(value) => std::env::set_var(key, value),+ None => std::env::remove_var(key),+ }+ }+ }+}diff --cc crates/openhuman-core/src/core/shutdown.rsindex 53690ec980,1572fc6dca..c5f7f388e4--- a/crates/openhuman-core/src/core/shutdown.rs+++ b/crates/openhuman-core/src/core/shutdown.rs@@@ -3,7 -3,7 +3,7 @@@//! Provides a shutdown signal that listens for SIGINT (Ctrl-C) **and** SIGTERM//! (on Unix), then runs registered cleanup hooks before the process exits.//! Domain-specific cleanup (autocomplete, voice, etc.) registers itself here- //! so the JSON-RPC server in `openhuman-rpc` stays transport-only.-//! so `jsonrpc.rs` stays transport-only.++//! so shutdown plumbing stays outside the JSON-RPC server.use std::future::Future;use std::pin::Pin;diff --cc crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rsindex 2350aac279,0da4111e3b..5b8d7e2df2--- a/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs+++ b/crates/openhuman-core/src/inference/provider/ops/models/catalog_listing.rs@@@ -182,9 -182,17 +182,17 @@@ pub async fn list_configured_models_fro);}}- let base = crate::api::config::effective_backend_api_url(&config.api_url);+ let Ok(base) = crate::backend::base_url(&config.api_url) else {+ log::info!(+ "[providers][list_models] managed catalog unavailable — no backend transport; returning an empty list"+ );- return Ok(crate::rpc::RpcOutcome::new(++ return Ok(crate::core::Outcome::new(+ serde_json::json!({ "models": Vec::<ModelInfo>::new() }),+ vec!["no hosted backend; managed catalog is empty".to_string()],+ ));+ };models_url = append_query_param(- &crate::api::config::api_url(&base, "/openai/v1/models"),+ &crate::util::url::join_url(&base, "/openai/v1/models"),"catalog","openrouter",);diff --cc crates/openhuman-core/src/integrations/client/budget_gate.rsindex c981b96397,2d3b176c0d..f4d00f2b5e--- a/crates/openhuman-core/src/integrations/client/budget_gate.rs+++ b/crates/openhuman-core/src/integrations/client/budget_gate.rs@@@ -16,25 -20,17 +20,17 @@@ use std::time::{Duration, Instant}use serde_json::Value;- use crate::api::config::effective_backend_api_url;- use crate::api::BackendOAuthClient;+ use crate::backend::BackendClient;use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;+ use crate::security::credentials::session_support::BackendCredential;- /// Fetch `GET /teams/me/usage` with the live backend credential.- ///- /// `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`- /// (expected session-lapse 401) onto the `SESSION_EXPIRED` sentinel so the- /// JSON-RPC layer classifies it as session expiry and skips Sentry (#3297,- /// TAURI-RUST-8WY on `/teams/me/usage`); every other error keeps its full- /// `{e:#}` anyhow chain so the underlying cause (connect timeout, DNS, TLS,- /// non-2xx) is what reaches Sentry rather than the truncated label- /// (OPENHUMAN-TAURI-AD).- async fn fetch_usage(config: &Config) -> Result<Value, String> {- let credential =- crate::security::credentials::session_support::resolve_backend_credential(config)?;- let api_url = effective_backend_api_url(&config.api_url);- let client = BackendOAuthClient::new(&api_url).map_err(|e| format!("{e:#}"))?;+ /// Fetch `GET /teams/me/usage` for the pre-call probe with an+ /// already-resolved credential. `flatten_authed_error` keeps the typed 401 on+ /// the `SESSION_EXPIRED` sentinel so a lapse never anchors the backoff.+ async fn fetch_usage(config: &Config, credential: BackendCredential) -> Result<Value, String> {+ let api_url = crate::backend::require_base_url(&config.api_url)?;+ let client = BackendClient::new(&api_url).map_err(|e| format!("{e:#}"))?;client.authed_json(&credential, reqwest::Method::GET, "/teams/me/usage", None).await@@@ -101,16 -97,27 +97,27 @@@ impl UsageFailureCachestatic USAGE_FAILURE_CACHE: UsageFailureCache = UsageFailureCache::new();- pub async fn get_usage(config: &Config) -> Result<Outcome<Value>, String> {- // Key the failure backoff by the effective backend URL so a failure on one- // backend never suppresses probes after the backend is re-pointed (#4153).- let backend_key = effective_backend_api_url(&config.api_url);+ /// Run a `/teams/me/usage` fetch behind the process-wide failure backoff.+ ///+ /// `backend_key` identifies the backend (the effective API URL) so a failure+ /// on one backend never suppresses a probe after the backend is re-pointed+ /// (#4153). Shared by the pre-call probe here and the hosted `team_get_usage`+ /// RPC, which supplies an SDK-backed `fetch`. Callers resolve the credential+ /// *before* calling this, so a missing credential never opens a streak.+ pub async fn usage_with_failure_backoff<F, Fut>(+ backend_key: &str,+ fetch: F,-) -> Result<RpcOutcome<Value>, String>++) -> Result<Outcome<Value>, String>+ where+ F: FnOnce() -> Fut,+ Fut: std::future::Future<Output = Result<Value, String>>,+ {get_usage_with_cache(&USAGE_FAILURE_CACHE,- &backend_key,+ backend_key,USAGE_FAILURE_BACKOFF,Instant::now(),- || async { fetch_usage(config).await },+ fetch,).await}diff --cc crates/openhuman-core/src/integrations/composio/README.mdindex aa0c5e2636,05334a9548..293553b10a--- a/crates/openhuman-core/src/integrations/composio/README.md+++ b/crates/openhuman-core/src/integrations/composio/README.md@@@ -146,7 -146,7 +146,7 @@@ From `tools.rs` (`all_composio_agent_to## Events- Subscribers/handlers for trigger and config-change events still live in `crate::memory::sync::composio::bus` (re-exported here via `bus.rs`). All three are registered by one call, `register_composio_trigger_subscriber()`, from `crates/openhuman-core/src/core/runtime/subscribers.rs` (~2158, right after `init_composio_trigger_history`):-Subscribers/handlers for trigger and config-change events still live in `crate::memory::sync::composio::bus` (re-exported here via `bus.rs`). All three are registered by one call, `register_composio_trigger_subscriber()`, from `crates/openhuman-core/src/core/jsonrpc.rs` (~2158, right after `init_composio_trigger_history`):++Subscribers/handlers for trigger and config-change events still live in `crate::memory::sync::composio::bus` (re-exported here via `bus.rs`). All three are registered by one call, `register_composio_trigger_subscriber()`, from `crates/openhuman-core/src/core/runtime/subscribers.rs` (right after `init_composio_trigger_history`):- **`ComposioTriggerSubscriber`**, reacts to `DomainEvent::ComposioTriggerReceived` (published by `platform::socket::event_handlers` when the backend emits `composio:trigger`); archives the event to `trigger_history` and routes it through `agent::triage::run_triage` unless `OPENHUMAN_TRIGGER_TRIAGE_DISABLED`, `composio.triage_disabled`, or `composio.triage_disabled_toolkits` opts out.- **`ComposioConnectionCreatedSubscriber`**, reacts to `DomainEvent::ComposioConnectionCreated` (published by `composio_authorize`); waits for the connection to go active, invalidates and eagerly warms the integrations cache, then runs the initial profile fetch + sync.diff --cc crates/openhuman-core/src/mcp/registry/README.mdindex 317ccbe89a,a3c29630c7..e32588c3f0--- a/crates/openhuman-core/src/mcp/registry/README.md+++ b/crates/openhuman-core/src/mcp/registry/README.md@@@ -148,10 -148,10 +148,10 @@@ same real type in both buildsinstalled servers, and connect, disconnect, config updates, and reconnectsupdate the map. `connected_overview()` reads tool snapshots from that map;it does not call an MCP server on each chat turn.-- `crates/openhuman-core/src/core/jsonrpc.rs`: the `/oauth/mcp/callback`+- `crates/openhuman-rpc/src/server/http/oauth_mcp.rs`: the `/oauth/mcp/callback`route calls `oauth::complete`.- `crates/openhuman-core/src/tools/registry/ops.rs` and- `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs`:+ `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs`:read `mcp::registry::connections` to list connected servers/tools for thetool catalog and the orchestrator prompt.- `crates/openhuman-core/src/agent/session_host/turn/core_turn.rs`: readsdiff --cc crates/openhuman-core/src/security/approval/README.mdindex 55030f825b,815f7ac0cd..a9c11906a3--- a/crates/openhuman-core/src/security/approval/README.md+++ b/crates/openhuman-core/src/security/approval/README.md@@@ -83,7 -83,7 +83,7 @@@ SQLite DB at `{workspace_dir}/approval/## Used by- - `crates/openhuman-core/src/core/runtime/subscribers.rs`: installs the global gate (`ApprovalGate::init_global`) at startup and wires the approval RPCs.-- `crates/openhuman-core/src/core/jsonrpc.rs`: installs the global gate (`ApprovalGate::init_global`) at startup and wires the approval RPCs.++- `crates/openhuman-core/src/core/runtime/bootstrap.rs`: installs the global gate (`ApprovalGate::init_global`) at startup. `core/all.rs` registers the approval RPC controllers.- `crates/openhuman-core/src/core/all.rs`: registers the controller schemas.- `crates/openhuman-core/src/agent/tinyagents/middleware.rs` (`ApprovalSecurityMiddleware`, a `wrap_tool` middleware on every turn path): routes external-effect tool calls through the gate before `execute()` and records the terminal audit row.- `crates/openhuman-core/src/web_chat/`: sets `APPROVAL_CHAT_CONTEXT`, hosts `ApprovalSurfaceSubscriber`, and routes typed yes/no replies to `approval_decide`.diff --cc crates/openhuman-core/src/security/credentials/ops/credential.rsindex 53f9c3c623,a3c34dfa85..c7cc0c877c--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs@@@ -12,9 -12,9 +12,9 @@@use serde::Deserialize;use serde_json::{json, Value};- use crate::api::jwt::decode_jwt_exp;use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;+ use crate::security::credentials::jwt::decode_jwt_exp;use crate::security::credentials::responses::AuthStateResponse;use crate::security::credentials::session_support::{build_session_state, load_app_session_profile, local_session_user_id,diff --cc crates/openhuman-core/src/security/credentials/ops/oauth.rsindex bb28764a1f,eb594db538..6a4e034fb4--- a/crates/openhuman-core/src/security/credentials/ops/oauth.rs+++ b/crates/openhuman-core/src/security/credentials/ops/oauth.rs@@@ -2,75 -10,20 +10,20 @@@use serde_json::json;- use crate::api::config::effective_backend_api_url;- use crate::api::jwt::get_session_token;- use crate::api::rest::BackendOAuthClient;+ use crate::backend::BackendClient;use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;-- pub async fn oauth_connect(- config: &Config,- provider: &str,- skill_id: Option<&str>,- response_type: Option<&str>,- encryption_mode: Option<&str>,- ) -> Result<Outcome<serde_json::Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);- let token = get_session_token(config)?.ok_or_else(|| {- "session JWT required; complete login and store_session first".to_string()- })?;- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- let r = client- .connect(provider, &token, skill_id, response_type, encryption_mode)- .await- .map_err(|e| e.to_string())?;- Ok(Outcome::single_log(- serde_json::json!({ "oauthUrl": r.oauth_url, "state": r.state }),- "oauth connect URL ready",- ))- }-- pub async fn oauth_list_integrations(- config: &Config,- ) -> Result<Outcome<serde_json::Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- let list = client- .list_integrations(&token)- .await- .map_err(|e| e.to_string())?;- Ok(Outcome::single_log(- serde_json::to_value(&list).map_err(|e| e.to_string())?,- "integrations listed",- ))- }-- pub async fn oauth_fetch_integration_tokens(- config: &Config,- integration_id: &str,- encryption_key: &str,- ) -> Result<Outcome<serde_json::Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);- let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- let tokens = client- .fetch_integration_tokens_handoff(integration_id, &token, encryption_key)- .await- .map_err(|e| e.to_string())?;- Ok(Outcome::single_log(- serde_json::to_value(&tokens).map_err(|e| e.to_string())?,- "integration tokens retrieved",- ))- }+ use crate::security::credentials::jwt::get_session_token;pub async fn oauth_fetch_client_key(config: &Config,integration_id: &str,-) -> Result<RpcOutcome<serde_json::Value>, String> {+) -> Result<Outcome<serde_json::Value>, String> {- let api_url = effective_backend_api_url(&config.api_url);let token = get_session_token(config)?.ok_or_else(|| "session JWT required".to_string())?;- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;+ let api_url = crate::backend::require_base_url(&config.api_url)?;+ let client = BackendClient::new(&api_url).map_err(|e| e.to_string())?;+ // `flatten_authed_error` keeps a 401 on the `SESSION_EXPIRED` sentinel (and+ // a missing transport on `BACKEND_UNAVAILABLE:`) instead of an opaque string.let client_key = client.fetch_client_key(integration_id, &token).awaitdiff --cc crates/openhuman-core/src/security/credentials/ops/session_query.rsindex 9c8e6d4eb5,1cb13696c1..69512fbdf7--- a/crates/openhuman-core/src/security/credentials/ops/session_query.rs+++ b/crates/openhuman-core/src/security/credentials/ops/session_query.rs@@@ -2,9 -2,9 +2,9 @@@use serde_json::json;- use crate::api::jwt::get_session_token;use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;+ use crate::security::credentials::jwt::get_session_token;use crate::security::credentials::session_support::build_session_state;pub async fn auth_get_state(diff --cc crates/openhuman-core/src/security/credentials/schemas.rsindex 7d291289a4,5bfe7ed274..29543d8e11--- a/crates/openhuman-core/src/security/credentials/schemas.rs+++ b/crates/openhuman-core/src/security/credentials/schemas.rs@@@ -4,15 -4,9 +4,9 @@@ use serde_json::{Map, Value}use crate::config::rpc as config_rpc;use crate::core::all::{ControllerFuture, RegisteredController};+use crate::core::Outcome;use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use crate::rpc::RpcOutcome;- #[derive(Debug, Deserialize)]- #[serde(rename_all = "camelCase")]- struct AuthCreateChannelLinkTokenParams {- channel: String,- }-#[derive(Debug, Deserialize)]#[serde(rename_all = "camelCase")]struct AuthStoreProviderCredentialsParams {diff --cc crates/openhuman-core/src/skills/webhooks/README.mdindex 9a617620d1,060671acb6..f43e4f5e8c--- a/crates/openhuman-core/src/skills/webhooks/README.md+++ b/crates/openhuman-core/src/skills/webhooks/README.md@@@ -95,7 -88,7 +88,7 @@@ Note that nothing in the production sta- `crates/openhuman-core/src/core/all.rs`: registers the controllers/schemas into the RPC registry.- `crates/openhuman-core/src/platform/socket/manager.rs`: stores the `WebhookRouter` (`set_webhook_router` / `webhook_router`) on the socket manager; ops/bus retrieve it from there.- `crates/openhuman-core/src/platform/socket/event_handlers.rs`: publishes `WebhookIncomingRequest` from the socket and reads the shared router slot.- - `crates/openhuman-core/src/core/runtime/subscribers.rs`: registers `WebhookRequestSubscriber` in `register_domain_subscribers()` and provides the RPC transport surface.-- `crates/openhuman-core/src/core/jsonrpc.rs`: registers `WebhookRequestSubscriber` in `register_domain_subscribers()` and provides the RPC transport surface.++- `crates/openhuman-core/src/core/runtime/subscribers.rs`: registers `WebhookRequestSubscriber` in `register_domain_subscribers()`.- `crates/openhuman-core/src/core/events.rs`: defines the `Webhook*` `DomainEvent` variants this module uses.## Notes / gotchasdiff --cc crates/openhuman-core/src/skills/webhooks/ops.rsindex 93923141a2,9f476f0af8..be83036dde--- a/crates/openhuman-core/src/skills/webhooks/ops.rs+++ b/crates/openhuman-core/src/skills/webhooks/ops.rs@@@ -1,8 -1,4 +1,4 @@@- use crate::api::config::effective_backend_api_url;- use crate::api::jwt::get_session_token;- use crate::api::BackendOAuthClient;- use crate::config::Config;-use crate::rpc::RpcOutcome;+use crate::core::Outcome;use crate::skills::webhooks::{WebhookDebugLogListResult, WebhookDebugLogsClearedResult, WebhookDebugRegistrationsResult,WebhookRequest, WebhookResponseData,diff --cc crates/openhuman-core/src/web_chat/README.mdindex 0fca84038a,4662d5f75c..4c398e1b9b--- a/crates/openhuman-core/src/web_chat/README.md+++ b/crates/openhuman-core/src/web_chat/README.md@@@ -165,11 -165,11 +165,11 @@@ Namespace `channel`, registered vi## Called by-- `core/socketio.rs`: the `chat:start` and `chat:cancel` handlers call+- `openhuman-rpc/src/server/socketio.rs`: the `chat:start` and `chat:cancel` handlers call`start_chat` / `cancel_chat_scoped`, and forward `WebChannelEvent`s to theclient.- - `core/runtime/subscribers.rs`: subscribes the event stream for `/events` SSE and-- `core/jsonrpc.rs`: subscribes the event stream for `/events` SSE and-- registers the three `DomainEvent` surface subscribers at startup.++- `openhuman-rpc/src/server/http/events.rs`: subscribes the `/events` SSE stream.++- `core/runtime/bootstrap.rs`: registers the `DomainEvent` surface subscribers at startup.- `core/all.rs`: registers `all_web_channel_registered_controllers()` under`DomainGroup::Channels`, deliberately not behind the `channels` feature(the in-app chat is core product surface, #5002).diff --cc crates/openhuman-tinyhumans/src/hosted/announcements/ops.rsindex c4ec0020c4,82d23ae368..a3e34e3b65--- a/crates/openhuman-tinyhumans/src/hosted/announcements/ops.rs+++ b/crates/openhuman-tinyhumans/src/hosted/announcements/ops.rs@@@ -1,35 -1,23 +1,23 @@@- //! Announcements RPC ops — a thin adapter that calls the hosted API.+ //! Announcements RPC ops — a thin adapter over the SDK's typed+ //! `announcements()` client.//!//! # Security- //! Requires a valid app-session JWT stored via `auth_store_session` (same guard- //! as `billing/ops.rs`). The JWT is sent as `Authorization: Bearer …`; the- //! backend decides what the user may see. No authorization is replicated here.- //! A lapsed session surfaces the backend 401 verbatim via `flatten_authed_error`.+ //! Authenticates with the core's resolved backend credential+ //! ([`HostedClient`]); the backend decides what the user may see. No+ //! authorization is replicated here.- use reqwest::Method;use serde_json::Value;+ use tinyhumans_sdk::Error as SdkError;- use openhuman_core::api::config::effective_backend_api_url;- use openhuman_core::api::{BackendApiError, BackendOAuthClient};use openhuman_core::config::Config;-use openhuman_core::rpc::RpcOutcome;+use openhuman_core::core::Outcome;- /// Canonical authed-session guard — rejects an expired token locally instead of- /// firing a doomed backend 401 (see `billing/ops.rs` / #3297).- fn require_token(- config: &Config,- ) -> Result<openhuman_core::security::credentials::session_support::BackendCredential, String> {- openhuman_core::security::credentials::session_support::resolve_backend_credential(config)- }+ use crate::hosted::client::HostedClient;- /// `true` when `err` is the typed `BackendApiError::AnnouncementNotFound` 404- /// (see `crates/openhuman-core/src/api/rest.rs`) — the backend has no announcement for this user,- /// which is a normal outcome for this best-effort feature, not a failure.- fn is_announcement_not_found(err: &anyhow::Error) -> bool {- matches!(- err.downcast_ref::<BackendApiError>(),- Some(BackendApiError::AnnouncementNotFound)- )+ /// `true` when `result` is the backend's 404 for "no announcement" — a normal+ /// outcome for this best-effort feature, not a failure.+ fn is_not_found<T>(result: &Result<T, SdkError>) -> bool {+ matches!(result, Err(SdkError::Status { status: 404, .. }))}/// Fetch the latest active announcement for the signed-in user.diff --cc crates/openhuman-tinyhumans/src/hosted/billing/ops.rsindex d9682ddaa4,aae17a045d..ca737213f3--- a/crates/openhuman-tinyhumans/src/hosted/billing/ops.rs+++ b/crates/openhuman-tinyhumans/src/hosted/billing/ops.rs@@@ -10,46 -11,36 +11,36 @@@//! API keys / JWTs are never written to logs (only redacted status codes + paths).use reqwest::Method;- use serde::Serialize;- use serde_json::{json, Value};+ use serde_json::{Map, Value};+ use tinyhumans_sdk::api::payments::{+ CoinbaseInterval, CoinbasePlan, CreateCoinbaseChargeRequest, CreditTopUpRequest,+ PaymentGateway, PurchaseStripePlanRequest, UpdateAutoRechargeCardRequest,+ };+ use tinyhumans_sdk::api::types::{BillingPlan, CodeRequest};- use openhuman_core::api::config::effective_backend_api_url;- use openhuman_core::api::BackendOAuthClient;use openhuman_core::config::Config;-use openhuman_core::rpc::RpcOutcome;+use openhuman_core::core::Outcome;- /// Canonical authed-session guard. Delegates to `require_live_session_token`,- /// which rejects an expired token locally (publishing `SessionExpired`) instead- /// of firing a doomed backend 401 — see #3297 / `session_support`.- fn require_token(- config: &Config,- ) -> Result<openhuman_core::security::credentials::session_support::BackendCredential, String> {- openhuman_core::security::credentials::session_support::resolve_backend_credential(config)+ use crate::hosted::client::HostedClient;++ /// Parse a wire string into one of the SDK's closed request enums, naming the+ /// field and the offending value on failure. The plan enums are+ /// `SCREAMING_SNAKE_CASE` on the wire, so a lower-case plan (`"pro"`) is+ /// accepted as its upper-case form; the lower-case `interval`/`gateway` enums+ /// are matched as given.+ fn parse_enum<T: serde::de::DeserializeOwned>(field: &str, raw: &str) -> Result<T, String> {+ serde_json::from_value(Value::String(raw.to_string()))+ .or_else(|_| serde_json::from_value(Value::String(raw.to_ascii_uppercase())))+ .map_err(|_| format!("unsupported {field}: {raw}"))}- async fn get_authed_value(- config: &Config,- method: Method,- path: &str,- body: Option<Value>,- ) -> Result<Value, String> {- let token = require_token(config)?;- let api_url = effective_backend_api_url(&config.api_url);- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`- // (expected session-lapse 401) onto the `SESSION_EXPIRED` sentinel so the- // JSON-RPC layer classifies it as session expiry and skips Sentry (#3297,- // TAURI-RUST-8WZ on `/payments/stripe/currentPlan`); every other error keeps- // its full `{e:#}` anyhow chain.- client- .authed_json(&token, method, path, body)- .await- .map_err(openhuman_core::api::flatten_authed_error)- }-- pub async fn get_current_plan(config: &Config) -> Result<Outcome<Value>, String> {- let data = get_authed_value(config, Method::GET, "/payments/stripe/currentPlan", None).await?;- Ok(Outcome::single_log(+ pub async fn get_current_plan(config: &Config) -> Result<RpcOutcome<Value>, String> {+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /payments/stripe/currentPlan",+ client.sdk().payments().get_current_plan().await,+ )?;+ Ok(RpcOutcome::single_log(data,"current plan fetched from backend",))@@@ -75,20 -68,43 +68,43 @@@ pub async fn get_transactionsconfig: &Config,limit: Option<u64>,offset: Option<u64>,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {let limit = limit.unwrap_or(20);let offset = offset.unwrap_or(0);- let path = format!("/payments/credits/transactions?limit={limit}&offset={offset}");- let data = get_authed_value(config, Method::GET, &path, None).await?;- Ok(Outcome::single_log(data, "credit transactions fetched"))+ let client = HostedClient::from_config(config)?;+ let query = [+ ("limit", Some(limit.to_string())),+ ("offset", Some(offset.to_string())),+ ];+ let data = client.finish_value(+ "GET /payments/credits/transactions",+ client+ .sdk()+ .payments()+ .list_credit_transactions(&query)+ .await,+ )?;+ Ok(RpcOutcome::single_log(data, "credit transactions fetched"))}- pub async fn get_auto_recharge(config: &Config) -> Result<Outcome<Value>, String> {- let data =- get_authed_value(config, Method::GET, "/payments/credits/auto-recharge", None).await?;- Ok(Outcome::single_log(data, "auto recharge settings fetched"))+ pub async fn get_auto_recharge(config: &Config) -> Result<RpcOutcome<Value>, String> {+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /payments/credits/auto-recharge",+ client.sdk().payments().get_auto_recharge().await,+ )?;+ Ok(RpcOutcome::single_log(+ data,+ "auto recharge settings fetched",+ ))}+ /// `PATCH /payments/credits/auto-recharge`.+ ///+ /// Forwarded verbatim on the SDK's raw primitive (route policy still applies)+ /// rather than through the typed `update_auto_recharge`: the SDK's+ /// `AutoRechargeRequest` has no `weeklyLimitUsd`, which the settings UI sends,+ /// so decoding into it would silently drop the weekly cap.pub async fn update_auto_recharge(config: &Config,payload: Value,@@@ -283,14 -314,9 +314,9 @@@ pub async fn create_coinbase_charge// ── Coupon operations ──────────────────────────────────────────────────────- #[derive(Debug, Serialize)]- struct RedeemCouponBody<'a> {- code: &'a str,- }-/// Redeem a coupon code to add credits to the user's account./// Maps to `POST /coupons/redeem`.-pub async fn redeem_coupon(config: &Config, code: &str) -> Result<RpcOutcome<Value>, String> {+pub async fn redeem_coupon(config: &Config, code: &str) -> Result<Outcome<Value>, String> {let code = code.trim();if code.is_empty() {return Err("code is required".to_string());diff --cc crates/openhuman-tinyhumans/src/hosted/referral/ops.rsindex 7998dee6a4,0abd081085..2b81b31e56--- a/crates/openhuman-tinyhumans/src/hosted/referral/ops.rs+++ b/crates/openhuman-tinyhumans/src/hosted/referral/ops.rs@@@ -1,39 -1,24 +1,24 @@@- //! Referral program — authenticated calls to the hosted API (`/referral/*`).+ //! Referral program — authenticated calls to the hosted API (`/referral/*`)+ //! through the SDK's typed `referral()` client.//!- //! The desktop WebView `fetch` to the backend can fail with a generic "Load failed"- //! (CORS / TLS / WebKit). These ops reuse the same `reqwest` path as billing.+ //! The desktop WebView `fetch` to the backend can fail with a generic "Load+ //! failed" (CORS / TLS / WebKit), so these run in-process like billing.- use reqwest::Method;- use serde_json::{json, Map, Value};+ use serde_json::Value;+ use tinyhumans_sdk::api::types::ClaimReferralRequest;- use openhuman_core::api::config::effective_backend_api_url;- use openhuman_core::api::jwt::get_session_token;- use openhuman_core::api::BackendOAuthClient;use openhuman_core::config::Config;-use openhuman_core::rpc::RpcOutcome;+use openhuman_core::core::Outcome;- fn require_token(config: &Config) -> Result<String, String> {- get_session_token(config)?- .and_then(|v| {- let t = v.trim().to_string();- if t.is_empty() {- None- } else {- Some(t)- }- })- .ok_or_else(|| "no backend session token; run auth_store_session first".to_string())- }+ use crate::hosted::client::HostedClient;- pub async fn get_stats(config: &Config) -> Result<Outcome<Value>, String> {- let token = require_token(config)?;- let api_url = effective_backend_api_url(&config.api_url);- let client = BackendOAuthClient::new(&api_url).map_err(|e| e.to_string())?;- let data = client- .authed_json(&token, Method::GET, "/referral/stats", None)- .await- .map_err(|e| e.to_string())?;- Ok(Outcome::single_log(+ pub async fn get_stats(config: &Config) -> Result<RpcOutcome<Value>, String> {+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /referral/stats",+ client.sdk().referral().get_referral_stats().await,+ )?;+ Ok(RpcOutcome::single_log(data,"referral stats fetched from backend GET /referral/stats",))diff --cc crates/openhuman-tinyhumans/src/hosted/team/ops.rsindex d8a243f289,7432b9f5b1..e46e7ee68c--- a/crates/openhuman-tinyhumans/src/hosted/team/ops.rs+++ b/crates/openhuman-tinyhumans/src/hosted/team/ops.rs@@@ -35,78 -31,69 +31,69 @@@ fn normalize_id(input: &str, field: &stOk(trimmed.to_string())}- fn build_api_path(segments: &[&str]) -> Result<String, String> {- let mut url = Url::parse("https://openhuman.invalid")- .map_err(|e| format!("failed to initialize URL path builder: {e}"))?;- {- let mut path_segments = url- .path_segments_mut()- .map_err(|_| "failed to initialize URL path builder".to_string())?;- path_segments.clear();- for segment in segments {- path_segments.push(segment);- }- }- Ok(url.path().to_string())+ fn clamp_u32(value: Option<u64>, field: &str) -> Result<Option<u32>, String> {+ value+ .map(|v| u32::try_from(v).map_err(|_| format!("{field} is out of range")))+ .transpose()}- async fn get_authed_value(- config: &Config,- method: Method,- path: &str,- body: Option<Value>,- ) -> Result<Value, String> {- let token = require_token(config)?;- let api_url = effective_backend_api_url(&config.api_url);- let client = BackendOAuthClient::new(&api_url).map_err(|e| format!("{e:#}"))?;- // `flatten_authed_error` maps the typed `BackendApiError::Unauthorized`- // (expected session-lapse 401) onto the `SESSION_EXPIRED` sentinel so the- // JSON-RPC layer classifies it as session expiry and skips Sentry (#3297,- // TAURI-RUST-8WY on `/teams/me/usage`); every other error keeps its full- // `{e:#}` anyhow chain. `authed_json` wraps the underlying reqwest error- // with `.context(format!("backend request {} {}", …))`- // (`api/rest.rs::authed_json`), so `{e:#}` (not `e.to_string()`) is required- // to surface the cause (connect timeout, DNS failure, TLS handshake, non-2xx- // status, …) before the JSON-RPC layer reports it to Sentry.- // OPENHUMAN-TAURI-AD is the canonical instance: 2 events on `0.53.35` from a- // Russia user, all with the truncated label and elapsed_ms=49 — far too- // short for a real timeout, so the underlying cause is the only signal worth- // surfacing. Same failure mode the `report_error` doc-string in- // `core/observability.rs` calls out (TAURI-B2).- client- .authed_json(&token, method, path, body)- .await- .map_err(openhuman_core::api::flatten_authed_error)+ /// `GET /teams/me/usage` — the usage document behind the frontend's usage+ /// poll. Wrapped in the core's shared failure backoff+ /// ([`budget_gate::usage_with_failure_backoff`]) so a persistent backend+ /// fault collapses to about one probe a minute across this RPC *and* the+ /// managed-tool budget gate (GH #4153).+ ///+ /// The credential is resolved first: a user with no TinyHumans account gets+ /// the core's `BACKEND_UNAVAILABLE:` sentinel without a request and without+ /// opening a backoff streak (Sentry 36649).+ pub async fn get_usage(config: &Config) -> Result<RpcOutcome<Value>, String> {+ let client = HostedClient::from_config(config)?;+ let backend_key = effective_backend_api_url(&config.api_url);+ budget_gate::usage_with_failure_backoff(&backend_key, || async {+ client.finish_value(+ "GET /teams/me/usage",+ client.sdk().teams().get_my_usage().await,+ )+ })+ .await}-pub async fn list_members(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {+pub async fn list_members(config: &Config, team_id: &str) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "members"])?;- let data = get_authed_value(config, Method::GET, &path, None).await?;- Ok(Outcome::single_log(+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /teams/{teamId}/members",+ client.sdk().teams().list_members(&team_id).await,+ )?;+ Ok(RpcOutcome::single_log(data,"team members fetched from backend",))}- pub async fn list_teams(config: &Config) -> Result<Outcome<Value>, String> {- let data = get_authed_value(config, Method::GET, "/teams", None).await?;- Ok(Outcome::single_log(data, "teams fetched from backend"))+ pub async fn list_teams(config: &Config) -> Result<RpcOutcome<Value>, String> {+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value("GET /teams", client.sdk().teams().list_teams().await)?;+ Ok(RpcOutcome::single_log(data, "teams fetched from backend"))}-pub async fn get_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {+pub async fn get_team(config: &Config, team_id: &str) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id])?;- let data = get_authed_value(config, Method::GET, &path, None).await?;- Ok(Outcome::single_log(data, "team fetched from backend"))+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "GET /teams/{teamId}",+ client.sdk().teams().get_team(&team_id).await,+ )?;+ Ok(RpcOutcome::single_log(data, "team fetched from backend"))}- #[derive(Debug, Serialize)]- struct TeamNameBody<'a> {- name: &'a str,- }-- pub async fn create_team(config: &Config, name: &str) -> Result<Outcome<Value>, String> {+ /// `POST /teams` through the core's `BackendClient::authed_json`.+ ///+ /// Deliberately **not** on the SDK: the SDK has no typed method for this route+ /// and its generated public-route registry has no entry for it (teams were+ /// folded into users on the backend). Until the route is added to the SDK+ /// upstream, or the RPC is retired, it stays on the pre-SDK path unchanged.+ pub async fn create_team(config: &Config, name: &str) -> Result<RpcOutcome<Value>, String> {let trimmed = name.trim();if trimmed.is_empty() {return Err("name is required".to_string());@@@ -115,52 -102,85 +102,85 @@@config,Method::POST,"/teams",- Some(json!(TeamNameBody { name: trimmed })),+ Some(json!({ "name": trimmed })),).await?;- Ok(RpcOutcome::single_log(data, "team created via backend"))+ Ok(Outcome::single_log(data, "team created via backend"))}+ /// The pre-SDK request path for the two team routes the SDK does not carry+ /// ([`create_team`], [`delete_team`]). Credential first, so a user without a+ /// TinyHumans account still gets the sentinel without a request.+ async fn legacy_authed_value(+ config: &Config,+ method: Method,+ path: &str,+ body: Option<Value>,+ ) -> Result<Value, String> {+ let credential =+ openhuman_core::security::credentials::session_support::resolve_backend_credential(config)?;+ let api_url = effective_backend_api_url(&config.api_url);+ let client = BackendClient::new(&api_url).map_err(|e| format!("{e:#}"))?;+ client+ .authed_json(credential, method, path, body)+ .await+ .map_err(openhuman_core::backend::flatten_authed_error)+ }+pub async fn update_team(config: &Config,team_id: &str,name: Option<&str>,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id])?;let mut body = serde_json::Map::new();if let Some(name) = name.map(str::trim).filter(|value| !value.is_empty()) {body.insert("name".to_string(), Value::String(name.to_string()));}- let data = get_authed_value(config, Method::PUT, &path, Some(Value::Object(body))).await?;- Ok(Outcome::single_log(data, "team updated via backend"))+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "PUT /teams/{teamId}",+ client+ .sdk()+ .teams()+ .update_team(&team_id, &Value::Object(body))+ .await,+ )?;+ Ok(RpcOutcome::single_log(data, "team updated via backend"))}- pub async fn delete_team(config: &Config, team_id: &str) -> Result<Outcome<Value>, String> {+ /// `DELETE /teams/{teamId}` on the pre-SDK path — see [`create_team`].+ pub async fn delete_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id])?;- let data = get_authed_value(config, Method::DELETE, &path, None).await?;- Ok(Outcome::single_log(data, "team deleted via backend"))+ let path = format!("/teams/{}", tinyhumans_sdk::enc(&team_id));+ let data = legacy_authed_value(config, Method::DELETE, &path, None).await?;+ Ok(RpcOutcome::single_log(data, "team deleted via backend"))}-pub async fn switch_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {+pub async fn switch_team(config: &Config, team_id: &str) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "switch"])?;- let data = get_authed_value(config, Method::POST, &path, Some(json!({}))).await?;- Ok(Outcome::single_log(+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "POST /teams/{teamId}/switch",+ client.sdk().teams().switch_team(&team_id).await,+ )?;+ Ok(RpcOutcome::single_log(data,"active team switched via backend",))}-pub async fn leave_team(config: &Config, team_id: &str) -> Result<RpcOutcome<Value>, String> {+pub async fn leave_team(config: &Config, team_id: &str) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "leave"])?;- let data = get_authed_value(config, Method::POST, &path, Some(json!({}))).await?;- Ok(Outcome::single_log(data, "team left via backend"))+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "POST /teams/{teamId}/leave",+ client.sdk().teams().leave_team(&team_id).await,+ )?;+ Ok(RpcOutcome::single_log(data, "team left via backend"))}-pub async fn join_team(config: &Config, code: &str) -> Result<RpcOutcome<Value>, String> {+pub async fn join_team(config: &Config, code: &str) -> Result<Outcome<Value>, String> {let trimmed = code.trim();if trimmed.is_empty() {return Err("code is required".to_string());@@@ -189,27 -201,39 +201,39 @@@ pub async fn create_inviteteam_id: &str,max_uses: Option<u64>,expires_in_days: Option<u64>,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;- let path = build_api_path(&["teams", &team_id, "invites"])?;- let body = json!(InviteBody {- max_uses,- expires_in_days,- });- let data = get_authed_value(config, Method::POST, &path, Some(body)).await?;- Ok(Outcome::single_log(data, "team invite created via backend"))+ let request = CreateTeamInviteRequest {+ max_uses: clamp_u32(max_uses, "maxUses")?,+ expires_in_days: clamp_u32(expires_in_days, "expiresInDays")?,+ };+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "POST /teams/{teamId}/invites",+ client.sdk().teams().create_invite(&team_id, &request).await,+ )?;+ Ok(RpcOutcome::single_log(+ data,+ "team invite created via backend",+ ))}pub async fn remove_member(config: &Config,team_id: &str,user_id: &str,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;let user_id = normalize_id(user_id, "userId")?;- let path = build_api_path(&["teams", &team_id, "members", &user_id])?;- let data = get_authed_value(config, Method::DELETE, &path, None).await?;- Ok(Outcome::single_log(data, "team member removed via backend"))+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "DELETE /teams/{teamId}/members/{userId}",+ client.sdk().teams().remove_member(&team_id, &user_id).await,+ )?;+ Ok(RpcOutcome::single_log(+ data,+ "team member removed via backend",+ ))}pub async fn change_member_role(@@@ -248,12 -279,22 +279,22 @@@ pub async fn revoke_inviteconfig: &Config,team_id: &str,invite_id: &str,-) -> Result<RpcOutcome<Value>, String> {+) -> Result<Outcome<Value>, String> {let team_id = normalize_id(team_id, "teamId")?;let invite_id = normalize_id(invite_id, "inviteId")?;- let path = build_api_path(&["teams", &team_id, "invites", &invite_id])?;- let data = get_authed_value(config, Method::DELETE, &path, None).await?;- Ok(Outcome::single_log(data, "team invite revoked via backend"))+ let client = HostedClient::from_config(config)?;+ let data = client.finish_value(+ "DELETE /teams/{teamId}/invites/{inviteId}",+ client+ .sdk()+ .teams()+ .revoke_invite(&team_id, &invite_id)+ .await,+ )?;+ Ok(RpcOutcome::single_log(+ data,+ "team invite revoked via backend",+ ))}#[cfg(test)]diff --cc scripts/ci/check-dep-sim-calibration.shindex 6b6fb06b3d,6b6fb06b3d..e685eab2ef--- a/scripts/ci/check-dep-sim-calibration.sh+++ b/scripts/ci/check-dep-sim-calibration.sh@@@ -59,6 -59,6 +59,8 @@@# build dependency. See the matching kernel-floor history entry.# 282 -> 285 on 2026-09-26: the required TinyBrowser integration adds# tinybrowser-bus, tinybrowser-control, and tinyjevclient. Native count stays 2.++# 285 -> 284 on 2026-09-27: moving the JSON-RPC server above the core removes++# openhuman-rpc from the core's no-default + flows dependency graph.## Called by ci-lite.yml's feature-gate smoke lane and by the lane runner, so the# expected count lives here once (plus scripts/kernel-floor.limits).@@@ -66,6 -66,6 +68,6 @@@ set -euo pipefaicd "$(dirname "$0")/../.."--EXPECTED_NAMES=285++EXPECTED_NAMES=284exec python3 scripts/dep-sim.py --cut-nothing --expect-names "${EXPECTED_NAMES}"diff --cc scripts/ci/ignored-test-baseline.jsonindex 465a341f60,e0204f9cbe..d5368c15fe--- a/scripts/ci/ignored-test-baseline.json+++ b/scripts/ci/ignored-test-baseline.json@@@ -1,9 -1,9 +1,9 @@@{"openhuman-app": 5,"openhuman-cli": 0,- "openhuman-core": 95,+ "openhuman-core": 90,"openhuman-embed": 0,- "openhuman-rpc": 0,+ "openhuman-rpc": 1,"openhuman-tinyhumans": 0,"openhuman-tui": 0,"tests": 32diff --cc scripts/kernel-floor.limitsindex b9926d74bd,b9926d74bd..e367ac34b0--- a/scripts/kernel-floor.limits+++ b/scripts/kernel-floor.limits@@@ -13,6 -13,6 +13,9 @@@# Simulate with: scripts/dep-sim.py --cut <crates>## History++# 305/284/2 2026-09-27 Moving the JSON-RPC server above openhuman-core++# removes openhuman-rpc from the no-default + flows graph.++# Measured with scripts/kernel-floor.sh flows --json.# 306/285/2 2026-09-26 The required TinyBrowser integration adds# tinybrowser-bus, tinybrowser-control, and tinyjevclient# to the flows profile compared with the 303/282 baseline.@@@ -600,4 -600,4 +603,4 @@@# into the required host runtime. The migration adds five# resolved packages and four unique crate names; it does# not add a native build dependency.--flows:306:285:2++flows:305:284:2diff --cc tests/composio_post_oauth_retry_e2e.rsindex ab6ae5a8fa,d938101ff1..0c1e4e0c83--- a/tests/composio_post_oauth_retry_e2e.rs+++ b/tests/composio_post_oauth_retry_e2e.rs@@@ -80,8 -80,11 +80,11 @@@ use serde_json::{json, Value}use tempfile::tempdir;use openhuman_core::core::auth::{init_rpc_token, CORE_TOKEN_ENV_VAR};-use openhuman_core::core::jsonrpc::build_core_http_router;+use openhuman_rpc::server::build_core_http_router;+ #[path = "support/tinyhumans_boot.rs"]+ mod tinyhumans_boot;+// ── env serialisation ─────────────────────────────────────────────────────────//// HOME / OPENHUMAN_WORKSPACE / BACKEND_URL are process-global; parallel tests