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
feat(composio): add scope and slug contract helpers
Steven Enamakel9e8d02422c84
diff --git a/crates/openhuman-core/src/integrations/composio/contract/scopes.rs b/crates/openhuman-core/src/integrations/composio/contract/scopes.rsdeleted file mode 100644index f4c9e7be10..0000000000--- a/crates/openhuman-core/src/integrations/composio/contract/scopes.rs+++ /dev/null@@ -1,299 +0,0 @@-//! How invasive an action is, and how much of that the user has agreed to.-//!-//! Composio publishes sixty-odd actions per toolkit and most of them are noise-//! for an agent's planning loop, so each provider hand-curates a slice of-//! [`CuratedTool`] entries that pares the surface down and tags every action-//! with a [`ToolScope`]. The user's [`UserScopePref`] then gates execution per-//! toolkit: reads and writes on by default, destructive and permission-changing-//! actions off until explicitly opted into.-//!-//! # Why the classification (and now the catalogs) live here-//!-//! Two different consumers ask the same question from opposite sides of the-//! module boundary. The host asks it when it renders the integrations panel and-//! when it filters the agent's visible tool list; the sync pipelines ask it-//! inside the module before firing an action. Both have to reach the same-//! verdict, which makes [`ToolScope`], [`UserScopePref::allows`] and the-//! heuristic fallback [`classify_unknown`] shared vocabulary rather than either-//! side's private policy.-//!-//! The catalogs themselves — thousands of `&'static str` action slugs across-//! thirty toolkits — live alongside this module, in [`super::catalogs`]-//! (moved here from the engine crate by OpenHuman#5560, for the same reason-//! the classification lives here: both sides of the module boundary need the-//! same answer, and a contract-crate lookup is the only way to get it without-//! either side linking the other). They are provider data, they change-//! whenever a provider does, and nothing about them has to cross a frame: what-//! crosses is the verdict.-//!-//! Reading and writing a preference is likewise the engine crate's; this module-//! defines what a preference *is*, not where it is stored.--use serde::{Deserialize, Serialize};--/// Classification of how invasive an action is.-///-/// Used both to filter the agent's visible tool list and to enforce per-user-/// scope preferences at execution time. The serde form is lowercase and is-/// persisted inside a [`UserScopePref`] key/value row.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]-#[serde(rename_all = "lowercase")]-pub enum ToolScope {- /// Pure reads — `GET` / `FETCH` / `LIST` / `SEARCH` / `GET_PROFILE`.- Read,- /// Side-effectful actions that create or mutate user data —- /// `SEND` / `CREATE` / `UPDATE` / `REPLY` / `APPEND`.- Write,- /// Destructive or permission-changing actions — `DELETE` / `TRASH` /- /// `REMOVE` / `MODIFY_LABELS` / `SHARE`.- Admin,-}--impl ToolScope {- /// Stable lowercase tag, matching the serde representation.- pub fn as_str(self) -> &'static str {- match self {- ToolScope::Read => "read",- ToolScope::Write => "write",- ToolScope::Admin => "admin",- }- }-}--/// One curated entry in a provider's tool catalog.-///-/// `slug` is the Composio action slug as the toolkit listing returns it, e.g.-/// `"GMAIL_SEND_EMAIL"`. `scope` controls whether the action is gated by the-/// user's read / write / admin preference.-///-/// Deliberately `&'static str` and `Copy`: catalogs are `const` slices built at-/// compile time, and giving this owned `String` fields would turn thirty static-/// tables into thirty heap allocations at startup for no gain.-#[derive(Debug, Clone, Copy)]-pub struct CuratedTool {- /// The Composio action slug, e.g. `"GMAIL_SEND_EMAIL"`.- pub slug: &'static str,- /// How invasive the action is, for preference gating.- pub scope: ToolScope,-}--/// Per-toolkit scope preference.-///-/// Defaults are `read = true`, `write = true`, `admin = false` — the agent can-/// use a connected integration productively out of the box, but destructive and-/// permission-changing actions require an explicit opt-in.-///-/// The two `default_true` helpers matter for decoding: a row written before a-/// field existed must not read back as "denied", which is what a bare-/// `#[serde(default)]` would give a `bool`.-#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]-pub struct UserScopePref {- /// Whether the agent may call [`ToolScope::Read`] actions.- #[serde(default = "default_true")]- pub read: bool,- /// Whether the agent may call [`ToolScope::Write`] actions.- #[serde(default = "default_true")]- pub write: bool,- /// Whether the agent may call [`ToolScope::Admin`] actions.- #[serde(default)]- pub admin: bool,-}--fn default_true() -> bool {- true-}--impl Default for UserScopePref {- fn default() -> Self {- Self {- read: true,- write: true,- admin: false,- }- }-}--impl UserScopePref {- /// Whether the given scope is enabled in this preference.- pub fn allows(&self, scope: ToolScope) -> bool {- match scope {- ToolScope::Read => self.read,- ToolScope::Write => self.write,- ToolScope::Admin => self.admin,- }- }-}--/// Heuristic fallback for gating a tool that is not in any provider's curated-/// list.-///-/// Prefer the curated classification when one exists; only reach for this when-/// a toolkit has no catalog or the catalog does not mention the slug. Admin-/// verbs are checked first so `MODIFY_LABELS` does not slip into the write-/// bucket on the `UPDATE` substring rule — the ordering is the whole point of-/// the function and not an implementation detail.-pub fn classify_unknown(slug: &str) -> ToolScope {- let upper = slug.to_ascii_uppercase();- const ADMIN: &[&str] = &[- "DELETE",- "TRASH",- "REMOVE",- "MODIFY_LABELS",- "SHARE",- "REVOKE",- "DESTROY",- ];- const WRITE: &[&str] = &[- "SEND", "CREATE", "UPDATE", "REPLY", "APPEND", "INSERT", "ADD", "POST", "PATCH", "WRITE",- "DRAFT",- ];- if ADMIN.iter().any(|kw| upper.contains(kw)) {- return ToolScope::Admin;- }- if WRITE.iter().any(|kw| upper.contains(kw)) {- return ToolScope::Write;- }- ToolScope::Read-}--/// Look up a slug inside a curated catalog, case-insensitively.-pub fn find_curated<'a>(catalog: &'a [CuratedTool], slug: &str) -> Option<&'a CuratedTool> {- catalog.iter().find(|t| t.slug.eq_ignore_ascii_case(slug))-}--/// Toolkits whose identifier itself contains an underscore, so the first-/// segment of their action slugs is not the toolkit: `(action prefix, toolkit)`.-/// Their real action slugs carry the prefix as written.-const MULTI_SEGMENT_TOOLKIT_PREFIXES: &[(&str, &str)] = &[- ("MICROSOFT_TEAMS_", "microsoft_teams"),- ("ONE_DRIVE_", "one_drive"),- ("ZOHO_MAIL_", "zoho_mail"),- ("GOOGLE_MAPS_", "google_maps"),-];--/// Spellings models use for toolkits whose real slugs have no separator-/// (`GOOGLE_DRIVE_FIND_FILE` for `GOOGLEDRIVE_FIND_FILE`):-/// `(alias prefix, toolkit, canonical action prefix)`. Without them the first-/// segment, `google`, names a toolkit that does not exist.-const ALIASED_TOOLKIT_PREFIXES: &[(&str, &str, &str)] = &[- ("GOOGLE_DRIVE_", "googledrive", "GOOGLEDRIVE_"),- ("GOOGLE_CALENDAR_", "googlecalendar", "GOOGLECALENDAR_"),- ("GOOGLE_SHEETS_", "googlesheets", "GOOGLESHEETS_"),- ("GOOGLE_DOCS_", "googledocs", "GOOGLEDOCS_"),- ("GOOGLE_MEET_", "googlemeet", "GOOGLEMEET_"),- ("GOOGLE_TASKS_", "googletasks", "GOOGLETASKS_"),- ("GOOGLE_SLIDES_", "googleslides", "GOOGLESLIDES_"),- ("GOOGLE_PHOTOS_", "googlephotos", "GOOGLEPHOTOS_"),- ("MICROSOFT_OUTLOOK_", "outlook", "OUTLOOK_"),-];--/// Extract the toolkit slug from a Composio action slug.-///-/// Most action slugs follow `<TOOLKIT>_<VERB>_…` — `GMAIL_SEND_EMAIL` yields-/// `gmail`. A few toolkit identifiers contain underscores themselves, so those-/// need known-prefix handling or a connected-toolkit check silently drops every-/// action for them (`ZOHO_MAIL_*` would resolve to the non-existent `zoho`).-/// Separated spellings of separator-less toolkits (`GOOGLE_DRIVE_*`) resolve to-/// the real toolkit too (`googledrive`); see [`canonical_action_slug`].-///-/// Returns `None` only for an empty or whitespace-only slug.-pub fn toolkit_from_slug(slug: &str) -> Option<String> {- let trimmed = slug.trim();- if trimmed.is_empty() {- return None;- }- let upper = trimmed.to_ascii_uppercase();- for (prefix, toolkit) in MULTI_SEGMENT_TOOLKIT_PREFIXES {- if upper.starts_with(prefix) {- return Some((*toolkit).to_string());- }- }- for (alias, toolkit, _) in ALIASED_TOOLKIT_PREFIXES {- if upper.starts_with(alias) {- return Some((*toolkit).to_string());- }- }- let prefix = trimmed.split('_').next()?;- if prefix.is_empty() {- None- } else {- Some(prefix.to_ascii_lowercase())- }-}--/// The real action slug for an aliased spelling — `GOOGLE_DRIVE_FIND_FILE`-/// becomes `GOOGLEDRIVE_FIND_FILE` — or `None` when `slug` uses no alias.-pub fn canonical_action_slug(slug: &str) -> Option<String> {- let upper = slug.trim().to_ascii_uppercase();- ALIASED_TOOLKIT_PREFIXES- .iter()- .find_map(|(alias, _, canonical)| {- upper- .strip_prefix(alias)- .map(|rest| format!("{canonical}{rest}"))- })-}--/// Whether catalog slug `candidate` is the action `requested` names, ignoring-/// case and accepting an aliased spelling ([`canonical_action_slug`]).-pub fn action_slug_matches(candidate: &str, requested: &str) -> bool {- let requested = requested.trim();- candidate.eq_ignore_ascii_case(requested)- || canonical_action_slug(requested).is_some_and(|c| candidate.eq_ignore_ascii_case(&c))-}--/// Every toolkit slug that has a curated, agent-ready catalog.-///-/// This is the source of truth behind the "preview / agent integration coming-/// soon" badge: a connected toolkit whose slug is *not* in this list can be-/// authorized but has no curated tool surface, so the agent cannot use it-/// productively and the UI should say so rather than offering it.-///-/// Returned sorted, so the RPC response is stable across builds.-///-/// The list is here rather than with the catalogs it names because the *host*-/// renders the badge. Keeping it beside the catalogs would mean the host asking-/// the module a question — "is this toolkit worth showing?" — that has no-/// user-visible state behind it and would answer identically forever.-pub fn agent_ready_toolkits() -> Vec<&'static str> {- let mut slugs: Vec<&'static str> = vec![- // Native providers.- "gmail",- "notion",- "github",- // Catalog-only toolkits.- "slack",- "discord",- "googlecalendar",- "googledrive",- "googledocs",- "googlesheets",- "outlook",- "microsoft_teams",- "linear",- "jira",- "trello",- "asana",- "dropbox",- "twitter",- "spotify",- "telegram",- "whatsapp",- "shopify",- "stripe",- "hubspot",- "salesforce",- "airtable",- "figma",- "youtube",- "one_drive",- "excel",- "todoist",- ];- slugs.sort_unstable();- slugs-}--#[cfg(test)]-#[path = "scopes_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/contract/slug.rs b/crates/openhuman-core/src/integrations/composio/contract/slug.rsnew file mode 100644index 0000000000..4e937de2da--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/contract/slug.rs@@ -0,0 +1,134 @@+//! Synchronous slug helpers for the Composio action slugs the host's hot+//! paths (tool visibility, flow gates, approval hooks) must classify without+//! awaiting the connector module.+//!+//! The types they return ([`ToolScope`], [`CuratedTool`], [`UserScopePref`])+//! are the connector contract's (`tinyconnectors_bus::vocabulary`); the+//! curated catalogs and the stored preference are the module's, read through+//! [`super::curated`] and `ops::scope_prefs`. What remains here is text-only+//! slug parsing that the contract does not yet serve synchronously+//! (`EvaluateActions` answers the same questions, asynchronously).++use super::{CuratedTool, ToolScope};++/// Heuristic fallback for gating a tool that is not in any provider's curated+/// list.+///+/// Prefer the curated classification when one exists; only reach for this when+/// a toolkit has no catalog or the catalog does not mention the slug. Admin+/// verbs are checked first so `MODIFY_LABELS` does not slip into the write+/// bucket on the `UPDATE` substring rule — the ordering is the whole point of+/// the function and not an implementation detail.+pub fn classify_unknown(slug: &str) -> ToolScope {+ let upper = slug.to_ascii_uppercase();+ const ADMIN: &[&str] = &[+ "DELETE",+ "TRASH",+ "REMOVE",+ "MODIFY_LABELS",+ "SHARE",+ "REVOKE",+ "DESTROY",+ ];+ const WRITE: &[&str] = &[+ "SEND", "CREATE", "UPDATE", "REPLY", "APPEND", "INSERT", "ADD", "POST", "PATCH", "WRITE",+ "DRAFT",+ ];+ if ADMIN.iter().any(|kw| upper.contains(kw)) {+ return ToolScope::Admin;+ }+ if WRITE.iter().any(|kw| upper.contains(kw)) {+ return ToolScope::Write;+ }+ ToolScope::Read+}++/// Look up a slug inside a curated catalog, case-insensitively.+pub fn find_curated<'a>(catalog: &'a [CuratedTool], slug: &str) -> Option<&'a CuratedTool> {+ catalog.iter().find(|t| t.slug.eq_ignore_ascii_case(slug))+}++/// Toolkits whose identifier itself contains an underscore, so the first+/// segment of their action slugs is not the toolkit: `(action prefix, toolkit)`.+/// Their real action slugs carry the prefix as written.+const MULTI_SEGMENT_TOOLKIT_PREFIXES: &[(&str, &str)] = &[+ ("MICROSOFT_TEAMS_", "microsoft_teams"),+ ("ONE_DRIVE_", "one_drive"),+ ("ZOHO_MAIL_", "zoho_mail"),+ ("GOOGLE_MAPS_", "google_maps"),+];++/// Spellings models use for toolkits whose real slugs have no separator+/// (`GOOGLE_DRIVE_FIND_FILE` for `GOOGLEDRIVE_FIND_FILE`):+/// `(alias prefix, toolkit, canonical action prefix)`. Without them the first+/// segment, `google`, names a toolkit that does not exist.+const ALIASED_TOOLKIT_PREFIXES: &[(&str, &str, &str)] = &[+ ("GOOGLE_DRIVE_", "googledrive", "GOOGLEDRIVE_"),+ ("GOOGLE_CALENDAR_", "googlecalendar", "GOOGLECALENDAR_"),+ ("GOOGLE_SHEETS_", "googlesheets", "GOOGLESHEETS_"),+ ("GOOGLE_DOCS_", "googledocs", "GOOGLEDOCS_"),+ ("GOOGLE_MEET_", "googlemeet", "GOOGLEMEET_"),+ ("GOOGLE_TASKS_", "googletasks", "GOOGLETASKS_"),+ ("GOOGLE_SLIDES_", "googleslides", "GOOGLESLIDES_"),+ ("GOOGLE_PHOTOS_", "googlephotos", "GOOGLEPHOTOS_"),+ ("MICROSOFT_OUTLOOK_", "outlook", "OUTLOOK_"),+];++/// Extract the toolkit slug from a Composio action slug.+///+/// Most action slugs follow `<TOOLKIT>_<VERB>_…` — `GMAIL_SEND_EMAIL` yields+/// `gmail`. A few toolkit identifiers contain underscores themselves, so those+/// need known-prefix handling or a connected-toolkit check silently drops every+/// action for them (`ZOHO_MAIL_*` would resolve to the non-existent `zoho`).+/// Separated spellings of separator-less toolkits (`GOOGLE_DRIVE_*`) resolve to+/// the real toolkit too (`googledrive`); see [`canonical_action_slug`].+///+/// Returns `None` only for an empty or whitespace-only slug.+pub fn toolkit_from_slug(slug: &str) -> Option<String> {+ let trimmed = slug.trim();+ if trimmed.is_empty() {+ return None;+ }+ let upper = trimmed.to_ascii_uppercase();+ for (prefix, toolkit) in MULTI_SEGMENT_TOOLKIT_PREFIXES {+ if upper.starts_with(prefix) {+ return Some((*toolkit).to_string());+ }+ }+ for (alias, toolkit, _) in ALIASED_TOOLKIT_PREFIXES {+ if upper.starts_with(alias) {+ return Some((*toolkit).to_string());+ }+ }+ let prefix = trimmed.split('_').next()?;+ if prefix.is_empty() {+ None+ } else {+ Some(prefix.to_ascii_lowercase())+ }+}++/// The real action slug for an aliased spelling — `GOOGLE_DRIVE_FIND_FILE`+/// becomes `GOOGLEDRIVE_FIND_FILE` — or `None` when `slug` uses no alias.+pub fn canonical_action_slug(slug: &str) -> Option<String> {+ let upper = slug.trim().to_ascii_uppercase();+ ALIASED_TOOLKIT_PREFIXES+ .iter()+ .find_map(|(alias, _, canonical)| {+ upper+ .strip_prefix(alias)+ .map(|rest| format!("{canonical}{rest}"))+ })+}++/// Whether catalog slug `candidate` is the action `requested` names, ignoring+/// case and accepting an aliased spelling ([`canonical_action_slug`]).+pub fn action_slug_matches(candidate: &str, requested: &str) -> bool {+ let requested = requested.trim();+ candidate.eq_ignore_ascii_case(requested)+ || canonical_action_slug(requested).is_some_and(|c| candidate.eq_ignore_ascii_case(&c))+}++#[cfg(test)]+#[path = "slug_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/contract/scopes_tests.rs b/crates/openhuman-core/src/integrations/composio/contract/slug_tests.rssimilarity index 66%rename from crates/openhuman-core/src/integrations/composio/contract/scopes_tests.rsrename to crates/openhuman-core/src/integrations/composio/contract/slug_tests.rsindex 35bae06c79..8462ec5db9 100644--- a/crates/openhuman-core/src/integrations/composio/contract/scopes_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/contract/slug_tests.rs@@ -10,10 +10,7 @@#![allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]-use super::{- action_slug_matches, agent_ready_toolkits, canonical_action_slug, classify_unknown,- find_curated, toolkit_from_slug, CuratedTool, ToolScope, UserScopePref,-};+use super::*;#[test]fn destructive_verbs_classify_as_admin() {@@ -94,7 +91,8 @@ fn multi_segment_toolkits_keep_their_whole_prefix() {#[test]fn a_curated_lookup_ignores_casing_and_reports_a_miss() {let catalog = &[CuratedTool {- slug: "GMAIL_SEND_EMAIL",+ toolkit: "gmail".to_string(),+ slug: "GMAIL_SEND_EMAIL".to_string(),scope: ToolScope::Write,}];assert!(find_curated(catalog, "gmail_send_email").is_some());@@ -102,81 +100,6 @@ fn a_curated_lookup_ignores_casing_and_reports_a_miss() {assert!(find_curated(catalog, "GMAIL_DELETE_EMAIL").is_none());}-#[test]-fn every_tool_scope_tag_matches_its_serde_form() {- for scope in [ToolScope::Read, ToolScope::Write, ToolScope::Admin] {- let json = serde_json::to_string(&scope).expect("serialize");- assert_eq!(json, format!("\"{}\"", scope.as_str()));- }-}--#[test]-fn a_new_connection_may_read_and_write_but_not_administer() {- let pref = UserScopePref::default();- assert!(pref.read);- assert!(pref.write);- assert!(!pref.admin);-}--#[test]-fn allows_answers_per_scope() {- let pref = UserScopePref {- read: true,- write: false,- admin: false,- };- assert!(pref.allows(ToolScope::Read));- assert!(!pref.allows(ToolScope::Write));- assert!(!pref.allows(ToolScope::Admin));-}--#[test]-fn a_preference_round_trips() {- let pref = UserScopePref {- read: true,- write: true,- admin: true,- };- let value = serde_json::to_value(pref).expect("serialize");- let back: UserScopePref = serde_json::from_value(value).expect("deserialize");- assert_eq!(pref, back);-}--#[test]-fn a_row_missing_read_and_write_decodes_as_permitted_not_denied() {- // A stored row written before a field existed must not read back as a- // denial: `#[serde(default)]` on a `bool` would silently revoke access the- // user never revoked.- let stored = serde_json::json!({ "admin": true });- let pref: UserScopePref = serde_json::from_value(stored).expect("deserialize");- assert!(pref.read);- assert!(pref.write);- assert!(pref.admin);-}--#[test]-fn the_agent_ready_list_is_sorted_and_free_of_duplicates() {- // The RPC response has to be stable across builds, and the badge logic is a- // membership test — a duplicate would be invisible there and confusing in- // the panel.- let slugs = agent_ready_toolkits();- let mut sorted = slugs.clone();- sorted.sort_unstable();- assert_eq!(slugs, sorted, "the list must come back sorted");-- let mut deduped = sorted.clone();- deduped.dedup();- assert_eq!(deduped.len(), slugs.len(), "the list has a duplicate slug");-}--#[test]-fn the_agent_ready_list_names_the_native_providers() {- let slugs = agent_ready_toolkits();- for native in ["gmail", "notion", "github", "linear"] {- assert!(slugs.contains(&native), "{native} is missing from the list");- }-}-#[test]fn spaced_google_and_microsoft_prefixes_resolve_to_the_real_toolkit() {// Production: `get_tool_contract { slug: "GOOGLE_DRIVE_FIND_FILE" }` looked@@ -213,23 +136,6 @@ fn spaced_google_and_microsoft_prefixes_resolve_to_the_real_toolkit() {);}-#[test]-fn every_resolved_multi_segment_toolkit_is_one_the_app_knows_or_a_real_composio_slug() {- let known = agent_ready_toolkits();- for slug in [- "GOOGLE_DRIVE_X",- "GOOGLE_CALENDAR_X",- "GOOGLE_SHEETS_X",- "GOOGLE_DOCS_X",- "MICROSOFT_TEAMS_X",- "MICROSOFT_OUTLOOK_X",- "ONE_DRIVE_X",- ] {- let toolkit = toolkit_from_slug(slug).unwrap();- assert!(known.contains(&toolkit.as_str()), "{slug} -> {toolkit}");- }-}-#[test]fn a_spaced_alias_is_rewritten_to_the_canonical_action_slug() {assert_eq!(