Skip to main content

base/
skill.rs

1//! Skill data types: what a loaded SKILL.md is ([`SkillEntry`]), where it came
2//! from, and the `$ARGUMENTS`-style substitution applied to its body.
3
4use std::path::PathBuf;
5
6/// 单个 Skill:从 `<dir>/<skill_name>/SKILL.md` 的 YAML frontmatter 抽出。
7#[derive(Debug, Clone)]
8pub struct SkillEntry {
9    /// 目录名(如 `summarize-pr`);当 frontmatter 给 `name` 时取 frontmatter 值
10    pub name: String,
11    /// frontmatter `description`;不存在则取 markdown 第一行
12    pub description: String,
13    /// frontmatter `when_to_use`;可选
14    pub when_to_use: Option<String>,
15    pub source: SkillSource,
16    /// Which user-level directory a `User` skill was read from.
17    pub tier: Option<SkillTier>,
18    /// SKILL.md 的物理路径(用于 `/skills` 命令展示)
19    pub path: PathBuf,
20    /// Hint shown to user for arguments (e.g. "commit message")
21    pub argument_hint: Option<String>,
22    /// Restrict tools this skill can invoke (whitelist of tool names)
23    pub allowed_tools: Option<Vec<String>>,
24    /// Tools removed from the pool while this skill is active (denylist,
25    /// applied before `allowed_tools`). Clears on the next user message,
26    /// same lifecycle as `allowed_tools`.
27    pub disallowed_tools: Option<Vec<String>>,
28    /// Named positional arguments (`arguments: [issue, branch]`) for `$name`
29    /// substitution in the skill body, in addition to the existing
30    /// positional `$1`..`$9`/`$ARGUMENTS` forms.
31    pub arguments: Option<Vec<String>>,
32    /// Override model for this skill
33    pub model: Option<String>,
34    /// Effort/thinking-mode override while this skill is active. Maps onto
35    /// `base::interface::model::ThinkingMode` — Agix has no separate
36    /// "effort" axis, so this is not a new concept, just this field's name.
37    pub effort: Option<String>,
38    /// Execution context: "fork" (sub-agent) or "inline" (default)
39    pub context: Option<String>,
40    /// Which agent type to run as when `context: "fork"` is set. Defaults to
41    /// `general-purpose` when unset.
42    pub agent: Option<String>,
43    /// Only meaningful with `context: "fork"`. `false` waits for the forked
44    /// result in the invoking turn instead of running it in the background.
45    /// Default: `true` (background).
46    pub background: Option<bool>,
47    /// If true, model cannot invoke this skill directly (only user via slash)
48    pub disable_model_invocation: bool,
49    /// If false, skill is hidden from user-facing slash command list
50    pub user_invocable: bool,
51    /// Glob patterns for conditional activation (auto-load when matching files are touched)
52    pub paths: Option<Vec<String>>,
53    /// Version string for the skill
54    pub version: Option<String>,
55    /// Reference files bundled with the skill. Each entry is a path
56    /// relative to the skill directory. When the skill is invoked, these files
57    /// are read and their content is injected into the skill context.
58    pub files: Option<Vec<String>>,
59    /// Hook event names this skill subscribes to. When the skill is
60    /// loaded, these hooks are registered with the HookRunner.
61    pub hooks: Option<Vec<String>>,
62}
63
64impl Default for SkillEntry {
65    fn default() -> Self {
66        Self {
67            name: String::new(),
68            description: String::new(),
69            when_to_use: None,
70            source: SkillSource::User,
71            tier: None,
72            path: PathBuf::new(),
73            argument_hint: None,
74            allowed_tools: None,
75            disallowed_tools: None,
76            arguments: None,
77            model: None,
78            effort: None,
79            context: None,
80            agent: None,
81            background: None,
82            disable_model_invocation: false,
83            user_invocable: true,
84            paths: None,
85            version: None,
86            files: None,
87            hooks: None,
88        }
89    }
90}
91
92impl SkillEntry {
93    /// Resolves `self.files` (paths relative to the skill's folder) to
94    /// absolute paths. `self.path` is the SKILL.md file itself, so the
95    /// skill folder is `self.path.parent()`. Returns an empty `Vec` if
96    /// `files` is `None`/empty.
97    ///
98    /// Purely mechanical path joining — no existence checks or
99    /// traversal/symlink-escape validation happen here. Callers that need
100    /// those (e.g. `SkillTool`, which must surface a visible error for any
101    /// declared file that escapes the skill folder) run them separately via
102    /// `permissions::path_safety`, which this `core` crate deliberately does
103    /// not depend on.
104    pub fn resolve_bundled_files(&self) -> Vec<PathBuf> {
105        let Some(files) = &self.files else {
106            return Vec::new();
107        };
108        let Some(skill_dir) = self.path.parent() else {
109            return Vec::new();
110        };
111        files.iter().map(|f| skill_dir.join(f)).collect()
112    }
113}
114
115/// Skill 来源 -- user / project;同名时后入者覆盖先入者(见下方扫描顺序)
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum SkillSource {
118    /// `~/.agix/skills/`(全局默认)或 `~/.agix/scenes/<scope>/skills/`(scene 覆盖)
119    User,
120    /// `<cwd>/.agents/skills/`(外部事实标准,Codex 也扫描这个路径)
121    Project,
122    /// Loaded from a plugin's manifest (`~/.agix/plugins/<name>/SKILL.md` or
123    /// `~/.agix/scenes/<scope>/plugins/<name>/SKILL.md`)
124    Plugin,
125    /// A directory the host listed for one session (`options.skill_dirs`):
126    /// trusted as a plugin package is.
127    Host,
128}
129
130/// The user-level directory a skill came from: the state root's own
131/// `skills/` (shared by every scene) or the scene's.
132#[derive(Debug, Clone, Copy, PartialEq, Eq)]
133#[non_exhaustive]
134pub enum SkillTier {
135    Global,
136    Scene,
137}
138
139impl SkillTier {
140    pub fn as_str(&self) -> &'static str {
141        match self {
142            SkillTier::Global => "global",
143            SkillTier::Scene => "scene",
144        }
145    }
146}
147
148impl SkillSource {
149    pub fn as_str(&self) -> &'static str {
150        match self {
151            SkillSource::User => "user",
152            SkillSource::Project => "project",
153            SkillSource::Plugin => "plugin",
154            SkillSource::Host => "host",
155        }
156    }
157}
158
159/// Whether a skill body holds a command its expansion would run: an inline
160/// `` !`cmd` `` or a ` ```! ` block.
161pub fn body_runs_commands(body: &str) -> bool {
162    body.contains("!`") || body.contains("```!")
163}
164
165/// What `${AGIX_SKILL_DIR}` and `${AGIX_SESSION_ID}` stand for in one
166/// invocation.
167pub struct InvocationVars<'a> {
168    /// The skill's `SKILL.md`; its folder is `${AGIX_SKILL_DIR}`.
169    pub skill_md: &'a std::path::Path,
170    pub session_id: Option<&'a str>,
171}
172
173/// Expands the variables in a skill body: for each name in `arg_names`
174/// (the skill's `arguments:` frontmatter list, in
175/// order), `$name` in the body is replaced with the positional argument at
176/// that index (whitespace-separated, same splitting as `$1`..`$9`). A name
177/// with no corresponding argument expands to an empty string, unlike an
178/// *indexed* placeholder with no argument, which is left unchanged — that
179/// asymmetry is intentional, not a bug.
180///
181/// `${AGIX_SKILL_DIR}` and `${AGIX_SESSION_ID}` are replaced from `vars`;
182/// one `vars` does not know — a skill with no folder of its own, a caller
183/// with no session — is left as written.
184pub fn expand_skill_vars_named(
185    body: &str,
186    args: &str,
187    arg_names: &[String],
188    vars: Option<&InvocationVars<'_>>,
189) -> String {
190    let positions: Vec<&str> = args.split_whitespace().collect();
191    let mut out = body.to_string();
192    let mut substituted = false;
193
194    // Named args: $name -> positional value by declared order.
195    for (i, name) in arg_names.iter().enumerate() {
196        let placeholder = format!("${name}");
197        if out.contains(&placeholder) {
198            let value = positions.get(i).copied().unwrap_or("");
199            out = out.replace(&placeholder, value);
200            substituted = true;
201        }
202    }
203
204    if out.contains("$ARGUMENTS") {
205        out = out.replace("$ARGUMENTS", args);
206        substituted = true;
207    }
208    // $@ -- all arguments
209    if out.contains("$@") {
210        out = out.replace("$@", args);
211        substituted = true;
212    }
213    // Positional args $1..$9 (reverse to avoid $10 partial match)
214    for i in (1..=9).rev() {
215        let placeholder = format!("${i}");
216        if out.contains(&placeholder) {
217            let value = positions.get(i - 1).copied().unwrap_or("");
218            out = out.replace(&placeholder, value);
219            substituted = true;
220        }
221    }
222
223    let skill_dir = vars
224        .and_then(|v| v.skill_md.parent())
225        .filter(|dir| !dir.as_os_str().is_empty());
226    if let Some(dir) = skill_dir.filter(|_| out.contains("${AGIX_SKILL_DIR}")) {
227        out = out.replace("${AGIX_SKILL_DIR}", &dir.display().to_string());
228        substituted = true;
229    }
230    if let Some(sid) = vars
231        .and_then(|v| v.session_id)
232        .filter(|_| out.contains("${AGIX_SESSION_ID}"))
233    {
234        out = out.replace("${AGIX_SESSION_ID}", sid);
235        substituted = true;
236    }
237
238    if !substituted && !args.is_empty() {
239        format!("{out}\n\nUser arguments: {args}")
240    } else {
241        out
242    }
243}
244
245#[cfg(test)]
246mod tests {
247    use super::*;
248
249    #[test]
250    fn resolve_bundled_files_joins_relative_to_skill_dir() {
251        let skill = SkillEntry {
252            name: "foo".into(),
253            path: PathBuf::from("/skills/foo/SKILL.md"),
254            files: Some(vec!["notes.md".into(), "ref/extra.md".into()]),
255            ..Default::default()
256        };
257        let resolved = skill.resolve_bundled_files();
258        assert_eq!(
259            resolved,
260            vec![
261                PathBuf::from("/skills/foo/notes.md"),
262                PathBuf::from("/skills/foo/ref/extra.md"),
263            ]
264        );
265    }
266
267    #[test]
268    fn resolve_bundled_files_empty_when_files_is_none() {
269        let skill = SkillEntry {
270            name: "foo".into(),
271            path: PathBuf::from("/skills/foo/SKILL.md"),
272            files: None,
273            ..Default::default()
274        };
275        assert!(skill.resolve_bundled_files().is_empty());
276    }
277
278    #[test]
279    fn resolve_bundled_files_empty_when_files_is_empty_vec() {
280        let skill = SkillEntry {
281            name: "foo".into(),
282            path: PathBuf::from("/skills/foo/SKILL.md"),
283            files: Some(vec![]),
284            ..Default::default()
285        };
286        assert!(skill.resolve_bundled_files().is_empty());
287    }
288
289    #[test]
290    fn resolve_bundled_files_does_not_reject_traversal_paths() {
291        // Purely mechanical joining — traversal rejection is the caller's
292        // job (SkillTool, via permissions::path_safety), not this method's.
293        let skill = SkillEntry {
294            name: "foo".into(),
295            path: PathBuf::from("/skills/foo/SKILL.md"),
296            files: Some(vec!["../../outside.md".into()]),
297            ..Default::default()
298        };
299        assert_eq!(
300            skill.resolve_bundled_files(),
301            vec![PathBuf::from("/skills/foo/../../outside.md")]
302        );
303    }
304
305    #[test]
306    fn expand_named_args_substitute_by_declared_order() {
307        let body = "Migrate $component from $from to $to.";
308        let names = vec![
309            "component".to_string(),
310            "from".to_string(),
311            "to".to_string(),
312        ];
313        let r = expand_skill_vars_named(body, "SearchBar React Vue", &names, None);
314        assert_eq!(r, "Migrate SearchBar from React to Vue.");
315    }
316
317    #[test]
318    fn expand_named_arg_with_no_matching_positional_becomes_empty() {
319        let body = "value=$only";
320        let names = vec!["only".to_string()];
321        let r = expand_skill_vars_named(body, "", &names, None);
322        assert_eq!(r, "value=");
323    }
324
325    #[test]
326    fn empty_names_leave_only_the_positional_forms() {
327        let body = "Run with $ARGUMENTS.";
328        assert_eq!(
329            expand_skill_vars_named(body, "x y z", &[], None),
330            "Run with x y z."
331        );
332    }
333}