agents-skills 0.10.1

A minimal, stable, easy-to-understand skill installer and manager for AI agents
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
//! agent → skills directory mapping (data-driven table) + directory resolution.
//!
//! The table itself lives in [`agents.jsonl`](agents.jsonl) (one JSON object per line,
//! embedded into the binary at compile time): adding or changing an agent is a one-line
//! edit, no Rust changes required. Resolution is fully declarative — [`PathSpec`] probes
//! are interpreted against the injectable [`Env`], making unit tests easy (build a temp
//! dir, no touching the real environment). This module is the single source of truth for
//! *where* skills live: the canonical dir ([`canonical_skills_dir`]) and each agent's own
//! skills dir ([`agent_skills_dir`]).

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;

use serde::Deserialize;

/// The common skills dir shared by most agents.
pub const UNIVERSAL_SKILLS_DIR: &str = ".agents/skills";

/// The sibling dir where disabled skills are parked (never symlinked to agents).
pub const DISABLED_SKILLS_DIR: &str = ".agents/disabled-skills";

/// Embedded agent table: one JSON object per agent line (blank lines and `#` comments
/// allowed). Schema documented in `docs/DEVELOPER.md`.
static AGENT_TABLE_JSONL: &str = include_str!("agents.jsonl");

/// Context for agent detection/dir resolution (owns data, easy to inject in tests).
pub struct Env {
    /// Home directory (`~`).
    pub home: PathBuf,
    /// Config directory (`$XDG_CONFIG_HOME` or `~/.config`).
    pub config: PathBuf,
    /// Current working directory.
    pub cwd: PathBuf,
    /// Environment variables injectable in tests (reads the real env when None).
    vars: Option<HashMap<String, String>>,
    /// Whether detection may probe well-known system locations outside
    /// `home`/`config`/`cwd` (e.g. `/Applications/ZCode.app`). Tests and
    /// sandboxes turn this off so detection stays hermetic.
    probe_system_dirs: bool,
}

impl Env {
    /// Construct an environment context from explicit paths.
    pub fn new(home: impl AsRef<Path>, config: impl AsRef<Path>, cwd: impl AsRef<Path>) -> Self {
        Env {
            home: home.as_ref().to_path_buf(),
            config: config.as_ref().to_path_buf(),
            cwd: cwd.as_ref().to_path_buf(),
            vars: None,
            probe_system_dirs: true,
        }
    }

    /// Read an environment variable (injectable override in tests).
    pub fn var(&self, key: &str) -> Option<String> {
        match &self.vars {
            Some(map) => map.get(key).cloned(),
            None => std::env::var(key).ok(),
        }
    }

    /// Inject environment variable overrides (for library users and tests).
    pub fn set_vars(&mut self, vars: HashMap<String, String>) {
        self.vars = Some(vars);
    }

    /// Toggle probing of well-known system locations outside `home`/`config`/`cwd`.
    ///
    /// Tests and sandboxes pass `false` so agent detection never consults the
    /// real machine (e.g. `/Applications`), keeping results hermetic.
    pub fn set_probe_system_dirs(&mut self, probe: bool) {
        self.probe_system_dirs = probe;
    }
}

/// config dir: `$XDG_CONFIG_HOME || ~/.config`.
pub fn config_home() -> PathBuf {
    match std::env::var("XDG_CONFIG_HOME") {
        Ok(v) if !v.trim().is_empty() => PathBuf::from(v.trim()),
        _ => home().join(".config"),
    }
}

/// Resolve the user's home directory.
pub fn home() -> PathBuf {
    dirs::home_dir().unwrap_or_default()
}

/// `$VAR || home/<default>` (with an optional sub-path) — agent homes like Claude's.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnvHomeSpec {
    /// Environment variable consulted first (e.g. `CLAUDE_CONFIG_DIR`).
    pub var: String,
    /// Home-relative fallback when the var is unset or blank (e.g. `.claude`).
    pub default: String,
    /// Optional sub-path joined after the base (e.g. `skills`).
    #[serde(default)]
    pub path: Option<String>,
}

/// `$VAR/<path>` — a var-derived location (e.g. Zed's `%APPDATA%/Zed`).
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct EnvVarSpec {
    /// Environment variable (e.g. `APPDATA`).
    pub var: String,
    /// Optional sub-path joined after the var value.
    #[serde(default)]
    pub path: Option<String>,
}

