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
perf: cache turn integration and skill discovery
Steven Enamakeld7f3409ee93c
diff --git a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rsindex 258dcbffd4..1cfb6ff1cc 100644--- a/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs+++ b/crates/openhuman-core/src/agent/session_host/prelude_integrations.rs@@ -32,8 +32,7 @@ impl OpenHumanTurnPrelude {pub(super) async fn refresh_turn_boundary(&self, cold: bool) {// Hydrate on the first turn of *this session instance*, not only on a// brand-new thread. A resumed thread is never `cold`, and a session- // rebuilt after a restart (or any rebuild past the 60 s integrations- // cache TTL) is seeded from an empty cache — gating the fetch on+ // rebuilt after a restart is seeded from an empty cache — gating the fetch on// `cold` left it with zero integrations, no deferred Composio// actions, and no `tool_search` bridge for the whole thread.// `refresh_cold_integrations` is a no-op once hydrated.@@ -113,8 +112,8 @@ impl OpenHumanTurnPrelude {.map(Arc::new),};if let Some(config) = config.as_deref() {- // An expired cache is refetched rather than skipped, so a- // long-lived session keeps tracking connects/revokes.+ // The connection list and change events invalidate the process+ // snapshot, so the turn reads it without an idle-time refresh.let current = match crate::integrations::composio::cached_active_integrations(config) {Some(current) => Some((current, true)),None => load_connected_integrations(config).await,diff --git a/crates/openhuman-core/src/integrations/composio/README.md b/crates/openhuman-core/src/integrations/composio/README.mdindex 7a0ecebf5b..8e458c8fe4 100644--- a/crates/openhuman-core/src/integrations/composio/README.md+++ b/crates/openhuman-core/src/integrations/composio/README.md@@ -160,7 +160,7 @@ Published from `ops/` via `crate::core::bus::BUS.publish` (`crate::core::events:- **Direct-mode API key**: stored in the encrypted keychain (via `credentials`); never logged/returned. `direct_auth/mod.rs` additionally tracks a process-local (non-persisted) consecutive-401 counter for the same key.- **Identity facets**: written through the bound memory driver via `identity_store.rs` (`MemoryProfile::upsert_provider_facet`) and mirrored into `PROFILE.md` by `profile_md.rs`; **user scope prefs** persist through `ops::user_scopes` over the same bound driver (`crate::memory::binding`).- **Connection-scoped cleanup**: `ops::memory_cleanup` deletes through `MemorySourceSink::forget_matching` (the `Source` / `SourcePrefix` / `Owner` selectors) rather than through the engine's chunk store (#5560). A driver that does not serve `Sources` is refused per target, and the refusal is reported beside `memory_chunks_deleted` rather than read as a delete of nothing.-- **Integrations cache**: in-process cache of active connections (`cached_active_integrations` / `invalidate_connected_integrations_cache`, `connected_integrations.rs`), reconciled on each `list_connections`.+- **Integrations cache**: warmed in the background after app startup/sign-in, then kept for the process lifetime. Connection create/delete, config changes, and a divergent `list_connections` response invalidate it; the change paths eagerly re-warm it. Idle time does not trigger a backend fetch on a chat turn (`connected_integrations.rs`).## Dependenciesdiff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations.rsindex a71e5f3bc5..164e8f5933 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations.rs@@ -33,6 +33,6 @@ pub use fetch::{// these via a plain `use super::<name>;`, exactly as when this was one// un-split file. See each item's `pub(super)` in its owning submodule.#[cfg(test)]-pub(crate) use cache::{cache_key, CachedIntegrations, CACHE_TTL, INTEGRATIONS_CACHE};+pub(crate) use cache::{cache_key, CachedIntegrations, INTEGRATIONS_CACHE};#[cfg(test)]pub(crate) use fetch::{connectable_toolkit_slugs, resolve_toolkit_description};diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rsindex 0b75e6453d..23eb01dc7c 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/cache.rs@@ -9,34 +9,12 @@ use crate::agent::prompts::ConnectedIntegration;use crate::config::Config;use std::collections::{HashMap, HashSet};+use std::sync::atomic::{AtomicU64, Ordering};use std::sync::{LazyLock, RwLock};-use std::time::{Duration, Instant};+use std::time::Instant;// ── Prompt integration discovery ────────────────────────────────────-/// Defensive TTL on the integrations cache.-///-/// Background: the primary invalidation path is the-/// `ComposioConnectionCreated` → `wait_for_connection_active` bus flow-/// (see [`crate::integrations::composio::bus::ComposioConnectionCreatedSubscriber`]), which-/// polls the backend for up to 60 s after `composio_authorize` returns-/// a `connectUrl`. On Windows the OAuth round-trip can exceed that-/// window (Defender SmartScreen, slower browser launch, extra consent-/// dialogs), so the invalidation call never fires and the chat-/// runtime's cache stays frozen on the pre-connect snapshot even-/// though the Settings UI polls `composio_list_connections` every 5 s-/// and shows the user as "Connected".-///-/// The cross-platform defenses we layer on top:-/// 1. [`composio_list_connections`] diff-invalidates the cache whenever-/// the backend's active-toolkit set diverges from what's cached,-/// so a running UI keeps the chat cache in sync within one poll-/// interval.-/// 2. This TTL caps worst-case staleness at 60 s regardless of-/// whether the UI is open, the bus fires, or the user reconnected-/// out-of-band.-pub(crate) const CACHE_TTL: Duration = Duration::from_secs(60);-/// Cached entry: the integrations list plus the timestamp we wrote it.#[derive(Clone)]pub(crate) struct CachedIntegrations {@@ -47,10 +25,14 @@ pub(crate) struct CachedIntegrations {/// Process-wide cache for connected integrations, keyed by the config/// identity (the `config_path` string) so different user contexts don't/// collide. Each entry is populated on first fetch and returned on-/// subsequent calls until explicitly invalidated or the TTL expires.+/// subsequent calls until explicitly invalidated or the process exits.pub(crate) static INTEGRATIONS_CACHE: LazyLock<RwLock<HashMap<String, CachedIntegrations>>> =LazyLock::new(|| RwLock::new(HashMap::new()));+/// Prevent an in-flight startup warm from restoring a snapshot that was+/// invalidated while its backend requests were running.+pub(crate) static CACHE_GENERATION: AtomicU64 = AtomicU64::new(0);+/// Crate-wide test serialization lock for all tests that mutate or read/// the process-global `INTEGRATIONS_CACHE`. Defined here so it is shared/// by every `cfg(test)` module in this crate (ops_tests, tools_tests, …).@@ -83,6 +65,7 @@ pub fn invalidate_connected_integrations_cache() {if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {let entries = guard.len();guard.clear();+ CACHE_GENERATION.fetch_add(1, Ordering::SeqCst);tracing::info!(cached_keys = entries,"[composio][integrations] cache invalidated"@@ -91,53 +74,33 @@ pub fn invalidate_connected_integrations_cache() {}/// Read-only snapshot of the currently cached connected integrations for-/// the given config, or [`None`] when the cache is empty, expired, or+/// the given config, or [`None`] when the cache is empty or/// the lock is held by a writer.////// Designed for hot-path callers that want a cheap "what does the cache-/// already say?" probe without triggering a backend fetch. The agent-/// harness uses this on every turn to detect mid-session connection-/// changes — it relies on the desktop UI's 5 s `composio_list_connections`-/// poll (which calls into [`fetch_connected_integrations`] and-/// repopulates this cache) plus the event-driven invalidation path to-/// keep the cache current.+/// already say?" probe without triggering a backend fetch. Connection+/// changes invalidate the snapshot and trigger a background refresh.////// `try_read` (not `read`) so a writer in progress — e.g. the UI poll/// repopulating the cache — never blocks a turn. Worst case the agent/// sees `None` for one turn while the writer holds the lock; the next/// turn picks up the value naturally.///-/// TTL is enforced defensively: entries older than [`CACHE_TTL`] are-/// treated as missing even though they're still in the map (a stale-/// entry would otherwise pin the agent to a frozen view if every-/// invalidation path silently failed).+/// Freshness is driven by connection events and the Settings connection-list+/// reconciliation, never by an idle-time expiry on the chat critical path.pub fn cached_active_integrations(config: &Config) -> Option<Vec<ConnectedIntegration>> {- read_cached_integrations(config, false)+ read_cached_integrations(config)}-/// Like [`cached_active_integrations`] but returns the last cached snapshot-/// even when it has aged past [`CACHE_TTL`].-///-/// Intended ONLY as a transient-failure fallback: when a live fetch reports-/// `Unavailable`/times out, preserving the last-known integrations is strictly-/// better than collapsing the integration surface to an empty set (which drops-/// every searchable integration action and silently disables channel tool-calling).-/// Without this, a backend blip that lands just after the 60 s TTL expiry still-/// wipes tool-calling despite having a perfectly good previous snapshot. A fresh-/// fetch repopulates the cache the moment the backend recovers, so the stale-/// window is bounded by the outage, not by this call.+/// Compatibility alias for callers preserving the last-known snapshot when a+/// connection-change refresh fails. Entries have no time-based expiry.pub fn cached_active_integrations_including_expired(config: &Config,) -> Option<Vec<ConnectedIntegration>> {- read_cached_integrations(config, true)+ read_cached_integrations(config)}-/// Shared reader for the integrations cache. `allow_expired` bypasses the-/// [`CACHE_TTL`] freshness check for the transient-failure fallback path.-fn read_cached_integrations(- config: &Config,- allow_expired: bool,-) -> Option<Vec<ConnectedIntegration>> {+fn read_cached_integrations(config: &Config) -> Option<Vec<ConnectedIntegration>> {let key = cache_key(config);let guard = match INTEGRATIONS_CACHE.try_read() {Ok(g) => g,@@ -157,30 +120,10 @@ fn read_cached_integrations(return None;};let age = cached.cached_at.elapsed();- if !allow_expired && age > CACHE_TTL {- tracing::trace!(- key = %key,- age_ms = age.as_millis() as u64,- ttl_ms = CACHE_TTL.as_millis() as u64,- "[composio][integrations_cache] cached_active_integrations:expired"- );- return None;- }- // Surface a *very* stale fallback so an unusually long backend outage is- // observable rather than silently pinning the agent to an ancient snapshot.- if allow_expired && age > 5 * CACHE_TTL {- tracing::warn!(- key = %key,- age_ms = age.as_millis() as u64,- ttl_ms = CACHE_TTL.as_millis() as u64,- "[composio][integrations_cache] serving a heavily-stale integrations snapshot on transient-failure fallback (backend outage?)"- );- }tracing::trace!(key = %key,entries = cached.entries.len(),age_ms = age.as_millis() as u64,- allow_expired,"[composio][integrations_cache] cached_active_integrations:hit");Some(cached.entries.clone())@@ -253,10 +196,11 @@ fn connected_toolkit_set(integrations: &[ConnectedIntegration]) -> HashSet<Strin/// `fetch_connected_integrations` call. This keeps tool availability/// in chat in sync with the badge the user sees in Settings, even when/// the primary event-bus invalidation path misses (e.g. Windows OAuth-/// flows that overrun the 60 s readiness poll).+/// flows that overrun the 60 s readiness poll). Returns whether an entry was+/// invalidated so the caller can eagerly re-warm it away from a chat turn.pub(crate) fn sync_cache_with_connections(connections: &[crate::integrations::composio::types::ComposioConnection],-) {+) -> bool {let live_active: HashSet<String> = connections.iter().filter(|c| c.is_active())@@ -285,7 +229,7 @@ pub(crate) fn sync_cache_with_connections(// lock before taking the write lock.let divergent_keys: Vec<(String, HashSet<String>, HashSet<String>)> = {let Ok(guard) = INTEGRATIONS_CACHE.read() else {- return;+ return false;};guard.iter()@@ -321,10 +265,11 @@ pub(crate) fn sync_cache_with_connections(live_connected = live_active.len(),"[composio][integrations] list_connections matches cache — no invalidation needed");- return;+ return false;}if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {+ CACHE_GENERATION.fetch_add(1, Ordering::SeqCst);for (key, cached_set, live_set) in divergent_keys {// Diff logging — makes Windows-timing regressions easy to// catch in user-supplied debug dumps without leaking any@@ -339,5 +284,7 @@ pub(crate) fn sync_cache_with_connections();guard.remove(&key);}+ return true;}+ false}diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rsindex c798a88387..96271e355f 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs@@ -4,12 +4,13 @@//! on a miss) and the just-in-time [`fetch_toolkit_actions`], plus their//! small toolkit-membership/description helpers.+use std::sync::atomic::Ordering;use std::time::Instant;use crate::agent::prompts::{ConnectedIntegration, ConnectedIntegrationTool};use crate::config::Config;-use super::cache::{cache_key, CachedIntegrations, CACHE_TTL, INTEGRATIONS_CACHE};+use super::cache::{cache_key, CachedIntegrations, CACHE_GENERATION, INTEGRATIONS_CACHE};use super::fetch_uncached::fetch_connected_integrations_uncached;use crate::integrations::composio::client::ComposioClient;use crate::integrations::composio::ops::should_forward_tags;@@ -23,10 +24,8 @@ use crate::integrations::composio::ops::should_forward_tags;////// Results are cached process-wide (keyed by config identity) and/// returned instantly on subsequent calls. The cache is invalidated-/// when a new connection is created-/// (via [`invalidate_connected_integrations_cache`]), when a UI-/// `list_connections` poll observes a divergent live set, when-/// [`CACHE_TTL`] expires, or on process restart.+/// when a connection changes (via [`invalidate_connected_integrations_cache`]+/// or `list_connections` reconciliation), or on process restart.////// Best-effort: returns an empty vec when the user isn't signed in,/// the backend is unreachable, or any step fails.@@ -84,42 +83,41 @@ pub async fn fetch_connected_integrations_status(}let key = cache_key(config);- // Fast path: return cached result if fresh. Stale entries fall- // through to the backend fetch below so the chat runtime can never- // be more than `CACHE_TTL` behind a real-world change.+ // A connection event or a divergent list_connections response invalidates+ // this snapshot. Idle time alone must never put a network request on the+ // first-token path.if let Ok(guard) = INTEGRATIONS_CACHE.read() {if let Some(cached) = guard.get(&key) {let age = cached.cached_at.elapsed();- if age < CACHE_TTL {- tracing::debug!(- count = cached.entries.len(),- age_ms = age.as_millis() as u64,- key = %key,- "[composio][integrations] returning cached result"- );- return FetchConnectedIntegrationsStatus::Authoritative(cached.entries.clone());- }- tracing::info!(+ tracing::debug!(count = cached.entries.len(),age_ms = age.as_millis() as u64,- ttl_ms = CACHE_TTL.as_millis() as u64,key = %key,- "[composio][integrations] cache entry expired — refetching"+ "[composio][integrations] returning cached result");+ return FetchConnectedIntegrationsStatus::Authoritative(cached.entries.clone());}}+ let generation = CACHE_GENERATION.load(Ordering::SeqCst);match fetch_connected_integrations_uncached(config).await {Some(result) => {// Backend was reachable — cache the result (even if empty).if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {- guard.insert(- key,- CachedIntegrations {- entries: result.clone(),- cached_at: Instant::now(),- },- );+ if CACHE_GENERATION.load(Ordering::SeqCst) == generation {+ guard.insert(+ key,+ CachedIntegrations {+ entries: result.clone(),+ cached_at: Instant::now(),+ },+ );+ } else {+ tracing::debug!(+ "[composio][integrations] discarded fetch invalidated in flight"+ );+ return FetchConnectedIntegrationsStatus::Unavailable;+ }}FetchConnectedIntegrationsStatus::Authoritative(result)}diff --git a/crates/openhuman-core/src/integrations/composio/ops/connections.rs b/crates/openhuman-core/src/integrations/composio/ops/connections.rsindex c4423cf780..1964d395a2 100644--- a/crates/openhuman-core/src/integrations/composio/ops/connections.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/connections.rs@@ -91,7 +91,15 @@ pub async fn composio_list_connections(let active = resp.connections.iter().filter(|c| c.is_active()).count();let total = resp.connections.len();- sync_cache_with_connections(&resp.connections);+ if sync_cache_with_connections(&resp.connections) {+ // The Settings poll also catches OAuth completions that outlive the+ // connection-created subscriber's readiness window. Re-warm here so+ // the next chat turn does not perform the three discovery requests.+ let config = config.clone();+ tokio::spawn(async move {+ let _ = fetch_connected_integrations_status(&config).await;+ });+ }let resp = enrich_connections_with_identity(config, resp).await;Ok(RpcOutcome::new(resp,diff --git a/crates/openhuman-core/src/integrations/composio/ops/mod.rs b/crates/openhuman-core/src/integrations/composio/ops/mod.rsindex a9e471df5c..1ede599a4a 100644--- a/crates/openhuman-core/src/integrations/composio/ops/mod.rs+++ b/crates/openhuman-core/src/integrations/composio/ops/mod.rs@@ -96,7 +96,7 @@ pub use super::types::{ComposioConnection as Connection, ComposioToolSchema as T#[cfg(test)]pub(crate) use super::connected_integrations::cache_key;#[cfg(test)]-pub(crate) use super::connected_integrations::{CachedIntegrations, CACHE_TTL, INTEGRATIONS_CACHE};+pub(crate) use super::connected_integrations::{CachedIntegrations, INTEGRATIONS_CACHE};#[cfg(test)]pub(crate) use crate::agent::prompts::ConnectedIntegration;#[cfg(test)]diff --git a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rsindex 470180ab72..b0825253a9 100644--- a/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/ops_fetch_integrations_and_triggers_tests.rs@@ -194,12 +194,14 @@ fn sync_cache_invalidates_when_connection_becomes_active() {// Fresh UI poll shows gmail just flipped ACTIVE — mirrors a// user who finished OAuth in the system browser.- sync_cache_with_connections(&[conn("c-1", "gmail", "ACTIVE")]);+ assert!(sync_cache_with_connections(&[conn(+ "c-1", "gmail", "ACTIVE"+ )]));// Chat-runtime cache must be cleared so the next// `fetch_connected_integrations` re-fetches truth from the// backend. Without this fix the entry would live on until- // `CACHE_TTL` expired or the process restarted.+ // the connection changes or the process restarts.let guard = INTEGRATIONS_CACHE.read().unwrap();assert!(guard.get(key).is_none(),@@ -217,7 +219,7 @@ fn sync_cache_invalidates_when_connection_is_removed() {clear_cache_key(key);seed_cache(key, vec![integration("gmail", true)]);- sync_cache_with_connections(&[]);+ assert!(sync_cache_with_connections(&[]));let guard = INTEGRATIONS_CACHE.read().unwrap();assert!(@@ -298,44 +300,33 @@ fn sync_cache_treats_connected_status_equivalent_to_active() {);}-#[test]-fn cache_entries_expire_after_ttl() {+#[tokio::test]+async fn cache_entries_survive_idle_time_until_connection_change() {let _guard = cache_guard();- // Even without any UI polling, the chat runtime must- // self-heal stale state within `CACHE_TTL`. We can't wait- // 60 s in a unit test; instead, directly age the entry by- // rewriting its `cached_at`.- let key = "windows-regression-6";- clear_cache_key(key);- seed_cache(key, vec![integration("gmail", true)]);-- // Age the entry past the TTL.+ let tmp = tempfile::TempDir::new().unwrap();+ let config = test_config(&tmp);+ let key = crate::integrations::composio::connected_integrations::cache_key(&config);+ clear_cache_key(&key);+ seed_cache(&key, vec![integration("gmail", true)]);{let mut guard = INTEGRATIONS_CACHE.write().unwrap();- let entry = guard.get_mut(key).unwrap();- entry.cached_at = Instant::now() - (CACHE_TTL + Duration::from_secs(1));+ guard.get_mut(&key).unwrap().cached_at = Instant::now() - Duration::from_secs(3600);}-- // Re-read via the public API — expired reads must not serve- // the stale entry. We can't trigger a real backend call in a- // unit test, so assert that the read path falls through (by- // asserting the entry is still present before the read, and- // proving the staleness check via a direct helper).- let is_fresh = {- let guard = INTEGRATIONS_CACHE.read().unwrap();- guard- .get(key)- .map(|c| c.cached_at.elapsed() < CACHE_TTL)- .unwrap_or(false)- };- assert!(- !is_fresh,- "entry aged past CACHE_TTL must not be treated as fresh"- );+ assert_eq!(cached_active_integrations(&config).unwrap().len(), 1);+ assert!(matches!(+ fetch_connected_integrations_status(&config).await,+ FetchConnectedIntegrationsStatus::Authoritative(entries) if entries.len() == 1+ ));+ sync_cache_with_connections(&[]);+ assert!(cached_active_integrations(&config).is_none());+ assert!(matches!(+ fetch_connected_integrations_status(&config).await,+ FetchConnectedIntegrationsStatus::Unavailable+ ));}#[test]-fn including_expired_serves_stale_snapshot_for_transient_fallback() {+fn fallback_reader_matches_main_reader_without_time_based_expiry() {let _guard = cache_guard();let tmp = tempfile::TempDir::new().unwrap();let config = test_config(&tmp);@@ -343,20 +334,12 @@ fn including_expired_serves_stale_snapshot_for_transient_fallback() {clear_cache_key(&key);seed_cache(&key, vec![integration("gmail", true)]);- // Age the entry past the TTL (simulates a session idle > 60s).+ // Simulate a long idle session.{let mut guard = INTEGRATIONS_CACHE.write().unwrap();- guard.get_mut(&key).unwrap().cached_at =- Instant::now() - (CACHE_TTL + Duration::from_secs(1));+ guard.get_mut(&key).unwrap().cached_at = Instant::now() - Duration::from_secs(3600);}-- // The TTL-enforcing read treats the expired entry as missing…- assert!(- cached_active_integrations(&config).is_none(),- "expired entry must not be served by the freshness-checked read"- );- // …but the transient-failure fallback read preserves the last-known set,- // so a backend blip just after TTL expiry doesn't drop tool-calling.+ assert!(cached_active_integrations(&config).is_some());let stale = cached_active_integrations_including_expired(&config).expect("expired entry should still be returned by the fallback read");assert_eq!(stale.len(), 1);diff --git a/crates/openhuman-core/src/mcp/registry/README.md b/crates/openhuman-core/src/mcp/registry/README.mdindex 750e8bc0b3..5979a567c1 100644--- a/crates/openhuman-core/src/mcp/registry/README.md+++ b/crates/openhuman-core/src/mcp/registry/README.md@@ -143,6 +143,10 @@ same real type in both builds.- `crates/openhuman-core/src/mcp/mod.rs` — `start`/`start_boot_jobs` wire up`bus::init()`, `boot::spawn_installed_servers`, and the reconnectsupervisor.+- `tinymcp`'s live connection map is the process cache: startup connects+ installed servers, and connect, disconnect, config updates, and reconnects+ update 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`route calls `oauth::complete`.- `crates/openhuman-core/src/tools/registry/ops.rs` anddiff --git a/crates/openhuman-core/src/memory/sync/composio/bus/config_changed_subscriber.rs b/crates/openhuman-core/src/memory/sync/composio/bus/config_changed_subscriber.rsindex 3f8f294bc0..9704ce23af 100644--- a/crates/openhuman-core/src/memory/sync/composio/bus/config_changed_subscriber.rs+++ b/crates/openhuman-core/src/memory/sync/composio/bus/config_changed_subscriber.rs@@ -13,7 +13,7 @@ use crate::integrations::composio::FetchConnectedIntegrationsStatus;/// `config.composio().mode` between `"backend"` and `"direct"` or/// stores/clears the direct-mode API key. Without this, the chat/// runtime keeps the old tenant's tool catalogue / connection list-/// pinned for up to `CACHE_TTL` (60s) — that's the regression behind+/// pinned until another event or process restart — that's the regression behind/// "I switched to Direct and my old integrations are still showing"/// (#1710).///diff --git a/crates/openhuman-core/src/security/credentials/ops/credential.rs b/crates/openhuman-core/src/security/credentials/ops/credential.rsindex 8e332a21c6..563f3cc8bf 100644--- a/crates/openhuman-core/src/security/credentials/ops/credential.rs+++ b/crates/openhuman-core/src/security/credentials/ops/credential.rs@@ -24,7 +24,9 @@ use crate::security::credentials::{api_key, identity, sentry_scope, AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME,};-use super::gated_services::{start_credential_gated_services, stop_credential_gated_services};+use super::gated_services::{+ spawn_integrations_cache_warm, start_credential_gated_services, stop_credential_gated_services,+};use super::user_scope::{activate_user_scope, deactivate_user_scope, rebind_after_credential_change, reload_config_or,};@@ -186,12 +188,15 @@ pub async fn set_credential(let was_authenticated =crate::security::credentials::session_support::has_backend_credential(config);api_key::store_api_key(config, &resolved.token).map_err(|e| e.to_string())?;+ crate::integrations::composio::invalidate_connected_integrations_cache();// API-key-backed runs must not retain a previous session identity in// prompt composition or observability scope.identity::clear_current_user();sentry_scope::clear();if !was_authenticated {start_credential_gated_services(config).await;+ } else {+ spawn_integrations_cache_warm(config);}crate::cron::scheduler_gate::set_signed_out(false);tracing::info!(@@ -281,6 +286,7 @@ pub async fn set_credential(logs.push(format!("{} credential stored", resolved.kind.as_str()));if !refresh {+ crate::integrations::composio::invalidate_connected_integrations_cache();if let Err(error) =rebind_after_credential_change(&effective_config, "credential installed"){@@ -412,6 +418,7 @@ pub async fn clear_credential(removed_api_key =api_key::clear_api_key(config).map_err(|e| e.to_string())? || cleared_source_api_key;if removed_api_key {+ crate::integrations::composio::invalidate_connected_integrations_cache();logs.push("api key cleared".to_string());}if !crate::security::credentials::session_support::has_backend_credential(config) {@@ -430,6 +437,7 @@ pub async fn clear_credential(.and_then(|raw| serde_json::from_str(raw).ok()),);}+ spawn_integrations_cache_warm(config);}}@@ -471,6 +479,9 @@ async fn clear_session_credential(config: &Config) -> Result<RpcOutcome<bool>, Slet removed = AuthService::from_config(config).remove_profile(APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME).map_err(|e| e.to_string())?;+ if removed {+ crate::integrations::composio::invalidate_connected_integrations_cache();+ }// The core process stays alive on sign-out. Tear down its authenticated// Socket.IO transport and the user-pinned workflow bridge so neither candiff --git a/crates/openhuman-core/src/security/credentials/ops/gated_services.rs b/crates/openhuman-core/src/security/credentials/ops/gated_services.rsindex f8f7eb29e6..713810d7cf 100644--- a/crates/openhuman-core/src/security/credentials/ops/gated_services.rs+++ b/crates/openhuman-core/src/security/credentials/ops/gated_services.rs@@ -15,6 +15,31 @@ pub(super) fn is_embedder_host() -> bool {crate::core::runtime::context::CoreContext::current_embedder_config().is_some()}+/// Populate the process cache away from the next chat turn after startup or a+/// credential change. Connection changes have their own invalidation paths.+pub(super) fn spawn_integrations_cache_warm(config: &Config) {+ let integration_config = config.clone();+ tokio::spawn(async move {+ let started = std::time::Instant::now();+ match crate::integrations::composio::fetch_connected_integrations_status(+ &integration_config,+ )+ .await+ {+ crate::integrations::composio::FetchConnectedIntegrationsStatus::Authoritative(+ entries,+ ) => log::info!(+ "[services] integrations cache warmed entries={} elapsed_ms={}",+ entries.len(),+ started.elapsed().as_millis()+ ),+ crate::integrations::composio::FetchConnectedIntegrationsStatus::Unavailable => {+ log::debug!("[services] integrations cache warm unavailable; first turn may retry")+ }+ }+ });+}+/// Start all login-gated background services (local AI and voice). Called both/// from the initial boot path (when an existing/// session is detected) and from `set_credential()` when a credential is installed.@@ -51,6 +76,18 @@ pub async fn start_credential_gated_services(config: &Config) {return;}+ // An embedder's task-local user-root policy does not cross spawn_blocking;+ // its first agent build warms the correctly scoped cache instead.+ if !is_embedder_host() {+ let skills_workspace = config.workspace_dir.clone();+ let _ = tokio::task::spawn_blocking(move || {+ let count = crate::skills::load_workflow_metadata(&skills_workspace).len();+ log::debug!("[services] skill metadata cache warmed entries={count}");+ });+ }++ spawn_integrations_cache_warm(config);+let started = std::time::Instant::now();// (service label, task) pairs so a panic surfaced on join is attributed to// the specific stage rather than an anonymous "a service failed".diff --git a/crates/openhuman-core/src/skills/README.md b/crates/openhuman-core/src/skills/README.mdindex 388ab5e71a..d80c29c237 100644--- a/crates/openhuman-core/src/skills/README.md+++ b/crates/openhuman-core/src/skills/README.md@@ -48,7 +48,7 @@ Plus the sub-domain namespaces: `skill_registry.*` (`browse`, `search`, `sources- `crates/openhuman-core/src/config/workspace/ops.rs` — calls `skills::init_workflows_dir` during workspace bootstrap.- `crates/openhuman-core/src/agent/registry/agents/orchestrator/prompt.rs` — renders the `## Installed Skills` catalog, fed by the skill list on `PromptContext` (`agent/session_host/turn/context.rs`).- `crates/openhuman-core/src/agent/context/channels_prompt.rs` — renders the `## Available Skills` list for channel-driven turns (`agent/prompts/` no longer emits a skills section).-- `crates/openhuman-core/src/core/bus.rs` / `crates/openhuman-core/src/core/events.rs` — `bus.rs` subscribes to `DomainEvent` for triggered skills; `ops_create.rs` and `ops_install/fetch.rs` publish `DomainEvent::WorkflowsChanged` after create/install/uninstall so open sessions refresh their catalog. (`WorkflowLoaded`/`WorkflowStopped`/`WorkflowStartFailed`/`WorkflowExecuted` are declared in `events.rs` but nothing in this module publishes them.)+- `crates/openhuman-core/src/core/bus.rs` / `crates/openhuman-core/src/core/events.rs` — `bus.rs` subscribes to `DomainEvent` for triggered skills; create/install/uninstall invalidate the process-wide metadata cache and publish `DomainEvent::WorkflowsChanged` so open sessions refresh their catalog. App startup warms the metadata cache in the background. (`WorkflowLoaded`/`WorkflowStopped`/`WorkflowStartFailed`/`WorkflowExecuted` are declared in `events.rs` but nothing in this module publishes them.)- `crates/openhuman-core/src/agent/harness/definition.rs` — `registry.rs` flattens `AgentDefinition` fields from `skill.toml`.## Called bydiff --git a/crates/openhuman-core/src/skills/ops_create.rs b/crates/openhuman-core/src/skills/ops_create.rsindex 9f405a13ac..78811721eb 100644--- a/crates/openhuman-core/src/skills/ops_create.rs+++ b/crates/openhuman-core/src/skills/ops_create.rs@@ -407,6 +407,7 @@ pub(crate) fn create_workflow_inner(// Notify live agent sessions so they pick up the new skill in their// `## Installed Skills` catalogue (see `OpenHumanSessionHost::refresh_workflows`).+ crate::skills::ops_discover::invalidate_workflow_metadata_cache();crate::core::bus::BUS.publish(crate::core::events::DomainEvent::WorkflowsChanged {reason: "create".to_string(),});diff --git a/crates/openhuman-core/src/skills/ops_discover.rs b/crates/openhuman-core/src/skills/ops_discover.rsindex d1329c4476..ef7f27e60b 100644--- a/crates/openhuman-core/src/skills/ops_discover.rs+++ b/crates/openhuman-core/src/skills/ops_discover.rs@@ -27,6 +27,7 @@ pub use api::{pub use resource::read_workflow_resource;pub(crate) use api::discover_workflows_inner;+pub(crate) use api::invalidate_workflow_metadata_cache;#[cfg(test)]pub(crate) use api::DISCOVERY_CALLS;diff --git a/crates/openhuman-core/src/skills/ops_discover/api.rs b/crates/openhuman-core/src/skills/ops_discover/api.rsindex c45ec45bdd..b3553f2a30 100644--- a/crates/openhuman-core/src/skills/ops_discover/api.rs+++ b/crates/openhuman-core/src/skills/ops_discover/api.rs@@ -2,12 +2,30 @@//! of `load_workflow_metadata*` / `discover_workflows*` shims that select a//! root scan (see [`super::scan`]) for a given caller shape.+use std::collections::HashMap;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::{LazyLock, RwLock};use crate::skills::ops_types::{Workflow, TRUST_MARKER};use super::scan::{discover_filtered, ALL_ROOT_KINDS, WORKFLOW_ROOT_KINDS};+type MetadataCacheKey = (PathBuf, Option<PathBuf>, bool);+static METADATA_CACHE: LazyLock<RwLock<HashMap<MetadataCacheKey, Vec<Workflow>>>> =+ LazyLock::new(|| RwLock::new(HashMap::new()));+static METADATA_GENERATION: AtomicU64 = AtomicU64::new(0);++/// Drop the process-wide metadata snapshot after a skill is created, installed,+/// or removed. Live sessions receive `WorkflowsChanged` separately and rebuild+/// their own catalogue from the next cached snapshot.+pub(crate) fn invalidate_workflow_metadata_cache() {+ if let Ok(mut cache) = METADATA_CACHE.write() {+ cache.clear();+ METADATA_GENERATION.fetch_add(1, Ordering::SeqCst);+ }+}+/// Initialize the legacy skills directory in the specified workspace.////// Creates `<workspace>/skills/` and a placeholder `README.md` so the folder@@ -65,7 +83,20 @@ pub fn discovery_home_dir() -> Option<PathBuf> {pub fn load_workflow_metadata(workspace_dir: &Path) -> Vec<Workflow> {let trusted = is_workspace_trusted(workspace_dir);let home = discovery_home_dir();- discover_workflows_inner(home.as_deref(), Some(workspace_dir), trusted)+ let key = (workspace_dir.to_path_buf(), home.clone(), trusted);+ if let Ok(cache) = METADATA_CACHE.read() {+ if let Some(workflows) = cache.get(&key) {+ return workflows.clone();+ }+ }+ let generation = METADATA_GENERATION.load(Ordering::SeqCst);+ let workflows = discover_workflows_inner(home.as_deref(), Some(workspace_dir), trusted);+ if let Ok(mut cache) = METADATA_CACHE.write() {+ if METADATA_GENERATION.load(Ordering::SeqCst) == generation {+ cache.insert(key, workflows.clone());+ }+ }+ workflows}/// Discover skills from every supported location.diff --git a/crates/openhuman-core/src/skills/ops_discovery_tests.rs b/crates/openhuman-core/src/skills/ops_discovery_tests.rsindex 731e988825..61664e88fb 100644--- a/crates/openhuman-core/src/skills/ops_discovery_tests.rs+++ b/crates/openhuman-core/src/skills/ops_discovery_tests.rs@@ -701,3 +701,31 @@ async fn load_workflow_metadata_skips_user_roots_under_a_hidden_context() {"no user-scope skill may leak into a hidden-root context: {names:?}");}++#[test]+fn workflow_metadata_is_reused_until_invalidated() {+ let workspace = tempfile::tempdir().unwrap();+ let skill = workspace.path().join("skills").join("cached-skill");+ write(+ &skill.join("SKILL.md"),+ "---\nname: cached-skill\ndescription: first version\n---\n",+ );+ let first = load_workflow_metadata(workspace.path());+ assert!(first.iter().any(|item| item.name == "cached-skill"));++ std::fs::remove_dir_all(&skill).unwrap();+ assert!(+ load_workflow_metadata(workspace.path())+ .iter()+ .any(|item| item.name == "cached-skill"),+ "a turn reuses the startup snapshot"+ );++ crate::skills::ops_discover::invalidate_workflow_metadata_cache();+ assert!(+ !load_workflow_metadata(workspace.path())+ .iter()+ .any(|item| item.name == "cached-skill"),+ "a skill change refreshes the snapshot"+ );+}diff --git a/crates/openhuman-core/src/skills/ops_install/fetch.rs b/crates/openhuman-core/src/skills/ops_install/fetch.rsindex c100571035..0dab37c755 100644--- a/crates/openhuman-core/src/skills/ops_install/fetch.rs+++ b/crates/openhuman-core/src/skills/ops_install/fetch.rs@@ -438,6 +438,7 @@ pub(crate) async fn install_workflow_from_url_with_home(// Notify live agent sessions so they refresh their `## Installed Skills`// catalogue mid-conversation (see `OpenHumanSessionHost::refresh_workflows`).+ crate::skills::ops_discover::invalidate_workflow_metadata_cache();crate::core::bus::BUS.publish(crate::core::events::DomainEvent::WorkflowsChanged {reason: "install".to_string(),});diff --git a/crates/openhuman-core/src/skills/ops_install/uninstall.rs b/crates/openhuman-core/src/skills/ops_install/uninstall.rsindex a43cd8c06d..80f7c59fc4 100644--- a/crates/openhuman-core/src/skills/ops_install/uninstall.rs+++ b/crates/openhuman-core/src/skills/ops_install/uninstall.rs@@ -166,6 +166,7 @@ pub fn uninstall_workflow(// Notify live agent sessions to drop the removed skill from their// `## Installed Skills` catalogue (see `OpenHumanSessionHost::refresh_workflows`).+ crate::skills::ops_discover::invalidate_workflow_metadata_cache();crate::core::bus::BUS.publish(crate::core::events::DomainEvent::WorkflowsChanged {reason: "uninstall".to_string(),});