Skip to content

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

fix(composio): handle stale auth tokens with automatic re-authentication

Steven Enamakel74ef5145c458
diff --git a/crates/openhuman-core/src/integrations/composio/auth_retry.rs b/crates/openhuman-core/src/integrations/composio/auth_retry.rs
deleted file mode 100644
index 766c0427b0..0000000000
--- a/crates/openhuman-core/src/integrations/composio/auth_retry.rs
+++ /dev/null
@@ -1,101 +0,0 @@
-//! Single-shot retry wrapper around [`ComposioClient::execute_tool_once`]
-//! for the post-OAuth token-propagation gap (issue #1688).
-//!
-//! NOTE: PR #1707 later added an in-client retry inside
-//! [`ComposioClient::execute_tool`] keyed on the same auth-readiness
-//! error string. To avoid stacking two retry layers (which would issue
-//! up to four backend calls per logical retry — see the
-//! `retries_once_only_even_when_second_call_still_errors` regression),
-//! this wrapper calls the non-retrying [`ComposioClient::execute_tool_once`]
-//! primitive instead. Direct callers of `execute_tool` (LinkedIn enrichment,
-//! tool schemas) still get #1707's inner retry.
-//!
-//! Composio reports `connection.status == ACTIVE` ~1-2s after the user
-//! finishes OAuth, but its action-execution gateway can take another
-//! 30-60s to sync the new token into its execution cache, run scope
-//! validation against the upstream provider, and step out of its
-//! first-use rate limit. During that window the gateway returns the
-//! literal string `"Connection error, try to authenticate"` for normal
-//! action calls — the connection is genuinely active and a second call
-//! seconds later succeeds.
-//!
-//! The retry here is intentionally narrow:
-//!
-//! * single re-attempt only, after a fixed short sleep
-//! * gated on a small constant list of well-known auth-error strings so
-//! a real revoked or mis-scoped connection still surfaces to the user
-//! after exactly one round-trip — never an infinite loop
-//! * only the payload-level `successful = false / error = "…"` shape is
-//! eligible; transport-level errors (HTTP non-2xx, bad envelope, connect
-//! failures) propagate unchanged because the upstream
-//! [`crate::integrations`] client already classifies and
-//! retries those separately.
-//!
-//! The wrapper calls the client's one-shot execution primitive instead of
-//! [`ComposioClient::execute_tool`] so this layer does not stack another
-//! two-attempt retry on top of the client's direct-call retry path.
-
-use std::time::Duration;
-
-use super::client::ComposioClient;
-use super::types::ComposioExecuteResponse;
-
-/// Backoff before the single retry. 8s sits in the middle of the 5-10s
-/// recommendation in issue #1688 — long enough for Composio's action
-/// gateway to sync the token, short enough that a genuine auth failure
-/// surfaces to the user well inside the orchestrator's per-turn budget.
-pub(crate) const AUTH_RETRY_BACKOFF: Duration = Duration::from_secs(8);
-
-/// Execute `slug` against the Composio gateway and, on a known
-/// post-OAuth auth-error payload, retry exactly once after
-/// [`AUTH_RETRY_BACKOFF`]. The second response is returned verbatim,
-/// even if it is itself an error — callers see exactly what the gateway
-/// produced.
-pub(crate) async fn execute_with_auth_retry(
- client: &ComposioClient,
- slug: &str,
- args: Option<serde_json::Value>,
-) -> anyhow::Result<ComposioExecuteResponse> {
- execute_with_auth_retry_inner(client, slug, args, AUTH_RETRY_BACKOFF, None).await
-}
-
-/// Test-visible inner form that takes an explicit backoff so unit tests
-/// can drive the retry path without sleeping for real seconds.
-pub(crate) async fn execute_with_auth_retry_inner(
- client: &ComposioClient,
- slug: &str,
- args: Option<serde_json::Value>,
- backoff: Duration,
- connection_id: Option<&str>,
-) -> anyhow::Result<ComposioExecuteResponse> {
- let tool = slug.trim();
- if tool.is_empty() {
- tracing::debug!(
- target: "composio",
- raw_slug_len = slug.len(),
- "[composio][auth_retry] rejecting empty tool slug"
- );
- anyhow::bail!("composio.execute_tool: tool slug must not be empty");
- }
- let arguments = args.unwrap_or(serde_json::Value::Object(Default::default()));
- let has_args = arguments.as_object().is_some_and(|a| !a.is_empty());
- let mut body = serde_json::json!({ "tool": tool, "arguments": arguments });
- if let Some(cid) = connection_id.map(str::trim).filter(|s| !s.is_empty()) {
- body["connectionId"] = serde_json::json!(cid);
- }
-
- tracing::debug!(
- target: "composio",
- slug = %tool,
- has_args,
- connection_id = ?connection_id,
- "[composio][auth_retry] execute start"
- );
- client
- .execute_tool_with_post_oauth_retry(tool, &body, backoff)
- .await
-}
-
-#[cfg(test)]
-#[path = "auth_retry_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/integrations/composio/auth_retry_tests.rs b/crates/openhuman-core/src/integrations/composio/auth_retry_tests.rs
deleted file mode 100644
index 187eba9b63..0000000000
--- a/crates/openhuman-core/src/integrations/composio/auth_retry_tests.rs
+++ /dev/null
@@ -1,266 +0,0 @@
-//! Tests for the post-OAuth auth-error retry in [`super`].
-//!
-//! These spin up a tiny axum backend that mimics Composio's
-//! `/agent-integrations/composio/execute` route. Each test wires a
-//! response sequence keyed by the request counter so we can assert
-//! exactly how many times the gateway was hit. The backoff between
-//! attempts is passed in as `Duration::from_millis(0)` so the suite
-//! never sleeps for real seconds.
-
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::Arc;
-use std::time::Duration;
-
-use axum::{routing::post, Json, Router};
-use serde_json::{json, Value};
-
-use super::*;
-use crate::integrations::IntegrationClient;
-
-async fn start_mock_backend(app: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- format!("http://127.0.0.1:{}", addr.port())
-}
-
-fn build_client_for(base_url: String) -> ComposioClient {
- let inner = Arc::new(IntegrationClient::new(base_url, "test-token".into()));
- ComposioClient::new(inner)
-}
-
-/// First call returns the post-OAuth auth-error payload; second call
-/// returns a normal success. Helper must hit the backend twice and
-/// surface the second response.
-#[tokio::test]
-async fn retries_once_on_post_oauth_auth_error_then_succeeds() {
- let counter = Arc::new(AtomicUsize::new(0));
- let counter_handler = counter.clone();
- let app = Router::new().route(
- "/agent-integrations/composio/execute",
- post(move |Json(_body): Json<Value>| {
- let counter = counter_handler.clone();
- async move {
- let n = counter.fetch_add(1, Ordering::SeqCst);
- if n == 0 {
- Json(json!({
- "success": true,
- "data": {
- "data": {},
- "successful": false,
- "error": "Connection error, try to authenticate",
- "costUsd": 0.0
- }
- }))
- } else {
- Json(json!({
- "success": true,
- "data": {
- "data": { "ok": true },
- "successful": true,
- "error": null,
- "costUsd": 0.0012
- }
- }))
- }
- }
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
-
- let resp = execute_with_auth_retry_inner(
- &client,
- "GOOGLECALENDAR_EVENTS_LIST",
- Some(json!({})),
- Duration::from_millis(0),
- None,
- )
- .await
- .expect("retry path must surface a response");
-
- assert!(resp.successful, "second attempt should report success");
- assert_eq!(resp.data["ok"], true);
- assert_eq!(
- counter.load(Ordering::SeqCst),
- 2,
- "gateway should be hit exactly twice"
- );
-}
-
-/// A real authentication failure (revoked token, mis-scoped connection,
-/// …) returns a 401-equivalent payload that does **not** match the
-/// post-OAuth gap string. The helper must surface it after exactly one
-/// attempt so the user sees the error without a needless 8s wait.
-#[tokio::test]
-async fn does_not_retry_on_unrelated_error_payload() {
- let counter = Arc::new(AtomicUsize::new(0));
- let counter_handler = counter.clone();
- let app = Router::new().route(
- "/agent-integrations/composio/execute",
- post(move |Json(_body): Json<Value>| {
- let counter = counter_handler.clone();
- async move {
- counter.fetch_add(1, Ordering::SeqCst);
- Json(json!({
- "success": true,
- "data": {
- "data": {},
- "successful": false,
- "error": "invalid_grant: refresh token revoked",
- "costUsd": 0.0
- }
- }))
- }
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
-
- let resp = execute_with_auth_retry_inner(
- &client,
- "GMAIL_SEND_EMAIL",
- Some(json!({"to": "[email protected]"})),
- Duration::from_millis(0),
- None,
- )
- .await
- .expect("non-retryable payload must still resolve cleanly");
-
- assert!(!resp.successful);
- assert_eq!(
- resp.error.as_deref(),
- Some("invalid_grant: refresh token revoked")
- );
- assert_eq!(
- counter.load(Ordering::SeqCst),
- 1,
- "non-retryable errors must not trigger a second attempt"
- );
-}
-
-/// Successful first attempt must short-circuit before the sleep — no
-/// retry, no wasted round-trip.
-#[tokio::test]
-async fn does_not_retry_on_first_attempt_success() {
- let counter = Arc::new(AtomicUsize::new(0));
- let counter_handler = counter.clone();
- let app = Router::new().route(
- "/agent-integrations/composio/execute",
- post(move |Json(_body): Json<Value>| {
- let counter = counter_handler.clone();
- async move {
- counter.fetch_add(1, Ordering::SeqCst);
- Json(json!({
- "success": true,
- "data": {
- "data": { "echoed": true },
- "successful": true,
- "error": null,
- "costUsd": 0.0
- }
- }))
- }
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
-
- let resp = execute_with_auth_retry_inner(
- &client,
- "GITHUB_GET_THE_AUTHENTICATED_USER",
- None,
- Duration::from_secs(60), // would hang the test if we ever slept
- None,
- )
- .await
- .unwrap();
-
- assert!(resp.successful);
- assert_eq!(counter.load(Ordering::SeqCst), 1);
-}
-
-/// If Composio still returns the auth-error payload on the second call
-/// (gateway not actually recovered, or real credential problem
-/// masquerading as the post-OAuth string), surface the second response
-/// verbatim — bounded retries, never a loop.
-///
-/// **NOTE on the gateway-hit count**: There are TWO retry layers stacked
-/// for this error shape today —
-///
-/// - This module (`auth_retry.rs`, added in #1708) wraps every composio
-/// tool call with one outer retry on `RETRYABLE_AUTH_ERRORS`.
-/// - `ComposioClient::execute_tool` (changed by #1707, merged
-/// independently) wraps every call with one inner retry on
-/// `is_post_oauth_auth_readiness_error`, which catches the same
-/// `"Connection error, try to authenticate"` string.
-///
-/// So an error that triggers BOTH classifiers fires 4 gateway hits
-/// (outer attempt 1: inner-retry → 2 hits, outer attempt 2: inner-retry
-/// → 2 hits). The user-visible contract — "bounded retries, never an
-/// infinite loop" — is preserved. The assertion below pins the compound
-/// count so a future fix that collapses the two layers surfaces here
-/// and the operator updates this test alongside the production change.
-///
-/// TODO(composio-retry-dedup): collapse the two retry layers — see
-/// `auth_retry.rs` doc-comment vs `client.rs::execute_tool_with_post_oauth_retry`.
-#[tokio::test]
-async fn retries_once_only_even_when_second_call_still_errors() {
- let counter = Arc::new(AtomicUsize::new(0));
- let counter_handler = counter.clone();
- let app = Router::new().route(
- "/agent-integrations/composio/execute",
- post(move |Json(_body): Json<Value>| {
- let counter = counter_handler.clone();
- async move {
- counter.fetch_add(1, Ordering::SeqCst);
- Json(json!({
- "success": true,
- "data": {
- "data": {},
- "successful": false,
- "error": "Connection error, try to authenticate",
- "costUsd": 0.0
- }
- }))
- }
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client_for(base);
-
- let resp = execute_with_auth_retry_inner(
- &client,
- "NOTION_PAGES_LIST",
- None,
- Duration::from_millis(0),
- None,
- )
- .await
- .unwrap();
-
- assert!(!resp.successful);
- assert_eq!(
- resp.error.as_deref(),
- Some("Connection error, try to authenticate")
- );
- // Bounded-retry contract: at least 2 hits (outer caught + retried once)
- // and at most 4 (outer × inner double-layer compound). Both extremes
- // surface in the field — local (macOS) consistently sees the inner
- // 10s sleep fire and counter == 4; CI (Linux nextest) sometimes
- // short-circuits the inner retry and counter == 2. Either way the
- // user-visible contract holds: never an infinite loop.
- //
- // TODO(composio-retry-dedup): collapse the two retry layers — see
- // `auth_retry.rs` doc-comment vs `client.rs::execute_tool_with_post_oauth_retry`.
- // Once collapsed, tighten this to `assert_eq!(counter, 2)`.
- let hits = counter.load(Ordering::SeqCst);
- assert!(
- (2..=4).contains(&hits),
- "compound retry must be bounded: got {hits} gateway hits, expected 2-4 \
- (2 = single-layer, 4 = outer auth_retry.rs #1708 × inner execute_tool_with_post_oauth_retry #1707). \
- A count outside this range means an unintended retry loop."
- );
-}
diff --git a/crates/openhuman-core/src/integrations/composio/execute_dispatch.rs b/crates/openhuman-core/src/integrations/composio/execute_dispatch.rs
index 477baff5f1..95a8f0ab65 100644
--- a/crates/openhuman-core/src/integrations/composio/execute_dispatch.rs
+++ b/crates/openhuman-core/src/integrations/composio/execute_dispatch.rs
@@ -1,28 +1,26 @@
-//! Shared Composio execute path: prepare args, retry policy, error mapping (#1797).
+//! Host entry for running one Composio action through the connector module.
+//!
+//! The prepare -> retry -> error-mapping pipeline (#1797) lives in the
+//! `tinyconnectors` module (`execute::execute_action`), which serves both the
+//! backend and direct routes. What stays here is the part the module
+//! deliberately leaves to the host: local-only egress enforcement and the
+//! external-transfer disclosure, applied once before the call.
-use std::time::Duration;
+use crate::config::Config;
+use crate::security::egress::{enforce_egress, emit_external_transfer, EgressDescriptor};
-use super::auth_retry::{execute_with_auth_retry_inner, AUTH_RETRY_BACKOFF};
-use super::client::{direct_execute, ComposioClient, ComposioClientKind};
-use super::error_mapping::{format_provider_error, remap_transport_error};
-use super::execute_prepare::prepare_execute_arguments;
-use super::types::ComposioExecuteResponse;
-
-const SLACK_HISTORY: &str = "SLACK_FETCH_CONVERSATION_HISTORY";
-const RATELIMIT_INITIAL_BACKOFF: Duration = Duration::from_secs(2);
-const RATELIMIT_MAX_BACKOFF: Duration = Duration::from_secs(30);
-const RATELIMIT_MAX_ATTEMPTS: u32 = 6;
+use super::module_client::{self, methods};
+use super::types::{ComposioExecuteRequest, ComposioExecuteResponse};
+/// Run `tool` against the ambient (or `connection_id`-pinned) account.
+///
+/// # Errors
+///
+/// Returns the message when the tool slug is empty, egress is refused by the
+/// local-only policy, or the module reports a transport failure. A provider
+/// refusal is `Ok` with `successful: false`.
pub async fn execute_composio_action(
- client: &ComposioClient,
- tool: &str,
- arguments: Option<serde_json::Value>,
-) -> Result<ComposioExecuteResponse, String> {
- execute_composio_action_with_connection(client, tool, arguments, None).await
-}
-
-pub async fn execute_composio_action_with_connection(
- client: &ComposioClient,
+ config: &Config,
tool: &str,
arguments: Option<serde_json::Value>,
connection_id: Option<&str>,
@@ -31,205 +29,31 @@ pub async fn execute_composio_action_with_connection(
if tool.is_empty() {
return Err("composio: tool slug must not be empty".to_string());
}
-
- let prepared = match prepare_execute_arguments(tool, arguments) {
- Ok(args) => args,
- Err(msg) => {
- tracing::debug!(
- tool = %tool,
- error = %msg,
- "[composio][prepare] local validation rejected execute"
- );
- return Err(format_provider_error(tool, &msg));
- }
- };
+ // Privacy epic S2/S7 (#4436, #4441): refuse under LocalOnly, otherwise
+ // disclose the transfer, before the arguments leave the device.
+ let egress = EgressDescriptor::composio(tool);
+ if let Err(e) = enforce_egress(&egress) {
+ tracing::debug!(tool = %tool, "[composio][dispatch] local-only egress block");
+ return Err(e.to_string());
+ }
+ emit_external_transfer(egress);
tracing::debug!(
tool = %tool,
connection_id = ?connection_id,
- "[composio][dispatch] execute_composio_action"
+ "[composio][dispatch] execute via connector module"
);
- let resp = match execute_with_retries(client, tool, prepared, connection_id).await {
- Ok(resp) => resp,
- Err(e) => {
- tracing::debug!(tool = %tool, "[composio][dispatch] transport failure");
- return Err(remap_transport_error(tool, &e.to_string()));
- }
- };
-
- if resp.successful {
- return Ok(resp);
- }
-
- let raw_err = resp
- .error
- .clone()
- .unwrap_or_else(|| "provider reported failure".to_string());
- Ok(ComposioExecuteResponse {
- error: Some(format_provider_error(tool, &raw_err)),
- ..resp
- })
-}
-
-async fn execute_with_retries(
- client: &ComposioClient,
- tool: &str,
- args: serde_json::Value,
- connection_id: Option<&str>,
-) -> anyhow::Result<ComposioExecuteResponse> {
- let mut delay = RATELIMIT_INITIAL_BACKOFF;
- for attempt in 1..=RATELIMIT_MAX_ATTEMPTS {
- let resp = execute_with_auth_retry_inner(
- client,
- tool,
- Some(args.clone()),
- if attempt == 1 {
- AUTH_RETRY_BACKOFF
- } else {
- Duration::ZERO
- },
- connection_id,
- )
- .await?;
-
- if resp.successful {
- return Ok(resp);
- }
-
- let err_text = resp.error.as_deref().unwrap_or("");
- // Only Slack's conversations.history is allow-listed for transparent
- // rate-limit retries today: it surfaces 429s on bursty agent reads and
- // has stable retry semantics. Other tools surface 429 to the caller
- // (formatted as `[composio:error:rate_limited]`) instead of stalling.
- if tool == SLACK_HISTORY && is_rate_limited(err_text) && attempt < RATELIMIT_MAX_ATTEMPTS {
- tracing::warn!(
- tool = %tool,
- attempt,
- max_attempts = RATELIMIT_MAX_ATTEMPTS,
- sleep_ms = delay.as_millis() as u64,
- "[composio][dispatch] upstream rate limit; backing off (#1797)"
- );
- tokio::time::sleep(delay).await;
- delay = (delay * 2).min(RATELIMIT_MAX_BACKOFF);
- continue;
- }
-
- return Ok(resp);
- }
- unreachable!("loop returns on final attempt");
+ module_client::call::<_, ComposioExecuteResponse>(
+ config,
+ methods::EXECUTE,
+ ComposioExecuteRequest {
+ tool: tool.to_string(),
+ arguments,
+ connection_id: connection_id
+ .map(str::trim)
+ .filter(|id| !id.is_empty())
+ .map(str::to_string),
+ },
+ )
+ .await
}
-
-fn is_rate_limited(err: &str) -> bool {
- let lower = err.to_ascii_lowercase();
- lower.contains("rate limit")
- || lower.contains("rate_limit")
- || lower.contains("ratelimited")
- || lower.contains("too many requests")
- || lower.contains("429")
-}
-
-/// Mode-aware variant: routes through the backend (with auth-retry +
-/// rate-limit backoff + error mapping) or the direct tenant client
-/// (no auth-retry, but local validation + error mapping still apply).
-///
-/// Added after #1710's mode-aware client split (`ComposioClientKind`) so
-/// the per-action tool surface, dispatcher tool, and RPC `composio_execute`
-/// op all share one entry point with consistent error semantics.
-pub async fn execute_composio_action_kind(
- kind: ComposioClientKind,
- tool: &str,
- arguments: Option<serde_json::Value>,
- entity_id: &str,
-) -> Result<ComposioExecuteResponse, String> {
- execute_composio_action_kind_with_connection(kind, tool, arguments, entity_id, None).await
-}
-
-pub async fn execute_composio_action_kind_with_connection(
- kind: ComposioClientKind,
- tool: &str,
- arguments: Option<serde_json::Value>,
- entity_id: &str,
- connection_id: Option<&str>,
-) -> Result<ComposioExecuteResponse, String> {
- let tool_trim = tool.trim();
- if tool_trim.is_empty() {
- return Err("composio: tool slug must not be empty".to_string());
- }
-
- // Local-only enforcement (privacy epic S7, #4441): gate ABOVE the
- // backend-vs-direct branch. The per-client gate lives inside
- // `ComposioClient::execute_tool{,_once}` and therefore only covers the
- // Backend arm — the Direct arm (`direct_execute`) never reaches it, so
- // without this a Composio tool call would still POST its arguments to
- // Composio under LocalOnly in direct mode (the dual-path drift this very
- // review flagged). A Composio execute ships the tool arguments off-device
- // in BOTH modes, so refuse here — once, before either dispatch — for a
- // single chokepoint. The Backend arm stays gated too (defense in depth).
- if let Err(e) = crate::security::egress::enforce_egress(
- &crate::security::egress::EgressDescriptor::composio(tool_trim),
- ) {
- tracing::debug!(tool = %tool_trim, "[composio][dispatch] local-only egress block");
- return Err(e.to_string());
- }
-
- let prepared = match prepare_execute_arguments(tool_trim, arguments) {
- Ok(args) => args,
- Err(msg) => {
- tracing::debug!(
- tool = %tool_trim,
- error = %msg,
- "[composio][prepare] local validation rejected execute"
- );
- return Err(format_provider_error(tool_trim, &msg));
- }
- };
-
- match kind {
- ComposioClientKind::Backend(client) => {
- tracing::debug!(
- tool = %tool_trim,
- connection_id = ?connection_id,
- "[composio][dispatch] backend variant"
- );
- let resp = match execute_with_retries(&client, tool_trim, prepared, connection_id).await
- {
- Ok(resp) => resp,
- Err(e) => {
- tracing::debug!(tool = %tool_trim, "[composio][dispatch] transport failure");
- return Err(remap_transport_error(tool_trim, &e.to_string()));
- }
- };
- Ok(format_response(tool_trim, resp))
- }
- ComposioClientKind::Direct(direct) => {
- tracing::debug!(
- tool = %tool_trim,
- connection_id = ?connection_id,
- "[composio][dispatch] direct variant"
- );
- match direct_execute(&direct, tool_trim, Some(prepared), entity_id, connection_id).await
- {
- Ok(resp) => Ok(format_response(tool_trim, resp)),
- Err(e) => Err(remap_transport_error(tool_trim, &e.to_string())),
- }
- }
- }
-}
-
-fn format_response(tool: &str, resp: ComposioExecuteResponse) -> ComposioExecuteResponse {
- if resp.successful {
- return resp;
- }
- let raw_err = resp
- .error
- .clone()
- .unwrap_or_else(|| "provider reported failure".to_string());
- ComposioExecuteResponse {
- error: Some(format_provider_error(tool, &raw_err)),
- ..resp
- }
-}
-
-#[cfg(test)]
-#[path = "execute_dispatch_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/integrations/composio/execute_dispatch_tests.rs b/crates/openhuman-core/src/integrations/composio/execute_dispatch_tests.rs
deleted file mode 100644
index 33211387de..0000000000
--- a/crates/openhuman-core/src/integrations/composio/execute_dispatch_tests.rs
+++ /dev/null
@@ -1,56 +0,0 @@
-use std::sync::atomic::{AtomicUsize, Ordering};
-use std::sync::Arc;
-
-use axum::{routing::post, Json, Router};
-use serde_json::json;
-
-use super::execute_composio_action;
-use crate::integrations::composio::client::ComposioClient;
-use crate::integrations::IntegrationClient;
-
-async fn start_mock_backend(app: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- // The spawned task is intentionally orphaned; it dies with the tokio
- // runtime when the test finishes. The previous oneshot-based graceful
- // shutdown was broken because the sender was dropped immediately,
- // signalling shutdown before the test could exercise the server.
- tokio::spawn(async move {
- let _ = axum::serve(listener, app).await;
- });
- format!("http://{addr}")
-}
-
-fn build_client(base: &str) -> ComposioClient {
- let inner = Arc::new(IntegrationClient::new(
- base.to_string(),
- "test-token".to_string(),
- ));
- ComposioClient::new(inner)
-}
-
-#[tokio::test]
-async fn local_validation_skips_network() {
- let attempts = Arc::new(AtomicUsize::new(0));
- let app = Router::new().route(
- "/agent-integrations/composio/execute",
- post({
- let attempts = attempts.clone();
- move || async move {
- attempts.fetch_add(1, Ordering::SeqCst);
- Json(json!({"success": true, "data": {"successful": true, "data": {}, "costUsd": 0.0}}))
- }
- }),
- );
- let base = start_mock_backend(app).await;
- let client = build_client(&base);
- let err = execute_composio_action(
- &client,
- "GMAIL_SEND_EMAIL",
- Some(json!({ "subject": "hello" })),
- )
- .await
- .unwrap_err();
- assert!(err.contains("[composio:error:"));
- assert_eq!(attempts.load(Ordering::SeqCst), 0);
-}
diff --git a/crates/openhuman-core/src/integrations/composio/oauth_handoff.rs b/crates/openhuman-core/src/integrations/composio/oauth_handoff.rs
deleted file mode 100644
index d74a23df84..0000000000
--- a/crates/openhuman-core/src/integrations/composio/oauth_handoff.rs
+++ /dev/null
@@ -1,190 +0,0 @@
-//! OAuth handoff helpers — Meta (Instagram / Facebook) rate-limit mitigations (#1952).
-//!
-//! Meta's OAuth authorize endpoint returns HTTP 429 when too many OAuth sessions
-//! are created in a short window. That often happens when a user retries after a
-//! failed handoff or clicks Connect multiple times, leaving several `PENDING`
-//! Composio rows that each redirect through Meta. Before starting a new handoff
-//! for Meta-owned toolkits we clear prior non-active connection rows and apply
-//! a small backoff retry when the backend reports a 429-shaped failure.
-
-use std::time::Duration;
-
-use super::client::{direct_authorize, ComposioClient};
-use super::types::ComposioAuthorizeResponse;
-
-/// Toolkits whose OAuth flows are hosted by Meta and share the same rate limits.
-pub const META_OAUTH_TOOLKITS: &[&str] = &["instagram", "facebook"];
-
-const AUTHORIZE_RATE_LIMIT_MAX_ATTEMPTS: u32 = 3;
-const AUTHORIZE_RATE_LIMIT_INITIAL_BACKOFF: Duration = Duration::from_secs(5);
-const AUTHORIZE_RATE_LIMIT_MAX_BACKOFF: Duration = Duration::from_secs(60);
-
-/// Return true when `toolkit` uses Meta-hosted OAuth (Instagram / Facebook).
-pub fn is_meta_oauth_toolkit(toolkit: &str) -> bool {
- let key = toolkit.trim().to_ascii_lowercase();
- META_OAUTH_TOOLKITS.contains(&key.as_str())
-}
-
-/// Status values that mean an OAuth handoff is still in flight.
-pub fn is_inflight_oauth_status(status: &str) -> bool {
- matches!(
- status.trim().to_ascii_uppercase().as_str(),
- "PENDING" | "INITIATED" | "INITIALIZING"
- )
-}
-
-/// Non-active rows safe to delete before starting a fresh Meta OAuth handoff.
-pub fn is_clearable_oauth_status(status: &str) -> bool {
- let upper = status.trim().to_ascii_uppercase();
- is_inflight_oauth_status(status) || matches!(upper.as_str(), "FAILED" | "ERROR" | "EXPIRED")
-}
-
-/// Detect authorize-path failures that look like upstream rate limiting.
-pub fn is_authorize_rate_limited(err: &str) -> bool {
- let lower = err.to_ascii_lowercase();
- lower.contains("429")
- || lower.contains("too many requests")
- || lower.contains("rate limit")
- || lower.contains("rate_limit")
- || lower.contains("ratelimited")
-}
-
-/// User-facing hint when Meta OAuth is rate-limited.
-pub fn meta_oauth_rate_limit_message(toolkit: &str) -> String {
- let name = toolkit.trim();
- let account_hint = if name.eq_ignore_ascii_case("instagram") {
- " Use an Instagram Business or Creator account — personal accounts are not supported."
- } else if name.eq_ignore_ascii_case("facebook") {
- " Confirm the Facebook account has access to the relevant Page or Business Manager."
- } else {
- ""
- };
- format!(
- "Meta is temporarily rate-limiting {name} sign-in (HTTP 429). Wait a few \
- minutes before retrying and avoid clicking Connect repeatedly.{account_hint}"
- )
-}
-
-/// If `err` is a Meta-toolkit authorize rate limit, replace it with guidance.
-pub fn wrap_authorize_rate_limit_error(toolkit: &str, err: anyhow::Error) -> anyhow::Error {
- let rendered = format!("{err:#}");
- if is_meta_oauth_toolkit(toolkit) && is_authorize_rate_limited(&rendered) {
- anyhow::anyhow!("{}", meta_oauth_rate_limit_message(toolkit))
- } else {
- err
- }
-}
-
-/// Remove non-active connection rows for `toolkit` so a fresh OAuth handoff does
-/// not accumulate Meta sessions (#1952).
-pub async fn clear_non_active_connections(
- client: &ComposioClient,
- toolkit: &str,
-) -> anyhow::Result<u32> {
- if !is_meta_oauth_toolkit(toolkit) {
- return Ok(0);
- }
- let toolkit_key = toolkit.trim().to_ascii_lowercase();
- let resp = client.list_connections().await?;
- let mut cleared = 0u32;
- for conn in resp.connections {
- if conn.normalized_toolkit() != toolkit_key {
- continue;
- }
- if conn.is_active() || !is_clearable_oauth_status(&conn.status) {
- continue;
- }
- tracing::info!(
- toolkit = %toolkit_key,
- connection_id = %conn.id,
- status = %conn.status,
- "[composio][oauth] clearing stale non-active connection before Meta OAuth handoff (#1952)"
- );
- match client.delete_connection(&conn.id).await {
- Ok(_) => cleared += 1,
- Err(e) => {
- tracing::warn!(
- toolkit = %toolkit_key,
- connection_id = %conn.id,
- error = %e,
- "[composio][oauth] failed to clear stale connection (non-fatal)"
- );
- }
- }
- }
- Ok(cleared)
-}
-
-/// Begin a backend-proxied OAuth handoff with Meta cleanup + 429 backoff.
-pub async fn authorize_with_meta_guard(
- client: &ComposioClient,
- toolkit: &str,
- extra_params: Option<serde_json::Value>,
-) -> anyhow::Result<ComposioAuthorizeResponse> {
- let cleared = match clear_non_active_connections(client, toolkit).await {
- Ok(cleared) => cleared,
- Err(e) => {
- tracing::warn!(
- toolkit = %toolkit,
- error = %e,
- "[composio][oauth] pre-handoff cleanup failed; continuing authorize"
- );
- 0
- }
- };
- tracing::debug!(
- toolkit = %toolkit,
- cleared,
- is_meta = is_meta_oauth_toolkit(toolkit),
- "[composio][oauth] authorize_with_meta_guard: pre-handoff cleanup"
- );
- authorize_with_rate_limit_retry(|| client.authorize(toolkit, extra_params.clone())).await
-}
-
-/// Direct-mode authorize with the same 429 backoff used for Meta toolkits.
-pub async fn direct_authorize_with_meta_guard(
- direct: &std::sync::Arc<crate::tools::ComposioTool>,
- toolkit: &str,
- entity_id: &str,
-) -> anyhow::Result<ComposioAuthorizeResponse> {
- authorize_with_rate_limit_retry(|| direct_authorize(direct, toolkit, entity_id)).await
-}
-
-async fn authorize_with_rate_limit_retry<F, Fut>(
- mut attempt_authorize: F,
-) -> anyhow::Result<ComposioAuthorizeResponse>
-where
- F: FnMut() -> Fut,
- Fut: std::future::Future<Output = anyhow::Result<ComposioAuthorizeResponse>>,
-{
- let mut delay = AUTHORIZE_RATE_LIMIT_INITIAL_BACKOFF;
- let mut last_err: Option<anyhow::Error> = None;
- for attempt in 1..=AUTHORIZE_RATE_LIMIT_MAX_ATTEMPTS {
- match attempt_authorize().await {
- Ok(resp) => return Ok(resp),
- Err(e) => {
- let rendered = format!("{e:#}");
- if is_authorize_rate_limited(&rendered)
- && attempt < AUTHORIZE_RATE_LIMIT_MAX_ATTEMPTS
- {
- tracing::warn!(
- attempt,
- max_attempts = AUTHORIZE_RATE_LIMIT_MAX_ATTEMPTS,
- sleep_secs = delay.as_secs(),
- "[composio][oauth] authorize rate-limited; backing off (#1952)"
- );
- tokio::time::sleep(delay).await;
- delay = (delay * 2).min(AUTHORIZE_RATE_LIMIT_MAX_BACKOFF);
- last_err = Some(e);
- continue;
- }
- return Err(e);
- }
- }
- }
- Err(last_err.unwrap_or_else(|| anyhow::anyhow!("authorize failed after retries")))
-}
-
-#[cfg(test)]
-#[path = "oauth_handoff_tests.rs"]
-mod tests;
diff --git a/crates/openhuman-core/src/integrations/composio/oauth_handoff_tests.rs b/crates/openhuman-core/src/integrations/composio/oauth_handoff_tests.rs
deleted file mode 100644
index 9c88d43246..0000000000
--- a/crates/openhuman-core/src/integrations/composio/oauth_handoff_tests.rs
+++ /dev/null
@@ -1,128 +0,0 @@
-//! Tests for Meta OAuth handoff helpers (#1952).
-
-use super::{
- authorize_with_meta_guard, is_authorize_rate_limited, is_clearable_oauth_status,
- is_inflight_oauth_status, is_meta_oauth_toolkit, meta_oauth_rate_limit_message,
- wrap_authorize_rate_limit_error,
-};
-use axum::{
- http::StatusCode,
- routing::{get, post},
- Json, Router,
-};
-use serde_json::{json, Value};
-use std::sync::Arc;
-
-use super::ComposioClient;
-
-async fn start_mock_backend(app: Router) -> String {
- let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
- let addr = listener.local_addr().unwrap();
- tokio::spawn(async move {
- axum::serve(listener, app).await.unwrap();
- });
- format!("http://127.0.0.1:{}", addr.port())
-}
-
-fn build_client_for(base_url: String) -> ComposioClient {
- let inner = Arc::new(crate::integrations::IntegrationClient::new(
- base_url,
- "test-token".into(),
- ));
- ComposioClient::new(inner)
-}
-
-#[test]
-fn meta_oauth_toolkit_detection() {
- assert!(is_meta_oauth_toolkit("instagram"));
- assert!(is_meta_oauth_toolkit("Facebook"));
- assert!(!is_meta_oauth_toolkit("gmail"));
-}
-
-#[test]
-fn inflight_and_clearable_statuses() {
- assert!(is_inflight_oauth_status("pending"));
- assert!(is_inflight_oauth_status("INITIATED"));
- assert!(!is_inflight_oauth_status("ACTIVE"));
-
- assert!(is_clearable_oauth_status("FAILED"));
- assert!(is_clearable_oauth_status("EXPIRED"));
- assert!(!is_clearable_oauth_status("ACTIVE"));
-}
-
-#[test]
-fn authorize_rate_limit_shape_detection() {
- assert!(is_authorize_rate_limited(
- "Backend returned 429 Too Many Requests"
- ));
- assert!(is_authorize_rate_limited("rate_limit exceeded"));
- assert!(!is_authorize_rate_limited("401 Unauthorized"));
-}
-
-#[test]
-fn wrap_authorize_rate_limit_error_replaces_meta_toolkit_message() {
- let err = anyhow::anyhow!("Backend returned 429 Too Many Requests");
- let wrapped = wrap_authorize_rate_limit_error("instagram", err);
- let msg = format!("{wrapped:#}");
- assert!(msg.contains("Business or Creator"));
- assert!(msg.contains("429"));
-}
-
-#[test]
-fn wrap_authorize_rate_limit_error_passthrough_for_non_meta() {
- let err = anyhow::anyhow!("Backend returned 429 Too Many Requests");
- let wrapped = wrap_authorize_rate_limit_error("gmail", err);
- assert!(format!("{wrapped:#}").contains("Backend returned 429"));
-}
-
-#[test]
-fn meta_oauth_rate_limit_message_mentions_business_account() {
- let msg = meta_oauth_rate_limit_message("instagram");
- assert!(msg.to_ascii_lowercase().contains("business"));
-}
-
-#[test]
-fn meta_oauth_rate_limit_message_uses_facebook_specific_guidance() {
- let msg = meta_oauth_rate_limit_message("facebook");
- assert!(msg.contains("Facebook"));
- assert!(msg.contains("Business Manager"));
- assert!(!msg.contains("Instagram Business or Creator"));
-}
-
-#[tokio::test]
-async fn authorize_continues_when_pre_handoff_cleanup_fails() {
- let app = Router::new()
- .route(
- "/agent-integrations/composio/connections",
- get(|| async {
- (
- StatusCode::INTERNAL_SERVER_ERROR,
- Json(json!({
- "success": false,
- "error": "temporary list failure"
- })),
- )
- }),
- )
- .route(
- "/agent-integrations/composio/authorize",
- post(|Json(body): Json<Value>| async move {
- assert_eq!(body["toolkit"].as_str(), Some("instagram"));
- Json(json!({
- "success": true,
- "data": {
- "connectUrl": "https://composio.example/instagram/consent",
- "connectionId": "conn-instagram"
- }
- }))
- }),
- );
- let client = build_client_for(start_mock_backend(app).await);
-
- let resp = authorize_with_meta_guard(&client, "instagram", None)
- .await
- .expect("authorize should continue when cleanup is unavailable");
-
- assert_eq!(resp.connection_id, "conn-instagram");
- assert!(resp.connect_url.contains("instagram"));
-}