Skip to content

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

feat(integrations): add gmail integration module

Steven Enamakelbffca5db4367
diff --git a/crates/openhuman-core/src/integrations/composio/orchestrator_actions.rs b/crates/openhuman-core/src/integrations/composio/orchestrator_actions.rs
new file mode 100644
index 0000000000..9739de66b6
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/orchestrator_actions.rs
@@ -0,0 +1,158 @@
+//! Dynamic orchestrator tool generation.
+//!
+//! The orchestrator delegates specialist work through the single
+//! `spawn_subagent(agent_id, prompt)` tool. `AgentId` entries in its
+//! `[subagents]` allowlist constrain that tool; they do not create additional
+//! model-facing tools.
+//!
+//! For [`SubagentEntry::Skills`] wildcard expansions we synthesize one
+//! `ToolExposure::Deferred` [`ComposioActionTool`] per action of every
+//! connected Composio toolkit. Those never reach the wire: a belt that opted
+//! into discovery (`tool_search` in its `[tools] named`) finds them through
+//! the harness's `tool_search` bridge and calls them directly.
+//!
+//! Called from [`crate::agent::session_host::builder`] at
+//! agent-build time, with the orchestrator's own definition and the current
+//! list of connected Composio integrations.
+//! [`SubagentEntry::AgentId`]: tinyagents_definition::SubagentEntry::AgentId
+//! [`SubagentEntry::Skills`]: tinyagents_definition::SubagentEntry::Skills
+
+use crate::agent_registry::host_definition::AgentDefinition;
+use crate::integrations::composio::ComposioActionTool;
+use crate::integrations::ConnectedIntegration;
+use tinyagents_definition::SubagentEntry;
+
+use tinytools::Tool;
+
+/// Return deferred integration actions for the agent's skills wildcard.
+///
+/// `AgentId` entries only configure the `spawn_subagent` allowlist; they do
+/// not create additional model-facing tools.
+///
+/// Each [`SubagentEntry::Skills`] wildcard expands to the connected
+/// integrations' actions as `Deferred` tools
+/// ([`collect_deferred_integration_actions`]): off the wire, reachable
+/// through the harness's `tool_search`, and callable directly by the agent
+/// that found them. No delegation tool is synthesised for the wildcard.
+///
+/// Entries that reference unknown agent ids (not in the registry) are
+/// logged at `warn` and skipped — the orchestrator still builds, just
+/// without the broken delegation. A Skills wildcard with an empty
+/// `connected_integrations` slice produces zero tools, which is the correct
+/// behaviour when the user has not yet connected any integrations.
+///
+/// Returns an empty Vec when there are no connected integration actions.
+pub fn collect_orchestrator_tools(
+ definition: &AgentDefinition,
+ connected_integrations: &[ConnectedIntegration],
+) -> Vec<Box<dyn Tool>> {
+ let mut tools: Vec<Box<dyn Tool>> = Vec::new();
+
+ for entry in &definition.subagents {
+ match entry {
+ SubagentEntry::AgentId(agent_id) => {
+ log::debug!(
+ "[orchestrator_tools] agent '{}' is allowed through spawn_subagent(agent_id)",
+ agent_id
+ );
+ }
+ SubagentEntry::Skills(wildcard) => {
+ if !wildcard.matches_all() {
+ log::warn!(
+ "[orchestrator_tools] subagent skills wildcard '{}' referenced by '{}' is not supported (only \"*\") — skipping",
+ wildcard.skills,
+ definition.id
+ );
+ continue;
+ }
+ // The connected toolkits' actions, one `Deferred` tool each.
+ // Never on the wire: a belt that opted into discovery reaches
+ // them through the harness's `tool_search`, so one clear
+ // action is a search and a call. A belt that did not opt in
+ // never sees them — the session builder leaves them
+ // prompt-hidden, which the direct-call gate refuses. Approval
+ // and channel permission apply per call. This used to sit
+ // beside a per-toolkit sub-agent route; searchable actions
+ // are directly callable through the harness.
+ let actions = collect_deferred_integration_actions(connected_integrations);
+ if !actions.is_empty() {
+ log::debug!(
+ "[orchestrator_tools] registering {} deferred integration action tool(s)",
+ actions.len()
+ );
+ tools.extend(actions);
+ }
+ }
+ }
+ }
+
+ log::info!(
+ "[orchestrator_tools] assembled {} deferred integration tool(s) for agent '{}' ({} integrations connected)",
+ tools.len(),
+ definition.id,
+ connected_integrations.len()
+ );
+
+ tools
+}
+
+/// One `ToolExposure::Deferred` [`ComposioActionTool`] per action of every
+/// connected integration, sorted by toolkit then action so the synthesised
+/// set — and with it the tool specs a session freezes — is stable across
+/// reconciles whatever order the backend returns.
+///
+/// Gated actions are left out: the model cannot call them and the prompt's
+/// Connected Integrations section already explains how to unlock them.
+/// A collision on an action slug across two toolkits keeps the first
+/// arrival.
+pub fn collect_deferred_integration_actions(
+ connected_integrations: &[ConnectedIntegration],
+) -> Vec<Box<dyn Tool>> {
+ let mut integrations: Vec<&ConnectedIntegration> = connected_integrations
+ .iter()
+ .filter(|integration| integration.connected)
+ .collect();
+ integrations.sort_by(|a, b| a.toolkit.cmp(&b.toolkit));
+ let mut seen: std::collections::HashSet<&str> = std::collections::HashSet::new();
+ let mut tools: Vec<Box<dyn Tool>> = Vec::new();
+ for integration in integrations {
+ let mut actions: Vec<&crate::integrations::ConnectedIntegrationTool> =
+ integration.tools.iter().collect();
+ actions.sort_by(|a, b| a.name.cmp(&b.name));
+ for action in actions {
+ if action.name.trim().is_empty() || !seen.insert(action.name.as_str()) {
+ continue;
+ }
+ tools.push(Box::new(ComposioActionTool::deferred(
+ &integration.toolkit,
+ action.name.clone(),
+ action.description.clone(),
+ action.parameters.clone(),
+ )));
+ }
+ }
+ tools
+}
+
+/// Produce a tool-name-safe slug from a free-form integration id.
+/// Allows ASCII alphanumerics and underscores; everything else becomes
+/// an underscore. OpenAI-style function names only accept
+/// `[a-zA-Z0-9_-]{1,64}`, so this is the conservative subset.
+///
+/// Used when rendering integration slugs in prompts so the prompt and any
+/// argument-facing enum agree on slug canonicalisation.
+pub(crate) fn sanitise_slug(raw: &str) -> String {
+ raw.chars()
+ .map(|c| {
+ if c.is_ascii_alphanumeric() || c == '_' {
+ c.to_ascii_lowercase()
+ } else {
+ '_'
+ }
+ })
+ .collect()
+}
+
+#[cfg(test)]
+#[path = "orchestrator_tools_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/integrations/composio/orchestrator_actions_tests.rs b/crates/openhuman-core/src/integrations/composio/orchestrator_actions_tests.rs
new file mode 100644
index 0000000000..9d6ccf5d20
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/orchestrator_actions_tests.rs
@@ -0,0 +1,62 @@
+use super::*;
+use tinyagents_definition::{
+ DefinitionSource, ModelSpec, PromptSource, SandboxMode, SkillsWildcard, ToolScope,
+};
+
+fn orchestrator() -> AgentDefinition {
+ AgentDefinition {
+ id: "orchestrator".into(),
+ when_to_use: String::new(),
+ display_name: None,
+ system_prompt: PromptSource::Inline(String::new()),
+ model: ModelSpec::Inherit,
+ temperature: 0.4,
+ tools: ToolScope::Wildcard,
+ disallowed_tools: vec![],
+ skill_filter: None,
+ extra_tools: vec![],
+ deferred_tools: Vec::new(),
+ tool_rules: None,
+ max_iterations: 8,
+ iteration_policy: Default::default(),
+ max_result_chars: None,
+ max_turn_output_tokens: None,
+ timeout_secs: None,
+ sandbox_mode: SandboxMode::None,
+ background: false,
+ subagents: vec![
+ SubagentEntry::AgentId("image_agent".into()),
+ SubagentEntry::AgentId("research_agent".into()),
+ SubagentEntry::Skills(SkillsWildcard { skills: "*".into() }),
+ ],
+ delegate_name: None,
+ agent_tier: tinyagents_definition::AgentTier::Worker,
+ source: DefinitionSource::Builtin,
+ extensions: crate::agent_registry::host_definition::AgentExt {
+ omit_identity: true,
+ omit_memory_context: true,
+ omit_safety_preamble: true,
+ tokenjuice_compression: tinyjuice_bus::types::AgentTokenjuiceCompression::Auto,
+ searches_connected_mcp: false,
+ ..Default::default()
+ },
+ role: None,
+ }
+}
+
+#[test]
+fn agent_id_allowlist_entries_do_not_synthesize_model_facing_dispatch_tools() {
+ let tools = collect_orchestrator_tools(&orchestrator(), &[]);
+
+ assert!(tools.is_empty());
+ let spawn = crate::agent::registration::dialogue_tools(
+ std::path::Path::new("."),
+ &crate::config::Config::default(),
+ );
+ let subagent_tools: Vec<_> = spawn
+ .iter()
+ .filter(|tool| tool.name().contains("subagent") || tool.name().starts_with("delegate_"))
+ .map(|tool| tool.name())
+ .collect();
+ assert_eq!(subagent_tools, ["spawn_subagent"]);
+}
diff --git a/crates/openhuman-core/src/integrations/gmail/mod.rs b/crates/openhuman-core/src/integrations/gmail/mod.rs
new file mode 100644
index 0000000000..5199419d03
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/gmail/mod.rs
@@ -0,0 +1,5 @@
+//! Gmail integration tools.
+
+mod unsubscribe_tool;
+
+pub use unsubscribe_tool::GmailUnsubscribeTool;
diff --git a/crates/openhuman-core/src/integrations/gmail/unsubscribe_tool.rs b/crates/openhuman-core/src/integrations/gmail/unsubscribe_tool.rs
new file mode 100644
index 0000000000..8634a12288
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/gmail/unsubscribe_tool.rs
@@ -0,0 +1,97 @@
+use async_trait::async_trait;
+use tinytools::{Tool, ToolCategory, ToolResult};
+
+pub struct GmailUnsubscribeTool;
+
+#[async_trait]
+impl Tool for GmailUnsubscribeTool {
+ fn name(&self) -> &str {
+ "gmail_unsubscribe"
+ }
+
+ fn description(&self) -> &str {
+ "Initiates an unsubscribe request for an email sender. Requires the exact List-Unsubscribe header value and the sender's name/email to ask the user for confirmation."
+ }
+
+ fn parameters_schema(&self) -> serde_json::Value {
+ serde_json::json!({
+ "type": "object",
+ "properties": {
+ "sender": {
+ "type": "string",
+ "description": "The name and email address of the sender you are unsubscribing from."
+ },
+ "unsubscribe_link": {
+ "type": "string",
+ "description": "The exact URL or mailto link extracted from the List-Unsubscribe header."
+ }
+ },
+ "required": ["sender", "unsubscribe_link"]
+ })
+ }
+
+ fn category(&self) -> ToolCategory {
+ ToolCategory::Workflow
+ }
+
+ // Intentionally NOT marked external_effect=true in v1.
+ //
+ // `execute()` below does NOT perform the unsubscribe itself —
+ // it returns a `pending_approval` JSON payload that the React
+ // UI intercepts and gates with its own legacy confirmation
+ // flow. Marking this tool external_effect=true would route the
+ // call through the new `ApprovalGate` AND the legacy UI prompt,
+ // so users would see two consecutive approval dialogs while the
+ // real side effect still lived outside core enforcement.
+ //
+ // Follow-up #1339-v3: move the actual outbound unsubscribe
+ // into `execute()`, retire the legacy UI prompt, and then flip
+ // `external_effect = true` here.
+
+ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {
+ let sender = args
+ .get("sender")
+ .and_then(|v| v.as_str())
+ .unwrap_or("Unknown Sender");
+
+ let redacted_sender = if let Some(idx) = sender.find('@') {
+ format!("***{}", &sender[idx..])
+ } else {
+ "***".to_string()
+ };
+ tracing::debug!("GMAIL_UNSUBSCRIBE:ENTRY sender={}", redacted_sender);
+
+ let link = args
+ .get("unsubscribe_link")
+ .and_then(|v| v.as_str())
+ .unwrap_or("");
+
+ if link.is_empty() {
+ tracing::debug!("GMAIL_UNSUBSCRIBE:VALIDATION:EMPTY_LINK");
+ return Ok(ToolResult::error(
+ "Cannot unsubscribe without a valid List-Unsubscribe link.",
+ ));
+ }
+
+ tracing::debug!(
+ "GMAIL_UNSUBSCRIBE:PENDING_APPROVAL sender={} action=unsubscribe status=pending_approval",
+ redacted_sender
+ );
+
+ // Return a structured JSON block indicating a Pending Action.
+ // The React UI will intercept this exact payload.
+ Ok(ToolResult::json(serde_json::json!({
+ "status": "pending_approval",
+ "action": "unsubscribe",
+ "metadata": {
+ "sender": sender,
+ "unsubscribe_link": link,
+ "message": format!("The agent is requesting permission to unsubscribe you from: {}", sender)
+ }
+ })))
+ }
+}
+
+#[cfg(test)]
+#[path = "unsubscribe_tool_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/integrations/gmail/unsubscribe_tool_tests.rs b/crates/openhuman-core/src/integrations/gmail/unsubscribe_tool_tests.rs
new file mode 100644
index 0000000000..fcfc1f9dcd
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/gmail/unsubscribe_tool_tests.rs
@@ -0,0 +1,66 @@
+use super::*;
+use tinytools::ToolContent;
+
+#[tokio::test]
+async fn test_gmail_unsubscribe_valid() {
+ let tool = GmailUnsubscribeTool;
+ let result = tool
+ .execute(serde_json::json!({
+ "sender": "[email protected]",
+ "unsubscribe_link": "https://example.com/unsub"
+ }))
+ .await
+ .unwrap();
+
+ assert!(!result.is_error);
+ let mut has_json = false;
+ for content in result.content {
+ if let ToolContent::Json { data: value } = content {
+ assert_eq!(value["status"].as_str().unwrap(), "pending_approval");
+ assert_eq!(value["action"].as_str().unwrap(), "unsubscribe");
+ assert_eq!(
+ value["metadata"]["sender"].as_str().unwrap(),
+ );
+ assert_eq!(
+ value["metadata"]["unsubscribe_link"].as_str().unwrap(),
+ "https://example.com/unsub"
+ );
+ has_json = true;
+ }
+ }
+ assert!(has_json, "Expected JSON result");
+}
+
+#[tokio::test]
+async fn test_gmail_unsubscribe_empty_link() {
+ let tool = GmailUnsubscribeTool;
+ let result = tool
+ .execute(serde_json::json!({
+ "sender": "[email protected]",
+ "unsubscribe_link": ""
+ }))
+ .await
+ .unwrap();
+
+ assert!(result.is_error);
+ assert!(result
+ .text()
+ .contains("without a valid List-Unsubscribe link"));
+}
+
+#[tokio::test]
+async fn test_gmail_unsubscribe_missing_link() {
+ let tool = GmailUnsubscribeTool;
+ let result = tool
+ .execute(serde_json::json!({
+ "sender": "[email protected]"
+ }))
+ .await
+ .unwrap();
+
+ assert!(result.is_error);
+ assert!(result
+ .text()
+ .contains("without a valid List-Unsubscribe link"));
+}
diff --git a/crates/openhuman-core/src/integrations/mod.rs b/crates/openhuman-core/src/integrations/mod.rs
index 091017046d..d88f1a2bc8 100644
--- a/crates/openhuman-core/src/integrations/mod.rs
+++ b/crates/openhuman-core/src/integrations/mod.rs
@@ -10,6 +10,7 @@
pub(crate) mod announcement_notes;
pub mod composio;
+pub mod gmail;
mod connected_identities;
pub(crate) mod recorded_tools;
pub mod task_sources;