edgecrab-tools 0.11.0

Tool registry, ToolHandler trait, and 50+ tool implementations
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
//! SkillSourceRouter — SOLID dispatcher for registry search/fetch (019 WR).
//!
//! Thin adapters wrap existing `sources.rs` / `mod.rs` functions so new
//! registries implement [`SkillSource`] instead of forking façade code.

use std::future::Future;
use std::path::Path;
use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;
use futures::stream::{FuturesUnordered, StreamExt};

use super::normalize::normalize_identifier;
use super::source_trait::SkillSource;
use super::{
    HubSourceInfo, SearchGroup, SkillBundle, SkillMeta, hub_client, is_provider_filter, sources,
};

type GroupFuture = Pin<Box<dyn Future<Output = SearchGroup> + Send>>;

/// Classify a normalized identifier into a `source_id`.
pub fn classify_source_id(normalized: &str) -> &'static str {
    let lower = normalized.to_ascii_lowercase();
    if lower.starts_with("npm:") {
        return "npm";
    }
    if lower.starts_with("http://") || lower.starts_with("https://") {
        if lower.contains("/.well-known/skills") || lower.contains("well-known:") {
            return "well-known";
        }
        return "url";
    }
    if lower.starts_with("well-known:") {
        return "well-known";
    }
    if lower.starts_with("clawhub:") || lower.starts_with('@') {
        return "clawhub";
    }
    if lower.starts_with("skills.sh:") || lower.starts_with("skills-sh:") {
        return "skills-sh";
    }
    if lower.starts_with("browse-sh:") || lower.starts_with("browse.sh:") {
        return "browse-sh";
    }
    if lower.starts_with("claude-marketplace:") || lower.starts_with("claude:") {
        return "claude-marketplace";
    }
    if lower.starts_with("lobehub:") {
        return "lobehub";
    }
    if lower.starts_with("agentskills:") || lower.starts_with("agentskills.io:") {
        return "agentskills.io";
    }
    if lower.starts_with("official/") {
        return "official";
    }
    if Path::new(normalized).exists() {
        return "local";
    }
    if lower.contains('/') && !lower.contains(' ') {
        return "github";
    }
    "hermes-index"
}

/// Global router with one adapter per catalogued `source_id`.
pub struct SkillSourceRouter {
    sources: Vec<Arc<dyn SkillSource>>,
}

impl SkillSourceRouter {
    pub fn new() -> Self {
        Self {
            sources: default_adapters(),
        }
    }

