Skip to content

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

refactor(composio): delegate provider ops to the module client\n\nMove the Composio provider operations — profile fetch, identity refresh, and sync — from direct provider calls to the module client, which now owns the network logic and returns structured responses. The sync pass is extracted into a private helper that reads records from the module and ingests them into memory through the bound driver, keeping the two halves decoupled.\n\nAuto-committed-on: dragonfly\n

Steven Enamakel0355d44ca81e
diff --git a/src/openhuman/integrations/composio/ops/providers_ops.rs b/src/openhuman/integrations/composio/ops/providers_ops.rs
index acbf525181..0ac4511bf7 100644
--- a/src/openhuman/integrations/composio/ops/providers_ops.rs
+++ b/src/openhuman/integrations/composio/ops/providers_ops.rs
@@ -1,15 +1,28 @@
//! Provider-backed ops: profile fetch, identity refresh, and sync.
-
-use std::sync::Arc;
+//!
+//! # The division of labour
+//!
+//! Reading a connected account is the module's job — it holds the credential,
+//! the provider registry, and the paging cursors. Writing what it read into
+//! memory is this crate's, because the memory driver is bound here and the
+//! guard that redacts and taints a batch sits in front of it.
+//!
+//! So a sync is two calls: `Sync` returns records, and the bound driver's
+//! `accept_source_items` ingests them. Neither half knows about the other,
+//! which is the point — the module cannot reach the user's memory, and the
+//! memory driver never sees a Composio credential.
use crate::openhuman::config::Config;
use crate::rpc::RpcOutcome;
-use super::super::providers::{
- get_provider, ProviderContext, ProviderUserProfile, SyncOutcome, SyncReason,
+use super::super::module_client::{self as connectors, methods};
+use super::super::providers::{ProviderUserProfile, SyncOutcome, SyncReason};
+use super::super::types::{
+ reencode, ComposioRefreshIdentitiesResponse, ComposioUserProfile, ComposioUserProfileRequest,
+ ConnectorSyncRequest, ConnectorSyncResponse,
};
use super::connections::resolve_toolkit_for_connection;
-use super::error_utils::{report_composio_op_error, resolve_client, OpResult};
+use super::error_utils::{report_composio_op_error, OpResult};
/// Aggregate result of [`composio_refresh_all_identities`].
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
@@ -21,37 +34,43 @@ pub struct RefreshIdentitiesReport {
pub rows_written: usize,
}
-/// `openhuman.composio_get_user_profile` — fetch a normalized user
-/// profile for a connected account by dispatching to the toolkit's
-/// registered [`super::super::providers::ComposioProvider`].
+/// Persist one profile's identity facets and report how many rows it wrote.
+///
+/// Still routed through the memory-side provider registry, which owns the facet
+/// schema. Phase 4 moves that here and this conversion goes away — see
+/// [`super::super::types::reencode`].
+fn persist_identity(profile: &ComposioUserProfile) -> OpResult<usize> {
+ let native: ProviderUserProfile = reencode(profile)?;
+ let Some(provider) = super::super::providers::get_provider(&profile.toolkit) else {
+ return Ok(0);
+ };
+ Ok(provider.identity_set(&native))
+}
+
+/// `openhuman.composio_get_user_profile` — fetch a normalized user profile for
+/// a connected account.
pub async fn composio_get_user_profile(
config: &Config,
connection_id: &str,
) -> OpResult<RpcOutcome<ProviderUserProfile>> {
tracing::debug!(connection_id = %connection_id, "[composio] rpc get_user_profile");
- let client = resolve_client(config)?;
- let toolkit = resolve_toolkit_for_connection(&client, connection_id).await?;
-
- let provider = get_provider(&toolkit).ok_or_else(|| {
- format!("[composio] no native provider registered for toolkit '{toolkit}'")
- })?;
-
- let _ = client;
- let ctx = ProviderContext {
- config: Arc::new(config.clone()),
- toolkit: toolkit.clone(),
- connection_id: Some(connection_id.to_string()),
- usage: Default::default(),
- max_items: None,
- sync_depth_days: None,
- };
+ let toolkit = resolve_toolkit_for_connection(config, connection_id).await?;
- let profile = provider.fetch_user_profile(&ctx).await.map_err(|e| {
- report_composio_op_error("get_user_profile", &e);
- format!("[composio] get_user_profile({toolkit}) failed: {e}")
+ let profile = connectors::call::<_, ComposioUserProfile>(
+ config,
+ methods::GET_USER_PROFILE,
+ ComposioUserProfileRequest {
+ toolkit: toolkit.clone(),
+ connection_id: Some(connection_id.to_string()),
+ },
+ )
+ .await
+ .map_err(|error| {
+ report_composio_op_error("get_user_profile", &anyhow::anyhow!("{error}"));
+ format!("[composio] get_user_profile({toolkit}) failed: {error}")
})?;
- let facets = provider.identity_set(&profile);
+ let facets = persist_identity(&profile)?;
tracing::debug!(
toolkit = %toolkit,
facets_written = facets,
@@ -59,110 +78,98 @@ pub async fn composio_get_user_profile(
);
Ok(RpcOutcome::new(
- profile,
+ reencode(&profile)?,
vec![format!(
"composio: fetched {toolkit} profile for connection {connection_id}"
)],
))
}
-/// `openhuman.composio_refresh_all_identities` — re-fetch the user
-/// profile for every active connection and persist via `identity_set`.
-/// Used to populate kind-tagged `user_profile` rows on existing
-/// connections after the #1365 schema rewrite without waiting for the
-/// next periodic sync tick.
+/// `openhuman.composio_refresh_all_identities` — re-fetch the user profile for
+/// every active connection and persist via `identity_set`.
///
-/// Best-effort per connection: a failure on one toolkit does not abort
-/// the others. Returns aggregate counts plus a per-connection trail in
-/// the envelope messages.
+/// Best-effort per connection: the module reports the ones it could not read as
+/// failures alongside the profiles it could, because a refresh exists precisely
+/// to find the broken ones.
pub async fn composio_refresh_all_identities(
config: &Config,
) -> OpResult<RpcOutcome<RefreshIdentitiesReport>> {
tracing::info!("[composio] rpc refresh_all_identities");
- let client = resolve_client(config)?;
- let conns = client.list_connections().await.map_err(|e| {
- report_composio_op_error("refresh_all_identities", &e);
- format!("[composio] list_connections failed: {e:#}")
+ let response = connectors::call_bare::<ComposioRefreshIdentitiesResponse>(
+ config,
+ methods::REFRESH_ALL_IDENTITIES,
+ )
+ .await
+ .map_err(|error| {
+ report_composio_op_error("refresh_all_identities", &anyhow::anyhow!("{error}"));
+ format!("[composio] refresh_all_identities failed: {error}")
})?;
let mut report = RefreshIdentitiesReport::default();
- let mut messages: Vec<String> = Vec::with_capacity(conns.connections.len() + 1);
+ let mut messages: Vec<String> =
+ Vec::with_capacity(response.profiles.len() + response.failures.len() + 1);
- for conn in conns.connections {
- if !conn.is_active() {
- report.skipped_inactive += 1;
- continue;
- }
- let toolkit = conn.toolkit.clone();
- let connection_id = conn.id.clone();
+ for profile in &response.profiles {
+ let connection_id = profile.connection_id.as_deref().unwrap_or("-");
+ let toolkit = &profile.toolkit;
- let Some(provider) = get_provider(&toolkit) else {
- tracing::debug!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- "[composio] refresh_all_identities: no native provider — skipping"
- );
+ // A toolkit the module read but this build has no facet schema for is
+ // not a failure — it is the same "no native provider" case the loop
+ // used to skip before fetching, now discovered one step later.
+ if super::super::providers::get_provider(toolkit).is_none() {
report.skipped_no_provider += 1;
messages.push(format!(
"{toolkit}/{connection_id}: skipped (no native provider)"
));
continue;
- };
+ }
- let ctx = ProviderContext {
- config: Arc::new(config.clone()),
- toolkit: toolkit.clone(),
- connection_id: Some(connection_id.clone()),
- usage: Default::default(),
- max_items: None,
- sync_depth_days: None,
- };
+ let rows = persist_identity(profile)?;
+ report.refreshed += 1;
+ report.rows_written += rows;
+ tracing::debug!(
+ toolkit = %toolkit,
+ connection_id = %connection_id,
+ rows_written = rows,
+ "[composio] refresh_all_identities: identity_set ok"
+ );
+ messages.push(format!("{toolkit}/{connection_id}: {rows} row(s)"));
+ }
- match provider.fetch_user_profile(&ctx).await {
- Ok(profile) => {
- let rows = provider.identity_set(&profile);
- report.refreshed += 1;
- report.rows_written += rows;
- tracing::debug!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- rows_written = rows,
- "[composio] refresh_all_identities: identity_set ok"
- );
- messages.push(format!("{toolkit}/{connection_id}: {rows} row(s)"));
- }
- Err(e) => {
- report.failed += 1;
- tracing::warn!(
- toolkit = %toolkit,
- connection_id = %connection_id,
- error = %e,
- "[composio] refresh_all_identities: fetch_user_profile failed"
- );
- messages.push(format!("{toolkit}/{connection_id}: ERROR — {e}"));
- }
- }
+ for failure in &response.failures {
+ report.failed += 1;
+ tracing::warn!(
+ toolkit = %failure.toolkit,
+ connection_id = %failure.connection_id,
+ error = %failure.message,
+ "[composio] refresh_all_identities: fetch_user_profile failed"
+ );
+ messages.push(format!(
+ "{}/{}: ERROR — {}",
+ failure.toolkit, failure.connection_id, failure.message
+ ));
}
let summary = format!(
"composio: refreshed {ok}/{tried} active conn(s) — {rows} rows; \
- {fail} failed, {nopv} skipped (no provider), {inact} inactive",
+ {fail} failed, {nopv} skipped (no provider)",
ok = report.refreshed,
tried = report.refreshed + report.failed + report.skipped_no_provider,
rows = report.rows_written,
fail = report.failed,
nopv = report.skipped_no_provider,
- inact = report.skipped_inactive,
);
let mut envelope = vec![summary];
envelope.extend(messages);
Ok(RpcOutcome::new(report, envelope))
}
-/// `openhuman.composio_sync` — run a sync pass for a connected account
-/// by dispatching to the toolkit's registered provider. `reason` is
-/// `"manual"` by default; the periodic scheduler passes `"periodic"`
-/// and the OAuth event subscriber passes `"connection_created"`.
+/// `openhuman.composio_sync` — read a connected account and write what it
+/// returns into memory.
+///
+/// Returns as soon as the run is *started*: a full sync is minutes of paging,
+/// and the RPC caller is a UI button. Progress is reported in the log, and the
+/// records land in memory as each page is ingested.
pub async fn composio_sync(
config: &Config,
connection_id: &str,
@@ -174,51 +181,52 @@ pub async fn composio_sync(
reason = reason.as_str(),
"[composio] rpc sync (spawned)"
);
- let client = resolve_client(config)?;
- let toolkit = resolve_toolkit_for_connection(&client, connection_id).await?;
- get_provider(&toolkit).ok_or_else(|| {
- format!("[composio] no native provider registered for toolkit '{toolkit}'")
- })?;
- let _ = client;
- let config_for_task = config.clone();
- let started_at_ms = std::time::SystemTime::now()
- .duration_since(std::time::UNIX_EPOCH)
- .map(|d| d.as_millis() as u64)
- .unwrap_or(0);
- let toolkit_for_outcome = toolkit.clone();
- let connection_id_for_log = connection_id.to_string();
+ let toolkit = resolve_toolkit_for_connection(config, connection_id).await?;
+
+ // Resolved before the spawn so a driver that serves no ingestion is an
+ // error the caller sees rather than a log line in a detached task.
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ if binding.provider().as_sources().is_none() {
+ return Err(format!(
+ "the bound memory driver '{}' does not accept source items",
+ binding.driver_id()
+ ));
+ }
+
+ let started_at_ms = u64::try_from(
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_millis())
+ .unwrap_or(0),
+ )
+ .unwrap_or(u64::MAX);
- // Resolved before the spawn so a driver that serves no sync is an error the
- // caller sees rather than a log line in a detached task.
- let binding = crate::openhuman::memory::binding::for_config(&config_for_task)?;
+ let config_for_task = config.clone();
+ let toolkit_for_task = toolkit.clone();
+ let connection_for_task = connection_id.to_string();
+ let reason_for_task = reason.as_str().to_string();
tokio::spawn(async move {
- let attempted = match binding.provider().as_source_sync() {
- Some(sync) => sync
- .run_connection_sync(&toolkit_for_outcome, &connection_id_for_log)
- .await
- .map_err(|error| error.to_string()),
- None => Err(format!(
- "the bound memory driver '{}' does not serve source sync",
- binding.driver_id()
- )),
- };
- match attempted {
- Ok(out) => {
- tracing::info!(
- toolkit = %toolkit_for_outcome,
- connection_id = %connection_id_for_log,
- items_ingested = out.records_ingested,
- actions_called = out.actions_called,
- "[composio] background sync ok"
- );
- }
- Err(e) => {
- report_composio_op_error("sync", &e);
+ let outcome = run_sync_pass(
+ &config_for_task,
+ &toolkit_for_task,
+ &connection_for_task,
+ &reason_for_task,
+ )
+ .await;
+ match outcome {
+ Ok(ingested) => tracing::info!(
+ toolkit = %toolkit_for_task,
+ connection_id = %connection_for_task,
+ items_ingested = ingested,
+ "[composio] background sync ok"
+ ),
+ Err(error) => {
+ report_composio_op_error("sync", &anyhow::anyhow!("{error}"));
tracing::warn!(
- toolkit = %toolkit_for_outcome,
- connection_id = %connection_id_for_log,
- error = %e,
+ toolkit = %toolkit_for_task,
+ connection_id = %connection_for_task,
+ error = %error,
"[composio] background sync failed"
);
}
@@ -239,6 +247,72 @@ pub async fn composio_sync(
Ok(RpcOutcome::new(outcome, vec![summary]))
}
+/// Read one connection through the module and ingest what it returns.
+///
+/// The two halves are deliberately not interleaved with retries or partial
+/// commits: the module already decides what a page is and where the cursor
+/// stands, and re-deciding that here would give the run two opinions about
+/// what has been read.
+async fn run_sync_pass(
+ config: &Config,
+ toolkit: &str,
+ connection_id: &str,
+ reason: &str,
+) -> Result<usize, String> {
+ let response = connectors::call::<_, ConnectorSyncResponse>(
+ config,
+ methods::SYNC,
+ ConnectorSyncRequest {
+ toolkit: toolkit.to_string(),
+ connection_id: Some(connection_id.to_string()),
+ reason: Some(reason.to_string()),
+ ..ConnectorSyncRequest::default()
+ },
+ )
+ .await?;
+
+ let count = response.batch.records.len();
+ if count == 0 {
+ return Ok(0);
+ }
+
+ let binding = crate::openhuman::memory::binding::for_config(config)?;
+ let sink = binding.provider().as_sources().ok_or_else(|| {
+ format!(
+ "the bound memory driver '{}' does not accept source items",
+ binding.driver_id()
+ )
+ })?;
+
+ // `ConnectorRecord` and memory's `SourceItem` carry the same seven keys —
+ // the contract crate asserts that against a literal list, so a drift is a
+ // failing test there rather than a decode error here.
+ let items = reencode::<_, Vec<tinymemory_bus::provider::SourceItem>>(&response.batch.records)?;
+
+ // `ExternalSync`: everything here came from a third-party account over the
+ // network, and the taint is what stops it being treated as the user's own
+ // words later.
+ let outcome = sink
+ .accept_source_items(
+ &response.batch.source_id,
+ &response.batch.source_kind,
+ items,
+ tinymemory_bus::provider::MemoryTaint::ExternalSync,
+ )
+ .await
+ .map_err(|error| format!("ingesting {toolkit} records failed: {error}"))?;
+
+ tracing::debug!(
+ toolkit = %toolkit,
+ stage = ?response.stage,
+ pages_read = response.pages_read,
+ records_skipped = response.records_skipped,
+ accepted = outcome.accepted,
+ "[composio] sync pass ingested"
+ );
+ Ok(count)
+}
+
/// Parse the optional `reason` parameter into a [`SyncReason`].
///
/// `None` and the explicit `"manual"` value both map to