Skip to content

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

refactor(extract): make extract response fields and types pub(super)

Steven Enamakeldc0f6248c27a
diff --git a/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs
new file mode 100644
index 0000000000..fe7d1be5c9
--- /dev/null
+++ b/crates/openhuman-core/src/integrations/composio/connected_integrations/fetch.rs
@@ -0,0 +1,252 @@
+//! 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) and the just-in-time [`fetch_toolkit_actions`], plus their
+//! small toolkit-membership/description helpers.
+
+use crate::agent::context::prompt::{ConnectedIntegration, ConnectedIntegrationTool};
+use crate::config::Config;
+
+use super::cache::{cache_key, CachedIntegrations, INTEGRATIONS_CACHE};
+use super::fetch_uncached::fetch_connected_integrations_uncached;
+use crate::integrations::composio::client::ComposioClient;
+use crate::integrations::composio::ops::should_forward_tags;
+
+/// Fetch the user's active Composio connections and their available
+/// tool actions, returning a prompt-ready summary.
+///
+/// This is the **single source of truth** for connected integration
+/// data injected into system prompts — both the agent turn loop and
+/// the debug dump CLI call this function.
+///
+/// Results are cached process-wide (keyed by config identity) and
+/// returned instantly on subsequent calls. The cache is invalidated
+/// when a new connection is created
+/// (via [`invalidate_connected_integrations_cache`]), when a UI
+/// `list_connections` poll observes a divergent live set, when
+/// [`CACHE_TTL`] expires, or on process restart.
+///
+/// Best-effort: returns an empty vec when the user isn't signed in,
+/// the backend is unreachable, or any step fails.
+pub async fn fetch_connected_integrations(config: &Config) -> Vec<ConnectedIntegration> {
+ match fetch_connected_integrations_status(config).await {
+ FetchConnectedIntegrationsStatus::Authoritative(v) => v,
+ FetchConnectedIntegrationsStatus::Unavailable => Vec::new(),
+ }
+}
+
+/// Discriminated outcome from [`fetch_connected_integrations_status`].
+///
+/// Lets callers distinguish "the backend confirmed the user has zero
+/// active connections right now" from "we couldn't talk to the backend
+/// (no client, transient failure, …) and have no truth to report".
+///
+/// The legacy [`fetch_connected_integrations`] collapses both into an
+/// empty `Vec`, which is fine for prompt-building (they look the same)
+/// but dangerous for spawn-time allowlist gates — using empty as truth
+/// in the unavailable case would silently wipe the user's allowlist
+/// during a transient 5xx.
+#[derive(Debug, Clone)]
+pub enum FetchConnectedIntegrationsStatus {
+ /// Backend was reachable. Vec may legitimately be empty (no
+ /// allowlisted toolkits, or no active connections).
+ Authoritative(Vec<ConnectedIntegration>),
+ /// Backend wasn't reachable (no auth client, transient error). The
+ /// caller should fall back to its prior snapshot rather than treat
+ /// "no connections" as truth.
+ Unavailable,
+}
+
+/// Status-returning variant of [`fetch_connected_integrations`].
+///
+/// Same caching, same cache-invalidation semantics — only the return
+/// shape differs. Cache hits are by definition `Authoritative` because
+/// we only cache the `Some(...)` arm of `_uncached` (i.e. results the
+/// backend confirmed).
+pub async fn fetch_connected_integrations_status(
+ config: &Config,
+) -> FetchConnectedIntegrationsStatus {
+ let key = cache_key(config);
+
+ // Fast path: return cached result if fresh. Stale entries fall
+ // through to the backend fetch below so the chat runtime can never
+ // be more than `CACHE_TTL` behind a real-world change.
+ if let Ok(guard) = INTEGRATIONS_CACHE.read() {
+ if let Some(cached) = guard.get(&key) {
+ let age = cached.cached_at.elapsed();
+ if age < CACHE_TTL {
+ tracing::debug!(
+ count = cached.entries.len(),
+ age_ms = age.as_millis() as u64,
+ key = %key,
+ "[composio][integrations] returning cached result"
+ );
+ return FetchConnectedIntegrationsStatus::Authoritative(cached.entries.clone());
+ }
+ tracing::info!(
+ count = cached.entries.len(),
+ age_ms = age.as_millis() as u64,
+ ttl_ms = CACHE_TTL.as_millis() as u64,
+ key = %key,
+ "[composio][integrations] cache entry expired — refetching"
+ );
+ }
+ }
+
+ match fetch_connected_integrations_uncached(config).await {
+ Some(result) => {
+ // Backend was reachable — cache the result (even if empty).
+ if let Ok(mut guard) = INTEGRATIONS_CACHE.write() {
+ guard.insert(
+ key,
+ CachedIntegrations {
+ entries: result.clone(),
+ cached_at: Instant::now(),
+ },
+ );
+ }
+ FetchConnectedIntegrationsStatus::Authoritative(result)
+ }
+ None => {
+ // No auth / client unavailable — do NOT cache so a
+ // subsequent call with a different config can retry.
+ FetchConnectedIntegrationsStatus::Unavailable
+ }
+ }
+}
+
+/// 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.
+/// The connectable toolkit slugs to surface in the agent prompt, aligned
+/// with the backend's execution gate.
+///
+/// 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.
+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()
+ }
+}
+
+/// 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.
+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::providers::toolkit_description(slug).to_string())
+}
+
+/// Just-in-time fetch of every available action for a single Composio
+/// toolkit, returned in the [`ConnectedIntegrationTool`] shape the
+/// `integrations_agent` spawn path expects.
+///
+/// Unlike [`fetch_connected_integrations`] (which bulk-fetches every
+/// connected toolkit's tools once per session and caches the result),
+/// this helper is uncached and scoped to a single toolkit — meant to
+/// be called at `integrations_agent` spawn time so the sub-agent's
+/// prompt always reflects the toolkit's current action catalogue.
+///
+/// The filter `starts_with("{TOOLKIT}_")` matches
+/// `fetch_connected_integrations_uncached`'s own namespacing rule so
+/// siblings like `github` / `git` don't leak into each other's buckets.
+///
+/// `tags` narrows the result by Composio action tag (OR semantics). Only
+/// honoured for the GitHub toolkit; passed through to `list_tools` so the
+/// backend can skip the repo-list force-include and return a focused set.
+///
+/// Returns an empty vec when the backend has no actions for the
+/// toolkit (valid steady state for a freshly-authorised integration
+/// whose catalogue hasn't been published yet). Returns `Err` only for
+/// transport / auth failures the caller should surface to the user.
+pub async fn fetch_toolkit_actions(
+ config: &Config,
+ client: &ComposioClient,
+ toolkit: &str,
+ tags: Option<&[String]>,
+) -> anyhow::Result<Vec<ConnectedIntegrationTool>> {
+ let toolkit_slug = toolkit.trim();
+ if toolkit_slug.is_empty() {
+ anyhow::bail!("fetch_toolkit_actions: toolkit must not be empty");
+ }
+ let effective_tags = if should_forward_tags(Some(&[toolkit_slug.to_string()])) {
+ tags
+ } else {
+ None
+ };
+ tracing::debug!(toolkit = %toolkit_slug, ?effective_tags, "[composio] fetch_toolkit_actions");
+ let resp = client
+ .list_tools(Some(&[toolkit_slug.to_string()]), effective_tags)
+ .await
+ .map_err(|e| anyhow::anyhow!("list_tools failed for toolkit `{toolkit_slug}`: {e}"))?;
+ let action_prefix = format!("{}_", toolkit_slug.to_uppercase());
+ // Apply curated whitelist + user scope so spawn-time tool
+ // discovery agrees with the bulk path and the meta-tool layer.
+ let pref = crate::integrations::composio::ops::load_user_scope_pref(config, toolkit_slug).await;
+ let actions: Vec<ConnectedIntegrationTool> = resp
+ .tools
+ .into_iter()
+ .filter(|t| t.function.name.starts_with(&action_prefix))
+ .filter(|t| crate::integrations::composio::providers::is_action_visible_with_pref(&t.function.name, &pref))
+ .map(|t| ConnectedIntegrationTool {
+ name: t.function.name,
+ description: t.function.description.unwrap_or_default(),
+ parameters: t.function.parameters,
+ })
+ .collect();
+ tracing::debug!(
+ toolkit = %toolkit_slug,
+ action_count = actions.len(),
+ "[composio] fetch_toolkit_actions: done"
+ );
+ Ok(actions)
+}
diff --git a/crates/openhuman-core/src/search/tools/parallel/extract.rs b/crates/openhuman-core/src/search/tools/parallel/extract.rs
index 978bc695c4..6b072c1fd7 100644
--- a/crates/openhuman-core/src/search/tools/parallel/extract.rs
+++ b/crates/openhuman-core/src/search/tools/parallel/extract.rs
@@ -12,33 +12,33 @@ use std::sync::Arc;
pub(super) struct ExtractResponse {
#[serde(rename = "extractId", default)]
#[allow(dead_code)]
- extract_id: String,
+ pub(super) extract_id: String,
#[serde(default)]
- results: Vec<ExtractResultItem>,
+ pub(super) results: Vec<ExtractResultItem>,
#[serde(default)]
- errors: Vec<ExtractError>,
+ pub(super) errors: Vec<ExtractError>,
#[serde(rename = "costUsd", default)]
- cost_usd: f64,
+ pub(super) cost_usd: f64,
}
#[derive(Debug, Deserialize)]
-struct ExtractResultItem {
+pub(super) struct ExtractResultItem {
#[serde(default)]
- url: String,
+ pub(super) url: String,
#[serde(default)]
- title: Option<String>,
+ pub(super) title: Option<String>,
#[serde(default)]
- excerpts: Vec<String>,
+ pub(super) excerpts: Vec<String>,
#[serde(default)]
- full_content: Option<String>,
+ pub(super) full_content: Option<String>,
}
#[derive(Debug, Deserialize)]
-struct ExtractError {
+pub(super) struct ExtractError {
#[serde(default)]
- url: String,
+ pub(super) url: String,
#[serde(default)]
- error: String,
+ pub(super) error: String,
}
// ── ParallelExtractTool ─────────────────────────────────────────────
diff --git a/crates/openhuman-core/src/tools/schemas/apify.rs b/crates/openhuman-core/src/tools/schemas/apify.rs
index 546d0f87ea..d1ca0304ce 100644
--- a/crates/openhuman-core/src/tools/schemas/apify.rs
+++ b/crates/openhuman-core/src/tools/schemas/apify.rs
@@ -28,11 +28,10 @@ pub(super) fn handle_apify_linkedin_scrape(params: Map<String, Value>) -> Contro
.await
.map_err(|e| format!("Apify LinkedIn scrape failed: {e:#}"))?;
- let markdown =
- crate::agent::learning::linkedin_enrichment::render_profile_markdown(
- &profile_url,
- &data,
- );
+ let markdown = crate::agent::learning::linkedin_enrichment::render_profile_markdown(
+ &profile_url,
+ &data,
+ );
let payload = json!({ "data": data, "markdown": markdown });
let log = vec![format!(
@@ -42,4 +41,3 @@ pub(super) fn handle_apify_linkedin_scrape(params: Map<String, Value>) -> Contro
RpcOutcome::new(payload, log).into_cli_compatible_json()
})
}
-
diff --git a/crates/openhuman-core/src/tools/schemas/web_search.rs b/crates/openhuman-core/src/tools/schemas/web_search.rs
index ba7e7c394c..d679109e0f 100644
--- a/crates/openhuman-core/src/tools/schemas/web_search.rs
+++ b/crates/openhuman-core/src/tools/schemas/web_search.rs
@@ -236,7 +236,6 @@ pub(super) fn handle_querit_search(params: Map<String, Value>) -> ControllerFutu
})
}
-
pub(super) fn handle_searxng_search(params: Map<String, Value>) -> ControllerFuture {
Box::pin(async move {
let query = params
@@ -305,7 +304,6 @@ pub(super) fn handle_searxng_search(params: Map<String, Value>) -> ControllerFut
})
}
-
fn optional_string_array(params: &Map<String, Value>, key: &str) -> Result<Vec<String>, String> {
let Some(value) = params.get(key) else {
return Ok(Vec::new());