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
chore: files changed crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rs,crate
Steven Enamakel4607de860437
diff --git a/crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rs b/crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rsnew file mode 100644index 0000000000..6ef91bfb06--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/tools/direct/discovery.rs@@ -0,0 +1,306 @@+//! Action/tool listing: `list_actions` (legacy flattened shape, v3-with-v2-fallback)+//! and `list_tool_schemas_v3` (full v3 schema, used by direct-mode+//! `composio_list_tools`), plus the wire types they decode into.++use super::http_errors::response_error;+use super::types::ComposioTool;+use anyhow::Context;+use serde::{Deserialize, Serialize};++impl ComposioTool {+ /// List available Composio apps/actions for the authenticated user.+ ///+ /// Uses v3 endpoint first and falls back to v2 for compatibility.+ pub async fn list_actions(+ &self,+ app_name: Option<&str>,+ ) -> anyhow::Result<Vec<ComposioAction>> {+ match self.list_actions_v3(app_name).await {+ Ok(items) => Ok(items),+ Err(v3_err) => {+ let v2 = self.list_actions_v2(app_name).await;+ match v2 {+ Ok(items) => Ok(items),+ Err(v2_err) => anyhow::bail!(+ "Composio action listing failed on v3 ({v3_err}) and v2 fallback ({v2_err})"+ ),+ }+ }+ }+ }++ async fn list_actions_v3(&self, app_name: Option<&str>) -> anyhow::Result<Vec<ComposioAction>> {+ let url = format!("{}/tools", self.base_v3);+ let mut req = self.client().get(&url).header("x-api-key", &self.api_key);++ // #3932: pin toolkit_versions=latest. Composio v3 otherwise defaults to+ // the 00000000_00 snapshot, which lists zero tools for any toolkit+ // published after it (Outlook and every other post-launch toolkit).+ req = req.query(&[("limit", "200"), ("toolkit_versions", "latest")]);+ if let Some(app) = app_name.map(str::trim).filter(|app| !app.is_empty()) {+ req = req.query(&[("toolkits", app), ("toolkit_slug", app)]);+ }++ let resp = req.send().await?;+ if !resp.status().is_success() {+ let err = response_error(resp).await;+ anyhow::bail!("Composio v3 API error: {err}");+ }++ let body: ComposioToolsResponse = resp+ .json()+ .await+ .context("Failed to decode Composio v3 tools response")?;+ Ok(map_v3_tools_to_actions(body.items))+ }++ async fn list_actions_v2(&self, app_name: Option<&str>) -> anyhow::Result<Vec<ComposioAction>> {+ let mut url = format!("{}/actions", self.base_v2);+ if let Some(app) = app_name {+ url = format!("{url}?appNames={app}");+ }++ let resp = self+ .client()+ .get(&url)+ .header("x-api-key", &self.api_key)+ .send()+ .await?;++ if !resp.status().is_success() {+ let err = response_error(resp).await;+ anyhow::bail!("Composio v2 API error: {err}");+ }++ let body: ComposioActionsResponse = resp+ .json()+ .await+ .context("Failed to decode Composio v2 actions response")?;+ Ok(body.items)+ }++ /// Build the query-parameter pairs for the Composio v3 `GET /tools`+ /// listing used by [`Self::list_tool_schemas_v3`].+ ///+ /// `toolkits` is sent as a single comma-joined `toolkits=` param (the+ /// legacy plural the v3 backend tolerates; cf. `list_actions_v3` which+ /// sends both the plural and `toolkit_slug` singular forms). `tags` is+ /// encoded as **repeated** `tags=` params (`tags=a&tags=b`) — the shape+ /// Composio v3 `/tools` documents for tag filtering ("can be specified+ /// multiple times"), NOT the comma-joined form the backend proxy uses.+ /// Blank entries are trimmed and dropped; an empty `tags` slice yields+ /// no `tags` params (treated as no filter).+ ///+ /// Pure (no I/O) so the param shape is unit-testable without a live+ /// HTTP round trip — mirrors [`Self::build_execute_action_v3_request`].+ fn build_list_tool_schemas_v3_query(+ toolkits: &[&str],+ tags: Option<&[&str]>,+ ) -> Vec<(&'static str, String)> {+ // #3932: pin toolkit_versions=latest. Without it Composio v3 defaults to+ // the 00000000_00 snapshot, which lists zero tools for any toolkit+ // published after it (Outlook and every other post-launch toolkit).+ let mut params: Vec<(&'static str, String)> = vec![+ ("limit", "200".to_string()),+ ("toolkit_versions", "latest".to_string()),+ ];++ let trimmed: Vec<&str> = toolkits+ .iter()+ .map(|t| t.trim())+ .filter(|t| !t.is_empty())+ .collect();+ if !trimmed.is_empty() {+ params.push(("toolkits", trimmed.join(",")));+ }++ if let Some(tags) = tags {+ for tag in tags.iter().map(|t| t.trim()).filter(|t| !t.is_empty()) {+ params.push(("tags", tag.to_string()));+ }+ }++ params+ }++ /// List v3 tool definitions for one or more toolkits, preserving the+ /// raw `input_parameters` JSON schema each action carries.+ ///+ /// Sibling of [`Self::list_actions`] but kept distinct because+ /// `list_actions` flattens to `Vec<ComposioAction>` (no parameters)+ /// for the legacy agent-discovery shape, whereas+ /// `composio_list_tools`'s direct-mode branch needs the full schema+ /// so the LLM agent can supply valid arguments without a separate+ /// round trip.+ ///+ /// `toolkits` may contain one or many slugs; when non-empty they are+ /// sent as a comma-separated `toolkits=` filter to constrain the v3+ /// catalogue scan. Empty filter returns every action across every+ /// toolkit on the user's tenant (potentially large; callers should+ /// pass a non-empty filter in practice).+ ///+ /// `tags` narrows the result by Composio action tag (OR semantics —+ /// multiple tags broaden the result). This is the direct-mode (BYO+ /// key) counterpart to the backend proxy's `tags` query param wired+ /// in [`crate::integrations::composio::client::ComposioClient::list_tools`];+ /// without it a self-key user's `composio_list_tools(..., tags)`+ /// request would silently drop the tag filter. Blank/empty `tags`+ /// are treated as no filter.+ pub(crate) async fn list_tool_schemas_v3(+ &self,+ toolkits: &[&str],+ tags: Option<&[&str]>,+ ) -> anyhow::Result<Vec<ComposioToolSchemaV3>> {+ let url = format!("{}/tools", self.base_v3);+ let params = Self::build_list_tool_schemas_v3_query(toolkits, tags);+ tracing::debug!(+ toolkits = toolkits.len(),+ tags = tags.map(<[&str]>::len).unwrap_or(0),+ "[composio-direct] list_tool_schemas_v3: GET v3 /tools query built"+ );+ let req = self+ .client()+ .get(&url)+ .header("x-api-key", &self.api_key)+ .query(¶ms);++ let resp = req.send().await?;+ if !resp.status().is_success() {+ let err = response_error(resp).await;+ anyhow::bail!("Composio v3 list_tool_schemas: {err}");+ }++ let body: ComposioToolsResponse = resp+ .json()+ .await+ .context("Failed to decode Composio v3 tools response")?;+ Ok(body+ .items+ .into_iter()+ .map(ComposioToolSchemaV3::from_v3_tool)+ .collect())+ }+}++fn map_v3_tools_to_actions(items: Vec<ComposioV3Tool>) -> Vec<ComposioAction> {+ items+ .into_iter()+ .filter_map(|item| {+ let name = item.slug.or(item.name.clone())?;+ let app_name = item+ .toolkit+ .as_ref()+ .and_then(|toolkit| toolkit.slug.clone().or(toolkit.name.clone()))+ .or(item.app_name);+ let description = item.description.or(item.name);+ Some(ComposioAction {+ name,+ app_name,+ description,+ enabled: true,+ })+ })+ .collect()+}++#[derive(Debug, Deserialize)]+struct ComposioActionsResponse {+ #[serde(default)]+ items: Vec<ComposioAction>,+}++#[derive(Debug, Deserialize)]+struct ComposioToolsResponse {+ #[serde(default)]+ items: Vec<ComposioV3Tool>,+}++#[derive(Debug, Clone, Deserialize)]+struct ComposioV3Tool {+ #[serde(default)]+ slug: Option<String>,+ #[serde(default)]+ name: Option<String>,+ #[serde(default)]+ description: Option<String>,+ #[serde(rename = "appName", default)]+ app_name: Option<String>,+ #[serde(default)]+ toolkit: Option<ComposioToolkitRef>,+ /// JSON schema for the tool parameters. Composio v3 names this+ /// `input_parameters`; older payloads use `parameters`. Either+ /// shape deserialises into this field, and we re-emit it as+ /// `ComposioToolFunction::parameters` so direct-mode users get+ /// the same model-callable schema backend mode surfaces.+ #[serde(default, alias = "parameters")]+ input_parameters: Option<serde_json::Value>,+ /// JSON schema for the tool's OUTPUT/return value, per Composio v3+ /// `/tools`'s `output_parameters` field ("Schema definition of return+ /// values from the tool" —+ /// <https://docs.composio.dev/reference/api-reference/tools/getTools>).+ /// Re-emitted as `ComposioToolFunction::output_parameters` so callers+ /// can ground a downstream binding in the tool's real output field+ /// names instead of guessing them.+ #[serde(default)]+ output_parameters: Option<serde_json::Value>,+}++#[derive(Debug, Clone, Deserialize)]+struct ComposioToolkitRef {+ #[serde(default)]+ slug: Option<String>,+ #[serde(default)]+ name: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ComposioAction {+ pub name: String,+ #[serde(rename = "appName")]+ pub app_name: Option<String>,+ pub description: Option<String>,+ #[serde(default)]+ pub enabled: bool,+}++/// Direct-mode tool definition lifted from Composio v3 `/tools`.+///+/// Carries the `input_parameters` JSON schema so the upstream+/// `composio_list_tools` direct branch can hand the LLM agent a+/// model-callable function shape — same fields backend mode surfaces+/// through `ComposioToolSchema`.+///+/// Kept distinct from `ComposioAction` (legacy flattened shape) so+/// new callers explicitly opt into the schema-preserving variant.+#[derive(Debug, Clone)]+pub struct ComposioToolSchemaV3 {+ pub slug: String,+ pub description: Option<String>,+ pub toolkit_slug: Option<String>,+ pub input_parameters: Option<serde_json::Value>,+ /// See [`ComposioV3Tool::output_parameters`] — Composio v3's schema for+ /// the action's return value, when published.+ pub output_parameters: Option<serde_json::Value>,+}++impl ComposioToolSchemaV3 {+ fn from_v3_tool(item: ComposioV3Tool) -> Self {+ let slug = item+ .slug+ .clone()+ .or_else(|| item.name.clone())+ .unwrap_or_default();+ let toolkit_slug = item+ .toolkit+ .as_ref()+ .and_then(|t| t.slug.clone().or(t.name.clone()))+ .or(item.app_name);+ Self {+ slug,+ description: item.description.or(item.name),+ toolkit_slug,+ input_parameters: item.input_parameters,+ output_parameters: item.output_parameters,+ }+ }+}diff --git a/crates/openhuman-core/src/memory/safety/secrets.rs b/crates/openhuman-core/src/memory/safety/secrets.rsnew file mode 100644index 0000000000..dc37c9f289--- /dev/null+++ b/crates/openhuman-core/src/memory/safety/secrets.rs@@ -0,0 +1,316 @@+//! Generic secret/credential scrubbing plus the sanitized-value types shared+//! with [`super::pii`].+//!+//! Split out of the original `safety.rs` (see that module's doc comment for+//! why this policy lives in OpenHuman rather than the memory engine). This+//! half owns the block/redaction pattern lists, the sensitive-key+//! classifier, the JSON depth cap, and the `sanitize_text`/`sanitize_json`+//! entry points; PII-specific regexes and checksum validators live in+//! [`super::pii`].+use std::sync::LazyLock;++use regex::Regex;+use serde_json::Value;++use super::pii::redact_pii;++const REDACTED_SECRET: &str = "[REDACTED_SECRET]";+const REDACTED_PRIVATE_KEY: &str = "[REDACTED_PRIVATE_KEY]";+const MAX_JSON_SANITIZE_DEPTH: usize = 128;++/// Tally of what a sanitization pass changed.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct SanitizationReport {+ /// Count of secret/token pattern matches rewritten in string text by the+ /// text-pattern redaction pass.+ pub text_redactions: usize,+ /// Count of JSON object entries dropped wholesale because their key was+ /// classified as sensitive by the key classifier.+ pub key_redactions: usize,+ /// Count of full private-key blocks replaced; these are+ /// the most severe hits since the entire block is removed.+ pub blocked_secret_hits: usize,+ /// Count of nodes collapsed because JSON nesting reached+ /// the JSON traversal depth cap; the subtree is replaced rather than walked.+ pub depth_redactions: usize,+ /// Count of personal-identifier matches replaced by the+ /// lightweight PII screen.+ pub pii_redactions: usize,+}++impl SanitizationReport {+ /// True when any field recorded a redaction.+ pub fn changed(&self) -> bool {+ self.text_redactions > 0+ || self.key_redactions > 0+ || self.blocked_secret_hits > 0+ || self.depth_redactions > 0+ || self.pii_redactions > 0+ }++ /// Sum two reports field-wise.+ pub fn merge(self, rhs: Self) -> Self {+ Self {+ text_redactions: self.text_redactions + rhs.text_redactions,+ key_redactions: self.key_redactions + rhs.key_redactions,+ blocked_secret_hits: self.blocked_secret_hits + rhs.blocked_secret_hits,+ depth_redactions: self.depth_redactions + rhs.depth_redactions,+ pii_redactions: self.pii_redactions + rhs.pii_redactions,+ }+ }+}++/// A sanitized value plus the [`SanitizationReport`] describing the changes.+#[derive(Debug, Clone)]+pub struct Sanitized<T> {+ /// The cleaned value with secrets and PII removed.+ pub value: T,+ /// Tally of what the sanitization pass changed to produce `value`.+ pub report: SanitizationReport,+}++static BLOCK_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {+ vec![+ Regex::new(+ r"(?is)-----BEGIN(?: [A-Z]+)? PRIVATE KEY-----.*?-----END(?: [A-Z]+)? PRIVATE KEY-----",+ )+ .expect("valid private key block"),+ Regex::new(r"(?is)-----BEGIN OPENSSH PRIVATE KEY-----.*?-----END OPENSSH PRIVATE KEY-----")+ .expect("valid openssh private key block"),+ Regex::new(+ r"(?is)-----BEGIN PGP PRIVATE KEY BLOCK-----.*?-----END PGP PRIVATE KEY BLOCK-----",+ )+ .expect("valid pgp private key block"),+ ]+});++static REDACTION_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {+ vec![+ (+ Regex::new(r"(?i)(bearer\s+)[A-Za-z0-9._~+/=-]{8,}").expect("valid bearer redaction"),+ "${1}[REDACTED]",+ ),+ (+ Regex::new(r#"(?i)(api[_-]?key\s*[=:\s]\s*["']?)[^\s"']+"#)+ .expect("valid api key redaction"),+ "${1}[REDACTED]",+ ),+ (+ Regex::new(+ r#"(?i)\b(token|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret)\b\s*[=:\s]\s*["']?[^\s"'&]+"#,+ )+ .expect("valid token redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bsk-[A-Za-z0-9]{20,}\b").expect("valid openai key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bgh[pousr]_[A-Za-z0-9_]{20,}\b").expect("valid github token redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bAKIA[0-9A-Z]{16}\b").expect("valid aws key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bASIA[0-9A-Z]{16}\b").expect("valid aws sts key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9._-]{8,}\.[A-Za-z0-9._-]{8,}\b")+ .expect("valid jwt redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(+ r#"(?i)\b(access_token|refresh_token|id_token|authorization_code|code_verifier|code_challenge)\b\s*[=:\s]\s*["']?[^\s"'&]+"#,+ )+ .expect("valid oauth token redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bAIza[0-9A-Za-z\-_]{35}\b").expect("valid google api key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bsk-ant-[A-Za-z0-9\-_]{16,}\b").expect("valid anthropic key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bsk-(?:proj|org)-[A-Za-z0-9\-_]{12,}\b")+ .expect("valid openai scoped key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b")+ .expect("valid stripe key redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bxox(?:a|b|p|s|r)-[A-Za-z0-9-]{10,}\b")+ .expect("valid slack token redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b").expect("valid github pat redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bglpat-[A-Za-z0-9\-_]{16,}\b").expect("valid gitlab pat redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bnpm_[A-Za-z0-9]{20,}\b").expect("valid npm token redaction"),+ "[REDACTED]",+ ),+ (+ Regex::new(r"\bSG\.[A-Za-z0-9_\-]{16,}\.[A-Za-z0-9_\-]{16,}\b")+ .expect("valid sendgrid key redaction"),+ "[REDACTED]",+ ),+ ]+});++/// True when `value` looks like it contains a credential.+pub fn has_likely_secret(value: &str) -> bool {+ BLOCK_PATTERNS.iter().any(|p| p.is_match(value))+ || REDACTION_PATTERNS.iter().any(|(p, _)| p.is_match(value))+}++/// Scrub secrets and PII from free text, returning the cleaned text plus a+/// [`SanitizationReport`].+pub fn sanitize_text(value: &str) -> Sanitized<String> {+ let mut out = value.to_string();+ let mut report = SanitizationReport::default();++ for pattern in BLOCK_PATTERNS.iter() {+ let hits = pattern.find_iter(&out).count();+ if hits > 0 {+ report.blocked_secret_hits += hits;+ out = pattern.replace_all(&out, REDACTED_PRIVATE_KEY).into_owned();+ }+ }++ for (pattern, replacement) in REDACTION_PATTERNS.iter() {+ let hits = pattern.find_iter(&out).count();+ if hits > 0 {+ report.text_redactions += hits;+ out = pattern.replace_all(&out, *replacement).into_owned();+ }+ }++ // Full multilingual national-ID PII scrub (checksum-gated, normalization+ // pre-pass) — runs after secret redaction so every call site that scrubs+ // secrets also scrubs PII.+ let pii = redact_pii(&out);+ report = report.merge(pii.report);+ out = pii.value;++ Sanitized { value: out, report }+}++/// Recursively scrub a JSON value: sensitive keys are replaced wholesale and+/// every string value runs through `sanitize_text`.+pub fn sanitize_json(value: &Value) -> Sanitized<Value> {+ sanitize_json_inner(value, 0)+}++/// Recursive worker behind [`sanitize_json`].+///+/// `depth` counts nesting from the call in `sanitize_json` (which starts at+/// `0`); once it reaches [`MAX_JSON_SANITIZE_DEPTH`] the whole subtree at that+/// point is replaced by a single redaction marker rather than walked further,+/// bounding recursion against pathologically deep or adversarial JSON.+fn sanitize_json_inner(value: &Value, depth: usize) -> Sanitized<Value> {+ if depth >= MAX_JSON_SANITIZE_DEPTH {+ return Sanitized {+ value: Value::String(REDACTED_SECRET.to_string()),+ report: SanitizationReport {+ depth_redactions: 1,+ ..SanitizationReport::default()+ },+ };+ }++ match value {+ Value::Object(map) => {+ let mut out = serde_json::Map::new();+ let mut report = SanitizationReport::default();+ for (key, value) in map {+ if is_sensitive_key(key) {+ report.key_redactions += 1;+ out.insert(key.clone(), Value::String(REDACTED_SECRET.to_string()));+ continue;+ }+ let sanitized = sanitize_json_inner(value, depth + 1);+ report = report.merge(sanitized.report);+ out.insert(key.clone(), sanitized.value);+ }+ Sanitized {+ value: Value::Object(out),+ report,+ }+ }+ Value::Array(items) => {+ let mut out = Vec::with_capacity(items.len());+ let mut report = SanitizationReport::default();+ for item in items {+ let sanitized = sanitize_json_inner(item, depth + 1);+ report = report.merge(sanitized.report);+ out.push(sanitized.value);+ }+ Sanitized {+ value: Value::Array(out),+ report,+ }+ }+ Value::String(value) => {+ let sanitized = sanitize_text(value);+ Sanitized {+ value: Value::String(sanitized.value),+ report: sanitized.report,+ }+ }+ _ => Sanitized {+ value: value.clone(),+ report: SanitizationReport::default(),+ },+ }+}++/// True when a JSON object key's name itself suggests it holds a secret+/// (`api_key`, `token`, `password`, …), independent of the value's contents.+///+/// Matching keys are redacted wholesale in [`sanitize_json_inner`] — the+/// value is replaced rather than scanned, since a key named e.g. `password`+/// is assumed sensitive even if its value doesn't match any+/// [`REDACTION_PATTERNS`] regex. Matching is on the key with all+/// non-alphanumeric characters stripped and lowercased, so `API-Key`,+/// `api_key`, and `apiKey` are all treated identically.+fn is_sensitive_key(key: &str) -> bool {+ let normalized: String = key+ .chars()+ .filter(|c| c.is_ascii_alphanumeric())+ .map(|c| c.to_ascii_lowercase())+ .collect();++ matches!(+ normalized.as_str(),+ "apikey"+ | "token"+ | "accesstoken"+ | "refreshtoken"+ | "authorization"+ | "password"+ | "secret"+ | "clientsecret"+ ) || normalized.ends_with("token")+ || normalized.ends_with("apikey")+ || normalized.ends_with("clientsecret")+ || normalized.contains("password")+ || normalized.contains("secret")+ || normalized.ends_with("key")+}+