craftbag 0.2.0

Discover and load Agent Skills (SKILL.md) for CLI and MCP hosts
Documentation
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
//! Host-neutral skill origin. No `Project` variant in v1.

use std::fmt;

use serde::{Deserialize, Serialize};

/// Where a skill was loaded from.
///
/// Repo-local `.agents/skills` is [`Self::Agents`]. Opt-in vendor trees
/// (`.bline`, `.claude`, `.cursor`, `.grok`) are [`Self::Vendor`]. Extra
/// `--paths` are [`Self::ExtraPath`]. A host-supplied user dir is
/// [`Self::User`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum SkillSource {
    /// Host-supplied user skills directory.
    User,
    /// Portable `.agents/skills` tree (repo walk or `$HOME`).
    Agents,
    /// Opt-in vendor tree. `name` is a host token: `bline`, `claude`,
    /// `cursor`, or `grok`.
    Vendor { name: String },
    /// Extra path from the host (`DiscoveryOptions.paths` later).
    ExtraPath,
}

impl SkillSource {
    /// Wire/label name. Unit variants are fixed; vendor uses `name`.
    ///
    /// [`Self::ExtraPath`] is `"extra"` here. Lib serde still emits
    /// `"extraPath"` (`rename_all = "camelCase"`). CLI/MCP list JSON
    /// and why JSON `source` use this token so they match list XML/TSV.
    pub fn as_str(&self) -> &str {
        match self {
            Self::User => "user",
            Self::Agents => "agents",
            Self::Vendor { name } => name.as_str(),
            Self::ExtraPath => "extra",
        }
    }

    /// Stable host-facing token. Same as [`Self::as_str`].
    ///
    /// This is not the serde enum token for [`Self::ExtraPath`]
    /// (`"extraPath"`). Some hosts serialize extra roots as `"config"`;
    /// use [`Self::from_host_token`] to accept that.
    pub fn wire_name(&self) -> String {
        self.as_str().to_owned()
    }

    /// Host list / why JSON: `extra`, `claude`. Not the serde enum tag.
    pub fn serialize_wire<S: serde::Serializer>(
        src: &Self,
        serializer: S,
    ) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(src.as_str())
    }

    /// Accept wire tokens and the older serde enum shape (`extraPath`,
    /// `{vendor:{name}}`).
    pub fn deserialize_host<'de, D: serde::Deserializer<'de>>(
        deserializer: D,
    ) -> Result<Self, D::Error> {
        struct HostVisitor;
        impl<'de> serde::de::Visitor<'de> for HostVisitor {
            type Value = SkillSource;

            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a source wire token or serde SkillSource")
            }

            fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<SkillSource, E> {
                SkillSource::from_host_token(v).ok_or_else(|| {
                    E::custom(format!(
                        "unknown source token: {}",
                        crate::sanitize_error_token(v)
                    ))
                })
            }

            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                map: M,
            ) -> Result<SkillSource, M::Error> {
                SkillSource::deserialize(serde::de::value::MapAccessDeserializer::new(map)).map_err(
                    |e| serde::de::Error::custom(crate::sanitize_error_token(&e.to_string())),
                )
            }
        }
        deserializer.deserialize_any(HostVisitor)
    }

    /// Map a host list / TUI token onto a v1 variant.
    ///
    /// Accepts `user`, `agents`, `extra` / `extraPath` / `extra_path` / `config`,
    /// and vendor tokens `bline` / `claude` / `cursor` / `grok`
    /// (a leading dot is the on-disk tree: `.claude` is `claude`).
    /// Vendor spellings match [`Self::parse_vendor_token`]: ASCII case
    /// and surrounding whitespace are ignored. `extra` / `user` stay
    /// non-vendor. `project` and `community` have no v1 variant (the
    /// host keeps those).
    pub fn from_host_token(token: &str) -> Option<Self> {
        if let Ok(Some(name)) = Self::parse_vendor_token(token) {
            return Some(Self::Vendor { name });
        }
        match token.trim() {
            "user" => Some(Self::User),
            "agents" => Some(Self::Agents),
            "extra" | "extraPath" | "extra_path" | "config" => Some(Self::ExtraPath),
            _ => None,
        }
    }

    /// Frozen v1 vendor tokens (`bline`, `claude`, `cursor`, `grok`).
    pub const VENDOR_TOKENS: &'static [&'static str] = &["bline", "claude", "cursor", "grok"];

    /// Vendor trees whose empty `triggers` are not always-active.
    ///
    /// Claude / Cursor / Grok product rule. [`Self::Vendor`] `bline` is
    /// not in this set ([`crate::filter_skills`] still auto-injects it).
    pub const COMPAT_VENDOR_TOKENS: &'static [&'static str] = &["claude", "cursor", "grok"];

    /// True when empty `triggers` must not auto-inject.
    ///
    /// [`crate::filter_skills`] and `why.activation` share this so a new
    /// vendor token cannot inject in one path and report
    /// `vendor_empty_triggers` in the other.
    pub fn empty_triggers_not_always_active(&self) -> bool {
        match self {
            Self::Vendor { name } => Self::COMPAT_VENDOR_TOKENS.contains(&name.as_str()),
            _ => false,
        }
    }

    /// Help / error list (`bline, claude, cursor, or grok`).
    pub fn vendor_choice_list() -> String {
        match Self::VENDOR_TOKENS {
            [] => String::new(),
            [one] => (*one).to_owned(),
            [a, b] => format!("{a} or {b}"),
            tokens => {
                let (last, rest) = tokens.split_last().expect("VENDOR_TOKENS len>=3");
                format!("{}, or {last}", rest.join(", "))
            }
        }
    }

    /// Parse one `--vendor` / MCP `vendor` token.
    ///
    /// Empty or whitespace is omitted (same as empty `--path` items).
    /// A leading dot and ASCII case are ignored (`.Claude` is `claude`).
    /// Other values, including `user` / `extra`, are errors.
    pub fn parse_vendor_token(token: &str) -> Result<Option<String>, String> {
        let trimmed = token.trim();
        if trimmed.is_empty() {
            return Ok(None);
        }
        let stripped = trimmed.strip_prefix('.').unwrap_or(trimmed);
        let lower = stripped.to_ascii_lowercase();
        if Self::VENDOR_TOKENS.contains(&lower.as_str()) {
            return Ok(Some(lower));
        }
        Err(format!(
            "unknown vendor: {} (use {})",
            crate::sanitize_error_token(trimmed),
            Self::vendor_choice_list()
        ))
    }

    /// Parse a host vendor list. First spelling of each token wins.
    pub fn parse_vendor_roots<I, S>(tokens: I) -> Result<Vec<String>, String>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        let mut out = Vec::new();
        for token in tokens {
            let Some(name) = Self::parse_vendor_token(token.as_ref())? else {
                continue;
            };
            if !out.iter().any(|e| e == &name) {
                out.push(name);
            }
        }
        Ok(out)
    }
}