    pub fn global() -> &'static SkillSourceRouter {
        use std::sync::OnceLock;
        static ROUTER: OnceLock<SkillSourceRouter> = OnceLock::new();
        ROUTER.get_or_init(SkillSourceRouter::new)
    }

    pub fn source_ids(&self) -> impl Iterator<Item = &'static str> + '_ {
        self.sources.iter().map(|s| s.source_id())
    }

    pub fn get(&self, source_id: &str) -> Option<&dyn SkillSource> {
        self.sources
            .iter()
            .find(|s| s.source_id().eq_ignore_ascii_case(source_id))
            .map(|s| s.as_ref())
    }

    pub fn classify(&self, identifier: &str) -> &'static str {
        classify_source_id(&normalize_identifier(identifier))
    }

    /// Fetch via the adapter matching the identifier's source_id.
    ///
    /// `optional_dir` is applied for official/local resolution (trait fetch has no cwd).
    pub async fn fetch(
        &self,
        identifier: &str,
        optional_dir: Option<&Path>,
    ) -> Result<SkillBundle, String> {
        let normalized = normalize_identifier(identifier);
        let source_id = classify_source_id(&normalized);
        match source_id {
            "local" => {
                return super::local_bundle::build_local_skill_bundle(Path::new(&normalized), None);
            }
            "official" => {
                return super::load_official_skill_bundle(&normalized, optional_dir);
            }
            "hermes-index" => {
                if let Some(bundle) = super::index::try_fetch_from_index(&normalized).await {
                    return Ok(bundle);
                }
                return super::fetch_github_resolved(&normalized, optional_dir).await;
            }
            "github" => {
                return super::fetch_github_resolved(&normalized, optional_dir).await;
            }
            _ => {}
        }
        if let Some(src) = self.get(source_id) {
            return src.fetch(&normalized).await;
        }
        Err(format!(
            "Skill source '{identifier}' not found (unknown source_id '{source_id}')"
        ))
    }

    pub async fn search(&self, source_id: &str, query: &str, limit: usize) -> Vec<SkillMeta> {
        match self.get(source_id) {
            Some(src) => src.search(query, limit).await,
            None => Vec::new(),
        }
    }

    /// Parallel live search for `search_hub` — curated + registry adapters + taps.
    ///
    /// Does not include unified-index (façade owns index bootstrap / short-circuit).
    pub async fn search_groups(
        &self,
        query: &str,
        filter: &str,
        limit: usize,
        configured_hub_url: Option<&str>,
    ) -> Vec<SearchGroup> {
        self.search_groups_progressive(query, filter, limit, configured_hub_url, &mut |_| {})
            .await
    }

    /// Progressive live search — invokes `on_partial` as each source group completes.
    ///
    /// True cross-source fan-out: curated + registry + taps share one
    /// `FuturesUnordered` pool (no phase barrier awaiting all curated before
    /// registries/taps start).
    pub async fn search_groups_progressive(
        &self,
        query: &str,
        filter: &str,
        limit: usize,
        configured_hub_url: Option<&str>,
        on_partial: &mut (dyn FnMut(SearchGroup) + Send),
    ) -> Vec<SearchGroup> {
        let mut groups = Vec::new();

        let client = match hub_client() {
            Ok(c) => c,
            Err(error) => {
                let g = SearchGroup {
                    source: HubSourceInfo {
                        id: "hub".into(),
                        label: "Skills Hub".into(),
                        origin: "local".into(),
                        trust_level: "n/a".into(),
                    },
                    results: Vec::new(),
                    notice: Some(error),
                };
                on_partial(g.clone());
                return vec![g];
            }
        };

        let mut pending: FuturesUnordered<GroupFuture> = FuturesUnordered::new();

        // Curated GitHub trees + skills.sh.
        if filter == "all"
            || filter == "github"
            || filter == "curated"
            || filter == "skills.sh"
            || filter == "skills-sh"
            || filter == "registry"
            || is_provider_filter(filter)
            || curated_search_entries().any(|s| source_id_matches_filter(s.id, filter))
        {
            for source in
                curated_search_entries().filter(|s| super::source_matches_filter(s, filter))
            {
                let client = client.clone();
                let q = query.to_string();
                let source = *source;
                pending.push(Box::pin(async move {
                    super::search_source(&client, &source, &q, limit).await
                }));
            }
        }

        // Registry adapters.
        if filter == "all" || sources::registry_filter_includes_any(filter) {
            let registry_filter = if filter == "all" || filter == "registry" {
                "all"
            } else {
                filter
            };
            let reg_limit = limit.clamp(1, 200);
            for source in sources::REGISTRY_SOURCES
                .iter()
                .filter(|source| sources::registry_source_included(source, registry_filter))
            {
                let client = client.clone();
                let q = query.to_string();
                let source = *source;
                pending.push(Box::pin(async move {
                    sources::search_one_registry(&client, &source, &q, reg_limit).await
                }));
            }
        }

        // Custom taps — one future each (stream as they complete).
        if filter == "all" || filter == "tap" || filter == "taps" || is_provider_filter(filter) {
            for tap in super::read_taps()
                .into_iter()
                .filter(|tap| !super::tap_mirrors_curated_catalog(tap))
            {
                let client = client.clone();
                let q = query.to_string();
                pending.push(Box::pin(async move {
                    super::search_custom_tap(&client, &tap, &q, limit).await
                }));
            }
        }

        while let Some(group) = pending.next().await {
            let is_registry = sources::REGISTRY_SOURCES
                .iter()
                .any(|s| s.id.eq_ignore_ascii_case(&group.source.id));
            if is_registry {
                if filter != "all"
                    && filter != "registry"
                    && !registry_id_matches_filter(&group.source.id, filter)
                {
                    continue;
                }
                if group.results.is_empty() && group.notice.is_none() {
                    continue;
                }
            }
            on_partial(group.clone());
            groups.push(group);
        }

        // Well-known URL queries stay sequential (rare; after fan-out).
        if (filter == "all" || filter == "well-known")
            && (query.starts_with("https://") || query.starts_with("http://"))
        {
            let g = super::search_well_known_source(&client, query, limit).await;
            on_partial(g.clone());
            groups.push(g);
        }

        if let Some(url) = configured_hub_url.map(str::trim).filter(|u| !u.is_empty())
            && (filter == "all" || filter == "well-known" || filter == "hub")
        {
            let g = super::search_well_known_source(&client, url, limit).await;
            on_partial(g.clone());
            groups.push(g);
        }

        groups
    }
}

