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): read tool contracts, probe and connected-integrations overview from the tinyconnectors module (#7599)
Steven Enamakel8a8bc6d76612
diff --git a/crates/openhuman-core/src/flows/builder_tools/tool_contract.rs b/crates/openhuman-core/src/flows/builder_tools/tool_contract.rsindex e22f10d48f..c846fe9ea4 100644--- a/crates/openhuman-core/src/flows/builder_tools/tool_contract.rs+++ b/crates/openhuman-core/src/flows/builder_tools/tool_contract.rs@@ -126,8 +126,7 @@ impl Tool for GetToolContractTool {// every GitHub action verified live as of this fix), where// `contract.primary_array_path` would otherwise be// permanently `None`.- let contract =- crate::flows::tinyflows::caps::apply_probe_override(contract.clone());+ let contract = contract.clone();// WS3 — EARLY runtime-gate warning (transcript failure #2): a// real-but-uncurated action of a toolkit that ships a curated@@ -179,7 +178,7 @@ impl Tool for GetToolContractTool {/// for `slug` and derive its `primary_array_path`/`output_fields` from the/// ACTUAL response, overriding `get_tool_contract`'s schema-derived hint for/// this slug from then on (see-/// [`crate::flows::tinyflows::caps::apply_probe_override`]).+/// the module's probe overlay).////// **Exists because a schema-derived hint sometimes doesn't exist at all**:/// Composio's live listing genuinely omits `output_parameters` for somediff --git a/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs b/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rsindex f84e21bbd8..af92f7db6e 100644--- a/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs+++ b/crates/openhuman-core/src/flows/builder_tools_dry_run_tests.rs@@ -1,6 +1,6 @@use super::*;-/// The scope gate runs BEFORE any client/network call, so a Write-scope+/// The module's scope gate runs BEFORE any network call, so a Write-scope/// action is refused entirely offline — this must never depend on a live/// Composio backend to prove the probe can't perform a real mutation.#[tokio::test]@@ -12,7 +12,11 @@ async fn get_tool_output_sample_refuses_a_write_scope_action() {.await.unwrap();assert!(result.is_error);- assert!(result.output().contains("READ-only"), "{}", result.output());+ assert!(+ result.output().to_lowercase().contains("read-only"),+ "{}",+ result.output()+ );}/// The connected-toolkit gate runs before the real call too — in a test@@ -29,7 +33,11 @@ async fn get_tool_output_sample_refuses_an_unconnected_toolkit() {.unwrap();assert!(result.is_error);assert!(- result.output().contains("not connected") || result.output().contains("no active"),+ result.output().contains("not connected")+ || result.output().contains("no active")+ // The module refuses before the connection check when this test+ // process has configured no connector route.+ || result.output().contains("connector route"),"{}",result.output());diff --git a/crates/openhuman-core/src/flows/ops/catalog.rs b/crates/openhuman-core/src/flows/ops/catalog.rsindex b992ac97df..49fcb5b5fb 100644--- a/crates/openhuman-core/src/flows/ops/catalog.rs+++ b/crates/openhuman-core/src/flows/ops/catalog.rs@@ -81,7 +81,7 @@ pub async fn flows_get_tool_contract(.find(|c| crate::integrations::composio::contract::action_slug_matches(&c.slug, trimmed)){Some(contract) => {- let contract = crate::flows::tinyflows::caps::apply_probe_override(contract.clone());+ let contract = contract.clone();let value = serde_json::to_value(&contract).map_err(|e| e.to_string())?;Ok(Outcome::single_log(json!({ "contract": value }),diff --git a/crates/openhuman-core/src/flows/ops/wiring_warnings.rs b/crates/openhuman-core/src/flows/ops/wiring_warnings.rsindex 2a55023b06..99e8a478d3 100644--- a/crates/openhuman-core/src/flows/ops/wiring_warnings.rs+++ b/crates/openhuman-core/src/flows/ops/wiring_warnings.rs@@ -137,7 +137,7 @@ pub(super) async fn graph_output_field_warnings(// exact slug overrides the schema-derived `output_fields` — most// relevant for an action whose live listing publishes no output// schema at all (e.g. every GitHub action, verified live).- let contract = crate::flows::tinyflows::caps::apply_probe_override(contract.clone());+ let contract = contract.clone();// Nothing real to check `field_path` against — schema unknown AND// no probed output fields either.if contract.output_schema.is_none() && contract.output_fields.is_empty() {@@ -252,7 +252,7 @@ fn schema_says_path_is_non_array(output_schema: &Value, configured_path: &str) -/// this already bakes in the `data.` segment Composio's execute-response/// wrapper adds, so `expected` below comes out `"json.data.<…>"` with no/// extra handling needed here — and, via-/// [`crate::flows::tinyflows::caps::apply_probe_override`], a real+/// the module's probe overlay, a real/// `get_tool_output_sample` probe for this slug overrides a schema that/// never named an array at all): if the configured `config.path` doesn't match the/// `json.<primary_array_path>` convention, suggest the real path.@@ -274,7 +274,7 @@ fn schema_says_path_is_non_array(output_schema: &Value, configured_path: &str) -/// `primary_array_path` NOR an `output_schema` is known (truly nothing to/// check against).async fn graph_split_out_path_warnings(config: &Config, graph: &WorkflowGraph) -> Vec<String> {- use crate::flows::tinyflows::caps::{apply_probe_override, fetch_live_toolkit_catalog};+ use crate::flows::tinyflows::caps::fetch_live_toolkit_catalog;use crate::integrations::composio::contract::toolkit_from_slug;let mut warnings = Vec::new();@@ -311,7 +311,7 @@ async fn graph_split_out_path_warnings(config: &Config, graph: &WorkflowGraph) -};// B12: a real-output probe overrides the schema-derived// `primary_array_path` for this exact slug when one is cached.- let contract = apply_probe_override(contract.clone());+ let contract = contract.clone();match contract.primary_array_path.as_deref() {Some(primary) => {diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs b/crates/openhuman-core/src/flows/tinyflows/caps/ops.rsindex 2ab18503ed..b60c795f23 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/ops.rs@@ -38,7 +38,7 @@ use crate::security::{GateDecision, POLICY_BLOCKED_MARKER};#[cfg(test)]pub(crate) use crate::integrations::composio::catalog::ProbedOutputSample;pub(crate) use crate::integrations::composio::catalog::{- apply_probe_override, composio_required_args, fetch_live_toolkit_catalog,+ composio_required_args, fetch_live_toolkit_catalog,probe_tool_output_sample, ToolContract,};#[cfg(test)]diff --git a/crates/openhuman-core/src/integrations/composio/README.md b/crates/openhuman-core/src/integrations/composio/README.mdindex f8dd1fed83..450f4fe234 100644--- a/crates/openhuman-core/src/integrations/composio/README.md+++ b/crates/openhuman-core/src/integrations/composio/README.md@@ -55,8 +55,8 @@ triggers) from a real transport failure.| `crates/openhuman-core/src/integrations/composio/client/{credential,network,direct}.rs` | The direct (BYO-key) reads. `credential.rs` is the key plus a validated base URL (HTTPS-or-loopback guard); `network.rs` resolves the host's `tool.composio` proxy and TLS policy for the module; `direct.rs` calls the module's stateless `ListConnectionsDirect` / `ListToolsDirect` members (the credential rides on the request, so the configured route is untouched and an unsaved key can be probed) under the host's invalid-key gate (`direct_auth`). Redirects are refused and failures are rendered with the messages users see by the module; the v3 paths and reshaping are `tinyconnectors::client::DirectRoute`. || [`crates/openhuman-core/src/integrations/composio/action_tool.rs`](./action_tool.rs) | `ComposioActionTool`: a `Tool` wrapping exactly one Composio action, constructed as a `ToolExposure::Deferred` tool per action of every connected toolkit ([`tools/orchestrator_tools.rs`](../../tools/orchestrator_tools.rs), and [`agent/session_host/recorded_tools.rs`](../../agent/session_host/recorded_tools.rs) when a resumed thread rebuilds its recorded actions), reached by the orchestrator through `tool_search`. || [`crates/openhuman-core/src/integrations/composio/contract_gate.rs`](./contract_gate.rs) | Late-bound action contract gate (#4853): on an action's first call this turn, surfaces the full live contract (via `catalog::fetch_live_toolkit_catalog`) as a recoverable tool error before executing, so the retry has the real schema in context. |-| [`crates/openhuman-core/src/integrations/composio/catalog.rs`](./catalog.rs) + `catalog/` (`contract.rs`, `lookups.rs`, `probe.rs`) | Live Composio tool contracts (`fetch_live_toolkit_catalog`, `ToolContract`, in [`catalog/contract.rs`](./catalog/contract.rs)): the unfiltered mode-aware `list_tools` schema (the module's `ListTools` member on the backend route, or direct v3 `direct_list_tools`) plus a bounded read-only response probe (`probe_tool_output_sample`, [`catalog/probe.rs`](./catalog/probe.rs)) when a schema publishes no `output_parameters`. |-| [`crates/openhuman-core/src/integrations/composio/connected_integrations.rs`](./connected_integrations.rs) + `connected_integrations/` (`cache.rs`, `fetch.rs`, `fetch_uncached.rs`) | Cached active-connections lookups (`cached_active_integrations`, `fetch_connected_integrations*`) reconciled against `list_connections`. |+| [`crates/openhuman-core/src/integrations/composio/catalog.rs`](./catalog.rs) | Call surface over the module's `ListToolContracts` / `ProbeToolOutput` members (`fetch_live_toolkit_catalog`, `probe_tool_output_sample`, `ToolContract` = `tinyconnectors_bus::ComposioToolContract`). The module owns the live fetch, the 30-minute cache, the confirmed-Read probe and its overlay; unit tests seed contracts through the test-only `catalog_seed.rs`. |+| [`crates/openhuman-core/src/integrations/composio/connected_integrations.rs`](./connected_integrations.rs) + `connected_integrations/` (`cache.rs`, `fetch.rs`) | Process cache over the module's `ListConnectedIntegrations` (`cached_active_integrations`, `fetch_connected_integrations*`) reconciled against `list_connections`; `fetch.rs` picks the backend/direct mode and maps the reply to the prompt types. || [`crates/openhuman-core/src/integrations/composio/execute_dispatch.rs`](./execute_dispatch.rs) | Host entry for running one action: applies egress enforcement/disclosure, then calls the module's `EXECUTE` member (prepare → retry → error mapping all run in `tinyconnectors`). Used by the `composio_execute` agent tool, `tools.composio_execute`, the memory host, LinkedIn enrichment and the output probe. || [`crates/openhuman-core/src/integrations/composio/googlecalendar_args.rs`](./googlecalendar_args.rs) | Host IANA time-zone lookup; the calendar defaulting itself is `tinyconnectors::execute::apply_calendar_query_defaults` (#1714). || [`crates/openhuman-core/src/integrations/composio/identity.rs`](./identity.rs) | Resolves the connected account username for a toolkit via the connector module profile-fetch path (used by skill preflight identity gate). |diff --git a/crates/openhuman-core/src/integrations/composio/catalog.rs b/crates/openhuman-core/src/integrations/composio/catalog.rsindex 7955286d15..bac6fa9897 100644--- a/crates/openhuman-core/src/integrations/composio/catalog.rs+++ b/crates/openhuman-core/src/integrations/composio/catalog.rs@@ -1,75 +1,100 @@-//! Live Composio tool contracts: the catalog, the probe, and their caches.+//! Live Composio tool contracts, read from the `tinyconnectors` module.//!-//! What a Composio action really accepts and really returns, sourced from-//! Composio itself rather than from a static curated list — the ground truth the-//! workflow builder authors against, and the enforcement gates validate against.+//! The module owns the fetch, the 30-minute cache, the confirmed-Read output+//! probe and the probe overlay; this file is the host's call surface over its+//! `GetToolContract` / `ListToolContracts` / `ProbeToolOutput` members. The+//! contract and probe types are the `tinyconnectors_bus` ones.//!-//! Two sources, in priority order:-//!-//! 1. **The published schema.** [`fetch_live_toolkit_catalog`] reads Composio's-//! own v3 `/tools` listing and derives a [`ToolContract`] per action.-//! 2. **A real response.** Many actions publish no `output_parameters` at all,-//! so [`probe_tool_output_sample`] makes one bounded, READ-only, real call-//! and derives the same hints from the actual value.-//! [`apply_probe_override`] lets a probe win over a schema, because an-//! observed response outranks a documented one.-//!-//! # Why this lives in `composio`, not in the workflow adapter seam-//!-//! It used to live in the seam, which put the dependency backwards: an-//! always-compiled domain reaching into a feature-gated adapter. That made the-//! adapter impossible to gate off, since `composio` would have followed it out-//! of the build. Everything here is Composio's own vocabulary — action slugs,-//! toolkits, the execute-response envelope, connection scope — so it belongs to-//! the domain that owns that vocabulary. The seam now imports from here.-//!-//! The vendor-neutral half of the work (walking a JSON Schema or a JSON value-//! for its primary array and its field names) is in-//! `tinyagents_harness::tool::schema_walk`.+//! A failed fetch is `None` here, as it always was: callers degrade to+//! "catalog unknown" rather than blocking on a catalog hiccup.-mod contract;-mod lookups;-mod probe;+use crate::config::Config;+use serde_json::Value;+use tinyconnectors_bus::names::methods;+use tinyconnectors_bus::{+ ComposioListToolContractsRequest, ComposioListToolContractsResponse,+ ComposioProbeToolOutputRequest,+};++pub use tinyconnectors_bus::ComposioProbedOutputSample as ProbedOutputSample;+pub use tinyconnectors_bus::ComposioToolContract as ToolContract;#[cfg(test)]-#[path = "catalog_in_flight_tests_tests.rs"]-mod in_flight_tests;+#[path = "catalog_seed.rs"]+mod seed;+#[cfg(test)]+pub(crate) use seed::{seed_live_catalog_cache, seed_live_catalog_cache_expired, seed_probe_cache};#[cfg(test)]#[path = "catalog_tests.rs"]mod tests;-pub(crate) use contract::fetch_live_toolkit_catalog;-#[cfg(test)]-pub(crate) use contract::seed_live_catalog_cache;-#[cfg(all(test, feature = "flows"))]-pub(crate) use contract::seed_live_catalog_cache_expired;-pub use contract::ToolContract;-#[cfg(any(test, feature = "flows"))]-pub(crate) use lookups::composio_required_args;-#[cfg(test)]-pub(crate) use probe::ProbedOutputSample;-#[cfg(any(test, feature = "flows"))]-pub(crate) use probe::{apply_probe_override, probe_tool_output_sample};-#[cfg(test)]-pub(crate) use probe::{seed_probe_cache, seed_probe_cache_expired};+/// Every real action Composio publishes for `toolkit`, with any cached probe+/// already overlaid by the module. `None` on any failure.+pub(crate) async fn fetch_live_toolkit_catalog(+ config: &Config,+ toolkit: &str,+) -> Option<Vec<ToolContract>> {+ #[cfg(test)]+ if let Some(seeded) = seed::seeded_catalog(toolkit) {+ return Some(seeded);+ }+ let toolkit = toolkit.trim().to_ascii_lowercase();+ match super::module_client::call::<_, ComposioListToolContractsResponse>(+ config,+ methods::LIST_TOOL_CONTRACTS,+ ComposioListToolContractsRequest {+ toolkit: toolkit.clone(),+ },+ )+ .await+ {+ Ok(resp) => Some(resp.contracts),+ Err(error) => {+ tracing::debug!(target: "flows", %toolkit, %error,+ "[composio][catalog] ListToolContracts failed — catalog unknown");+ None+ }+ }+}-// Brought into this module's own namespace (private `use`, not `pub use`) so-// `catalog_tests.rs` / `catalog_in_flight_tests_tests.rs` — declared as-// direct child modules of `catalog` above — can still reach the-// implementation details they exercise via a plain `use super::*;`, exactly-// as when this was one un-split file. See each item's `pub(super)` in its-// owning submodule.-#[cfg(test)]-use crate::config::Config;-#[cfg(test)]-use contract::{compute_composio_array_path, live_catalog_fetch_lock};-#[cfg(test)]-use lookups::composio_response_fields;-#[cfg(test)]-use probe::{- cache_probe_result, probed_output_sample, resolve_composio_action_scope,- COMPOSIO_ENVELOPE_META_KEYS_AT_ROOT,-};-#[cfg(test)]-use serde_json::Value;+/// One bounded, confirmed-Read real call whose response shape the module+/// derives and caches. Refusals come back as the module's message.+pub(crate) async fn probe_tool_output_sample(+ config: &Config,+ slug: &str,+ args: Value,+) -> Result<ProbedOutputSample, String> {+ super::module_client::call::<_, ProbedOutputSample>(+ config,+ methods::PROBE_TOOL_OUTPUT,+ ComposioProbeToolOutputRequest {+ slug: slug.trim().to_string(),+ args,+ },+ )+ .await+}++/// A Composio action's **required** top-level parameter names, or `None` when+/// the schema is unavailable (so callers skip the preflight).+pub(crate) async fn composio_required_args(config: &Config, slug: &str) -> Option<Vec<String>> {+ let toolkit = super::contract::toolkit_from_slug(slug)?;+ let contracts = fetch_live_toolkit_catalog(config, &toolkit).await?;+ contracts+ .iter()+ .find(|c| c.slug.eq_ignore_ascii_case(slug))+ .map(|c| c.required_args.clone())+}++/// A Composio action's response top-level field names. `None` when no output+/// schema is known; `Some(vec![])` when one is known and names no properties.+pub(crate) async fn composio_response_fields(config: &Config, slug: &str) -> Option<Vec<String>> {+ let toolkit = super::contract::toolkit_from_slug(slug)?;+ let contracts = fetch_live_toolkit_catalog(config, &toolkit).await?;+ let contract = contracts+ .iter()+ .find(|c| c.slug.eq_ignore_ascii_case(slug))?;+ contract.output_schema.as_ref()?;+ Some(contract.output_fields.clone())+}diff --git a/crates/openhuman-core/src/integrations/composio/catalog_in_flight_tests_tests.rs b/crates/openhuman-core/src/integrations/composio/catalog_in_flight_tests_tests.rsdeleted file mode 100644index 1b8584ae6a..0000000000--- a/crates/openhuman-core/src/integrations/composio/catalog_in_flight_tests_tests.rs+++ /dev/null@@ -1,10 +0,0 @@-use super::*;--#[test]-fn catalog_miss_locks_are_shared_per_toolkit_only() {- let first = live_catalog_fetch_lock("test-lock-a").unwrap();- let same = live_catalog_fetch_lock("test-lock-a").unwrap();- let other = live_catalog_fetch_lock("test-lock-b").unwrap();- assert!(std::sync::Arc::ptr_eq(&first, &same));- assert!(!std::sync::Arc::ptr_eq(&first, &other));-}diff --git a/crates/openhuman-core/src/integrations/composio/catalog_seed.rs b/crates/openhuman-core/src/integrations/composio/catalog_seed.rsnew file mode 100644index 0000000000..85ed3e6db6--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/catalog_seed.rs@@ -0,0 +1,62 @@+//! Test-only stand-in for the module's catalog and probe caches.+//!+//! The real caches live inside the loaded `tinyconnectors` module, which unit+//! tests cannot reach, so tests seed contracts here and+//! [`super::fetch_live_toolkit_catalog`] answers from them first. A seeded+//! probe is overlaid the way the module overlays a cached one.++use super::{ProbedOutputSample, ToolContract};+use std::collections::HashMap;+use std::sync::{Mutex, OnceLock};++static CATALOGS: OnceLock<Mutex<HashMap<String, Vec<ToolContract>>>> = OnceLock::new();+static PROBES: OnceLock<Mutex<HashMap<String, ProbedOutputSample>>> = OnceLock::new();++fn key(s: &str) -> String {+ s.trim().to_ascii_lowercase()+}++pub(crate) fn seed_live_catalog_cache(toolkit: &str, contracts: Vec<ToolContract>) {+ CATALOGS+ .get_or_init(Default::default)+ .lock()+ .expect("catalog seed poisoned")+ .insert(key(toolkit), contracts);+}++/// An expired module entry means a refetch; with no module in unit tests that+/// is "unknown", so expiring removes the seed.+pub(crate) fn seed_live_catalog_cache_expired(toolkit: &str, _contracts: Vec<ToolContract>) {+ CATALOGS+ .get_or_init(Default::default)+ .lock()+ .expect("catalog seed poisoned")+ .remove(&key(toolkit));+}++pub(crate) fn seed_probe_cache(slug: &str, sample: ProbedOutputSample) {+ PROBES+ .get_or_init(Default::default)+ .lock()+ .expect("probe seed poisoned")+ .insert(key(slug), sample);+}++pub(super) fn seeded_catalog(toolkit: &str) -> Option<Vec<ToolContract>> {+ let mut contracts = CATALOGS+ .get_or_init(Default::default)+ .lock()+ .expect("catalog seed poisoned")+ .get(&key(toolkit))+ .cloned()?;+ let probes = PROBES.get_or_init(Default::default).lock().ok()?;+ for contract in &mut contracts {+ if let Some(probe) = probes.get(&key(&contract.slug)) {+ contract.primary_array_path = probe.primary_array_path.clone();+ if !probe.output_fields.is_empty() {+ contract.output_fields = probe.output_fields.clone();+ }+ }+ }+ Some(contracts)+}diff --git a/crates/openhuman-core/src/integrations/composio/catalog_tests.rs b/crates/openhuman-core/src/integrations/composio/catalog_tests.rsindex 6e0c1fc76b..4e46dc3e14 100644--- a/crates/openhuman-core/src/integrations/composio/catalog_tests.rs+++ b/crates/openhuman-core/src/integrations/composio/catalog_tests.rs@@ -1,445 +1,79 @@-//! Unit tests for the live Composio catalog and the real-output probe.-//!-//! Moved here with the code they exercise. Two of them-//! (`cache_probe_result_*`, `resolve_composio_action_scope_*`) reach private-//! helpers, which is the reason they must live in this module rather than be-//! reachable from the adapter seam: widening a helper to `pub(crate)` purely so-//! a foreign test can call it would leak implementation surface to the whole-//! crate to satisfy a test.--use tinyagents_harness::tool::compute_primary_array_path_from_value;-// `super` is `catalog` itself — this file is included as its child module — so-// the glob reaches its private helpers as well as its imports.use super::*;-use serde_json::json;--// ── compute_composio_array_path (B1: the `data` wrapper prefix) ─────────--#[test]-fn compute_composio_array_path_prefixes_data_for_an_unwrapped_payload_schema() {- // The real shape: Composio's `output_parameters` for GMAIL_FETCH_EMAILS- // describes the payload directly — no `data` key in the schema — but- // the tool_call's real runtime output nests that payload one level- // deeper under `data` (`ComposioExecuteResponse`). The array path must- // account for that even though the schema itself never mentions `data`.- let schema = json!({- "type": "object",- "properties": {- "messages": { "type": "array" },- "nextPageToken": { "type": "string" }- }- });- assert_eq!(- compute_composio_array_path(Some(&schema)),- Some("data.messages".to_string())- );-}--#[test]-fn compute_composio_array_path_still_prefixes_data_when_the_payload_schema_itself_has_a_data_key() {- // A payload whose own real shape happens to have a top-level `data`- // key (unrelated to Composio's wrapper — e.g. a provider that- // itself returns `{data: {messages: [...]}}`) must NOT be mistaken- // for "this schema already models the envelope". `output_parameters`- // always describes the payload only (see `ToolContract::output_fields`'s- // doc) — the real runtime path still needs the wrapper's `data.`- // prefix stacked on top, landing on `data.data.messages`, not- // `data.messages`.- let schema = json!({- "type": "object",- "properties": {- "data": {- "type": "object",- "properties": { "messages": { "type": "array" } }- }- }- });- assert_eq!(- compute_composio_array_path(Some(&schema)),- Some("data.data.messages".to_string())- );-}--#[test]-fn compute_composio_array_path_none_when_the_bare_walk_finds_nothing() {- assert_eq!(compute_composio_array_path(None), None);- assert_eq!(- compute_composio_array_path(Some(- &json!({ "type": "object", "properties": { "id": { "type": "string" } } })- )),- None- );-}-// ── compute_primary_array_path_from_value (B12: the real-output probe) ──--#[test]-fn compute_primary_array_path_from_value_finds_a_named_array_under_data() {- // The exact GITHUB_LIST_REPOSITORY_ISSUES shape observed live: the- // real array lives at `data.issues` (a NAMED field), not `data.items`- // — and there is no schema at all to derive this from (verified live:- // `output_schema: null` for this action), so only a real-value probe- // can find it.- let value = json!({- "data": { "issues": [ { "id": 1 }, { "id": 2 } ], "total_count": 2 },- "successful": true,- "error": null,- "costUsd": 0.0,- "markdownFormatted": null- });- assert_eq!(- compute_primary_array_path_from_value(&value, COMPOSIO_ENVELOPE_META_KEYS_AT_ROOT),- Some("data.issues".to_string())- );-}--#[test]-fn compute_primary_array_path_from_value_skips_envelope_metadata_at_the_root() {- // None of the envelope's OTHER top-level fields are ever arrays in- // practice, but the skip-list is explicit so one never wins a- // shallowest-wins tie against a real nested array.- let value = json!({- "successful": true,- "error": null,- "costUsd": 0.0,- "markdownFormatted": null,- "data": { "messages": ["a", "b"] }- });- assert_eq!(- compute_primary_array_path_from_value(&value, COMPOSIO_ENVELOPE_META_KEYS_AT_ROOT),- Some("data.messages".to_string())- );-}--#[test]-fn compute_primary_array_path_from_value_none_when_no_array_anywhere() {- let value = json!({- "data": { "id": "abc123", "name": "octocat" },- "successful": true- });- assert_eq!(- compute_primary_array_path_from_value(&value, COMPOSIO_ENVELOPE_META_KEYS_AT_ROOT),- None- );- assert_eq!(- compute_primary_array_path_from_value(&json!(null), COMPOSIO_ENVELOPE_META_KEYS_AT_ROOT),- None- );- assert_eq!(- compute_primary_array_path_from_value(- &json!("scalar"),- COMPOSIO_ENVELOPE_META_KEYS_AT_ROOT- ),- None- );-}--// ── apply_probe_override (B12) ───────────────────────────────────────────--fn bare_contract(slug: &str) -> ToolContract {+fn contract(slug: &str, toolkit: &str, required: &[&str], fields: &[&str]) -> ToolContract {ToolContract {- slug: slug.to_string(),- toolkit: "github".to_string(),- description: None,- required_args: vec![],- input_schema: None,- output_fields: vec![],- output_schema: None,- primary_array_path: None,- is_curated: true,- }-}--#[test]-fn apply_probe_override_overlays_a_cached_probe_onto_a_schemaless_contract() {- seed_probe_cache(- "PROBETEST_LIST_REPOSITORY_ISSUES",- ProbedOutputSample {- primary_array_path: Some("data.issues".to_string()),- output_fields: vec!["issues".to_string(), "total_count".to_string()],- sample: json!({ "data": { "issues": [], "total_count": 0 } }),- },- );- let contract = bare_contract("PROBETEST_LIST_REPOSITORY_ISSUES");- assert_eq!(contract.primary_array_path, None);- let overridden = apply_probe_override(contract);- assert_eq!(- overridden.primary_array_path,- Some("data.issues".to_string())- );- assert_eq!(- overridden.output_fields,- vec!["issues".to_string(), "total_count".to_string()]- );-}--#[test]-fn apply_probe_override_passes_through_unchanged_without_a_cached_probe() {- let contract = bare_contract("PROBETEST_SOME_UNPROBED_ACTION");- let overridden = apply_probe_override(contract.clone());- assert_eq!(overridden.primary_array_path, contract.primary_array_path);- assert_eq!(overridden.output_fields, contract.output_fields);-}--/// E-m8: an EXPIRED `PROBE_CACHE` entry must behave exactly like "never-/// probed" — `apply_probe_override` must NOT apply it. Before the TTL-/// fix a probe result was permanent for the process's lifetime, so a-/// corrected/changed real response stayed masked by the first-ever probe-/// until restart.-#[test]-fn apply_probe_override_ignores_an_expired_cached_probe() {- seed_probe_cache_expired(- "PROBETEST_EXPIRED_ACTION",- ProbedOutputSample {- primary_array_path: Some("data.issues".to_string()),- output_fields: vec!["issues".to_string()],- sample: json!({ "data": { "issues": [] } }),- },- );- let contract = bare_contract("PROBETEST_EXPIRED_ACTION");- let overridden = apply_probe_override(contract.clone());- assert_eq!(- overridden.primary_array_path, contract.primary_array_path,- "an expired probe must not overlay onto the contract"- );- assert_eq!(overridden.output_fields, contract.output_fields);- assert!(probed_output_sample("PROBETEST_EXPIRED_ACTION").is_none());-}--/// CodeRabbit (PR #4702 review): a probe that OBSERVED the real response-/// and found no array anywhere must CLEAR a stale schema-derived-/// `primary_array_path`, not merely leave it in place because the probe's-/// own path happens to be `None`. A schema-derived path a real-/// observation just disproved is worse than no path at all — it would-/// otherwise keep suggesting a `split_out.path` the probe itself showed-/// is wrong.-#[test]-fn apply_probe_override_clears_a_stale_schema_path_when_the_probe_finds_no_array() {- seed_probe_cache(- "PROBETEST_CLEARS_STALE_PATH",- ProbedOutputSample {- primary_array_path: None,- output_fields: vec![],- sample: json!({ "data": { "id": "abc123" } }),- },- );- let mut contract = bare_contract("PROBETEST_CLEARS_STALE_PATH");- contract.primary_array_path = Some("data.items".to_string());- let overridden = apply_probe_override(contract);- assert_eq!(overridden.primary_array_path, None);-}--/// PR #4702 review (security): the process-wide [`PROBE_CACHE`] must-/// never retain the raw observed payload — only derived metadata. A real-/// probe response can carry one user/connection/args' actual private-/// data (repo issues, messages, …), and nothing that reads the CACHE-/// (only [`apply_probe_override`], via [`probed_output_sample`]) ever-/// needs the raw payload.-#[test]-fn cache_probe_result_redacts_the_raw_sample_before_caching() {- cache_probe_result(- "PROBETEST_REDACTS_SAMPLE",- ProbedOutputSample {- primary_array_path: Some("data.issues".to_string()),- output_fields: vec!["issues".to_string()],- sample: json!({ "data": { "issues": [{"secret": "do-not-retain"}] } }),- },- );- let cached = probed_output_sample("PROBETEST_REDACTS_SAMPLE").expect("just cached this slug");- assert_eq!(cached.sample, Value::Null);- // The derived metadata is still cached faithfully — only the raw- // payload is redacted.- assert_eq!(cached.primary_array_path, Some("data.issues".to_string()));-}--// ── resolve_composio_action_scope (B12: hard Read-only gate) ─────────────--#[test]-fn resolve_composio_action_scope_uses_the_curated_catalog_when_available() {- use crate::integrations::composio::contract::ToolScope;- // GITHUB_LIST_REPOSITORY_ISSUES is curated as Read (github/tools.rs).- assert_eq!(- resolve_composio_action_scope("GITHUB_LIST_REPOSITORY_ISSUES"),- Some(ToolScope::Read)- );- // A curated Write action must classify as Write, not Read — the probe- // must refuse it regardless of the verb heuristic agreeing or not.- assert_eq!(- resolve_composio_action_scope("GMAIL_SEND_EMAIL"),- Some(ToolScope::Write)- );-}--/// PR #4702 review (P1): a toolkit with a static curated catalog (like-/// `github`) must NOT fall through to the `classify_unknown` verb-/// heuristic for a slug that isn't actually one of its curated actions —-/// `GITHUB_LIST_WORKFLOWS` is a REAL GitHub action name (reads as-/// Read-scope by its `LIST` verb) that was deliberately left uncurated-/// (see the commented-out entry in `github/tools.rs`), so this must-/// resolve to `None` (fail closed), not `Some(ToolScope::Read)` — the-/// heuristic agreeing with the "looks safe" name is exactly the-/// misclassification hole this guards against.-#[test]-fn resolve_composio_action_scope_rejects_an_uncurated_slug_on_a_cataloged_toolkit() {- assert_eq!(resolve_composio_action_scope("GITHUB_LIST_WORKFLOWS"), None);-}--#[test]-fn resolve_composio_action_scope_falls_back_to_the_verb_heuristic_only_without_a_static_catalog() {- use crate::integrations::composio::contract::ToolScope;- assert_eq!(- resolve_composio_action_scope("MADEUPTOOLKIT_LIST_THINGS"),- Some(ToolScope::Read)- );- assert_eq!(- resolve_composio_action_scope("MADEUPTOOLKIT_DELETE_THING"),- Some(ToolScope::Admin)- );-}--// ── probe_tool_output_sample (B12: gates) ────────────────────────────────--#[tokio::test]-async fn probe_tool_output_sample_refuses_a_non_read_action_before_any_client_call() {- let config = Config::default();- let result = probe_tool_output_sample(&config, "GMAIL_SEND_EMAIL", json!({})).await;- let err = result.expect_err("a Write action must be refused");- assert!(err.contains("READ-only"), "{err}");-}--/// PR #4702 review (P1): the probe entry point itself must refuse an-/// uncurated-but-read-sounding slug on a cataloged toolkit BEFORE any-/// client call — not just `resolve_composio_action_scope` in isolation.-#[tokio::test]-async fn probe_tool_output_sample_refuses_an_uncurated_slug_on_a_cataloged_toolkit_before_any_client_call(-) {- let config = Config::default();- let result = probe_tool_output_sample(&config, "GITHUB_LIST_WORKFLOWS", json!({})).await;- let err = result.expect_err("an uncurated slug on a cataloged toolkit must be refused");- assert!(err.contains("could not confirm"), "{err}");-}--// ── fetch_live_toolkit_catalog / composio_required_args /-// composio_response_fields delegation ─────────────────────────────────--fn contract(slug: &str, toolkit: &str, required: &[&str], output_fields: &[&str]) -> ToolContract {- let output_schema = if output_fields.is_empty() {- None- } else {- Some(json!({- "type": "object",- "properties": output_fields- .iter()- .map(|f| (f.to_string(), json!({ "type": "string" })))- .collect::<serde_json::Map<String, Value>>()- }))- };- ToolContract {- slug: slug.to_string(),- toolkit: toolkit.to_string(),+ slug: slug.into(),+ toolkit: toolkit.into(),description: None,required_args: required.iter().map(|s| s.to_string()).collect(),input_schema: None,- output_fields: output_fields.iter().map(|s| s.to_string()).collect(),- output_schema,+ output_fields: fields.iter().map(|s| s.to_string()).collect(),+ output_schema: if fields.is_empty() {+ None+ } else {+ Some(serde_json::json!({"type": "object"}))+ },primary_array_path: None,is_curated: false,}}#[tokio::test]-async fn fetch_live_toolkit_catalog_returns_the_seeded_cache_without_a_network_call() {- let config = Config::default();+async fn a_seeded_catalog_answers_without_calling_the_module() {seed_live_catalog_cache(- "flowscatalogkit",- vec![contract(- "FLOWSCATALOGKIT_DO_THING",- "flowscatalogkit",- &["to"],- &["id", "threadId"],- )],+ "hostseam1",+ vec![contract("HOSTSEAM1_A", "hostseam1", &["x"], &[])],);-- let catalog = fetch_live_toolkit_catalog(&config, "flowscatalogkit")+ let got = fetch_live_toolkit_catalog(&Config::default(), "HOSTSEAM1").await- .expect("seeded catalog must be returned without a network call");- assert_eq!(catalog.len(), 1);- assert_eq!(catalog[0].slug, "FLOWSCATALOGKIT_DO_THING");-- // Case/whitespace-insensitive on the toolkit key.- let same = fetch_live_toolkit_catalog(&config, " FlowsCatalogKit ")- .await- .expect("cache lookup is case/whitespace-insensitive");- assert_eq!(same.len(), 1);+ .expect("seeded");+ assert_eq!(got.len(), 1);+ assert_eq!(got[0].slug, "HOSTSEAM1_A");}#[tokio::test]-async fn composio_required_args_and_response_fields_delegate_to_the_live_catalog() {- let config = Config::default();+async fn required_args_and_response_fields_project_the_catalog() {seed_live_catalog_cache(- "flowsreqkit",- vec![contract(- "FLOWSREQKIT_SEND",- "flowsreqkit",- &["to", "body"],- &["id", "threadId"],- )],+ "hostseam2",+ vec![+ contract("HOSTSEAM2_LIST", "hostseam2", &["q"], &["items"]),+ contract("HOSTSEAM2_BARE", "hostseam2", &[], &[]),+ ],);-+ let cfg = Config::default();assert_eq!(- composio_required_args(&config, "FLOWSREQKIT_SEND").await,- Some(vec!["to".to_string(), "body".to_string()])+ composio_required_args(&cfg, "hostseam2_list").await,+ Some(vec!["q".to_string()]));assert_eq!(- composio_response_fields(&config, "FLOWSREQKIT_SEND").await,- Some(vec!["id".to_string(), "threadId".to_string()])+ composio_response_fields(&cfg, "HOSTSEAM2_LIST").await,+ Some(vec!["items".to_string()]));-- // An unknown slug within a known/seeded toolkit yields None (not a- // panic, not an empty-vec false positive).+ // Real action with no published output schema: unknown, not empty.+ assert_eq!(composio_response_fields(&cfg, "HOSTSEAM2_BARE").await, None);assert_eq!(- composio_required_args(&config, "FLOWSREQKIT_UNKNOWN_ACTION").await,- None- );- assert_eq!(- composio_response_fields(&config, "FLOWSREQKIT_UNKNOWN_ACTION").await,+ composio_required_args(&cfg, "HOSTSEAM2_MISSING").await,None);}#[tokio::test]-async fn composio_response_fields_distinguishes_unknown_schema_from_empty_fields() {- let config = Config::default();-- // Schema KNOWN but empty (`properties: {}`) → `Some(vec![])`.- seed_live_catalog_cache(- "flowsschemaempty",- vec![{- let mut c = contract("FLOWSSCHEMAEMPTY_ACTION", "flowsschemaempty", &[], &[]);- c.output_schema = Some(json!({ "type": "object", "properties": {} }));- c- }],- );- assert_eq!(- composio_response_fields(&config, "FLOWSSCHEMAEMPTY_ACTION").await,- Some(Vec::new()),- "schema known but empty must be Some(vec![]), not None"- );-- // Schema UNKNOWN (`output_schema: None`, the degrade-gracefully case)- // → `None`, even though the slug itself is found in the catalog.+async fn a_seeded_probe_is_overlaid_onto_the_contract() {seed_live_catalog_cache(- "flowsschemaunknown",- vec![contract(- "FLOWSSCHEMAUNKNOWN_ACTION",- "flowsschemaunknown",- &[],- &[],- )],+ "hostseam3",+ vec![contract("HOSTSEAM3_X", "hostseam3", &[], &["a"])],);- assert_eq!(- composio_response_fields(&config, "FLOWSSCHEMAUNKNOWN_ACTION").await,- None,- "an action with no published output schema must be None, not Some(vec![])"+ seed_probe_cache(+ "HOSTSEAM3_X",+ ProbedOutputSample {+ primary_array_path: Some("data.rows".into()),+ output_fields: vec!["rows".into()],+ sample: serde_json::Value::Null,+ },);+ let got = fetch_live_toolkit_catalog(&Config::default(), "hostseam3")+ .await+ .unwrap();+ assert_eq!(got[0].primary_array_path.as_deref(), Some("data.rows"));+ assert_eq!(got[0].output_fields, vec!["rows".to_string()]);}diff --git a/crates/openhuman-core/src/integrations/composio/client.rs b/crates/openhuman-core/src/integrations/composio/client.rsindex bea08e8c3a..dd89cc236f 100644--- a/crates/openhuman-core/src/integrations/composio/client.rs+++ b/crates/openhuman-core/src/integrations/composio/client.rs@@ -21,6 +21,7 @@ mod tests;pub use credential::DirectCredential;pub use direct::direct_list_connections;+#[cfg(test)]pub(crate) use direct::direct_list_tools;pub(crate) use factory::create_direct_client_for_api_key;pub use factory::{resolve_composio_route, ComposioRoute};diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations.rsindex 9076975655..0681e1ec64 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations.rs@@ -1,18 +1,9 @@//! Connected-integrations discovery: the process-wide [`cache`] fronting a-//! mode-aware backend/direct [`fetch`] (whose uncached backend walk lives in-//! [`fetch_uncached`] since it is one large, sequential routine).+//! mode switch [`fetch`]. The backend/direct walk itself is the module's+//! `ListConnectedIntegrations` member.mod cache;mod fetch;-mod fetch_uncached;--#[cfg(test)]-#[path = "connected_integrations_connectable_slug_tests_tests.rs"]-mod connectable_slug_tests;--#[cfg(test)]-#[path = "connected_integrations_catalog_description_tests_tests.rs"]-mod catalog_description_tests;pub(crate) use cache::sync_cache_with_connections;pub use cache::{@@ -25,15 +16,8 @@ pub use fetch::{FetchConnectedIntegrationsStatus,};-// Brought into this module's own namespace (private `use`, not `pub use`)-// so `connected_integrations_connectable_slug_tests_tests.rs` /-// `connected_integrations_catalog_description_tests_tests.rs` — declared as-// direct child modules of `connected_integrations` above — can still reach-// these via a plain `use super::<name>;`, exactly as when this was one-// un-split file. See each item's `pub(super)` in its owning submodule.+// Test-only access to the cache internals for the sibling cache tests.#[cfg(test)]pub(crate) use cache::{cache_key, read_cached_integrations_from, CachedIntegrations, INTEGRATIONS_CACHE,-};-#[cfg(test)]-pub(crate) use fetch::{connectable_toolkit_slugs, resolve_toolkit_description};+};\ No newline at end of filediff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rsindex 4324d8c0a1..58fac4e563 100644--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs@@ -1,7 +1,6 @@//! The public fetch surface for connected integrations://! [`fetch_connected_integrations`] / [`fetch_connected_integrations_status`]-//! (cache-fronted, calling [`super::fetch_uncached::fetch_connected_integrations_uncached`]-//! on a miss), plus their small toolkit-membership/description helpers.+//! (cache-fronted; a miss asks the module's `ListConnectedIntegrations`).use std::sync::atomic::Ordering;@@ -11,7 +10,6 @@ use crate::config::Config;use super::cache::{cache_generation, checked_cache_key, store_fetched_integrations, INTEGRATIONS_CACHE,};-use super::fetch_uncached::fetch_connected_integrations_uncached;/// Fetch the user's active Composio connections and their available/// tool actions, returning a prompt-ready summary.@@ -133,61 +131,108 @@ pub async fn fetch_connected_integrations_status(}}-/// The connectable toolkit slugs to surface in the agent prompt, aligned-/// with the backend's execution gate.+/// The cache-miss fetch: ask the module for the overview of the live route and+/// map it to the prompt types.///-/// Prefers the dynamic catalog's **enabled** entries (openhuman PR #3933 /-/// backend #1012). The backend gate (`isToolkitConnectable` →-/// `getProjectList().filter(p => p.enabled)`) and `catalog[].enabled` are-/// driven by the same project auth-config status, so sourcing membership from-/// `catalog.filter(enabled)` pins the prompt's advertised set to exactly what-/// connect/authorize/execute will actually allow — it can't drift even if the-/// backend later changes how the flat `toolkits` array is projected.-///-/// Falls back to the back-compat `toolkits` array when the catalog is absent-/// (backends predating the dynamic catalog send only `toolkits`); without the-/// fallback, membership against an old core would collapse to empty and the-/// agent would lose every integration. Disabled catalog entries are dropped-/// because the gate would reject them — advertising them would only invite-/// failed delegations. Slugs are trimmed + lowercased to match downstream-/// canonicalisation.-pub(crate) fn connectable_toolkit_slugs(- toolkits: &[String],- catalog: &[crate::integrations::composio::types::ComposioToolkitCatalogEntry],-) -> Vec<String> {- let normalize = |s: &str| s.trim().to_ascii_lowercase();- if catalog.is_empty() {- toolkits- .iter()- .map(|t| normalize(t))- .filter(|t| !t.is_empty())- .collect()- } else {- catalog- .iter()- .filter(|entry| entry.enabled.unwrap_or(false))- .map(|entry| normalize(&entry.slug))- .filter(|slug| !slug.is_empty())- .collect()- }-}+/// `None` when no route can be built (not signed in) or the module call fails,+/// so the caller does NOT cache the failure -- a single 5xx during startup must+/// not hide every integration for the rest of the session.+#[inline(never)]+fn fetch_connected_integrations_uncached(+ config: &Config,+) -> futures::future::BoxFuture<'_, Option<Vec<ConnectedIntegration>>> {+ Box::pin(async move {+ use tinyconnectors_bus::names::methods;+ use tinyconnectors_bus::{+ ComposioConnectedIntegrationsMode as Mode, ComposioConnectedIntegrationsResponse,+ ComposioListConnectedIntegrationsRequest,+ };-/// Choose the one-line description rendered for a toolkit in the agent-/// prompt's `## Connected Integrations` block.-///-/// Prefers the backend's **dynamic catalog** description (openhuman PR #3933-/// / backend #1012 — `GET /agent-integrations/composio/toolkits` now returns-/// a `catalog[]` with per-toolkit metadata) so the orchestrator advertises-/// what Composio actually offers. Falls back to the hardcoded-/// `toolkit_description` table when the catalog omits the toolkit or ships an-/// empty description — i.e. older backends that predate the dynamic catalog,-/// or project toolkits whose Composio metadata join produced no blurb. Keyed-/// by lowercased slug to match the canonicalised allowlist.-pub(crate) fn resolve_toolkit_description(- catalog_descriptions: &std::collections::HashMap<String, String>,- slug: &str,-) -> String {- catalog_descriptions.get(slug).cloned().unwrap_or_else(|| {- crate::integrations::composio::contract::toolkit_description(slug).to_string()+ let mode = match crate::integrations::composio::client::resolve_composio_route(config) {+ Ok(crate::integrations::composio::client::ComposioRoute::Backend) => Mode::Backend,+ Ok(crate::integrations::composio::client::ComposioRoute::Direct(_)) => Mode::Direct,+ Err(error) => {+ tracing::debug!(%error,+ "[composio][integrations] no client (not signed in?)");+ return None;+ }+ };+ match crate::integrations::composio::module_client::call::<+ _,+ ComposioConnectedIntegrationsResponse,+ >(+ config,+ methods::LIST_CONNECTED_INTEGRATIONS,+ ComposioListConnectedIntegrationsRequest { mode },+ )+ .await+ {+ Ok(resp) => Some(to_prompt_integrations(resp)),+ Err(error) => {+ tracing::warn!(?mode, %error,+ "[composio][integrations] ListConnectedIntegrations failed");+ None+ }+ }})}++/// Map the module's overview to the agent prompt's types. The unlock text for a+/// gated action is product copy, so it is built here from the scope.+pub(crate) fn to_prompt_integrations(+ resp: tinyconnectors_bus::ComposioConnectedIntegrationsResponse,+) -> Vec<ConnectedIntegration> {+ use crate::agent::prompts::{+ ConnectedIntegrationTool, GatedIntegrationTool, IntegrationConnection,+ };+ resp.integrations+ .into_iter()+ .map(|i| {+ let toolkit = i.toolkit;+ ConnectedIntegration {+ tools: i+ .tools+ .into_iter()+ .map(|t| ConnectedIntegrationTool {+ name: t.name,+ description: t.description,+ parameters: t.parameters,+ })+ .collect(),+ gated_tools: i+ .gated_tools+ .into_iter()+ .map(|g| {+ let scope = g.required_scope.as_str();+ GatedIntegrationTool {+ name: g.name,+ description: g.description,+ required_scope: scope.to_string(),+ unlock_paths: vec![format!(+ "the user enables it themselves in \+ Connections → {toolkit} → {scope}"+ )],+ }+ })+ .collect(),+ connections: i+ .connections+ .into_iter()+ .map(|c| IntegrationConnection {+ connection_id: c.connection_id,+ label: c.label,+ is_default: c.is_default,+ })+ .collect(),+ description: i.description,+ connected: i.connected,+ non_active_status: i.non_active_status,+ toolkit,+ }+ })+ .collect()+}++#[cfg(test)]+#[path = "fetch_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch_tests.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch_tests.rsnew file mode 100644index 0000000000..85c1845b51--- /dev/null+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch_tests.rs@@ -0,0 +1,63 @@+use super::*;+use tinyconnectors_bus::vocabulary::ToolScope;+use tinyconnectors_bus::{+ ComposioConnectedIntegration, ComposioConnectedIntegrationTool,+ ComposioConnectedIntegrationsResponse, ComposioGatedIntegrationTool,+ ComposioIntegrationConnection,+};++fn overview() -> ComposioConnectedIntegrationsResponse {+ ComposioConnectedIntegrationsResponse {+ integrations: vec![+ ComposioConnectedIntegration {+ toolkit: "gmail".into(),+ description: "mail".into(),+ tools: vec![ComposioConnectedIntegrationTool {+ name: "GMAIL_FETCH_EMAILS".into(),+ description: "fetch".into(),+ parameters: Some(serde_json::json!({"type": "object"})),+ }],+ gated_tools: vec![ComposioGatedIntegrationTool {+ name: "GMAIL_DELETE_MESSAGE".into(),+ description: "delete".into(),+ required_scope: ToolScope::Admin,+ }],+ connected: true,+ connections: vec![ComposioIntegrationConnection {+ connection_id: "c1".into(),+ label: Some("[email protected]".into()),+ is_default: true,+ }],+ non_active_status: None,+ },+ ComposioConnectedIntegration {+ toolkit: "notion".into(),+ description: "notes".into(),+ tools: vec![],+ gated_tools: vec![],+ connected: false,+ connections: vec![],+ non_active_status: Some("EXPIRED".into()),+ },+ ],+ }+}++#[test]+fn the_module_overview_maps_to_the_prompt_types() {+ let out = to_prompt_integrations(overview());+ assert_eq!(out.len(), 2);+ let gmail = &out[0];+ assert!(gmail.connected);+ assert_eq!(gmail.tools[0].name, "GMAIL_FETCH_EMAILS");+ assert_eq!(gmail.connections[0].connection_id, "c1");+ assert!(gmail.connections[0].is_default);+ let gated = &gmail.gated_tools[0];+ assert_eq!(gated.required_scope, "admin");+ assert_eq!(+ gated.unlock_paths,+ vec!["the user enables it themselves in Connections → gmail → admin".to_string()]+ );+ assert_eq!(out[1].non_active_status.as_deref(), Some("EXPIRED"));+ assert!(out[1].tools.is_empty());+}diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch_uncached.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch_uncached.rsdeleted file mode 100644index 8fecdec18c..0000000000--- a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch_uncached.rs+++ /dev/null@@ -1,526 +0,0 @@-//! [`fetch_connected_integrations_uncached`] — the actual mode-aware-//! backend/direct fetch behind [`super::fetch::fetch_connected_integrations_status`]'s-//! cache miss path. Kept in its own file because it is one large,-//! sequential fetch-then-merge routine that resists a further-//! responsibility split without changing its behavior.--use crate::agent::prompts::{ConnectedIntegration, ConnectedIntegrationTool, GatedIntegrationTool};-use crate::config::Config;--use super::fetch::{connectable_toolkit_slugs, resolve_toolkit_description};--/// The actual backend fetch, called on cache miss.-///-/// Returns `Some(vec)` when the backend was reachable. The returned-/// vector is the merged **integration overview** — every toolkit in-/// the backend allowlist appears as one entry, with a `connected`-/// flag indicating whether the user has an active OAuth connection.-/// Connected entries also carry the per-action tool catalogue-/// (fetched in a single batched call).-///-/// Returns `None` when we couldn't even build a client (no auth),-/// signalling the caller should NOT cache this result.-///-/// Returned boxed and `#[inline(never)]` on purpose: an `async fn` body is-/// otherwise re-instantiated inside every crate / codegen unit that awaits it,-/// and these state machines are large. Boxing here keeps one copy, compiled in-/// this crate.-#[inline(never)]-pub(super) fn fetch_connected_integrations_uncached(- config: &Config,-) -> futures::future::BoxFuture<'_, Option<Vec<ConnectedIntegration>>> {- Box::pin(fetch_connected_integrations_uncached_inner(config))-}--async fn fetch_connected_integrations_uncached_inner(- config: &Config,-) -> Option<Vec<ConnectedIntegration>> {- use super::super::client::{direct_list_connections, resolve_composio_route, ComposioRoute};- use super::super::module_client::{self as connectors};- use super::super::types::{- ComposioConnectionsResponse, ComposioListToolsRequest, ComposioToolkitsResponse,- ComposioToolsResponse,- };- use tinyconnectors_bus::names::methods;-- // Route via the mode-aware factory so the chat-agent's- // "connected_integrations" view reflects the live tenant — backend- // (tinyhumans) or direct (user's personal Composio). Prior to #1710- // Wave 3 this path called `build_composio_client` directly, which- // is backend-only — after a `composio.mode = "direct"` toggle the- // cache kept replaying the tinyhumans-tenant connections back into- // the integration overview (e.g. gmail / notion appearing as- // connected in direct mode even when the user's direct tenant had- // a different set of toolkits). Resolving per call closes the- // loop: `ComposioConfigChangedSubscriber` invalidates the cache on- // toggle and the next miss re-populates it from the live tenant.- let kind = match resolve_composio_route(config) {- Ok(kind) => kind,- Err(e) => {- tracing::debug!(- error = %e,- "[composio] fetch_connected_integrations: no client (not signed in?)"- );- return None;- }- };-- // Pull the allowlist + connections + tool catalogue. Backend mode- // walks the tinyhumans tenant's curated allowlist via- // `list_toolkits`; direct mode has no centralised allowlist (per- // `ops::composio_list_toolkits`'s direct-mode branch) so the- // user's set of active connections IS the universe of valid- // toolkit arguments.- //- // On transient errors we return `None` instead of a degraded- // `Some(Vec::new())` so `fetch_connected_integrations` does NOT- // cache the failure. Caching an empty allowlist would hide every- // integration from the orchestrator until the process restarts or- // the cache is explicitly invalidated — a single 5xx during- // startup would silently break delegation for the whole session.- let (allowlisted_toolkits, connections, tools_by_toolkit, catalog_descriptions): (- Vec<String>,- Vec<super::super::types::ComposioConnection>,- Vec<super::super::types::ComposioToolSchema>,- std::collections::HashMap<String, String>,- ) = match &kind {- ComposioRoute::Backend => {- let (allowlist, catalog_descriptions): (- Vec<String>,- std::collections::HashMap<String, String>,- ) = match connectors::call_bare::<ComposioToolkitsResponse>(- config,- methods::LIST_TOOLKITS,- )- .await- {- Ok(resp) => {- // Index the dynamic catalog's descriptions by lowercased- // slug so the prompt builder can prefer them over the- // hardcoded table (see `resolve_toolkit_description`).- // Empty descriptions are skipped so the fallback applies.- let catalog_descriptions: std::collections::HashMap<String, String> = resp- .catalog- .iter()- .filter_map(|entry| {- let slug = entry.slug.trim().to_ascii_lowercase();- if slug.is_empty() {- return None;- }- let desc = entry- .description- .as_deref()- .map(str::trim)- .filter(|d| !d.is_empty())?;- Some((slug, desc.to_string()))- })- .collect();- // Source the connectable set from the catalog's enabled- // entries (the gate's own predicate), falling back to the- // flat `toolkits` array for pre-catalog backends. See- // `connectable_toolkit_slugs`.- let allowlist = connectable_toolkit_slugs(&resp.toolkits, &resp.catalog);- tracing::debug!(- catalog_entries = resp.catalog.len(),- catalog_descriptions = catalog_descriptions.len(),- connectable = allowlist.len(),- catalog_sourced = !resp.catalog.is_empty(),- "[composio] fetch_connected_integrations: resolved connectable set from catalog"- );- (allowlist, catalog_descriptions)- }- Err(e) => {- tracing::warn!(- "[composio] fetch_connected_integrations: list_toolkits (backend) failed: {e}"- );- return None;- }- };-- if allowlist.is_empty() {- tracing::debug!(- "[composio] fetch_connected_integrations: backend allowlist is empty"- );- return Some(Vec::new());- }-- let connections = match connectors::call_bare::<ComposioConnectionsResponse>(- config,- methods::LIST_CONNECTIONS,- )- .await- {- Ok(resp) => resp.connections,- Err(e) => {- tracing::warn!(- "[composio] fetch_connected_integrations: list_connections (backend) failed: {e}"- );- return None;- }- };-- // Tool catalogue scoped to the active subset only —- // not-connected toolkits won't be invoked from a sub-agent.- let connected_slugs_for_tools: Vec<String> = {- let mut v: Vec<String> = connections- .iter()- .filter(|c| c.is_active())- .map(|c| c.normalized_toolkit())- .filter(|t| !t.is_empty())- .collect();- v.sort();- v.dedup();- v- };- let tools = if connected_slugs_for_tools.is_empty() {- Vec::new()- } else {- match connectors::call::<_, ComposioToolsResponse>(- config,- methods::LIST_TOOLS,- ComposioListToolsRequest {- toolkits: connected_slugs_for_tools.clone(),- tags: Vec::new(),- apply_user_scopes: false,- },- )- .await- {- Ok(resp) => resp.tools,- Err(e) => {- tracing::warn!(- "[composio] fetch_connected_integrations: list_tools (backend) failed: {e}"- );- return None;- }- }- };-- (allowlist, connections, tools, catalog_descriptions)- }- ComposioRoute::Direct(direct) => {- // Direct mode: walk the user's personal Composio tenant- // for *connection state* (active accounts on their key) —- // there's no central allowlist in direct mode, so the- // active set IS the allowlist.- //- // Tool *schemas* are tenant-agnostic — Composio's action- // definitions (e.g. GMAIL_SEND_EMAIL parameter shape) are- // identical regardless of which Composio tenant a user is- // connected via. So we best-effort fetch schemas through- // the backend client (curated list_tools) if a backend- // session is available, even though connection routing- // goes to the user's direct tenant. This preserves the- // chat agent's "21 gmail actions available" view while- // execution itself (via `ComposioActionTool` / Wave 1- // factory) still routes to the user's tenant. Direct-only- // users without a backend session get empty tools — that- // matches `composio_list_tools`'s direct-mode policy.- let connections = match direct_list_connections(config, direct).await {- Ok(resp) => resp.connections,- Err(e) => {- tracing::warn!(- "[composio] fetch_connected_integrations: list_connections (direct) failed: {e:#}"- );- return None;- }- };- let allowlist: Vec<String> = {- let mut v: Vec<String> = connections- .iter()- .filter(|c| c.is_active())- .map(|c| c.normalized_toolkit())- .filter(|t| !t.is_empty())- .collect();- v.sort();- v.dedup();- v- };- if allowlist.is_empty() {- tracing::info!(- "[composio-direct] fetch_connected_integrations: direct tenant has no active connections; returning empty overview"- );- return Some(Vec::new());- }- tracing::debug!(- connected = allowlist.len(),- "[composio-direct] fetch_connected_integrations: using direct tenant's active set as allowlist (no central allowlist in direct mode)"- );-- // Tool schemas are tenant-agnostic, but direct mode must keep- // every Composio request on the user's direct route. Failure is- // non-fatal — lazy resolution can still discover actions later.- let tools = match super::super::client::direct_list_tools(- config, direct, &allowlist, None,- )- .await- {- Ok(resp) => {- tracing::debug!(- count = resp.tools.len(),- "[composio-direct] fetch_connected_integrations: pulled tool schemas from direct route"- );- resp.tools- }- Err(e) => {- tracing::info!(- "[composio-direct] fetch_connected_integrations: direct list_tools failed (will use lazy fallback at delegation time): {e:#}"- );- Vec::new()- }- };- // Direct mode has no central catalog endpoint, so prompt- // descriptions come from the hardcoded fallback table.- (- allowlist,- connections,- tools,- std::collections::HashMap::new(),- )- }- };-- // Active connection slugs (status filter mirrors the original logic).- let connected_slugs: std::collections::HashSet<String> = connections- .iter()- .filter(|c| c.is_active())- .map(|c| c.normalized_toolkit())- .filter(|toolkit| !toolkit.is_empty())- .collect();-- // Most-informative *non-active* status per toolkit slug (#2365):- // distinguishes a connection row that isn't usable yet (`INITIATED`- // — OAuth still in progress) or any longer (`EXPIRED` / `FAILED`)- // — instead of the legacy generic "available but not authorized".- //- // Status priority (UI-actionability):- // 1. EXPIRED — reconnect path- // 2. FAILED / ERROR — reconnect path- // 3. INITIATED / INITIALIZING / PENDING — finish OAuth in browser- // 4. anything else — passes through verbatim- let non_active_status_by_slug: std::collections::HashMap<String, String> = {- fn priority(status: &str) -> u8 {- let s = status.trim().to_ascii_uppercase();- match s.as_str() {- "EXPIRED" => 4,- "FAILED" | "ERROR" => 3,- "INITIATED" | "INITIALIZING" | "PENDING" => 2,- _ => 1,- }- }- let mut map: std::collections::HashMap<String, (u8, String)> =- std::collections::HashMap::new();- for conn in connections.iter().filter(|c| !c.is_active()) {- let slug = conn.normalized_toolkit();- if slug.is_empty() {- continue;- }- // Don't override an ACTIVE-slug — those carry no non-active- // status from this map's perspective.- if connected_slugs.contains(&slug) {- continue;- }- let p = priority(&conn.status);- map.entry(slug.clone())- .and_modify(|cur| {- if p > cur.0 {- tracing::debug!(- target: "composio",- toolkit = %slug,- previous_status = %cur.1,- previous_priority = cur.0,- new_status = %conn.status,- new_priority = p,- "[composio] non_active_status_by_slug: upgraded most-informative status"- );- *cur = (p, conn.status.clone());- } else {- tracing::trace!(- target: "composio",- toolkit = %slug,- kept_status = %cur.1,- kept_priority = cur.0,- candidate_status = %conn.status,- candidate_priority = p,- "[composio] non_active_status_by_slug: kept higher-priority status"- );- }- })- .or_insert_with(|| {- tracing::debug!(- target: "composio",- toolkit = %slug,- status = %conn.status,- priority = p,- "[composio] non_active_status_by_slug: first non-active row"- );- (p, conn.status.clone())- });- }- let final_map: std::collections::HashMap<String, String> =- map.into_iter().map(|(k, (_, v))| (k, v)).collect();- tracing::debug!(- target: "composio",- entries = final_map.len(),- "[composio] non_active_status_by_slug: final map"- );- final_map- };-- // Deduplicate the allowlist so a backend that returns duplicates- // doesn't produce dual entries downstream.- let mut unique_toolkits: Vec<String> = allowlisted_toolkits.clone();- unique_toolkits.sort();- unique_toolkits.dedup();-- // Build one entry per allowlisted toolkit. Connected entries- // carry their action catalogue; not-connected entries carry an- // empty `tools` vec.- let mut integrations: Vec<ConnectedIntegration> = Vec::with_capacity(unique_toolkits.len());- for slug in &unique_toolkits {- let connected = connected_slugs.contains(slug);- // Anchor the prefix with an underscore so slugs that share- // a text prefix (e.g. `git` vs `github`) don't false-match- // each other's actions. `GMAIL_SEND_EMAIL` matches `gmail_`,- // not just `gmail`, so siblings stay in their own buckets.- let action_prefix = format!("{}_", slug.to_uppercase());- let (tools, gated_tools): (Vec<ConnectedIntegrationTool>, Vec<GatedIntegrationTool>) =- if connected {- // Apply the same curated-whitelist + user-scope filter the- // meta-tool layer uses, so a prompt only advertises actions- // the agent is actually allowed to call. One pref load per toolkit (not per action).- //- // Actions that the catalog *does* know about but the user's- // current scope pref denies are routed into `gated_tools` so- // the agent can honestly answer "I have this capability but- // it needs the {scope} toggle in Connections → {toolkit}".- // The agent cannot flip the scope itself — that's a UI-only- // action. Without this gated surface the LLM has no way to- // know the gated action exists at all and will tell the user- // "I don't support that" — technically correct about its- // callable surface, but misleading about the toolkit.- let pref = super::super::ops::load_user_scope_pref(config, slug).await;- let mut visible: Vec<ConnectedIntegrationTool> = Vec::new();- let mut gated: Vec<GatedIntegrationTool> = Vec::new();- for t in tools_by_toolkit- .iter()- .filter(|t| t.function.name.starts_with(&action_prefix))- {- if super::super::contract::is_action_visible_with_pref(&t.function.name, &pref)- {- visible.push(ConnectedIntegrationTool {- name: t.function.name.clone(),- description: t.function.description.clone().unwrap_or_default(),- parameters: t.function.parameters.clone(),- });- } else if let Some(required_scope) =- super::super::contract::curated_scope_for(&t.function.name)- {- // Only surface CURATED actions as `gated` — uncurated- // tools (which fall through to `classify_unknown` and- // happen to land outside the user's pref) are not- // first-class user-facing capabilities, and listing- // them would clutter the prompt with internal slugs.- // Deliberately NO `parameters` field: the LLM should- // not be able to construct a call envelope; it can- // only describe + point at the unlock path.- // Ship the unlock path as data — single path today- // (the Connections UI toggle). The agent does NOT- // have a tool to flip scopes; that capability was- // removed because LLM-mediated scope elevation made- // the safety contract depend on model behavior and- // was a soft gate the model could route around. If- // more unlock paths exist in future (per-action- // approval modal, time-boxed elevation, etc.) they- // land here and the prompt renderer picks them up.- let scope_str = required_scope.as_str();- let unlock_paths = vec![format!(- "the user enables it themselves in \- Connections → {slug} → {scope_str}"- )];- gated.push(GatedIntegrationTool {- name: t.function.name.clone(),- description: t.function.description.clone().unwrap_or_default(),- required_scope: scope_str.to_string(),- unlock_paths,- });- }- }- tracing::debug!(- toolkit = %slug,- visible = visible.len(),- gated = gated.len(),- "[composio][scopes] integrations prompt action set"- );- (visible, gated)- } else {- (Vec::new(), Vec::new())- };-- let integration_connections: Vec<crate::agent::prompts::IntegrationConnection> =- if connected {- let mut conns: Vec<_> = connections- .iter()- .filter(|c| c.is_active() && c.normalized_toolkit() == *slug)- .collect();- conns.sort_by(|a, b| a.created_at.cmp(&b.created_at));- conns- .iter()- .enumerate()- .map(|(idx, c)| {- let label = [- c.account_email.as_deref(),- c.workspace.as_deref(),- c.username.as_deref(),- ]- .into_iter()- .flatten()- .map(str::trim)- .find(|s| !s.is_empty())- .map(str::to_string);- crate::agent::prompts::IntegrationConnection {- connection_id: c.id.clone(),- label,- is_default: idx == 0,- }- })- .collect()- } else {- Vec::new()- };-- integrations.push(ConnectedIntegration {- toolkit: slug.clone(),- description: resolve_toolkit_description(&catalog_descriptions, slug),- tools,- gated_tools,- connected,- connections: integration_connections,- non_active_status: if connected {- None- } else {- non_active_status_by_slug.get(slug).cloned()- },- });- }-- integrations.sort_by(|a, b| a.toolkit.cmp(&b.toolkit));-- let connected_count = integrations.iter().filter(|i| i.connected).count();- tracing::info!(- total = integrations.len(),- connected = connected_count,- "[composio] fetch_connected_integrations: done"- );- for ci in &integrations {- tracing::debug!(- toolkit = %ci.toolkit,- connected = ci.connected,- non_active_status = ?ci.non_active_status,- tool_count = ci.tools.len(),- "[composio] integration overview"- );- }-- Some(integrations)-}diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations_catalog_description_tests_tests.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations_catalog_description_tests_tests.rsdeleted file mode 100644index efdcdf3802..0000000000--- a/crates/openhuman-core/src/integrations/composio/connected_integrations_catalog_description_tests_tests.rs+++ /dev/null@@ -1,39 +0,0 @@-use super::resolve_toolkit_description;-use std::collections::HashMap;--#[test]-fn prefers_dynamic_catalog_description_when_present() {- let mut catalog = HashMap::new();- catalog.insert(- "gmail".to_string(),- "Live Gmail blurb from the Composio catalog".to_string(),- );- assert_eq!(- resolve_toolkit_description(&catalog, "gmail"),- "Live Gmail blurb from the Composio catalog"- );-}--#[test]-fn falls_back_to_hardcoded_table_when_catalog_omits_toolkit() {- // Empty catalog (older backend / no metadata) → hardcoded fallback.- let catalog = HashMap::new();- let got = resolve_toolkit_description(&catalog, "gmail");- assert_eq!(- got,- crate::integrations::composio::contract::toolkit_description("gmail")- );- assert!(!got.is_empty());-}--#[test]-fn falls_back_when_a_different_toolkit_is_catalogued() {- // Catalog has an entry, but not for the slug we're rendering — the- // fallback must still apply per-slug, not globally.- let mut catalog = HashMap::new();- catalog.insert("notion".to_string(), "Notion from catalog".to_string());- assert_eq!(- resolve_toolkit_description(&catalog, "gmail"),- crate::integrations::composio::contract::toolkit_description("gmail")- );-}diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations_connectable_slug_tests_tests.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations_connectable_slug_tests_tests.rsdeleted file mode 100644index 477fe256ac..0000000000--- a/crates/openhuman-core/src/integrations/composio/connected_integrations_connectable_slug_tests_tests.rs+++ /dev/null@@ -1,48 +0,0 @@-use super::connectable_toolkit_slugs;-use crate::integrations::composio::types::ComposioToolkitCatalogEntry;--fn entry(slug: &str, enabled: bool) -> ComposioToolkitCatalogEntry {- ComposioToolkitCatalogEntry {- slug: slug.to_string(),- enabled: Some(enabled),- ..Default::default()- }-}--#[test]-fn prefers_catalog_enabled_entries_and_drops_disabled() {- // Disabled entries are excluded (the gate would reject them); the- // flat `toolkits` array is ignored when a catalog is present.- let catalog = vec![- entry("gmail", true),- entry("notion", false),- entry("GitHub", true), // uppercase slug normalised- ];- let toolkits = vec!["ignored_when_catalog_present".to_string()];- assert_eq!(- connectable_toolkit_slugs(&toolkits, &catalog),- vec!["gmail".to_string(), "github".to_string()]- );-}--#[test]-fn falls_back_to_toolkits_when_catalog_empty() {- // Older backends send only `toolkits`; membership must still resolve.- let toolkits = vec!["Gmail".to_string(), " ".to_string()];- assert_eq!(- connectable_toolkit_slugs(&toolkits, &[]),- vec!["gmail".to_string()]- );-}--#[test]-fn enabled_none_is_treated_as_not_connectable() {- // Defensive: an entry without an explicit `enabled` is excluded,- // matching the gate's strict `enabled === true` check.- let catalog = vec![ComposioToolkitCatalogEntry {- slug: "mystery".to_string(),- enabled: None,- ..Default::default()- }];- assert!(connectable_toolkit_slugs(&[], &catalog).is_empty());-}diff --git a/crates/openhuman-core/src/modules/connectors.rs b/crates/openhuman-core/src/modules/connectors.rsindex 607724cb09..25250ed943 100644--- a/crates/openhuman-core/src/modules/connectors.rs+++ b/crates/openhuman-core/src/modules/connectors.rs@@ -66,6 +66,29 @@ pub use names::methods;pub fn module_config(config: &Config) -> Result<serde_json::Value, String> {let state_dir = config.workspace_dir.join("state");+ // A host-pinned credential outranks the mode and the credential store, the+ // way `resolve_composio_route` resolves it, so the module's configured route+ // (executes, the connected-integrations overview) is the pinned tenant too.+ if let Some(pinned) = config.composio.host_credential.as_ref() {+ let base = pinned.direct_base_urls().map(|urls| urls.v3.clone());+ let destination = base+ .as_deref()+ .unwrap_or("https://backend.composio.dev/api/v3");+ let mut payload = serde_json::json!({+ "route": "direct",+ "api_key": pinned.api_key(),+ "entity_id": pinned.entity(),+ "base_url": base,+ "state_dir": state_dir,+ });+ if let Some(transport) =+ crate::integrations::composio::client::module_transport(destination)+ {+ payload["transport"] = serde_json::json!(transport);+ }+ return Ok(payload);+ }+match config.composio.mode.trim() {// Empty is the default, for hand-edited configs that omit the field."" | COMPOSIO_MODE_BACKEND => {diff --git a/crates/openhuman-core/src/modules/connectors_tests.rs b/crates/openhuman-core/src/modules/connectors_tests.rsindex c7076423ba..ff151a8582 100644--- a/crates/openhuman-core/src/modules/connectors_tests.rs+++ b/crates/openhuman-core/src/modules/connectors_tests.rs@@ -245,3 +245,19 @@ fn direct_auth_refusals_preserve_the_provider_status_and_prevent_duplicate_repor&message));}++#[test]+fn a_host_pinned_credential_outranks_the_mode_and_the_store() {+ let mut config = bare_config();+ config.composio.mode = COMPOSIO_MODE_BACKEND.into();+ config.composio.pin_host_credential(+ crate::config::ComposioHostCredential::direct("ck_pinned")+ .entity_id("tenant-7")+ .base_urls("http://127.0.0.1:1/v2", "http://127.0.0.1:1/v3"),+ );+ let route = module_config(&config).expect("pinned credential names a route");+ assert_eq!(route["route"], "direct");+ assert_eq!(route["api_key"], "ck_pinned");+ assert_eq!(route["entity_id"], "tenant-7");+ assert_eq!(route["base_url"], "http://127.0.0.1:1/v3");+}diff --git a/docs/module-boundary-inventory.md b/docs/module-boundary-inventory.mdindex 7e307f5dab..00d3ac6a0c 100644--- a/docs/module-boundary-inventory.md+++ b/docs/module-boundary-inventory.md@@ -15,7 +15,7 @@ copying its implementation into a host, or accepting weaker isolation.| Owner | Linked implementation packages | Contract | Host consumers | Required module work || --- | --- | --- | --- | --- || tinyjuice | none (module loaded through TinyBus) | tinyjuice-bus | core tools, compression, CCR REPL | Complete: PR #59 provides module-owned compression, CCR queries, HTML extraction, schemas and declarations; handle/marker parsing (`tinyjuice_bus::handle`) and `juice_*` tool-name constants (`tinyjuice_bus::tools`) live in the bus since contract 2.2; the host retains turn-bound model callbacks and artifact authorization |-| tinyconnectors | none | tinyconnectors-bus | core integrations, credentials and triggers | Module-backed argument preparation, action execution, trigger archives and the curated toolkit catalogs (`ListCuratedCatalog`, `GetVocabulary`, held as a process snapshot) and per-toolkit scope preferences (`GetUserScopes`, `SetUserScopes`; a legacy workspace file is migrated into the module once); host credential reconciliation and frozen tool restoration remain in OpenHuman |+| tinyconnectors | none | tinyconnectors-bus | core integrations, credentials and triggers | Module-backed argument preparation, action execution, trigger archives and the curated toolkit catalogs (`ListCuratedCatalog`, `GetVocabulary`, held as a process snapshot) and per-toolkit scope preferences (`GetUserScopes`, `SetUserScopes`; a legacy workspace file is migrated into the module once), live tool-contract fetch/cache (`GetToolContract`, `ListToolContracts`), the confirmed-Read output probe (`ProbeToolOutput`) and the backend/direct connected-integrations walk (`ListConnectedIntegrations`, contract 1.20); the host keeps the overview cache, mode switch, prompt mapping and `contract_gate`; host credential reconciliation and frozen tool restoration remain in OpenHuman || tinymcp | none in normal/build host dependencies | tinymcp-bus | core MCP registry, supervisor, CLI stdio/HTTP server | Merged host adapters use the released v0.15.0 module (contract 1.22; configured-client receipt machine and client cache are `tinymcp_bus::client_lifecycle`, host keeps only the bus-calling driver) for registry, supervisor, client and server protocol operations, with approved host callbacks kept in OpenHuman. The 62-member artifact and local focused, lifecycle, registry, native and build gates pass; frozen recorded tool declarations are restored independently of the current catalog || tinychannels | tinychannels, tinychannels-runtime, tinychannels-module (test-only) | tinychannels-bus | core channels, TinyHumans host, CLI REPL | Contract 16 (operation 1.17) is pure; scoped providers, inbound/identity/outbound preparation, remote commands, runtime limits, typing and progressive delivery execute through confidential module calls. Host-owned policy, credentials, persistence and callbacks remain in OpenHuman. Both host implementation exceptions are removed; the 254-test focused suite and released-artifact runtime fixture pass || tinyhosts | none | tinyhosts-bus | core hosting tools | Released Execute/Providers contract consumed through the module (v0.4.0: tool-to-operation mapping, argument shaping, outcome matching and summaries live in `tinyhosts-bus::tools`); workspace authorization, credentials and approval policy remain in OpenHuman |