diff --git a/crates/ox-core/src/agent.rs b/crates/ox-core/src/agent.rs index a23153af2..36bb8f6c3 100644 --- a/crates/ox-core/src/agent.rs +++ b/crates/ox-core/src/agent.rs @@ -1,5 +1,6 @@ //! Multi-turn streaming agent loop coordinating a [`Wire`] and [`ToolRegistry`]. +use std::collections::HashSet; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; @@ -11,6 +12,7 @@ use tokio::sync::mpsc; use crate::client::{ReasoningEffort, Request, ResponseEvent, StopReason, Usage, Wire}; use crate::hooks::{HookInput, HookOutcome, HookRunner}; use crate::message::{ContentBlock, Message, Role}; +use crate::skills::SkillRegistry; use crate::tools::{ToolContext, ToolOutput, ToolRegistry}; /// Default maximum number of model turns before an [`Agent`] stops. @@ -105,6 +107,7 @@ pub struct Agent { tool_ctx: ToolContext, config: AgentConfig, hooks: HookRunner, + skills: Arc, } impl Agent { @@ -121,6 +124,7 @@ impl Agent { tool_ctx, config, hooks: HookRunner::default(), + skills: Arc::new(SkillRegistry::new()), } } @@ -131,23 +135,43 @@ impl Agent { self } + /// Attaches a [`SkillRegistry`] for automatic session-start and matcher-driven skill loading. + #[must_use] + pub fn with_skills(mut self, skills: Arc) -> Self { + self.skills = skills; + self + } + /// Starts the multi-turn agent loop with `messages` and returns a stream of [`AgentEvent`]s. pub fn run(&self, messages: Vec) -> AgentEventStream { let (tx, rx) = mpsc::unbounded_channel(); - let wire = Arc::clone(&self.wire); - let tools = Arc::clone(&self.tools); - let tool_ctx = self.tool_ctx.clone(); + let ctx = RunContext { + wire: Arc::clone(&self.wire), + tools: Arc::clone(&self.tools), + tool_ctx: self.tool_ctx.clone(), + hooks: self.hooks.clone(), + skills: Arc::clone(&self.skills), + tx, + }; let config = self.config.clone(); - let hooks = self.hooks.clone(); tokio::spawn(async move { - run_loop(wire, tools, tool_ctx, config, hooks, messages, tx).await; + run_loop(ctx, config, messages).await; }); Box::pin(ReceiverStream(rx)) } } +struct RunContext { + wire: Arc, + tools: Arc, + tool_ctx: ToolContext, + hooks: HookRunner, + skills: Arc, + tx: mpsc::UnboundedSender, +} + struct ReceiverStream(mpsc::UnboundedReceiver); impl Stream for ReceiverStream { @@ -164,55 +188,15 @@ struct TurnOutput { stop_reason: StopReason, } -async fn run_loop( - wire: Arc, - tools: Arc, - tool_ctx: ToolContext, - mut config: AgentConfig, - hooks: HookRunner, - mut messages: Vec, - tx: mpsc::UnboundedSender, -) { - let specs = tools.specs(); +async fn run_loop(ctx: RunContext, mut config: AgentConfig, mut messages: Vec) { + let specs = ctx.tools.specs(); let mut turns = 0; + let mut loaded_skills = HashSet::new(); - if !hooks.is_empty() { - if let HookOutcome::Allow { - system_message: Some(msg), - .. - } = hooks.run(&HookInput::session_start(&tool_ctx.cwd)).await - { - append_system_context(&mut config.system, &msg); - } - - if let Some(prompt) = last_user_prompt(&messages) { - match hooks - .run(&HookInput::user_prompt_submit(&tool_ctx.cwd, prompt)) - .await - { - HookOutcome::Block { reason } => { - _ = hooks.run(&HookInput::session_end(&tool_ctx.cwd)).await; - _ = tx.send(AgentEvent::Error(format!("Blocked by hook: {reason}"))); - return; - } - - HookOutcome::Allow { - system_message: Some(msg), - .. - } => { - if let Some(user_msg) = messages.iter_mut().rev().find(|m| m.role == Role::User) - { - user_msg.content.push(ContentBlock::Text { text: msg }); - } - } + inject_always_active_skills(&ctx.skills, &mut config.system, &mut loaded_skills); - HookOutcome::Allow { - system_message: None, - .. - } - | HookOutcome::Error { .. } => {} - } - } + if !run_session_start_hooks(&ctx, &mut config, &mut messages).await { + return; } while turns < config.max_turns { @@ -227,9 +211,12 @@ async fn run_loop( reasoning_effort: config.reasoning_effort, }; - let Some(turn) = run_turn(&*wire, req, &tx).await else { - if !hooks.is_empty() { - _ = hooks.run(&HookInput::session_end(&tool_ctx.cwd)).await; + let Some(turn) = run_turn(&*ctx.wire, req, &ctx.tx).await else { + if !ctx.hooks.is_empty() { + _ = ctx + .hooks + .run(&HookInput::session_end(&ctx.tool_ctx.cwd)) + .await; } return; }; @@ -241,16 +228,22 @@ async fn run_loop( }); } - if !hooks.is_empty() { - _ = hooks.run(&HookInput::turn_end(&tool_ctx.cwd, turns)).await; + if !ctx.hooks.is_empty() { + _ = ctx + .hooks + .run(&HookInput::turn_end(&ctx.tool_ctx.cwd, turns)) + .await; } if turn.tool_calls.is_empty() { - if !hooks.is_empty() { - _ = hooks.run(&HookInput::stop(&tool_ctx.cwd)).await; - _ = hooks.run(&HookInput::session_end(&tool_ctx.cwd)).await; + if !ctx.hooks.is_empty() { + _ = ctx.hooks.run(&HookInput::stop(&ctx.tool_ctx.cwd)).await; + _ = ctx + .hooks + .run(&HookInput::session_end(&ctx.tool_ctx.cwd)) + .await; } - _ = tx.send(AgentEvent::Done { + _ = ctx.tx.send(AgentEvent::Done { reason: AgentStopReason::Completed(turn.stop_reason), turns, messages, @@ -258,11 +251,13 @@ async fn run_loop( return; } - let Some(tool_results) = - execute_tools(&tools, &tool_ctx, &hooks, turn.tool_calls, &tx).await + let Some(tool_results) = execute_tools(&ctx, &mut loaded_skills, turn.tool_calls).await else { - if !hooks.is_empty() { - _ = hooks.run(&HookInput::session_end(&tool_ctx.cwd)).await; + if !ctx.hooks.is_empty() { + _ = ctx + .hooks + .run(&HookInput::session_end(&ctx.tool_ctx.cwd)) + .await; } return; }; @@ -273,17 +268,91 @@ async fn run_loop( }); } - if !hooks.is_empty() { - _ = hooks.run(&HookInput::stop(&tool_ctx.cwd)).await; - _ = hooks.run(&HookInput::session_end(&tool_ctx.cwd)).await; + if !ctx.hooks.is_empty() { + _ = ctx.hooks.run(&HookInput::stop(&ctx.tool_ctx.cwd)).await; + _ = ctx + .hooks + .run(&HookInput::session_end(&ctx.tool_ctx.cwd)) + .await; } - _ = tx.send(AgentEvent::Done { + _ = ctx.tx.send(AgentEvent::Done { reason: AgentStopReason::MaxTurnsReached, turns, messages, }); } +fn inject_always_active_skills( + skills: &SkillRegistry, + system: &mut Option, + loaded_skills: &mut HashSet, +) { + for skill in skills.always_active() { + if let Ok(body) = skills.load_body(&skill.name) { + let formatted = format_loaded_skill(&skill.name, &body); + append_system_context(system, &formatted); + loaded_skills.insert(skill.name.clone()); + } + } +} + +async fn run_session_start_hooks( + ctx: &RunContext, + config: &mut AgentConfig, + messages: &mut [Message], +) -> bool { + if ctx.hooks.is_empty() { + return true; + } + + if let HookOutcome::Allow { + system_message: Some(msg), + .. + } = ctx + .hooks + .run(&HookInput::session_start(&ctx.tool_ctx.cwd)) + .await + { + append_system_context(&mut config.system, &msg); + } + + if let Some(prompt) = last_user_prompt(messages) { + match ctx + .hooks + .run(&HookInput::user_prompt_submit(&ctx.tool_ctx.cwd, prompt)) + .await + { + HookOutcome::Block { reason } => { + _ = ctx + .hooks + .run(&HookInput::session_end(&ctx.tool_ctx.cwd)) + .await; + _ = ctx + .tx + .send(AgentEvent::Error(format!("Blocked by hook: {reason}"))); + return false; + } + + HookOutcome::Allow { + system_message: Some(msg), + .. + } => { + if let Some(user_msg) = messages.iter_mut().rev().find(|m| m.role == Role::User) { + user_msg.content.push(ContentBlock::Text { text: msg }); + } + } + + HookOutcome::Allow { + system_message: None, + .. + } + | HookOutcome::Error { .. } => {} + } + } + + true +} + async fn run_turn( wire: &dyn Wire, req: Request, @@ -397,16 +466,15 @@ async fn run_turn( } async fn execute_tools( - tools: &ToolRegistry, - tool_ctx: &ToolContext, - hooks: &HookRunner, + ctx: &RunContext, + loaded_skills: &mut HashSet, tool_calls: Vec<(String, String, Value)>, - tx: &mpsc::UnboundedSender, ) -> Option> { let mut tool_results = Vec::with_capacity(tool_calls.len()); for (id, name, mut arguments) in tool_calls { - if tx + if ctx + .tx .send(AgentEvent::ToolCallStart { id: id.clone(), name: name.clone(), @@ -417,15 +485,12 @@ async fn execute_tools( return None; } - let output = if hooks.is_empty() { - match tools.execute(tool_ctx, &name, arguments).await { - Ok(out) => out, - Err(err) => ToolOutput::error(err.to_string()), - } + let mut pre_context = None; + let blocked = if ctx.hooks.is_empty() { + None } else { - let pre_input = HookInput::pre_tool_use(&tool_ctx.cwd, &name, arguments.clone()); - let mut pre_context = None; - let blocked = match hooks.run(&pre_input).await { + let pre_input = HookInput::pre_tool_use(&ctx.tool_ctx.cwd, &name, arguments.clone()); + match ctx.hooks.run(&pre_input).await { HookOutcome::Block { reason } => { Some(ToolOutput::error(format!("Blocked by hook: {reason}"))) } @@ -442,37 +507,55 @@ async fn execute_tools( } HookOutcome::Error { .. } => None, + } + }; + + let output = if let Some(out) = blocked { + out + } else { + let injected_skills = + collect_matching_skills(&ctx.skills, loaded_skills, &name, &arguments); + + let mut out = match ctx + .tools + .execute(&ctx.tool_ctx, &name, arguments.clone()) + .await + { + Ok(out) => out, + Err(err) => ToolOutput::error(err.to_string()), }; + record_explicit_skill_load(loaded_skills, &name, &arguments, out.is_error); - if let Some(out) = blocked { - out + let post_context = if ctx.hooks.is_empty() { + None } else { - let mut out = match tools.execute(tool_ctx, &name, arguments.clone()).await { - Ok(out) => out, - Err(err) => ToolOutput::error(err.to_string()), - }; let post_input = HookInput::post_tool_use( - &tool_ctx.cwd, + &ctx.tool_ctx.cwd, &name, arguments, &out.content, out.is_error, ); - let post_context = match hooks.run(&post_input).await { + match ctx.hooks.run(&post_input).await { HookOutcome::Allow { system_message, .. } => system_message, HookOutcome::Block { .. } | HookOutcome::Error { .. } => None, - }; - if let Some(ctx) = pre_context { - append_tool_context(&mut out.content, &ctx); } - if let Some(ctx) = post_context { - append_tool_context(&mut out.content, &ctx); - } - out + }; + + if let Some(pre) = pre_context { + append_tool_context(&mut out.content, &pre); + } + if let Some(post) = post_context { + append_tool_context(&mut out.content, &post); + } + for skill_ctx in injected_skills { + append_tool_context(&mut out.content, &skill_ctx); } + out }; - if tx + if ctx + .tx .send(AgentEvent::ToolResult { call_id: id.clone(), name, @@ -512,6 +595,59 @@ fn append_tool_context(content: &mut String, ctx: &str) { content.push_str(ctx); } +fn record_explicit_skill_load( + loaded_skills: &mut HashSet, + tool_name: &str, + arguments: &Value, + is_error: bool, +) { + if tool_name == "load_skill" + && !is_error + && let Some(loaded_name) = arguments + .get("name") + .and_then(Value::as_str) + .map(str::trim) + .filter(|value| !value.is_empty()) + { + loaded_skills.insert(loaded_name.to_owned()); + } +} + +fn collect_matching_skills( + skills: &SkillRegistry, + loaded_skills: &mut HashSet, + tool_name: &str, + arguments: &Value, +) -> Vec { + if skills.is_empty() { + return Vec::new(); + } + + let file_path = extract_file_path(arguments); + let mut injected = Vec::new(); + for skill in skills.matching_skills(tool_name, file_path) { + if loaded_skills.contains(&skill.name) { + continue; + } + if let Ok(body) = skills.load_body(&skill.name) { + loaded_skills.insert(skill.name.clone()); + injected.push(format_loaded_skill(&skill.name, &body)); + } + } + injected +} + +fn extract_file_path(arguments: &Value) -> Option<&str> { + arguments + .get("path") + .and_then(Value::as_str) + .or_else(|| arguments.get("file_path").and_then(Value::as_str)) +} + +fn format_loaded_skill(name: &str, body: &str) -> String { + format!("\n{}\n", body.trim_end()) +} + fn last_user_prompt(messages: &[Message]) -> Option { let user_msg = messages.iter().rev().find(|m| m.role == Role::User)?; let parts: Vec<&str> = user_msg @@ -1323,4 +1459,155 @@ mod tests { "ended" ); } + + fn write_test_skills(skills_root: &std::path::Path) -> Arc { + for (subdir, contents) in [ + ( + "always-policy", + indoc::indoc! {" + --- + name: always-policy + description: Always active session rules + activation: always + on_tools: read + --- + + Always verify outputs. + "}, + ), + ( + "rust-files", + indoc::indoc! {" + --- + name: rust-files + description: Rust file rules + on_files: *.rs + --- + + Follow clippy lints. + "}, + ), + ( + "read-tool", + indoc::indoc! {" + --- + name: read-tool + description: Read tool guidance + on_tools: read + --- + + Inspect context around matches. + "}, + ), + ( + "manual-first", + indoc::indoc! {" + --- + name: manual-first + description: Loaded explicitly before matcher runs + on_tools: read + --- + + Manual guidance. + "}, + ), + ] { + let skill_dir = skills_root.join(subdir); + std::fs::create_dir_all(&skill_dir).expect("create skill dir"); + std::fs::write(skill_dir.join("SKILL.md"), contents).expect("write SKILL.md"); + } + Arc::new(crate::skills::SkillRegistry::discover(&[ + skills_root.to_path_buf() + ])) + } + + #[tokio::test] + async fn skills_inject_always_on_start_and_matchers_once_per_session() { + let dir = tempdir().expect("create tempdir"); + std::fs::write(dir.path().join("lib.rs"), "pub fn demo() {}\n").expect("write lib.rs"); + + let skills = write_test_skills(&dir.path().join("skills")); + let mut registry = ToolRegistry::with_defaults(); + registry.register(Arc::new(crate::skills::LoadSkillTool::new(Arc::clone( + &skills, + )))); + + let wire = Arc::new(MockWire::new(vec![ + Ok(vec![ + Ok(ResponseEvent::ToolCall { + id: "call_0".into(), + name: "load_skill".into(), + arguments: json!({ "name": "manual-first" }), + thought_signature: None, + }), + Ok(ResponseEvent::Done(StopReason::ToolUse)), + ]), + Ok(vec![ + Ok(ResponseEvent::ToolCall { + id: "call_1".into(), + name: "read".into(), + arguments: json!({ "path": "lib.rs" }), + thought_signature: None, + }), + Ok(ResponseEvent::Done(StopReason::ToolUse)), + ]), + Ok(vec![ + Ok(ResponseEvent::ToolCall { + id: "call_2".into(), + name: "read".into(), + arguments: json!({ "path": "lib.rs" }), + thought_signature: None, + }), + Ok(ResponseEvent::Done(StopReason::ToolUse)), + ]), + Ok(vec![ + Ok(ResponseEvent::TextDelta("done".into())), + Ok(ResponseEvent::Done(StopReason::EndTurn)), + ]), + ])); + + let mut config = AgentConfig::new("claude-sonnet-5-5"); + config.system = Some("Base system.".into()); + + let agent = Agent::new( + Arc::clone(&wire) as Arc, + Arc::new(registry), + ToolContext::new(dir.path()), + config, + ) + .with_skills(skills); + + let events: Vec = agent + .run(vec![Message::user("check lib.rs")]) + .collect() + .await; + + let requests = wire.recorded_requests(); + assert_eq!(requests.len(), 4); + let system = requests[0].system.as_deref().expect("system prompt"); + assert!(system.contains("Base system.")); + assert!(system.contains("")); + assert!(system.contains("Always verify outputs.")); + + let tool_results: Vec<&str> = events + .iter() + .filter_map(|event| match event { + AgentEvent::ToolResult { content, .. } => Some(content.as_str()), + _ => None, + }) + .collect(); + assert_eq!(tool_results.len(), 3); + assert!(tool_results[0].contains("Manual guidance.")); + + // First read injects matching skills not already loaded at session start or via load_skill. + assert!(tool_results[1].contains("")); + assert!(tool_results[1].contains("Inspect context around matches.")); + assert!(tool_results[1].contains("")); + assert!(tool_results[1].contains("Follow clippy lints.")); + assert!(!tool_results[1].contains("always-policy")); + assert!(!tool_results[1].contains("manual-first")); + + // Second read does not re-inject already loaded skills. + assert!(!tool_results[2].contains(" SkillActivation::OnDemand, + Some("always") => SkillActivation::Always, + + Some(other) => { + return Err(SkillError::MalformedFrontmatter { + path: path.to_path_buf(), + reason: format!("invalid activation `{other}`; expected `on_demand` or `always`"), + }); + } + }; + let on_files = parsed + .get("on_files") + .map(parse_csv_list) + .unwrap_or_default(); + let on_tools = parsed + .get("on_tools") + .map(parse_csv_list) + .unwrap_or_default(); + let model = parsed + .get("model") + .map(str::trim) + .filter(|value| !value.is_empty()) + .map(str::to_owned); + let tools = parsed + .get("tools") + .map(parse_csv_list) + .filter(|list| !list.is_empty()); + let body = parsed.body.replace("\r\n", "\n"); let skill = Skill { name, description, path: path.to_path_buf(), + activation, + on_files, + on_tools, + model, + tools, }; Ok((skill, body)) } +fn parse_csv_list(raw: &str) -> Vec { + raw.split(',') + .map(str::trim) + .filter(|item| !item.is_empty()) + .map(str::to_owned) + .collect() +} + #[cfg(test)] mod tests { use indoc::indoc; @@ -466,6 +569,78 @@ mod tests { assert!(registry.get("beta").is_some()); } + #[test] + fn registry_filters_always_active_and_matching_skills_deterministically() { + let temp = TempDir::new().expect("tempdir"); + write_skill( + temp.path(), + "always-b", + indoc! {" + --- + name: always-b + description: Always active B + activation: always + --- + + Always B body. + "}, + ); + write_skill( + temp.path(), + "always-a", + indoc! {" + --- + name: always-a + description: Always active A + activation: always + --- + + Always A body. + "}, + ); + write_skill( + temp.path(), + "rust-files", + indoc! {" + --- + name: rust-files + description: Triggered on Rust files + on_files: *.rs, Cargo.toml + --- + + Rust body. + "}, + ); + write_skill( + temp.path(), + "edit-guard", + indoc! {" + --- + name: edit-guard + description: Triggered on edit tools + on_tools: edit, write + --- + + Edit body. + "}, + ); + + let registry = SkillRegistry::discover(&[temp.path().to_path_buf()]); + let always: Vec<&str> = registry + .always_active() + .iter() + .map(|s| s.name.as_str()) + .collect(); + assert_eq!(always, vec!["always-a", "always-b"]); + + let matched: Vec<&str> = registry + .matching_skills("edit", Some("crates/ox-core/src/lib.rs")) + .iter() + .map(|s| s.name.as_str()) + .collect(); + assert_eq!(matched, vec!["edit-guard", "rust-files"]); + } + #[test] fn prompt_index_returns_none_when_empty_and_formats_entries_deterministically() { let empty = SkillRegistry::new(); @@ -477,16 +652,31 @@ mod tests { name: "zeta".into(), description: "Last alphabetically".into(), path: PathBuf::from("/z/SKILL.md"), + activation: SkillActivation::OnDemand, + on_files: Vec::new(), + on_tools: Vec::new(), + model: None, + tools: None, })); assert!(registry.register(Skill { name: "alpha".into(), description: "First alphabetically".into(), path: PathBuf::from("/a/SKILL.md"), + activation: SkillActivation::OnDemand, + on_files: Vec::new(), + on_tools: Vec::new(), + model: None, + tools: None, })); assert!(!registry.register(Skill { name: "alpha".into(), description: "Duplicate ignored".into(), path: PathBuf::from("/dup/SKILL.md"), + activation: SkillActivation::OnDemand, + on_files: Vec::new(), + on_tools: Vec::new(), + model: None, + tools: None, })); let index = registry.prompt_index().expect("non-empty index"); @@ -625,5 +815,62 @@ mod tests { .. }) )); + assert!(matches!( + parse_skill_content( + path, + indoc! {" + --- + name: bad-activation + description: Invalid activation mode + activation: never + --- + "} + ), + Err(SkillError::MalformedFrontmatter { reason, .. }) if reason.contains("invalid activation") + )); + } + + #[test] + fn parse_skill_content_parses_activation_matchers_and_role_metadata() { + let path = Path::new("/skills/rust/SKILL.md"); + let (skill, _) = parse_skill_content( + path, + indoc! {" + --- + name: rust-role + description: Rust coding rules and reviewer role + activation: always + on_files: *.rs, Cargo.toml, docs/* + on_tools: edit, write, mcp__* + model: claude-sonnet-5-5 + tools: read, grep, glob + --- + + Always run clippy. + "}, + ) + .expect("parse extended frontmatter"); + + assert_eq!(skill.activation, SkillActivation::Always); + 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")); + assert_eq!( + skill.tools, + Some(vec!["read".into(), "grep".into(), "glob".into()]) + ); + + assert!(skill.matches_file("src/main.rs")); + assert!(skill.matches_file("crates/ox-core/Cargo.toml")); + assert!(skill.matches_file("docs/reference/skills.md")); + assert!(!skill.matches_file("README.md")); + + assert!(skill.matches_tool("edit")); + assert!(skill.matches_tool("mcp__git_diff")); + assert!(!skill.matches_tool("bash")); + + assert!(skill.matches_tool_call("bash", Some("src/lib.rs"))); + assert!(skill.matches_tool_call("write", None)); + assert!(!skill.matches_tool_call("bash", Some("README.md"))); } } diff --git a/docs/reference/skills.md b/docs/reference/skills.md index d07eb90f2..774681823 100644 --- a/docs/reference/skills.md +++ b/docs/reference/skills.md @@ -1,6 +1,6 @@ # Skills -`ox-core` discovers `SKILL.md` skill files from ordered search roots and exposes them to the model through progressive disclosure: a compact system-prompt index plus the on-demand `load_skill` tool. +`ox-core` discovers `SKILL.md` skill files from ordered search roots and exposes them through progressive disclosure, deterministic auto-loading, and agent role metadata. ## Search Roots @@ -15,12 +15,17 @@ ## Skill File Format -Each skill lives in `//SKILL.md` and begins with a `---` YAML frontmatter block defining `name` and `description`: +Each skill lives in `//SKILL.md` and begins with a `---` YAML frontmatter block defining `name`, `description`, and optional activation, matcher, and role fields: ```markdown --- name: rust-review description: Check Rust changes for idioms, error handling, and test coverage. +activation: on_demand +on_files: *.rs, Cargo.toml +on_tools: edit, write +model: claude-sonnet-5-5 +tools: read, grep, glob --- # Rust Review @@ -28,14 +33,21 @@ description: Check Rust changes for idioms, error handling, and test coverage. Run `cargo clippy --all-targets -- -D warnings` before approving changes. ``` -| Field | Required | Notes | -| ------------- | -------- | -------------------------------------------------------- | -| `name` | Yes | Unique skill identifier (single-line, quoted / unquoted) | -| `description` | Yes | Short summary rendered in the system prompt index | +| 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. +Unknown frontmatter keys and `#` comment lines are ignored. Invalid `activation` values fail parsing. -## Progressive Disclosure +## Progressive Disclosure and Auto-Loading - **Prompt index**: `SkillRegistry::prompt_index` returns `None` when no skills are registered, or a deterministic `- : ` list for system prompt injection without embedding full skill bodies. - **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.