fn curated_search_entries() -> impl Iterator<Item = &'static super::HubCatalogEntry> {
    super::catalog::curated_search_entries()
}

fn source_id_matches_filter(source_id: &str, filter: &str) -> bool {
    filter.eq_ignore_ascii_case(source_id)
}

fn registry_id_matches_filter(source_id: &str, filter: &str) -> bool {
    let f = filter.trim().to_ascii_lowercase();
    let id = source_id.to_ascii_lowercase();
    f == id
        || (f == "skills-sh" && id == "skills-sh")
        || (f == "skills.sh" && (id == "skills-sh" || id == "skills.sh"))
        || (f == "agentskills" && id == "agentskills.io")
        || (f == "registry")
}

impl Default for SkillSourceRouter {
    fn default() -> Self {
        Self::new()
    }
}

fn default_adapters() -> Vec<Arc<dyn SkillSource>> {
    vec![
        Arc::new(OfficialSource),
        Arc::new(HermesIndexSource),
        Arc::new(SkillsShSource),
        Arc::new(WellKnownSource),
        Arc::new(UrlSource),
        Arc::new(GitHubSource),
        Arc::new(ClawHubSource),
        Arc::new(ClaudeMarketplaceSource),
        Arc::new(LobeHubSource),
        Arc::new(BrowseShSource),
        Arc::new(AgentskillsSource),
        Arc::new(NpmSource),
        Arc::new(LocalSource),
    ]
}

struct OfficialSource;
struct HermesIndexSource;
struct SkillsShSource;
struct WellKnownSource;
struct UrlSource;
struct GitHubSource;
struct ClawHubSource;
struct ClaudeMarketplaceSource;
struct LobeHubSource;
struct BrowseShSource;
struct AgentskillsSource;
struct NpmSource;
struct LocalSource;

#[async_trait]
impl SkillSource for OfficialSource {
    fn source_id(&self) -> &'static str {
        "official"
    }
    async fn search(&self, _query: &str, _limit: usize) -> Vec<SkillMeta> {
        Vec::new()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        super::load_official_skill_bundle(identifier, None)
    }
    fn trust_level_for(&self, _: &str) -> &'static str {
        "official"
    }
}

#[async_trait]
impl SkillSource for HermesIndexSource {
    fn source_id(&self) -> &'static str {
        "hermes-index"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let group = super::index::search_unified_index(query, limit);
        group.results
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        if let Some(bundle) = super::index::try_fetch_from_index(identifier).await {
            return Ok(bundle);
        }
        super::fetch_github_resolved(identifier, None).await
    }
}