/// One declarative path probe: exactly one of the keys below may appear.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum PathSpec {
    /// Exists when `home/<home>` exists.
    Home {
        /// Path relative to the home directory.
        home: String,
    },
    /// Exists when `config/<config>` exists.
    Config {
        /// Path relative to the config directory.
        config: String,
    },
    /// Exists when `cwd/<cwd>` exists.
    Cwd {
        /// Path relative to the working directory.
        cwd: String,
    },
    /// `$VAR || home/<default>`, optionally joined with a sub-path.
    EnvHome {
        /// The env-home spec.
        env_home: EnvHomeSpec,
    },
    /// `$VAR/<path>`; unmatched when the var is unset.
    EnvVar {
        /// The env-var spec.
        env_var: EnvVarSpec,
    },
    /// Absolute system location; only probed when system probing is enabled.
    System {
        /// Absolute path (e.g. `/Applications/ZCode.app`).
        system: String,
    },
}

impl PathSpec {
    /// Resolve against `env`; `None` = not applicable (e.g. var unset, probing off).
    fn resolve(&self, env: &Env) -> Option<PathBuf> {
        match self {
            PathSpec::Home { home } => Some(env.home.join(home)),
            PathSpec::Config { config } => Some(env.config.join(config)),
            PathSpec::Cwd { cwd } => Some(env.cwd.join(cwd)),
            PathSpec::EnvHome { env_home } => Some(env_home.resolve(env)),
            PathSpec::EnvVar { env_var } => env_var.resolve(env),
            PathSpec::System { system } => env.probe_system_dirs.then(|| PathBuf::from(system)),
        }
    }
}

impl EnvHomeSpec {
    fn resolve(&self, env: &Env) -> PathBuf {
        let base = match env.var(&self.var) {
            Some(v) if !v.trim().is_empty() => PathBuf::from(v.trim()),
            _ => env.home.join(&self.default),
        };
        match &self.path {
            Some(p) => base.join(p),
            None => base,
        }
    }
}

impl EnvVarSpec {
    fn resolve(&self, env: &Env) -> Option<PathBuf> {
        let base = PathBuf::from(env.var(&self.var)?);
        Some(match &self.path {
            Some(p) => base.join(p),
            None => base,
        })
    }
}

/// An agent's directory config (one line of the embedded JSONL table).
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Agent {
    /// Agent identifier (used on the CLI).
    pub name: String,
    /// Human-readable display name.
    pub display: String,
    /// Project-level skills dir (relative to cwd).
    pub skills_dir: String,
    /// Global skills directory.
    pub global: PathSpec,
    /// Install detection rules (any match = installed; empty = never detected).
    #[serde(default)]
    pub detect: Vec<PathSpec>,
    /// Whether it is excluded from the universal agents list (default false).
    #[serde(default)]
    pub hidden: bool,
}

impl Agent {
    /// Whether it uses the common `.agents/skills` dir (no symlink needed).
    pub fn is_universal(&self) -> bool {
        self.skills_dir == UNIVERSAL_SKILLS_DIR
    }
}

/// Parse the JSONL table; invalid input is a build bug, so it panics with the line number.
fn parse_agent_table(jsonl: &str) -> Vec<Agent> {
    let mut agents: Vec<Agent> = Vec::new();
    for (idx, line) in jsonl.lines().enumerate() {
        let line = line.trim();
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let agent: Agent = serde_json::from_str(line)
            .unwrap_or_else(|e| panic!("agents.jsonl line {}: {e}", idx + 1));
        if let Some(prev) = agents.iter().position(|a| a.name == agent.name) {
            panic!(
                "agents.jsonl line {}: duplicate agent '{}' (first defined on line {})",
                idx + 1,
                agent.name,
                prev + 1
            );
        }
        agents.push(agent);
    }
    assert!(
        !agents.is_empty(),
        "agents.jsonl must define at least one agent"
    );
    agents
}

/// Agent table, parsed once from the embedded JSONL (leaked to get `&'static` entries).
pub static AGENTS: LazyLock<&'static [Agent]> = LazyLock::new(|| {
    Box::leak(parse_agent_table(AGENT_TABLE_JSONL).into_boxed_slice()) as &'static [Agent]
});

/// Look up an agent by name.
pub fn get_agent(name: &str) -> Option<&'static Agent> {
    let agents: &'static [Agent] = *AGENTS;
    agents.iter().find(|a| a.name == name)
}

/// Display name of an agent (falls back to the raw name).
pub fn agent_display(name: &str) -> String {
    get_agent(name)
        .map(|a| a.display.to_string())
        .unwrap_or_else(|| name.to_string())
}

