Skills: manage and import your own, switch on per chat, search instead of listing

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Richard ZinkandClaude Sonnet 5.5 committed 2026-11-17 14:28:13 +01:00
1 parent e150de3c93
commit a84a3acaa0
20 files changed
+943 -26

No files matched your search

+122 -12
View File
@@ -285,11 +285,16 @@ pub fn system_prompt(app: &App, agent: &Agent, root: &Path, cwd: &Path, model: &
s.push_str(&format!("- {server} ({n} tools, e.g. {})\n", names.join(", ")));
}
}
let skills = skills(app, root, cwd);
let skills = skills(app, root, cwd, owner.map(|u| u.id.as_str()));
if !skills.is_empty() {
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
for sk in &skills {
s.push_str(&format!("- {}: {}\n", sk.name, sk.description));
if skills.len() <= SKILL_LIST_MAX {
s.push_str("\n# Skills\nLoad a skill with the skill tool when the task matches its description:\n");
for sk in &skills {
s.push_str(&format!("- {}: {}\n", sk.name, sk.description.chars().take(160).collect::<String>()));
}
} else {
// A large library must not fill the context: only the count; the agent searches on demand.
s.push_str(&format!("\n# Skills\n{} skills (packaged instructions for kinds of task) are available but not listed. Find one with the skill tool (query=<keywords>), then load it with name=<skill>.\n", skills.len()));
}
}
if let Some(u) = owner {
@@ -381,23 +386,91 @@ pub struct Skill {
pub name: String,
pub description: String,
pub path: PathBuf,
/// Further files of the skill (relative paths, without SKILL.md).
pub files: Vec<String>,
/// Created by the user in the UI (editable there).
pub user: bool,
}
pub fn skills(app: &App, root: &Path, cwd: &Path) -> Vec<Skill> {
/// Where a user's own skills live: `<data>/user-skills/<user id>/<name>/SKILL.md` (+ more files).
pub fn user_skills_dir(app: &App, owner_id: &str) -> PathBuf {
app.data_dir().join("user-skills").join(owner_id)
}
/// Relative paths of all files below `dir` (depth <= 5, at most 200), without `SKILL.md` at the top.
pub fn skill_files(dir: &Path) -> Vec<String> {
fn walk(base: &Path, dir: &Path, depth: usize, out: &mut Vec<String>) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let mut entries: Vec<_> = entries.flatten().collect();
entries.sort_by_key(|e| e.file_name());
for e in entries {
if out.len() >= 200 {
return;
}
let p = e.path();
let Ok(ty) = e.file_type() else { continue };
if ty.is_dir() && depth < 5 {
walk(base, &p, depth + 1, out);
} else if ty.is_file() {
if let Ok(rel) = p.strip_prefix(base) {
let rel = rel.to_string_lossy().to_string();
if rel != "SKILL.md" {
out.push(rel);
}
}
}
}
}
let mut out = Vec::new();
walk(dir, dir, 0, &mut out);
out
}
pub fn skills(app: &App, root: &Path, cwd: &Path, owner_id: Option<&str>) -> Vec<Skill> {
let mut map = BTreeMap::new();
for dir in resource_dirs(app, root, cwd, "skills") {
let mut dirs: Vec<(PathBuf, bool)> = resource_dirs(app, root, cwd, "skills").into_iter().map(|d| (d, false)).collect();
if let Some(id) = owner_id {
dirs.push((user_skills_dir(app, id), true));
}
for (dir, user) in dirs {
let Ok(entries) = std::fs::read_dir(&dir) else { continue };
for e in entries.flatten() {
let p = e.path().join("SKILL.md");
let Ok(text) = std::fs::read_to_string(&p) else { continue };
let (meta, _) = frontmatter(&text);
let name = meta.get("name").cloned().unwrap_or_else(|| e.file_name().to_string_lossy().into());
map.insert(name.clone(), Skill { name, description: meta.get("description").cloned().unwrap_or_default(), path: p });
map.insert(name.clone(), Skill { name, description: meta.get("description").cloned().unwrap_or_default(), files: skill_files(&e.path()), path: p, user });
}
}
map.into_values().collect()
}
/// Adds the skills the user switched on for this chat: their full instructions are part of every turn.
pub fn with_active_skills(app: &App, mut system: String, active: &[String], root: &Path, cwd: &Path, owner_id: Option<&str>) -> String {
if active.is_empty() {
return system;
}
let all = skills(app, root, cwd, owner_id);
let mut block = String::new();
for name in active {
let Some(sk) = all.iter().find(|s| &s.name == name) else { continue };
let Ok(text) = std::fs::read_to_string(&sk.path) else { continue };
let (_, body) = frontmatter(&text);
let body: String = body.chars().take(40_000).collect();
block.push_str(&format!("\n## Skill: {}\n{}\n", sk.name, body.trim()));
if !sk.files.is_empty() {
block.push_str(&format!("\nFurther files of this skill (read them with the skill tool: name=\"{}\", file=<path>): {}\n", sk.name, sk.files.join(", ")));
}
}
if !block.is_empty() {
system.push_str(&format!("\n\n# Active skills\nThe user switched these skills on for this chat. Follow them for every task they cover.\n{block}"));
}
system
}
/// More skills than this are not listed in the system prompt (the agent searches instead).
const SKILL_LIST_MAX: usize = 12;
pub struct SkillTool;
#[async_trait]
@@ -406,23 +479,60 @@ impl Tool for SkillTool {
"skill"
}
fn description(&self) -> String {
"Load a skill (packaged instructions for a kind of task) by name. Follow the returned instructions.".into()
"Load a skill (packaged instructions for a kind of task) by name and follow the returned instructions. `query` (keywords) lists matching skills instead; `file` reads one of the skill's further files.".into()
}
fn schema(&self) -> Value {
json!({"type": "object", "properties": {"name": {"type": "string"}}, "required": ["name"]})
json!({"type": "object", "properties": {
"name": {"type": "string"},
"file": {"type": "string", "description": "relative path of a further file of the skill"},
"query": {"type": "string", "description": "keywords: lists the matching skills instead of loading one"}
}})
}
fn read_only(&self) -> bool {
true
}
async fn run(&self, input: Value, ctx: &ToolCtx) -> Result<ToolOutput> {
let owner = ctx.app.store.get_session(&ctx.session_id).ok().flatten().and_then(|s| s.owner_id).or_else(|| ctx.owner_id.clone());
let all = skills(&ctx.app, &ctx.root(), &ctx.cwd, owner.as_deref());
if let Some(q) = input.get("query").and_then(|v| v.as_str()).filter(|q| !q.trim().is_empty()) {
let words: Vec<String> = q.to_lowercase().split_whitespace().map(str::to_string).collect();
let mut hits: Vec<(usize, &Skill)> = all
.iter()
.map(|s| {
let hay = format!("{} {}", s.name, s.description).to_lowercase();
(words.iter().filter(|w| hay.contains(w.as_str())).count(), s)
})
.filter(|(n, _)| *n > 0)
.collect();
hits.sort_by_key(|(n, s)| (std::cmp::Reverse(*n), s.name.clone()));
if hits.is_empty() {
return Ok(ToolOutput::text(format!("No skill matches '{q}' ({} skills available).", all.len())));
}
let lines: Vec<String> = hits.iter().take(15).map(|(_, s)| format!("- {}: {}", s.name, s.description.chars().take(200).collect::<String>())).collect();
return Ok(ToolOutput::text(format!("Matching skills (load one with name=<skill>):\n{}", lines.join("\n"))));
}
let name = arg_str(&input, "name")?;
let Some(sk) = skills(&ctx.app, &ctx.root(), &ctx.cwd).into_iter().find(|s| s.name == name) else {
let Some(sk) = all.into_iter().find(|s| s.name == name) else {
return Ok(ToolOutput::error(format!("unknown skill '{name}'")));
};
let dir = sk.path.parent().unwrap_or(Path::new("."));
if let Some(file) = input.get("file").and_then(|v| v.as_str()).filter(|f| !f.trim().is_empty()) {
let rel = Path::new(file.trim());
if rel.is_absolute() || rel.components().any(|c| !matches!(c, std::path::Component::Normal(_))) {
return Ok(ToolOutput::error("file must be a relative path inside the skill"));
}
let Ok(real) = std::fs::canonicalize(dir.join(rel)) else { return Ok(ToolOutput::error(format!("no file '{file}' in skill '{name}'"))) };
if !real.starts_with(std::fs::canonicalize(dir)?) || !real.is_file() {
return Ok(ToolOutput::error(format!("no file '{file}' in skill '{name}'")));
}
let mut text = std::fs::read_to_string(&real).unwrap_or_else(|_| "(binary file)".into());
text.truncate(text.char_indices().nth(100_000).map(|(i, _)| i).unwrap_or(text.len()));
return Ok(ToolOutput::text(text));
}
let text = std::fs::read_to_string(&sk.path)?;
let (_, body) = frontmatter(&text);
let dir = sk.path.parent().unwrap_or(Path::new("."));
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}", dir.display())))
let files = if sk.files.is_empty() { String::new() } else { format!("\n\nFurther files (read with name=\"{name}\" and file=<path>): {}", sk.files.join(", ")) };
Ok(ToolOutput::text(format!("Skill '{name}' (base directory: {}):\n\n{body}{files}", dir.display())))
}
}