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
fix(scope): correct channel connection and tool filtering logic
Steven Enamakel21a8a07e80fe
diff --git a/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner/toolkit_scope_filter.rs b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner/toolkit_scope_filter.rsnew file mode 100644index 0000000000..0e24489d39--- /dev/null+++ b/crates/openhuman-core/src/agent/harness/subagent_runner/ops/runner/toolkit_scope_filter.rs@@ -0,0 +1,39 @@+//! Re-filtering a cached toolkit action catalogue against the user's+//! *current* per-toolkit scope preference (read/write/admin), used by the+//! typed-mode prompt builder when it reuses a cached connected-integration+//! catalogue instead of re-fetching it.++/// Re-filter `actions` (a cached toolkit action catalogue) against the+/// caller's live per-toolkit scope preference, so a scope change since the+/// catalogue was cached is honored without a re-fetch.+pub(super) async fn filter_cached_toolkit_actions_with_current_scope(+ agent_id: &str,+ toolkit: &str,+ config: &crate::config::Config,+ actions: &[crate::agent::context::prompt::ConnectedIntegrationTool],+) -> Vec<crate::agent::context::prompt::ConnectedIntegrationTool> {+ let pref = crate::integrations::composio::ops::load_user_scope_pref(config, toolkit).await;+ let before = actions.len();+ let filtered: Vec<_> = actions+ .iter()+ .filter(|action| {+ crate::integrations::composio::providers::is_action_visible_with_pref(+ &action.name,+ &pref,+ )+ })+ .cloned()+ .collect();+ tracing::debug!(+ agent_id = %agent_id,+ toolkit = %toolkit,+ cached_actions = before,+ visible_actions = filtered.len(),+ hidden_actions = before.saturating_sub(filtered.len()),+ read = pref.read,+ write = pref.write,+ admin = pref.admin,+ "[subagent_runner:typed] re-filtered cached toolkit catalogue with current user scope"+ );+ filtered+}diff --git a/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs b/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rsindex f0591e675b..a984702644 100644--- a/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs+++ b/crates/openhuman-core/src/channels/controllers/ops/connect/connect_channel.rs@@ -9,11 +9,13 @@ use crate::config::{Config, DiscordConfig, IMessageConfig, TelegramConfig};use crate::rpc::RpcOutcome;use crate::security::credentials;-use super::super::definitions::{find_channel_definition, ChannelAuthMode};+use super::super::super::definitions::{find_channel_definition, ChannelAuthMode};use super::super::types::ChannelConnectionResult;use super::email::{build_email_config, persist_email_config, verify_email_credentials};use super::shared::{credential_provider, parse_allowed_users, parse_optional_bool};-use super::yuanbao::{build_effective_yuanbao_config, require_yuanbao_field, verify_yuanbao_credentials};+use super::super::yuanbao::{+ build_effective_yuanbao_config, require_yuanbao_field, verify_yuanbao_credentials,+};/// Initiate a channel connection.///diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/tool_impl.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/tool_impl.rsnew file mode 100644index 0000000000..e438954201--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/tools/direct/tool_impl.rs@@ -0,0 +1,210 @@+//! The generic-agent-facing `Tool` trait implementation for `ComposioTool`+//! (`list` / `execute` / `connect` dispatch).++use super::types::ComposioTool;+use crate::security::policy::ToolOperation;+use crate::tools::traits::{Tool, ToolCategory, ToolResult};+use async_trait::async_trait;+use serde_json::json;++#[async_trait]+impl Tool for ComposioTool {+ fn name(&self) -> &str {+ "composio"+ }++ fn description(&self) -> &str {+ "Execute actions on 1000+ apps via Composio (Gmail, Notion, GitHub, Slack, etc.). \+ Use action='list' to see available actions, action='execute' with action_name/tool_slug, params, and optional connected_account_id, \+ or action='connect' with app/auth_config_id to get OAuth URL. \+ For Gmail: GMAIL_FETCH_EMAILS supports standard Gmail search syntax in the 'query' param — \+ use query='from:me' or query='label:SENT' to retrieve sent emails, query='label:INBOX' for inbox, \+ query='is:unread' for unread mail, etc. Sent mail is synced and searchable."+ }++ fn parameters_schema(&self) -> serde_json::Value {+ json!({+ "type": "object",+ "properties": {+ "action": {+ "type": "string",+ "description": "The operation: 'list' (list available actions), 'execute' (run an action), or 'connect' (get OAuth URL)",+ "enum": ["list", "execute", "connect"]+ },+ "app": {+ "type": "string",+ "description": "Toolkit slug filter for 'list', or toolkit/app for 'connect' (e.g. 'gmail', 'notion', 'github')"+ },+ "action_name": {+ "type": "string",+ "description": "Action/tool identifier to execute (legacy aliases supported)"+ },+ "tool_slug": {+ "type": "string",+ "description": "Preferred v3 tool slug to execute (alias of action_name)"+ },+ "params": {+ "type": "object",+ "description": "Parameters to pass to the action"+ },+ "entity_id": {+ "type": "string",+ "description": "Entity/user ID for multi-user setups (defaults to composio.entity_id from config)"+ },+ "auth_config_id": {+ "type": "string",+ "description": "Optional Composio v3 auth config id for connect flow"+ },+ "connected_account_id": {+ "type": "string",+ "description": "Optional connected account ID for execute flow when a specific account is required"+ }+ },+ "required": ["action"]+ })+ }++ fn category(&self) -> ToolCategory {+ // Composio proxies to external SaaS (Gmail, Notion, …) — surface+ // it in the Workflow category so the skills sub-agent+ // (`category_filter = "skill"`) can see and call it.+ ToolCategory::Workflow+ }++ fn external_effect(&self) -> bool {+ // Conservative default for the arg-less path: assume any+ // composio call is a write so callers that don't reach the+ // args-aware override still get gated. The harness uses+ // `external_effect_with_args` (below) which inspects+ // `action` and lets read-only branches through.+ true+ }++ fn external_effect_with_args(&self, args: &serde_json::Value) -> bool {+ // `action="list"` enumerates available Composio actions —+ // a read-only catalog call. `action="connect"` only returns+ // an OAuth URL the user then visits manually; the+ // subsequent OAuth handoff is its own consent flow so the+ // tool call itself has no outbound side effect to gate.+ // `action="execute"` (or anything unknown / missing) is the+ // write path and routes through the approval gate.+ !matches!(+ args.get("action").and_then(|v| v.as_str()),+ Some("list") | Some("connect")+ )+ }++ async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {+ let action = args+ .get("action")+ .and_then(|v| v.as_str())+ .ok_or_else(|| anyhow::anyhow!("Missing 'action' parameter"))?;++ let entity_id = args+ .get("entity_id")+ .and_then(|v| v.as_str())+ .unwrap_or(self.default_entity_id.as_str());++ match action {+ "list" => {+ let app = args.get("app").and_then(|v| v.as_str());+ match self.list_actions(app).await {+ Ok(actions) => {+ let summary: Vec<String> = actions+ .iter()+ .take(20)+ .map(|a| {+ format!(+ "- {} ({}): {}",+ a.name,+ a.app_name.as_deref().unwrap_or("?"),+ a.description.as_deref().unwrap_or("")+ )+ })+ .collect();+ let total = actions.len();+ let output = format!(+ "Found {total} available actions:\n{}{}",+ summary.join("\n"),+ if total > 20 {+ format!("\n... and {} more", total - 20)+ } else {+ String::new()+ }+ );+ Ok(ToolResult::success(output))+ }+ Err(e) => Ok(ToolResult::error(format!("Failed to list actions: {e}"))),+ }+ }++ "execute" => {+ if let Err(error) = self+ .security+ .enforce_tool_operation(ToolOperation::Act, "composio.execute")+ {+ return Ok(ToolResult::error(error));+ }++ let action_name = args+ .get("tool_slug")+ .or_else(|| args.get("action_name"))+ .and_then(|v| v.as_str())+ .ok_or_else(|| {+ anyhow::anyhow!("Missing 'action_name' (or 'tool_slug') for execute")+ })?;++ let params = args.get("params").cloned().unwrap_or(json!({}));+ let acct_ref = args.get("connected_account_id").and_then(|v| v.as_str());++ match self+ .execute_action(action_name, params, Some(entity_id), acct_ref)+ .await+ {+ Ok(result) => {+ let output = serde_json::to_string_pretty(&result)+ .unwrap_or_else(|_| format!("{result:?}"));+ Ok(ToolResult::success(output))+ }+ Err(e) => Ok(ToolResult::error(format!("Action execution failed: {e}"))),+ }+ }++ "connect" => {+ if let Err(error) = self+ .security+ .enforce_tool_operation(ToolOperation::Act, "composio.connect")+ {+ return Ok(ToolResult::error(error));+ }++ let app = args.get("app").and_then(|v| v.as_str());+ let auth_config_id = args.get("auth_config_id").and_then(|v| v.as_str());++ if app.is_none() && auth_config_id.is_none() {+ anyhow::bail!("Missing 'app' or 'auth_config_id' for connect");+ }++ match self+ .get_connection_url(app, auth_config_id, entity_id)+ .await+ {+ Ok(url) => {+ let target =+ app.unwrap_or(auth_config_id.unwrap_or("provided auth config"));+ Ok(ToolResult::success(format!(+ "Open this URL to connect {target}:\n{url}"+ )))+ }+ Err(e) => Ok(ToolResult::error(format!(+ "Failed to get connection URL: {e}"+ ))),+ }+ }++ _ => Ok(ToolResult::error(format!(+ "Unknown action '{action}'. Use 'list', 'execute', or 'connect'."+ ))),+ }+ }+}diff --git a/crates/openhuman-core/src/memory/safety/normalize.rs b/crates/openhuman-core/src/memory/safety/normalize.rsnew file mode 100644index 0000000000..6069320fef--- /dev/null+++ b/crates/openhuman-core/src/memory/safety/normalize.rs@@ -0,0 +1,328 @@+//! Unicode normalization and the cheap byte-oriented candidate pre-filter+//! that gates which precise PII regexes run.+//!+//! Split out of `pii.rs`. [`NormalizedView`] defeats fullwidth-digit and+//! zero-width-character bypasses while keeping a byte map back to the+//! original string; [`scan_candidates`] is a single linear pass deciding,+//! per PII class, whether it is even worth running the (comparatively+//! expensive) regex/checksum pass in [`super::pii_patterns`].++// ---------- Unicode normalization for matching ----------+//+// A pre-pass that defeats fullwidth-digit and zero-width-char bypasses while+// keeping a byte map back to the original string, so matches found on the+// normalized view can be spliced onto the exact original bytes.++struct NormalizedView {+ normalized: String,+ // For each byte offset i in `normalized`, `byte_map[i]` is the byte offset+ // in the original string where the corresponding char *starts*.+ // The last entry maps the normalized length to the original length, so+ // `norm_to_orig(normalized.len())` is well-defined.+ byte_map: Vec<usize>,+}++impl NormalizedView {+ fn build(original: &str) -> Self {+ let mut normalized = String::with_capacity(original.len());+ let mut byte_map: Vec<usize> = Vec::with_capacity(original.len() + 1);+ for (idx, ch) in original.char_indices() {+ if is_zero_width(ch) {+ continue;+ }+ let mapped = fold_char(ch);+ let start = normalized.len();+ normalized.push(mapped);+ // One byte_map entry per byte of the normalized char.+ let added = normalized.len() - start;+ for _ in 0..added {+ byte_map.push(idx);+ }+ }+ byte_map.push(original.len());+ Self {+ normalized,+ byte_map,+ }+ }++ fn norm_to_orig(&self, norm_byte: usize) -> usize {+ if norm_byte >= self.byte_map.len() {+ return *self.byte_map.last().unwrap_or(&0);+ }+ self.byte_map[norm_byte]+ }+}++fn is_zero_width(c: char) -> bool {+ matches!(+ c,+ '\u{200B}'+ | '\u{200C}'+ | '\u{200D}'+ | '\u{200E}'+ | '\u{200F}'+ | '\u{2060}'+ | '\u{180E}'+ | '\u{FEFF}'+ )+}++fn fold_char(c: char) -> char {+ match c {+ // Fullwidth digits 0-9+ '\u{FF10}'..='\u{FF19}' => char::from_u32(c as u32 - 0xFF10 + 0x30).unwrap_or(c),+ // Arabic-Indic digits ٠-٩+ '\u{0660}'..='\u{0669}' => char::from_u32(c as u32 - 0x0660 + 0x30).unwrap_or(c),+ // Eastern Arabic-Indic digits ۰-۹+ '\u{06F0}'..='\u{06F9}' => char::from_u32(c as u32 - 0x06F0 + 0x30).unwrap_or(c),+ // Common fullwidth punctuation we care about for PII formats+ '\u{FF0D}' => '-',+ '\u{FF0E}' => '.',+ '\u{FF0F}' => '/',+ '\u{FF1A}' => ':',+ '\u{2010}'..='\u{2015}' => '-', // various unicode hyphens/dashes+ '\u{2212}' => '-', // minus sign+ other => other,+ }+}++// ---------- Byte-oriented candidate pre-filter ----------+//+// Replaces the always-resident combined `RegexSet` (one shared NFA plus a+// per-thread lazy-DFA cache in *every* process/thread) with a single cheap pass+// over the raw bytes. The scan derives per-class candidate flags from a handful+// of structural signals — digit-run lengths, punctuation presence, uppercase /+// alpha presence, `+`, and case-insensitive keyword probes (including the+// non-Latin Aadhaar and My-Number keywords). Each flag then decides whether that+// class's precise validation regex is worth compiling and running; the precise+// `Regex`es stay `LazyLock`, so a class that never sees a candidate is never+// compiled at all. At 100–1000 concurrent agents that turns "combined NFA + N+// thread-local DFA caches resident forever" into "only the regexes a workload+// actually needs, compiled on first hit".+//+// Correctness: every flag is a NECESSARY CONDITION of the class's *precise*+// regex, so a flag can only over-fire (harmless — the precise regex then simply+// fails to match), never under-fire on real PII. Consequently, whenever a+// precise pattern would have matched without the pre-filter, its flag is set and+// it still runs — output is unchanged. The union of the flags is a superset of+// the legacy `SCREEN` set (pinned by `prefilter_is_superset_of_legacy_screen`).+// The NANP phone class gates on the *screen*-entry necessary condition — an+// internal `digit sep digit` separator OR a `\d{11,}` run (the old SCREEN reached+// `PHONE_NANP_RE` through both) — faithfully preserving the documented "a bare+// 10-digit NANP run is never reached" behavior while still redacting a bare+// `1`+10-digit country-code number — see+// `redact_pii_does_not_reach_bare_10_digit_nanp_today`.++/// Per-class candidate flags produced by [`scan_candidates`]. A set flag means+/// "run this class's precise regex"; an unset flag means the class cannot+/// possibly match, so its regex is skipped (and never compiled).+#[derive(Default, Clone, Copy)]+struct Candidates {+ cpf_fmt: bool,+ cnpj_fmt: bool,+ cuit: bool,+ iban: bool,+ cc: bool,+ cnpj_bare: bool,+ cpf_bare: bool,+ aadhaar_fmt: bool,+ aadhaar_kw: bool,+ dni: bool,+ nie: bool,+ nino: bool,+ ssn: bool,+ rrn: bool,+ rfc: bool,+ pan_in: bool,+ phone_e164: bool,+ phone_nanp: bool,+ mynumber: bool,+}++impl Candidates {+ /// True if any class is a candidate — i.e. the text is worth a precise pass.+ fn any(&self) -> bool {+ self.cpf_fmt+ || self.cnpj_fmt+ || self.cuit+ || self.iban+ || self.cc+ || self.cnpj_bare+ || self.cpf_bare+ || self.aadhaar_fmt+ || self.aadhaar_kw+ || self.dni+ || self.nie+ || self.nino+ || self.ssn+ || self.rrn+ || self.rfc+ || self.pan_in+ || self.phone_e164+ || self.phone_nanp+ || self.mynumber+ }+}++/// Case-insensitive (ASCII-only case folding) substring test over raw bytes.+/// Non-ASCII bytes compare exactly, so this also serves as an exact matcher for+/// the multibyte Devanagari / Japanese keyword needles.+fn contains_ci(hay: &[u8], needle: &[u8]) -> bool {+ if needle.is_empty() {+ return true;+ }+ if hay.len() < needle.len() {+ return false;+ }+ hay.windows(needle.len())+ .any(|w| w.iter().zip(needle).all(|(a, b)| a.eq_ignore_ascii_case(b)))+}++/// Aadhaar keyword needles — ASCII forms plus Devanagari `आधार`.+const AADHAAR_KEYWORDS: &[&[u8]] = &[b"aadhaar", b"aadhar", b"uidai", b"uid", "आधार".as_bytes()];+/// My-Number Japanese keyword needles. The English `My\s?Number` variant is+/// handled separately (see `scan_candidates`) so any `\s` separator between the+/// two words is recognised, not just a literal space.+const MYNUMBER_JP_KEYWORDS: &[&[u8]] = &["マイナンバー".as_bytes(), "個人番号".as_bytes()];++/// Single linear pass over the bytes deriving every per-class candidate flag.+///+/// Only ASCII structural bytes carry signal here; multibyte UTF-8 lead /+/// continuation bytes are all `>= 0x80`, so scanning `as_bytes()` for ASCII+/// digits/punctuation/letters is boundary-safe. Keyword probes run over the+/// same byte slice so the non-Latin needles match verbatim.+fn scan_candidates(text: &str) -> Candidates {+ let bytes = text.as_bytes();++ let mut total_digits: usize = 0;+ let mut max_digit_run: usize = 0;+ let mut cur_run: usize = 0;+ let mut has_dot = false;+ let mut has_dash = false;+ let mut has_slash = false;+ // Any ASCII whitespace separator (space, tab, newline, CR, form feed,+ // vertical tab). The precise Aadhaar pattern separates its groups with+ // `[\s-]`, which matches the whole `\s` class — so gating on space/tab+ // alone would under-fire on newline-separated Aadhaar (a real PII drop).+ let mut has_ws = false;+ let mut has_upper = false;+ let mut has_alpha = false;+ let mut has_xyz = false;+ let mut has_plus = false;+ // NANP-style "separated group" signal: some `[digit or ')'] [sep] [digit]`+ // window exists (sep ∈ space/tab/./-). This is the necessary condition of+ // the old SCREEN NANP entry, which required internal separators — keeping+ // bare separator-less 10-digit runs out of the phone path.+ let mut nanp_sep = false;++ for (i, &b) in bytes.iter().enumerate() {+ if b.is_ascii_digit() {+ total_digits += 1;+ cur_run += 1;+ if cur_run > max_digit_run {+ max_digit_run = cur_run;+ }+ } else {+ cur_run = 0;+ match b {+ b'.' => has_dot = true,+ b'-' => has_dash = true,+ b'/' => has_slash = true,+ b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c => has_ws = true,+ b'+' => has_plus = true,+ b'A'..=b'Z' => {+ has_upper = true;+ has_alpha = true;+ if matches!(b, b'X' | b'Y' | b'Z') {+ has_xyz = true;+ }+ }+ b'a'..=b'z' => {+ has_alpha = true;+ if matches!(b, b'x' | b'y' | b'z') {+ has_xyz = true;+ }+ }+ _ => {}+ }+ }++ if matches!(b, b' ' | b'\t' | b'.' | b'-') && i > 0 && i + 1 < bytes.len() {+ let prev = bytes[i - 1];+ let next = bytes[i + 1];+ if (prev.is_ascii_digit() || prev == b')') && next.is_ascii_digit() {+ nanp_sep = true;+ }+ }+ }++ let has_digit = total_digits > 0;+ let aadhaar_kw = AADHAAR_KEYWORDS.iter().any(|kw| contains_ci(bytes, kw));+ // English `My\s?Number` accepts any single `\s` between the words, so a tab-+ // or newline-separated keyword (`My\tNumber`) must still flag. Requiring both+ // `my` and `number` substrings is a necessary condition of the precise regex+ // and covers every whitespace variant; it may over-fire (harmless — the+ // precise `MYNUM_RE` re-checks the separator and the trailing 12 digits).+ let mynumber = MYNUMBER_JP_KEYWORDS.iter().any(|kw| contains_ci(bytes, kw))+ || (contains_ci(bytes, b"my") && contains_ci(bytes, b"number"));++ let cand = Candidates {+ // Formatted CPF `\d{3}\.\d{3}\.\d{3}-\d{2}` — needs digits, `.`, `-`.+ cpf_fmt: has_digit && has_dot && has_dash,+ // Formatted CNPJ `\d{2}\.\d{3}\.\d{3}/\d{4}-\d{2}` — adds `/`.+ cnpj_fmt: has_digit && has_dot && has_slash && has_dash,+ // CUIT `\d{2}-\d{8}-\d` — needs digits and `-`.+ cuit: has_digit && has_dash,+ // IBAN `[A-Z]{2}\d{2}…` — case-sensitive uppercase letters and digits.+ iban: has_upper && has_digit,+ // Credit card `(?:\d[\s\-]?){13,19}` — at least 13 digits total.+ cc: total_digits >= 13,+ // Bare CNPJ `\d{14}` — a 14-long digit run.+ cnpj_bare: max_digit_run >= 14,+ // Bare CPF `\d{11}` — an 11-long digit run.+ cpf_bare: max_digit_run >= 11,+ // Formatted Aadhaar `\d{4}[\s-]\d{4}[\s-]\d{4}` — 12 digits + a `\s`/dash+ // separator (any ASCII whitespace, matching the precise `[\s-]` class).+ aadhaar_fmt: total_digits >= 12 && (has_ws || has_dash),+ // Keyword-gated Aadhaar — keyword suffices (precise regex checks digits).+ aadhaar_kw,+ // Spain DNI `\d{8}[A-Z]` — 8-run plus a letter.+ dni: max_digit_run >= 8 && has_alpha,+ // Spain NIE `[XYZ]\d{7}[A-Z]` — X/Y/Z, 7-run, letter.+ nie: has_xyz && max_digit_run >= 7 && has_alpha,+ // UK NINO `[A-Z]{2}\d{6}[A-D]` — letters and a 6-run.+ nino: max_digit_run >= 6 && has_alpha,+ // US SSN `\d{3}-\d{2}-\d{4}` — digits and `-`.+ ssn: has_digit && has_dash,+ // Korea RRN `\d{6}-[1-4]\d{6}` — a 6-run and `-`.+ rrn: max_digit_run >= 6 && has_dash,+ // Mexico RFC `[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}` — a 6-run (leading class may+ // be all non-ASCII `Ñ`, so gate on the digit run alone, not on letters).+ rfc: max_digit_run >= 6,+ // India PAN `[A-Z]{5}\d{4}[A-Z]` — letters and a 4-run.+ pan_in: max_digit_run >= 4 && has_alpha,+ // E.164 `\+\d{7,15}` — a `+` and a 7+ digit run.+ phone_e164: has_plus && max_digit_run >= 7,+ // NANP — screen-entry necessary condition. The old SCREEN reached+ // `PHONE_NANP_RE` via either the separated-group pattern OR the long+ // `\d{11,}` run (which covers a bare `1`+10-digit country-code number+ // like `12025551234`). A bare 10-digit run still stays out of the phone+ // path (no internal separator, run length 10 < 11).+ phone_nanp: nanp_sep || max_digit_run >= 11,+ // My Number — keyword suffices (precise regex checks the 12 digits).+ mynumber,+ };++ log::trace!(+ "[pii] scan_candidates bytes={} digits={} max_run={} nanp_sep={} any={}",+ bytes.len(),+ total_digits,+ max_digit_run,+ nanp_sep,+ cand.any()+ );++ cand+}+