diff --git a/crates/ox-core/src/skills.rs b/crates/ox-core/src/skills.rs index 2b5757cef..1d1070753 100644 --- a/crates/ox-core/src/skills.rs +++ b/crates/ox-core/src/skills.rs @@ -87,6 +87,8 @@ pub struct Skill { pub model: Option, /// Optional tool allowlist for agent roles. pub tools: Option>, + /// Whether the skill can be invoked directly by the user as a `/` slash command. + pub user_invocable: bool, } impl Skill { @@ -208,6 +210,14 @@ impl SkillRegistry { .collect() } + /// Returns all registered skills with `user_invocable` enabled in deterministic name order. + pub fn user_invocable(&self) -> Vec<&Skill> { + self.skills + .values() + .filter(|skill| skill.user_invocable) + .collect() + } + /// Returns the number of registered skills. pub fn len(&self) -> usize { self.skills.len() @@ -403,6 +413,18 @@ fn parse_skill_content(path: &Path, content: &str) -> Result<(Skill, String), Sk .get("tools") .map(parse_csv_list) .filter(|list| !list.is_empty()); + let user_invocable = match parsed.get("user_invocable") { + None => activation == SkillActivation::OnDemand, + Some("true") => true, + Some("false") => false, + + Some(other) => { + return Err(SkillError::MalformedFrontmatter { + path: path.to_path_buf(), + reason: format!("invalid user_invocable `{other}`; expected `true` or `false`"), + }); + } + }; let body = parsed.body.replace("\r\n", "\n"); let skill = Skill { @@ -414,6 +436,7 @@ fn parse_skill_content(path: &Path, content: &str) -> Result<(Skill, String), Sk on_tools, model, tools, + user_invocable, }; Ok((skill, body)) } @@ -639,6 +662,13 @@ mod tests { .map(|s| s.name.as_str()) .collect(); assert_eq!(matched, vec!["edit-guard", "rust-files"]); + + let invocable: Vec<&str> = registry + .user_invocable() + .iter() + .map(|s| s.name.as_str()) + .collect(); + assert_eq!(invocable, vec!["edit-guard", "rust-files"]); } #[test] @@ -657,6 +687,7 @@ mod tests { on_tools: Vec::new(), model: None, tools: None, + user_invocable: true, })); assert!(registry.register(Skill { name: "alpha".into(), @@ -667,6 +698,7 @@ mod tests { on_tools: Vec::new(), model: None, tools: None, + user_invocable: true, })); assert!(!registry.register(Skill { name: "alpha".into(), @@ -677,6 +709,7 @@ mod tests { on_tools: Vec::new(), model: None, tools: None, + user_invocable: true, })); let index = registry.prompt_index().expect("non-empty index"); @@ -828,6 +861,19 @@ mod tests { ), Err(SkillError::MalformedFrontmatter { reason, .. }) if reason.contains("invalid activation") )); + assert!(matches!( + parse_skill_content( + path, + indoc! {" + --- + name: bad-invocable + description: Invalid user_invocable flag + user_invocable: maybe + --- + "} + ), + Err(SkillError::MalformedFrontmatter { reason, .. }) if reason.contains("invalid user_invocable") + )); } #[test] @@ -852,6 +898,7 @@ mod tests { .expect("parse extended frontmatter"); assert_eq!(skill.activation, SkillActivation::Always); + assert!(!skill.user_invocable); assert_eq!(skill.on_files, vec!["*.rs", "Cargo.toml", "docs/*"]); assert_eq!(skill.on_tools, vec!["edit", "write", "mcp__*"]); assert_eq!(skill.model.as_deref(), Some("claude-sonnet-5-5")); @@ -860,6 +907,37 @@ mod tests { Some(vec!["read".into(), "grep".into(), "glob".into()]) ); + let (explicit_true, _) = parse_skill_content( + path, + indoc! {" + --- + name: always-invocable + description: Always active yet user-invocable + activation: always + user_invocable: true + --- + + Body. + "}, + ) + .expect("parse explicit user_invocable true"); + assert!(explicit_true.user_invocable); + + let (explicit_false, _) = parse_skill_content( + path, + indoc! {" + --- + name: hidden-skill + description: On-demand but not user-invocable + user_invocable: false + --- + + Body. + "}, + ) + .expect("parse explicit user_invocable false"); + assert!(!explicit_false.user_invocable); + assert!(skill.matches_file("src/main.rs")); assert!(skill.matches_file("crates/ox-core/Cargo.toml")); assert!(skill.matches_file("docs/reference/skills.md")); diff --git a/crates/ox-tui/src/app.rs b/crates/ox-tui/src/app.rs index 6a071ef86..bff6e7cab 100644 --- a/crates/ox-tui/src/app.rs +++ b/crates/ox-tui/src/app.rs @@ -1,9 +1,12 @@ //! Pure Elm / TEA-style state machine for the terminal UI. +use std::sync::Arc; + use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyModifiers}; use ox_core::agent::{AgentEvent, AgentStopReason}; use ox_core::client::Usage; use ox_core::message::Message; +use ox_core::skills::SkillRegistry; use crate::command::{CommandEffect, CommandRegistry}; use crate::keymap::{CommandId, Keymap}; @@ -151,6 +154,13 @@ impl App { self } + /// Registers all `user_invocable` skills from `skills` as `/` slash commands. + #[must_use] + pub fn with_skills(mut self, skills: &Arc) -> Self { + self.commands.register_skills(skills); + self + } + /// Returns the active model identifier. pub fn model(&self) -> &str { &self.model @@ -577,6 +587,14 @@ impl App { self.overlay = Some(overlay); None } + + CommandEffect::SubmitPrompt(prompt) => { + if self.is_busy() { + None + } else { + Some(AppAction::Submit(prompt)) + } + } } } @@ -961,4 +979,52 @@ mod tests { assert_eq!(app.handle_key(key(KeyCode::Enter)), Some(AppAction::Quit)); assert!(app.should_quit()); } + + #[test] + fn with_skills_submits_skill_prompt_when_idle_and_ignores_when_busy() { + use std::sync::Arc; + + use indoc::indoc; + use ox_core::skills::{SKILL_FILENAME, SkillRegistry}; + use tempfile::TempDir; + + let temp = TempDir::new().expect("tempdir"); + let skill_dir = temp.path().join("review"); + std::fs::create_dir_all(&skill_dir).expect("create skill dir"); + std::fs::write( + skill_dir.join(SKILL_FILENAME), + indoc! {" + --- + name: review + description: Review changes + --- + + Check error handling. + "}, + ) + .expect("write SKILL.md"); + + let skills = Arc::new(SkillRegistry::discover(&[temp.path().to_path_buf()])); + let mut app = App::new("gemini-4-neon").with_skills(&skills); + + type_text(&mut app, "/review crates/ox-tui"); + assert_eq!( + app.handle_key(key(KeyCode::Enter)), + Some(AppAction::Submit( + indoc! {" + + Check error handling. + + + crates/ox-tui" + } + .into() + )) + ); + + // Busy app ignores skill prompt submissions until the active turn completes. + app.submit_user_message("in flight".into()); + type_text(&mut app, "/review"); + assert_eq!(app.handle_key(key(KeyCode::Enter)), None); + } } diff --git a/crates/ox-tui/src/command.rs b/crates/ox-tui/src/command.rs index d7f979c56..15e38341f 100644 --- a/crates/ox-tui/src/command.rs +++ b/crates/ox-tui/src/command.rs @@ -4,6 +4,8 @@ use std::collections::BTreeMap; use std::fmt; use std::sync::Arc; +use ox_core::skills::SkillRegistry; + use crate::overlay::Overlay; /// Metadata describing a registered slash command. @@ -26,6 +28,8 @@ pub enum CommandEffect { SystemMessage(String), /// Open an inline [`Overlay`] primitive. OpenOverlay(Overlay), + /// Submit a prompt to the agent (for example, from a user-invocable skill slash command). + SubmitPrompt(String), } type CommandHandler = Arc CommandEffect + Send + Sync>; @@ -97,6 +101,37 @@ impl CommandRegistry { self.aliases.insert(alias.into(), target.into()); } + /// Registers all `user_invocable` skills from `skills` as `/` slash commands. + /// + /// Skills whose name collides with an already-registered command or alias are skipped so + /// built-in commands cannot be shadowed. Returns the number of newly registered skill commands. + pub fn register_skills(&mut self, skills: &Arc) -> usize { + let mut registered = 0; + for skill in skills.user_invocable() { + if self.commands.contains_key(&skill.name) || self.aliases.contains_key(&skill.name) { + continue; + } + + let skill_name = skill.name.clone(); + let registry = Arc::clone(skills); + self.register( + skill.name.clone(), + skill.description.clone(), + move |args| match registry.load_body(&skill_name) { + Ok(body) => { + CommandEffect::SubmitPrompt(format_skill_prompt(&skill_name, &body, args)) + } + + Err(err) => CommandEffect::SystemMessage(format!( + "failed to load skill `{skill_name}`: {err}" + )), + }, + ); + registered += 1; + } + registered + } + /// Returns all aliases targeting `target` in alphabetical order. pub fn aliases_for(&self, target: &str) -> Vec<&str> { self.aliases @@ -180,6 +215,15 @@ impl CommandRegistry { } } +fn format_skill_prompt(name: &str, body: &str, args: &str) -> String { + let body = body.trim(); + if args.is_empty() { + format!("\n{body}\n") + } else { + format!("\n{body}\n\n\n{args}") + } +} + #[cfg(test)] mod tests { use crate::overlay::Overlay; @@ -278,4 +322,116 @@ mod tests { )) ); } + + fn write_test_skill(root: &std::path::Path, dir: &str, content: &str) { + let skill_dir = root.join(dir); + std::fs::create_dir_all(&skill_dir).expect("create skill dir"); + std::fs::write(skill_dir.join(ox_core::skills::SKILL_FILENAME), content) + .expect("write SKILL.md"); + } + + #[test] + fn register_skills_exposes_user_invocable_skills_skips_collisions_and_formats_prompts() { + use std::sync::Arc; + + use indoc::indoc; + use ox_core::skills::{SKILL_FILENAME, SkillRegistry}; + use tempfile::TempDir; + + let temp = TempDir::new().expect("tempdir"); + for (dir, content) in [ + ( + "review", + indoc! {" + --- + name: review + description: Review changes for correctness + --- + + Inspect all modified files carefully. + "}, + ), + ( + "always-on", + indoc! {" + --- + name: always-on + description: Always active skill + activation: always + --- + + Always active body. + "}, + ), + ( + "hidden", + indoc! {" + --- + name: hidden + description: Hidden on-demand skill + user_invocable: false + --- + + Hidden body. + "}, + ), + ( + "help", + indoc! {" + --- + name: help + description: Collides with built-in command + --- + + Shadowed body. + "}, + ), + ( + "exit", + indoc! {" + --- + name: exit + description: Collides with built-in alias + --- + + Shadowed alias body. + "}, + ), + ] { + write_test_skill(temp.path(), dir, content); + } + + let skills = Arc::new(SkillRegistry::discover(&[temp.path().to_path_buf()])); + let mut registry = CommandRegistry::with_builtins(); + assert_eq!(registry.register_skills(&skills), 1); + + assert_eq!(registry.dispatch("/exit"), Some(CommandEffect::Quit)); + let Some(CommandEffect::SystemMessage(help)) = registry.dispatch("/help") else { + panic!("expected help system message"); + }; + assert!(help.contains("/review")); + assert!(help.contains("Review changes for correctness")); + assert!(!help.contains("/always-on")); + assert!(!help.contains("/hidden")); + + assert_eq!( + registry.dispatch("/review"), + Some(CommandEffect::SubmitPrompt( + "\nInspect all modified files carefully.\n".into() + )) + ); + assert_eq!( + registry.dispatch("/review focus on error handling"), + Some(CommandEffect::SubmitPrompt( + "\nInspect all modified files carefully.\n\n\nfocus on error handling".into() + )) + ); + + std::fs::remove_file(temp.path().join("review").join(SKILL_FILENAME)) + .expect("remove skill file"); + let Some(CommandEffect::SystemMessage(err)) = registry.dispatch("/review") else { + panic!("expected error system message"); + }; + assert!(err.contains("failed to load skill `review`")); + } } diff --git a/docs/reference/skills.md b/docs/reference/skills.md index 774681823..0a73dbe97 100644 --- a/docs/reference/skills.md +++ b/docs/reference/skills.md @@ -33,17 +33,18 @@ tools: read, grep, glob Run `cargo clippy --all-targets -- -D warnings` before approving changes. ``` -| Field | Required | Default | Notes | -| ------------- | -------- | ----------- | ------------------------------------------------------------------------ | -| `name` | Yes | | Unique skill identifier (single-line, quoted / unquoted) | -| `description` | Yes | | Short summary rendered in the system prompt index | -| `activation` | No | `on_demand` | `on_demand` or `always` (auto-injected into the system prompt at start) | -| `on_files` | No | empty | Comma-separated file globs matched against `path` / `file_path` tool arg | -| `on_tools` | No | empty | Comma-separated tool name globs matched before tool execution | -| `model` | No | unset | Optional model / profile hint for agent roles | -| `tools` | No | unset | Optional comma-separated tool allowlist for agent roles | - -Unknown frontmatter keys and `#` comment lines are ignored. Invalid `activation` values fail parsing. +| Field | Required | Default | Notes | +| ---------------- | -------- | ------------------------------------ | ------------------------------------------------------------------------ | +| `name` | Yes | | Unique skill identifier (single-line, quoted / unquoted) | +| `description` | Yes | | Short summary rendered in the system prompt index | +| `activation` | No | `on_demand` | `on_demand` or `always` (auto-injected into the system prompt at start) | +| `on_files` | No | empty | Comma-separated file globs matched against `path` / `file_path` tool arg | +| `on_tools` | No | empty | Comma-separated tool name globs matched before tool execution | +| `model` | No | unset | Optional model / profile hint for agent roles | +| `tools` | No | unset | Optional comma-separated tool allowlist for agent roles | +| `user_invocable` | No | `true` for `on_demand`, else `false` | Whether the TUI exposes the skill as a `/` slash command | + +Unknown frontmatter keys and `#` comment lines are ignored. Invalid `activation` or `user_invocable` values fail parsing. ## Progressive Disclosure and Auto-Loading @@ -51,3 +52,4 @@ Unknown frontmatter keys and `#` comment lines are ignored. Invalid `activation` - **On-demand loading**: `LoadSkillTool` implements `Tool` under the name `load_skill` with schema `{ "name": string }`. Calling it reads the matching `SKILL.md` file from disk, strips its frontmatter, and returns the Markdown body. Unknown skill names return a tool error. - **Session-start injection**: When a `SkillRegistry` is attached via `Agent::with_skills`, all skills with `activation: always` are injected into the system prompt at session start and marked loaded. - **Matcher-driven injection**: Before each tool executes, `Agent` evaluates `on_files` against the tool call's `path` / `file_path` argument and `on_tools` against the tool name. Matching skills not yet loaded are injected into the tool context and marked loaded so each skill is injected at most once per session. +- **User-invocable slash commands**: Calling `CommandRegistry::register_skills` or `App::with_skills` in `ox-tui` registers every skill with `user_invocable: true` as `/` with its frontmatter description, skipping names that collide with existing commands or aliases. Dispatching `/ [args]` loads the skill body, wraps it in `...` with any trailing user arguments, and returns `CommandEffect::SubmitPrompt`.