impl fmt::Display for SkillSource {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::SkillSource;

    #[test]
    fn as_str_labels() {
        assert_eq!(SkillSource::User.as_str(), "user");
        assert_eq!(SkillSource::Agents.as_str(), "agents");
        assert_eq!(SkillSource::ExtraPath.as_str(), "extra");
        assert_eq!(
            SkillSource::Vendor {
                name: "bline".to_owned()
            }
            .as_str(),
            "bline"
        );
        assert_eq!(
            SkillSource::Vendor {
                name: "claude".to_owned()
            }
            .as_str(),
            "claude"
        );
    }

    #[test]
    fn serde_unit_variants_are_camel_case_strings() {
        let user = serde_json::to_string(&SkillSource::User).expect("ser");
        let agents = serde_json::to_string(&SkillSource::Agents).expect("ser");
        let extra = serde_json::to_string(&SkillSource::ExtraPath).expect("ser");
        assert_eq!(user, "\"user\"");
        assert_eq!(agents, "\"agents\"");
        assert_eq!(extra, "\"extraPath\"");

        assert_eq!(
            serde_json::from_str::<SkillSource>(&user).expect("de"),
            SkillSource::User
        );
        assert_eq!(
            serde_json::from_str::<SkillSource>(&agents).expect("de"),
            SkillSource::Agents
        );
        assert_eq!(
            serde_json::from_str::<SkillSource>(&extra).expect("de"),
            SkillSource::ExtraPath
        );
    }

