Skip to content

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

feat(composio): restructure client module into submodules

Steven Enamakel26ea229d99b8
diff --git a/crates/openhuman-core/src/integrations/composio/client.rs b/crates/openhuman-core/src/integrations/composio/client.rs
index 8ea9002b70..530c33ef1d 100644
--- a/crates/openhuman-core/src/integrations/composio/client.rs
+++ b/crates/openhuman-core/src/integrations/composio/client.rs
@@ -1,34 +1,29 @@
-//! Thin HTTP wrapper over the openhuman backend's
-//! `/agent-integrations/composio/*` routes.
+//! Host-side Composio route resolution and the direct-mode v3 reads.
//!
-//! All calls go through the shared
-//! [`crate::integrations::IntegrationClient`] so they inherit
-//! the same Bearer JWT auth, timeout, envelope parsing, and proxy behavior
-//! as the other backend-proxied integrations.
+//! The Composio HTTP client itself lives in the `tinyconnectors` module and is
+//! reached through [`super::module_client`]. What remains here is the part the
+//! module does not decide for the host: which route the config selects
+//! ([`resolve_composio_route`]) and the two direct-mode v3 reads
+//! ([`direct_list_connections`], [`direct_list_tools`]) that keep the
+//! pagination and toolkit-version parameters the pinned module route omits.
//!
//! Logging uses the `[composio]` grep-prefix so all sidecar output for
//! this domain can be filtered in one shot.
-mod connections;
mod direct;
-mod execute;
mod factory;
-mod triggers;
#[cfg(test)]
#[path = "client_tests.rs"]
mod tests;
-pub use connections::ComposioClient;
-pub(crate) use direct::direct_list_tools;
pub use direct::direct_list_connections;
-pub(crate) use factory::{build_composio_client, create_direct_composio_tool_for_api_key};
-pub use factory::{create_composio_client, ComposioClientKind};
+pub(crate) use direct::direct_list_tools;
+pub(crate) use factory::create_direct_client_for_api_key;
+pub use factory::{resolve_composio_route, ComposioRoute};
// Brought into this module's own namespace (private `use`, not `pub use`)
// so `client_tests.rs` — declared as a direct child module of `client`
-// above — can still reach these via a plain `use super::*;`, exactly as
-// when this was one un-split file. See each item's `pub(super)` in its
-// owning submodule.
+// above — can still reach these via a plain `use super::*;`.
#[cfg(test)]
use std::sync::Arc;
diff --git a/crates/openhuman-core/src/integrations/composio/client/connections.rs b/crates/openhuman-core/src/integrations/composio/client/connections.rs
deleted file mode 100644
index cf72d0a4e4..0000000000
--- a/crates/openhuman-core/src/integrations/composio/client/connections.rs
+++ /dev/null
@@ -1,291 +0,0 @@
-//! [`ComposioClient`]'s core lifecycle plus its toolkit/connection/OAuth
-//! surface — construction, `list_toolkits`, `list_connections`, `authorize`
-//! (including the Gmail OAuth-scope merge helpers it needs), and
-//! `delete_connection` (via the shared `raw_delete` HTTP helper).
-
-use std::sync::Arc;
-
-use anyhow::Result;
-use serde_json::{json, Value};
-
-use crate::integrations::IntegrationClient;
-
-use super::super::types::{
- ComposioAuthorizeResponse, ComposioConnectionsResponse, ComposioDeleteResponse,
- ComposioToolkitsResponse,
-};
-
-const AUTHORIZE_OAUTH_SCOPES_FIELD: &str = "oauth_scopes";
-const GMAIL_REQUIRED_OAUTH_SCOPES: &[&str] = &["https://www.googleapis.com/auth/gmail.readonly"];
-
-/// High-level client for all backend-proxied Composio operations.
-#[derive(Clone)]
-pub struct ComposioClient {
- pub(super) inner: Arc<IntegrationClient>,
-}
-
-impl ComposioClient {
- pub fn new(inner: Arc<IntegrationClient>) -> Self {
- Self { inner }
- }
-
- /// Access the underlying integration client (useful for tests or for
- /// callers that need to reuse the same reqwest pool for bespoke calls).
- pub fn inner(&self) -> &Arc<IntegrationClient> {
- &self.inner
- }
-
- // ── Toolkits ────────────────────────────────────────────────────
-
- /// `GET /agent-integrations/composio/toolkits` — server-enforced
- /// allowlist of toolkits that composio calls may target.
- pub async fn list_toolkits(&self) -> Result<ComposioToolkitsResponse> {
- tracing::debug!("[composio] list_toolkits");
- self.inner
- .get::<ComposioToolkitsResponse>("/agent-integrations/composio/toolkits")
- .await
- }
-
- // ── Connections ─────────────────────────────────────────────────
-
- /// `GET /agent-integrations/composio/connections` — active connected
- /// accounts for the authenticated user, filtered to the allowlist.
- pub async fn list_connections(&self) -> Result<ComposioConnectionsResponse> {
- tracing::debug!("[composio] list_connections");
- self.inner
- .get::<ComposioConnectionsResponse>("/agent-integrations/composio/connections")
- .await
- }
-
- /// `POST /agent-integrations/composio/authorize` — begin an OAuth
- /// handoff for `toolkit` and return the hosted `connectUrl` the user
- /// must open in a browser.
- ///
- /// `extra_params` is an optional JSON object whose key/value pairs are
- /// merged into the request body. Some toolkits (e.g. `whatsapp`) require
- /// additional fields (e.g. `waba_id`) that Composio will reject the
- /// authorization without.
- pub async fn authorize(
- &self,
- toolkit: &str,
- extra_params: Option<serde_json::Value>,
- ) -> Result<ComposioAuthorizeResponse> {
- let toolkit = toolkit.trim();
- if toolkit.is_empty() {
- anyhow::bail!("composio.authorize: toolkit must not be empty");
- }
- tracing::debug!(toolkit = %toolkit, has_extra_params = extra_params.is_some(), "[composio] authorize");
- let mut body = serde_json::json!({ "toolkit": toolkit });
- if let Some(extra) = extra_params {
- const RESERVED: &[&str] = &["toolkit", "toolkit_version", "auth", "client_id"];
- let extra_obj = extra.as_object().ok_or_else(|| {
- anyhow::anyhow!("composio.authorize: extra_params must be a JSON object")
- })?;
- let obj = body.as_object_mut().ok_or_else(|| {
- anyhow::anyhow!("composio.authorize: internal payload must be an object")
- })?;
- for (k, v) in extra_obj {
- if RESERVED.contains(&k.as_str()) {
- anyhow::bail!(
- "composio.authorize: extra_params cannot override reserved key '{k}'"
- );
- }
- obj.insert(k.clone(), v.clone());
- }
- }
- merge_required_oauth_scopes(&mut body, toolkit)?;
- self.inner
- .post::<ComposioAuthorizeResponse>("/agent-integrations/composio/authorize", &body)
- .await
- }
-
- /// `DELETE /agent-integrations/composio/connections/{id}`.
- ///
- /// The backend verifies that the caller owns the connection before
- /// deleting it. We call this via `POST` with a synthetic `_method`
- /// body because [`IntegrationClient`] does not currently expose a
- /// generic `delete()` — the backend accepts the method override.
- pub async fn delete_connection(&self, connection_id: &str) -> Result<ComposioDeleteResponse> {
- let connection_id = connection_id.trim();
- if connection_id.is_empty() {
- anyhow::bail!("composio.delete_connection: connectionId must not be empty");
- }
- tracing::debug!(connection_id = %connection_id, "[composio] delete_connection");
- // Fall through to the reusable raw HTTP delete helper below.
- self.raw_delete::<ComposioDeleteResponse>(&format!(
- "/agent-integrations/composio/connections/{connection_id}"
- ))
- .await
- }
-
- // ── Raw DELETE ──────────────────────────────────────────────────
-
- /// Perform an HTTP DELETE and parse the standard backend envelope.
- ///
- /// [`IntegrationClient`] only exposes `get` / `post` today, and the
- /// composio route actually requires a DELETE. We re-implement the
- /// envelope handling here so we don't have to widen the shared
- /// client's public surface just for one caller.
- pub(super) async fn raw_delete<T: serde::de::DeserializeOwned>(&self, path: &str) -> Result<T> {
- #[derive(serde::Deserialize)]
- struct Envelope<T> {
- #[serde(default)]
- success: bool,
- data: Option<T>,
- #[serde(default)]
- error: Option<String>,
- }
-
- let url = crate::util::url::join_url(&self.inner.backend_url, path);
- tracing::debug!("[composio] DELETE {}", url);
-
- // Build a fresh lightweight reqwest client for this DELETE.
- // Note: this allocates a *new* connection pool — it does NOT
- // reuse the pool inside `self.inner`. To reuse the shared pool
- // we'd need to clone or expose the existing `reqwest::Client`
- // from `IntegrationClient`, which we intentionally avoid so the
- // public surface of that type doesn't widen for one caller.
- //
- // Mirror the TLS settings of the shared client so this path has the
- // same connection behaviour as the other backend calls.
- // Platform-appropriate TLS backend — see [`crate::util::tls`].
- let http_client = crate::util::tls::tls_client_builder()
- .http1_only()
- .timeout(std::time::Duration::from_secs(60))
- .connect_timeout(std::time::Duration::from_secs(15))
- .build()?;
-
- let resp = http_client
- .delete(&url)
- .headers(self.inner.auth_headers()?)
- .send()
- .await?;
-
- let status = resp.status();
- if !status.is_success() {
- let body_text = resp.text().await.unwrap_or_default();
- let detail = crate::integrations::client::extract_error_detail(
- &body_text,
- crate::integrations::client::MAX_ERROR_BODY_LEN,
- );
- // Use the same UTF-8-safe truncation for the debug-log preview
- // — direct byte-slicing (`&body_text[..len.min(300)]`) panics
- // when the cutoff lands inside a multibyte codepoint.
- let logged_body = crate::integrations::client::extract_error_detail(&body_text, 300);
- tracing::debug!(
- "[composio] DELETE {} → {} body={}",
- url,
- status,
- logged_body
- );
- let status_str = status.as_u16().to_string();
- // Mirrors the integrations post()/get() sites — see
- // OPENHUMAN-TAURI-BC. 4xx user-input / auth-state shapes
- // demote via the observability classifier; 5xx and
- // non-transient 4xx still surface as actionable events.
- crate::core::observability::report_error_or_expected(
- format!("Backend returned {status} for DELETE {url}: {detail}").as_str(),
- "composio",
- "delete",
- &[
- ("path", path),
- ("status", status_str.as_str()),
- ("failure", "non_2xx"),
- ],
- );
- anyhow::bail!("Backend returned {status} for DELETE {url}: {detail}");
- }
-
- let envelope: Envelope<T> = resp.json().await?;
- if !envelope.success {
- let msg = envelope
- .error
- .unwrap_or_else(|| "unknown backend error".into());
- // Mirrors the integrations envelope-error sites — route through
- // the observability classifier so user-state envelope failures
- // (composio "Toolkit X is not enabled" / "Trigger type …
- // not found" / "Missing required fields: …" — OPENHUMAN-TAURI-3R
- // / -3S / -34 / -97) demote to a breadcrumb instead of firing
- // a Sentry event. Genuine backend bugs still surface.
- crate::core::observability::report_error_or_expected(
- msg.as_str(),
- "composio",
- "delete",
- &[("path", path), ("failure", "envelope_error")],
- );
- anyhow::bail!("Backend error for DELETE {}: {}", url, msg);
- }
- envelope.data.ok_or_else(|| {
- anyhow::anyhow!("Backend returned success but no data for DELETE {}", url)
- })
- }
-}
-
-fn required_oauth_scopes_for_toolkit(toolkit: &str) -> &'static [&'static str] {
- match toolkit.trim().to_ascii_lowercase().as_str() {
- // GMAIL_NEW_GMAIL_MESSAGE and the native Gmail sync path need read access
- // to messages. Without this hint fresh OAuth handoffs can complete with a
- // profile-only Google token and trigger enable fails with 403 insufficient
- // authentication scopes (#2186).
- "gmail" => GMAIL_REQUIRED_OAUTH_SCOPES,
- _ => &[],
- }
-}
-
-fn merge_required_oauth_scopes(body: &mut Value, toolkit: &str) -> anyhow::Result<()> {
- let required = required_oauth_scopes_for_toolkit(toolkit);
- if required.is_empty() {
- return Ok(());
- }
-
- let obj = body
- .as_object_mut()
- .ok_or_else(|| anyhow::anyhow!("composio.authorize: internal payload must be an object"))?;
- match obj.get_mut(AUTHORIZE_OAUTH_SCOPES_FIELD) {
- Some(existing) => append_missing_oauth_scopes(existing, required)?,
- None => {
- obj.insert(AUTHORIZE_OAUTH_SCOPES_FIELD.to_string(), json!(required));
- }
- }
- Ok(())
-}
-
-fn append_missing_oauth_scopes(value: &mut Value, required: &[&str]) -> anyhow::Result<()> {
- let mut scopes = match value {
- Value::Null => Vec::new(),
- Value::String(raw) => raw
- .split(|ch: char| ch == ',' || ch.is_whitespace())
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(ToString::to_string)
- .collect(),
- Value::Array(items) => {
- let mut out = Vec::with_capacity(items.len() + required.len());
- for item in items {
- let Some(scope) = item.as_str() else {
- anyhow::bail!(
- "composio.authorize: {AUTHORIZE_OAUTH_SCOPES_FIELD} entries must be strings"
- );
- };
- let scope = scope.trim();
- if !scope.is_empty() {
- out.push(scope.to_string());
- }
- }
- out
- }
- _ => {
- anyhow::bail!(
- "composio.authorize: {AUTHORIZE_OAUTH_SCOPES_FIELD} must be a string or array"
- );
- }
- };
-
- for scope in required {
- if !scopes.iter().any(|existing| existing == scope) {
- scopes.push((*scope).to_string());
- }
- }
- *value = json!(scopes);
- Ok(())
-}
diff --git a/crates/openhuman-core/src/integrations/composio/client/execute.rs b/crates/openhuman-core/src/integrations/composio/client/execute.rs
deleted file mode 100644
index e4f4168368..0000000000
--- a/crates/openhuman-core/src/integrations/composio/client/execute.rs
+++ /dev/null
@@ -1,48 +0,0 @@
-//! [`ComposioClient`]'s tool-discovery surface (`list_tools`). Execution runs
-//! in the `tinyconnectors` module; see `execute_dispatch`.
-
-use anyhow::Result;
-
-use super::super::types::ComposioToolsResponse;
-use super::connections::ComposioClient;
-
-impl ComposioClient {
- pub async fn list_tools(
- &self,
- toolkits: Option<&[String]>,
- tags: Option<&[String]>,
- ) -> Result<ComposioToolsResponse> {
- let mut params: Vec<String> = Vec::new();
- if let Some(list) = toolkits {
- let joined = list
- .iter()
- .map(|t| t.trim())
- .filter(|t| !t.is_empty())
- .map(|t| urlencoding::encode(t).into_owned())
- .collect::<Vec<_>>()
- .join(",");
- if !joined.is_empty() {
- params.push(format!("toolkits={joined}"));
- }
- }
- if let Some(list) = tags {
- let joined = list
- .iter()
- .map(|t| t.trim())
- .filter(|t| !t.is_empty())
- .map(|t| urlencoding::encode(t).into_owned())
- .collect::<Vec<_>>()
- .join(",");
- if !joined.is_empty() {
- params.push(format!("tags={joined}"));
- }
- }
- let path = if params.is_empty() {
- "/agent-integrations/composio/tools".to_string()
- } else {
- format!("/agent-integrations/composio/tools?{}", params.join("&"))
- };
- tracing::debug!(path = %path, "[composio] list_tools");
- self.inner.get::<ComposioToolsResponse>(&path).await
- }
-}
diff --git a/crates/openhuman-core/src/integrations/composio/client/factory.rs b/crates/openhuman-core/src/integrations/composio/client/factory.rs
index 0babd54238..0f96421fef 100644
--- a/crates/openhuman-core/src/integrations/composio/client/factory.rs
+++ b/crates/openhuman-core/src/integrations/composio/client/factory.rs
@@ -1,46 +1,23 @@
-//! Mode-aware Composio client construction: [`build_composio_client`]
-//! (backend-mode constructor), [`ComposioClientKind`] (the tagged
-//! backend/direct union), and [`create_composio_client`] (the factory that
-//! reads `config.composio.mode`).
+//! Mode-aware Composio route resolution.
+//!
+//! Every Composio operation runs in the `tinyconnectors` module
+//! (`module_client`). What stays on the host is the decision the module
+//! deliberately does not make: which route the current config selects and
+//! whether the credential for it exists. [`resolve_composio_route`] answers
+//! that with the actionable, user-facing messages (a missing direct key, a
+//! missing backend session, a typo in `composio.mode`) instead of the opaque
+//! "no connector route" the module reports when it is configured without one
+//! (#1710).
+//!
+//! [`ComposioRoute::Direct`] carries the slim direct-mode HTTP reader the host
+//! still needs for the two v3 reads the pinned module route does not match
+//! byte-for-byte (`/connected_accounts?limit=200`, `/tools` with
+//! `toolkit_versions=latest`, #3932) and for its loopback overrides.
use std::sync::Arc;
-use super::connections::ComposioClient;
-
-/// Backend-mode [`ComposioClient`] constructor. **Internal to the
-/// composio module** — external callers should use
-/// [`create_composio_client`] (factory) or
-/// [`crate::agent::subagent_host::user_is_signed_in_to_composio`]
-/// (probe) instead.
-///
-/// Direct exposure leaked through several call sites during the early
-/// direct-mode rollout (#1710), where the backend-only nature caused
-/// direct-mode users to false-negative the "signed in" check (the
-/// agent-tool registration gate, slack sync RPC, `tools.composio_execute`
-/// controller all silently dropped
-/// direct-mode users). Locking down here prevents future regressions —
-/// any new probe or execution path is forced through the mode-aware
-/// surface.
-///
-/// Composio is **always enabled** — there are no configuration flags
-/// gating it. The backend URL and credential come from the shared
-/// core defaults (`config.api_url` plus the TinyHumans API key or the
-/// app-session JWT) via [`crate::integrations::build_client`]. The only
-/// reason this returns `None` is that there is no backend credential. Direct-mode availability is orthogonal — see
-/// [`create_composio_client`].
-pub(crate) fn build_composio_client(config: &crate::config::Config) -> Option<ComposioClient> {
- let inner = crate::integrations::build_client(config)?;
- Some(ComposioClient::new(inner))
-}
-
-// ── Direct-mode factory ─────────────────────────────────────────────
-//
-// Mirrors `tinyinference-embeddings/src/factory.rs` so anyone reading both can
-// pattern-match between domains: string-matched mode, explicit error
-// on unknown mode, explicit error when `direct` is selected without an
-// API key.
-
use crate::config::schema::{COMPOSIO_MODE_BACKEND, COMPOSIO_MODE_DIRECT};
+use crate::integrations::composio::tools::DirectComposioClient;
// Re-declare the mode strings as local consts so they can be used as
// pattern arms in the `match` below. `use` imports of `pub const &str`
@@ -51,103 +28,79 @@ use crate::config::schema::{COMPOSIO_MODE_BACKEND, COMPOSIO_MODE_DIRECT};
const MODE_BACKEND_PAT: &str = COMPOSIO_MODE_BACKEND;
const MODE_DIRECT_PAT: &str = COMPOSIO_MODE_DIRECT;
-/// Tagged variant returned by [`create_composio_client`].
-///
-/// `Backend` wraps the existing backend-proxied [`ComposioClient`]
-/// (calls `api.tinyhumans.ai/agent-integrations/composio/*`).
+/// The route [`resolve_composio_route`] selected.
///
-/// `Direct` wraps the existing direct-mode HTTP wrapper from
-/// `composio/tools/direct.rs` that calls
-/// `https://backend.composio.dev/api/v{2,3}` with `x-api-key`. The
-/// direct client does not currently cover every endpoint the
-/// backend-proxied path exposes (no per-toolkit allowlist, no
-/// HMAC-verified trigger fan-out, no `/agent-integrations/pricing`),
-/// so most existing call-sites continue to use `Backend` for now.
-/// Direct-mode integration of the full surface (especially trigger
-/// webhooks) is a follow-up.
-pub enum ComposioClientKind {
- Backend(ComposioClient),
- /// Held inside an `Arc` so the variant stays cheap to clone — this
- /// matches the rest of the tool registry which juggles
- /// `Arc<dyn Tool>` for the same direct-mode tool elsewhere.
- Direct(Arc<crate::tools::ComposioTool>),
+/// `Backend` is a unit: the backend-proxied route is reached through the
+/// connector module, whose configuration (`modules::connectors::module_config`)
+/// carries the base URL and bearer. `Direct` wraps the host-side v3 reader
+/// (see the module docs) for the user's own key.
+pub enum ComposioRoute {
+ Backend,
+ /// Held inside an `Arc` so the variant stays cheap to clone.
+ Direct(Arc<DirectComposioClient>),
}
-pub(crate) fn create_direct_composio_tool_for_api_key(
+impl ComposioRoute {
+ /// Returns `"backend"` or `"direct"` — handy for logging and tests.
+ pub fn mode(&self) -> &'static str {
+ match self {
+ ComposioRoute::Backend => COMPOSIO_MODE_BACKEND,
+ ComposioRoute::Direct(_) => COMPOSIO_MODE_DIRECT,
+ }
+ }
+}
+
+pub(crate) fn create_direct_client_for_api_key(
config: &crate::config::Config,
api_key: &str,
-) -> anyhow::Result<Arc<crate::tools::ComposioTool>> {
- direct_tool(api_key, config.composio.entity_id.as_str(), None)
+) -> anyhow::Result<Arc<DirectComposioClient>> {
+ direct_client(api_key, config.composio.entity_id.as_str(), None)
}
-fn direct_tool(
+fn direct_client(
api_key: &str,
entity_id: &str,
base_urls: Option<&crate::config::ComposioDirectBaseUrls>,
-) -> anyhow::Result<Arc<crate::tools::ComposioTool>> {
+) -> anyhow::Result<Arc<DirectComposioClient>> {
let api_key = api_key.trim();
if api_key.is_empty() {
anyhow::bail!("composio direct api key must not be empty");
}
- // The direct client takes a `SecurityPolicy` for `Tool::execute`
- // gating, but the factory's job is only to materialize a *client*
- // — it does not actually invoke `execute()` itself, so the
- // default policy is sufficient here. Callers that go through
- // the `Tool` surface re-acquire the live policy from their own
- // context.
- let security = Arc::new(crate::security::SecurityPolicy::default());
if let Some(urls) = base_urls {
- let tool = crate::tools::ComposioTool::new_with_base_urls(
+ let client = DirectComposioClient::new_with_base_urls(
api_key,
Some(entity_id),
- security,
urls.v2.clone(),
urls.v3.clone(),
)?;
- return Ok(Arc::new(tool));
+ return Ok(Arc::new(client));
}
#[cfg(debug_assertions)]
- let tool = match (
+ let client = match (
std::env::var("OPENHUMAN_COMPOSIO_DIRECT_BASE_V2").ok(),
std::env::var("OPENHUMAN_COMPOSIO_DIRECT_BASE_V3").ok(),
) {
- (Some(base_v2), Some(base_v3)) => {
- crate::tools::ComposioTool::new_with_base_urls_for_loopback(
- api_key,
- Some(entity_id),
- security,
- base_v2,
- base_v3,
- )
- .map_err(|e| {
- anyhow::anyhow!("invalid debug composio direct loopback base override: {e}")
- })?
- }
- _ => crate::tools::ComposioTool::new(api_key, Some(entity_id), security),
+ (Some(base_v2), Some(base_v3)) => DirectComposioClient::new_with_base_urls_for_loopback(
+ api_key,
+ Some(entity_id),
+ base_v2,
+ base_v3,
+ )
+ .map_err(|e| anyhow::anyhow!("invalid debug composio direct loopback base override: {e}"))?,
+ _ => DirectComposioClient::new(api_key, Some(entity_id)),
};
#[cfg(not(debug_assertions))]
- let tool = crate::tools::ComposioTool::new(api_key, Some(entity_id), security);
- Ok(Arc::new(tool))
-}
-
-impl ComposioClientKind {
- /// Returns `"backend"` or `"direct"` — handy for logging and tests.
- pub fn mode(&self) -> &'static str {
- match self {
- ComposioClientKind::Backend(_) => COMPOSIO_MODE_BACKEND,
- ComposioClientKind::Direct(_) => COMPOSIO_MODE_DIRECT,
- }
- }
+ let client = DirectComposioClient::new(api_key, Some(entity_id));
+ Ok(Arc::new(client))
}
-/// Construct a [`ComposioClientKind`] from the root config.
+/// Resolve the [`ComposioRoute`] the root config selects.
///
/// Supported `config.composio.mode` values:
///
-/// - `"backend"` (default) — backend-proxied; identical to
-/// [`build_composio_client`]. Returns
-/// `Err("no backend session")` when the user is not signed in.
+/// - `"backend"` (default) — backend-proxied through the connector module.
+/// Returns `Err("no backend session token")` when the user is not signed in.
/// - `"direct"` — BYO key against `backend.composio.dev`. Requires a
/// stored Composio API key under the
/// [`crate::security::credentials::COMPOSIO_DIRECT_PROVIDER`]
@@ -160,17 +113,15 @@ impl ComposioClientKind {
///
/// Any other mode string is rejected with an explicit error so a typo
/// in `config.toml` fails loud instead of silently downgrading.
-pub fn create_composio_client(
- config: &crate::config::Config,
-) -> anyhow::Result<ComposioClientKind> {
+pub fn resolve_composio_route(config: &crate::config::Config) -> anyhow::Result<ComposioRoute> {
if let Some(pinned) = config.composio.host_credential.as_ref() {
- let tool = direct_tool(pinned.api_key(), pinned.entity(), pinned.direct_base_urls())?;
+ let client = direct_client(pinned.api_key(), pinned.entity(), pinned.direct_base_urls())?;
tracing::debug!("[composio-factory] resolved host-pinned direct variant (key redacted)");
- return Ok(ComposioClientKind::Direct(tool));
+ return Ok(ComposioRoute::Direct(client));
}
let mode = config.composio.mode.trim();
- tracing::debug!(mode = %mode, "[composio-factory] resolving client");
+ tracing::debug!(mode = %mode, "[composio-factory] resolving route");
match mode {
// Empty string is treated as the default for forward compatibility
@@ -178,14 +129,14 @@ pub fn create_composio_client(
// already gives us "backend" for missing fields, but a literal
// empty string in TOML would otherwise be rejected.
"" | MODE_BACKEND_PAT => {
- let client = build_composio_client(config).ok_or_else(|| {
- anyhow::anyhow!(
+ if crate::integrations::build_client(config).is_none() {
+ anyhow::bail!(
"composio backend mode unavailable: no backend session token. \
Sign in or set a TinyHumans API key."
- )
- })?;
+ );
+ }
tracing::debug!("[composio-factory] resolved backend variant");
- Ok(ComposioClientKind::Backend(client))
+ Ok(ComposioRoute::Backend)
}
MODE_DIRECT_PAT => {
// Prefer keychain-stored key; fall back to `config.toml`.
@@ -207,12 +158,12 @@ pub fn create_composio_client(
)
})?;
- let tool = create_direct_composio_tool_for_api_key(config, &api_key)?;
+ let client = create_direct_client_for_api_key(config, &api_key)?;
tracing::debug!(
key_len = api_key.len(),
"[composio-factory] resolved direct variant (key redacted)"
);
- Ok(ComposioClientKind::Direct(tool))
+ Ok(ComposioRoute::Direct(client))
}
unknown => {
tracing::warn!(mode = %unknown, "[composio-factory] unknown composio mode");
diff --git a/crates/openhuman-core/src/integrations/composio/client/triggers.rs b/crates/openhuman-core/src/integrations/composio/client/triggers.rs
deleted file mode 100644
index 641784d6cc..0000000000
--- a/crates/openhuman-core/src/integrations/composio/client/triggers.rs
+++ /dev/null
@@ -1,145 +0,0 @@
-//! [`ComposioClient`]'s GitHub-repo listing and trigger-management surface:
-//! `list_github_repos`, `create_trigger`, `list_available_triggers`,
-//! `list_active_triggers`, `enable_trigger`, and `disable_trigger` (the
-//! latter via the shared `raw_delete` helper in [`super::connections`]).
-
-use anyhow::Result;
-use serde_json::json;
-
-use super::super::types::{
- ComposioActiveTriggersResponse, ComposioAvailableTriggersResponse,
- ComposioCreateTriggerResponse, ComposioDisableTriggerResponse, ComposioEnableTriggerResponse,
- ComposioGithubReposResponse,
-};
-use super::connections::ComposioClient;
-
-impl ComposioClient {
- pub async fn list_github_repos(
- &self,
- connection_id: Option<&str>,
- ) -> Result<ComposioGithubReposResponse> {
- let path = match connection_id.map(str::trim).filter(|id| !id.is_empty()) {
- Some(id) => format!("/agent-integrations/composio/github/repos?connectionId={id}"),
- None => "/agent-integrations/composio/github/repos".to_string(),
- };
- tracing::debug!(path = %path, "[composio] list_github_repos");
- self.inner.get::<ComposioGithubReposResponse>(&path).await
- }
-
- /// `POST /agent-integrations/composio/triggers` — create a trigger
- /// instance for the authenticated user.
- pub async fn create_trigger(
- &self,
- slug: &str,
- connection_id: Option<&str>,
- trigger_config: Option<serde_json::Value>,
- ) -> Result<ComposioCreateTriggerResponse> {
- let slug = slug.trim();
- if slug.is_empty() {
- anyhow::bail!("composio.create_trigger: slug must not be empty");
- }
- let mut body = json!({ "slug": slug });
- if let Some(connection_id) = connection_id.map(str::trim).filter(|id| !id.is_empty()) {
- body["connectionId"] = json!(connection_id);
- }
- if let Some(config) = trigger_config {
- body["triggerConfig"] = config;
- }
- tracing::debug!(slug = %slug, "[composio] create_trigger");
- self.inner
- .post::<ComposioCreateTriggerResponse>("/agent-integrations/composio/triggers", &body)
- .await
- }
-
- // ── Trigger management (PR #671) ────────────────────────────────
-
- /// `GET /agent-integrations/composio/triggers/available` — catalog of
- /// triggers the user could enable for a toolkit. For GitHub the
- /// backend fans out into per-repo entries scoped by `connection_id`.
- pub async fn list_available_triggers(
- &self,
- toolkit: &str,
- connection_id: Option<&str>,
- ) -> Result<ComposioAvailableTriggersResponse> {
- let toolkit = toolkit.trim();
- if toolkit.is_empty() {
- anyhow::bail!("composio.list_available_triggers: toolkit must not be empty");
- }
- let toolkit_q = urlencoding::encode(toolkit);
- let path = match connection_id.map(str::trim).filter(|id| !id.is_empty()) {
- Some(id) => format!(
- "/agent-integrations/composio/triggers/available?toolkit={toolkit_q}&connectionId={}",
- urlencoding::encode(id)
- ),
- None => format!(
- "/agent-integrations/composio/triggers/available?toolkit={toolkit_q}"
- ),
- };
- tracing::debug!(path = %path, "[composio] list_available_triggers");
- self.inner
- .get::<ComposioAvailableTriggersResponse>(&path)
- .await
- }
-
- /// `GET /agent-integrations/composio/triggers` — currently enabled
- /// triggers for the user, optionally filtered to a toolkit.
- pub async fn list_active_triggers(
- &self,
- toolkit: Option<&str>,
- ) -> Result<ComposioActiveTriggersResponse> {
- let path = match toolkit.map(str::trim).filter(|t| !t.is_empty()) {
- Some(t) => format!(
- "/agent-integrations/composio/triggers?toolkit={}",
- urlencoding::encode(t)
- ),
- None => "/agent-integrations/composio/triggers".to_string(),
- };
- tracing::debug!(path = %path, "[composio] list_active_triggers");
- self.inner
- .get::<ComposioActiveTriggersResponse>(&path)
- .await
- }
-
- /// `POST /agent-integrations/composio/triggers` — enable a single
- /// trigger on a connection the caller owns.
- pub async fn enable_trigger(
- &self,
- connection_id: &str,
- slug: &str,
- trigger_config: Option<serde_json::Value>,
- ) -> Result<ComposioEnableTriggerResponse> {
- let connection_id = connection_id.trim();
- let slug = slug.trim();
- if connection_id.is_empty() {
- anyhow::bail!("composio.enable_trigger: connectionId must not be empty");
- }
- if slug.is_empty() {
- anyhow::bail!("composio.enable_trigger: slug must not be empty");
- }
- let mut body = json!({ "connectionId": connection_id, "slug": slug });
- if let Some(config) = trigger_config {
- body["triggerConfig"] = config;
- }
- tracing::debug!(slug = %slug, connection_id = %connection_id, "[composio] enable_trigger");
- self.inner
- .post::<ComposioEnableTriggerResponse>("/agent-integrations/composio/triggers", &body)
- .await
- }
-
- /// `DELETE /agent-integrations/composio/triggers/:triggerId`.
- pub async fn disable_trigger(
- &self,
- trigger_id: &str,
- ) -> Result<ComposioDisableTriggerResponse> {
- let trigger_id = trigger_id.trim();
- if trigger_id.is_empty() {
- anyhow::bail!("composio.disable_trigger: triggerId must not be empty");
- }
- tracing::debug!(trigger_id = %trigger_id, "[composio] disable_trigger");
- self.raw_delete::<ComposioDisableTriggerResponse>(&format!(
- "/agent-integrations/composio/triggers/{}",
- urlencoding::encode(trigger_id)
- ))
- .await
- }
-}
diff --git a/crates/openhuman-core/src/integrations/composio/client_authorize_and_execute_tests.rs b/crates/openhuman-core/src/integrations/composio/client_authorize_and_execute_tests.rs
deleted file mode 100644
index bb1013287b..0000000000
--- a/crates/openhuman-core/src/integrations/composio/client_authorize_and_execute_tests.rs
+++ /dev/null
@@ -1,389 +0,0 @@
-use super::*;
-
-/// `build_composio_client` must return `None` when the user has no auth
-/// token — callers treat that as "skip silently" (user not signed in).
-#[test]
-fn build_composio_client_none_without_auth_token() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = Config::default();
- config.config_path = tmp.path().join("config.toml");
- assert!(build_composio_client(&config).is_none());
-}
-
-#[test]
-fn build_composio_client_some_with_auth_token() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = Config::default();
- config.config_path = tmp.path().join("config.toml");
- crate::security::credentials::AuthService::from_config(&config)
- .store_provider_token(
- crate::security::credentials::APP_SESSION_PROVIDER,
- crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,
- "test-token",
- std::collections::HashMap::new(),
- true,
- )
- .expect("store test session token");
- let client = build_composio_client(&config).expect("client should build when session is set");
- assert!(
- !client.inner().auth_token.is_empty(),
- "resolved auth token should not be empty"
- );
-}
-
-/// `authorize()` is input-validated — an empty / whitespace toolkit
-/// must error without making any HTTP call.
-#[tokio::test]
-async fn authorize_rejects_empty_toolkit() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
- let err = client.authorize(" ", None).await.unwrap_err();
- assert!(
- err.to_string().contains("toolkit must not be empty"),
- "unexpected error: {err}"
- );
-}
-
-/// `authorize()` must reject a non-object `extra_params` before making any HTTP call.
-#[tokio::test]
-async fn authorize_rejects_non_object_extra_params() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
- let err = client
- .authorize("whatsapp", Some(serde_json::json!("waba-123")))
- .await
- .unwrap_err();
- assert!(
- err.to_string()
- .contains("extra_params must be a JSON object"),
- "unexpected error: {err}"
- );
-}
-
-/// `authorize()` must reject an `extra_params` object that tries to override a reserved key.
-#[tokio::test]
-async fn authorize_rejects_reserved_key_override() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
- let err = client
- .authorize("whatsapp", Some(serde_json::json!({ "toolkit": "gmail" })))
- .await
- .unwrap_err();
- assert!(
- err.to_string().contains("cannot override reserved key"),
- "unexpected error: {err}"
- );
-}
-
-/// `delete_connection()` likewise must reject empty connection ids.
-#[tokio::test]
-async fn delete_connection_rejects_empty_id() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
- let err = client.delete_connection("").await.unwrap_err();
- assert!(
- err.to_string().contains("connectionId must not be empty"),
- "unexpected error: {err}"
- );
-}
-
-/// ComposioClient is `Clone` so each tool gets a cheap handle share.
-/// Inner client must be Arc-shared — no duplication.
-#[test]
-fn client_clone_shares_inner_arc() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client_a = ComposioClient::new(inner);
- let client_b = client_a.clone();
- assert!(
- Arc::ptr_eq(client_a.inner(), client_b.inner()),
- "clones should share the same Arc<IntegrationClient>"
- );
-}
-
-#[tokio::test]
-async fn list_toolkits_parses_backend_envelope() {
- let app = Router::new().route(
- "/agent-integrations/composio/toolkits",
- get(|| async {
- Json(json!({
- "success": true,
- "data": { "toolkits": ["gmail", "notion"] }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client.list_toolkits().await.unwrap();
- assert_eq!(
- resp.toolkits,
- vec!["gmail".to_string(), "notion".to_string()]
- );
-}
-
-#[tokio::test]
-async fn list_connections_parses_connection_array() {
- let app = Router::new().route(
- "/agent-integrations/composio/connections",
- get(|| async {
- Json(json!({
- "success": true,
- "data": {
- "connections": [
- { "id": "c1", "toolkit": "gmail", "status": "ACTIVE", "createdAt": "2026-01-01T00:00:00Z" },
- { "id": "c2", "toolkit": "notion", "status": "PENDING" }
- ]
- }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client.list_connections().await.unwrap();
- assert_eq!(resp.connections.len(), 2);
- assert_eq!(resp.connections[0].id, "c1");
- assert_eq!(resp.connections[1].status, "PENDING");
-}
-
-#[tokio::test]
-async fn authorize_posts_toolkit_and_returns_connect_url() {
- let app =
- Router::new().route(
- "/agent-integrations/composio/authorize",
- post(|Json(body): Json<Value>| async move {
- // Echo toolkit back so we know our POST body made it.
- let tk = body["toolkit"].as_str().unwrap_or("").to_string();
- let scopes = body["oauth_scopes"]
- .as_array()
- .expect("gmail authorize should include oauth_scopes");
- assert!(scopes.iter().any(|scope| scope.as_str()
- == Some("https://www.googleapis.com/auth/gmail.readonly")));
- Json(json!({
- "success": true,
- "data": {
- "connectUrl": format!("https://composio.example/{tk}/consent"),
- "connectionId": "conn-abc"
- }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client.authorize("gmail", None).await.unwrap();
- assert!(resp.connect_url.contains("gmail"));
- assert_eq!(resp.connection_id, "conn-abc");
-}
-
-#[tokio::test]
-async fn authorize_merges_gmail_required_oauth_scopes_with_extra_params() {
- let app = Router::new().route(
- "/agent-integrations/composio/authorize",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["toolkit"].as_str(), Some("gmail"));
- assert_eq!(body["prompt"].as_str(), Some("consent"));
- let scopes: Vec<&str> = body["oauth_scopes"]
- .as_array()
- .expect("oauth_scopes should be an array")
- .iter()
- .map(|item| item.as_str().expect("scope should be a string"))
- .collect();
- assert!(scopes.contains(&"openid"));
- assert!(scopes.contains(&"https://www.googleapis.com/auth/gmail.readonly"));
- Json(json!({
- "success": true,
- "data": {
- "connectUrl": "https://composio.example/gmail/consent",
- "connectionId": "conn-gmail"
- }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let extra = serde_json::json!({
- "prompt": "consent",
- "oauth_scopes": ["openid"]
- });
- let resp = client.authorize("gmail", Some(extra)).await.unwrap();
- assert!(resp.connect_url.contains("gmail"));
- assert_eq!(resp.connection_id, "conn-gmail");
-}
-
-#[tokio::test]
-async fn authorize_forwards_extra_params_and_returns_connect_url() {
- let app = Router::new().route(
- "/agent-integrations/composio/authorize",
- post(|Json(body): Json<Value>| async move {
- // Assert extra_params are forwarded alongside toolkit.
- assert_eq!(body["toolkit"].as_str(), Some("whatsapp"));
- assert_eq!(body["waba_id"].as_str(), Some("waba-123"));
- assert!(body.get("oauth_scopes").is_none());
- Json(json!({
- "success": true,
- "data": {
- "connectUrl": "https://composio.example/whatsapp/consent",
- "connectionId": "conn-xyz"
- }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let extra = serde_json::json!({ "waba_id": "waba-123" });
- let resp = client.authorize("whatsapp", Some(extra)).await.unwrap();
- assert!(resp.connect_url.contains("whatsapp"));
- assert_eq!(resp.connection_id, "conn-xyz");
-}
-
-#[tokio::test]
-async fn list_tools_filters_pass_through_as_csv_query_param() {
- let app = Router::new().route(
- "/agent-integrations/composio/tools",
- get(|Query(q): Query<HashMap<String, String>>| async move {
- let toolkits = q.get("toolkits").cloned().unwrap_or_default();
- let tags = q.get("tags").cloned().unwrap_or_default();
- // Echo both filters back so the test can assert they reached the server.
- let echo = if tags.is_empty() {
- format!("ECHO_{toolkits}")
- } else {
- format!("ECHO_{toolkits}_TAGS_{tags}")
- };
- Json(json!({
- "success": true,
- "data": {
- "tools": [{
- "type": "function",
- "function": {
- "name": echo,
- "description": "echo",
- "parameters": {}
- }
- }]
- }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
-
- // No filter: URL should lack both query params
- let resp_all = client.list_tools(None, None).await.unwrap();
- assert_eq!(resp_all.tools.len(), 1);
- assert_eq!(resp_all.tools[0].function.name, "ECHO_");
-
- // toolkits only: CSV-joined
- let resp_filtered = client
- .list_tools(Some(&["gmail".to_string(), "notion".to_string()]), None)
- .await
- .unwrap();
- assert_eq!(resp_filtered.tools[0].function.name, "ECHO_gmail,notion");
-
- // Whitespace entries should be dropped before joining
- let resp_trimmed = client
- .list_tools(Some(&["gmail".to_string(), " ".to_string()]), None)
- .await
- .unwrap();
- assert_eq!(resp_trimmed.tools[0].function.name, "ECHO_gmail");
-
- // tags only
- let resp_tags = client
- .list_tools(None, Some(&["readOnlyHint".to_string()]))
- .await
- .unwrap();
- assert_eq!(resp_tags.tools[0].function.name, "ECHO__TAGS_readOnlyHint");
-
- // toolkits + tags both forwarded
- let resp_both = client
- .list_tools(
- Some(&["github".to_string()]),
- Some(&["stars".to_string(), "repos".to_string()]),
- )
- .await
- .unwrap();
- assert_eq!(
- resp_both.tools[0].function.name,
- "ECHO_github_TAGS_stars,repos"
- );
-
- // Empty tags slice treated as no filter
- let resp_empty_tags = client
- .list_tools(Some(&["gmail".to_string()]), Some(&[]))
- .await
- .unwrap();
- assert_eq!(resp_empty_tags.tools[0].function.name, "ECHO_gmail");
-}
-
-#[tokio::test]
-async fn backend_error_envelope_becomes_bail() {
- let app = Router::new().route(
- "/agent-integrations/composio/toolkits",
- get(|| async { Json(json!({ "success": false, "error": "backend unavailable" })) }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let err = client.list_toolkits().await.unwrap_err();
- assert!(err.to_string().contains("backend unavailable"));
-}
-
-#[tokio::test]
-async fn http_error_status_propagates() {
- let app = Router::new().route(
- "/agent-integrations/composio/connections",
- get(|| async { StatusCode::INTERNAL_SERVER_ERROR }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let err = client.list_connections().await.unwrap_err();
- assert!(err.to_string().contains("500") || err.to_string().contains("Backend returned"));
-}
-
-#[tokio::test]
-async fn delete_connection_happy_path_returns_deleted_true() {
- let app = Router::new().route(
- "/agent-integrations/composio/connections/{id}",
- axum::routing::delete(|Path(id): Path<String>| async move {
- assert_eq!(id, "conn-42");
- Json(json!({
- "success": true,
- "data": { "deleted": true }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client.delete_connection("conn-42").await.unwrap();
- assert!(resp.deleted);
-}
-
-// ── Trigger management (PR #671) ────────────────────────────────────
-
-#[tokio::test]
-async fn list_available_triggers_rejects_empty_toolkit() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
- let err = client
- .list_available_triggers(" ", None)
- .await
- .unwrap_err();
- assert!(
- err.to_string().contains("toolkit must not be empty"),
- "unexpected: {err}"
- );
-}
diff --git a/crates/openhuman-core/src/integrations/composio/client_triggers_and_factory_tests.rs b/crates/openhuman-core/src/integrations/composio/client_triggers_and_factory_tests.rs
deleted file mode 100644
index 25d8b20e25..0000000000
--- a/crates/openhuman-core/src/integrations/composio/client_triggers_and_factory_tests.rs
+++ /dev/null
@@ -1,436 +0,0 @@
-use super::*;
-
-#[tokio::test]
-async fn list_available_triggers_forwards_query_params() {
- let app = Router::new().route(
- "/agent-integrations/composio/triggers/available",
- get(|Query(q): Query<HashMap<String, String>>| async move {
- assert_eq!(q.get("toolkit").map(String::as_str), Some("github"));
- assert_eq!(q.get("connectionId").map(String::as_str), Some("c1"));
- Json(json!({
- "success": true,
- "data": {"triggers": [{"slug": "GITHUB_PUSH_EVENT", "scope": "github_repo"}]}
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client
- .list_available_triggers("github", Some("c1"))
- .await
- .unwrap();
- assert_eq!(resp.triggers.len(), 1);
- assert_eq!(resp.triggers[0].scope, "github_repo");
-}
-
-#[tokio::test]
-async fn list_active_triggers_filters_by_toolkit() {
- let app = Router::new().route(
- "/agent-integrations/composio/triggers",
- get(|Query(q): Query<HashMap<String, String>>| async move {
- assert_eq!(q.get("toolkit").map(String::as_str), Some("gmail"));
- Json(json!({
- "success": true,
- "data": {"triggers": []}
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client.list_active_triggers(Some("gmail")).await.unwrap();
- assert!(resp.triggers.is_empty());
-}
-
-#[tokio::test]
-async fn enable_trigger_rejects_empty_inputs() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
-
- let err = client.enable_trigger("", "X", None).await.unwrap_err();
- assert!(err.to_string().contains("connectionId must not be empty"));
-
- let err = client.enable_trigger("c1", " ", None).await.unwrap_err();
- assert!(err.to_string().contains("slug must not be empty"));
-}
-
-#[tokio::test]
-async fn enable_trigger_posts_body_and_parses_response() {
- let app = Router::new().route(
- "/agent-integrations/composio/triggers",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["connectionId"], "c1");
- assert_eq!(body["slug"], "GMAIL_NEW_GMAIL_MESSAGE");
- assert_eq!(body["triggerConfig"]["labelIds"], "INBOX");
- Json(json!({
- "success": true,
- "data": {
- "triggerId": "ti_1",
- "slug": "GMAIL_NEW_GMAIL_MESSAGE",
- "connectionId": "c1"
- }
- }))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client
- .enable_trigger(
- "c1",
- "GMAIL_NEW_GMAIL_MESSAGE",
- Some(json!({"labelIds": "INBOX"})),
- )
- .await
- .unwrap();
- assert_eq!(resp.trigger_id, "ti_1");
-}
-
-#[tokio::test]
-async fn disable_trigger_rejects_empty_id() {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- "http://127.0.0.1:0".into(),
- "test".into(),
- ));
- let client = ComposioClient::new(inner);
- let err = client.disable_trigger("").await.unwrap_err();
- assert!(err.to_string().contains("triggerId must not be empty"));
-}
-
-#[tokio::test]
-async fn disable_trigger_calls_delete_path() {
- let app = Router::new().route(
- "/agent-integrations/composio/triggers/{id}",
- axum::routing::delete(|Path(id): Path<String>| async move {
- assert_eq!(id, "ti_1");
- Json(json!({"success": true, "data": {"deleted": true}}))
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let resp = client.disable_trigger("ti_1").await.unwrap();
- assert!(resp.deleted);
-}
-
-#[tokio::test]
-async fn disable_trigger_surfaces_non_2xx_status() {
- let app = Router::new().route(
- "/agent-integrations/composio/triggers/{id}",
- axum::routing::delete(|Path(_id): Path<String>| async move {
- (
- StatusCode::NOT_FOUND,
- Json(json!({"success": false, "error": "no"})),
- )
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let err = client.disable_trigger("ti_x").await.unwrap_err();
- let msg = err.to_string();
- assert!(msg.contains("404"), "expected status 404, got: {msg}");
- // Phase A (#1296): raw_delete must propagate the envelope's `error`
- // field so callers can tell *why* the backend rejected the call.
- assert!(
- msg.contains("no"),
- "expected envelope error detail in message, got: {msg}"
- );
-}
-
-#[tokio::test]
-async fn delete_connection_surfaces_envelope_error_detail() {
- // Direct cover of the `raw_delete` envelope-error path used by
- // `delete_connection` — proves the backend message ("Connection
- // not found") makes it into the propagated bail message rather
- // than being discarded with the body. Mirror of the `post`/`get`
- // envelope tests in `integrations/client_tests.rs`.
- let app = Router::new().route(
- "/agent-integrations/composio/connections/{id}",
- axum::routing::delete(|Path(_id): Path<String>| async move {
- (
- StatusCode::BAD_REQUEST,
- Json(json!({"success": false, "error": "Connection not found"})),
- )
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
- let err = client.delete_connection("missing-id").await.unwrap_err();
- let msg = err.to_string();
- assert!(
- msg.contains("Connection not found"),
- "expected backend error detail in message, got: {msg}"
- );
- assert!(msg.contains("400"), "expected status 400, got: {msg}");
-}
-
-// ── execute_tool resilience tests (Batch 1 — post-OAuth readiness) ─────
-
-#[test]
-fn create_composio_client_backend_variant_when_mode_default() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let config = config_with_session_token(&tmp);
- let kind = create_composio_client(&config).expect("backend mode should build");
- assert_eq!(kind.mode(), "backend");
- assert!(matches!(kind, ComposioClientKind::Backend(_)));
-}
-
-#[test]
-fn create_composio_client_backend_empty_mode_falls_back_to_backend() {
- // A literal empty string in TOML should be treated as the default
- // (`"backend"`) rather than an unknown mode error.
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = config_with_session_token(&tmp);
- config.composio.mode = String::new();
- let kind = create_composio_client(&config).expect("empty mode should fall back to backend");
- assert_eq!(kind.mode(), "backend");
-}
-
-#[test]
-fn create_composio_client_backend_errors_without_session() {
- // Backend mode requires the app-session JWT — without it the
- // factory must return an explicit error (not silently downgrade).
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.config_path = tmp.path().join("config.toml");
- let err = create_composio_client(&config)
- .err()
- .expect("must error without auth token");
- assert!(
- err.to_string().contains("no backend session token"),
- "unexpected error: {err}"
- );
-}
-
-#[test]
-fn create_composio_client_direct_variant_with_stored_key() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.config_path = tmp.path().join("config.toml");
- config.composio.mode = "direct".into();
- // Persist the key the way the RPC layer would.
- crate::security::credentials::AuthService::from_config(&config)
- .store_provider_token(
- crate::security::credentials::COMPOSIO_DIRECT_PROVIDER,
- crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,
- "ck_test_key_redacted",
- std::collections::HashMap::new(),
- true,
- )
- .expect("store direct api key");
- let kind = create_composio_client(&config).expect("direct mode with stored key should build");
- assert_eq!(kind.mode(), "direct");
- assert!(matches!(kind, ComposioClientKind::Direct(_)));
-}
-
-#[test]
-fn create_composio_client_direct_falls_back_to_config_api_key() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.config_path = tmp.path().join("config.toml");
- config.composio.mode = "direct".into();
- // No keychain entry — fall back to the inline config field.
- config.composio.api_key = Some("ck_inline_redacted".into());
- let kind = create_composio_client(&config)
- .expect("direct mode should accept inline config.api_key when keychain is empty");
- assert_eq!(kind.mode(), "direct");
-}
-
-#[test]
-fn create_composio_client_direct_errors_without_key() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.config_path = tmp.path().join("config.toml");
- config.composio.mode = "direct".into();
- let err = create_composio_client(&config)
- .err()
- .expect("direct without key must error");
- let msg = err.to_string();
- assert!(
- msg.contains("no api key is configured"),
- "unexpected error: {msg}"
- );
-}
-
-#[test]
-fn create_composio_client_unknown_mode_errors() {
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.config_path = tmp.path().join("config.toml");
- config.composio.mode = "voyage".into();
- let err = create_composio_client(&config)
- .err()
- .expect("unknown mode must error");
- let msg = err.to_string();
- assert!(msg.contains("unknown composio mode"), "got: {msg}");
- assert!(
- msg.contains("voyage"),
- "should echo the invalid value, got: {msg}"
- );
-}
-
-// ── Direct-mode credentials helpers ─────────────────────────────────
-
-#[test]
-fn store_get_clear_composio_api_key_roundtrip() {
- use crate::security::credentials::{get_composio_api_key, COMPOSIO_DIRECT_PROVIDER};
-
- let tmp = tempfile::tempdir().expect("tempdir");
- let mut config = crate::config::Config::default();
- config.config_path = tmp.path().join("config.toml");
-
- // Initially: nothing stored.
- assert_eq!(
- get_composio_api_key(&config).expect("read empty store"),
- None
- );
-
- // Store under the direct-mode provider slot.
- crate::security::credentials::AuthService::from_config(&config)
- .store_provider_token(
- COMPOSIO_DIRECT_PROVIDER,
- crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,
- "ck_secret_value_redacted",
- std::collections::HashMap::new(),
- true,
- )
- .expect("store");
-
- assert_eq!(
- get_composio_api_key(&config).expect("read stored"),
- Some("ck_secret_value_redacted".into())
- );
-
- // Clearing the profile must remove it again.
- crate::security::credentials::AuthService::from_config(&config)
- .remove_profile(
- COMPOSIO_DIRECT_PROVIDER,
- crate::security::credentials::DEFAULT_AUTH_PROFILE_NAME,
- )
- .expect("remove");
- assert_eq!(
- get_composio_api_key(&config).expect("read post-clear"),
- None
- );
-}
-
-#[tokio::test]
-async fn direct_list_connections_stops_hitting_composio_after_repeated_invalid_api_key() {
- let hits = Arc::new(AtomicUsize::new(0));
- let app = Router::new()
- .route(
- "/connected_accounts",
- get(|State(hits): State<Arc<AtomicUsize>>| async move {
- hits.fetch_add(1, Ordering::SeqCst);
- (
- StatusCode::UNAUTHORIZED,
- Json(json!({ "error": { "message": "Invalid API key" } })),
- )
- }),
- )
- .with_state(hits.clone());
- let base = start_mock_backend(app).await;
- let tool = direct_tool_for_mock_with_key(base, "ck_test_direct_invalid_backoff");
- let _auth_guard = DirectAuthFailureGuard::for_tool(&tool);
-
- for _ in 0..2 {
- let err = direct_list_connections(&tool)
- .await
- .expect_err("invalid key should reject");
- assert!(
- err.to_string().contains("Invalid API key"),
- "unexpected error: {err:#}"
- );
- }
-
- let opened = direct_list_connections(&tool)
- .await
- .expect_err("third invalid-key failure should open the backoff gate");
- assert!(
- opened.to_string().contains("re-enter"),
- "backoff error should be actionable, got: {opened:#}"
- );
-
- let short_circuit = direct_list_connections(&tool)
- .await
- .expect_err("open backoff gate should short-circuit before HTTP");
- assert!(
- short_circuit.to_string().contains("re-enter"),
- "short-circuit error should stay actionable, got: {short_circuit:#}"
- );
- assert_eq!(
- hits.load(Ordering::SeqCst),
- 3,
- "after three invalid-key failures, later polls must not hit Composio"
- );
-}
-
-#[tokio::test]
-async fn direct_list_tools_forwards_tags_and_reshapes_v3_envelope() {
- use axum::extract::RawQuery;
- use std::sync::Mutex;
-
- let captured: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
- let sink = captured.clone();
- let app = Router::new().route(
- "/tools",
- get(move |RawQuery(q): RawQuery| {
- let sink = sink.clone();
- async move {
- *sink.lock().unwrap() = q;
- Json(json!({
- "items": [
- {
- "slug": "GITHUB_STAR_A_REPOSITORY",
- "description": "Star a repository",
- "input_parameters": { "type": "object" },
- "toolkit": { "slug": "github" }
- },
- // Empty-slug rows must be dropped by the reshaper.
- { "slug": "", "description": "junk" }
- ]
- }))
- }
- }),
- );
- let base = start_mock_backend(app).await;
- let tool = direct_tool_for_mock(base);
-
- let resp = super::super::direct_list_tools(
- &tool,
- &["github".to_string()],
- Some(&["stars".to_string(), "repos".to_string()]),
- )
- .await
- .expect("direct_list_tools should succeed against the mock");
-
- // Outbound: tags forwarded as repeated params, toolkits CSV.
- let query = captured.lock().unwrap().clone().expect("server saw query");
- assert!(query.contains("tags=stars"), "query was: {query}");
- assert!(query.contains("tags=repos"), "query was: {query}");
- assert!(query.contains("toolkits=github"), "query was: {query}");
-
- // Inbound: reshaped into the backend envelope, empty-slug row dropped.
- assert_eq!(resp.tools.len(), 1);
- assert_eq!(resp.tools[0].function.name, "GITHUB_STAR_A_REPOSITORY");
- assert_eq!(resp.tools[0].kind, "function");
-}
-
-#[tokio::test]
-async fn pricing_for_config_short_circuits_in_direct_mode() {
- // Build a client pointed at an unreachable backend — if the
- // short-circuit fires, we never actually attempt the network call
- // and the empty default struct comes back immediately.
- let client =
- crate::integrations::IntegrationClient::new("http://127.0.0.1:0".into(), "test".into());
- let mut config = crate::config::Config::default();
- config.composio.mode = "direct".into();
-
- let pricing = crate::integrations::pricing_for_config(&client, &config).await;
- // The default struct has every per-integration entry as `None`.
- assert!(pricing.integrations.apify.is_none());
- assert!(pricing.integrations.twilio.is_none());
- assert!(pricing.integrations.google_places.is_none());
- assert!(pricing.integrations.parallel.is_none());
- assert!(pricing.integrations.tinyfish.is_none());
-}