Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(memory): remove obsolete composio bus subscriber modules

Steven Enamakel1669fb298ce8
diff --git a/crates/openhuman-core/src/memory/sync/composio/bus_part_01.rs b/crates/openhuman-core/src/memory/sync/composio/bus_part_01.rs
deleted file mode 100644
index cf31b5217a..0000000000
--- a/crates/openhuman-core/src/memory/sync/composio/bus_part_01.rs
+++ /dev/null
@@ -1,462 +0,0 @@
-use std::sync::{Arc, OnceLock};
-use std::time::Duration;
-
-use async_trait::async_trait;
-
-use crate::core::bus::BUS;
-use crate::core::events::DomainEvent;
-use crate::agent::triage::{
- apply_decision, remote_trigger_origin, run_triage, TriageOutcome, TriggerEnvelope,
-};
-use crate::agent::turn_origin::with_origin;
-use crate::config::rpc as config_rpc;
-use crate::integrations::composio::trigger_history;
-use tinybus::EventHandler;
-use tinybus::SubscriptionHandle;
-use tinymemory_api::host::COMPOSIO_MODE_DIRECT;
-
-/// A backend-tenant Composio client for one toolkit.
-///
-/// This was `ProviderContextExt::backend_client`, an extension trait on the
-/// engine's `ProviderContext` that existed for a single caller — the
-/// connection-readiness probe below. With the context gone the trait had
-/// nothing to extend, so the resolution lives here instead.
-///
-/// The config is reloaded rather than taken from the snapshot on purpose: the
-/// OAuth completion this subscriber reacts to may have written credentials
-/// since, and a `composio.mode` toggle mid-session must take effect on the
-/// next call. Direct mode is a hard error rather than a silent fallback — the
-/// helpers behind this were written against the backend tenant, and routing
-/// them through the wrong one is worse than refusing (#1710).
-async fn backend_composio_client(
- config: &crate::config::Config,
- toolkit: &str,
-) -> anyhow::Result<ComposioClient> {
- let live_config = crate::config::rpc::reload_config_from_paths(
- &config.config_path,
- &config.workspace_dir,
- )
- .await
- .map_err(|e| anyhow::anyhow!("composio backend client: failed to reload live config: {e}"))?;
- match create_composio_client(&live_config)? {
- ComposioClientKind::Backend(client) => Ok(client),
- ComposioClientKind::Direct(_) => Err(anyhow::anyhow!(
- "composio direct mode is not supported on this helper path; toolkit={toolkit}"
- )),
- }
-}
-use crate::integrations::composio::client::{
- create_composio_client, ComposioClient, ComposioClientKind,
-};
-use crate::integrations::composio::ops;
-use crate::integrations::composio::FetchConnectedIntegrationsStatus;
-
-/// Whether a Composio `toolkit` may be auto-registered as a memory source.
-///
-/// A toolkit is registrable iff a native sync provider exists for it AND the
-/// bound driver can accept what it returns. A toolkit with no provider has
-/// nothing that would ever call `accept_source_items` for it, so registering
-/// it would report ACTIVE and then never sync — the silent lie of #4957.
-/// Both auto-register sites in the connection-created handler skip
-/// non-registrable toolkits. Extracted as a pure predicate so the skip
-/// decision is unit-testable without driving the async event handler.
-///
-/// # Asked of the catalog, not of the driver
-///
-/// This used to ask `MemorySourceSync::is_toolkit_syncable`, a driver method
-/// tinymemory v1.13.4 made unconditionally answer `Ok(false)` for every
-/// toolkit — the in-process pipeline it answered from is gone, and the
-/// contract kept the member rather than removing it out from under every
-/// implementor. Asking it now would silently disable every Composio memory
-/// source. `has_native_provider` is the answer that is still real: it names
-/// the six toolkits `tinyconnectors-sync` (the module's own sync provider
-/// tree) actually knows how to read — gmail, notion, slack, clickup, github,
-/// linear — the same list `catalog_for_toolkit`'s callers already trust.
-///
-/// A binding with no `Sources` family reads as "not registrable" for the same
-/// reason a driver with no provider used to: nothing here would ever be able
-/// to call `accept_source_items` for it.
-async fn toolkit_is_memory_source_registrable(
- config: &crate::config::Config,
- toolkit: &str,
-) -> bool {
- if !crate::integrations::composio::providers::has_native_provider(toolkit) {
- return false;
- }
- let Ok(binding) = crate::memory::binding::for_config(config) else {
- tracing::warn!(
- toolkit = %toolkit,
- "[composio:bus] memory binding failed; treating toolkit as not registrable"
- );
- return false;
- };
- if binding.provider().as_sources().is_none() {
- tracing::debug!(
- toolkit = %toolkit,
- driver = %binding.driver_id(),
- "[composio:bus] driver does not serve Sources; treating toolkit as not registrable"
- );
- return false;
- }
- true
-}
-
-/// Env var that **disables** the triage pipeline. The pipeline is
-/// enabled by default; set to `1`/`true`/`yes` to opt out (e.g. for
-/// debugging or in environments where LLM calls on every Composio
-/// webhook are undesirable).
-const TRIAGE_DISABLED_ENV: &str = "OPENHUMAN_TRIGGER_TRIAGE_DISABLED";
-
-/// How long we'll keep polling the backend after `composio_authorize`
-/// returns a `connectUrl`, waiting for the user to actually finish the
-/// hosted OAuth flow and the connection to flip to ACTIVE/CONNECTED.
-/// One minute matches typical hosted-OAuth round-trip times and is
-/// generous enough to absorb a slow tab-switch + login + consent.
-const CONNECTION_READY_TIMEOUT: Duration = Duration::from_secs(60);
-
-/// Poll backoff schedule (start, max). We start aggressive so the
-/// fast-path (user already had the tab open) feels immediate, then
-/// back off so we don't hammer the backend during the long tail of
-/// users who actually have to log in to the upstream service.
-const CONNECTION_READY_INITIAL_BACKOFF: Duration = Duration::from_millis(500);
-const CONNECTION_READY_MAX_BACKOFF: Duration = Duration::from_secs(4);
-
-static COMPOSIO_TRIGGER_HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();
-static COMPOSIO_CONNECTION_HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();
-static COMPOSIO_CONFIG_HANDLE: OnceLock<SubscriptionHandle> = OnceLock::new();
-
-/// Register both long-lived composio subscribers on the global event
-/// bus, and initialise the default provider registry. Idempotent.
-pub fn register_composio_trigger_subscriber() {
- // No host-side provider registry any more. It existed so this process
- // could answer `get_provider`; the driver answers that question now, and
- // the module initialises its own registry in its own process
- // (tinymemory#105) — which a `cdylib`'s separate statics require anyway.
-
- if COMPOSIO_TRIGGER_HANDLE.get().is_none() {
- match BUS.subscribe(Arc::new(ComposioTriggerSubscriber::new())) {
- Some(handle) => {
- let _ = COMPOSIO_TRIGGER_HANDLE.set(handle);
- log::debug!("[event_bus] composio trigger subscriber registered");
- }
- None => {
- log::warn!(
- "[event_bus] failed to register composio trigger subscriber — bus not initialized"
- );
- }
- }
- }
-
- if COMPOSIO_CONNECTION_HANDLE.get().is_none() {
- match BUS.subscribe(Arc::new(ComposioConnectionCreatedSubscriber::new())) {
- Some(handle) => {
- let _ = COMPOSIO_CONNECTION_HANDLE.set(handle);
- log::debug!("[event_bus] composio connection_created subscriber registered");
- }
- None => {
- log::warn!(
- "[event_bus] failed to register composio connection_created subscriber — bus not initialized"
- );
- }
- }
- }
-
- if COMPOSIO_CONFIG_HANDLE.get().is_none() {
- match BUS.subscribe(Arc::new(ComposioConfigChangedSubscriber::new())) {
- Some(handle) => {
- let _ = COMPOSIO_CONFIG_HANDLE.set(handle);
- log::debug!("[event_bus] composio config_changed subscriber registered");
- }
- None => {
- log::warn!(
- "[event_bus] failed to register composio config_changed subscriber — bus not initialized"
- );
- }
- }
- }
-}
-
-/// Logs and (when enabled) routes `ComposioTriggerReceived` events
-/// through the reusable `agent::triage` pipeline.
-pub struct ComposioTriggerSubscriber;
-
-impl ComposioTriggerSubscriber {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for ComposioTriggerSubscriber {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl EventHandler<DomainEvent> for ComposioTriggerSubscriber {
- fn name(&self) -> &str {
- "composio::trigger"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["composio"])
- }
-
- async fn handle(&self, event: &DomainEvent) {
- let DomainEvent::ComposioTriggerReceived {
- toolkit,
- trigger,
- metadata_id,
- metadata_uuid,
- payload,
- } = event
- else {
- return;
- };
-
- tracing::debug!(
- toolkit = %toolkit,
- trigger = %trigger,
- id = %metadata_id,
- uuid = %metadata_uuid,
- payload_bytes = payload.to_string().len(),
- "[composio:bus] trigger received"
- );
-
- // [composio-direct] Direct-mode trigger gate.
- //
- // Inbound `composio:trigger` events ride the backend socket
- // (`wss://api.tinyhumans.ai`) which only fans out events from
- // the tinyhumans Composio tenant. When the user has switched
- // to direct mode, that tenant is no longer their active source
- // of truth — connections live on `backend.composio.dev` under
- // their own API key, and any backend-tenant triggers that keep
- // firing are ghosts from the prior mode. Drop them here so the
- // user doesn't see triage runs or history entries originating
- // from a tenant they've moved away from. Real-time triggers
- // for direct-mode users are tracked as a follow-up — see the
- // `composio.direct_mode_triggers_gap` capability and
- // `periodic.rs` docstring.
- //
- // Fail-open on config load error: if config is unreadable, we
- // let the event through rather than silently dropping it. The
- // existing env-var / config triage flags below remain the
- // backend-mode gates.
- if let Ok(config) = config_rpc::load_config_with_timeout().await {
- if config.composio.mode == COMPOSIO_MODE_DIRECT {
- tracing::info!(
- toolkit = %toolkit,
- trigger = %trigger,
- "[composio:trigger] dropped — direct mode active (backend-tenant event ignored)"
- );
- return;
- }
- }
-
- if let Some(store) = trigger_history::global() {
- let toolkit_owned = toolkit.clone();
- let trigger_owned = trigger.clone();
- let metadata_id_owned = metadata_id.clone();
- let metadata_uuid_owned = metadata_uuid.clone();
- let payload_owned = payload.clone();
-
- match tokio::task::spawn_blocking(move || {
- store.record_trigger(
- &toolkit_owned,
- &trigger_owned,
- &metadata_id_owned,
- &metadata_uuid_owned,
- &payload_owned,
- )
- })
- .await
- {
- Ok(Ok(_)) => {}
- Ok(Err(error)) => {
- tracing::warn!(
- toolkit = %toolkit,
- trigger = %trigger,
- error = %error,
- "[composio][history] failed to archive trigger"
- );
- }
- Err(error) => {
- tracing::warn!(
- toolkit = %toolkit,
- trigger = %trigger,
- error = %error,
- "[composio][history] failed to join archive task"
- );
- }
- }
- } else {
- tracing::debug!(
- toolkit = %toolkit,
- trigger = %trigger,
- "[composio][history] archive store not initialized"
- );
- }
-
- if triage_disabled() {
- tracing::debug!(
- toolkit = %toolkit,
- trigger = %trigger,
- "[composio][triage] skipped: {TRIAGE_DISABLED_ENV} is set"
- );
- return;
- }
-
- // Config-level triage gates — checked after env var so the env var
- // remains a global emergency kill-switch that works even when the
- // config file is corrupt. Fail-open on load error: if we can't read
- // the config we let triage run rather than silently drop events.
- match config_rpc::load_config_with_timeout().await {
- Ok(config) => {
- if config.composio.triage_disabled {
- tracing::debug!(
- toolkit = %toolkit,
- trigger = %trigger,
- "[composio][triage] skipped: composio.triage_disabled=true in config"
- );
- return;
- }
- let toolkit_lower = toolkit.to_ascii_lowercase();
- if config
- .composio
- .triage_disabled_toolkits
- .iter()
- .any(|t| t.to_ascii_lowercase() == toolkit_lower)
- {
- tracing::debug!(
- toolkit = %toolkit,
- trigger = %trigger,
- "[composio][triage] skipped: toolkit in composio.triage_disabled_toolkits"
- );
- return;
- }
- }
- Err(e) => {
- tracing::warn!(
- toolkit = %toolkit,
- trigger = %trigger,
- error = %e,
- "[composio][triage] config load failed — falling through to triage (fail-open)"
- );
- }
- }
-
- // Build the envelope outside the spawned task so any panic in
- // `from_composio` surfaces on the bus dispatch thread (where
- // the broadcast subscriber loop can log it) rather than being
- // swallowed inside a detached task.
- let envelope = TriggerEnvelope::from_composio(
- toolkit,
- trigger,
- metadata_id,
- metadata_uuid,
- payload.clone(),
- );
- tracing::debug!(
- label = %envelope.display_label,
- external_id = %envelope.external_id,
- "[composio][triage] dispatching to agent::triage::run_triage"
- );
-
- // Spawn so the bus dispatch loop stays non-blocking — the
- // triage turn is an LLM round-trip that may take seconds.
- tokio::spawn(async move {
- match run_triage(&envelope).await {
- Ok(TriageOutcome::Decision(run)) => {
- // Remote payload: a Composio trigger body is
- // attacker-influenceable, so the dispatch parks rather than
- // running on a trust root (#5634). Scoped here, inside the
- // spawned task, because `AGENT_TURN_ORIGIN` is a task-local
- // and does not cross `tokio::spawn`.
- let origin = remote_trigger_origin(&envelope);
- if let Err(e) = with_origin(origin, apply_decision(run, &envelope)).await {
- tracing::error!(
- label = %envelope.display_label,
- error = %e,
- "[composio][triage] apply_decision failed"
- );
- }
- }
- Ok(TriageOutcome::Deferred {
- defer_until_ms,
- reason,
- }) => {
- // Tiered fallback exhausted both arms; the caller
- // surface (composio bus) has no scheduler of its
- // own — log and drop. The next composio fire will
- // re-enter the chain.
- tracing::warn!(
- label = %envelope.display_label,
- defer_until_ms = defer_until_ms,
- reason = %reason,
- "[composio][triage] run_triage deferred"
- );
- }
- Err(e) => {
- // Route through the central observability classifier
- // so user-config / budget-exhausted / provider-state
- // rollups from `reliable.rs` (e.g. `The model
- // \`<id>\` may not be available on your provider …`)
- // get demoted to info-level breadcrumbs instead of
- // surfacing as raw Sentry errors. Previously this
- // call used `tracing::error!` directly and bypassed
- // the classifier — 10.7k events / 14d on self-hosted
- // Sentry TAURI-RUST-1V, dominated by
- // ProviderConfigRejection-class rollups whose inner
- // attempts the provider layer already demoted.
- let detail = format!(
- "[composio][triage] run_triage failed (label={}): {e:#}",
- envelope.display_label
- );
- // The classifier named here is the host's own. The
- // engine crate exposes a `report_error_or_expected` of its
- // own, but that is a global slot for *extracted* code to
- // report through — installed by whichever process embeds
- // the engine, which since #5560 is the loaded TinyMemory
- // module and no longer this one (`memory/host_impls.rs`,
- // the host's installer, is deleted; `modules/memory_host.rs`
- // is the bus-served twin). This subscriber is host code, so
- // the detour buys nothing and only costs an engine
- // dependency the seam is trying to shed.
- crate::core::observability::report_error_or_expected(
- detail.as_str(),
- "composio",
- "trigger_triage",
- &[("label", envelope.display_label.as_str())],
- );
- }
- }
- });
- }
-}
-
-/// Returns `true` when `OPENHUMAN_TRIGGER_TRIAGE_DISABLED` is set to a
-/// truthy value. The pipeline is **on by default**; this env var is the
-/// opt-out escape hatch.
-fn triage_disabled() -> bool {
- matches!(
- std::env::var(TRIAGE_DISABLED_ENV).ok().as_deref(),
- Some("1") | Some("true") | Some("TRUE") | Some("yes") | Some("YES")
- )
-}
-
-// ── Connection-created subscriber ───────────────────────────────────
-
-/// Routes `ComposioConnectionCreated` events to the toolkit's provider.
-pub struct ComposioConnectionCreatedSubscriber;
-
-impl ComposioConnectionCreatedSubscriber {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for ComposioConnectionCreatedSubscriber {
- fn default() -> Self {
- Self::new()
- }
-}
diff --git a/crates/openhuman-core/src/memory/sync/composio/bus_part_02.rs b/crates/openhuman-core/src/memory/sync/composio/bus_part_02.rs
deleted file mode 100644
index 263f80110a..0000000000
--- a/crates/openhuman-core/src/memory/sync/composio/bus_part_02.rs
+++ /dev/null
@@ -1,573 +0,0 @@
-
-#[async_trait]
-impl EventHandler<DomainEvent> for ComposioConnectionCreatedSubscriber {
- fn name(&self) -> &str {
- "composio::connection_created"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["composio"])
- }
-
- async fn handle(&self, event: &DomainEvent) {
- let DomainEvent::ComposioConnectionCreated {
- toolkit,
- connection_id,
- connect_url: _,
- } = event
- else {
- return;
- };
-
- tracing::info!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- "[composio:bus] connection_created"
- );
-
- // Run the post-active cache refresh for EVERY toolkit, not just
- // ones with a registered provider. Earlier shape gated the
- // entire spawn block on `get_provider(toolkit)` — that meant
- // toolkits without a provider (most of the 119 Composio
- // toolkits, e.g. `googlecalendar`) bypassed the eager cache
- // warm and had to wait for the desktop UI's 5 s
- // `composio_list_connections` diff-poll to invalidate the
- // stale cache. The chat-runtime then missed the new connection
- // on any turn that fell inside that window. Decoupling the
- // cache refresh from provider routing fixes it: every
- // connect → invalidate + eager warm, provider hook becomes a
- // downstream optional step gated on its own `get_provider`
- // lookup.
- let toolkit = toolkit.clone();
- let connection_id = connection_id.clone();
-
- tokio::spawn(async move {
- // The OAuth handoff is asynchronous — the backend returned
- // a `connectUrl` and we published the event before the user
- // has actually clicked through. Resolve the config + client
- // first, then poll the backend for the connection record
- // until we observe ACTIVE/CONNECTED (or hit the timeout).
- // Only then do we invalidate + warm the cache so we never
- // surface a half-finished connection to the chat runtime.
- //
- // NOTE: Future improvement — listen for an explicit
- // "connection_active" backend event instead of polling.
- let config = match config_rpc::load_config_with_timeout().await {
- Ok(c) => c,
- Err(e) => {
- tracing::warn!(
- toolkit = %toolkit,
- error = %e,
- "[composio:bus] failed to load config for connection_created dispatch"
- );
- return;
- }
- };
- // Look up per-source caps from the memory_sources registry.
- // Non-fatal: if the lookup fails we proceed without caps.
- //
- // upsert_composio_source runs AFTER this block (below), so for
- // brand-new connections the entry may not exist yet. In that case
- // fall back to the per-toolkit defaults so the first sync is still
- // capped. list_enabled_by_kind would also drop disabled-but-
- // configured entries, so we use list_sources() and filter ourselves.
- let (src_max_items, src_sync_depth_days) = {
- let registry_sources = crate::memory::sources::list_sources()
- .await
- .unwrap_or_default();
- registry_sources
- .iter()
- .find(|s| {
- s.kind == crate::memory::sources::SourceKind::Composio
- && s.connection_id.as_deref() == Some(connection_id.as_str())
- })
- .map(|s| (s.max_items, s.sync_depth_days))
- .unwrap_or_else(|| {
- crate::memory::sources::memory_sync_defaults_for_toolkit(
- toolkit.as_str(),
- )
- })
- };
-
- // The engine's `ProviderContext::from_config` used to stand here,
- // and its `None` arm is the behaviour being preserved: it probed
- // whether *any* Composio client resolves and skipped the hook when
- // none did, which is the not-signed-in case. That probe is this
- // host's own factory, so ask it directly rather than through a
- // context object built only to be handed back over the bus.
- let config = Arc::new(config);
- if create_composio_client(&config).is_err() {
- tracing::debug!(
- toolkit = %toolkit,
- "[composio:bus] no composio client (not signed in?), skipping hook"
- );
- return;
- }
-
- // The caps are no longer set on a context: `BootstrapConnection`
- // takes none, because the driver reads the per-source budgets from
- // the registry it already owns — the same reasoning
- // `RunConnectionSync` documents for carrying no budget arguments.
- // They are still logged, since this is where they were resolved and
- // a bootstrap that ignored a cap is worth being able to see.
-
- tracing::debug!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- max_items = ?src_max_items,
- sync_depth_days = ?src_sync_depth_days,
- "[composio:bus] caps from registry for connection_created"
- );
-
- // `wait_for_connection_active` is a backend-only metadata
- // probe (`list_connections`). Resolve a backend
- // `ComposioClient` from the live config for it; direct-mode
- // users surface a clear error here rather than silently
- // routing through the wrong tenant (#1710).
- // Was `ctx.backend_client()`, a host extension trait bolted onto
- // the engine's context for this one caller. The context is gone, so
- // the resolution lives at its only call site: reload the live config
- // (the OAuth completion being reacted to may have written
- // credentials since the snapshot) and require the backend tenant.
- let backend_client = match backend_composio_client(&config, &toolkit).await {
- Ok(c) => c,
- Err(e) => {
- tracing::debug!(
- toolkit = %toolkit,
- error = %e,
- "[composio:bus] backend client unavailable for connection-readiness poll; skipping"
- );
- return;
- }
- };
- match wait_for_connection_active(&backend_client, &connection_id).await {
- Ok(status) => {
- tracing::info!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- status = %status,
- "[composio:bus] connection observed active; invalidating + eagerly warming integrations cache"
- );
- // Bust the prompt-level integrations cache now that
- // the connection is confirmed ACTIVE, so the next
- // agent session picks up the newly connected toolkit.
- ops::invalidate_connected_integrations_cache();
- // Eagerly warm the cache from the backend so the
- // very next `cached_active_integrations` read
- // (typically the orchestrator's next-turn refresh,
- // or the desktop UI's 5 s `composio_list_connections`
- // poll — whichever fires first) returns the new
- // toolkit immediately instead of waiting for a
- // cache-miss round trip on the hot path. Cost: one
- // background `list_connections` call per OAuth
- // completion. Best-effort — on backend failure the
- // UI poll will repopulate within ~5 s as a safety
- // net.
- //
- // Use the status-distinguishing fetcher so we log
- // `Authoritative(empty)` and backend unavailability
- // differently — `fetch_connected_integrations`
- // collapses both to `Vec::new()` and would
- // otherwise hide auth/backend failures from
- // incident triage.
- // `ctx.config` is the seam's `dyn MemoryHostConfig` now,
- // and this fetcher wants the host's concrete `Config`.
- // Re-reading it here is also the correct thing on its own
- // terms: the context snapshot was taken at hook-entry and
- // the OAuth completion we are reacting to may have written
- // credentials since.
- let live_config = match crate::config::rpc::reload_config_from_paths(
- &config.config_path,
- &config.workspace_dir,
- )
- .await
- {
- Ok(cfg) => cfg,
- Err(e) => {
- tracing::debug!(
- error = %e,
- "[composio:bus] connected-integrations refresh: \
- reload_config failed; skipping"
- );
- return;
- }
- };
- match ops::fetch_connected_integrations_status(&live_config).await {
- FetchConnectedIntegrationsStatus::Authoritative(entries) => {
- let mut toolkits: Vec<String> = entries
- .iter()
- .filter(|entry| entry.connected)
- .map(|entry| entry.toolkit.clone())
- .collect();
- toolkits.sort();
- toolkits.dedup();
- tinymemory_api::events::publish(
- tinymemory_api::events::MemoryEvent::ComposioIntegrationsChanged {
- toolkits: toolkits.clone(),
- },
- );
- tracing::debug!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- cached_entries = entries.len(),
- active_toolkits = ?toolkits,
- "[composio:bus] eagerly warmed integrations cache after connection became active"
- );
- }
- FetchConnectedIntegrationsStatus::Unavailable => {
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- "[composio:bus] eager cache warm after connection became active skipped: backend unavailable"
- );
- }
- }
- }
- Err(WaitError::Timeout { last_status }) => {
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- last_status = ?last_status,
- timeout_secs = CONNECTION_READY_TIMEOUT.as_secs(),
- "[composio:bus] timed out waiting for connection to become active; skipping cache refresh + provider hook"
- );
- return;
- }
- Err(WaitError::Lookup { error }) => {
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- error = %error,
- "[composio:bus] backend lookup failed while waiting for connection; skipping cache refresh + provider hook"
- );
- return;
- }
- }
-
- // Optional provider-specific post-OAuth hook (e.g. gmail's
- // inbox ingest). Only fires for toolkits that registered a
- // provider, and only when the user has completed onboarding.
- //
- // Skip the initial sync when onboarding is still in progress
- // (#3097). Connections made during the setup wizard would otherwise
- // enqueue embedding/LLM jobs that drain cloud credits before the
- // user has had a chance to choose their AI routing. The periodic
- // scheduler (20-min tick) will fire the first real sync after
- // onboarding completes. The memory_sources auto-register below
- // still runs unconditionally so the source appears in the unified
- // sources list immediately.
- if !config.onboarding_completed {
- tracing::info!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- "[composio:bus] onboarding not yet complete — deferring initial sync to periodic scheduler"
- );
- } else {
- // The same predicate the other auto-register site uses, rather
- // than a second `get_provider` call beside it: the bootstrap
- // that wanted the provider *handle* runs in the driver now, so
- // all this site needs is the #4957 answer.
- if !toolkit_is_memory_source_registrable(&config, &toolkit).await {
- // No native memory-sync provider → this toolkit cannot ingest
- // into memory. Do NOT auto-register it as a memory source: a
- // source that reports ACTIVE and then fails every sync with
- // "tinycortex sync does not support toolkit" is a silent lie
- // to the user (#4957). The connection stays a valid agent-tool
- // integration; it simply never becomes a memory source until a
- // pipeline lands (tracked per-toolkit in #4958+). The cache
- // refresh above already ran for every toolkit.
- tracing::info!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- "[composio:bus] no memory-sync provider for toolkit; skipping memory_sources auto-register (not syncable, #4957)"
- );
- return;
- }
-
- // The bootstrap step used to be `MemorySourceSync::bootstrap_connection`,
- // run by the driver — "fetch and persist the account profile".
- // tinymemory v1.13.4 made that member unconditionally refuse
- // for every toolkit (reaching a connected account now needs a
- // credential the engine must not hold), so this host does it
- // directly through the connector module instead — the same
- // `GET_USER_PROFILE` round trip `composio_get_user_profile`
- // already performs.
- if let Err(e) = crate::integrations::composio::ops::composio_get_user_profile(
- &config,
- &connection_id,
- )
- .await
- {
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- error = %e,
- "[composio:bus] connection bootstrap (profile fetch) failed"
- );
- }
-
- // `ctx.config` is the seam's `dyn MemoryHostConfig`; the binding
- // keys on this host's own `Config`, so it is re-read from the
- // paths the seam carries — the same move the live-config read
- // above this makes, and for the same reason.
- let host_config = match crate::config::rpc::reload_config_from_paths(
- &config.config_path,
- &config.workspace_dir,
- )
- .await
- {
- Ok(config) => config,
- Err(error) => {
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- error = %error,
- "[composio:bus] initial sync skipped: config re-read failed"
- );
- return;
- }
- };
- // Was `MemorySourceSync::run_connection_sync`, now unconditionally
- // refused for the same reason `bootstrap_connection` above is:
- // reads through the connector module and ingests through the
- // bound driver's `MemorySourceSink` instead — the same
- // `run_sync_pass` helper every other sync entry point in this
- // domain uses now.
- let attempted = crate::integrations::composio::ops::run_sync_within_budget(
- &host_config,
- &toolkit,
- &connection_id,
- "connection_created",
- )
- .await;
- match attempted {
- Ok(pass) => {
- tracing::info!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- records_read = pass.records_read,
- written = pass.written,
- already_ingested = pass.already_ingested,
- more_pending = pass.more_pending,
- "[composio:bus] initial sync complete"
- );
- // Avoid immediately re-firing from the periodic scheduler.
- crate::integrations::composio::periodic::record_sync_success(
- &toolkit,
- &connection_id,
- );
- }
- Err(error) => tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- error = %error,
- "[composio:bus] initial sync failed"
- ),
- }
- }
-
- // Auto-register this connection in the memory_sources registry so it
- // appears in the unified sources list regardless of whether the
- // initial sync ran — but ONLY for toolkits that can actually sync.
- // The provider registry is the single source of truth shared with the
- // `memory_sources.supported_toolkits` RPC; gating here (the same check
- // used above) means a toolkit with no pipeline never surfaces as a
- // memory source that would silently fail every sync (#4957). This also
- // guards the onboarding-incomplete path, which reaches here without
- // evaluating the provider branch above.
- if !toolkit_is_memory_source_registrable(&config, &toolkit).await {
- tracing::info!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- "[composio:bus] no memory-sync provider for toolkit; skipping memory_sources auto-register (not syncable, #4957)"
- );
- return;
- }
- let label = format!("{toolkit} connection");
- if let Err(e) = crate::memory::sources::upsert_composio_source(
- &toolkit,
- &connection_id,
- &label,
- )
- .await
- {
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- error = %e,
- "[composio:bus] memory_sources auto-register failed (non-fatal)"
- );
- }
- });
- }
-}
-
-// ── Connection-readiness polling ────────────────────────────────────
-
-#[derive(Debug)]
-enum WaitError {
- /// Polling exhausted [`CONNECTION_READY_TIMEOUT`] without observing
- /// the connection in an active state. `last_status` is whatever the
- /// backend last reported (e.g. `"INITIATED"`, `"PENDING"`).
- Timeout { last_status: Option<String> },
- /// The backend lookup itself errored — we treat that as fatal for
- /// this dispatch (no point spinning when `list_connections` is
- /// unreachable).
- Lookup { error: String },
-}
-
-/// Poll the backend for `connection_id` until it appears with an
-/// `ACTIVE` or `CONNECTED` status, or until we hit
-/// [`CONNECTION_READY_TIMEOUT`]. Backoff is exponential between
-/// [`CONNECTION_READY_INITIAL_BACKOFF`] and
-/// [`CONNECTION_READY_MAX_BACKOFF`].
-///
-/// On success returns the observed status string. On timeout returns
-/// the last status we saw (helpful for "stuck in INITIATED" debugging).
-async fn wait_for_connection_active(
- client: &ComposioClient,
- connection_id: &str,
-) -> Result<String, WaitError> {
- let started = std::time::Instant::now();
- let mut backoff = CONNECTION_READY_INITIAL_BACKOFF;
- let mut last_status: Option<String> = None;
-
- loop {
- match client.list_connections().await {
- Ok(resp) => {
- if let Some(conn) = resp.connections.into_iter().find(|c| c.id == connection_id) {
- if conn.is_active() {
- return Ok(conn.status);
- }
- last_status = Some(conn.status);
- }
- // Connection not found yet — backend may not have
- // persisted it to its index. Treat the same as a
- // not-yet-active status and retry.
- }
- Err(e) => {
- // One transient lookup failure shouldn't kill the
- // dispatch — keep polling until the timeout.
- tracing::debug!(
- connection_id = %connection_id,
- error = %e,
- "[composio:bus] list_connections failed during readiness poll (will retry)"
- );
- last_status = last_status.or_else(|| Some(format!("lookup_error: {e}")));
- }
- }
-
- if started.elapsed() >= CONNECTION_READY_TIMEOUT {
- // If we never even got a successful lookup, propagate that
- // as a Lookup error rather than Timeout so the caller can
- // distinguish "user is taking forever" from "backend is
- // down".
- if let Some(ref status) = last_status {
- if status.starts_with("lookup_error:") {
- return Err(WaitError::Lookup {
- error: status.clone(),
- });
- }
- }
- return Err(WaitError::Timeout { last_status });
- }
-
- tokio::time::sleep(backoff).await;
- backoff = (backoff * 2).min(CONNECTION_READY_MAX_BACKOFF);
- }
-}
-
-// ── Config-changed subscriber ───────────────────────────────────────
-
-/// Drops the prompt-level integrations cache whenever the user flips
-/// `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
-/// "I switched to Direct and my old integrations are still showing"
-/// (#1710).
-///
-/// The subscriber is intentionally tiny: it only clears the cache,
-/// then attempts a best-effort eager warm + `ComposioIntegrationsChanged`
-/// publish in a detached task so active sessions can refresh their
-/// delegation schema without waiting for the next turn boundary.
-///
-/// The warm/publish step is intentionally opportunistic: if config load
-/// or backend access fails we leave the cache cold and rely on the
-/// existing 5 s UI poll / next-turn fallback path.
-pub struct ComposioConfigChangedSubscriber;
-
-impl ComposioConfigChangedSubscriber {
- pub fn new() -> Self {
- Self
- }
-}
-
-impl Default for ComposioConfigChangedSubscriber {
- fn default() -> Self {
- Self::new()
- }
-}
-
-#[async_trait]
-impl EventHandler<DomainEvent> for ComposioConfigChangedSubscriber {
- fn name(&self) -> &str {
- "composio::config_changed"
- }
-
- fn domains(&self) -> Option<&[&str]> {
- Some(&["composio"])
- }
-
- async fn handle(&self, event: &DomainEvent) {
- let DomainEvent::ComposioConfigChanged { mode, api_key_set } = event else {
- return;
- };
-
- tracing::info!(
- mode = %mode,
- api_key_set = api_key_set,
- "[composio-cache] config changed — invalidating integrations cache"
- );
- ops::invalidate_connected_integrations_cache();
-
- tokio::spawn(async move {
- let config = match config_rpc::load_config_with_timeout().await {
- Ok(config) => config,
- Err(error) => {
- tracing::debug!(
- error = %error,
- "[composio-cache] config changed eager warm skipped: config load failed"
- );
- return;
- }
- };
-
- match ops::fetch_connected_integrations_status(&config).await {
- FetchConnectedIntegrationsStatus::Authoritative(entries) => {
- let mut toolkits: Vec<String> = entries
- .iter()
- .filter(|entry| entry.connected)
- .map(|entry| entry.toolkit.clone())
- .collect();
- toolkits.sort();
- toolkits.dedup();
- tinymemory_api::events::publish(
- tinymemory_api::events::MemoryEvent::ComposioIntegrationsChanged {
- toolkits: toolkits.clone(),
- },
- );
- tracing::debug!(
- active_toolkits = ?toolkits,
- "[composio-cache] config changed eager warm complete; published integrations changed"
- );
- }
- FetchConnectedIntegrationsStatus::Unavailable => {
- tracing::debug!(
- "[composio-cache] config changed eager warm skipped: backend unavailable"
- );
- }
- }
- });
- }
-}