/// Agents using the common dir (no symlink; excludes hidden ones).
pub fn universal_agents() -> Vec<&'static Agent> {
    let agents: &'static [Agent] = *AGENTS;
    agents
        .iter()
        .filter(|a| a.is_universal() && !a.hidden)
        .collect()
}

/// An agent's global skills dir (None when global is unsupported).
pub fn global_skills_dir(agent: &Agent, env: &Env) -> Option<PathBuf> {
    agent.global.resolve(env)
}

/// Canonical skills dir: `(global ? home : cwd)/.agents/skills`.
pub fn canonical_skills_dir(global: bool, env: &Env) -> PathBuf {
    let base = if global { &env.home } else { &env.cwd };
    base.join(UNIVERSAL_SKILLS_DIR)
}

/// Disabled skills dir: `(global ? home : cwd)/.agents/disabled-skills`.
///
/// Disabled skills are moved here, out of the canonical dir, so no agent (linked
/// or universal) sees them. Enabling moves them back.
pub fn disabled_skills_dir(global: bool, env: &Env) -> PathBuf {
    let base = if global { &env.home } else { &env.cwd };
    base.join(DISABLED_SKILLS_DIR)
}

/// An agent's own skills dir (`None` for universal agents: canonical is their dir).
pub fn agent_skills_dir(agent: &Agent, global: bool, env: &Env) -> Option<PathBuf> {
    if agent.is_universal() {
        return None;
    }
    if global {
        global_skills_dir(agent, env)
    } else {
        Some(env.cwd.join(&agent.skills_dir))
    }
}

/// Determine whether an agent is installed: any detection rule resolves to an existing path.
pub fn is_installed(agent: &Agent, env: &Env) -> bool {
    agent
        .detect
        .iter()
        .any(|spec| spec.resolve(env).is_some_and(|p| p.exists()))
}

/// Detect currently installed agents (universal is never detected as installed).
pub fn detect_installed_agents(env: &Env) -> Vec<&'static Agent> {
    let agents: &'static [Agent] = *AGENTS;
    agents.iter().filter(|a| is_installed(a, env)).collect()
}