#[async_trait]
impl SkillSource for SkillsShSource {
    fn source_id(&self) -> &'static str {
        "skills-sh"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = sources::search_registry_sources(query, "skills-sh", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for WellKnownSource {
    fn source_id(&self) -> &'static str {
        "well-known"
    }
    async fn search(&self, _query: &str, _limit: usize) -> Vec<SkillMeta> {
        Vec::new()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for UrlSource {
    fn source_id(&self) -> &'static str {
        "url"
    }
    async fn search(&self, _query: &str, _limit: usize) -> Vec<SkillMeta> {
        Vec::new()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        let client = super::hub_client()?;
        sources::fetch_url_skill_bundle(&client, identifier).await
    }
}

#[async_trait]
impl SkillSource for GitHubSource {
    fn source_id(&self) -> &'static str {
        "github"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = super::search_curated_groups(query, "github", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        super::fetch_github_resolved(identifier, None).await
    }
}

#[async_trait]
impl SkillSource for ClawHubSource {
    fn source_id(&self) -> &'static str {
        "clawhub"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = sources::search_registry_sources(query, "clawhub", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for ClaudeMarketplaceSource {
    fn source_id(&self) -> &'static str {
        "claude-marketplace"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = sources::search_registry_sources(query, "claude-marketplace", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for LobeHubSource {
    fn source_id(&self) -> &'static str {
        "lobehub"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = sources::search_registry_sources(query, "lobehub", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for BrowseShSource {
    fn source_id(&self) -> &'static str {
        "browse-sh"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = sources::search_registry_sources(query, "browse-sh", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for AgentskillsSource {
    fn source_id(&self) -> &'static str {
        "agentskills.io"
    }
    async fn search(&self, query: &str, limit: usize) -> Vec<SkillMeta> {
        let groups = sources::search_registry_sources(query, "agentskills", limit).await;
        groups
            .into_iter()
            .flat_map(|g| g.results)
            .take(limit)
            .collect()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        sources::fetch_registry_bundle(identifier).await
    }
}

#[async_trait]
impl SkillSource for NpmSource {
    fn source_id(&self) -> &'static str {
        "npm"
    }
    async fn search(&self, _query: &str, _limit: usize) -> Vec<SkillMeta> {
        Vec::new()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        let bundles = super::npm_pack::fetch_npm_skill_bundles(identifier)?;
        bundles
            .into_iter()
            .next()
            .ok_or_else(|| format!("npm package '{identifier}' produced no skill bundles"))
    }
}

#[async_trait]
impl SkillSource for LocalSource {
    fn source_id(&self) -> &'static str {
        "local"
    }
    async fn search(&self, _query: &str, _limit: usize) -> Vec<SkillMeta> {
        Vec::new()
    }
    async fn fetch(&self, identifier: &str) -> Result<SkillBundle, String> {
        super::local_bundle::build_local_skill_bundle(Path::new(identifier), None)
    }
    fn trust_level_for(&self, _: &str) -> &'static str {
        "community"
    }
}

#[cfg(test)]
mod tests {
    use super::super::source_trait::ALL_SOURCE_IDS;
    use super::*;
    use std::time::Duration;

    #[test]
    fn classify_peer_and_registry_ids() {
        assert_eq!(classify_source_id("npm:foo"), "npm");
        assert_eq!(classify_source_id("clawhub:bar"), "clawhub");
        assert_eq!(classify_source_id("skills.sh:a/b/c"), "skills-sh");
        assert_eq!(classify_source_id("well-known:https://x/y"), "well-known");
        assert_eq!(classify_source_id("official/cat/name"), "official");
        assert_eq!(classify_source_id("owner/repo/path"), "github");
    }

    #[test]
    fn router_registers_all_catalog_ids() {
        let router = SkillSourceRouter::new();
        let ids: Vec<_> = router.source_ids().collect();
        for id in ALL_SOURCE_IDS {
            assert!(
                ids.iter().any(|x| x == id),
                "router missing adapter for {id}"
            );
        }
    }

    /// Cross-source pool ordering: a fast sibling completes before a slow one
    /// (the barrier that made registries wait on curated).
    #[tokio::test]
    async fn cross_source_pool_emits_fast_before_slow() {
        let mut pending: FuturesUnordered<GroupFuture> = FuturesUnordered::new();
        pending.push(Box::pin(async {
            tokio::time::sleep(Duration::from_millis(80)).await;
            SearchGroup {
                source: HubSourceInfo {
                    id: "slow-curated".into(),
                    label: "Slow".into(),
                    origin: "test".into(),
                    trust_level: "n/a".into(),
                },
                results: Vec::new(),
                notice: Some("slow".into()),
            }
        }));
        pending.push(Box::pin(async {
            tokio::time::sleep(Duration::from_millis(5)).await;
            SearchGroup {
                source: HubSourceInfo {
                    id: "fast-registry".into(),
                    label: "Fast".into(),
                    origin: "test".into(),
                    trust_level: "n/a".into(),
                },
                results: Vec::new(),
                notice: Some("fast".into()),
            }
        }));
        let first = pending.next().await.expect("first completion");
        assert_eq!(
            first.source.id, "fast-registry",
            "registry-shaped sibling must be able to finish before slow curated"
        );
    }
}