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