/// Ensure universal agents are present (append those missing from the target list).
pub fn ensure_universal_agents(mut target: Vec<&'static Agent>) -> Vec<&'static Agent> {
    let agents: &'static [Agent] = *AGENTS;
    for a in agents.iter().filter(|a| a.is_universal()) {
        if !target.iter().any(|x| x.name == a.name) {
            target.push(a);
        }
    }
    target
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::test_utils::env_at;

    #[test]
    fn agent_table_has_key_agents() {
        assert!(get_agent("claude-code").is_some());
        assert!(get_agent("codex").is_some());
        assert!(get_agent("universal").is_some());
        assert!(get_agent("amp").is_some());
        assert!(get_agent("nope").is_none());
    }

    #[test]
    fn universal_agents_use_agents_skills_dir() {
        for a in ["amp", "codex", "cursor", "opencode"] {
            let agent = get_agent(a).unwrap();
            assert!(agent.is_universal(), "{a} should be universal");
        }
        let claude = get_agent("claude-code").unwrap();
        assert!(!claude.is_universal());
        assert_eq!(claude.skills_dir, ".claude/skills");
    }

    #[test]
    fn hidden_agents_excluded_from_universal_list() {
        let names: Vec<&str> = universal_agents().iter().map(|a| a.name.as_str()).collect();
        assert!(!names.contains(&"dexto"));
        assert!(!names.contains(&"universal"));
        assert!(names.contains(&"amp"));
    }

    #[test]
    fn global_dir_resolution() {
        let tmp = tempfile::TempDir::new().unwrap();
        let env = env_at(&tmp);

        // home base
        let cline = get_agent("cline").unwrap();
        assert_eq!(
            global_skills_dir(cline, &env).unwrap(),
            tmp.path().join(".agents/skills")
        );
        // config base
        let amp = get_agent("amp").unwrap();
        assert_eq!(
            global_skills_dir(amp, &env).unwrap(),
            tmp.path().join("config/agents/skills")
        );
    }

    #[test]
    fn detect_home_config_cwd() {
        let tmp = tempfile::TempDir::new().unwrap();
        let env = env_at(&tmp);

        std::fs::create_dir_all(tmp.path().join(".cline")).unwrap();
        assert!(is_installed(get_agent("cline").unwrap(), &env));

        std::fs::create_dir_all(tmp.path().join("config/amp")).unwrap();
        assert!(is_installed(get_agent("amp").unwrap(), &env));

        std::fs::create_dir_all(tmp.path().join(".replit")).unwrap();
        assert!(is_installed(get_agent("replit").unwrap(), &env));
    }

    #[test]
    fn detect_home_or_cwd() {
        let tmp = tempfile::TempDir::new().unwrap();
        let env = env_at(&tmp);
        std::fs::create_dir_all(tmp.path().join(".codebuddy")).unwrap();
        assert!(is_installed(get_agent("codebuddy").unwrap(), &env));
    }

    #[test]
    fn universal_never_detected_installed() {
        let tmp = tempfile::TempDir::new().unwrap();
        let env = env_at(&tmp);
        assert!(!is_installed(get_agent("universal").unwrap(), &env));
    }

    // Declarative detection semantics (the rules that used to live in special_detect).

    #[test]
    fn env_home_prefers_var_over_default() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut env = env_at(&tmp);
        let claude = get_agent("claude-code").unwrap();

        // Default home: ~/.claude.
        std::fs::create_dir_all(tmp.path().join(".claude")).unwrap();
        assert!(is_installed(claude, &env));

        // Var override: $CLAUDE_CONFIG_DIR wins, default no longer consulted.
        let mut vars = HashMap::new();
        vars.insert(
            "CLAUDE_CONFIG_DIR".to_string(),
            tmp.path().join("cc").display().to_string(),
        );
        env.set_vars(vars);
        assert!(!is_installed(claude, &env));
        std::fs::create_dir_all(tmp.path().join("cc")).unwrap();
        assert!(is_installed(claude, &env));
    }

    #[test]
    fn env_var_unset_never_matches() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut env = env_at(&tmp);
        env.set_vars(HashMap::new()); // no APPDATA
        let zed = get_agent("zed").unwrap();
        assert!(!is_installed(zed, &env)); // config/zed also missing

        let mut vars = HashMap::new();
        vars.insert(
            "APPDATA".to_string(),
            tmp.path().join("appdata").display().to_string(),
        );
        env.set_vars(vars);
        assert!(!is_installed(zed, &env)); // set but path missing
        std::fs::create_dir_all(tmp.path().join("appdata/Zed")).unwrap();
        assert!(is_installed(zed, &env));
    }

    #[test]
    fn system_probe_respects_probe_flag() {
        let tmp = tempfile::TempDir::new().unwrap();
        let mut env = env_at(&tmp);
        env.set_vars(HashMap::new());
        env.set_probe_system_dirs(true);
        let marker = tmp.path().join("sys-marker"); // absolute, outside home/config/cwd
        std::fs::create_dir_all(&marker).unwrap();

        let spec = PathSpec::System {
            system: marker.display().to_string(),
        };
        assert!(spec.resolve(&env).is_some());
        env.set_probe_system_dirs(false);
        assert!(spec.resolve(&env).is_none());
    }

    #[test]
    fn agent_table_parses_comments_and_blank_lines() {
        let table = parse_agent_table(
            "# header comment\n\n{\"name\":\"x\",\"display\":\"X\",\"skills_dir\":\".agents/skills\",\"global\":{\"home\":\".x/skills\"},\"detect\":[{\"home\":\".x\"}]}\n\n",
        );
        assert_eq!(table.len(), 1);
        assert!(table[0].is_universal());
        assert!(!table[0].hidden);
    }

    #[test]
    #[should_panic(expected = "duplicate agent 'x'")]
    fn agent_table_rejects_duplicate_names() {
        let one =
            r#"{"name":"x","display":"X","skills_dir":"s","global":{"home":".x"},"detect":[]}"#;
        let two =
            r#"{"name":"x","display":"Y","skills_dir":"s","global":{"home":".y"},"detect":[]}"#;
        parse_agent_table(&format!("{one}\n{two}\n"));
    }

    #[test]
    #[should_panic(expected = "agents.jsonl line 2:")]
    fn agent_table_reports_offending_line() {
        parse_agent_table(
            "{\"name\":\"x\",\"display\":\"X\",\"skills_dir\":\"s\",\"global\":{\"home\":\".x\"},\"detect\":[]}\nnot json\n",
        );
    }

    #[test]
    fn agent_table_row_count() {
        let agents: &'static [Agent] = *AGENTS;
        assert_eq!(agents.len(), 83);
    }
}