Skip to content

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

chore(composio): remove unused direct-mode tool implementation

Steven Enamakelf6af33bd5945
diff --git a/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs
new file mode 100644
index 0000000000..b956b7e34e
--- /dev/null
+++ b/crates/openhuman-core/src/agent/orchestration/spawn_parallel_graph/collect.rs
@@ -0,0 +1,222 @@
+//! Collecting fanned-out worker results into the tool's final shape: overlap
+//! detection, stale-parent-read annotation, progress projection for
+//! completed/failed workers, and the outcome enum the graph run resolves to.
+
+use std::path::PathBuf;
+
+use serde_json::json;
+use tokio::sync::mpsc::Sender;
+
+use crate::agent::file_state;
+use crate::agent::progress::AgentProgress;
+
+use super::request::SpawnParallelTaskValidationError;
+use super::types::ParallelAgentResult;
+
+#[derive(Clone)]
+pub(crate) struct SpawnParallelCollected {
+ pub(crate) results: Vec<ParallelAgentResult>,
+ pub(crate) failures: usize,
+ pub(crate) overlap_warnings: Vec<serde_json::Value>,
+}
+
+pub(crate) enum SpawnParallelGraphOutcome {
+ Collected(SpawnParallelCollected),
+ InvalidRequest(SpawnParallelTaskValidationError),
+ Rejected(String),
+ Cancelled(String),
+}
+
+impl SpawnParallelCollected {
+ pub(crate) fn total(&self) -> usize {
+ self.results.len()
+ }
+
+ pub(crate) fn succeeded(&self) -> usize {
+ self.results.len().saturating_sub(self.failures)
+ }
+}
+
+pub(crate) fn collect_spawn_parallel_results(
+ parent_session: &str,
+ mut results: Vec<ParallelAgentResult>,
+) -> SpawnParallelCollected {
+ annotate_stale_parent_reads(&mut results);
+ let overlap_warnings = overlap_warnings_for_results(parent_session, &results);
+ let failures = results.iter().filter(|r| !r.success).count();
+ SpawnParallelCollected {
+ results,
+ failures,
+ overlap_warnings,
+ }
+}
+
+pub(crate) fn format_spawn_parallel_success(collected: &SpawnParallelCollected) -> String {
+ serde_json::to_string_pretty(&json!({
+ "parallel_agents": {
+ "total": collected.total(),
+ "succeeded": collected.succeeded(),
+ "failed": collected.failures,
+ "results": collected.results,
+ "overlap_warnings": collected.overlap_warnings,
+ }
+ }))
+ .unwrap_or_else(|_| "{}".to_string())
+}
+
+pub(crate) async fn project_spawn_parallel_result(
+ parent_session: &str,
+ progress_sink: Option<&Sender<AgentProgress>>,
+ result: &ParallelAgentResult,
+) {
+ match result {
+ ParallelAgentResult {
+ success: true,
+ agent_id,
+ task_id,
+ elapsed_ms,
+ iterations,
+ output,
+ worktree_path,
+ changed_files,
+ dirty_status,
+ ..
+ } => {
+ tracing::debug!(
+ parent_session = %parent_session,
+ task_id = %task_id,
+ agent_id = %agent_id,
+ elapsed_ms = *elapsed_ms,
+ iterations = *iterations,
+ "[spawn_parallel_agents] publishing_subagent_completed"
+ );
+ crate::agent::orchestration::subagent_events::publish_subagent_completed(
+ parent_session.to_string(),
+ task_id.clone(),
+ agent_id.clone(),
+ *elapsed_ms,
+ output.as_ref().map(|s| s.chars().count()).unwrap_or(0),
+ *iterations as usize,
+ );
+ if let Some(tx) = progress_sink {
+ if let Err(err) = tx
+ .send(AgentProgress::SubagentCompleted {
+ agent_id: agent_id.clone(),
+ task_id: task_id.clone(),
+ elapsed_ms: *elapsed_ms,
+ iterations: *iterations,
+ output_chars: output.as_ref().map(|s| s.chars().count()).unwrap_or(0),
+ output: output.clone().unwrap_or_default(),
+ worktree_path: worktree_path.clone(),
+ changed_files: changed_files.clone(),
+ dirty_status: *dirty_status,
+ })
+ .await
+ {
+ tracing::debug!(
+ parent_session = %parent_session,
+ task_id = %task_id,
+ agent_id = %agent_id,
+ error = %err,
+ "[spawn_parallel_agents] progress_send_failed completed"
+ );
+ }
+ }
+ }
+ ParallelAgentResult {
+ success: false,
+ agent_id,
+ task_id,
+ error,
+ ..
+ } => {
+ let message = error
+ .clone()
+ .unwrap_or_else(|| "unknown failure".to_string());
+ tracing::debug!(
+ parent_session = %parent_session,
+ task_id = %task_id,
+ agent_id = %agent_id,
+ error = %message,
+ "[spawn_parallel_agents] publishing_subagent_failed"
+ );
+ crate::agent::orchestration::subagent_events::publish_subagent_failed(
+ parent_session.to_string(),
+ task_id.clone(),
+ agent_id.clone(),
+ message.clone(),
+ );
+ if let Some(tx) = progress_sink {
+ if let Err(err) = tx
+ .send(AgentProgress::SubagentFailed {
+ agent_id: agent_id.clone(),
+ task_id: task_id.clone(),
+ error: message,
+ })
+ .await
+ {
+ tracing::debug!(
+ parent_session = %parent_session,
+ task_id = %task_id,
+ agent_id = %agent_id,
+ error = %err,
+ "[spawn_parallel_agents] progress_send_failed failed"
+ );
+ }
+ }
+ }
+ }
+}
+
+fn annotate_stale_parent_reads(results: &mut [ParallelAgentResult]) {
+ if let Some(parent_agent_id) = file_state::current_file_state_agent_id() {
+ let child_ids: Vec<String> = results.iter().map(|r| r.task_id.clone()).collect();
+ let stale = file_state::parent_stale_files(&parent_agent_id, &child_ids);
+ if !stale.is_empty() {
+ let stale_strings: Vec<String> =
+ stale.iter().map(|p| p.display().to_string()).collect();
+ tracing::debug!(
+ parent = %parent_agent_id,
+ stale_count = stale.len(),
+ "[file_state] parent reads stale after child writes"
+ );
+ for result in results {
+ result.stale_parent_reads = stale_strings.clone();
+ }
+ }
+ }
+}
+
+fn overlap_warnings_for_results(
+ parent_session: &str,
+ results: &[ParallelAgentResult],
+) -> Vec<serde_json::Value> {
+ let per_worker: Vec<(String, Vec<PathBuf>)> = results
+ .iter()
+ .filter(|r| !r.changed_files.is_empty())
+ .map(|r| {
+ (
+ r.task_id.clone(),
+ r.changed_files.iter().map(PathBuf::from).collect(),
+ )
+ })
+ .collect();
+ let overlaps = crate::agent::orchestration::worktree::detect_overlaps(&per_worker);
+ let overlap_warnings: Vec<serde_json::Value> = overlaps
+ .iter()
+ .map(|(file, workers)| {
+ json!({
+ "file": file.to_string_lossy(),
+ "workers": workers,
+ })
+ })
+ .collect();
+ if !overlap_warnings.is_empty() {
+ tracing::warn!(
+ parent_session = %parent_session,
+ overlap_count = overlap_warnings.len(),
+ "[spawn_parallel_agents] detected overlapping changed files across workers"
+ );
+ }
+ overlap_warnings
+}
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct_part_01.rs b/crates/openhuman-core/src/integrations/composio/tools/direct_part_01.rs
deleted file mode 100644
index 233aee8fce..0000000000
--- a/crates/openhuman-core/src/integrations/composio/tools/direct_part_01.rs
+++ /dev/null
@@ -1,74 +0,0 @@
-// Composio Tool Provider — optional managed tool surface with 1000+ OAuth integrations.
-//
-// When enabled, OpenHuman can execute actions on Gmail, Notion, GitHub, Slack, etc.
-// through Composio's API without storing raw OAuth tokens locally.
-//
-// This is opt-in. Users who prefer sovereign/local-only mode skip this entirely.
-// The Composio API key is stored in the encrypted secret store.
-
-use crate::security::policy::ToolOperation;
-use crate::security::SecurityPolicy;
-use crate::tools::traits::{Tool, ToolCategory, ToolResult};
-use anyhow::Context;
-use async_trait::async_trait;
-use reqwest::Client;
-use serde::{Deserialize, Serialize};
-use serde_json::json;
-use std::sync::Arc;
-
-const COMPOSIO_API_BASE_V2: &str = "https://backend.composio.dev/api/v2";
-const COMPOSIO_API_BASE_V3: &str = "https://backend.composio.dev/api/v3";
-
-fn ensure_https(url: &str) -> anyhow::Result<()> {
- if !url.starts_with("https://") {
- anyhow::bail!(
- "Refusing to transmit sensitive data over non-HTTPS URL: URL scheme must be https"
- );
- }
- Ok(())
-}
-
-fn is_loopback_http_url(url: &str) -> bool {
- // Parse rather than prefix-match: a raw `starts_with("http://127.0.0.1:")`
- // is fooled by userinfo smuggling like
- // `http://127.0.0.1:[email protected]/api/v3/tools`, which reqwest routes to the
- // *parsed* host (`evil.com`). Verify the actual scheme + host and reject any
- // embedded credentials so the insecure-loopback path can never leak the
- // `x-api-key` header to a non-loopback host.
- let Ok(parsed) = url::Url::parse(url) else {
- return false;
- };
- if parsed.scheme() != "http" {
- return false;
- }
- if !parsed.username().is_empty() || parsed.password().is_some() {
- return false;
- }
- match parsed.host() {
- Some(url::Host::Domain(host)) => host.eq_ignore_ascii_case("localhost"),
- Some(url::Host::Ipv4(ip)) => ip.is_loopback(),
- Some(url::Host::Ipv6(ip)) => ip.is_loopback(),
- None => false,
- }
-}
-
-#[cfg(debug_assertions)]
-fn is_loopback_http_base(url: &str) -> bool {
- is_loopback_http_url(&format!("{}/", url.trim_end_matches('/')))
-}
-
-/// A tool that proxies actions to the Composio managed tool platform.
-pub struct ComposioTool {
- api_key: String,
- default_entity_id: String,
- security: Arc<SecurityPolicy>,
- base_v2: String,
- /// Base URL for Composio v3 endpoints (`{base}/tools`). Production
- /// always uses [`COMPOSIO_API_BASE_V3`] via [`Self::new`]; the
- /// `#[cfg(test)]` `new_with_v3_base` constructor lets unit tests point
- /// the direct-mode `/tools` listing at a local axum mock — the same
- /// base-URL injection the backend `ComposioClient` gets through
- /// `IntegrationClient::new` in `client_tests.rs`.
- base_v3: String,
- allow_insecure_loopback: bool,
-}
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct_part_02.rs b/crates/openhuman-core/src/integrations/composio/tools/direct_part_02.rs
deleted file mode 100644
index 854bff4015..0000000000
--- a/crates/openhuman-core/src/integrations/composio/tools/direct_part_02.rs
+++ /dev/null
@@ -1,629 +0,0 @@
-
-impl ComposioTool {
- pub fn new(
- api_key: &str,
- default_entity_id: Option<&str>,
- security: Arc<SecurityPolicy>,
- ) -> Self {
- // Production always pins the real HTTPS endpoints.
- Self::new_internal(
- api_key,
- default_entity_id,
- security,
- COMPOSIO_API_BASE_V2.to_string(),
- COMPOSIO_API_BASE_V3.to_string(),
- false,
- )
- }
-
- pub(crate) fn auth_key_fingerprint(&self) -> u64 {
- crate::integrations::composio::direct_auth::fingerprint_api_key(&self.api_key)
- }
-
- /// Debug-test seam for raw integration coverage: construct a direct
- /// Composio tool against explicit v2/v3 base URLs. Non-HTTPS URLs are
- /// accepted only for loopback hosts and only in debug builds.
- #[cfg(debug_assertions)]
- pub fn new_with_base_urls_for_loopback(
- api_key: &str,
- default_entity_id: Option<&str>,
- security: Arc<SecurityPolicy>,
- base_v2: String,
- base_v3: String,
- ) -> anyhow::Result<Self> {
- for base in [&base_v2, &base_v3] {
- if !base.starts_with("https://") && !is_loopback_http_base(base) {
- anyhow::bail!("debug Composio base URL must be HTTPS or loopback HTTP");
- }
- }
- Ok(Self::new_internal(
- api_key,
- default_entity_id,
- security,
- base_v2,
- base_v3,
- true,
- ))
- }
-
- /// Test-only seam: construct with an explicit Composio v3 base URL so
- /// unit tests can point the direct `/tools` request — including the
- /// `tags` filter — at a local mock instead of `backend.composio.dev`.
- ///
- /// `#[cfg(test)]`-gated on purpose: `list_tool_schemas_v3` attaches the
- /// `x-api-key` header to whatever `base_v3` holds, so the only way to
- /// reach the v3 endpoint in production is [`Self::new`], which always
- /// uses the HTTPS [`COMPOSIO_API_BASE_V3`] const. An injectable base must
- /// never carry a non-HTTPS URL outside tests.
- #[cfg(test)]
- pub(crate) fn new_with_v3_base(
- api_key: &str,
- default_entity_id: Option<&str>,
- security: Arc<SecurityPolicy>,
- base_v3: String,
- ) -> Self {
- Self::new_internal(
- api_key,
- default_entity_id,
- security,
- COMPOSIO_API_BASE_V2.to_string(),
- base_v3,
- true,
- )
- }
-
- /// Shared constructor body. Private so the injectable `base_v3` cannot be
- /// supplied by production callers — they go through [`Self::new`] (real
- /// HTTPS const) and tests through the `#[cfg(test)]` `new_with_v3_base`.
- fn new_internal(
- api_key: &str,
- default_entity_id: Option<&str>,
- security: Arc<SecurityPolicy>,
- base_v2: String,
- base_v3: String,
- allow_insecure_loopback: bool,
- ) -> Self {
- let trimmed = api_key.trim();
- if trimmed.len() != api_key.len() {
- // The key carried leading/trailing whitespace that would otherwise
- // reach Composio's `x-api-key` header verbatim and trip the
- // server-side "Invalid API key format" 401 (Sentry TAURI-RUST-D3).
- // We trim here so the request succeeds; logging the length delta
- // (never the key itself) helps trace which credential source
- // produced a dirty value without leaking the secret.
- tracing::debug!(
- original_len = api_key.len(),
- trimmed_len = trimmed.len(),
- "[composio] trimmed leading/trailing whitespace from api_key"
- );
- }
- Self {
- api_key: trimmed.to_string(),
- default_entity_id: normalize_entity_id(default_entity_id.unwrap_or("default")),
- security,
- base_v2,
- base_v3,
- allow_insecure_loopback,
- }
- }
-
- fn client(&self) -> Client {
- crate::config::build_runtime_proxy_client_with_timeouts("tool.composio", 60, 10)
- }
-
- fn ensure_request_url(&self, url: &str) -> anyhow::Result<()> {
- if self.allow_insecure_loopback && is_loopback_http_url(url) {
- return Ok(());
- }
- ensure_https(url)
- }
-
- /// List available Composio apps/actions for the authenticated user.
- ///
- /// Uses v3 endpoint first and falls back to v2 for compatibility.
- pub async fn list_actions(
- &self,
- app_name: Option<&str>,
- ) -> anyhow::Result<Vec<ComposioAction>> {
- match self.list_actions_v3(app_name).await {
- Ok(items) => Ok(items),
- Err(v3_err) => {
- let v2 = self.list_actions_v2(app_name).await;
- match v2 {
- Ok(items) => Ok(items),
- Err(v2_err) => anyhow::bail!(
- "Composio action listing failed on v3 ({v3_err}) and v2 fallback ({v2_err})"
- ),
- }
- }
- }
- }
-
- async fn list_actions_v3(&self, app_name: Option<&str>) -> anyhow::Result<Vec<ComposioAction>> {
- let url = format!("{}/tools", self.base_v3);
- let mut req = self.client().get(&url).header("x-api-key", &self.api_key);
-
- // #3932: pin toolkit_versions=latest. Composio v3 otherwise defaults to
- // the 00000000_00 snapshot, which lists zero tools for any toolkit
- // published after it (Outlook and every other post-launch toolkit).
- req = req.query(&[("limit", "200"), ("toolkit_versions", "latest")]);
- if let Some(app) = app_name.map(str::trim).filter(|app| !app.is_empty()) {
- req = req.query(&[("toolkits", app), ("toolkit_slug", app)]);
- }
-
- let resp = req.send().await?;
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v3 API error: {err}");
- }
-
- let body: ComposioToolsResponse = resp
- .json()
- .await
- .context("Failed to decode Composio v3 tools response")?;
- Ok(map_v3_tools_to_actions(body.items))
- }
-
- async fn list_actions_v2(&self, app_name: Option<&str>) -> anyhow::Result<Vec<ComposioAction>> {
- let mut url = format!("{}/actions", self.base_v2);
- if let Some(app) = app_name {
- url = format!("{url}?appNames={app}");
- }
-
- let resp = self
- .client()
- .get(&url)
- .header("x-api-key", &self.api_key)
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v2 API error: {err}");
- }
-
- let body: ComposioActionsResponse = resp
- .json()
- .await
- .context("Failed to decode Composio v2 actions response")?;
- Ok(body.items)
- }
-
- /// Build the query-parameter pairs for the Composio v3 `GET /tools`
- /// listing used by [`Self::list_tool_schemas_v3`].
- ///
- /// `toolkits` is sent as a single comma-joined `toolkits=` param (the
- /// legacy plural the v3 backend tolerates; cf. `list_actions_v3` which
- /// sends both the plural and `toolkit_slug` singular forms). `tags` is
- /// encoded as **repeated** `tags=` params (`tags=a&tags=b`) — the shape
- /// Composio v3 `/tools` documents for tag filtering ("can be specified
- /// multiple times"), NOT the comma-joined form the backend proxy uses.
- /// Blank entries are trimmed and dropped; an empty `tags` slice yields
- /// no `tags` params (treated as no filter).
- ///
- /// Pure (no I/O) so the param shape is unit-testable without a live
- /// HTTP round trip — mirrors [`Self::build_execute_action_v3_request`].
- fn build_list_tool_schemas_v3_query(
- toolkits: &[&str],
- tags: Option<&[&str]>,
- ) -> Vec<(&'static str, String)> {
- // #3932: pin toolkit_versions=latest. Without it Composio v3 defaults to
- // the 00000000_00 snapshot, which lists zero tools for any toolkit
- // published after it (Outlook and every other post-launch toolkit).
- let mut params: Vec<(&'static str, String)> = vec![
- ("limit", "200".to_string()),
- ("toolkit_versions", "latest".to_string()),
- ];
-
- let trimmed: Vec<&str> = toolkits
- .iter()
- .map(|t| t.trim())
- .filter(|t| !t.is_empty())
- .collect();
- if !trimmed.is_empty() {
- params.push(("toolkits", trimmed.join(",")));
- }
-
- if let Some(tags) = tags {
- for tag in tags.iter().map(|t| t.trim()).filter(|t| !t.is_empty()) {
- params.push(("tags", tag.to_string()));
- }
- }
-
- params
- }
-
- /// List v3 tool definitions for one or more toolkits, preserving the
- /// raw `input_parameters` JSON schema each action carries.
- ///
- /// Sibling of [`Self::list_actions`] but kept distinct because
- /// `list_actions` flattens to `Vec<ComposioAction>` (no parameters)
- /// for the legacy agent-discovery shape, whereas
- /// `composio_list_tools`'s direct-mode branch needs the full schema
- /// so the LLM agent can supply valid arguments without a separate
- /// round trip.
- ///
- /// `toolkits` may contain one or many slugs; when non-empty they are
- /// sent as a comma-separated `toolkits=` filter to constrain the v3
- /// catalogue scan. Empty filter returns every action across every
- /// toolkit on the user's tenant (potentially large; callers should
- /// pass a non-empty filter in practice).
- ///
- /// `tags` narrows the result by Composio action tag (OR semantics —
- /// multiple tags broaden the result). This is the direct-mode (BYO
- /// key) counterpart to the backend proxy's `tags` query param wired
- /// in [`crate::integrations::composio::client::ComposioClient::list_tools`];
- /// without it a self-key user's `composio_list_tools(..., tags)`
- /// request would silently drop the tag filter. Blank/empty `tags`
- /// are treated as no filter.
- pub(crate) async fn list_tool_schemas_v3(
- &self,
- toolkits: &[&str],
- tags: Option<&[&str]>,
- ) -> anyhow::Result<Vec<ComposioToolSchemaV3>> {
- let url = format!("{}/tools", self.base_v3);
- let params = Self::build_list_tool_schemas_v3_query(toolkits, tags);
- tracing::debug!(
- toolkits = toolkits.len(),
- tags = tags.map(<[&str]>::len).unwrap_or(0),
- "[composio-direct] list_tool_schemas_v3: GET v3 /tools query built"
- );
- let req = self
- .client()
- .get(&url)
- .header("x-api-key", &self.api_key)
- .query(&params);
-
- let resp = req.send().await?;
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v3 list_tool_schemas: {err}");
- }
-
- let body: ComposioToolsResponse = resp
- .json()
- .await
- .context("Failed to decode Composio v3 tools response")?;
- Ok(body
- .items
- .into_iter()
- .map(ComposioToolSchemaV3::from_v3_tool)
- .collect())
- }
-
- /// Execute a Composio action/tool with given parameters.
- ///
- /// Uses v3 endpoint first and falls back to v2 for compatibility.
- pub async fn execute_action(
- &self,
- action_name: &str,
- params: serde_json::Value,
- entity_id: Option<&str>,
- connected_account_ref: Option<&str>,
- ) -> anyhow::Result<serde_json::Value> {
- // The Composio v3 action-execute contract keys off the UPPERCASE_SNAKE
- // *action* slug (e.g. `GMAIL_SEND_EMAIL`) at `/tools/execute/{slug}`.
- // The previous code lowercased + dashed it into the *toolkit* slug
- // (`gmail-send-email`) and posted to the wrong `/tools/{slug}/execute`
- // path, so every direct-mode execute 404'd (issue #3219). Pass the
- // action slug through verbatim (trimmed only); the v2 fallback already
- // used the same untransformed name.
- let action_slug = action_name.trim();
-
- match self
- .execute_action_v3(
- action_slug,
- params.clone(),
- entity_id,
- connected_account_ref,
- )
- .await
- {
- Ok(result) => Ok(result),
- Err(v3_err) => match self.execute_action_v2(action_name, params, entity_id).await {
- Ok(result) => Ok(result),
- Err(v2_err) => anyhow::bail!(
- "Composio execute failed on v3 ({v3_err}) and v2 fallback ({v2_err})"
- ),
- },
- }
- }
-
- fn build_execute_action_v3_request(
- action_slug: &str,
- params: serde_json::Value,
- entity_id: Option<&str>,
- connected_account_ref: Option<&str>,
- ) -> (String, serde_json::Value) {
- // POST /api/v3/tools/execute/{ACTION_SLUG} — the action slug stays
- // UPPERCASE_SNAKE (see `execute_action`). Path is `/tools/execute/{slug}`,
- // NOT `/tools/{slug}/execute` (issue #3219).
- let url = format!("{COMPOSIO_API_BASE_V3}/tools/execute/{action_slug}");
- let account_ref = connected_account_ref.and_then(|candidate| {
- let trimmed_candidate = candidate.trim();
- (!trimmed_candidate.is_empty()).then_some(trimmed_candidate)
- });
-
- let mut body = json!({
- "arguments": params,
- });
-
- if let Some(entity) = entity_id {
- body["user_id"] = json!(entity);
- }
- if let Some(account_ref) = account_ref {
- body["connected_account_id"] = json!(account_ref);
- }
-
- (url, body)
- }
-
- async fn execute_action_v3(
- &self,
- action_slug: &str,
- params: serde_json::Value,
- entity_id: Option<&str>,
- connected_account_ref: Option<&str>,
- ) -> anyhow::Result<serde_json::Value> {
- let (_default_url, body) = Self::build_execute_action_v3_request(
- action_slug,
- params,
- entity_id,
- connected_account_ref,
- );
- let url = format!("{}/tools/execute/{action_slug}", self.base_v3);
-
- self.ensure_request_url(&url)?;
-
- let resp = self
- .client()
- .post(&url)
- .header("x-api-key", &self.api_key)
- .json(&body)
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v3 action execution failed: {err}");
- }
-
- let result: serde_json::Value = resp
- .json()
- .await
- .context("Failed to decode Composio v3 execute response")?;
- Ok(result)
- }
-
- async fn execute_action_v2(
- &self,
- action_name: &str,
- params: serde_json::Value,
- entity_id: Option<&str>,
- ) -> anyhow::Result<serde_json::Value> {
- let url = format!("{}/actions/{action_name}/execute", self.base_v2);
-
- let mut body = json!({
- "input": params,
- });
-
- if let Some(entity) = entity_id {
- body["entityId"] = json!(entity);
- }
-
- let resp = self
- .client()
- .post(&url)
- .header("x-api-key", &self.api_key)
- .json(&body)
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v2 action execution failed: {err}");
- }
-
- let result: serde_json::Value = resp
- .json()
- .await
- .context("Failed to decode Composio v2 execute response")?;
- Ok(result)
- }
-
- /// Get the OAuth connection URL for a specific app/toolkit or auth config.
- ///
- /// Uses v3 endpoint first and falls back to v2 for compatibility.
- pub async fn get_connection_url(
- &self,
- app_name: Option<&str>,
- auth_config_id: Option<&str>,
- entity_id: &str,
- ) -> anyhow::Result<String> {
- let v3 = self
- .get_connection_url_v3(app_name, auth_config_id, entity_id)
- .await;
- match v3 {
- Ok(url) => Ok(url),
- Err(v3_err) => {
- let app = app_name.ok_or_else(|| {
- anyhow::anyhow!(
- "Composio v3 connect failed ({v3_err}) and v2 fallback requires 'app'"
- )
- })?;
- match self.get_connection_url_v2(app, entity_id).await {
- Ok(url) => Ok(url),
- Err(v2_err) => anyhow::bail!(
- "Composio connect failed on v3 ({v3_err}) and v2 fallback ({v2_err})"
- ),
- }
- }
- }
- }
-
- async fn get_connection_url_v3(
- &self,
- app_name: Option<&str>,
- auth_config_id: Option<&str>,
- entity_id: &str,
- ) -> anyhow::Result<String> {
- let auth_config_id = match auth_config_id {
- Some(id) => id.to_string(),
- None => {
- let app = app_name.ok_or_else(|| {
- anyhow::anyhow!("Missing 'app' or 'auth_config_id' for v3 connect")
- })?;
- self.resolve_auth_config_id(app).await?
- }
- };
-
- let url = format!("{}/connected_accounts/link", self.base_v3);
- let body = json!({
- "auth_config_id": auth_config_id,
- "user_id": entity_id,
- });
-
- let resp = self
- .client()
- .post(&url)
- .header("x-api-key", &self.api_key)
- .json(&body)
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v3 connect failed: {err}");
- }
-
- let result: serde_json::Value = resp
- .json()
- .await
- .context("Failed to decode Composio v3 connect response")?;
- extract_redirect_url(&result)
- .ok_or_else(|| anyhow::anyhow!("No redirect URL in Composio v3 response"))
- }
-
- async fn get_connection_url_v2(
- &self,
- app_name: &str,
- entity_id: &str,
- ) -> anyhow::Result<String> {
- let url = format!("{}/connectedAccounts", self.base_v2);
-
- let body = json!({
- "integrationId": app_name,
- "entityId": entity_id,
- });
-
- let resp = self
- .client()
- .post(&url)
- .header("x-api-key", &self.api_key)
- .json(&body)
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v2 connect failed: {err}");
- }
-
- let result: serde_json::Value = resp
- .json()
- .await
- .context("Failed to decode Composio v2 connect response")?;
- extract_redirect_url(&result)
- .ok_or_else(|| anyhow::anyhow!("No redirect URL in Composio v2 response"))
- }
-
- /// List the user's connected accounts on Composio v3.
- ///
- /// GET `https://backend.composio.dev/api/v3/connected_accounts` with
- /// `x-api-key: <user_key>`. Returns the raw item list; reshaping
- /// into [`super::super::super::composio::types::ComposioConnection`]
- /// happens at the call site in `composio/client.rs::direct_list_connections`.
- ///
- /// The v3 envelope is `{ items: [{ id, status, toolkit, created_at, ... }] }`.
- /// Toolkit may arrive as either a plain string slug or as a nested
- /// object — we tolerate both via [`ComposioConnectedAccount::toolkit_slug`].
- /// This matches the same upstream shape drift handled by
- /// `de_string_or_object` in `composio/types.rs`.
- pub async fn list_connected_accounts(&self) -> anyhow::Result<Vec<ComposioConnectedAccount>> {
- let url = format!("{}/connected_accounts", self.base_v3);
- self.ensure_request_url(&url)?;
-
- let resp = self
- .client()
- .get(&url)
- .header("x-api-key", &self.api_key)
- // Composio paginates; pull a generous page size so most
- // users see their full list in one round trip. If a user has
- // > 200 connected accounts (extremely rare for an individual
- // tenant) the rest will be missing until we add explicit
- // pagination — note for the follow-up.
- .query(&[("limit", "200")])
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v3 connected_accounts failed: {err}");
- }
-
- let mut body: ComposioConnectedAccountsResponse = resp
- .json()
- .await
- .context("Failed to decode Composio v3 connected_accounts response")?;
- // Drop rows with a blank id — serde_default means id can be ""
- // if the upstream response is malformed. An empty connectionId
- // propagated downstream causes invalid v3 API calls.
- body.items.retain(|item| !item.id.trim().is_empty());
- tracing::debug!(
- count = body.items.len(),
- "[composio-direct] list_connected_accounts: fetched connected accounts"
- );
- Ok(body.items)
- }
-
- async fn resolve_auth_config_id(&self, app_name: &str) -> anyhow::Result<String> {
- let url = format!("{}/auth_configs", self.base_v3);
-
- let resp = self
- .client()
- .get(&url)
- .header("x-api-key", &self.api_key)
- .query(&[
- ("toolkit_slug", app_name),
- ("show_disabled", "true"),
- ("limit", "25"),
- ])
- .send()
- .await?;
-
- if !resp.status().is_success() {
- let err = response_error(resp).await;
- anyhow::bail!("Composio v3 auth config lookup failed: {err}");
- }
-
- let body: ComposioAuthConfigsResponse = resp
- .json()
- .await
- .context("Failed to decode Composio v3 auth configs response")?;
-
- if body.items.is_empty() {
- anyhow::bail!(
- "No auth config found for toolkit '{app_name}'. Create one in Composio first."
- );
- }
-
- let preferred = body
- .items
- .iter()
- .find(|cfg| cfg.is_enabled())
- .or_else(|| body.items.first())
- .context("No usable auth config returned by Composio")?;
-
- Ok(preferred.id.clone())
- }
-}
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct_part_03.rs b/crates/openhuman-core/src/integrations/composio/tools/direct_part_03.rs
deleted file mode 100644
index 62177edf8c..0000000000
--- a/crates/openhuman-core/src/integrations/composio/tools/direct_part_03.rs
+++ /dev/null
@@ -1,503 +0,0 @@
-
-#[async_trait]
-impl Tool for ComposioTool {
- fn name(&self) -> &str {
- "composio"
- }
-
- fn description(&self) -> &str {
- "Execute actions on 1000+ apps via Composio (Gmail, Notion, GitHub, Slack, etc.). \
- Use action='list' to see available actions, action='execute' with action_name/tool_slug, params, and optional connected_account_id, \
- or action='connect' with app/auth_config_id to get OAuth URL. \
- For Gmail: GMAIL_FETCH_EMAILS supports standard Gmail search syntax in the 'query' param — \
- use query='from:me' or query='label:SENT' to retrieve sent emails, query='label:INBOX' for inbox, \
- query='is:unread' for unread mail, etc. Sent mail is synced and searchable."
- }
-
- fn parameters_schema(&self) -> serde_json::Value {
- json!({
- "type": "object",
- "properties": {
- "action": {
- "type": "string",
- "description": "The operation: 'list' (list available actions), 'execute' (run an action), or 'connect' (get OAuth URL)",
- "enum": ["list", "execute", "connect"]
- },
- "app": {
- "type": "string",
- "description": "Toolkit slug filter for 'list', or toolkit/app for 'connect' (e.g. 'gmail', 'notion', 'github')"
- },
- "action_name": {
- "type": "string",
- "description": "Action/tool identifier to execute (legacy aliases supported)"
- },
- "tool_slug": {
- "type": "string",
- "description": "Preferred v3 tool slug to execute (alias of action_name)"
- },
- "params": {
- "type": "object",
- "description": "Parameters to pass to the action"
- },
- "entity_id": {
- "type": "string",
- "description": "Entity/user ID for multi-user setups (defaults to composio.entity_id from config)"
- },
- "auth_config_id": {
- "type": "string",
- "description": "Optional Composio v3 auth config id for connect flow"
- },
- "connected_account_id": {
- "type": "string",
- "description": "Optional connected account ID for execute flow when a specific account is required"
- }
- },
- "required": ["action"]
- })
- }
-
- fn category(&self) -> ToolCategory {
- // Composio proxies to external SaaS (Gmail, Notion, …) — surface
- // it in the Workflow category so the skills sub-agent
- // (`category_filter = "skill"`) can see and call it.
- ToolCategory::Workflow
- }
-
- fn external_effect(&self) -> bool {
- // Conservative default for the arg-less path: assume any
- // composio call is a write so callers that don't reach the
- // args-aware override still get gated. The harness uses
- // `external_effect_with_args` (below) which inspects
- // `action` and lets read-only branches through.
- true
- }
-
- fn external_effect_with_args(&self, args: &serde_json::Value) -> bool {
- // `action="list"` enumerates available Composio actions —
- // a read-only catalog call. `action="connect"` only returns
- // an OAuth URL the user then visits manually; the
- // subsequent OAuth handoff is its own consent flow so the
- // tool call itself has no outbound side effect to gate.
- // `action="execute"` (or anything unknown / missing) is the
- // write path and routes through the approval gate.
- !matches!(
- args.get("action").and_then(|v| v.as_str()),
- Some("list") | Some("connect")
- )
- }
-
- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
- let action = args
- .get("action")
- .and_then(|v| v.as_str())
- .ok_or_else(|| anyhow::anyhow!("Missing 'action' parameter"))?;
-
- let entity_id = args
- .get("entity_id")
- .and_then(|v| v.as_str())
- .unwrap_or(self.default_entity_id.as_str());
-
- match action {
- "list" => {
- let app = args.get("app").and_then(|v| v.as_str());
- match self.list_actions(app).await {
- Ok(actions) => {
- let summary: Vec<String> = actions
- .iter()
- .take(20)
- .map(|a| {
- format!(
- "- {} ({}): {}",
- a.name,
- a.app_name.as_deref().unwrap_or("?"),
- a.description.as_deref().unwrap_or("")
- )
- })
- .collect();
- let total = actions.len();
- let output = format!(
- "Found {total} available actions:\n{}{}",
- summary.join("\n"),
- if total > 20 {
- format!("\n... and {} more", total - 20)
- } else {
- String::new()
- }
- );
- Ok(ToolResult::success(output))
- }
- Err(e) => Ok(ToolResult::error(format!("Failed to list actions: {e}"))),
- }
- }
-
- "execute" => {
- if let Err(error) = self
- .security
- .enforce_tool_operation(ToolOperation::Act, "composio.execute")
- {
- return Ok(ToolResult::error(error));
- }
-
- let action_name = args
- .get("tool_slug")
- .or_else(|| args.get("action_name"))
- .and_then(|v| v.as_str())
- .ok_or_else(|| {
- anyhow::anyhow!("Missing 'action_name' (or 'tool_slug') for execute")
- })?;
-
- let params = args.get("params").cloned().unwrap_or(json!({}));
- let acct_ref = args.get("connected_account_id").and_then(|v| v.as_str());
-
- match self
- .execute_action(action_name, params, Some(entity_id), acct_ref)
- .await
- {
- Ok(result) => {
- let output = serde_json::to_string_pretty(&result)
- .unwrap_or_else(|_| format!("{result:?}"));
- Ok(ToolResult::success(output))
- }
- Err(e) => Ok(ToolResult::error(format!("Action execution failed: {e}"))),
- }
- }
-
- "connect" => {
- if let Err(error) = self
- .security
- .enforce_tool_operation(ToolOperation::Act, "composio.connect")
- {
- return Ok(ToolResult::error(error));
- }
-
- let app = args.get("app").and_then(|v| v.as_str());
- let auth_config_id = args.get("auth_config_id").and_then(|v| v.as_str());
-
- if app.is_none() && auth_config_id.is_none() {
- anyhow::bail!("Missing 'app' or 'auth_config_id' for connect");
- }
-
- match self
- .get_connection_url(app, auth_config_id, entity_id)
- .await
- {
- Ok(url) => {
- let target =
- app.unwrap_or(auth_config_id.unwrap_or("provided auth config"));
- Ok(ToolResult::success(format!(
- "Open this URL to connect {target}:\n{url}"
- )))
- }
- Err(e) => Ok(ToolResult::error(format!(
- "Failed to get connection URL: {e}"
- ))),
- }
- }
-
- _ => Ok(ToolResult::error(format!(
- "Unknown action '{action}'. Use 'list', 'execute', or 'connect'."
- ))),
- }
- }
-}
-
-fn normalize_entity_id(entity_id: &str) -> String {
- let trimmed = entity_id.trim();
- if trimmed.is_empty() {
- "default".to_string()
- } else {
- trimmed.to_string()
- }
-}
-
-fn map_v3_tools_to_actions(items: Vec<ComposioV3Tool>) -> Vec<ComposioAction> {
- items
- .into_iter()
- .filter_map(|item| {
- let name = item.slug.or(item.name.clone())?;
- let app_name = item
- .toolkit
- .as_ref()
- .and_then(|toolkit| toolkit.slug.clone().or(toolkit.name.clone()))
- .or(item.app_name);
- let description = item.description.or(item.name);
- Some(ComposioAction {
- name,
- app_name,
- description,
- enabled: true,
- })
- })
- .collect()
-}
-
-fn extract_redirect_url(result: &serde_json::Value) -> Option<String> {
- result
- .get("redirect_url")
- .and_then(|v| v.as_str())
- .or_else(|| result.get("redirectUrl").and_then(|v| v.as_str()))
- .or_else(|| {
- result
- .get("data")
- .and_then(|v| v.get("redirect_url"))
- .and_then(|v| v.as_str())
- })
- .map(ToString::to_string)
-}
-
-async fn response_error(resp: reqwest::Response) -> String {
- let status = resp.status();
- let body = resp.text().await.unwrap_or_default();
- if body.trim().is_empty() {
- return format!("HTTP {}", status.as_u16());
- }
-
- if let Some(api_error) = extract_api_error_message(&body) {
- return format!(
- "HTTP {}: {}",
- status.as_u16(),
- sanitize_error_message(&api_error)
- );
- }
-
- format!("HTTP {}", status.as_u16())
-}
-
-fn sanitize_error_message(message: &str) -> String {
- let mut sanitized = message.replace('\n', " ");
- for marker in [
- "connected_account_id",
- "connectedAccountId",
- "entity_id",
- "entityId",
- "user_id",
- "userId",
- ] {
- sanitized = sanitized.replace(marker, "[redacted]");
- }
-
- crate::util::truncate_with_ellipsis(&sanitized, 240)
-}
-
-fn extract_api_error_message(body: &str) -> Option<String> {
- let parsed: serde_json::Value = serde_json::from_str(body).ok()?;
- parsed
- .get("error")
- .and_then(|v| v.get("message"))
- .and_then(|v| v.as_str())
- .map(ToString::to_string)
- .or_else(|| {
- parsed
- .get("message")
- .and_then(|v| v.as_str())
- .map(ToString::to_string)
- })
-}
-
-// ── API response types ──────────────────────────────────────────
-
-#[derive(Debug, Deserialize)]
-struct ComposioActionsResponse {
- #[serde(default)]
- items: Vec<ComposioAction>,
-}
-
-#[derive(Debug, Deserialize)]
-struct ComposioToolsResponse {
- #[serde(default)]
- items: Vec<ComposioV3Tool>,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-struct ComposioV3Tool {
- #[serde(default)]
- slug: Option<String>,
- #[serde(default)]
- name: Option<String>,
- #[serde(default)]
- description: Option<String>,
- #[serde(rename = "appName", default)]
- app_name: Option<String>,
- #[serde(default)]
- toolkit: Option<ComposioToolkitRef>,
- /// JSON schema for the tool parameters. Composio v3 names this
- /// `input_parameters`; older payloads use `parameters`. Either
- /// shape deserialises into this field, and we re-emit it as
- /// `ComposioToolFunction::parameters` so direct-mode users get
- /// the same model-callable schema backend mode surfaces.
- #[serde(default, alias = "parameters")]
- input_parameters: Option<serde_json::Value>,
- /// JSON schema for the tool's OUTPUT/return value, per Composio v3
- /// `/tools`'s `output_parameters` field ("Schema definition of return
- /// values from the tool" —
- /// <https://docs.composio.dev/reference/api-reference/tools/getTools>).
- /// Re-emitted as `ComposioToolFunction::output_parameters` so callers
- /// can ground a downstream binding in the tool's real output field
- /// names instead of guessing them.
- #[serde(default)]
- output_parameters: Option<serde_json::Value>,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-struct ComposioToolkitRef {
- #[serde(default)]
- slug: Option<String>,
- #[serde(default)]
- name: Option<String>,
-}
-
-#[derive(Debug, Deserialize)]
-struct ComposioAuthConfigsResponse {
- #[serde(default)]
- items: Vec<ComposioAuthConfig>,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-struct ComposioAuthConfig {
- id: String,
- #[serde(default)]
- status: Option<String>,
- #[serde(default)]
- enabled: Option<bool>,
-}
-
-impl ComposioAuthConfig {
- fn is_enabled(&self) -> bool {
- self.enabled.unwrap_or(false)
- || self
- .status
- .as_deref()
- .is_some_and(|v| v.eq_ignore_ascii_case("enabled"))
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct ComposioAction {
- pub name: String,
- #[serde(rename = "appName")]
- pub app_name: Option<String>,
- pub description: Option<String>,
- #[serde(default)]
- pub enabled: bool,
-}
-
-/// Direct-mode tool definition lifted from Composio v3 `/tools`.
-///
-/// Carries the `input_parameters` JSON schema so the upstream
-/// `composio_list_tools` direct branch can hand the LLM agent a
-/// model-callable function shape — same fields backend mode surfaces
-/// through `ComposioToolSchema`.
-///
-/// Kept distinct from `ComposioAction` (legacy flattened shape) so
-/// new callers explicitly opt into the schema-preserving variant.
-#[derive(Debug, Clone)]
-pub struct ComposioToolSchemaV3 {
- pub slug: String,
- pub description: Option<String>,
- pub toolkit_slug: Option<String>,
- pub input_parameters: Option<serde_json::Value>,
- /// See [`ComposioV3Tool::output_parameters`] — Composio v3's schema for
- /// the action's return value, when published.
- pub output_parameters: Option<serde_json::Value>,
-}
-
-impl ComposioToolSchemaV3 {
- fn from_v3_tool(item: ComposioV3Tool) -> Self {
- let slug = item
- .slug
- .clone()
- .or_else(|| item.name.clone())
- .unwrap_or_default();
- let toolkit_slug = item
- .toolkit
- .as_ref()
- .and_then(|t| t.slug.clone().or(t.name.clone()))
- .or(item.app_name);
- Self {
- slug,
- description: item.description.or(item.name),
- toolkit_slug,
- input_parameters: item.input_parameters,
- output_parameters: item.output_parameters,
- }
- }
-}
-
-// ── v3 /connected_accounts envelope ─────────────────────────────────
-//
-// Public so the `composio/client.rs::direct_list_connections` helper
-// in the domain layer can reshape it into the canonical
-// `ComposioConnection` type. Kept distinct from `ComposioConnection`
-// itself (which is the backend-proxied envelope) so the two paths
-// don't get coupled — Composio v3 may add or rename fields and we'd
-// rather adjust the mapping than reshuffle the public type.
-
-#[derive(Debug, Deserialize)]
-struct ComposioConnectedAccountsResponse {
- #[serde(default)]
- items: Vec<ComposioConnectedAccount>,
-}
-
-/// One v3 connected-account row.
-///
-/// Field shapes follow Composio's v3 docs as of May 2026. `toolkit` may
-/// be either a string slug (older payloads) or a nested object with a
-/// `slug` field (newer payloads); [`Self::toolkit_slug`] extracts the
-/// canonical slug from either shape.
-#[derive(Debug, Clone, Deserialize)]
-pub struct ComposioConnectedAccount {
- #[serde(default)]
- pub id: String,
- /// `"ACTIVE"`, `"INITIATED"`, `"FAILED"`, … — passed through as-is
- /// so the caller's status filter (`ComposioConnection::is_active`)
- /// applies uniformly across both backend-proxied and direct paths.
- #[serde(default)]
- pub status: Option<String>,
- /// Composio uses `created_at` (snake_case) at v3. We keep both
- /// spellings to tolerate any upstream drift back to `createdAt`.
- #[serde(default, alias = "createdAt")]
- pub created_at: Option<String>,
- /// Toolkit may be a plain string slug or a nested
- /// `ComposioToolkitRef`. Extracted via [`Self::toolkit_slug`].
- #[serde(default)]
- toolkit: Option<serde_json::Value>,
- /// Older payload shape — a top-level `app_name` string. Used as
- /// a fallback when `toolkit` is absent or unparseable.
- #[serde(default, rename = "appName", alias = "app_name")]
- app_name: Option<String>,
-}
-
-impl ComposioConnectedAccount {
- /// Best-effort extract of the toolkit slug from the
- /// possibly-polymorphic `toolkit` field, falling back to
- /// `app_name`. Returns `None` only when no recognizable slug
- /// representation is present.
- pub fn toolkit_slug(&self) -> Option<String> {
- if let Some(value) = &self.toolkit {
- match value {
- serde_json::Value::String(s) => {
- let t = s.trim();
- if !t.is_empty() {
- return Some(t.to_string());
- }
- }
- serde_json::Value::Object(map) => {
- for key in ["slug", "id", "name", "key"] {
- if let Some(serde_json::Value::String(s)) = map.get(key) {
- let t = s.trim();
- if !t.is_empty() {
- return Some(t.to_string());
- }
- }
- }
- }
- _ => {}
- }
- }
- self.app_name
- .as_deref()
- .map(str::trim)
- .filter(|s| !s.is_empty())
- .map(str::to_string)
- }
-}
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct_tests_part_01_tests.rs b/crates/openhuman-core/src/integrations/composio/tools/direct_tests_constructor_and_wire_types_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/integrations/composio/tools/direct_tests_part_01_tests.rs
rename to crates/openhuman-core/src/integrations/composio/tools/direct_tests_constructor_and_wire_types_tests.rs
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct_tests_part_02_tests.rs b/crates/openhuman-core/src/integrations/composio/tools/direct_tests_sanitization_and_connected_accounts_tests.rs
similarity index 100%
rename from crates/openhuman-core/src/integrations/composio/tools/direct_tests_part_02_tests.rs
rename to crates/openhuman-core/src/integrations/composio/tools/direct_tests_sanitization_and_connected_accounts_tests.rs