The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(skills): serve catalog browse, search, facets and detail from the registry
oxoxDevbc976a5a06bb
diff --git a/crates/openhuman-core/src/skills/catalog/mod.rs b/crates/openhuman-core/src/skills/catalog/mod.rsindex a4df0ef1b8..919131cd50 100644--- a/crates/openhuman-core/src/skills/catalog/mod.rs+++ b/crates/openhuman-core/src/skills/catalog/mod.rs@@ -23,6 +23,8 @@ mod registry;pub mod schemas;#[cfg(feature = "skills")]pub mod store;+#[cfg(all(test, feature = "skills"))]+pub(crate) mod test_fixtures;#[cfg(feature = "skills")]pub mod tools;#[cfg(feature = "skills")]diff --git a/crates/openhuman-core/src/skills/catalog/ops.rs b/crates/openhuman-core/src/skills/catalog/ops.rsindex 7235e6c508..e177423d27 100644--- a/crates/openhuman-core/src/skills/catalog/ops.rs+++ b/crates/openhuman-core/src/skills/catalog/ops.rs@@ -1,54 +1,35 @@-//! Business logic for the skill registry: fetch, index, search, and install.+//! Business logic for the skill registry: thin adapters over the tinyskills+//! [`SkillRegistry`] for browse, search, facets, detail and install.//!-//! The catalog is sourced from the HermesHub aggregated JSON API which-//! includes skills from HermesHub (built-in + optional), ClawHub, skills.sh,-//! LobeHub, and browse.sh — all accessible from a single endpoint.+//! The registry owns fetching, caching, stale-while-revalidate, single-flight+//! refresh, ranking and `SKILL.md` resolution. This module maps OpenHuman's+//! queries onto it, shapes the results for RPC and tools, and applies the+//! host's install and reporting policy.-use std::future::Future;-use std::sync::atomic::{AtomicBool, Ordering};+use std::path::Path;-use tokio::sync::Mutex;+use tinyskills::{+ EntryKey, ReadPolicy, RegistryError, RegistryErrorKind, SkillDetail, SkillQuery, SkillRegistry,+ SkillSummary,+};-use tinyskills::SkillsShRef;+use super::registry::skill_registry;+use super::types::{+ CatalogDetail, CatalogEntry, CatalogPage, CatalogQuery, RegistryCatalogEntry, RegistryFacets,+ DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE,+};+use crate::skills::ops_install::InstallWorkflowFromUrlOutcome;-use super::download;-use super::store;-use super::store::CachedCatalog;-use super::types::CatalogEntry;--const CATALOG_URL: &str = "https://hermes-agent.nousresearch.com/docs/api/skills.json";-const CATALOG_URL_ENV: &str = "OPENHUMAN_SKILL_REGISTRY_CATALOG_URL";const REFRESH_ON_BOOT_ENV: &str = "OPENHUMAN_SKILL_REGISTRY_REFRESH_ON_BOOT";-const FETCH_TIMEOUT_SECS: u64 = 180;--/// Single-flight gate for catalog fetches. On mount the skills explorer issues-/// several catalog reads that each funnel into [`browse_catalog`] — `sources`-/// and `browse` from two separate effects, plus `search` as the user types —-/// and React StrictMode double-invokes those effects in dev, so a handful of-/// reads land within the same instant. Without this lock each would issue its-/// own ~80s download of the same ~90k-entry catalog. Concurrent cache-miss-/// callers serialize here, and all but the first re-read the just-written cache-/// instead of hitting the network.-static FETCH_LOCK: Mutex<()> = Mutex::const_new(());--/// True while a background (stale-while-revalidate) refresh is scheduled or-/// running, so a burst of stale-cache reads spawns at most one refresh task.-static REFRESHING: AtomicBool = AtomicBool::new(false);--/// Clears [`REFRESHING`] when the background refresh task ends (incl. panic).-struct RefreshGuard;-impl Drop for RefreshGuard {- fn drop(&mut self) {- REFRESHING.store(false, Ordering::Release);- }-}+/// Prefix of every registry error a caller sees, followed by the+/// upper-cased [`RegistryErrorKind`] and `: `.+pub const REGISTRY_ERROR_PREFIX: &str = "SKILL_REGISTRY_";-/// Start a one-shot background refresh of the remote skills catalog.+/// Start a one-shot background warm-up of the skill registry.///-/// This is intended for core startup: it warms the explorer/search cache without+/// Loads the stored catalog (or fetches one when none is stored) without/// making core readiness depend on registry availability. Set-/// `OPENHUMAN_SKILL_REGISTRY_REFRESH_ON_BOOT=0` to disable it in constrained-/// environments.+/// `OPENHUMAN_SKILL_REGISTRY_REFRESH_ON_BOOT=0` to disable it.pub fn start_boot_catalog_refresh() {static STARTED: std::sync::Once = std::sync::Once::new();@@ -61,23 +42,22 @@ pub fn start_boot_catalog_refresh() {return;}- tracing::info!("[skill_registry] scheduling boot catalog refresh");+ tracing::info!("[skill_registry] scheduling boot catalog warm-up");tokio::spawn(async {let started = std::time::Instant::now();- match browse_catalog(true).await {- Ok(entries) => {- tracing::info!(- count = entries.len(),+ let statuses = skill_registry().warm().await;+ for status in statuses {+ match &status.last_error {+ None => tracing::info!(+ registry = %status.id,+ entries = status.entry_count,+ freshness = ?status.freshness,elapsed_ms = started.elapsed().as_millis(),- "[skill_registry] boot catalog refresh complete"- );- }- Err(error) => {- tracing::warn!(- error = %error,- elapsed_ms = started.elapsed().as_millis(),- "[skill_registry] boot catalog refresh failed"- );+ "[skill_registry] boot warm-up complete"+ ),+ Some(error) => {+ observe_summary("warm", error);+ }}}});@@ -93,354 +73,325 @@ fn refresh_on_boot_enabled(raw: Option<&str>) -> bool {|| value.eq_ignore_ascii_case("off"))}-/// Whether a past-TTL (stale) cache may be served without a network round-trip.-#[derive(Clone, Copy, PartialEq)]-enum StaleMode {- /// Serve stale immediately + revalidate in the background — for the- /// unfiltered browse, where a slightly-old catalog is fine and speed wins.- Allow,- /// Treat stale as a miss and fetch fresh under the single-flight lock — for- /// search / filter reads, which must reflect the current catalog.- Reject,+/// The caller-facing text of a registry error:+/// `SKILL_REGISTRY_<KIND>: <message>`.+pub fn registry_error_message(error: &RegistryError) -> String {+ let mut message = format!(+ "{REGISTRY_ERROR_PREFIX}{}: {error}",+ error.kind().as_str().to_ascii_uppercase()+ );+ if let RegistryError::NoDirectDownload {+ source_url: Some(url),+ ..+ } = error+ {+ message.push_str(&format!(". View it at {url}"));+ }+ message}-/// Fetch the full catalog for the **unfiltered browse** view, accepting a stale-/// cache (stale-while-revalidate):-/// - **Fresh cache** → returned immediately.-/// - **Stale cache** (past TTL) → returned immediately *and* a single background-/// refresh is kicked off, so the explorer renders from the last-known catalog-/// instead of blocking on the ~80s download.-/// - **No cache** → fetch under the single-flight lock; concurrent callers-/// coalesce onto that one request.-///-/// `force_refresh == true` (boot warm-up / explicit refresh) always re-fetches.-/// Search / filter reads use [`browse_catalog_fresh`], which never serves stale.-pub async fn browse_catalog(force_refresh: bool) -> Result<Vec<CatalogEntry>, String> {- browse_catalog_with(force_refresh, StaleMode::Allow, fetch_catalog_uncached).await+/// Whether a registry failure is a defect worth reporting, as opposed to an+/// upstream outage, throttling, or a caller asking for something absent.+fn is_reportable(kind: RegistryErrorKind, catalog_read: bool) -> bool {+ match kind {+ RegistryErrorKind::TransportContract => true,+ RegistryErrorKind::Malformed => catalog_read,+ _ => false,+ }}-/// Fetch the full catalog for **search / filter** reads. Never serves a stale-/// cache: a fresh cache is used as-is, but a stale-or-absent cache falls through-/// to a (single-flight) fresh fetch so results aren't computed over an outdated-/// catalog. Thanks to single-flight, a search issued while a background-/// revalidation is already running simply awaits that in-flight fetch rather-/// than starting a new one.-pub async fn browse_catalog_fresh() -> Result<Vec<CatalogEntry>, String> {- browse_catalog_with(false, StaleMode::Reject, fetch_catalog_uncached).await+fn observe(operation: &'static str, error: &RegistryError, catalog_read: bool) {+ let kind = error.kind();+ if is_reportable(kind, catalog_read) {+ crate::core::observability::report_error(+ error,+ "skills",+ "registry",+ &[("failure", kind.as_str()), ("registry_op", operation)],+ );+ } else if error.is_unavailable() || kind == RegistryErrorKind::TooLarge {+ tracing::warn!(+ operation,+ kind = kind.as_str(),+ error = %error,+ "[skill_registry] upstream unavailable"+ );+ } else {+ tracing::debug!(+ operation,+ kind = kind.as_str(),+ error = %error,+ "[skill_registry] request refused"+ );+ }}-/// Core of [`browse_catalog`] / [`browse_catalog_fresh`], parameterised over the-/// fetcher so the cache / single-flight orchestration can be unit-tested without-/// real network I/O.-async fn browse_catalog_with<F, Fut>(- force_refresh: bool,- stale_mode: StaleMode,- fetch: F,-) -> Result<Vec<CatalogEntry>, String>-where- F: FnOnce() -> Fut,- Fut: Future<Output = Result<Vec<CatalogEntry>, String>>,-{- if !force_refresh {- match store::load_cached_catalog_state() {- Some(CachedCatalog::Fresh(entries)) => {- tracing::debug!(- count = entries.len(),- "[skill_registry] serving fresh cache"- );- return Ok(entries);- }- // Browse: serve stale now, revalidate in background.- Some(CachedCatalog::Stale(entries)) if stale_mode == StaleMode::Allow => {- tracing::info!(- count = entries.len(),- "[skill_registry] serving stale cache; revalidating in background"- );- spawn_background_refresh();- return Ok(entries);- }- // Search / filter: stale is not good enough — fall through to fetch.- Some(CachedCatalog::Stale(_)) => {- tracing::debug!("[skill_registry] stale cache rejected for fresh read; fetching");- }- None => {}- }+fn observe_summary(operation: &'static str, error: &tinyskills::RegistryErrorSummary) {+ if is_reportable(error.kind, true) {+ crate::core::observability::report_error(+ error.message.as_str(),+ "skills",+ "registry",+ &[("failure", error.kind.as_str()), ("registry_op", operation)],+ );+ } else {+ tracing::warn!(+ operation,+ kind = error.kind.as_str(),+ error = %error.message,+ "[skill_registry] source has no fresh catalog"+ );}+}- // Single-flight: only one fetch runs at a time. Callers that queued behind- // the lock re-check the cache below and reuse the just-fetched result.- let _guard = FETCH_LOCK.lock().await;- if !force_refresh {- if let Some(CachedCatalog::Fresh(entries)) = store::load_cached_catalog_state() {- tracing::debug!(- count = entries.len(),- "[skill_registry] cache populated by concurrent fetch; reusing"- );- return Ok(entries);- }+fn entry_from_summary(summary: SkillSummary) -> RegistryCatalogEntry {+ RegistryCatalogEntry {+ entry: CatalogEntry {+ id: summary.id,+ name: summary.name,+ description: summary.description,+ source: summary.upstream,+ category: summary.category,+ author: summary.author,+ version: summary.version,+ tags: summary.tags,+ platforms: summary.platforms,+ download_url: String::new(),+ source_url: summary.source_url,+ docs_path: None,+ commands: Vec::new(),+ env_vars: Vec::new(),+ license: None,+ },+ registry: summary.registry,+ installable: summary.installable,+ category_label: summary.category_label,}+}- fetch().await+fn entry_from_detail(detail: SkillDetail) -> RegistryCatalogEntry {+ let mut shaped = entry_from_summary(detail.summary);+ shaped.entry.download_url = detail.download_url;+ shaped.entry.docs_path = detail.docs_path;+ shaped.entry.commands = detail.commands;+ shaped.entry.env_vars = detail.env_vars;+ shaped.entry.license = detail.license;+ shaped}-/// Spawn at most one background catalog refresh (stale-while-revalidate). Extra-/// calls while a refresh is in flight no-op via [`REFRESHING`]. The refresh runs-/// under [`FETCH_LOCK`] so it never races a foreground fetch.-fn spawn_background_refresh() {- if REFRESHING.swap(true, Ordering::AcqRel) {- return;+fn skill_query(query: &CatalogQuery) -> SkillQuery {+ let mut skill = SkillQuery::text(query.text.trim());+ skill.upstreams = query.upstreams.clone();+ skill.categories = query.categories.clone();+ skill.read = ReadPolicy::AllowStale;+ if query.is_paged() {+ skill.page = query.page.unwrap_or(1).max(1);+ skill.page_size = query+ .page_size+ .unwrap_or(DEFAULT_PAGE_SIZE)+ .clamp(1, MAX_PAGE_SIZE);+ } else {+ skill.page = 1;+ skill.page_size = usize::MAX;}- tokio::spawn(async {- let _reset = RefreshGuard;- let _guard = FETCH_LOCK.lock().await;- match fetch_catalog_uncached().await {- Ok(entries) => tracing::info!(- count = entries.len(),- "[skill_registry] background catalog refresh complete"- ),- Err(error) => {- tracing::warn!(error = %error, "[skill_registry] background catalog refresh failed")- }- }- });+ skill}-/// Download, parse, index, and cache the catalog — the network path, unguarded.-/// Callers must go through [`browse_catalog_with`] / [`spawn_background_refresh`]-/// so this runs under the single-flight lock.-async fn fetch_catalog_uncached() -> Result<Vec<CatalogEntry>, String> {- let catalog_url = catalog_url();- tracing::info!(- catalog_url = %redact_url_for_log(&catalog_url),- "[skill_registry] fetching catalog"- );-- let client = reqwest::Client::builder()- .timeout(std::time::Duration::from_secs(FETCH_TIMEOUT_SECS))- .build()- .map_err(|e| format!("failed to build http client: {e}"))?;-- let response = client- .get(&catalog_url)- .header("User-Agent", "openhuman-core")- .send()- .await- .map_err(|e| format!("catalog fetch failed: {e}"))?;+/// One page of matches from the process registry.+pub async fn catalog_page(query: &CatalogQuery) -> Result<CatalogPage, RegistryError> {+ catalog_page_in(&skill_registry(), query).await+}- if !response.status().is_success() {- return Err(format!(- "catalog returned status {}",- response.status().as_u16()- ));+pub(crate) async fn catalog_page_in(+ registry: &SkillRegistry,+ query: &CatalogQuery,+) -> Result<CatalogPage, RegistryError> {+ tracing::debug!(+ text = %query.text,+ upstreams = query.upstreams.len(),+ categories = query.categories.len(),+ page = ?query.page,+ page_size = ?query.page_size,+ force_refresh = query.force_refresh,+ "[skill_registry] catalog_page"+ );+ if query.force_refresh {+ let statuses = registry.refresh(None, true).await?;+ for status in &statuses {+ if let Some(error) = &status.last_error {+ tracing::warn!(+ registry = %status.id,+ kind = error.kind.as_str(),+ error = %error.message,+ "[skill_registry] forced refresh failed; serving what is held"+ );+ }+ }}-- let body = response- .text()+ let page = registry+ .search(&skill_query(query)).await- .map_err(|e| format!("failed to read response: {e}"))?;+ .inspect_err(|error| observe("search", error, true))?;- let raw_items: Vec<serde_json::Value> = parse_catalog_json(&body)?;+ let mut entries = Vec::with_capacity(page.items.len());+ for summary in page.items {+ if !query.is_paged() {+ entries.push(entry_from_summary(summary));+ continue;+ }+ let key = EntryKey::in_registry(summary.registry.clone(), summary.id.clone());+ match registry.detail(&key).await {+ Ok(detail) => entries.push(entry_from_detail(detail)),+ Err(error) => {+ tracing::debug!(+ id = %summary.id,+ error = %error,+ "[skill_registry] detail unavailable for a hit; returning its summary"+ );+ entries.push(entry_from_summary(summary));+ }+ }+ }- tracing::info!(- total_raw = raw_items.len(),- "[skill_registry] parsing catalog"+ let refreshing = page.sources.iter().any(|source| source.refreshing);+ let last_error = page+ .sources+ .iter()+ .find_map(|source| source.last_error.clone());+ tracing::debug!(+ total = page.total,+ returned = entries.len(),+ page = page.page,+ freshness = ?page.freshness,+ refreshing,+ has_error = last_error.is_some(),+ "[skill_registry] catalog_page result");-- let entries: Vec<CatalogEntry> = {- let base = download::download_base_override();- raw_items- .iter()- .filter_map(|item| tinyskills::parse_hermes_entry(item, base.as_deref()))- .collect()- };-- tracing::info!(count = entries.len(), "[skill_registry] catalog indexed");-- store::save_catalog_cache(&entries);- Ok(entries)+ Ok(CatalogPage {+ entries,+ total: page.total,+ page: page.page,+ page_size: page.page_size,+ total_pages: page.total_pages,+ freshness: page.freshness,+ fetched_at: page.fetched_at,+ refreshing,+ last_error,+ })}-fn catalog_url() -> String {- std::env::var(CATALOG_URL_ENV)- .ok()- .map(|value| value.trim().to_string())- .filter(|value| !value.is_empty())- .unwrap_or_else(|| CATALOG_URL.to_string())+/// Upstream and category facets across every source.+pub async fn catalog_facets() -> Result<RegistryFacets, RegistryError> {+ catalog_facets_in(&skill_registry()).await}-fn redact_url_for_log(raw: &str) -> String {- match url::Url::parse(raw) {- Ok(parsed) => {- let scheme = parsed.scheme();- let host = parsed.host_str().unwrap_or("");- let path = parsed.path();- format!("{scheme}://{host}{path}")- }- Err(_) => "<unparseable>".to_string(),- }+pub(crate) async fn catalog_facets_in(+ registry: &SkillRegistry,+) -> Result<RegistryFacets, RegistryError> {+ registry+ .facets(None)+ .await+ .inspect_err(|error| observe("facets", error, true))}-pub(crate) fn parse_catalog_json(body: &str) -> Result<Vec<serde_json::Value>, String> {- tinyskills::parse_catalog_json(body).map_err(|e| e.to_string())+/// Everything known about one entry, by id or unique name.+pub async fn catalog_detail(entry_id: &str) -> Result<CatalogDetail, RegistryError> {+ catalog_detail_in(&skill_registry(), entry_id).await}-/// Search the catalog by query string.-pub async fn search_catalog(- query: &str,- source_filter: Option<&str>,- category_filter: Option<&str>,-) -> Result<Vec<CatalogEntry>, String> {- tracing::debug!(- query = %query,- source_filter = ?source_filter,- category_filter = ?category_filter,- "[skill_registry] search_catalog"- );- // Search/filter must reflect the current catalog — never serve stale.- let catalog = browse_catalog_fresh().await?;- // Entries install cannot fetch go last, so find-and-install reaches a- // working hit first (see `tinyskills::filter_catalog`).- let filtered = tinyskills::filter_catalog(catalog, query, source_filter, category_filter);-- tracing::debug!(- result_count = filtered.len(),- "[skill_registry] search complete"- );- Ok(filtered)-}--/// Return the distinct set of upstream sources present in the catalog.-pub async fn list_sources() -> Result<Vec<String>, String> {- let catalog = browse_catalog(false).await?;- let mut sources: Vec<String> = catalog- .iter()- .map(|e| e.source.clone())- .collect::<std::collections::BTreeSet<_>>()- .into_iter()- .collect();- sources.sort();- Ok(sources)+pub(crate) async fn catalog_detail_in(+ registry: &SkillRegistry,+ entry_id: &str,+) -> Result<CatalogDetail, RegistryError> {+ let detail = registry+ .detail(&EntryKey::new(entry_id))+ .await+ .inspect_err(|error| observe("detail", error, true))?;+ let overview = detail.overview.clone();+ let install_identifier = detail.install_identifier.clone();+ Ok(CatalogDetail {+ entry: entry_from_detail(detail),+ overview,+ install_identifier,+ })}-/// Return the distinct set of categories present in the catalog.-pub async fn list_categories() -> Result<Vec<String>, String> {- let catalog = browse_catalog(false).await?;- let mut categories: Vec<String> = catalog- .iter()- .map(|e| e.category.clone())- .filter(|c| !c.is_empty())- .collect::<std::collections::BTreeSet<_>>()- .into_iter()- .collect();- categories.sort();- Ok(categories)+/// Why a catalog install failed.+#[derive(Debug)]+pub enum CatalogInstallError {+ /// The registry could not locate or fetch the entry's `SKILL.md`.+ Registry(RegistryError),+ /// The document was fetched but could not be installed.+ Install(String),}-/// Install a skill from the catalog by its entry id.-pub async fn install_from_catalog(- workspace_dir: &std::path::Path,- entry: &CatalogEntry,-) -> Result<crate::skills::ops_install::InstallWorkflowFromUrlOutcome, String> {- tracing::info!(- entry_id = %entry.id,- source = %entry.source,- download_url = %entry.download_url,- "[skill_registry] installing from catalog"- );-- if !entry.has_direct_download() {- let where_to_find = entry- .source_url- .as_deref()- .map(|u| format!(" View it at {u}."))- .unwrap_or_default();- return Err(format!(- "'{}' is hosted on {} and has no direct SKILL.md download, so it can't be installed automatically yet.{}",- entry.name, entry.source, where_to_find- ));+impl CatalogInstallError {+ pub fn kind(&self) -> Option<RegistryErrorKind> {+ match self {+ Self::Registry(error) => Some(error.kind()),+ Self::Install(_) => None,+ }}+}- // A skills.sh entry's `download_url` is the most common location, not a- // verified one: find where this repo keeps the skill before fetching.- let url = match entry.source_url.as_deref().and_then(SkillsShRef::parse) {- Some(skill) if skill.candidate_urls().first() == Some(&entry.download_url) => {- download::resolve_skills_sh(&skill).await?+impl std::fmt::Display for CatalogInstallError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ Self::Registry(error) => f.write_str(®istry_error_message(error)),+ Self::Install(message) => f.write_str(message),}- _ => entry.download_url.clone(),- };-- let params = crate::skills::ops_install::InstallWorkflowFromUrlParams {- url,- timeout_secs: Some(CATALOG_INSTALL_TIMEOUT_SECS),- };-- crate::skills::ops_install::install_workflow_from_url(workspace_dir, params)- .await- .map_err(|error| {- // ClawHub answers a slug that several authors publish under with- // 409, and the catalog does not record which author's skill this is.- if entry.source.eq_ignore_ascii_case("clawhub") && error.ends_with("returned status 409")- {- format!(- "'{}' is published on ClawHub by more than one author and the catalog does not say which one, so it can't be installed automatically.",- entry.name- )- } else {- error- }- })+ }}-/// Wall-clock budget for a catalog-driven SKILL.md fetch.-///-/// Deliberately the same 15s as the skills.sh probe timeout in `download.rs` — the two bound-/// requests to the same hosts in the same flow, so tuning one without the other-/// is almost always a mistake. This path used the 60s-/// `DEFAULT_INSTALL_TIMEOUT_SECS` instead, which is the documented default for-/// the public `skills.install_from_url` tool and is left alone; a user clicking-/// Install in the registry is waiting on a UI, not scripting a long fetch, and-/// a minute of a disabled button with no reason was the whole of #6409's-/// reported symptom.-const CATALOG_INSTALL_TIMEOUT_SECS: u64 = 15;--/// Resolve an install request to exactly one catalog entry.-///-/// `entry_id` is matched against [`CatalogEntry::id`]. Ids used to be display-/// names, which many entries share, so a name is still accepted when exactly-/// one entry carries it; otherwise the error names real ids to use instead.-pub fn find_catalog_entry<'a>(- catalog: &'a [CatalogEntry],+/// Install a catalog entry, by id or unique name, into the user skills root.+pub async fn install_from_catalog(+ workspace_dir: &Path,entry_id: &str,-) -> Result<&'a CatalogEntry, String> {- tinyskills::find_catalog_entry(catalog, entry_id).map_err(|error| match error {- tinyskills::CatalogError::NotFound { id, closest } => {- tracing::debug!(- entry_id = %id,- suggestions = closest.len(),- "[skill_registry] install id not in catalog"- );- if closest.is_empty() {- format!(- "no catalog entry has id '{id}'. Use an id returned by skill_registry_search."- )- } else {- format!(- "no catalog entry has id '{id}'. Closest ids: {}.",- closest.join(", ")- )- }- }- other => other.to_string(),- })+) -> Result<InstallWorkflowFromUrlOutcome, CatalogInstallError> {+ install_from_catalog_in(+ &skill_registry(),+ workspace_dir,+ dirs::home_dir().as_deref(),+ entry_id,+ )+ .await}-/// Index one raw Hermes catalog item, honouring the download-base test-/// override (`OPENHUMAN_SKILL_REGISTRY_DOWNLOAD_BASE_URL`).-pub(crate) fn parse_hermes_entry(item: &serde_json::Value) -> Option<CatalogEntry> {- let base = download::download_base_override();- tinyskills::parse_hermes_entry(item, base.as_deref())+pub(crate) async fn install_from_catalog_in(+ registry: &SkillRegistry,+ workspace_dir: &Path,+ home: Option<&Path>,+ entry_id: &str,+) -> Result<InstallWorkflowFromUrlOutcome, CatalogInstallError> {+ tracing::info!(entry_id = %entry_id, "[skill_registry] installing from catalog");+ let document = registry+ .fetch_document(&EntryKey::new(entry_id))+ .await+ .map_err(|error| {+ observe("install", &error, false);+ CatalogInstallError::Registry(error)+ })?;+ if document.is_blocked() {+ tracing::warn!(+ entry_id = %entry_id,+ fetched_from = %document.fetched_from,+ "[skill_registry] supply-chain scan flagged the document"+ );+ }+ crate::skills::ops_install::install_validated_document(+ workspace_dir,+ home,+ &document.fetched_from,+ &document.fetched_from,+ document.document,+ )+ .map_err(CatalogInstallError::Install)}#[cfg(test)]#[path = "ops_tests.rs"]mod tests;++#[cfg(test)]+#[path = "ops_install_tests.rs"]+mod install_tests;diff --git a/crates/openhuman-core/src/skills/catalog/ops_install_tests.rs b/crates/openhuman-core/src/skills/catalog/ops_install_tests.rsnew file mode 100644index 0000000000..bc2c537390--- /dev/null+++ b/crates/openhuman-core/src/skills/catalog/ops_install_tests.rs@@ -0,0 +1,137 @@+use super::*;++use std::sync::atomic::Ordering;++use serde_json::json;++use crate::skills::catalog::test_fixtures::{hermes_item, Fixture};++#[tokio::test]+async fn installs_a_catalog_entry_once_and_announces_it() {+ use crate::core::events::DomainEvent;+ use tinybus::TryRecvError;++ crate::core::bus::init().await.expect("bus init");+ let mut rx = crate::core::bus::BUS+ .get()+ .expect("event bus should be initialized")+ .receiver();++ let fixture = Fixture::start(vec![hermes_item("zz-registry-install", "built-in")]).await;+ let registry = fixture.registry();+ let workspace = tempfile::tempdir().unwrap();+ let home = tempfile::tempdir().unwrap();++ let first = install_from_catalog_in(+ ®istry,+ workspace.path(),+ Some(home.path()),+ "zz-registry-install",+ )+ .await+ .expect("install");+ assert_eq!(first.new_skills, ["zz-registry-install"]);+ assert!(first.stdout.contains("Installed to"), "{}", first.stdout);+ assert!(home+ .path()+ .join(".openhuman/skills/zz-registry-install/SKILL.md")+ .exists());++ let mut announced = false;+ loop {+ match rx.try_recv() {+ Ok(DomainEvent::WorkflowsChanged { reason }) if reason == "install" => {+ announced = true;+ break;+ }+ Ok(_) | Err(TryRecvError::Lagged(_)) => continue,+ Err(TryRecvError::Empty) | Err(TryRecvError::Closed) => break,+ }+ }+ assert!(announced, "a catalog install publishes WorkflowsChanged");++ let second = install_from_catalog_in(+ ®istry,+ workspace.path(),+ Some(home.path()),+ "zz-registry-install",+ )+ .await+ .expect("a repeat install succeeds");+ assert!(second.new_skills.is_empty());+ assert!(+ second.stdout.contains("already installed"),+ "{}",+ second.stdout+ );+}++#[tokio::test]+async fn a_portal_entry_fails_fast_with_its_source_page() {+ let fixture = Fixture::start(vec![json!({+ "name": "code-audit",+ "description": "x",+ "category": "other",+ "source": "LobeHub",+ "identifier": "lobehub/code-audit",+ "sourceUrl": "https://lobehub.com/agent/code-audit"+ })])+ .await;+ let home = tempfile::tempdir().unwrap();+ let error = install_from_catalog_in(+ &fixture.registry_without_download_base(),+ home.path(),+ Some(home.path()),+ "lobehub/code-audit",+ )+ .await+ .expect_err("no SKILL.md to fetch");+ assert_eq!(error.kind(), Some(RegistryErrorKind::NoDirectDownload));+ let message = error.to_string();+ assert!(+ message.starts_with("SKILL_REGISTRY_NO_DIRECT_DOWNLOAD: "),+ "{message}"+ );+ assert!(+ message.contains("https://lobehub.com/agent/code-audit"),+ "{message}"+ );+}++#[tokio::test]+async fn an_unknown_id_names_real_ids() {+ let fixture = Fixture::start(vec![hermes_item("git-helper", "built-in")]).await;+ let home = tempfile::tempdir().unwrap();+ let error = install_from_catalog_in(+ &fixture.registry(),+ home.path(),+ Some(home.path()),+ "git-helpr",+ )+ .await+ .expect_err("unknown id");+ assert_eq!(error.kind(), Some(RegistryErrorKind::NotFound));+ assert!(error.to_string().contains("git-helper"), "{error}");+}++#[tokio::test]+async fn a_throttled_document_host_reports_rate_limiting() {+ let fixture = Fixture::start(vec![hermes_item("slow-skill", "built-in")]).await;+ fixture.document_status.store(429, Ordering::SeqCst);+ let home = tempfile::tempdir().unwrap();+ let error = install_from_catalog_in(+ &fixture.registry(),+ home.path(),+ Some(home.path()),+ "slow-skill",+ )+ .await+ .expect_err("throttled");+ assert_eq!(error.kind(), Some(RegistryErrorKind::RateLimited));+ let message = error.to_string();+ assert!(+ message.starts_with("SKILL_REGISTRY_RATE_LIMITED: rate limited"),+ "{message}"+ );+ assert!(message.contains("42s"), "{message}");+}diff --git a/crates/openhuman-core/src/skills/catalog/ops_tests.rs b/crates/openhuman-core/src/skills/catalog/ops_tests.rsindex f0bf36cc13..3bdbe444cb 100644--- a/crates/openhuman-core/src/skills/catalog/ops_tests.rs+++ b/crates/openhuman-core/src/skills/catalog/ops_tests.rs@@ -1,53 +1,35 @@use super::*;-use serde_json::json;-fn same_named_catalog() -> Vec<CatalogEntry> {- [- json!({ "name": "AI Code Review", "source": "ClawHub", "identifier": "qf-code-review" }),- json!({ "name": "AI Code Review", "source": "ClawHub", "identifier": "ai-code-review-ops" }),- json!({ "name": "apple-notes", "source": "built-in", "docsPath": "bundled/apple/apple-apple-notes" }),- json!({ "name": "apple-notes", "source": "ClawHub", "identifier": "apple-notes" }),- json!({ "name": "Apple Design", "source": "ClawHub", "identifier": "apple-design" }),- ]- .iter()- .map(|item| parse_hermes_entry(item).expect("entry"))- .collect()-}+use std::sync::atomic::Ordering;+use std::sync::{Arc, Mutex};+use std::time::{Duration, SystemTime};-#[test]-fn find_catalog_entry_not_found_suggests_real_ids_instead_of_a_refresh() {- let err = find_catalog_entry(&same_named_catalog(), "ai-code-review").unwrap_err();- assert!(- err.starts_with("no catalog entry has id 'ai-code-review'"),- "{err}"- );- assert!(err.contains("clawhub/ai-code-review-ops"), "{err}");- assert!(!err.contains("refresh"), "{err}");+use serde_json::{json, Value};+use tinyskills::{Clock, Freshness};++use crate::skills::catalog::test_fixtures::{hermes_item, Fixture};++#[derive(Clone)]+struct ManualClock(Arc<Mutex<SystemTime>>);++impl Clock for ManualClock {+ fn now(&self) -> SystemTime {+ *self.0.lock().unwrap()+ }}-#[tokio::test]-async fn install_from_catalog_errors_for_portal_skill_without_download() {- // A portal-only entry (empty download_url) must fail fast with an- // actionable message naming the source + page — never fetch a 404. (#3741)- let tmp = tempfile::tempdir().unwrap();- let entry = parse_hermes_entry(&json!({- "name": "code-audit",- "description": "x",- "category": "other",- "source": "ClawHub",- "sourceUrl": "https://clawhub.ai/skills/agentkilox-code-audit"- }))- .expect("entry");- assert_eq!(entry.download_url, "");+fn numbered(count: usize) -> Vec<Value> {+ (0..count)+ .map(|i| hermes_item(&format!("review-{i:02}"), "built-in"))+ .collect()+}- let err = install_from_catalog(tmp.path(), &entry)- .await- .expect_err("portal skill cannot install");- assert!(err.contains("ClawHub"), "names the source: {err}");- assert!(- err.contains("https://clawhub.ai/skills/agentkilox-code-audit"),- "links the source page: {err}"- );+fn paged(page: usize, page_size: usize) -> CatalogQuery {+ CatalogQuery {+ page: Some(page),+ page_size: Some(page_size),+ ..CatalogQuery::default()+ }}#[test]@@ -62,200 +44,285 @@ fn refresh_on_boot_enabled_defaults_on_and_accepts_common_false_values() {assert!(!refresh_on_boot_enabled(Some("OFF")));}-use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering as AtomicOrdering};-use std::sync::Arc;--const CACHE_DIR_ENV: &str = "OPENHUMAN_SKILL_REGISTRY_CACHE_DIR";+#[test]+fn every_error_kind_renders_a_typed_prefix() {+ let cases = [+ (+ RegistryError::Timeout {+ operation: "catalog",+ budget: Duration::from_secs(180),+ },+ "SKILL_REGISTRY_TIMEOUT: ",+ ),+ (+ RegistryError::Unavailable { status: 503 },+ "SKILL_REGISTRY_UNAVAILABLE: ",+ ),+ (+ RegistryError::RateLimited {+ retry_after: Some(Duration::from_secs(42)),+ },+ "SKILL_REGISTRY_RATE_LIMITED: rate limited: retry after 42s",+ ),+ (+ RegistryError::NotFound {+ id: "nope".into(),+ closest: vec!["clawhub/nope-ops".into()],+ },+ "SKILL_REGISTRY_NOT_FOUND: ",+ ),+ (+ RegistryError::UpstreamAmbiguous {+ name: "AI Code Review".into(),+ },+ "SKILL_REGISTRY_UPSTREAM_AMBIGUOUS: ",+ ),+ (+ RegistryError::Malformed {+ what: "catalog",+ detail: "expected an array".into(),+ },+ "SKILL_REGISTRY_MALFORMED: ",+ ),+ ];+ for (error, prefix) in cases {+ let message = registry_error_message(&error);+ assert!(message.starts_with(prefix), "{message} vs {prefix}");+ }+}-fn env_lock() -> tokio::sync::MutexGuard<'static, ()> {- crate::skills::catalog::TEST_ENV_LOCK.blocking_lock()+#[test]+fn a_skill_without_a_download_links_its_source_page() {+ let message = registry_error_message(&RegistryError::NoDirectDownload {+ name: "code-audit".into(),+ source_url: Some("https://clawhub.ai/skills/agentkilox-code-audit".into()),+ });+ assert!(message.starts_with("SKILL_REGISTRY_NO_DIRECT_DOWNLOAD: "));+ assert!(message.contains("https://clawhub.ai/skills/agentkilox-code-audit"));}-async fn env_lock_async() -> tokio::sync::MutexGuard<'static, ()> {- crate::skills::catalog::TEST_ENV_LOCK.lock().await+#[test]+fn only_registry_defects_are_reportable() {+ assert!(is_reportable(RegistryErrorKind::TransportContract, false));+ assert!(is_reportable(RegistryErrorKind::Malformed, true));+ assert!(!is_reportable(RegistryErrorKind::Malformed, false));+ for kind in [+ RegistryErrorKind::Timeout,+ RegistryErrorKind::Unavailable,+ RegistryErrorKind::RateLimited,+ RegistryErrorKind::Transport,+ RegistryErrorKind::NotFound,+ RegistryErrorKind::NoDirectDownload,+ ] {+ assert!(!is_reportable(kind, true), "{kind:?}");+ }}-fn sample_entry() -> CatalogEntry {- parse_hermes_entry(&json!({- "name": "apple-notes",- "description": "Manage Apple Notes",- "category": "apple",- "source": "built-in",- "docsPath": "bundled/apple/apple-apple-notes"- }))- .expect("entry")+#[test]+fn queries_page_only_when_asked_and_clamp_the_page_size() {+ let unpaged = skill_query(&CatalogQuery::default());+ assert_eq!(unpaged.page, 1);+ assert_eq!(unpaged.page_size, usize::MAX);++ let defaulted = skill_query(&CatalogQuery {+ page: Some(0),+ ..CatalogQuery::default()+ });+ assert_eq!(defaulted.page, 1);+ assert_eq!(defaulted.page_size, DEFAULT_PAGE_SIZE);++ let clamped = skill_query(&paged(3, 10_000));+ assert_eq!(clamped.page, 3);+ assert_eq!(clamped.page_size, MAX_PAGE_SIZE);+ assert_eq!(clamped.read, ReadPolicy::AllowStale);}#[tokio::test]-async fn fresh_cache_skips_fetch() {- let _env = env_lock_async().await;- let tmp = tempfile::tempdir().unwrap();- std::env::set_var(CACHE_DIR_ENV, tmp.path());- store::save_catalog_cache(&[sample_entry()]);+async fn pages_split_the_matches_and_carry_full_entries() {+ let fixture = Fixture::start(numbered(30)).await;+ let registry = fixture.registry();++ let first = catalog_page_in(®istry, &paged(1, 25)).await.unwrap();+ assert_eq!(first.total, 30);+ assert_eq!(first.total_pages, 2);+ assert_eq!(first.entries.len(), 25);+ assert_eq!(first.freshness, Freshness::Live);+ assert!(first.fetched_at.is_some());+ assert!(first.last_error.is_none());+ let entry = &first.entries[0];+ assert_eq!(entry.registry, "hermes");+ assert!(entry.installable);+ assert_eq!(+ entry.entry.download_url,+ format!("{}/skills/{}/SKILL.md", fixture.base, entry.entry.name)+ );+ assert!(entry.entry.docs_path.is_some());- let called = Arc::new(AtomicBool::new(false));- let called_in = called.clone();- let entries = browse_catalog_with(false, StaleMode::Allow, move || async move {- called_in.store(true, AtomicOrdering::SeqCst);- Ok(Vec::new())- })- .await- .unwrap();+ let second = catalog_page_in(®istry, &paged(2, 25)).await.unwrap();+ assert_eq!(second.page, 2);+ assert_eq!(second.entries.len(), 5);+ assert_eq!(fixture.catalog_hits.load(Ordering::SeqCst), 1);+}- assert_eq!(entries.len(), 1);+#[tokio::test]+async fn an_unpaged_read_returns_every_match_on_one_page() {+ let fixture = Fixture::start(numbered(30)).await;+ let page = catalog_page_in(&fixture.registry(), &CatalogQuery::default())+ .await+ .unwrap();+ assert_eq!(page.entries.len(), 30);+ assert_eq!(page.total_pages, 1);+ assert!(page.entries.iter().all(|entry| entry.installable));+}++#[tokio::test]+async fn several_sources_filter_together() {+ let fixture = Fixture::start(vec![+ hermes_item("alpha", "ClawHub"),+ hermes_item("beta", "skills.sh"),+ hermes_item("gamma", "built-in"),+ ])+ .await;+ let query = CatalogQuery {+ upstreams: vec!["clawhub".into(), "built-in".into()],+ ..paged(1, 25)+ };+ let page = catalog_page_in(&fixture.registry(), &query).await.unwrap();+ let names: Vec<&str> = page.entries.iter().map(|e| e.entry.name.as_str()).collect();+ assert_eq!(page.total, 2);assert!(- !called.load(AtomicOrdering::SeqCst),- "fetcher must not run when the cache is fresh"+ names.contains(&"alpha") && names.contains(&"gamma"),+ "{names:?}");-- store::clear_cache();- std::env::remove_var(CACHE_DIR_ENV);}#[tokio::test]-async fn concurrent_cache_miss_coalesces_to_single_fetch() {- let _env = env_lock_async().await;- let tmp = tempfile::tempdir().unwrap();- std::env::set_var(CACHE_DIR_ENV, tmp.path());- store::clear_cache();+async fn search_ranks_installable_entries_before_uninstallable_ones() {+ let fixture = Fixture::start(vec![+ json!({+ "name": "review-agent",+ "description": "x",+ "source": "LobeHub",+ "identifier": "lobehub/review-agent",+ "sourceUrl": "https://lobehub.com/agent/review-agent"+ }),+ json!({+ "name": "review-skill",+ "description": "x",+ "source": "ClawHub",+ "identifier": "review-skill"+ }),+ ])+ .await;+ let query = CatalogQuery {+ text: "review".into(),+ ..paged(1, 25)+ };+ let page = catalog_page_in(&fixture.registry_without_download_base(), &query)+ .await+ .unwrap();+ let ids: Vec<&str> = page.entries.iter().map(|e| e.entry.id.as_str()).collect();+ assert_eq!(ids, ["clawhub/review-skill", "lobehub/review-agent"]);+ assert!(!page.entries[1].installable);+ assert_eq!(+ page.entries[1].entry.source_url.as_deref(),+ Some("https://lobehub.com/agent/review-agent")+ );+}- let calls = Arc::new(AtomicUsize::new(0));+#[tokio::test]+async fn concurrent_cold_reads_share_one_upstream_fetch() {+ let fixture = Fixture::start(numbered(5)).await;+ let registry = fixture.registry();let mut handles = Vec::new();- for _ in 0..4 {- let calls = calls.clone();+ for _ in 0..6 {+ let registry = Arc::clone(®istry);handles.push(tokio::spawn(async move {- browse_catalog_with(false, StaleMode::Allow, move || async move {- calls.fetch_add(1, AtomicOrdering::SeqCst);- // Mimic the slow upstream so the other callers queue on the- // single-flight lock instead of each starting a fetch.- tokio::time::sleep(std::time::Duration::from_millis(50)).await;- let entries = vec![sample_entry()];- store::save_catalog_cache(&entries);- Ok(entries)- })- .await+ catalog_page_in(®istry, &paged(1, 25)).await}));}-for handle in handles {- let entries = handle.await.unwrap().unwrap();- assert_eq!(entries.len(), 1, "every caller receives the catalog");+ assert_eq!(handle.await.unwrap().unwrap().total, 5);}+ assert_eq!(fixture.catalog_hits.load(Ordering::SeqCst), 1);+}++#[tokio::test]+async fn a_failed_refresh_keeps_serving_the_held_catalog_with_its_error() {+ let fixture = Fixture::start(numbered(3)).await;+ let clock = ManualClock(Arc::new(Mutex::new(SystemTime::now())));+ let registry = fixture.registry_with_clock(clock.clone());assert_eq!(- calls.load(AtomicOrdering::SeqCst),- 1,- "four concurrent cache-miss callers must trigger exactly one fetch"+ catalog_page_in(®istry, &paged(1, 25))+ .await+ .unwrap()+ .freshness,+ Freshness::Live);- store::clear_cache();- std::env::remove_var(CACHE_DIR_ENV);-}--/// Write a cache file with an explicit `fetched_at_epoch` (epoch 1 => stale).-fn write_cache_at(dir: &std::path::Path, entries: Vec<CatalogEntry>, epoch: u64) {- let cache = store::CatalogCache {- entries,- fetched_at_epoch: epoch,- };- std::fs::write(- dir.join("cache.json"),- serde_json::to_string(&cache).unwrap(),+ fixture.catalog_status.store(503, Ordering::SeqCst);+ let refreshed = catalog_page_in(+ ®istry,+ &CatalogQuery {+ force_refresh: true,+ ..paged(1, 25)+ },)- .unwrap();+ .await+ .expect("the held catalog still answers");+ assert_eq!(refreshed.total, 3);+ let error = refreshed.last_error.expect("the failure is reported");+ assert_eq!(error.kind, RegistryErrorKind::Unavailable);++ *clock.0.lock().unwrap() += Duration::from_secs(2 * 3600);+ let stale = catalog_page_in(®istry, &paged(1, 25)).await.unwrap();+ assert_eq!(stale.freshness, Freshness::Cached);+ assert!(stale.last_error.is_some());}#[tokio::test]-async fn browse_serves_stale_without_a_foreground_fetch() {- let _env = env_lock_async().await;- let tmp = tempfile::tempdir().unwrap();- std::env::set_var(CACHE_DIR_ENV, tmp.path());- write_cache_at(tmp.path(), vec![sample_entry()], 1); // epoch 1 => stale-- // Pin REFRESHING so the background revalidation no-ops (no real network).- REFRESHING.store(true, AtomicOrdering::SeqCst);- let called = Arc::new(AtomicBool::new(false));- let called_in = called.clone();- let entries = browse_catalog_with(false, StaleMode::Allow, move || async move {- called_in.store(true, AtomicOrdering::SeqCst);- Ok(Vec::new())- })- .await- .unwrap();- REFRESHING.store(false, AtomicOrdering::SeqCst);-- assert_eq!(entries.len(), 1, "browse returns the stale entry");- assert!(- !called.load(AtomicOrdering::SeqCst),- "browse must serve stale without a foreground fetch"- );-- store::clear_cache();- std::env::remove_var(CACHE_DIR_ENV);+async fn a_cold_registry_with_an_unreachable_upstream_returns_the_typed_error() {+ let fixture = Fixture::start(Vec::new()).await;+ fixture.catalog_status.store(502, Ordering::SeqCst);+ let error = catalog_page_in(&fixture.registry(), &paged(1, 25))+ .await+ .expect_err("nothing is held");+ assert_eq!(error.kind(), RegistryErrorKind::Unavailable);+ assert!(registry_error_message(&error).starts_with("SKILL_REGISTRY_UNAVAILABLE: "));}#[tokio::test]-async fn search_rejects_stale_and_fetches_fresh() {- let _env = env_lock_async().await;- let tmp = tempfile::tempdir().unwrap();- std::env::set_var(CACHE_DIR_ENV, tmp.path());- write_cache_at(tmp.path(), vec![sample_entry()], 1); // stale: 1 entry-- let called = Arc::new(AtomicBool::new(false));- let called_in = called.clone();- let entries = browse_catalog_with(false, StaleMode::Reject, move || async move {- called_in.store(true, AtomicOrdering::SeqCst);- let fresh = vec![sample_entry(), sample_entry()];- store::save_catalog_cache(&fresh);- Ok(fresh)- })- .await- .unwrap();-- assert!(- called.load(AtomicOrdering::SeqCst),- "a fresh (search) read must not be satisfied by a stale cache"- );- assert_eq!(- entries.len(),- 2,- "returns the freshly fetched catalog, not the stale one"- );-- store::clear_cache();- std::env::remove_var(CACHE_DIR_ENV);+async fn facets_list_upstreams_and_categories_most_entries_first() {+ let fixture = Fixture::start(vec![+ hermes_item("a", "ClawHub"),+ hermes_item("b", "ClawHub"),+ hermes_item("c", "built-in"),+ ])+ .await;+ let facets = catalog_facets_in(&fixture.registry()).await.unwrap();+ let upstreams: Vec<(&str, usize)> = facets+ .upstreams+ .iter()+ .map(|facet| (facet.value.as_str(), facet.count))+ .collect();+ assert_eq!(upstreams, [("ClawHub", 2), ("built-in", 1)]);+ assert_eq!(facets.categories[0].value, "productivity");}#[tokio::test]-async fn search_ranks_installable_entries_before_uninstallable_ones() {- let _env = env_lock_async().await;- let tmp = tempfile::tempdir().unwrap();- std::env::set_var(CACHE_DIR_ENV, tmp.path());- let agent = parse_hermes_entry(&json!({- "name": "review-agent",- "description": "x",- "source": "LobeHub",- "identifier": "lobehub/review-agent",- "sourceUrl": "https://lobehub.com/agent/review-agent"- }))- .unwrap();- let skill = parse_hermes_entry(&json!({- "name": "review-skill",- "description": "x",- "source": "ClawHub",- "identifier": "review-skill"- }))- .unwrap();- store::save_catalog_cache(&[agent, skill]);+async fn detail_carries_the_overview_and_an_unknown_id_suggests_real_ones() {+ let mut item = hermes_item("git-helper", "built-in");+ item["overview"] = json!("Longer text about git-helper.");+ let fixture = Fixture::start(vec![item, hermes_item("notes", "built-in")]).await;+ let registry = fixture.registry();- let hits = search_catalog("review", None, None).await.unwrap();+ let detail = catalog_detail_in(®istry, "git-helper").await.unwrap();+ assert_eq!(detail.overview, "Longer text about git-helper.");+ assert_eq!(detail.entry.entry.name, "git-helper");- let ids: Vec<&str> = hits.iter().map(|e| e.id.as_str()).collect();- assert_eq!(- ids,- ["clawhub/review-skill", "lobehub/review-agent"],- "an installable hit must come before one install will reject"- );-- store::clear_cache();- std::env::remove_var(CACHE_DIR_ENV);+ let error = catalog_detail_in(®istry, "git-helpr")+ .await+ .expect_err("unknown id");+ assert_eq!(error.kind(), RegistryErrorKind::NotFound);+ assert!(error.to_string().contains("git-helper"), "{error}");}diff --git a/crates/openhuman-core/src/skills/catalog/schemas/controller_schemas.rs b/crates/openhuman-core/src/skills/catalog/schemas/controller_schemas.rsindex fcf74a123e..f389158e0b 100644--- a/crates/openhuman-core/src/skills/catalog/schemas/controller_schemas.rs+++ b/crates/openhuman-core/src/skills/catalog/schemas/controller_schemas.rs@@ -4,7 +4,7 @@ use crate::core::all::RegisteredController;use crate::core::{ControllerSchema, FieldSchema, TypeSchema};use super::handlers::{- handle_browse, handle_categories, handle_install, handle_schemas, handle_search,+ handle_browse, handle_categories, handle_detail, handle_install, handle_schemas, handle_search,handle_sources, handle_uninstall,};@@ -14,6 +14,7 @@ pub fn all_skill_registry_controller_schemas() -> Vec<ControllerSchema> {skill_registry_schemas("search"),skill_registry_schemas("sources"),skill_registry_schemas("categories"),+ skill_registry_schemas("detail"),skill_registry_schemas("install"),skill_registry_schemas("uninstall"),skill_registry_schemas("schemas"),@@ -38,6 +39,10 @@ pub fn all_skill_registry_registered_controllers() -> Vec<RegisteredController>schema: skill_registry_schemas("categories"),handler: handle_categories,},+ RegisteredController {+ schema: skill_registry_schemas("detail"),+ handler: handle_detail,+ },RegisteredController {schema: skill_registry_schemas("install"),handler: handle_install,@@ -58,50 +63,16 @@ pub fn skill_registry_schemas(function: &str) -> ControllerSchema {"browse" => ControllerSchema {namespace: "skill_registry",function: "browse",- description: "Browse the skill registry catalog (aggregated from HermesHub). Returns cached results unless force_refresh is true.",- inputs: vec![FieldSchema {- name: "force_refresh",- ty: TypeSchema::Bool,- comment: "Force re-fetch from the Hermes API, ignoring the local cache.",- required: false,- }],- outputs: vec![FieldSchema {- name: "entries",- ty: TypeSchema::Json,- comment: "Array of catalog entries.",- required: true,- }],+ description: "Browse the skill registry catalog (aggregated from HermesHub). Serves the cached catalog and refreshes it in the background when stale; force_refresh refetches first. Pass page or page_size for one page; with neither, every entry is returned.",+ inputs: catalog_inputs(false),+ outputs: catalog_outputs("Catalog entries on this page."),},"search" => ControllerSchema {namespace: "skill_registry",function: "search",- description: "Search the registry catalog by query string. Matches against name, description, tags, category, and author.",- inputs: vec![- FieldSchema {- name: "query",- ty: TypeSchema::String,- comment: "Search query string.",- required: false,- },- FieldSchema {- name: "source",- ty: TypeSchema::String,- comment: "Filter by upstream source (e.g. 'ClawHub', 'skills.sh', 'built-in').",- required: false,- },- FieldSchema {- name: "category",- ty: TypeSchema::String,- comment: "Filter by category.",- required: false,- },- ],- outputs: vec![FieldSchema {- name: "entries",- ty: TypeSchema::Json,- comment: "Matching catalog entries.",- required: true,- }],+ description: "Search the registry catalog by query string. Matches against name, description, tags, category, and author. Pass page or page_size for one page; with neither, every match is returned.",+ inputs: catalog_inputs(true),+ outputs: catalog_outputs("Matching catalog entries on this page."),},"sources" => ControllerSchema {namespace: "skill_registry",@@ -127,6 +98,23 @@ pub fn skill_registry_schemas(function: &str) -> ControllerSchema {required: true,}],},+ "detail" => ControllerSchema {+ namespace: "skill_registry",+ function: "detail",+ description: "Everything the registry knows about one catalog entry, by id (or a name exactly one entry carries).",+ inputs: vec![FieldSchema {+ name: "entry_id",+ ty: TypeSchema::String,+ comment: "Catalog entry id.",+ required: true,+ }],+ outputs: vec![FieldSchema {+ name: "entry",+ ty: TypeSchema::Json,+ comment: "The catalog entry fields plus registry, installable, category_label, overview and install_identifier.",+ required: true,+ }],+ },"install" => ControllerSchema {namespace: "skill_registry",function: "install",@@ -223,3 +211,121 @@ pub fn skill_registry_schemas(function: &str) -> ControllerSchema {},}}++fn catalog_inputs(with_query: bool) -> Vec<FieldSchema> {+ let mut inputs = Vec::new();+ if with_query {+ inputs.push(FieldSchema {+ name: "query",+ ty: TypeSchema::String,+ comment: "Search query string.",+ required: false,+ });+ }+ inputs.extend([+ FieldSchema {+ name: "source",+ ty: TypeSchema::String,+ comment: "Filter by one upstream source (e.g. 'ClawHub', 'skills.sh', 'built-in').",+ required: false,+ },+ FieldSchema {+ name: "sources",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Filter by any of these upstream sources.",+ required: false,+ },+ FieldSchema {+ name: "category",+ ty: TypeSchema::String,+ comment: "Filter by category.",+ required: false,+ },+ FieldSchema {+ name: "categories",+ ty: TypeSchema::Array(Box::new(TypeSchema::String)),+ comment: "Filter by any of these categories.",+ required: false,+ },+ FieldSchema {+ name: "page",+ ty: TypeSchema::U64,+ comment: "1-based page number.",+ required: false,+ },+ FieldSchema {+ name: "page_size",+ ty: TypeSchema::U64,+ comment: "Entries per page, 1-100 (default 25).",+ required: false,+ },+ FieldSchema {+ name: "force_refresh",+ ty: TypeSchema::Bool,+ comment: "Refetch the catalog before answering.",+ required: false,+ },+ ]);+ inputs+}++fn catalog_outputs(entries_comment: &'static str) -> Vec<FieldSchema> {+ vec![+ FieldSchema {+ name: "entries",+ ty: TypeSchema::Json,+ comment: entries_comment,+ required: true,+ },+ FieldSchema {+ name: "total",+ ty: TypeSchema::U64,+ comment: "Matches across all pages.",+ required: true,+ },+ FieldSchema {+ name: "page",+ ty: TypeSchema::U64,+ comment: "The 1-based page served.",+ required: true,+ },+ FieldSchema {+ name: "page_size",+ ty: TypeSchema::U64,+ comment: "Entries per page after clamping.",+ required: true,+ },+ FieldSchema {+ name: "total_pages",+ ty: TypeSchema::U64,+ comment: "Number of pages; 0 when nothing matched.",+ required: true,+ },+ FieldSchema {+ name: "freshness",+ ty: TypeSchema::Enum {+ variants: vec!["live", "cached", "local_fallback"],+ },+ comment: "How fresh the catalog behind this page is.",+ required: true,+ },+ FieldSchema {+ name: "fetched_at",+ ty: TypeSchema::Option(Box::new(TypeSchema::U64)),+ comment: "Unix seconds of the oldest catalog fetch that answered.",+ required: false,+ },+ FieldSchema {+ name: "refreshing",+ ty: TypeSchema::Bool,+ comment: "Whether a background refresh is running.",+ required: true,+ },+ FieldSchema {+ name: "last_error",+ ty: TypeSchema::Json,+ comment: "The last refresh failure ({kind, message, retry_after_secs}), or null.",+ required: false,+ },+ ]+}diff --git a/crates/openhuman-core/src/skills/catalog/schemas/handlers.rs b/crates/openhuman-core/src/skills/catalog/schemas/handlers.rsindex dc135ab654..06756f67f6 100644--- a/crates/openhuman-core/src/skills/catalog/schemas/handlers.rs+++ b/crates/openhuman-core/src/skills/catalog/schemas/handlers.rs@@ -8,8 +8,8 @@ use crate::skills::catalog::ops;use super::controller_schemas::all_skill_registry_controller_schemas;use super::wire_types::{- BrowseParams, BrowseResult, CategoriesResult, InstallParams, InstallResult, SchemasResult,- SearchParams, SearchResult, SourcesResult, UninstallParams, UninstallResult,+ CatalogParams, CatalogResult, CategoriesResult, EntryParams, InstallResult, SchemasResult,+ SourcesResult, UninstallParams, UninstallResult,};fn deserialize_params<T: serde::de::DeserializeOwned>(@@ -22,64 +22,94 @@ fn to_json<T: serde::Serialize>(outcome: Outcome<T>) -> Result<Value, String> {outcome.into_cli_compatible_json()}+fn registry_error(error: tinyskills::RegistryError) -> String {+ ops::registry_error_message(&error)+}++async fn catalog(method: &'static str, params: Map<String, Value>) -> Result<Value, String> {+ let query = deserialize_params::<CatalogParams>(params)?.into_query();+ tracing::debug!(+ method,+ text = %query.text,+ upstreams = ?query.upstreams,+ categories = ?query.categories,+ page = ?query.page,+ page_size = ?query.page_size,+ force_refresh = query.force_refresh,+ "[skill_registry][rpc] catalog read"+ );+ let page: CatalogResult = ops::catalog_page(&query).await.map_err(registry_error)?;+ tracing::debug!(+ method,+ total = page.total,+ returned = page.entries.len(),+ freshness = ?page.freshness,+ "[skill_registry][rpc] catalog result"+ );+ to_json(Outcome::new(page, Vec::new()))+}+pub(super) fn handle_browse(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p = deserialize_params::<BrowseParams>(params)?;- tracing::debug!(- force_refresh = p.force_refresh,- "[skill_registry][rpc] browse"- );- let entries = ops::browse_catalog(p.force_refresh).await?;- tracing::debug!(count = entries.len(), "[skill_registry][rpc] browse result");- to_json(Outcome::new(BrowseResult { entries }, Vec::new()))- })+ Box::pin(catalog("browse", params))}pub(super) fn handle_search(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let p = deserialize_params::<SearchParams>(params)?;- tracing::debug!(- query = %p.query,- source = ?p.source,- category = ?p.category,- "[skill_registry][rpc] search"- );- let entries =- ops::search_catalog(&p.query, p.source.as_deref(), p.category.as_deref()).await?;- tracing::debug!(count = entries.len(), "[skill_registry][rpc] search result");- to_json(Outcome::new(SearchResult { entries }, Vec::new()))- })+ Box::pin(catalog("search", params))}pub(super) fn handle_sources(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let _ = params;- let sources = ops::list_sources().await?;- to_json(Outcome::new(SourcesResult { sources }, Vec::new()))+ let facets = ops::catalog_facets().await.map_err(registry_error)?;+ to_json(Outcome::new(+ SourcesResult {+ sources: facets.upstreams.iter().map(|f| f.value.clone()).collect(),+ facets: facets.upstreams,+ freshness: facets.freshness,+ },+ Vec::new(),+ ))})}pub(super) fn handle_categories(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {let _ = params;- let categories = ops::list_categories().await?;- to_json(Outcome::new(CategoriesResult { categories }, Vec::new()))+ let facets = ops::catalog_facets().await.map_err(registry_error)?;+ to_json(Outcome::new(+ CategoriesResult {+ categories: facets.categories.iter().map(|f| f.value.clone()).collect(),+ facets: facets.categories,+ freshness: facets.freshness,+ },+ Vec::new(),+ ))+ })+}++pub(super) fn handle_detail(params: Map<String, Value>) -> ControllerFuture {+ Box::pin(async move {+ let p = deserialize_params::<EntryParams>(params)?;+ tracing::debug!(entry_id = %p.entry_id, "[skill_registry][rpc] detail");+ let detail = ops::catalog_detail(&p.entry_id)+ .await+ .map_err(registry_error)?;+ to_json(Outcome::new(detail, Vec::new()))})}pub(super) fn handle_install(params: Map<String, Value>) -> ControllerFuture {Box::pin(async move {- let p = deserialize_params::<InstallParams>(params)?;+ let p = deserialize_params::<EntryParams>(params)?;tracing::info!(entry_id = %p.entry_id,"[skill_registry][rpc] install");- let catalog = ops::browse_catalog(false).await?;- let entry = ops::find_catalog_entry(&catalog, &p.entry_id)?;-let workspace = crate::skills::schemas::resolve_workspace_dir().await;- let outcome = ops::install_from_catalog(&workspace, entry).await?;+ let outcome = ops::install_from_catalog(&workspace, &p.entry_id)+ .await+ .map_err(|error| error.to_string())?;to_json(Outcome::new(InstallResult {diff --git a/crates/openhuman-core/src/skills/catalog/schemas/wire_types.rs b/crates/openhuman-core/src/skills/catalog/schemas/wire_types.rsindex ce51031571..fed682ede0 100644--- a/crates/openhuman-core/src/skills/catalog/schemas/wire_types.rs+++ b/crates/openhuman-core/src/skills/catalog/schemas/wire_types.rs@@ -3,29 +3,58 @@use serde::{Deserialize, Serialize};use crate::core::ControllerSchema;-use crate::skills::catalog::types::CatalogEntry;+use crate::skills::catalog::types::{CatalogPage, CatalogQuery, Facet, Freshness};use crate::skills::ops_types::WorkflowScope;// ── Params ──────────────────────────────────────────────────────────────────+/// Filters and paging shared by `browse` and `search`.#[derive(Debug, Deserialize, Default)]-pub(super) struct BrowseParams {- #[serde(default)]- pub(super) force_refresh: bool,-}--#[derive(Debug, Deserialize, Default)]-pub(super) struct SearchParams {+pub(super) struct CatalogParams {#[serde(default)]pub(super) query: String,#[serde(default)]pub(super) source: Option<String>,#[serde(default)]+ pub(super) sources: Vec<String>,+ #[serde(default)]pub(super) category: Option<String>,+ #[serde(default)]+ pub(super) categories: Vec<String>,+ #[serde(default)]+ pub(super) page: Option<usize>,+ #[serde(default)]+ pub(super) page_size: Option<usize>,+ #[serde(default)]+ pub(super) force_refresh: bool,+}++fn merge_filter(single: Option<String>, many: Vec<String>) -> Vec<String> {+ let mut merged: Vec<String> = Vec::new();+ for value in single.into_iter().chain(many) {+ let value = value.trim().to_owned();+ if !value.is_empty() && !merged.iter().any(|seen| seen.eq_ignore_ascii_case(&value)) {+ merged.push(value);+ }+ }+ merged+}++impl CatalogParams {+ pub(super) fn into_query(self) -> CatalogQuery {+ CatalogQuery {+ text: self.query,+ upstreams: merge_filter(self.source, self.sources),+ categories: merge_filter(self.category, self.categories),+ page: self.page,+ page_size: self.page_size,+ force_refresh: self.force_refresh,+ }+ }}#[derive(Debug, Deserialize)]-pub(super) struct InstallParams {+pub(super) struct EntryParams {pub(super) entry_id: String,}@@ -36,24 +65,20 @@ pub(super) struct UninstallParams {// ── Results ─────────────────────────────────────────────────────────────────-#[derive(Debug, Serialize)]-pub(super) struct BrowseResult {- pub(super) entries: Vec<CatalogEntry>,-}--#[derive(Debug, Serialize)]-pub(super) struct SearchResult {- pub(super) entries: Vec<CatalogEntry>,-}+pub(super) type CatalogResult = CatalogPage;#[derive(Debug, Serialize)]pub(super) struct SourcesResult {pub(super) sources: Vec<String>,+ pub(super) facets: Vec<Facet>,+ pub(super) freshness: Freshness,}#[derive(Debug, Serialize)]pub(super) struct CategoriesResult {pub(super) categories: Vec<String>,+ pub(super) facets: Vec<Facet>,+ pub(super) freshness: Freshness,}#[derive(Debug, Serialize)]@@ -75,3 +100,7 @@ pub(super) struct UninstallResult {pub(super) struct SchemasResult {pub(super) schemas: Vec<ControllerSchema>,}++#[cfg(test)]+#[path = "wire_types_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/skills/catalog/schemas/wire_types_tests.rs b/crates/openhuman-core/src/skills/catalog/schemas/wire_types_tests.rsnew file mode 100644index 0000000000..12b210e599--- /dev/null+++ b/crates/openhuman-core/src/skills/catalog/schemas/wire_types_tests.rs@@ -0,0 +1,93 @@+use super::*;++use serde_json::json;++use crate::skills::catalog::types::{CatalogEntry, RegistryCatalogEntry};++fn params(value: serde_json::Value) -> CatalogParams {+ serde_json::from_value(value).expect("params")+}++#[test]+fn legacy_and_multi_value_filters_merge_without_duplicates() {+ let query = params(json!({+ "query": "git",+ "source": "ClawHub",+ "sources": ["clawhub", "skills.sh", " "],+ "category": "dev",+ }))+ .into_query();+ assert_eq!(query.text, "git");+ assert_eq!(query.upstreams, ["ClawHub", "skills.sh"]);+ assert_eq!(query.categories, ["dev"]);+ assert!(!query.is_paged(), "no paging params reads every match");+}++#[test]+fn paging_params_make_the_read_paged() {+ let query = params(json!({ "page": 2 })).into_query();+ assert!(query.is_paged());+ assert_eq!(query.page, Some(2));+ assert_eq!(query.page_size, None);+}++#[test]+fn a_page_serializes_the_entry_shape_and_snake_case_freshness() {+ let entry = RegistryCatalogEntry {+ entry: CatalogEntry {+ id: "git-helper".into(),+ name: "git-helper".into(),+ description: "d".into(),+ source: "built-in".into(),+ category: "dev".into(),+ author: None,+ version: None,+ tags: Vec::new(),+ platforms: Vec::new(),+ download_url: "https://example.com/SKILL.md".into(),+ source_url: Some("https://example.com/git-helper".into()),+ docs_path: None,+ commands: Vec::new(),+ env_vars: Vec::new(),+ license: None,+ },+ registry: "hermes".into(),+ installable: true,+ category_label: None,+ };+ let page: CatalogResult = CatalogPage {+ entries: vec![entry],+ total: 1,+ page: 1,+ page_size: 25,+ total_pages: 1,+ freshness: Freshness::LocalFallback,+ fetched_at: Some(1),+ refreshing: true,+ last_error: Some(+ serde_json::from_value(json!({+ "kind": "rate_limited",+ "message": "rate limited: retry after 9s",+ "retry_after_secs": 9+ }))+ .unwrap(),+ ),+ };+ let value = serde_json::to_value(&page).unwrap();+ assert_eq!(value["freshness"], "local_fallback");+ assert_eq!(value["refreshing"], true);+ assert_eq!(value["last_error"]["kind"], "rate_limited");+ assert_eq!(value["last_error"]["retry_after_secs"], 9);+ let entry = &value["entries"][0];+ for field in [+ "id",+ "name",+ "download_url",+ "source_url",+ "docs_path",+ "registry",+ "installable",+ ] {+ assert!(entry.get(field).is_some(), "missing {field}: {entry}");+ }+}diff --git a/crates/openhuman-core/src/skills/catalog/test_fixtures.rs b/crates/openhuman-core/src/skills/catalog/test_fixtures.rsnew file mode 100644index 0000000000..7778b9b5e4--- /dev/null+++ b/crates/openhuman-core/src/skills/catalog/test_fixtures.rs@@ -0,0 +1,126 @@+//! A loopback Hermes index and `SKILL.md` host for registry tests.++use std::sync::atomic::{AtomicU16, AtomicUsize, Ordering};+use std::sync::{Arc, Mutex};+use std::time::Duration;++use axum::extract::{Path as AxumPath, State};+use axum::http::StatusCode;+use axum::response::{IntoResponse, Response};+use axum::routing::get;+use axum::Router;+use serde_json::{json, Value};+use tinyskills::{Clock, FetchPolicy, HermesIndexSource, SkillRegistry};++use super::registry::RegistryConfig;+use super::transport::ReqwestTransport;++#[derive(Clone)]+pub(crate) struct Fixture {+ pub(crate) base: String,+ pub(crate) catalog_hits: Arc<AtomicUsize>,+ pub(crate) catalog_status: Arc<AtomicU16>,+ pub(crate) document_status: Arc<AtomicU16>,+}++#[derive(Clone)]+struct FixtureState {+ catalog: Arc<Mutex<Value>>,+ catalog_hits: Arc<AtomicUsize>,+ catalog_status: Arc<AtomicU16>,+ document_status: Arc<AtomicU16>,+}++async fn catalog_route(State(state): State<FixtureState>) -> Response {+ state.catalog_hits.fetch_add(1, Ordering::SeqCst);+ tokio::time::sleep(Duration::from_millis(30)).await;+ let status = state.catalog_status.load(Ordering::SeqCst);+ if status != 200 {+ return StatusCode::from_u16(status).unwrap().into_response();+ }+ axum::Json(state.catalog.lock().unwrap().clone()).into_response()+}++async fn document_route(+ State(state): State<FixtureState>,+ AxumPath(name): AxumPath<String>,+) -> Response {+ let status = state.document_status.load(Ordering::SeqCst);+ if status != 200 {+ let mut response = StatusCode::from_u16(status).unwrap().into_response();+ if status == 429 {+ response+ .headers_mut()+ .insert("retry-after", "42".parse().unwrap());+ }+ return response;+ }+ format!("---\nname: {name}\ndescription: Fixture skill {name}.\n---\n\n# {name}\n")+ .into_response()+}++pub(crate) fn hermes_item(name: &str, source: &str) -> Value {+ json!({+ "name": name,+ "description": format!("{name} helper"),+ "category": "productivity",+ "source": source,+ "tags": ["fixture"],+ "docsPath": format!("fixture/productivity/{name}"),+ })+}++impl Fixture {+ pub(crate) async fn start(items: Vec<Value>) -> Self {+ let state = FixtureState {+ catalog: Arc::new(Mutex::new(Value::Array(items))),+ catalog_hits: Arc::new(AtomicUsize::new(0)),+ catalog_status: Arc::new(AtomicU16::new(200)),+ document_status: Arc::new(AtomicU16::new(200)),+ };+ let app = Router::new()+ .route("/skills.json", get(catalog_route))+ .route("/skills/{name}/SKILL.md", get(document_route))+ .with_state(state.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let addr = listener.local_addr().unwrap();+ tokio::spawn(async move {+ axum::serve(listener, app).await.unwrap();+ });+ Self {+ base: format!("http://{addr}"),+ catalog_hits: state.catalog_hits,+ catalog_status: state.catalog_status,+ document_status: state.document_status,+ }+ }++ pub(crate) fn registry(&self) -> Arc<SkillRegistry> {+ self.build(tinyskills::SystemClock, true)+ }++ pub(crate) fn registry_without_download_base(&self) -> Arc<SkillRegistry> {+ self.build(tinyskills::SystemClock, false)+ }++ pub(crate) fn registry_with_clock(&self, clock: impl Clock + 'static) -> Arc<SkillRegistry> {+ self.build(clock, true)+ }++ fn build(&self, clock: impl Clock + 'static, download_base: bool) -> Arc<SkillRegistry> {+ let mut policy = FetchPolicy::default();+ policy.allow_loopback_http = true;+ let source = HermesIndexSource::new("hermes", format!("{}/skills.json", self.base));+ let source = if download_base {+ source.with_download_base(format!("{}/skills", self.base))+ } else {+ source+ };+ SkillRegistry::builder(ReqwestTransport::new())+ .source(source)+ .policy(policy)+ .limits(RegistryConfig::limits())+ .clock(clock)+ .build()+ }+}diff --git a/crates/openhuman-core/src/skills/catalog/tools.rs b/crates/openhuman-core/src/skills/catalog/tools.rsindex a2a8982981..37ccc6d687 100644--- a/crates/openhuman-core/src/skills/catalog/tools.rs+++ b/crates/openhuman-core/src/skills/catalog/tools.rs@@ -14,6 +14,129 @@ use crate::tools::status::{NOT_FOUND_MARKER, UNSUPPORTED_MARKER};use tinytools::{PermissionLevel, Tool, ToolResult};use super::ops;+use super::types::{CatalogPage, CatalogQuery, RegistryErrorKind, MAX_PAGE_SIZE};++/// Matches returned per browse/search call when the caller does not say:+/// enough candidates to compare and pick from in one read. A broad query over+/// the ~100k-entry catalog matches hundreds, and returning them all makes+/// every search a payload the harness has to summarize first.+const PAGE_DEFAULT_LIMIT: usize = 20;+/// Largest page a caller may ask for.+const PAGE_MAX_LIMIT: usize = MAX_PAGE_SIZE;++fn str_arg<'a>(args: &'a serde_json::Value, key: &str) -> Option<&'a str> {+ args.get(key)+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|v| !v.is_empty())+}++fn usize_arg(args: &serde_json::Value, key: &str) -> Option<usize> {+ args.get(key)+ .and_then(|v| v.as_u64())+ .map(|n| usize::try_from(n).unwrap_or(usize::MAX))+}++/// The catalog query a browse/search call asks for. `offset` is accepted for+/// callers that still page by it and mapped onto the page it falls in.+fn paged_query(args: &serde_json::Value, text: &str) -> CatalogQuery {+ let limit = usize_arg(args, "limit").map_or(PAGE_DEFAULT_LIMIT, |n| n.clamp(1, PAGE_MAX_LIMIT));+ let page = usize_arg(args, "page")+ .or_else(|| usize_arg(args, "offset").map(|offset| offset / limit + 1))+ .unwrap_or(1)+ .max(1);+ CatalogQuery {+ text: text.to_owned(),+ upstreams: str_arg(args, "source")+ .map(str::to_owned)+ .into_iter()+ .collect(),+ categories: str_arg(args, "category")+ .map(str::to_owned)+ .into_iter()+ .collect(),+ page: Some(page),+ page_size: Some(limit),+ force_refresh: args+ .get("force_refresh")+ .and_then(|v| v.as_bool())+ .unwrap_or(false),+ }+}++fn page_result(page: CatalogPage) -> anyhow::Result<ToolResult> {+ let next_page = (page.page < page.total_pages).then_some(page.page + 1);+ tracing::debug!(+ total = page.total,+ page = page.page,+ returned = page.entries.len(),+ freshness = ?page.freshness,+ "[tool][skill_registry] page"+ );+ Ok(ToolResult::success(serde_json::to_string(&json!({+ "total": page.total,+ "page": page.page,+ "total_pages": page.total_pages,+ "next_page": next_page,+ "count": page.entries.len(),+ "freshness": page.freshness,+ "fetched_at": page.fetched_at,+ "refreshing": page.refreshing,+ "last_error": page.last_error,+ "entries": page.entries,+ }))?))+}++fn paging_schema() -> serde_json::Value {+ json!({+ "page": {+ "type": "integer",+ "minimum": 1,+ "default": 1,+ "description": "1-based page. Pass `next_page` from the previous result to read on."+ },+ "limit": {+ "type": "integer",+ "minimum": 1,+ "maximum": PAGE_MAX_LIMIT,+ "default": PAGE_DEFAULT_LIMIT,+ "description": "Matches per page."+ },+ "source": {+ "type": "string",+ "description": "Filter by upstream source (e.g. 'ClawHub', 'skills.sh', 'built-in', 'LobeHub')."+ },+ "category": {+ "type": "string",+ "description": "Filter by category."+ }+ })+}++fn with_paging(mut properties: serde_json::Value) -> serde_json::Value {+ if let (Some(target), serde_json::Value::Object(paging)) =+ (properties.as_object_mut(), paging_schema())+ {+ target.extend(paging);+ }+ properties+}++fn registry_tool_error(action: &str, error: &tinyskills::RegistryError) -> ToolResult {+ let marker = match error.kind() {+ RegistryErrorKind::NotFound | RegistryErrorKind::UnknownRegistry => {+ format!("{NOT_FOUND_MARKER} ")+ }+ RegistryErrorKind::NoDirectDownload | RegistryErrorKind::UpstreamAmbiguous => {+ format!("{UNSUPPORTED_MARKER} ")+ }+ _ => String::new(),+ };+ ToolResult::error(format!(+ "{marker}Failed to {action}: {}",+ ops::registry_error_message(error)+ ))+}pub struct SkillRegistryBrowseTool;@@ -25,38 +148,36 @@ impl Tool for SkillRegistryBrowseTool {fn description(&self) -> &str {"Browse the aggregated skill catalog (HermesHub, ClawHub, skills.sh, \- LobeHub, browse.sh). Returns all available skills with metadata. \- Use `force_refresh: true` to bypass the cache."+ LobeHub, browse.sh) one page at a time (`limit`, default 20). Returns \+ the `total` count, `next_page`, and `freshness` (`cached` with a \+ `last_error` means a saved copy is shown). Use `force_refresh: true` \+ to refetch first."}fn parameters_schema(&self) -> serde_json::Value {json!({"type": "object",- "properties": {+ "properties": with_paging(json!({"force_refresh": {"type": "boolean",- "description": "Force re-fetch from the Hermes API, bypassing cache.",+ "description": "Refetch the catalog before answering.","default": false}- }+ }))})}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let force = args- .get("force_refresh")- .and_then(|v| v.as_bool())- .unwrap_or(false);- tracing::debug!(force_refresh = force, "[tool][skill_registry] browse");-- match ops::browse_catalog(force).await {- Ok(entries) => Ok(ToolResult::success(serde_json::to_string(&json!({- "count": entries.len(),- "entries": entries,- }))?)),- Err(e) => Ok(ToolResult::error(format!(- "Failed to browse skill catalog: {e}"- ))),+ let query = paged_query(&args, "");+ tracing::debug!(+ page = ?query.page,+ limit = ?query.page_size,+ force_refresh = query.force_refresh,+ "[tool][skill_registry] browse"+ );+ match ops::catalog_page(&query).await {+ Ok(page) => page_result(page),+ Err(error) => Ok(registry_tool_error("browse skill catalog", &error)),}}@@ -67,14 +188,6 @@ impl Tool for SkillRegistryBrowseTool {pub struct SkillRegistrySearchTool;-/// Matches returned per `skill_registry_search` call when the caller does not-/// say: enough candidates to compare and pick from in one read. A broad query-/// over the ~100k-entry catalog matches hundreds, and returning them all makes-/// every search a payload the harness has to summarize first (#6286).-const SEARCH_DEFAULT_LIMIT: usize = 20;-/// Largest page a caller may ask for.-const SEARCH_MAX_LIMIT: usize = 100;-#[async_trait]impl Tool for SkillRegistrySearchTool {fn name(&self) -> &str {@@ -85,90 +198,36 @@ impl Tool for SkillRegistrySearchTool {"Search available skills by keyword. Matches against name, description, \tags, category, and author. Optionally filter by source or category. \Returns one page of matches (`limit`, default 20) with the `total` \- match count; pass `next_offset` as `offset` to read the next page."+ match count; pass `next_page` as `page` to read the next page."}fn parameters_schema(&self) -> serde_json::Value {json!({"type": "object",- "properties": {+ "properties": with_paging(json!({"query": {"type": "string","description": "Search query to match against skill name, description, tags, category, or author."- },- "source": {- "type": "string",- "description": "Filter by upstream source (e.g. 'ClawHub', 'skills.sh', 'built-in', 'LobeHub')."- },- "category": {- "type": "string",- "description": "Filter by category."- },- "limit": {- "type": "integer",- "minimum": 1,- "maximum": SEARCH_MAX_LIMIT,- "default": SEARCH_DEFAULT_LIMIT,- "description": "Maximum number of matches to return."- },- "offset": {- "type": "integer",- "minimum": 0,- "default": 0,- "description": "Number of matches to skip. Pass `next_offset` from the previous page."}- },+ })),"required": ["query"]})}async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- let query = args.get("query").and_then(|v| v.as_str()).unwrap_or("");- let source_filter = args.get("source").and_then(|v| v.as_str());- let category_filter = args.get("category").and_then(|v| v.as_str());- let limit = args- .get("limit")- .and_then(|v| v.as_u64())- .map_or(SEARCH_DEFAULT_LIMIT, |n| {- usize::try_from(n).map_or(SEARCH_MAX_LIMIT, |n| n.clamp(1, SEARCH_MAX_LIMIT))- });- let offset = args- .get("offset")- .and_then(|v| v.as_u64())- .map_or(0, |n| usize::try_from(n).unwrap_or(usize::MAX));-+ let text = args.get("query").and_then(|v| v.as_str()).unwrap_or("");+ let query = paged_query(&args, text);tracing::debug!(- query = %query,- source = ?source_filter,- category = ?category_filter,- limit,- offset,+ query = %query.text,+ source = ?query.upstreams,+ category = ?query.categories,+ page = ?query.page,+ limit = ?query.page_size,"[tool][skill_registry] search");-- match ops::search_catalog(query, source_filter, category_filter).await {- Ok(entries) => {- let total = entries.len();- let page: Vec<_> = entries.into_iter().skip(offset).take(limit).collect();- let end = offset.saturating_add(page.len());- let next_offset = (end < total).then_some(end);- tracing::debug!(- total,- returned = page.len(),- next_offset = ?next_offset,- "[tool][skill_registry] search page"- );- Ok(ToolResult::success(serde_json::to_string(&json!({- "total": total,- "offset": offset,- "count": page.len(),- "next_offset": next_offset,- "entries": page,- }))?))- }- Err(e) => Ok(ToolResult::error(format!(- "Failed to search skill catalog: {e}"- ))),+ match ops::catalog_page(&query).await {+ Ok(page) => page_result(page),+ Err(error) => Ok(registry_tool_error("search skill catalog", &error)),}}@@ -220,9 +279,8 @@ impl Tool for SkillRegistryInstallTool {/// Installing a skill mutates the user's local skill set and fetches a/// remote `SKILL.md`, so it routes through the process-global- /// `ApprovalGate` (#3993). On an interactive chat turn the user sees an- /// inline approval card and approves before anything is written; on- /// background/cron turns (no `APPROVAL_CHAT_CONTEXT`) the gate is bypassed,+ /// `ApprovalGate`. On an interactive chat turn the user approves an inline+ /// card before anything is written; background turns bypass the gate,/// matching every other external-effect tool.fn external_effect(&self) -> bool {true@@ -236,32 +294,20 @@ impl Tool for SkillRegistryInstallTool {tracing::debug!(entry_id = %entry_id, "[tool][skill_registry] install");- let catalog = ops::browse_catalog(false)- .await- .map_err(|e| anyhow::anyhow!("failed to load catalog: {e}"))?;-- let entry = ops::find_catalog_entry(&catalog, entry_id)- .map_err(|e| anyhow::anyhow!("{NOT_FOUND_MARKER} {e}"))?;-- match ops::install_from_catalog(&self.workspace_dir, entry).await {+ match ops::install_from_catalog(&self.workspace_dir, entry_id).await {Ok(outcome) => Ok(ToolResult::success(serde_json::to_string(&json!({"url": outcome.url,"stdout": outcome.stdout,"stderr": outcome.stderr,"new_skills": outcome.new_skills,}))?)),- Err(e) => {- // Tagged from the entry, not sniffed from `e`: an entry with no- // direct download can never install, whatever the message says.- let tag = if entry.has_direct_download() {- String::new()- } else {- format!("{UNSUPPORTED_MARKER} ")- };- Ok(ToolResult::error(format!(- "{tag}Failed to install skill '{entry_id}': {e}"- )))- }+ Err(ops::CatalogInstallError::Registry(error)) => Ok(registry_tool_error(+ &format!("install skill '{entry_id}'"),+ &error,+ )),+ Err(error @ ops::CatalogInstallError::Install(_)) => Ok(ToolResult::error(format!(+ "Failed to install skill '{entry_id}': {error}"+ ))),}}}@@ -276,7 +322,8 @@ impl Tool for SkillRegistrySourcesTool {fn description(&self) -> &str {"List the distinct upstream sources available in the catalog \- (e.g. 'built-in', 'ClawHub', 'skills.sh', 'LobeHub', 'browse.sh')."+ (e.g. 'built-in', 'ClawHub', 'skills.sh', 'LobeHub', 'browse.sh'), \+ most entries first, with their entry counts."}fn parameters_schema(&self) -> serde_json::Value {@@ -285,12 +332,18 @@ impl Tool for SkillRegistrySourcesTool {async fn execute(&self, _args: serde_json::Value) -> anyhow::Result<ToolResult> {tracing::debug!("[tool][skill_registry] sources");- match ops::list_sources().await {- Ok(sources) => Ok(ToolResult::success(serde_json::to_string(&json!({- "count": sources.len(),- "sources": sources,- }))?)),- Err(e) => Ok(ToolResult::error(format!("Failed to list sources: {e}"))),+ match ops::catalog_facets().await {+ Ok(facets) => {+ let sources: Vec<&str> =+ facets.upstreams.iter().map(|f| f.value.as_str()).collect();+ Ok(ToolResult::success(serde_json::to_string(&json!({+ "count": sources.len(),+ "sources": sources,+ "counts": facets.upstreams,+ "freshness": facets.freshness,+ }))?))+ }+ Err(error) => Ok(registry_tool_error("list sources", &error)),}}diff --git a/crates/openhuman-core/src/skills/catalog/tools_tests.rs b/crates/openhuman-core/src/skills/catalog/tools_tests.rsindex 9d2b39f742..bcafb373f1 100644--- a/crates/openhuman-core/src/skills/catalog/tools_tests.rs+++ b/crates/openhuman-core/src/skills/catalog/tools_tests.rs@@ -1,10 +1,17 @@use super::*;+use crate::skills::catalog::test_fixtures::{hermes_item, Fixture};++const ENV: [&str; 3] = [+ "OPENHUMAN_SKILL_REGISTRY_CATALOG_URL",+ "OPENHUMAN_SKILL_REGISTRY_CACHE_DIR",+ "OPENHUMAN_SKILL_INSTALL_ALLOW_LOCAL_HTTP",+];+#[test]fn install_tool_is_external_effect_so_it_routes_through_approval_gate() {let tool = SkillRegistryInstallTool::new(Arc::new(Config::default()));assert_eq!(tool.name(), "skill_registry_install");- // #3993: installs must raise an inline approval card before writing.assert!(tool.external_effect(),"skill_registry_install must declare external_effect so the harness gates it"@@ -14,58 +21,113 @@ fn install_tool_is_external_effect_so_it_routes_through_approval_gate() {#[test]fn read_only_skill_tools_are_not_gated() {- // Browse/search/sources stay ungated — they only read the catalog.assert!(!SkillRegistryBrowseTool.external_effect());assert!(!SkillRegistrySearchTool.external_effect());assert!(!SkillRegistrySourcesTool.external_effect());}-async fn search_page(args: serde_json::Value) -> serde_json::Value {- let result = SkillRegistrySearchTool- .execute(args)- .await- .expect("execute");- serde_json::from_str(&result.output()).expect("search result is json")+#[test]+fn paging_arguments_default_clamp_and_accept_an_offset() {+ let defaults = paged_query(&json!({}), "q");+ assert_eq!(defaults.page, Some(1));+ assert_eq!(defaults.page_size, Some(PAGE_DEFAULT_LIMIT));++ let clamped = paged_query(&json!({ "limit": 0, "page": 0 }), "q");+ assert_eq!(clamped.page_size, Some(1));+ assert_eq!(clamped.page, Some(1));++ let capped = paged_query(&json!({ "limit": 10_000 }), "q");+ assert_eq!(capped.page_size, Some(PAGE_MAX_LIMIT));++ let by_offset = paged_query(&json!({ "offset": 40, "limit": 10 }), "q");+ assert_eq!(by_offset.page, Some(5));++ let filtered = paged_query(&json!({ "source": " ClawHub ", "category": "" }), "q");+ assert_eq!(filtered.upstreams, ["ClawHub"]);+ assert!(filtered.categories.is_empty());+}++#[test]+fn registry_errors_carry_the_tool_status_markers() {+ let missing = registry_tool_error(+ "install skill 'x'",+ &tinyskills::RegistryError::NotFound {+ id: "x".into(),+ closest: Vec::new(),+ },+ );+ assert!(+ missing.output().starts_with(NOT_FOUND_MARKER),+ "{}",+ missing.output()+ );+ assert!(missing.output().contains("SKILL_REGISTRY_NOT_FOUND: "));++ let portal = registry_tool_error(+ "install skill 'x'",+ &tinyskills::RegistryError::NoDirectDownload {+ name: "x".into(),+ source_url: None,+ },+ );+ assert!(+ portal.output().starts_with(UNSUPPORTED_MARKER),+ "{}",+ portal.output()+ );++ let outage = registry_tool_error(+ "browse skill catalog",+ &tinyskills::RegistryError::Unavailable { status: 503 },+ );+ assert!(outage+ .output()+ .starts_with("Failed to browse skill catalog: SKILL_REGISTRY_UNAVAILABLE: "));+}++async fn run(tool: &dyn Tool, args: serde_json::Value) -> serde_json::Value {+ let result = tool.execute(args).await.expect("execute");+ serde_json::from_str(&result.output()).expect("tool result is json")}#[tokio::test]-async fn search_tool_returns_a_bounded_page_and_where_the_next_one_starts() {- // #6286: a broad query used to return every match in one result.+async fn browse_and_search_return_bounded_pages_with_their_freshness() {let _env = crate::skills::catalog::TEST_ENV_LOCK.lock().await;- let tmp = tempfile::tempdir().unwrap();- std::env::set_var("OPENHUMAN_SKILL_REGISTRY_CACHE_DIR", tmp.path());- let catalog: Vec<_> = (0..45)- .map(|i| {- ops::parse_hermes_entry(&json!({- "name": format!("review-{i:02}"),- "description": "x",- "source": "built-in"- }))- .expect("entry")- })+ let items = (0..45)+ .map(|i| hermes_item(&format!("review-{i:02}"), "built-in")).collect();- crate::skills::catalog::store::save_catalog_cache(&catalog);+ let fixture = Fixture::start(items).await;+ let cache = tempfile::tempdir().unwrap();+ std::env::set_var(ENV[0], format!("{}/skills.json", fixture.base));+ std::env::set_var(ENV[1], cache.path());+ std::env::set_var(ENV[2], "1");- let first = search_page(json!({ "query": "review" })).await;+ let first = run(&SkillRegistrySearchTool, json!({ "query": "review" })).await;assert_eq!(first["total"], 45);- assert_eq!(- first["count"], SEARCH_DEFAULT_LIMIT,- "default page is bounded"- );- assert_eq!(- first["entries"].as_array().map(Vec::len),- Some(SEARCH_DEFAULT_LIMIT)- );- assert_eq!(first["next_offset"], SEARCH_DEFAULT_LIMIT);+ assert_eq!(first["page"], 1);+ assert_eq!(first["count"], PAGE_DEFAULT_LIMIT);+ assert_eq!(first["next_page"], 2);+ assert_eq!(first["freshness"], "live");+ assert!(first["last_error"].is_null());- let last = search_page(json!({ "query": "review", "offset": 40, "limit": 10 })).await;+ let last = run(+ &SkillRegistrySearchTool,+ json!({ "query": "review", "page": 5, "limit": 10 }),+ )+ .await;assert_eq!(last["count"], 5);assert_eq!(last["entries"][0]["id"], "review-40");- assert!(last["next_offset"].is_null(), "no page after the last one");+ assert!(last["next_page"].is_null(), "no page after the last one");++ let browse = run(&SkillRegistryBrowseTool, json!({})).await;+ assert_eq!(browse["count"], PAGE_DEFAULT_LIMIT);+ assert_eq!(browse["total_pages"], 3);- let clamped = search_page(json!({ "query": "review", "limit": 0 })).await;- assert_eq!(clamped["count"], 1, "limit is at least 1");+ let sources = run(&SkillRegistrySourcesTool, json!({})).await;+ assert_eq!(sources["sources"][0], "built-in");+ assert_eq!(sources["counts"][0]["count"], 45);- crate::skills::catalog::store::clear_cache();- std::env::remove_var("OPENHUMAN_SKILL_REGISTRY_CACHE_DIR");+ for name in ENV {+ std::env::remove_var(name);+ }}diff --git a/crates/openhuman-core/src/skills/catalog/types.rs b/crates/openhuman-core/src/skills/catalog/types.rsindex 51886fedc1..6a1f41596c 100644--- a/crates/openhuman-core/src/skills/catalog/types.rs+++ b/crates/openhuman-core/src/skills/catalog/types.rs@@ -1,4 +1,69 @@-//! Domain types for the skill registry. The catalog entry shape is owned by-//! [`tinyskills`].+//! Domain types for the skill registry. The catalog entry shape and the+//! registry contract are owned by [`tinyskills`].-pub use tinyskills::CatalogEntry;+use serde::Serialize;++pub use tinyskills::{+ CatalogEntry, Facet, Freshness, RegistryErrorKind, RegistryErrorSummary, RegistryFacets,+};++/// Entries per page when a caller pages without naming a size.+pub const DEFAULT_PAGE_SIZE: usize = 25;+/// Largest page a caller may ask for.+pub const MAX_PAGE_SIZE: usize = 100;++/// A catalog entry as the RPC and agent tools return it: the [`CatalogEntry`]+/// fields plus the registry it came from and whether it installs directly.+#[derive(Debug, Clone, Serialize)]+pub struct RegistryCatalogEntry {+ #[serde(flatten)]+ pub entry: CatalogEntry,+ pub registry: String,+ pub installable: bool,+ pub category_label: Option<String>,+}++/// A catalog read: free text plus filters, optionally paged.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct CatalogQuery {+ pub text: String,+ pub upstreams: Vec<String>,+ pub categories: Vec<String>,+ /// 1-based page. With neither `page` nor `page_size` every match is+ /// returned on one page.+ pub page: Option<usize>,+ pub page_size: Option<usize>,+ pub force_refresh: bool,+}++impl CatalogQuery {+ pub fn is_paged(&self) -> bool {+ self.page.is_some() || self.page_size.is_some()+ }+}++/// One page of catalog matches and the state of the data behind it.+#[derive(Debug, Clone, Serialize)]+pub struct CatalogPage {+ pub entries: Vec<RegistryCatalogEntry>,+ pub total: usize,+ pub page: usize,+ pub page_size: usize,+ pub total_pages: usize,+ pub freshness: Freshness,+ /// Unix seconds of the oldest catalog fetch that answered.+ pub fetched_at: Option<u64>,+ /// Whether a source is refreshing in the background now.+ pub refreshing: bool,+ /// The last refresh failure of a source that answered, if any.+ pub last_error: Option<RegistryErrorSummary>,+}++/// Everything the registry knows about one entry.+#[derive(Debug, Clone, Serialize)]+pub struct CatalogDetail {+ #[serde(flatten)]+ pub entry: RegistryCatalogEntry,+ pub overview: String,+ pub install_identifier: Option<String>,+}diff --git a/crates/openhuman-core/src/skills/ops_install.rs b/crates/openhuman-core/src/skills/ops_install.rsindex 35a7382f88..f4cc4a9683 100644--- a/crates/openhuman-core/src/skills/ops_install.rs+++ b/crates/openhuman-core/src/skills/ops_install.rs@@ -8,6 +8,7 @@ mod fetch;mod uninstall;mod url_validation;+pub(crate) use fetch::install_validated_document;pub use fetch::{install_workflow_from_url, InstallWorkflowFromUrlOutcome, InstallWorkflowFromUrlParams,DEFAULT_INSTALL_TIMEOUT_SECS, MAX_INSTALL_TIMEOUT_SECS, MAX_WORKFLOW_MD_BYTES,