The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
refactor(composio): consolidate split client modules into single file
Steven Enamakel517795c632a3
diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rsnew file mode 100644index 0000000000..d34b5a67fe--- /dev/null+++ b/crates/openhuman-core/src/channels/runtime/dispatch/processor/turn.rs@@ -0,0 +1,722 @@+//! The per-message pipeline: typing indicator, ACK reaction, history+//! assembly, dispatching the agentic turn over the native bus, and+//! delivering the draft/final reply.++use crate::core::bus::BUS;+use crate::core::events::DomainEvent;+use crate::agent::bus::{AgentTurnRequest, AgentTurnResponse, AGENT_RUN_TURN_METHOD};+use crate::agent::messages::ChatMessage;+use crate::agent::progress::AgentProgress;+use crate::channels::context::{+ build_memory_context, compact_sender_history, conversation_history_key,+ conversation_memory_key, is_context_window_overflow_error, ChannelRuntimeContext,+};+use crate::channels::routes::{+ get_or_create_turn_model_source, get_route_selection, handle_runtime_command_if_needed,+};+use crate::channels::traits;+use crate::channels::{ChannelSendExt, SendMessage};+use crate::inference::provider;+use crate::util::truncate_with_ellipsis;+use std::sync::Arc;+use std::time::{Duration, Instant};+use tinybus::NativeRequestError;+use tinymemory_api::provider::MemoryCore as _;+use tokio_util::sync::CancellationToken;++use super::super::helpers::{+ build_channel_context_block, log_worker_join_result, select_acknowledgment_reaction,+ spawn_scoped_typing_task, REPLY_LOG_TRUNCATE_CHARS,+};+use super::super::routing::resolve_target_agent;+use super::approval::{channel_has_approval_surface, try_route_approval_reply};+use super::message::RuntimeChannelMessage;++pub(crate) async fn process_channel_message(+ ctx: Arc<ChannelRuntimeContext>,+ msg: traits::ChannelMessage,+) {+ process_channel_runtime_message(ctx, RuntimeChannelMessage::from(msg)).await;+}++pub(crate) async fn process_channel_runtime_message(+ ctx: Arc<ChannelRuntimeContext>,+ runtime_msg: RuntimeChannelMessage,+) {+ let RuntimeChannelMessage {+ message: msg,+ inbound_envelope,+ } = runtime_msg;++ println!(+ " π¬ [{}] from {}: {}",+ msg.channel,+ msg.sender,+ truncate_with_ellipsis(&msg.content, 80)+ );++ BUS.publish(DomainEvent::ChannelMessageReceived {+ channel: msg.channel.clone(),+ message_id: msg.id.clone(),+ sender: msg.sender.clone(),+ reply_target: msg.reply_target.clone(),+ content: msg.content.clone(),+ thread_ts: msg.thread_ts.clone(),+ inbound_envelope: Some(+ inbound_envelope+ .unwrap_or_else(|| tinychannels::inbound_envelope_from_legacy_message(&msg)),+ ),+ workspace_dir: ctx.workspace_dir.as_ref().clone(),+ });++ let target_channel = ctx.channels_by_name.get(&msg.channel).cloned();+ if handle_runtime_command_if_needed(ctx.as_ref(), &msg, target_channel.as_ref()).await {+ return;+ }++ // Sub-issue 2 of #3098: if this channel has an approval surface and the+ // inbound message is a yes/no reply for a parked approval on this same+ // history key, route it to `ApprovalGate::decide` and return β running+ // a fresh agent turn would cancel the parked tool call. Any other text+ // falls through to the normal dispatch (the user is redirecting). Mirrors+ // the same intercept in `web_chat/`.+ if channel_has_approval_surface(&msg.channel) && try_route_approval_reply(&msg).await {+ return;+ }++ // Fire typing indicator as early as possible β before any async I/O β so the+ // user sees feedback immediately regardless of how fast the LLM responds.+ if let Some(channel) = target_channel.as_ref() {+ if let Err(e) = channel.start_typing(&msg.reply_target).await {+ tracing::debug!(+ "[dispatch] Early typing start failed on {}: {e}",+ channel.name()+ );+ }+ }++ // Send a smart acknowledgment reaction immediately so the user knows the message+ // was received and understood. The LLM may override this later by including its+ // own [REACTION:...] marker, which Telegram replaces atomically.+ if let Some(channel) = target_channel.as_ref() {+ if channel.supports_reactions() && msg.thread_ts.is_some() {+ let ack_emoji = select_acknowledgment_reaction(&msg.content);+ tracing::debug!(+ channel = msg.channel,+ emoji = ack_emoji,+ "[dispatch] Sending acknowledgment reaction"+ );+ let react_content = format!("[REACTION:{ack_emoji}]");+ let channel_for_react = Arc::clone(channel);+ let react_msg =+ SendMessage::new(react_content, &msg.reply_target).in_thread(msg.thread_ts.clone());+ tokio::spawn(async move {+ if let Err(e) = channel_for_react+ .send_with_outbound_intent(&react_msg)+ .await+ {+ tracing::debug!("[dispatch] Acknowledgment reaction failed: {e}");+ }+ });+ }+ }++ let history_key = conversation_history_key(&msg);+ let route = get_route_selection(ctx.as_ref(), &history_key);+ let active_turn_model_source = if ctx.config.is_none() {+ match get_or_create_turn_model_source(ctx.as_ref(), &route.provider).await {+ Ok(source) => Some(source),+ Err(err) => {+ crate::core::observability::report_error(+ &err,+ "channels",+ "provider_init",+ &[+ ("channel", msg.channel.as_str()),+ ("provider", route.provider.as_str()),+ ],+ );+ let safe_err = provider::sanitize_api_error(&err.to_string());+ let message = format!(+ "β οΈ Failed to initialize provider `{}`. Please run `/models` to choose another provider.\nDetails: {safe_err}",+ route.provider+ );+ if let Some(channel) = target_channel.as_ref() {+ let _ = channel+ .send_with_outbound_intent(+ &SendMessage::new(message, &msg.reply_target)+ .in_thread(msg.thread_ts.clone()),+ )+ .await;+ }+ return;+ }+ }+ } else {+ None+ };++ let memory_context =+ build_memory_context(&ctx.memory, &msg.content, ctx.min_relevance_score).await;++ if ctx.auto_save_memory {+ let autosave_key = conversation_memory_key(&msg);+ let _ = ctx+ .memory+ .store(+ crate::agent::learning::transcript_ingest::CONVERSATION_RAW_NAMESPACE,+ &autosave_key,+ &msg.content,+ tinymemory_api::types::MemoryCategory::Conversation,+ None,+ tinymemory_api::types::MemoryTaint::Internal,+ )+ .await;+ }++ let channel_context = build_channel_context_block(&msg);+ let enriched_message = match (memory_context.is_empty(), channel_context.is_empty()) {+ (true, true) => msg.content.clone(),+ (false, true) => format!("{memory_context}{}", msg.content),+ (true, false) => format!("{channel_context}{}", msg.content),+ (false, false) => format!("{memory_context}{channel_context}{}", msg.content),+ };++ println!(" β³ Processing message...");+ let started_at = Instant::now();++ // Build history from per-sender conversation cache+ let mut prior_turns = ctx+ .conversation_histories+ .lock()+ .unwrap_or_else(|e| e.into_inner())+ .get(&history_key)+ .cloned()+ .unwrap_or_default();++ // Re-rendered by `ChannelSystemPrompt` only when the active profile or an+ // identity file changed since the last message (#6028); otherwise the+ // same bytes as the previous turn.+ let system_prompt = ctx.system_prompt.current();+ let mut history = vec![ChatMessage::system(system_prompt.as_str())];+ history.append(&mut prior_turns);+ history.push(ChatMessage::user(&enriched_message));++ // Determine if this channel supports streaming draft updates+ let use_streaming = target_channel+ .as_ref()+ .is_some_and(|ch| ch.supports_draft_updates());++ // Set up streaming channel if supported+ let (progress_tx, progress_rx) = if use_streaming {+ let (tx, rx) = tokio::sync::mpsc::channel::<AgentProgress>(64);+ (Some(tx), Some(rx))+ } else {+ (None, None)+ };++ // Send initial draft message if streaming+ let draft_message_id = if use_streaming {+ if let Some(channel) = target_channel.as_ref() {+ match channel+ .send_draft(+ &SendMessage::new("...", &msg.reply_target).in_thread(msg.thread_ts.clone()),+ )+ .await+ {+ Ok(id) => id,+ Err(e) => {+ tracing::debug!("Failed to send draft on {}: {e}", channel.name());+ None+ }+ }+ } else {+ None+ }+ } else {+ None+ };++ // Spawn a task to forward streaming progress to draft updates+ let draft_updater = if let (Some(mut rx), Some(draft_id_ref), Some(channel_ref)) = (+ progress_rx,+ draft_message_id.as_deref(),+ target_channel.as_ref(),+ ) {+ let channel = Arc::clone(channel_ref);+ let reply_target = msg.reply_target.clone();+ let draft_id = draft_id_ref.to_string();+ Some(tokio::spawn(async move {+ let mut accumulated = String::new();+ let mut last_thinking_update = None;+ const THINKING_UPDATE_INTERVAL_MS: u128 = 2000;++ while let Some(progress) = rx.recv().await {+ match progress {+ AgentProgress::TextDelta { delta, .. } => {+ accumulated.push_str(&delta);+ if let Err(e) = channel+ .update_draft(&reply_target, &draft_id, &accumulated)+ .await+ {+ tracing::debug!("Draft update failed: {e}");+ }+ }+ AgentProgress::ThinkingDelta { .. } => {+ // Suppress thinking text to Telegram; only show a placeholder if we haven't+ // started receiving the final answer yet.+ if accumulated.is_empty() {+ let now = std::time::Instant::now();+ let should_update = match last_thinking_update {+ None => true,+ Some(last) => {+ now.duration_since(last).as_millis()+ > THINKING_UPDATE_INTERVAL_MS+ }+ };++ if should_update {+ if let Err(e) = channel+ .update_draft(&reply_target, &draft_id, "Thinking...")+ .await+ {+ tracing::debug!("Thinking update failed: {e}");+ }+ last_thinking_update = Some(now);+ }+ }+ }+ AgentProgress::ToolCallStarted { tool_name, .. } if accumulated.is_empty() => {+ let _ = channel+ .update_draft(+ &reply_target,+ &draft_id,+ &format!("Working ({})...", tool_name),+ )+ .await;+ }+ _ => {}+ }+ }+ }))+ } else {+ None+ };++ let typing_cancellation = target_channel.as_ref().map(|_| CancellationToken::new());+ // Typing was already started early (before memory/provider setup). Here we only+ // spawn the background refresh task that keeps the indicator alive during long turns.+ let typing_task = match (target_channel.as_ref(), typing_cancellation.as_ref()) {+ (Some(channel), Some(token)) => Some(spawn_scoped_typing_task(+ Arc::clone(channel),+ msg.reply_target.clone(),+ token.clone(),+ )),+ _ => None,+ };++ // Dispatch the agentic turn through the native event bus instead of+ // calling `run_tool_call_loop` directly. The agent domain registers+ // an `agent.run_turn` handler at startup (see+ // `crate::agent::bus::register_agent_handlers`); this keeps+ // the channel layer free of direct harness imports and makes the+ // agent side mockable in unit tests via a handler override.+ //+ // The agent handler owns the history vector β we `mem::take` the+ // local one to avoid an unnecessary clone; `history` is not read+ // again below.+ // Pick the active agent for this turn (always orchestrator) and+ // synthesise its delegation tool surface. Fresh disk read of+ // `Config::onboarding_completed` happens inside `resolve_target_agent`.+ let scoping = resolve_target_agent(&msg.channel).await;++ // A channel's explicitly-registered `tools_registry` tools are always visible+ // to the model. The resolved agent's visible-tool scope is meant to filter the+ // ambient/builtin tool surface, not to hide tools the channel deliberately+ // handed in for this turn. Without this, a channel that provides a tool+ // outside the resolved agent's `Named` scope (e.g. a test mock, or a custom+ // channel-specific tool) would be filtered out and surfaced to the model as+ // "unknown tool". When the scope is `Wildcard` (`None`), no filter applies.+ let visible_tool_names = scoping.visible_tool_names.map(|mut set| {+ for tool in ctx.tools_registry.iter() {+ set.insert(tool.name().to_string());+ }+ set+ });++ // Non-web channel turns label themselves as `ExternalChannel` so the+ // approval gate's origin-aware decision tree treats the inbound text+ // as untrusted (remote-attacker-controlled). Cron-driven channel+ // deliveries get a `TrustedAutomation { Cron }` label from the+ // scheduler instead and never reach this dispatch path.+ // Per-sender provenance flows into the origin so a co-channel attacker+ // who reads a leaked `quote_id` / approval prompt from a shared Discord /+ // Slack channel cannot use it from their own session β distinct senders+ // produce distinct origins, and the wallet preparer / parked-approval+ // gates compare these for equality before honouring confirmations.+ let turn_origin = crate::agent::turn_origin::AgentTurnOrigin::ExternalChannel {+ channel: msg.channel.clone(),+ sender: Some(msg.sender.clone()),+ reply_target: msg.reply_target.clone(),+ message_id: msg.id.clone(),+ };++ let turn_request = AgentTurnRequest {+ // Crate-native channel turn models (Phase 3 P3-B): when the runtime carries+ // the full config, build crate `ChatModel`s from `("chat", route.provider,+ // config)` β `route.provider` is the effective provider string. Tests (no+ // `config`) stay on an injected model source.+ turn_model_source: match &ctx.config {+ Some(cfg) => {+ crate::agent::tinyagents::TurnModelSource::new_crate_native_from_string(+ "chat",+ route.provider.clone(),+ cfg.clone(),+ )+ }+ None => active_turn_model_source+ .expect("test channel context must inject a turn model source"),+ },+ history: std::mem::take(&mut history),+ tools_registry: Arc::clone(&ctx.tools_registry),+ provider_name: route.provider.clone(),+ model: route.model.clone(),+ temperature: ctx.temperature,+ silent: true,+ channel_name: msg.channel.clone(),+ multimodal: ctx.multimodal.clone(),+ // Channel-sourced text is untrusted (Slack / Discord / Telegram+ // / WhatsApp / etc. β anyone who can DM the bot can put bytes+ // here). Operator-supplied defaults at `config.multimodal_files`+ // would otherwise let a remote sender smuggle a marker like+ // `[FILE:/etc/passwd]`, `[FILE:/home/<user>/.ssh/id_rsa]`, or+ // `[FILE:.env]` into the agent prompt β `read_local_file`+ // resolves the path with no workspace confinement, so absolute+ // paths exfiltrate server-local files via a follow-up question.+ //+ // Hard-disable file-marker resolution on this path regardless of+ // operator config; the desktop / web-chat path (where the user+ // owns the local filesystem) goes through a different turn+ // builder and keeps the operator default. Mirrors the triage-arm+ // hardening in `agent::triage::evaluator`.+ multimodal_files:+ crate::config::MultimodalFileConfig::for_untrusted_channel_input(),+ max_tool_iterations: ctx.max_tool_iterations,+ on_delta: None, // on_progress handles text deltas now+ target_agent_id: scoping.target_agent_id,+ visible_tool_names,+ extra_tools: scoping.extra_tools,+ on_progress: progress_tx,+ origin: turn_origin,+ };+ tracing::debug!(+ channel = %msg.channel,+ provider = %route.provider,+ model = %route.model,+ "[channels::dispatch] dispatching {AGENT_RUN_TURN_METHOD} via native bus"+ );+ let agent_call = async {+ BUS.native()+ .request::<AgentTurnRequest, AgentTurnResponse>(AGENT_RUN_TURN_METHOD, turn_request)+ .await+ .map_err(|err| match err {+ // Unwrap handler-returned errors so the underlying+ // message (e.g. "Agent exceeded maximum tool iterations")+ // flows through without being wrapped in bus-transport+ // layer prose. The error-formatting path downstream+ // treats this `anyhow::Error` the same way it did before+ // the bus migration.+ NativeRequestError::HandlerFailed { message, .. } => {+ anyhow::anyhow!(message)+ }+ // Bus-level errors (UnregisteredHandler / TypeMismatch /+ // NotInitialized) surface with their full Display so+ // startup wiring bugs are immediately obvious in logs.+ other => anyhow::anyhow!("[agent.run_turn dispatch] {other}"),+ })+ };+ // Sub-issue 2 of #3098: scope the agent turn in an `ApprovalChatContext`+ // for channels that have a registered approval surface β currently+ // Telegram only via `TelegramApprovalSurfaceSubscriber`. Without this+ // scope the gate's "no chat context β allow straight through" branch+ // (`approval/gate.rs:219-231`) silently bypasses every `Prompt`-class+ // tool call, voiding the `supervised` autonomy tier on the channel.+ // Discord / Slack / iMessage / Mattermost stay in the legacy bypass+ // until each gets its own approval surface in a follow-up PR.+ let llm_result = tokio::time::timeout(Duration::from_secs(ctx.message_timeout_secs), async {+ if channel_has_approval_surface(&msg.channel) {+ let approval_ctx = crate::security::approval::ApprovalChatContext {+ thread_id: history_key.clone(),+ client_id: msg.channel.clone(),+ };+ crate::security::approval::APPROVAL_CHAT_CONTEXT+ .scope(approval_ctx, agent_call)+ .await+ } else {+ agent_call.await+ }+ })+ .await;++ // Wait for draft updater to finish+ if let Some(handle) = draft_updater {+ let _ = handle.await;+ }++ if let Some(token) = typing_cancellation.as_ref() {+ token.cancel();+ }+ if let Some(handle) = typing_task {+ log_worker_join_result(handle.await);+ }++ let (success, response_text, response_provider, response_model) = match llm_result {+ Ok(Ok(response)) => {+ let resolved_provider = response+ .resolved_provider+ .clone()+ .unwrap_or_else(|| route.provider.clone());+ let resolved_model = response+ .resolved_model+ .clone()+ .unwrap_or_else(|| route.model.clone());+ let response_text = response.text;+ // Save user + assistant turn to per-sender history+ {+ let mut histories = ctx+ .conversation_histories+ .lock()+ .unwrap_or_else(|e| e.into_inner());+ let turns = histories.entry(history_key).or_default();+ turns.push(ChatMessage::user(&enriched_message));+ turns.push(ChatMessage::assistant(&response_text));+ // Trim to MAX_CHANNEL_HISTORY (keep recent turns)+ while turns.len() > crate::channels::context::MAX_CHANNEL_HISTORY {+ turns.remove(0);+ }+ }+ println!(+ " π€ Reply ({}ms): {}",+ started_at.elapsed().as_millis(),+ truncate_with_ellipsis(&response_text, REPLY_LOG_TRUNCATE_CHARS)+ );+ if let Some(channel) = target_channel.as_ref() {+ if let Some(ref draft_id) = draft_message_id {+ if let Err(e) = channel+ .finalize_draft(+ &msg.reply_target,+ draft_id,+ &response_text,+ msg.thread_ts.as_deref(),+ )+ .await+ {+ tracing::warn!("Failed to finalize draft: {e}; sending as new message");+ let _ = channel+ .send_with_outbound_intent(+ &SendMessage::new(&response_text, &msg.reply_target)+ .in_thread(msg.thread_ts.clone()),+ )+ .await;+ }+ } else if let Err(e) = channel+ .send_with_outbound_intent(+ &SendMessage::new(&response_text, &msg.reply_target)+ .in_thread(msg.thread_ts.clone()),+ )+ .await+ {+ eprintln!(" β Failed to reply on {}: {e}", channel.name());+ }+ }+ (true, response_text, resolved_provider, resolved_model)+ }+ Ok(Err(e)) => {+ if is_context_window_overflow_error(&e) {+ let compacted = compact_sender_history(ctx.as_ref(), &history_key);+ let error_text = if compacted {+ "β οΈ Context window exceeded for this conversation. I compacted recent history and kept the latest context. Please resend your last message."+ } else {+ "β οΈ Context window exceeded for this conversation. Please resend your last message."+ };+ eprintln!(+ " β οΈ Context window exceeded after {}ms; sender history compacted={}",+ started_at.elapsed().as_millis(),+ compacted+ );+ if let Some(channel) = target_channel.as_ref() {+ if let Some(ref draft_id) = draft_message_id {+ let _ = channel+ .finalize_draft(+ &msg.reply_target,+ draft_id,+ error_text,+ msg.thread_ts.as_deref(),+ )+ .await;+ } else {+ let _ = channel+ .send_with_outbound_intent(+ &SendMessage::new(error_text, &msg.reply_target)+ .in_thread(msg.thread_ts.clone()),+ )+ .await;+ }+ }++ BUS.publish(DomainEvent::ChannelMessageProcessed {+ channel: msg.channel.clone(),+ message_id: msg.id.clone(),+ sender: msg.sender.clone(),+ reply_target: msg.reply_target.clone(),+ content: msg.content.clone(),+ thread_ts: msg.thread_ts.clone(),+ response: error_text.to_string(),+ provider: route.provider.clone(),+ model: route.model.clone(),+ elapsed_ms: started_at.elapsed().as_millis() as u64,+ success: false,+ workspace_dir: ctx.workspace_dir.as_ref().clone(),+ });+ return;+ }++ let error_response = format!("β οΈ Error: {e}");+ eprintln!(+ " β LLM error after {}ms: {e}",+ started_at.elapsed().as_millis()+ );+ // The typed `AgentError` is flattened to a `String` at the+ // native-bus boundary (`agent::bus` map_err β `e.to_string()`),+ // so the downcast that works in `Agent::run_single` is not an+ // option here β fall back to canonical-phrase substring match.+ // The max-tool-iterations cap is a deterministic agent-state+ // outcome and is already surfaced to the user as the+ // chat-rendered "β οΈ Error: β¦" message just above. Skip the+ // Sentry funnel (OPENHUMAN-TAURI-98) and emit `log::info!`+ // instead β `Err` propagation through the surrounding match+ // arm is unchanged.+ if crate::agent::error::is_max_iterations_error(&e.to_string()) {+ log::info!(+ target: "channels",+ "[channels.dispatch] suppressed Sentry emission for max-iteration cap \+ channel={} provider={} message={}",+ msg.channel.as_str(),+ route.provider.as_str(),+ e+ );+ } else {+ // Route through `report_error_or_expected` so+ // transient-upstream provider HTTP errors that bubbled+ // up via `agent.run_single` (`OpenHuman API error+ // (502 Bad Gateway): β¦`) get demoted via+ // `is_transient_upstream_http_message` β the agent+ // re-emit at the dispatch layer was previously+ // unconditionally calling `report_error`, which firehoses+ // Sentry under `domain="channels"` even though the same+ // chain was already classified at the provider + agent+ // layers (OPENHUMAN-TAURI-4F ~157ev / -1C ~87ev / -8F+ // ~39ev: provider 5xx that the reliable layer retried+ // and exhausted, then the channels layer re-reported as+ // a fresh per-attempt event). Genuine bugs (404 / 500+ // / unrelated agent failures) still surface β the+ // classifier only demotes the canonical transient+ // shapes documented in+ // `crate::core::observability::expected_error_kind`.+ crate::core::observability::report_error_or_expected(+ &e,+ "channels",+ "dispatch_llm_error",+ &[+ ("channel", msg.channel.as_str()),+ ("provider", route.provider.as_str()),+ ],+ );+ }+ if let Some(channel) = target_channel.as_ref() {+ if let Some(ref draft_id) = draft_message_id {+ let _ = channel+ .finalize_draft(+ &msg.reply_target,+ draft_id,+ &error_response,+ msg.thread_ts.as_deref(),+ )+ .await;+ } else {+ let _ = channel+ .send_with_outbound_intent(+ &SendMessage::new(&error_response, &msg.reply_target)+ .in_thread(msg.thread_ts.clone()),+ )+ .await;+ }+ }+ (+ false,+ error_response,+ route.provider.clone(),+ route.model.clone(),+ )+ }+ Err(_) => {+ let timeout_msg = format!("LLM response timed out after {}s", ctx.message_timeout_secs);+ eprintln!(+ " β {} (elapsed: {}ms)",+ timeout_msg,+ started_at.elapsed().as_millis()+ );+ crate::core::observability::report_error(+ timeout_msg.as_str(),+ "channels",+ "dispatch_llm_timeout",+ &[+ ("channel", msg.channel.as_str()),+ ("timeout_secs", &ctx.message_timeout_secs.to_string()),+ ],+ );+ let error_text =+ "β οΈ Request timed out while waiting for the model. Please try again.".to_string();+ if let Some(channel) = target_channel.as_ref() {+ if let Some(ref draft_id) = draft_message_id {+ let _ = channel+ .finalize_draft(+ &msg.reply_target,+ draft_id,+ &error_text,+ msg.thread_ts.as_deref(),+ )+ .await;+ } else {+ let _ = channel+ .send_with_outbound_intent(+ &SendMessage::new(&error_text, &msg.reply_target)+ .in_thread(msg.thread_ts.clone()),+ )+ .await;+ }+ }+ (+ false,+ error_text,+ route.provider.clone(),+ route.model.clone(),+ )+ }+ };++ BUS.publish(DomainEvent::ChannelMessageProcessed {+ channel: msg.channel.clone(),+ message_id: msg.id.clone(),+ sender: msg.sender.clone(),+ reply_target: msg.reply_target.clone(),+ content: msg.content.clone(),+ thread_ts: msg.thread_ts.clone(),+ response: response_text,+ provider: response_provider,+ model: response_model,+ elapsed_ms: started_at.elapsed().as_millis() as u64,+ success,+ workspace_dir: ctx.workspace_dir.as_ref().clone(),+ });+}diff --git a/crates/openhuman-core/src/integrations/composio/client_part_01.rs b/crates/openhuman-core/src/integrations/composio/client_part_01.rsdeleted file mode 100644index a6aba5d4b6..0000000000--- a/crates/openhuman-core/src/integrations/composio/client_part_01.rs+++ /dev/null@@ -1,666 +0,0 @@-use std::sync::Arc;-use std::time::Duration;--use anyhow::Result;-use serde_json::{json, Value};--use crate::integrations::IntegrationClient;--use super::types::{- ComposioActiveTriggersResponse, ComposioAuthorizeResponse, ComposioAvailableTriggersResponse,- ComposioConnectionsResponse, ComposioCreateTriggerResponse, ComposioDeleteResponse,- ComposioDisableTriggerResponse, ComposioEnableTriggerResponse, ComposioExecuteResponse,- ComposioGithubReposResponse, ComposioToolkitsResponse, ComposioToolsResponse,-};--const POST_OAUTH_ACTION_RETRY_DELAY: Duration = Duration::from_secs(10);-/// Literal error fragments Composio's gateway emits during the post-OAuth-/// readiness gap. Matching is case-insensitive and substring-based so-/// trailing punctuation or wrapper text from the gateway does not silently-/// disable the retry.-const POST_OAUTH_AUTH_ERROR_STRINGS: &[&str] = &["connection error, try to authenticate"];-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 {- 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- }-- // ββ Tools βββββββββββββββββββββββββββββββββββββββββββββββββββββββ-- /// `GET /agent-integrations/composio/tools?toolkits=<csv>&tags=<csv>` β fetch- /// OpenAI function-calling schemas. Omit `toolkits` to get every enabled- /// toolkit's tools. `tags` narrows by Composio action tag (OR semantics β- /// multiple tags broaden the result).- 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- }-- // ββ Execute βββββββββββββββββββββββββββββββββββββββββββββββββββββ-- /// `POST /agent-integrations/composio/execute` β run a Composio- /// action and return the provider result + cost.- pub async fn execute_tool(- &self,- tool: &str,- arguments: Option<serde_json::Value>,- ) -> Result<ComposioExecuteResponse> {- self.execute_tool_with_connection(tool, arguments, None)- .await- }-- /// `POST /agent-integrations/composio/execute` β run a Composio action- /// against one specific connected account.- ///- /// `connection_id = None` preserves [`Self::execute_tool`]'s ambient-account- /// behavior. A non-empty id is forwarded as `connectionId`; the backend- /// verifies that the authenticated user owns it before dispatching.- pub async fn execute_tool_with_connection(- &self,- tool: &str,- arguments: Option<serde_json::Value>,- connection_id: Option<&str>,- ) -> Result<ComposioExecuteResponse> {- let tool = tool.trim();- if tool.is_empty() {- anyhow::bail!("composio.execute_tool: tool slug must not be empty");- }- // Egress spine (privacy epic S2, #4436): a Composio tool call ships the- // (already-normalized) arguments to the third-party provider β disclose- // the transfer before the round-trip. S4 will add an approval arm here.- let egress = crate::security::egress::EgressDescriptor::composio(tool);- // Local-only enforcement (privacy epic S7, #4441): refuse the external- // tool call under LocalOnly BEFORE disclosing or sending it.- crate::security::egress::enforce_egress(&egress)?;- crate::security::egress::emit_external_transfer(egress);- // PR #1827 routes all execute-side argument normalization- // (including the bare-date β RFC 3339 fix #1802 brought to- // `normalize_calendar_query_args` on `main`) through the- // centralized `prepare_execute_arguments` helper. The helper- // covers the same calendar query case and is the shared entry- // point for `composio_execute`, per-action tools, and direct-- // mode dispatch.- let arguments = super::execute_prepare::prepare_execute_arguments(tool, arguments)- .map_err(anyhow::Error::msg)?;- let connection_id = connection_id.map(str::trim).filter(|id| !id.is_empty());- tracing::debug!(- tool = %tool,- connection_id = ?connection_id,- "[composio] execute_tool"- );- let mut body = json!({ "tool": tool, "arguments": arguments });- if let Some(connection_id) = connection_id {- body["connectionId"] = json!(connection_id);- }- let mut resp = self- .execute_tool_with_post_oauth_retry(tool, &body, POST_OAUTH_ACTION_RETRY_DELAY)- .await?;- if !resp.successful {- if let Some(ref err) = resp.error {- resp.error = Some(super::error_mapping::format_provider_error(tool, err));- }- }- Ok(resp)- }-- /// `POST /agent-integrations/composio/execute` β single, non-retrying- /// HTTP round-trip. Use this when the caller owns the retry loop- /// (e.g. `auth_retry`) to avoid double-retry. In particular,- /// [`super::auth_retry::execute_with_auth_retry`] uses this entry- /// point so its `must retry exactly once` contract still holds- /// after PR #1707 introduced the inner retry.- pub(crate) async fn execute_tool_once(- &self,- tool: &str,- arguments: Option<serde_json::Value>,- ) -> Result<ComposioExecuteResponse> {- let tool = tool.trim();- if tool.is_empty() {- anyhow::bail!("composio.execute_tool_once: tool slug must not be empty");- }- // Egress spine (privacy epic S2, #4436): see `execute_tool`. This is the- // caller-owns-retry entry point (e.g. `auth_retry`), disjoint from- // `execute_tool`, so each logical tool call emits exactly once.- let egress = crate::security::egress::EgressDescriptor::composio(tool);- // Local-only enforcement (privacy epic S7, #4441): same gate as- // `execute_tool` β this disjoint entry point must block too.- crate::security::egress::enforce_egress(&egress)?;- crate::security::egress::emit_external_transfer(egress);- let arguments = super::execute_prepare::prepare_execute_arguments(tool, arguments)- .map_err(anyhow::Error::msg)?;- tracing::debug!(tool = %tool, "[composio] execute_tool_once (no built-in retry)");- let body = json!({ "tool": tool, "arguments": arguments });- let result = self.post_execute_tool(&body).await;- match &result {- Ok(resp) => tracing::debug!(- tool = %tool,- successful = resp.successful,- has_error = resp.error.is_some(),- "[composio] execute_tool_once completed"- ),- Err(err) => tracing::warn!(- tool = %tool,- error = %err,- "[composio] execute_tool_once failed"- ),- }- result.map_err(|e| {- anyhow::Error::msg(super::error_mapping::remap_transport_error(- tool,- &e.to_string(),- ))- })- }-- pub(super) async fn execute_tool_with_post_oauth_retry(- &self,- tool: &str,- body: &serde_json::Value,- retry_delay: Duration,- ) -> Result<ComposioExecuteResponse> {- tracing::debug!(- tool = %tool,- retry_delay_ms = retry_delay.as_millis() as u64,- attempt = 1u8,- "[composio] execute_tool_with_post_oauth_retry attempt"- );- let first = self.post_execute_tool(body).await?;- let should_retry = is_post_oauth_auth_readiness_error(&first);- tracing::debug!(- tool = %tool,- attempt = 1u8,- successful = first.successful,- has_error = first.error.is_some(),- should_retry,- "[composio] execute_tool_with_post_oauth_retry branch decision"- );- if !should_retry {- return Ok(first);- }-- tracing::warn!(- tool = %tool,- retry_delay_ms = retry_delay.as_millis() as u64,- "[composio] action returned post-OAuth auth-readiness error; retrying once"- );- if !retry_delay.is_zero() {- tokio::time::sleep(retry_delay).await;- }- tracing::debug!(- tool = %tool,- retry_delay_ms = retry_delay.as_millis() as u64,- attempt = 2u8,- "[composio] execute_tool_with_post_oauth_retry retry dispatch"- );- let retry = self.post_execute_tool(body).await;- match &retry {- Ok(resp) => tracing::debug!(- tool = %tool,- attempt = 2u8,- successful = resp.successful,- has_error = resp.error.is_some(),- "[composio] execute_tool_with_post_oauth_retry retry completed"- ),- Err(err) => tracing::debug!(- tool = %tool,- attempt = 2u8,- error = %err,- "[composio] execute_tool_with_post_oauth_retry retry failed"- ),- }- retry- }-- async fn post_execute_tool(&self, body: &serde_json::Value) -> Result<ComposioExecuteResponse> {- self.inner- .post::<ComposioExecuteResponse>("/agent-integrations/composio/execute", body)- .await- }-- /// `GET /agent-integrations/composio/github/repos` β list repositories- /// available via the user's authorized GitHub connected account.- 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- }-- // ββ 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.- 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::api::config::api_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)- .header("Authorization", format!("Bearer {}", self.inner.auth_token))- .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 is_post_oauth_auth_readiness_error(resp: &ComposioExecuteResponse) -> bool {- if resp.successful {- return false;- }- let Some(error) = resp.error.as_deref() else {- return false;- };- let normalized = error.trim().to_ascii_lowercase();- POST_OAUTH_AUTH_ERROR_STRINGS- .iter()- .any(|needle| normalized.contains(needle))-}--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_part_02.rs b/crates/openhuman-core/src/integrations/composio/client_part_02.rsdeleted file mode 100644index 14825aaf44..0000000000--- a/crates/openhuman-core/src/integrations/composio/client_part_02.rs+++ /dev/null@@ -1,473 +0,0 @@--/// Backend-mode [`ComposioClient`] constructor. **Internal to the-/// composio module** β external callers should use-/// [`create_composio_client`] (factory) or-/// [`crate::agent::harness::subagent_runner::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, and heartbeat calendar collector 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 auth token come from the shared-/// core defaults (`config.api_url` plus the app-session JWT) via-/// [`crate::integrations::build_client`]. The only reason-/// this returns `None` is that the user isn't signed in to the backend-/// (no JWT). Direct-mode availability is orthogonal β see-/// [`create_composio_client`].-pub(super) 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 `crates/openhuman-core/src/inference/embeddings/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};--// 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`-// values get treated as fresh variable bindings in pattern position-// (Rust's pattern grammar accepts only path-qualified constants), so-// pulling them in here resolves to the same `&'static str` values-// without the "unreachable pattern" warning chain.-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/*`).-///-/// `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>),-}--pub(crate) fn create_direct_composio_tool_for_api_key(- config: &crate::config::Config,- api_key: &str,-) -> anyhow::Result<Arc<crate::tools::ComposioTool>> {- 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());- #[cfg(debug_assertions)]- let tool = 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(config.composio.entity_id.as_str()),- 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(config.composio.entity_id.as_str()),- security,- ),- };- #[cfg(not(debug_assertions))]- let tool = crate::tools::ComposioTool::new(- api_key,- Some(config.composio.entity_id.as_str()),- 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,- }- }-}--/// Construct a [`ComposioClientKind`] from the root config.-///-/// 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.-/// - `"direct"` β BYO key against `backend.composio.dev`. Requires a-/// stored Composio API key under the-/// [`crate::security::credentials::COMPOSIO_DIRECT_PROVIDER`]-/// slot **or** an `api_key` value in `config.composio.api_key`. The-/// stored key takes precedence so the encrypted keychain remains the-/// source of truth β `config.toml` is a fallback for power users.-///-/// 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> {- let mode = config.composio.mode.trim();- tracing::debug!(mode = %mode, "[composio-factory] resolving client");-- match mode {- // Empty string is treated as the default for forward compatibility- // with hand-edited configs that omit the field β `serde(default)`- // 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!(- "composio backend mode unavailable: no backend session token. \- Sign in first (auth_store_session)."- )- })?;- tracing::debug!("[composio-factory] resolved backend variant");- Ok(ComposioClientKind::Backend(client))- }- MODE_DIRECT_PAT => {- // Prefer keychain-stored key; fall back to `config.toml`.- let stored = crate::security::credentials::get_composio_api_key(config)- .map_err(|e| anyhow::anyhow!("failed to read stored composio api key: {e}"))?;- let api_key = stored- .or_else(|| {- config- .composio- .api_key- .as_ref()- .map(|k| k.trim().to_string())- .filter(|k| !k.is_empty())- })- .ok_or_else(|| {- anyhow::anyhow!(- "composio direct mode selected but no api key is configured \- (set via composio.set_api_key RPC or config.composio.api_key)"- )- })?;-- let tool = create_direct_composio_tool_for_api_key(config, &api_key)?;- tracing::debug!(- key_len = api_key.len(),- "[composio-factory] resolved direct variant (key redacted)"- );- Ok(ComposioClientKind::Direct(tool))- }- unknown => {- tracing::warn!(mode = %unknown, "[composio-factory] unknown composio mode");- Err(anyhow::anyhow!(- "unknown composio mode: \"{unknown}\". Supported: \"backend\", \"direct\""- ))- }- }-}--// ββ Direct-mode response reshapers ββββββββββββββββββββββββββββββββββ-//-// The direct-mode `ComposioTool` (in `composio/tools/direct.rs`)-// speaks `backend.composio.dev/api/v3/*` natively. The helpers below-// reshape those v3 responses into the same envelopes the-// backend-proxied [`ComposioClient`] returns, so callers in `ops.rs` /-// `tools.rs` don't have to branch on mode for downstream concerns-// (event-bus shape, log format, frontend type contract).-//-// All three helpers live next to the factory so anyone touching the-// direct-mode plumbing can see the full envelope-translation surface-// in one place.--use super::{direct_auth, types::ComposioConnection};--/// Direct-mode counterpart to [`ComposioClient::authorize`]. Calls-/// Composio v3 `/connected_accounts/link` via-/// [`crate::tools::ComposioTool::get_connection_url`] and-/// reshapes the response into the [`ComposioAuthorizeResponse`] the-/// backend-proxied path emits.-///-/// The v3 endpoint returns a redirect URL but does NOT (currently)-/// surface a stable `connection_id` in the same call β the connection-/// row is created lazily when the user completes OAuth on Composio's-/// hosted page. To preserve the response contract the frontend already-/// consumes, we emit an empty `connection_id` for now. The 5 s-/// `list_connections` poll (now live in direct mode too β see-/// [`direct_list_connections`]) is what ultimately surfaces the new-/// row to the UI.-pub(super) async fn direct_authorize(- direct: &Arc<crate::tools::ComposioTool>,- toolkit: &str,- entity_id: &str,-) -> anyhow::Result<ComposioAuthorizeResponse> {- let toolkit = toolkit.trim();- if toolkit.is_empty() {- anyhow::bail!("composio direct authorize: toolkit must not be empty");- }- let entity_id = entity_id.trim();- let entity_id = if entity_id.is_empty() {- "default"- } else {- entity_id- };- tracing::debug!(- toolkit = %toolkit,- entity_id = %entity_id,- "[composio-direct] authorize: requesting hosted connect URL"- );- let connect_url = direct- .get_connection_url(Some(toolkit), None, entity_id)- .await?;- tracing::debug!(- toolkit = %toolkit,- url_len = connect_url.len(),- "[composio-direct] authorize: got connect url (redacted)"- );- Ok(ComposioAuthorizeResponse {- connect_url,- // No stable connection id in the v3 link response β see fn-level- // doc. The frontend uses `connectUrl` to open the browser and- // `listConnections` polling to detect the resulting row.- connection_id: String::new(),- })-}--/// Direct-mode counterpart to [`ComposioClient::execute_tool`]. Mirrors-/// the v3 `/tools/{slug}/execute` envelope into [`ComposioExecuteResponse`]-/// so the caller doesn't branch on mode for the-/// `ComposioActionExecuted` event-bus payload or the-/// markdown-vs-JSON-body preference.-///-/// Direct mode runs without the backend's billing margin, so `cost_usd`-/// is reported as `0.0`. The backend's `markdownFormatted` field is-/// likewise specific to the backend-proxied path and remains `None` for-/// direct callers, which fall back to the raw JSON envelope.-pub async fn direct_execute(- direct: &Arc<crate::tools::ComposioTool>,- tool: &str,- arguments: Option<serde_json::Value>,- entity_id: &str,- connection_id: Option<&str>,-) -> anyhow::Result<ComposioExecuteResponse> {- let tool = tool.trim();- if tool.is_empty() {- anyhow::bail!("composio direct_execute: tool slug must not be empty");- }- let params = arguments.unwrap_or_else(|| serde_json::Value::Object(Default::default()));- let entity_id = entity_id.trim();- let entity_id_opt = (!entity_id.is_empty()).then_some(entity_id);- let conn_id = connection_id.map(str::trim).filter(|s| !s.is_empty());- tracing::debug!(- tool = %tool,- has_entity = entity_id_opt.is_some(),- connection_id = ?conn_id,- "[composio-direct] execute: invoking v3 /tools/{{slug}}/execute"- );- let raw = direct- .execute_action(tool, params, entity_id_opt, conn_id)- .await?;- // v3 surfaces `successful` + `data` + `error` at the top level. If- // none are present, treat the call as success so callers see the- // raw payload instead of an empty error envelope.- let successful = raw- .get("successful")- .and_then(serde_json::Value::as_bool)- .or_else(|| raw.get("success").and_then(serde_json::Value::as_bool))- .unwrap_or(true);- let error = raw- .get("error")- .and_then(serde_json::Value::as_str)- .map(str::to_string);- let data = raw.get("data").cloned().unwrap_or(raw);- Ok(ComposioExecuteResponse {- data,- successful,- error,- cost_usd: 0.0,- markdown_formatted: None,- })-}--/// Direct-mode counterpart to [`ComposioClient::list_connections`].-///-/// Calls Composio v3 `/connected_accounts` (via-/// [`crate::tools::ComposioTool::list_connected_accounts`])-/// and maps each item to the canonical [`ComposioConnection`] so the-/// existing frontend type contract and the 5 s UI poll keep working-/// unchanged.-///-/// Toolkit slug, status, and `created_at` are extracted defensively β-/// missing or unparseable fields fall back to empty strings / `None`-/// rather than dropping the row. The status filter applied downstream-/// (`ComposioConnection::is_active`) treats empty status as inactive,-/// so a malformed row will simply not be presented as connected β the-/// fail-safe shape the user expects.-pub async fn direct_list_connections(- direct: &Arc<crate::tools::ComposioTool>,-) -> anyhow::Result<ComposioConnectionsResponse> {- tracing::debug!("[composio-direct] list_connections: GET v3 /connected_accounts");- let key_id = direct.auth_key_fingerprint();- if let Some(error) = direct_auth::direct_auth_backoff_error(key_id) {- tracing::warn!(- "[composio-direct] list_connections: direct API key backoff gate open; \- skipping v3 /connected_accounts"- );- anyhow::bail!("{error}");- }-- let items = match direct.list_connected_accounts().await {- Ok(items) => {- direct_auth::record_direct_auth_success(key_id);- items- }- Err(error) => {- let rendered = format!("{error:#}");- match direct_auth::record_direct_auth_failure(key_id, &rendered) {- direct_auth::DirectAuthFailureDecision::NotAuthFailure => {}- direct_auth::DirectAuthFailureDecision::RetryAllowed { consecutive } => {- tracing::warn!(- consecutive,- threshold = direct_auth::DIRECT_INVALID_API_KEY_THRESHOLD,- "[composio-direct] list_connections: direct API key rejected"- );- }- direct_auth::DirectAuthFailureDecision::CircuitOpened { consecutive } => {- let backoff = direct_auth::invalid_api_key_backoff_message(consecutive);- tracing::warn!(- consecutive,- threshold = direct_auth::DIRECT_INVALID_API_KEY_THRESHOLD,- "[composio-direct] list_connections: direct API key backoff gate opened"- );- anyhow::bail!("{backoff}");- }- }- return Err(error);- }- };- let connections: Vec<ComposioConnection> = items- .into_iter()- .filter_map(|item| {- let id = item.id.trim().to_string();- if id.is_empty() {- return None;- }- let toolkit = item.toolkit_slug().unwrap_or_default();- let status = item.status.clone().unwrap_or_default();- Some(ComposioConnection {- id,- toolkit,- status,- created_at: item.created_at.clone(),- // Identity fields are populated by- // `enrich_connections_with_identity` in ops.rs after- // the full list is fetched, using cached profile data.- account_email: None,- workspace: None,- username: None,- })- })- .collect();- tracing::debug!(- count = connections.len(),- "[composio-direct] list_connections: mapped v3 connected accounts"- );- Ok(ComposioConnectionsResponse { connections })-}--/// Direct-mode counterpart to [`ComposioClient::list_tools`]. Calls-/// Composio v3 `/tools?toolkits=<csv>&tags=<a>&tags=<b>` via-/// [`crate::tools::ComposioTool::list_tool_schemas_v3`] and-/// reshapes each item into the same [`ComposioToolSchema`] envelope the-/// backend-proxied path returns.-///-/// `toolkits` may be empty (full direct-tenant catalogue) or scoped to-/// the user's connected toolkits (preferred β keeps response size bounded-/// and skips schemas the agent can't actually call). `composio_list_tools`'s-/// direct branch passes `direct_list_connections`'s active set.-///-/// `tags` mirrors the backend path's tag filter so a self-key user's-/// `composio_list_tools(..., tags)` request narrows by Composio action tag-/// in direct mode too (previously the tag filter was silently dropped on-/// the direct branch). The caller is expected to have already applied-/// [`super::ops::should_forward_tags`] before passing `tags` here.-///-/// Schemas surfaced here are tenant-agnostic β Composio's action-/// definitions are the same across tenants, so direct-mode users get-/// the same model-callable shape backend-mode does. Downstream curated--/// whitelist filtering (`evaluate_tool_visibility` / `find_curated`)-/// still applies at the `ops::composio_list_tools` layer.-///-/// `pub(crate)` (widened from `pub(super)`) so-/// `catalog::fetch_raw_toolkit_tools` can call this directly for-/// the LIVE (uncurated) tool-contract catalog the Workflow builder grounds-/// against β that caller deliberately bypasses `composio_list_tools`'s-/// curated-whitelist filter (`filter_list_tools_response_for_direct`),-/// which this function never applies itself; the filter is layered on by-/// its `composio_list_tools` caller, not baked in here.-pub(crate) async fn direct_list_tools(- direct: &Arc<crate::tools::ComposioTool>,- toolkits: &[String],- tags: Option<&[String]>,-) -> anyhow::Result<ComposioToolsResponse> {- let toolkit_refs: Vec<&str> = toolkits.iter().map(|s| s.as_str()).collect();- let tag_refs: Option<Vec<&str>> = tags.map(|t| t.iter().map(|s| s.as_str()).collect());- tracing::debug!(- toolkits = toolkit_refs.len(),- tags = tag_refs.as_ref().map(Vec::len).unwrap_or(0),- "[composio-direct] list_tools: GET v3 /tools"- );- let items = direct- .list_tool_schemas_v3(&toolkit_refs, tag_refs.as_deref())- .await?;- let tools: Vec<super::types::ComposioToolSchema> = items- .into_iter()- .filter(|item| !item.slug.is_empty())- .map(|item| super::types::ComposioToolSchema {- kind: "function".to_string(),- function: super::types::ComposioToolFunction {- name: item.slug,- description: item.description,- parameters: item.input_parameters,- output_parameters: item.output_parameters,- },- })- .collect();- tracing::debug!(- count = tools.len(),- "[composio-direct] list_tools: mapped v3 tool schemas"- );- Ok(ComposioToolsResponse { tools })-}