    #[test]
    fn serde_vendor_is_externally_tagged() {
        let src = SkillSource::Vendor {
            name: "cursor".to_owned(),
        };
        let json = serde_json::to_string(&src).expect("ser");
        assert_eq!(json, r#"{"vendor":{"name":"cursor"}}"#);
        let back: SkillSource = serde_json::from_str(&json).expect("de");
        assert_eq!(back, src);
    }

    #[test]
    fn v1_has_no_project_variant() {
        // Exhaustive match is the contract: adding Project fails to compile.
        let src = SkillSource::Agents;
        match src {
            SkillSource::User
            | SkillSource::Agents
            | SkillSource::Vendor { .. }
            | SkillSource::ExtraPath => {}
        }
    }

    #[test]
    fn compat_vendor_tokens_are_a_named_subset() {
        for token in SkillSource::COMPAT_VENDOR_TOKENS {
            assert!(
                SkillSource::VENDOR_TOKENS.contains(token),
                "compat vendor {token} must be a VENDOR_TOKENS member"
            );
            assert!(
                SkillSource::Vendor {
                    name: (*token).to_owned()
                }
                .empty_triggers_not_always_active(),
                "{token} empty triggers must not auto-inject"
            );
        }
        assert!(
            !SkillSource::COMPAT_VENDOR_TOKENS.contains(&"bline"),
            "bline stays always-active when triggers are empty"
        );
        assert!(
            !SkillSource::Vendor {
                name: "bline".to_owned()
            }
            .empty_triggers_not_always_active()
        );
        assert!(!SkillSource::Agents.empty_triggers_not_always_active());
        assert!(!SkillSource::User.empty_triggers_not_always_active());
        assert!(!SkillSource::ExtraPath.empty_triggers_not_always_active());
    }

    #[test]
    fn extra_as_str_is_not_serde_token() {
        assert_eq!(SkillSource::ExtraPath.as_str(), "extra");
        assert_eq!(SkillSource::ExtraPath.wire_name(), "extra");
        let json = serde_json::to_string(&SkillSource::ExtraPath).expect("ser");
        assert_eq!(json, "\"extraPath\"");
    }

    #[test]
    fn host_json_source_is_wire_name_and_accepts_old_enum() {
        #[derive(serde::Serialize, serde::Deserialize)]
        struct Row {
            #[serde(
                serialize_with = "SkillSource::serialize_wire",
                deserialize_with = "SkillSource::deserialize_host"
            )]
            source: SkillSource,
        }
        let extra = serde_json::to_value(&Row {
            source: SkillSource::ExtraPath,
        })
        .expect("ser extra");
        assert_eq!(extra["source"], "extra", "{extra}");
        let vendor = serde_json::to_value(&Row {
            source: SkillSource::Vendor {
                name: "claude".to_owned(),
            },
        })
        .expect("ser vendor");
        assert_eq!(vendor["source"], "claude", "{vendor}");
        let old_extra: Row = serde_json::from_str(r#"{"source":"extraPath"}"#).expect("old extra");
        assert_eq!(old_extra.source, SkillSource::ExtraPath);
        let snake_extra: Row =
            serde_json::from_str(r#"{"source":"extra_path"}"#).expect("snake extra");
        assert_eq!(snake_extra.source, SkillSource::ExtraPath);
        let old_vendor: Row =
            serde_json::from_str(r#"{"source":{"vendor":{"name":"claude"}}}"#).expect("old vendor");
        assert_eq!(old_vendor.source.as_str(), "claude");
    }

    #[test]
    fn from_host_token_maps_list_and_tui_tokens() {
        assert_eq!(
            SkillSource::from_host_token("user"),
            Some(SkillSource::User)
        );
        assert_eq!(
            SkillSource::from_host_token("agents"),
            Some(SkillSource::Agents)
        );
        assert_eq!(
            SkillSource::from_host_token("extra"),
            Some(SkillSource::ExtraPath)
        );
        assert_eq!(
            SkillSource::from_host_token("extraPath"),
            Some(SkillSource::ExtraPath)
        );
        assert_eq!(
            SkillSource::from_host_token("extra_path"),
            Some(SkillSource::ExtraPath)
        );
        assert_eq!(
            SkillSource::from_host_token("config"),
            Some(SkillSource::ExtraPath)
        );
        assert_eq!(
            SkillSource::from_host_token("bline"),
            Some(SkillSource::Vendor {
                name: "bline".to_owned()
            })
        );
        assert_eq!(
            SkillSource::from_host_token("claude"),
            Some(SkillSource::Vendor {
                name: "claude".to_owned()
            })
        );
        assert_eq!(
            SkillSource::from_host_token("cursor"),
            Some(SkillSource::Vendor {
                name: "cursor".to_owned()
            })
        );
        assert_eq!(
            SkillSource::from_host_token("grok"),
            Some(SkillSource::Vendor {
                name: "grok".to_owned()
            })
        );
        assert_eq!(SkillSource::from_host_token("project"), None);
        assert_eq!(SkillSource::from_host_token("community"), None);
        assert_eq!(SkillSource::from_host_token("Project"), None);
        assert_eq!(
            SkillSource::from_host_token(".claude"),
            Some(SkillSource::Vendor {
                name: "claude".to_owned()
            })
        );
        assert_eq!(
            SkillSource::from_host_token(".bline"),
            Some(SkillSource::Vendor {
                name: "bline".to_owned()
            })
        );
        assert_eq!(SkillSource::from_host_token(".user"), None);
        assert_eq!(SkillSource::from_host_token(".extra"), None);
        // parse_vendor_roots folds ASCII case and a leading dot. Hosts
        // that pass the same token through from_host_token must land on
        // the same Vendor name, not None.
        for token in [".Claude", "Claude", " CLAUDE ", ".BLINE", "Cursor"] {
            let parsed =
                SkillSource::parse_vendor_roots([token]).unwrap_or_else(|e| panic!("{token}: {e}"));
            assert_eq!(
                SkillSource::from_host_token(token),
                Some(SkillSource::Vendor {
                    name: parsed[0].clone()
                }),
                "from_host_token({token:?}) must match parse_vendor_roots"
            );
        }
    }

    #[test]
    fn parse_vendor_roots_accepts_dot_and_rejects_unknown() {
        assert_eq!(
            SkillSource::parse_vendor_roots([".claude", "Bline", " claude "]).expect("ok"),
            ["claude", "bline"]
        );
        assert!(
            SkillSource::parse_vendor_roots(["", "  "])
                .expect("empty items")
                .is_empty()
        );
        let err = SkillSource::parse_vendor_roots(["nope"]).expect_err("unknown");
        assert!(err.contains("unknown vendor: nope"), "{err}");
        let listed = SkillSource::vendor_choice_list();
        assert!(
            err.contains(&listed),
            "unknown-vendor error must name vendor_choice_list: {err}"
        );
        for token in SkillSource::VENDOR_TOKENS {
            assert!(
                listed.contains(token),
                "vendor_choice_list must name {token}: {listed}"
            );
        }
        let extra = SkillSource::parse_vendor_roots(["extra"]).expect_err("extra");
        assert!(
            extra.contains("unknown vendor: extra"),
            "extra is --path, not a vendor: {extra}"
        );
        let injected = SkillSource::parse_vendor_roots(["no\npe"]).expect_err("control");
        assert!(
            injected.contains("unknown vendor: no?pe"),
            "vendor errors must stay one line: {injected}"
        );
        assert!(!injected.contains('\n'), "{injected}");
    }

    #[test]
    fn deserialize_host_unknown_source_token_is_sanitized() {
        #[derive(Debug, serde::Deserialize)]
        struct Row {
            #[serde(deserialize_with = "SkillSource::deserialize_host")]
            #[allow(dead_code)]
            source: SkillSource,
        }
        let json = serde_json::json!({ "source": "foo\u{2028}bar\u{2014}" }).to_string();
        let err = serde_json::from_str::<Row>(&json).expect_err("unknown source");
        let msg = err.to_string();
        assert!(
            msg.contains("unknown source token:"),
            "host source errors must name the token: {msg}"
        );
        assert_eq!(
            msg.lines().count(),
            1,
            "unknown source token must stay one line: {msg:?}"
        );
        assert!(
            !msg.contains('\u{2028}'),
            "U+2028 must not leak from source token: {msg:?}"
        );
        assert!(
            !msg.contains('\u{2014}'),
            "em dash must not leak from source token: {msg:?}"
        );
        assert!(
            msg.contains("foo?bar-"),
            "hostile source token must be sanitized in place: {msg}"
        );
    }

    #[test]
    fn deserialize_host_unknown_source_map_token_is_sanitized() {
        #[derive(Debug, serde::Deserialize)]
        struct Row {
            #[serde(deserialize_with = "SkillSource::deserialize_host")]
            #[allow(dead_code)]
            source: SkillSource,
        }
        let json = serde_json::json!({
            "source": { "foo\u{2028}bar\u{2014}": { "name": "x" } }
        })
        .to_string();
        let err = serde_json::from_str::<Row>(&json).expect_err("unknown source map");
        let msg = err.to_string();
        assert!(
            msg.contains("unknown variant"),
            "host source map errors must name the token: {msg}"
        );
        assert_eq!(
            msg.lines().count(),
            1,
            "unknown source map token must stay one line: {msg:?}"
        );
        assert!(
            !msg.contains('\u{2028}'),
            "U+2028 must not leak from source map token: {msg:?}"
        );
        assert!(
            !msg.contains('\u{2014}'),
            "em dash must not leak from source map token: {msg:?}"
        );
        assert!(
            msg.contains("foo?bar-"),
            "hostile source map token must be sanitized in place: {msg}"
        );
    }
}