//! Agent Skills (`agentskills.io` / `anthropics/skills`) package format, built-in skill packs, //! marketplace catalog, bundled resource reader, and GitHub / URL / local installer. //! //! Each skill package lives in `/skills//`: //! - `SKILL.md` — YAML frontmatter (`name`, `description`, optional `enabled`) + Markdown SOP //! (and an optional AnyBot ```` ```steps ```` fence for deterministic UI replay). //! - `scripts/` — executable helper scripts (`*.py`, `*.sh`, …) the bot can run or inspect. //! - `references/` / `assets/` / `examples/` — progressive-disclosure docs & templates loaded //! on demand via `use_skill(name, file)`. //! //! Legacy single-file `/skills/.md` files remain supported for backwards compatibility. use crate::memory::{ReplayStep, Skill}; use std::path::{Component, Path, PathBuf}; /// Max files and total bytes downloaded when installing a folder skill from GitHub or copying locally. const MAX_PACKAGE_FILES: usize = 48; const MAX_PACKAGE_BYTES: usize = 6 * 1024 * 1024; const MAX_RESOURCE_READ_BYTES: usize = 256 * 1024; /// A built-in skill compiled into AnyBot so new and upgraded installations work out of the box, /// offline, and can re-add deleted built-ins from 技能市集 at any time. pub struct BuiltinSkill { pub slug: &'static str, pub title: &'static str, pub summary: &'static str, pub default_on: bool, pub skill_md: &'static str, pub files: &'static [(&'static str, &'static str)], } /// Curated remote skills from `https://github.com/anthropics/skills` (Apache-2.0) for 1-click GitHub install. pub struct RemoteMarketSkill { pub name: &'static str, pub summary: &'static str, pub source: &'static str, } pub const BUILTIN_SKILLS: &[BuiltinSkill] = &[ BuiltinSkill { slug: "pdf", title: "PDF 處理與排版生成", summary: "讀取、合併拆分、檢查表單欄位與產出高品質繁中向量 PDF(附 pdf_tool.py)", default_on: true, skill_md: include_str!("../skills/pdf/SKILL.md"), files: &[("scripts/pdf_tool.py", include_str!("../skills/pdf/scripts/pdf_tool.py"))], }, BuiltinSkill { slug: "xlsx", title: "Excel 試算表與動態公式", summary: "製作財務/數據試算表、動態公式與欄寬排版,交付前自動掃描公式錯誤(附 audit_xlsx.py)", default_on: true, skill_md: include_str!("../skills/xlsx/SKILL.md"), files: &[("scripts/audit_xlsx.py", include_str!("../skills/xlsx/scripts/audit_xlsx.py"))], }, BuiltinSkill { slug: "docx", title: "Word 正式文件編排", summary: "企劃書、合約、會議紀錄與報告排版,自動設定繁中字型與結構檢查(附 audit_docx.py)", default_on: true, skill_md: include_str!("../skills/docx/SKILL.md"), files: &[("scripts/audit_docx.py", include_str!("../skills/docx/scripts/audit_docx.py"))], }, BuiltinSkill { slug: "pptx", title: "PowerPoint 簡報設計", summary: "16:9 商務與數據簡報設計規範,自動檢查元件超界與重疊(附 audit_pptx.py)", default_on: true, skill_md: include_str!("../skills/pptx/SKILL.md"), files: &[("scripts/audit_pptx.py", include_str!("../skills/pptx/scripts/audit_pptx.py"))], }, BuiltinSkill { slug: "web-design", title: "現代網頁與互動儀表板", summary: "高辨識度網頁、小工具與數據儀表板設計與發布(附 design-checklist.md)", default_on: true, skill_md: include_str!("../skills/web-design/SKILL.md"), files: &[("references/design-checklist.md", include_str!("../skills/web-design/references/design-checklist.md"))], }, BuiltinSkill { slug: "deep-research", title: "多來源深度研究與海巡", summary: "競品調查、Threads/論壇海巡、一手來源查證與結構化頁面產出", default_on: true, skill_md: include_str!("../skills/deep-research/SKILL.md"), files: &[], }, BuiltinSkill { slug: "browser-automation", title: "瀏覽器與桌面穩定自動化", summary: "後台報表擷取、複雜表單填寫、保險庫/真人接手協作與防卡關 SOP", default_on: true, skill_md: include_str!("../skills/browser-automation/SKILL.md"), files: &[], }, BuiltinSkill { slug: "skill-creator", title: "技能產生器(Skill Creator)", summary: "在對話中訪談需求、撰寫並封裝含隨附腳本的標準 SKILL.md 技能包", default_on: true, skill_md: include_str!("../skills/skill-creator/SKILL.md"), files: &[], }, BuiltinSkill { slug: "看報快摘", title: "看報快摘", summary: "把長篇文章或需登入的網頁讀成精準三句話摘要", default_on: false, skill_md: include_str!("../skills/看報快摘.md"), files: &[], }, BuiltinSkill { slug: "每日打卡", title: "每日打卡", summary: "在文件資料夾的每日記錄檔記下今天完成的最重要一件事", default_on: false, skill_md: include_str!("../skills/每日打卡.md"), files: &[], }, BuiltinSkill { slug: "螢幕報表存檔", title: "螢幕報表存檔", summary: "辨識畫面上的報表與日期並自動截圖歸檔命名", default_on: false, skill_md: include_str!("../skills/螢幕報表存檔.md"), files: &[], }, ]; pub const REMOTE_MARKET: &[RemoteMarketSkill] = &[ RemoteMarketSkill { name: "mcp-builder", summary: "Anthropic 官方:設計與實作高品質 MCP 連接器伺服器(Python FastMCP / TypeScript SDK)", source: "https://github.com/anthropics/skills/tree/main/skills/mcp-builder", }, RemoteMarketSkill { name: "webapp-testing", summary: "Anthropic 官方:使用 Playwright 自動化驗證與除錯本機網頁應用程式", source: "https://github.com/anthropics/skills/tree/main/skills/webapp-testing", }, RemoteMarketSkill { name: "doc-coauthoring", summary: "Anthropic 官方:結構化協作撰寫技術規格書、RFC、提案與決策文件", source: "https://github.com/anthropics/skills/tree/main/skills/doc-coauthoring", }, RemoteMarketSkill { name: "frontend-design", summary: "Anthropic 官方:前端視覺識別、字體排版與互動動態設計指南", source: "https://github.com/anthropics/skills/tree/main/skills/frontend-design", }, RemoteMarketSkill { name: "canvas-design", summary: "Anthropic 官方:海報、視覺構成與高品質平面版面設計指南", source: "https://github.com/anthropics/skills/tree/main/skills/canvas-design", }, ]; /// Safe folder slug for a skill name (`web-design`, `每日打卡`, `threads-發文`). pub fn slug_of(name: &str) -> String { let mut o: String = name .trim() .chars() .map(|c| if c.is_alphanumeric() || c == '_' { c.to_ascii_lowercase() } else { '-' }) .collect(); while o.contains("--") { o = o.replace("--", "-"); } let o: String = o.trim_matches(|c| c == '-' || c == '.').chars().take(48).collect(); if o.is_empty() { "skill".into() } else { o } } /// Validate a relative path inside a skill package (`scripts/tool.py`, `references/guide.md`). pub fn safe_rel_path(rel: &str) -> Option { let clean = rel.trim().replace('\\', "/"); let clean = clean.trim_start_matches("./"); if clean.is_empty() || clean.starts_with('/') || clean.contains(':') { return None; } let p = Path::new(clean); let mut out = PathBuf::new(); for c in p.components() { match c { Component::Normal(seg) => { let s = seg.to_str()?; let low = s.to_ascii_lowercase(); if s.is_empty() || s.starts_with('.') || low == "node_modules" || low == "__pycache__" || low.ends_with(".pem") || low.ends_with(".key") || low == "credentials" { return None; } out.push(s); } _ => return None, } } if out.as_os_str().is_empty() { None } else { Some(out) } } fn unquote_yaml(v: &str) -> String { let v = v.trim(); if v.len() >= 2 && v.starts_with('"') && v.ends_with('"') { let inner = &v[1..v.len() - 1]; let mut out = String::with_capacity(inner.len()); let mut chars = inner.chars(); while let Some(c) = chars.next() { if c == '\\' { match chars.next() { Some('n') => out.push('\n'), Some('t') => out.push('\t'), Some('r') => out.push('\r'), Some('"') => out.push('"'), Some('\\') => out.push('\\'), Some(other) => { out.push('\\'); out.push(other); } None => out.push('\\'), } } else { out.push(c); } } return out; } if v.len() >= 2 && v.starts_with('\'') && v.ends_with('\'') { return v[1..v.len() - 1].replace("''", "'"); } v.to_string() } /// Parse YAML frontmatter (`name`, `description`, `enabled`) supporting single-line values, quotes, /// and multiline block scalars (`>`, `>-`, `|`, `|-`), plus AnyBot's optional ```` ```steps ```` fence. pub fn parse_skill_markdown(text: &str) -> Option { let normalized = text.trim_start_matches('\u{feff}').replace("\r\n", "\n"); let t = normalized.trim_start(); let mut name = String::new(); let mut description = String::new(); let mut enabled = true; let (mut argument_hint, mut arguments, mut allowed_tools, mut fork) = (String::new(), vec![], vec![], false); let mut rest = t; if let Some(after_open) = t.strip_prefix("---\n") { let end_idx = if after_open.starts_with("---\n") { Some((0usize, 4usize)) } else if after_open.trim() == "---" { Some((0usize, after_open.len())) } else { after_open.find("\n---\n").map(|i| (i, 5usize)).or_else(|| { after_open.strip_suffix("\n---").map(|s| (s.len(), 4usize)) }) }; if let Some((end, delim_len)) = end_idx { let fm = &after_open[..end]; rest = after_open[end + delim_len..].trim_start_matches('\n'); let lines: Vec<&str> = fm.lines().collect(); let mut i = 0; while i < lines.len() { let line = lines[i]; let trimmed = line.trim(); // (A list's items, indented or not, belong to the key above them.) if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('-') || line.starts_with(' ') || line.starts_with('\t') { i += 1; continue; } let Some((raw_key, raw_val)) = line.split_once(':') else { i += 1; continue; }; let key = raw_key.trim(); let val = raw_val.trim(); // A block list under the key (`allowed-tools:` then ` - Read` lines). let list_items: Vec = if val.is_empty() { lines[i + 1..].iter().take_while(|l| l.starts_with(' ') || l.starts_with('\t') || l.starts_with('-') || l.trim().is_empty()).filter_map(|l| l.trim().strip_prefix('-')).map(|x| unquote_yaml(x.trim())).filter(|x| !x.is_empty()).collect() } else { vec![] }; let is_folded = matches!(val, ">" | ">-" | ">+"); let is_literal = matches!(val, "|" | "|-" | "|+"); let parsed_val = if is_folded || is_literal { i += 1; let mut block: Vec<&str> = vec![]; let mut base_indent: Option = None; while i < lines.len() { let bl = lines[i]; if bl.trim().is_empty() { block.push(""); i += 1; continue; } let indent = bl.len() - bl.trim_start_matches([' ', '\t']).len(); if indent == 0 { break; } let bi = *base_indent.get_or_insert(indent); let cut = indent.min(bi); block.push(&bl[cut..]); i += 1; } if is_literal { block.join("\n").trim().to_string() } else { let mut out = String::new(); for part in block { if part.is_empty() { if !out.ends_with('\n') && !out.is_empty() { out.push('\n'); } } else { if !out.is_empty() && !out.ends_with('\n') { out.push(' '); } out.push_str(part.trim()); } } out.trim().to_string() } } else { // Continuation lines for plain multiline scalars (`description:\n foo bar`) i += 1; if val.is_empty() { let mut cont: Vec<&str> = vec![]; while i < lines.len() { let bl = lines[i]; if bl.starts_with(' ') || bl.starts_with('\t') { if !bl.trim().is_empty() && !bl.trim().starts_with('-') { cont.push(bl.trim()); } i += 1; } else { break; } } cont.join(" ") } else { unquote_yaml(val) } }; match key { "name" => name = parsed_val.trim().to_string(), "description" => description = parsed_val.trim().to_string(), "enabled" => enabled = !matches!(parsed_val.trim().to_ascii_lowercase().as_str(), "false" | "0" | "no" | "off"), "argument-hint" | "argument_hint" => argument_hint = parsed_val.trim().to_string(), "arguments" => arguments = yaml_list(&parsed_val, &list_items), "allowed-tools" | "allowed_tools" => allowed_tools = yaml_list(&parsed_val, &list_items), "context" => fork = parsed_val.trim().eq_ignore_ascii_case("fork"), _ => {} } } } } let mut steps: Vec = vec![]; let mut instructions = rest.trim().to_string(); if let Some(start) = rest.find("```steps") { let after_tag = start + "```steps".len(); if let Some(end) = rest[after_tag..].find("```") { let json = &rest[after_tag..after_tag + end]; steps = serde_json::from_str(json.trim()).unwrap_or_default(); instructions = format!("{}\n{}", &rest[..start], &rest[after_tag + end + 3..]).trim().to_string(); } } if name.is_empty() { return None; } Some(Skill { name, description, instructions, steps, enabled, argument_hint, arguments, allowed_tools, fork, ..Default::default() }) } /// A YAML list as it may be written: a block list (`items`), a flow list `[a, b]`, or one line /// `Read, Grep, Bash(git add:*)` (commas, or else spaces, outside parentheses). fn yaml_list(val: &str, items: &[String]) -> Vec { if !items.is_empty() { return items.to_vec(); } let v = val.trim(); let v = v.strip_prefix('[').and_then(|x| x.strip_suffix(']')).unwrap_or(v); let split_on = if v.contains(',') { ',' } else { ' ' }; let (mut out, mut cur, mut depth) = (vec![], String::new(), 0i32); for c in v.chars() { match c { '(' => depth += 1, ')' => depth -= 1, _ => {} } if c == split_on && depth <= 0 { out.push(std::mem::take(&mut cur)); } else { cur.push(c); } } out.push(cur); out.into_iter().map(|x| unquote_yaml(x.trim())).filter(|x| !x.is_empty()).collect() } /// Whether a skill takes arguments: it names them, hints at them, or its instructions use them. pub fn takes_arguments(k: &Skill) -> bool { // (Not a bare `$1`: a skill's own code has those — awk '{print $1}', a shell script.) !k.arguments.is_empty() || !k.argument_hint.is_empty() || k.instructions.contains("$ARGUMENTS") } /// What was typed after 「/名稱」 at the start of a message ("" when nothing). pub fn arguments_after(text: &str, name: &str) -> String { text.trim_start().strip_prefix('/').and_then(|r| r.strip_prefix(name)).map(|r| r.trim().to_string()).unwrap_or_default() } /// Arguments the way a shell splits them: spaces apart, "quoted words" together. fn split_arguments(args: &str) -> Vec { let (mut out, mut cur, mut quote, mut any) = (vec![], String::new(), None::, false); for c in args.chars() { match (quote, c) { (Some(q), c) if c == q => quote = None, (Some(_), c) => cur.push(c), // (Not ': 「don't stop」 has one.) (None, '"' | '「') => { quote = Some(if c == '「' { '」' } else { c }); any = true; } (None, c) if c.is_whitespace() => { if any || !cur.is_empty() { out.push(std::mem::take(&mut cur)); } any = false; } (None, c) => cur.push(c), } } if any || !cur.is_empty() { out.push(cur); } out } /// The skill's instructions with this time's arguments in them (Claude Code's way): $ARGUMENTS all /// of them, $ARGUMENTS[N] and $N the N-th (from 0), $name a named one; when it says none of those, /// they go at the end as 「ARGUMENTS: …」. pub fn with_arguments(k: &Skill, args: &str) -> String { let args = args.trim(); if args.is_empty() { return k.instructions.clone(); } let parts = split_arguments(args); let nth = |i: usize| parts.get(i).cloned().unwrap_or_default(); let mut out = String::new(); let mut used = false; let text = &k.instructions; let mut rest = text.as_str(); while let Some(at) = rest.find('$') { out.push_str(&rest[..at]); let after = &rest[at + 1..]; let digits: String = after.chars().take_while(char::is_ascii_digit).collect(); if let Some(r) = after.strip_prefix("ARGUMENTS[") { let n: String = r.chars().take_while(char::is_ascii_digit).collect(); if let (Ok(i), Some(r2)) = (n.parse::(), r[n.len()..].strip_prefix(']')) { out.push_str(&nth(i)); used = true; rest = r2; continue; } } if let Some(r) = after.strip_prefix("ARGUMENTS") { out.push_str(args); used = true; rest = r; continue; } if !digits.is_empty() && takes_arguments(k) { out.push_str(&nth(digits.parse().unwrap_or(usize::MAX))); used = true; rest = &after[digits.len()..]; continue; } let word: String = after.chars().take_while(|c| c.is_alphanumeric() || *c == '_').collect(); if let Some(i) = k.arguments.iter().position(|a| !word.is_empty() && *a == word) { out.push_str(&nth(i)); used = true; rest = &after[word.len()..]; continue; } out.push('$'); rest = after; } out.push_str(rest); if !used { out.push_str(&format!("\n\nARGUMENTS: {args}")); } out } /// Claude Code's tool names, as AnyBot's (a skill written for it limits the same tools here). fn anybot_tool(name: &str) -> &str { match name { "Read" => "read_file", "Write" | "Edit" | "MultiEdit" | "NotebookEdit" => "edit_file", "Bash" => "shell", "Grep" | "Glob" => "search", "LS" => "list_dir", "WebFetch" => "web_fetch", "WebSearch" => "web_search", other => other, } } /// A skill's allowed-tools as rules gate::patterns reads: a name → `tool(name)`, `Bash(git add:*)` /// → `shell(git add *)`, AnyBot's own `shell(git *)` / `file(…)` / `connector(…)` as they are. pub fn tool_rules(k: &Skill) -> Vec { k.allowed_tools .iter() .map(|t| { let t = t.trim(); match t.split_once('(') { Some((kind, inner)) => { let inner = inner.strip_suffix(')').unwrap_or(inner).replace(":*", " *"); match kind.trim() { "Bash" | "shell" => format!("shell({inner})"), // (Read(…) is for reading there, not for changing it; WebFetch(…) for // reading that site, not for the logged-in browser: skill_allows.) "Read" => format!("read:file({inner})"), "Write" | "Edit" | "file" => format!("file({inner})"), "WebFetch" => format!("fetch:web({inner})"), "web" => format!("web({inner})"), other => format!("{other}({inner})"), } } // (The browser and the screen are one tool each to the model, many underneath.) None if t == "browser" => "tool(browser_*)".to_string(), None if t == "computer" => "tool(computer_use_*)".to_string(), None => format!("tool({})", anybot_tool(t)), } }) .collect() } /// Tools a skill's limit never takes away: reading skills and kept results, asking the person. const ALWAYS_ALLOWED: [&str; 5] = ["use_skill", "read_result", "ask_person", "submit_plan", "update_plan"]; /// Whether a tool call is within a loaded skill's allowed-tools (`rules` from tool_rules). pub fn skill_allows(rules: &[String], name: &str, args: &str) -> bool { if ALWAYS_ALLOWED.contains(&name) { return true; } rules.iter().any(|r| { let (rule, fits) = match r.split_once(':').filter(|(k, _)| matches!(*k, "read" | "fetch")) { Some(("read", rest)) => (rest, matches!(name, "read_file" | "list_dir" | "search")), Some((_, rest)) => (rest, name == "web_fetch"), None => (r.as_str(), true), }; fits && matches!(crate::gate::patterns(name, args, &[rule.to_string()], &[]), crate::gate::PatternVerdict::Allow(_)) }) } fn quote_yaml_if_needed(s: &str) -> String { let clean = s.replace('\r', ""); if clean.contains('\n') { let indented: String = clean.lines().map(|l| format!(" {l}")).collect::>().join("\n"); format!("|-\n{indented}") } else if clean.contains(':') || clean.contains('#') || clean.starts_with(['"', '\'', '[', '{', '>', '|', '-', '*', '&', '!']) { format!("\"{}\"", clean.replace('\\', "\\\\").replace('"', "\\\"")) } else { clean } } pub fn render_skill_markdown(s: &Skill) -> String { let mut o = format!("---\nname: {}\ndescription: {}\n", quote_yaml_if_needed(&s.name), quote_yaml_if_needed(&s.description)); if !s.enabled { o.push_str("enabled: false\n"); } if !s.argument_hint.is_empty() { o.push_str(&format!("argument-hint: {}\n", quote_yaml_if_needed(&s.argument_hint))); } for (key, list) in [("arguments", &s.arguments), ("allowed-tools", &s.allowed_tools)] { if !list.is_empty() { o.push_str(&format!("{key}:\n{}", list.iter().map(|x| format!(" - {}\n", quote_yaml_if_needed(x))).collect::())); } } if s.fork { o.push_str("context: fork\n"); } o.push_str(&format!("---\n\n{}\n", s.instructions.trim())); if !s.steps.is_empty() { if let Ok(j) = serde_json::to_string(&s.steps) { o.push_str(&format!("\n```steps\n{j}\n```\n")); } } o } /// Discover bundled relative resource paths inside a skill folder (excluding `SKILL.md` and dotfiles). pub fn discover_resources(dir: &Path) -> Vec { let Ok(canon_root) = std::fs::canonicalize(dir) else { return vec![] }; let mut out = vec![]; let mut stack = vec![dir.to_path_buf()]; while let Some(cur) = stack.pop() { let Ok(rd) = std::fs::read_dir(&cur) else { continue }; for entry in rd.flatten() { let p = entry.path(); let Some(fname) = p.file_name().and_then(|n| n.to_str()) else { continue }; if fname.starts_with('.') || fname.eq_ignore_ascii_case("SKILL.md") || fname == "node_modules" || fname == "__pycache__" { continue; } let Ok(meta) = std::fs::symlink_metadata(&p) else { continue }; if meta.file_type().is_symlink() { continue; } let Ok(real) = std::fs::canonicalize(&p) else { continue }; if !real.starts_with(&canon_root) { continue; } if meta.is_dir() { stack.push(p); } else if meta.is_file() { if let Ok(rel) = p.strip_prefix(dir) { let rel_str = rel.to_string_lossy().replace('\\', "/"); if safe_rel_path(&rel_str).is_some() { out.push(rel_str); } } } if out.len() >= MAX_PACKAGE_FILES { break; } } } out.sort(); out } /// Load a folder skill (`/SKILL.md` or `/skill.md`). pub fn load_folder_skill(dir: &Path) -> Option { let md_path = [dir.join("SKILL.md"), dir.join("skill.md")].into_iter().find(|p| p.is_file())?; let text = std::fs::read_to_string(&md_path).ok()?; let mut s = parse_skill_markdown(&text)?; s.dir = dir.display().to_string(); s.resources = discover_resources(dir); Some(s) } /// Load all skills (both folder packages `//SKILL.md` and legacy `/.md`) from `root`. /// Folder packages take precedence over legacy flat files of the same `name`. pub fn load_skills_in_dir(root: &Path) -> Vec<(PathBuf, Skill)> { let Ok(rd) = std::fs::read_dir(root) else { return vec![] }; let mut flat = vec![]; let mut folders = vec![]; for entry in rd.flatten() { let p = entry.path(); if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with('.')) { continue; } if p.is_dir() { if let Some(s) = load_folder_skill(&p) { folders.push((p, s)); } } else if p.extension().and_then(|e| e.to_str()) == Some("md") { if let Some(s) = std::fs::read_to_string(&p).ok().and_then(|t| parse_skill_markdown(&t)) { flat.push((p, s)); } } } flat.sort_by(|a, b| a.1.name.cmp(&b.1.name)); folders.sort_by(|a, b| a.1.name.cmp(&b.1.name)); let mut out = flat; for (p, f) in folders { if let Some(existing) = out.iter_mut().find(|(_, x)| x.name == f.name) { *existing = (p, f); } else { out.push((p, f)); } } out } /// Write a skill package (`SKILL.md` + optional bundled files) into `//`. pub fn write_skill_package(skill: &Skill, extra_files: &[(String, Vec)]) -> Result { let root = crate::memory::skill_dir(); let base_slug = slug_of(&skill.name); let mut slug = if base_slug == "skill" && !skill.name.trim().eq_ignore_ascii_case("skill") { format!("skill-{}", &crate::httpd::sha256_hex(skill.name.trim())[..8]) } else if !skill.source.starts_with("builtin:") && BUILTIN_SKILLS.iter().any(|b| b.slug == base_slug && !b.title.eq_ignore_ascii_case(skill.name.trim()) && b.slug != skill.name.trim()) { // Prevent a crafted name like `"pdf!"` from colliding onto built-in `skills/pdf/` and replacing `scripts/pdf_tool.py`. format!("{base_slug}-{}", &crate::httpd::sha256_hex(skill.name.trim())[..6]) } else { base_slug }; let candidate = root.join(&slug); if let Ok(existing_md) = std::fs::read_to_string(candidate.join("SKILL.md")) { if let Some(existing) = parse_skill_markdown(&existing_md) { if !existing.name.trim().eq_ignore_ascii_case(skill.name.trim()) { slug = format!("{slug}-{}", &crate::httpd::sha256_hex(skill.name.trim())[..6]); } } } let pkg_dir = root.join(&slug); std::fs::create_dir_all(&pkg_dir).map_err(|e| format!("建立技能資料夾失敗:{e}"))?; let md = render_skill_markdown(skill); std::fs::write(pkg_dir.join("SKILL.md"), md.as_bytes()).map_err(|e| format!("寫入 SKILL.md 失敗:{e}"))?; for (rel, bytes) in extra_files { let Some(clean) = safe_rel_path(rel) else { return Err(format!("不允許的隨附檔案路徑:{rel}")); }; if clean == Path::new("SKILL.md") || clean == Path::new("skill.md") { continue; } let dst = pkg_dir.join(&clean); if let Some(parent) = dst.parent() { std::fs::create_dir_all(parent).map_err(|e| e.to_string())?; } std::fs::write(&dst, bytes).map_err(|e| format!("寫入 {rel} 失敗:{e}"))?; #[cfg(unix)] if clean.starts_with("scripts") { use std::os::unix::fs::PermissionsExt; let _ = std::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o755)); } } // Remove legacy flat file `.md` if we upgraded it into a package folder. let legacy = root.join(format!("{slug}.md")); if legacy.is_file() { let _ = std::fs::remove_file(legacy); } Ok(pkg_dir) } /// Materialize one built-in skill onto disk and return the parsed `Skill`. pub fn materialize_builtin(b: &BuiltinSkill) -> Result { let mut s = parse_skill_markdown(b.skill_md).ok_or_else(|| format!("內建技能 {} 格式錯誤", b.slug))?; s.source = format!("builtin:{}", b.slug); let files: Vec<(String, Vec)> = b.files.iter().map(|(p, c)| ((*p).to_string(), c.as_bytes().to_vec())).collect(); let dir = write_skill_package(&s, &files)?; s.dir = dir.display().to_string(); s.resources = discover_resources(&dir); Ok(s) } /// Seed the default built-in core skills once (on first run or first upgrade from empty skills). pub fn seed_defaults(skills: &mut Vec) { for b in BUILTIN_SKILLS.iter().filter(|b| b.default_on) { if let Ok(s) = materialize_builtin(b) { if !skills.iter().any(|k| k.name == s.name) { skills.push(s); } } else if let Some(mut s) = parse_skill_markdown(b.skill_md) { s.source = format!("builtin:{}", b.slug); s.resources = b.files.iter().map(|(p, _)| (*p).to_string()).collect(); if !skills.iter().any(|k| k.name == s.name) { skills.push(s); } } } } /// Install one built-in skill by slug or name into `/skills/` and `skills`. pub fn install_builtin(slug_or_name: &str, skills: &mut Vec) -> Result { let want = slug_or_name.trim(); let b = BUILTIN_SKILLS .iter() .find(|b| b.slug.eq_ignore_ascii_case(want) || b.title == want || parse_skill_markdown(b.skill_md).is_some_and(|s| s.name.eq_ignore_ascii_case(want))) .ok_or_else(|| format!("內建技能市集裡沒有「{want}」"))?; let s = materialize_builtin(b)?; let name = s.name.clone(); crate::memory::upsert_skill(skills, s); Ok(name) } /// Resolve the local folder of a skill, if it exists on disk. pub fn resolve_skill_dir(k: &Skill) -> Option { if !k.dir.is_empty() { let p = PathBuf::from(&k.dir); if p.is_dir() { return Some(p); } } let candidate = crate::memory::skill_dir().join(slug_of(&k.name)); candidate.is_dir().then_some(candidate) } /// Read a bundled resource file (`scripts/...`, `references/...`, `assets/...`) belonging to `k`. pub fn read_resource(k: &Skill, rel: &str) -> Result { let clean = safe_rel_path(rel).ok_or_else(|| format!("不合法的技能資源路徑:「{rel}」"))?; let clean_str = clean.to_string_lossy().replace('\\', "/"); if let Some(dir) = resolve_skill_dir(k) { let canon_root = std::fs::canonicalize(&dir).map_err(|e| e.to_string())?; let target = dir.join(&clean); let canon_target = std::fs::canonicalize(&target).map_err(|_| format!("技能「{}」裡找不到檔案「{clean_str}」", k.name))?; if !canon_target.starts_with(&canon_root) || !canon_target.is_file() { return Err("不允許讀取技能資料夾以外的檔案".into()); } let bytes = std::fs::read(&canon_target).map_err(|e| e.to_string())?; if bytes.len() > MAX_RESOURCE_READ_BYTES { return Err(format!("檔案太大({} bytes),請直接在終端機讀取或執行:{}", bytes.len(), canon_target.display())); } return match String::from_utf8(bytes) { Ok(text) => Ok(text), Err(_) => Ok(format!("(這是二進位資源檔,本機路徑為:{})", canon_target.display())), }; } // Fallback to embedded built-in files (e.g. when running without a writable disk directory). if let Some(b) = BUILTIN_SKILLS.iter().find(|b| b.slug == k.name) { if let Some((_, content)) = b.files.iter().find(|(p, _)| *p == clean_str) { return Ok((*content).to_string()); } } Err(format!("技能「{}」裡沒有「{clean_str}」這個隨附檔案", k.name)) } /// Format what `use_skill` returns to the model: full `SKILL.md` instructions + progressive-disclosure resource index. pub fn format_skill_for_model(k: &Skill, file: Option<&str>, arguments: Option<&str>) -> Result { if let Some(f) = file.map(str::trim).filter(|f| !f.is_empty()) { let content = read_resource(k, f)?; return Ok(format!("技能「{}」隨附檔案 `{f}`:\n\n{content}", k.name)); } let mut out = format!("技能「{}」的做法:\n{}", k.name, with_arguments(k, arguments.unwrap_or(""))); if !k.allowed_tools.is_empty() { out.push_str(&format!("\n\n(這個技能只准用這些工具:{}。這一輪接下來 AnyBot 只讓你用這些(還有 use_skill、read_result、ask_person);要用別的,先告訴使用者。)", k.allowed_tools.join("、"))); } let resources = if !k.resources.is_empty() { k.resources.clone() } else if let Some(dir) = resolve_skill_dir(k) { discover_resources(&dir) } else { vec![] }; if !resources.is_empty() { out.push_str("\n\n---\n隨附資源(需要時用 `use_skill` 帶 `\"file\": \"相對路徑\"` 讀取內容"); if let Some(dir) = resolve_skill_dir(k) { out.push_str(&format!(";在這台電腦上也可直接讀取或執行 `{}` 下的檔案", dir.display())); } out.push_str("):\n"); for r in &resources { out.push_str(&format!("- {r}\n")); } } Ok(out) } // ---------- GitHub / URL / Local Package Installer ---------- #[derive(Debug, PartialEq, Eq)] pub struct GitHubSpec { pub owner: String, pub repo: String, pub git_ref: Option, pub path: String, } /// Recognize GitHub skill URLs or shorthand: /// - `https://github.com/anthropics/skills/tree/main/skills/pdf` /// - `https://github.com/anthropics/skills/blob/main/skills/pdf/SKILL.md` /// - `https://github.com/owner/repo` /// - `github:anthropics/skills/skills/pdf` /// - `anthropics/skills/skills/pdf` pub fn parse_github_source(src: &str) -> Option { let s = src.trim().trim_end_matches('/'); if let Some(rest) = s.strip_prefix("https://github.com/").or_else(|| s.strip_prefix("http://github.com/")) { let parts: Vec<&str> = rest.split('/').filter(|p| !p.is_empty()).collect(); if parts.len() < 2 { return None; } let (owner, repo) = (parts[0].to_string(), parts[1].trim_end_matches(".git").to_string()); if parts.len() == 2 { return Some(GitHubSpec { owner, repo, git_ref: None, path: String::new() }); } match parts[2] { "tree" if parts.len() >= 4 => { let git_ref = Some(parts[3].to_string()); let path = parts[4..].join("/"); return Some(GitHubSpec { owner, repo, git_ref, path }); } "blob" if parts.len() >= 5 => { let git_ref = Some(parts[3].to_string()); let last = *parts.last().unwrap_or(&""); let dir_parts = if last.eq_ignore_ascii_case("SKILL.md") { &parts[4..parts.len() - 1] } else { &parts[4..] }; // Only treat blob URLs as folder packages when pointing at SKILL.md; other single .md files fetch raw. if last.eq_ignore_ascii_case("SKILL.md") { return Some(GitHubSpec { owner, repo, git_ref, path: dir_parts.join("/") }); } return None; } _ => return None, } } let shorthand = s.strip_prefix("github:").unwrap_or(s); if shorthand.contains("://") || shorthand.starts_with(['/', '.', '~']) || shorthand.ends_with(".md") { return None; } let parts: Vec<&str> = shorthand.split('/').filter(|p| !p.is_empty()).collect(); if parts.len() >= 2 && parts.iter().all(|p| p.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))) { return Some(GitHubSpec { owner: parts[0].to_string(), repo: parts[1].to_string(), git_ref: None, path: parts[2..].join("/"), }); } None } fn install_from_github(spec: &GitHubSpec) -> Result { let mut files: Vec<(String, Vec)> = vec![]; let mut total_bytes = 0usize; let base_prefix = spec.path.trim_matches('/'); fn walk_gh( owner: &str, repo: &str, git_ref: Option<&str>, dir_path: &str, base_prefix: &str, files: &mut Vec<(String, Vec)>, total_bytes: &mut usize, ) -> Result<(), String> { if files.len() >= MAX_PACKAGE_FILES { return Ok(()); } let encoded_path = dir_path .split('/') .filter(|s| !s.is_empty()) .map(crate::httpd::url_encode) .collect::>() .join("/"); let mut api_url = if encoded_path.is_empty() { format!("https://api.github.com/repos/{}/{}/contents", crate::httpd::url_encode(owner), crate::httpd::url_encode(repo)) } else { format!("https://api.github.com/repos/{}/{}/contents/{encoded_path}", crate::httpd::url_encode(owner), crate::httpd::url_encode(repo)) }; if let Some(r) = git_ref.filter(|r| !r.is_empty()) { api_url.push_str(&format!("?ref={}", crate::httpd::url_encode(r))); } let (_, status, _, raw) = crate::web::get_public_bytes(&api_url, 2 * 1024 * 1024)?; if status == 404 { return Err(format!("GitHub 上找不到路徑:{owner}/{repo}/{}", dir_path)); } if status == 403 || status == 429 { return Err("GitHub API 暫時達到速率限制,請稍後再試或改貼 raw SKILL.md 網址".into()); } if status >= 400 { return Err(format!("GitHub 回應錯誤(HTTP {status})")); } let val: serde_json::Value = serde_json::from_slice(&raw).map_err(|_| "解析 GitHub 回應失敗".to_string())?; let entries = match val { serde_json::Value::Array(a) => a, obj @ serde_json::Value::Object(_) => vec![obj], _ => return Err("GitHub 回應格式不正確".into()), }; for item in entries { if files.len() >= MAX_PACKAGE_FILES { break; } let kind = item["type"].as_str().unwrap_or(""); let item_path = item["path"].as_str().unwrap_or(""); let name = item["name"].as_str().unwrap_or(""); if name.starts_with('.') { continue; } let rel = if base_prefix.is_empty() { item_path.to_string() } else { item_path.strip_prefix(base_prefix).unwrap_or(item_path).trim_start_matches('/').to_string() }; if kind == "dir" { walk_gh(owner, repo, git_ref, item_path, base_prefix, files, total_bytes)?; } else if kind == "file" { let size = item["size"].as_u64().unwrap_or(0) as usize; if *total_bytes + size > MAX_PACKAGE_BYTES { return Err("技能套件超過大小上限(6 MB)".into()); } let dl = item["download_url"].as_str().ok_or_else(|| format!("無法取得 {rel} 的下載網址"))?; let (_, st, _, bytes) = crate::web::get_public_bytes(dl, MAX_PACKAGE_BYTES as u64)?; if st >= 400 { return Err(format!("下載 {rel} 失敗(HTTP {st})")); } *total_bytes += bytes.len(); files.push((rel, bytes)); } } Ok(()) } walk_gh(&spec.owner, &spec.repo, spec.git_ref.as_deref(), base_prefix, base_prefix, &mut files, &mut total_bytes)?; let md_idx = files .iter() .position(|(p, _)| p.eq_ignore_ascii_case("SKILL.md")) .ok_or_else(|| format!("{}/{}/{} 裡面沒有 SKILL.md", spec.owner, spec.repo, base_prefix))?; let md_text = String::from_utf8_lossy(&files[md_idx].1).to_string(); let mut skill = parse_skill_markdown(&md_text).ok_or("SKILL.md 缺少有效的 name: 欄位")?; skill.source = if base_prefix.is_empty() { format!("{}/{}", spec.owner, spec.repo) } else { format!("{}/{}/{base_prefix}", spec.owner, spec.repo) }; let extra: Vec<(String, Vec)> = files .into_iter() .enumerate() .filter(|(i, _)| *i != md_idx) .filter(|(_, (p, _))| safe_rel_path(p).is_some()) .map(|(_, pair)| pair) .collect(); let extra_n = extra.len(); let dir = write_skill_package(&skill, &extra)?; let _ = dir; Ok(if extra_n > 0 { format!("{}(含 {} 個隨附檔案)", skill.name, extra_n) } else { skill.name }) } fn install_from_local_dir(dir: &Path) -> Result { let (md_text, extra) = read_package(dir)?; let mut skill = parse_skill_markdown(&md_text).ok_or("SKILL.md 開頭需要有 name: 欄位")?; skill.source = dir.display().to_string(); let extra_n = extra.len(); write_skill_package(&skill, &extra)?; Ok(if extra_n > 0 { format!("{}(含 {} 個隨附檔案)", skill.name, extra_n) } else { skill.name }) } /// A skill as files: its `SKILL.md`, and each bundled file's relative path and bytes. type Package = (String, Vec<(String, Vec)>); /// A skill folder on this disk: its `SKILL.md` and the files that come with it (within the /// package limits). fn read_package(dir: &Path) -> Result { let md_path = [dir.join("SKILL.md"), dir.join("skill.md")] .into_iter() .find(|p| p.is_file()) .ok_or_else(|| format!("資料夾「{}」裡找不到 SKILL.md", dir.display()))?; let md_text = std::fs::read_to_string(&md_path).map_err(|e| format!("讀不到 SKILL.md:{e}"))?; let mut extra = vec![]; let mut total = 0usize; for r in discover_resources(dir) { let bytes = std::fs::read(dir.join(&r)).map_err(|e| e.to_string())?; total += bytes.len(); if total > MAX_PACKAGE_BYTES { return Err("技能資料夾超過大小上限(6 MB)".into()); } extra.push((r, bytes)); } Ok((md_text, extra)) } // ---------- A skill handed from a screen to its brain ---------- // // The bots run on the brain and read skills from the brain's own disk, so a skill a screen has // (a folder picked on that computer, or its own skills moved over) goes up whole: `SKILL.md` and // every file with it, as one JSON value. fn package_json(skill_md: String, files: Vec<(String, Vec)>, source: &str, enabled: bool) -> serde_json::Value { use base64::Engine; let files: Vec = files.into_iter().map(|(path, bytes)| serde_json::json!({"path": path, "b64": base64::engine::general_purpose::STANDARD.encode(bytes)})).collect(); serde_json::json!({"skill_md": skill_md, "files": files, "source": source, "enabled": enabled}) } /// A folder with a `SKILL.md`, or one `.md` file, on this computer — as a package. pub fn package_from_path(p: &Path) -> Result { if p.is_dir() { let (md, files) = read_package(p)?; return Ok(package_json(md, files, &p.display().to_string(), true)); } let md = std::fs::read_to_string(p).map_err(|e| format!("讀不到檔案:{e}"))?; Ok(package_json(md, vec![], &p.display().to_string(), true)) } /// One of this computer's skills as a package: its folder when it has one (the files win, as at /// start), or else the list's own entry written out as a `SKILL.md`. pub fn package_of(k: &Skill) -> Result { let (md, files) = match resolve_skill_dir(k) { Some(dir) => read_package(&dir)?, None => (render_skill_markdown(k), vec![]), }; Ok(package_json(md, files, &k.source, k.enabled)) } /// The brain's side: write the package into `/skills//` and give back the skill as /// the list keeps it. pub fn install_package(v: &serde_json::Value) -> Result { use base64::Engine; let md = v["skill_md"].as_str().ok_or("技能內容是空的")?; let mut skill = parse_skill_markdown(md).ok_or("SKILL.md 開頭需要有 name: 欄位")?; let list = v["files"].as_array().map(Vec::as_slice).unwrap_or_default(); if list.len() > MAX_PACKAGE_FILES { return Err(format!("技能的隨附檔案太多(最多 {MAX_PACKAGE_FILES} 個)")); } let mut files = vec![]; let mut total = 0usize; for f in list { let path = f["path"].as_str().unwrap_or("").to_string(); // Every path checked before anything is written: a refused package leaves no folder // behind (one would put the skill on the list at the next start). if safe_rel_path(&path).is_none() { return Err(format!("不允許的隨附檔案路徑:{path}")); } let bytes = base64::engine::general_purpose::STANDARD.decode(f["b64"].as_str().unwrap_or("")).map_err(|_| format!("隨附檔案「{path}」壞了"))?; total += bytes.len(); if total > MAX_PACKAGE_BYTES { return Err("技能資料夾超過大小上限(6 MB)".into()); } files.push((path, bytes)); } skill.enabled = v["enabled"].as_bool().unwrap_or(skill.enabled); skill.source = v["source"].as_str().unwrap_or("").to_string(); let dir = write_skill_package(&skill, &files)?; skill.dir = dir.display().to_string(); skill.resources = discover_resources(&dir); Ok(skill) } /// Universal installer: accepts `builtin:`, a local skill folder, a local `.md` file, /// a GitHub tree/blob URL or `owner/repo/path` shorthand, or any `http(s)://` `.md` URL. pub fn install_from_source(src: &str) -> Result { let src = src.trim(); if src.is_empty() { return Err("請輸入技能的 GitHub 網址、SKILL.md 網址或本機路徑".into()); } if let Some(slug) = src.strip_prefix("builtin:") { let b = BUILTIN_SKILLS .iter() .find(|b| b.slug.eq_ignore_ascii_case(slug.trim())) .ok_or_else(|| format!("找不到內建技能「{slug}」"))?; let s = materialize_builtin(b)?; return Ok(s.name); } // Check local filesystem first when not a URL. if !src.starts_with("http://") && !src.starts_with("https://") && !src.starts_with("github:") { let expanded = crate::tools::expand_home(src); if expanded.is_dir() { return install_from_local_dir(&expanded); } if expanded.is_file() { let text = std::fs::read_to_string(&expanded).map_err(|e| format!("讀不到檔案:{e}"))?; return crate::memory::install_skill_text(&text); } } if let Some(gh) = parse_github_source(src) { return install_from_github(&gh); } if src.starts_with("http://") || src.starts_with("https://") { // Rewrite github.com/.../blob//.md -> raw.githubusercontent.com so single .md links work too. let fetch_url = if let Some(rest) = src.strip_prefix("https://github.com/") { let parts: Vec<&str> = rest.split('/').collect(); if parts.len() >= 5 && parts[2] == "blob" { format!("https://raw.githubusercontent.com/{}/{}/{}/{}", parts[0], parts[1], parts[3], parts[4..].join("/")) } else { src.to_string() } } else { src.to_string() }; let (_, status, text) = crate::web::get_public(&fetch_url, 600_000)?; if status >= 400 { return Err(format!("抓不到技能檔:網站回應 HTTP {status}")); } return crate::memory::install_skill_text(&text); } Err(format!("找不到路徑或無法識別的技能來源:「{src}」")) } #[cfg(test)] mod package_tests { use super::*; /// A skill with no folder (learned in a chat) goes up as its list entry written out: the /// steps a replay follows and its off switch come through. #[test] fn a_skill_without_a_folder_goes_up_as_written() { let name = format!("學會的做法-{}", std::process::id()); let k = Skill { name: name.clone(), description: "訂 pizza".into(), instructions: "打開網站,選大的".into(), steps: vec![crate::memory::ReplayStep { tool: "shell".into(), args: "{\"cmd\":\"date\"}".into(), targets: vec![] }], enabled: false, source: "learned".into(), ..Default::default() }; assert!(resolve_skill_dir(&k).is_none()); let back = install_package(&package_of(&k).unwrap()).unwrap(); assert_eq!((back.name.as_str(), back.instructions.as_str(), back.enabled, back.source.as_str()), (name.as_str(), "打開網站,選大的", false, "learned")); assert_eq!(back.steps, k.steps); let _ = std::fs::remove_dir_all(&back.dir); // Nothing outside its folder, and nothing too big. let refused = format!("不收的-{}", std::process::id()); let bad = serde_json::json!({"skill_md": format!("---\nname: {refused}\ndescription: y\n---\n\nz"), "files": [{"path": "../evil.sh", "b64": ""}]}); assert!(install_package(&bad).is_err()); assert!(!crate::memory::skill_dir().join(slug_of(&refused)).exists(), "a refused package leaves no folder"); } } #[cfg(test)] mod tests { use super::*; /// 技能帶參數 (M4): the three new fields read from SKILL.md, written back the same. #[test] fn a_skill_takes_arguments_tools_and_fork() { let md = "---\nname: release-notes\ndescription: 寫版本說明\nargument-hint: <版本> [格式]\narguments: [version, format]\nallowed-tools:\n - Read\n - Bash(git log:*)\n - shell(git tag *)\ncontext: fork\n---\n替 $version 寫說明(格式 $format),全部參數:$ARGUMENTS;第一個 $0、第二個 $ARGUMENTS[1]。價格 $5 不是參數。\n"; let k = parse_skill_markdown(md).unwrap(); assert_eq!(k.argument_hint, "<版本> [格式]"); assert_eq!(k.arguments, ["version", "format"]); assert_eq!(k.allowed_tools, ["Read", "Bash(git log:*)", "shell(git tag *)"]); assert!(k.fork); assert_eq!(parse_skill_markdown(&render_skill_markdown(&k)).unwrap(), Skill { instructions: k.instructions.clone(), ..k.clone() }); let one_line = parse_skill_markdown("---\nname: x\nallowed-tools: Read, Grep, Bash(git add:*)\n---\nhi").unwrap(); assert_eq!(one_line.allowed_tools, ["Read", "Grep", "Bash(git add:*)"]); // The arguments into the instructions. let t = with_arguments(&k, "v2.3 \"條列 簡短\""); assert!(t.contains("替 v2.3 寫說明(格式 條列 簡短)"), "{t}"); assert!(t.contains("全部參數:v2.3 \"條列 簡短\"") && t.contains("第一個 v2.3、第二個 條列 簡短"), "{t}"); assert!(t.contains("價格 不是參數") || t.contains("價格 $5"), "a $5 past the arguments is empty, as Claude Code does: {t}"); let plain = Skill { name: "p".into(), instructions: "照做".into(), ..Default::default() }; assert_eq!(with_arguments(&plain, "a b"), "照做\n\nARGUMENTS: a b"); assert_eq!(with_arguments(&plain, ""), "照做"); // A skill's own code keeps its $1 (it names no arguments). let awk = Skill { name: "a".into(), instructions: "跑 awk '{print $1}' 再算 $2".into(), ..Default::default() }; assert!(!takes_arguments(&awk) && with_arguments(&awk, "x y").starts_with("跑 awk '{print $1}' 再算 $2")); assert_eq!(arguments_after("/release-notes v2.3 條列", "release-notes"), "v2.3 條列"); // allowed-tools as rules: Claude Code's names are AnyBot's tools. let rules = tool_rules(&k); assert_eq!(rules, ["tool(read_file)", "shell(git log *)", "shell(git tag *)"]); // A list at the left edge, an item with a colon; Read(…) reads only, and not past `..`. let k2 = parse_skill_markdown("---\nname: y\nallowed-tools:\n- Read(docs/**)\n- Bash(git add:*)\n- browser\n---\nhi").unwrap(); assert_eq!(k2.allowed_tools, ["Read(docs/**)", "Bash(git add:*)", "browser"]); let r2 = tool_rules(&k2); let path = |p: &str| serde_json::json!({"path": p}).to_string(); assert!(skill_allows(&r2, "read_file", &path("docs/a.md")) && !skill_allows(&r2, "edit_file", &path("docs/a.md"))); assert!(!skill_allows(&r2, "read_file", &path("docs/../../.ssh/config"))); assert!(skill_allows(&r2, "browser_open", "{}") && skill_allows(&r2, "shell", &serde_json::json!({"command": "git add ."}).to_string())); assert_eq!(split_arguments("don't stop now"), ["don't", "stop", "now"]); let sh = |c: &str| serde_json::json!({"command": c}).to_string(); assert!(skill_allows(&rules, "read_file", r#"{"path":"a"}"#)); assert!(skill_allows(&rules, "shell", &sh("git log --oneline")) && skill_allows(&rules, "shell", &sh("git tag v2"))); assert!(!skill_allows(&rules, "shell", &sh("rm -rf build")) && !skill_allows(&rules, "edit_file", r#"{"path":"a"}"#)); assert!(skill_allows(&rules, "use_skill", "{}") && skill_allows(&rules, "ask_person", "{}")); let text = format_skill_for_model(&k, None, Some("v2.3")).unwrap(); assert!(text.contains("替 v2.3") && text.contains("只准用這些工具"), "{text}"); } #[test] fn parses_standard_agent_skills_frontmatter_and_blocks() { let md = "\u{feff}---\r\nname: \"webapp-testing\"\r\ndescription: >-\r\n Toolkit for interacting with and testing local web applications\r\n using Playwright.\r\nlicense: Apache-2.0\r\nmetadata:\r\n author: anthropic\r\n---\r\n\r\n# Web Application Testing\r\n\r\nRun `scripts/with_server.py`.\r\n"; let s = parse_skill_markdown(md).unwrap(); assert_eq!(s.name, "webapp-testing"); assert_eq!(s.description, "Toolkit for interacting with and testing local web applications using Playwright."); assert!(s.enabled); assert!(s.instructions.starts_with("# Web Application Testing")); let literal = "---\nname: custom\ndescription: |\n 第一行\n 第二行\nenabled: false\n---\n內容\n```steps\n[{\"tool\":\"shell\",\"args\":\"{}\"}]\n```"; let s2 = parse_skill_markdown(literal).unwrap(); assert_eq!(s2.name, "custom"); assert_eq!(s2.description, "第一行\n第二行"); assert!(!s2.enabled); assert_eq!(s2.steps.len(), 1); assert_eq!(s2.instructions, "內容"); } #[test] fn all_embedded_builtins_parse_and_have_valid_resources() { for b in BUILTIN_SKILLS { let s = parse_skill_markdown(b.skill_md).unwrap_or_else(|| panic!("builtin {} failed to parse", b.slug)); assert!(!s.name.is_empty() && !s.description.is_empty() && !s.instructions.is_empty()); for (rel, content) in b.files { assert!(safe_rel_path(rel).is_some(), "unsafe rel path {rel}"); assert!(!content.trim().is_empty(), "empty resource {rel}"); } } } #[test] fn recognizes_github_urls_and_shorthands() { assert_eq!( parse_github_source("https://github.com/anthropics/skills/tree/main/skills/mcp-builder"), Some(GitHubSpec { owner: "anthropics".into(), repo: "skills".into(), git_ref: Some("main".into()), path: "skills/mcp-builder".into() }) ); assert_eq!( parse_github_source("https://github.com/anthropics/skills/blob/main/skills/pdf/SKILL.md"), Some(GitHubSpec { owner: "anthropics".into(), repo: "skills".into(), git_ref: Some("main".into()), path: "skills/pdf".into() }) ); assert_eq!( parse_github_source("anthropics/skills/skills/webapp-testing"), Some(GitHubSpec { owner: "anthropics".into(), repo: "skills".into(), git_ref: None, path: "skills/webapp-testing".into() }) ); assert_eq!(parse_github_source("https://example.com/my-skill.md"), None); } #[test] fn safe_rel_path_rejects_traversal_and_secrets() { assert!(safe_rel_path("scripts/audit_xlsx.py").is_some()); assert!(safe_rel_path("references/design-checklist.md").is_some()); assert!(safe_rel_path("../secret.txt").is_none()); assert!(safe_rel_path("/etc/passwd").is_none()); assert!(safe_rel_path(".env").is_none()); assert!(safe_rel_path("scripts/.hidden").is_none()); assert!(safe_rel_path("keys/private.pem").is_none()); } #[test] fn chinese_skill_names_get_distinct_folders_and_do_not_clobber_each_other() { let s1 = parse_skill_markdown("---\nname: 每日打卡\ndescription: A\n---\n步驟一").unwrap(); let s2 = parse_skill_markdown("---\nname: 看報快摘\ndescription: B\n---\n步驟二").unwrap(); let d1 = write_skill_package(&s1, &[]).unwrap(); let d2 = write_skill_package(&s2, &[]).unwrap(); assert_ne!(d1, d2, "two Chinese skills must not write into the same `skill/` folder"); assert!(std::fs::read_to_string(d1.join("SKILL.md")).unwrap().contains("每日打卡")); assert!(std::fs::read_to_string(d2.join("SKILL.md")).unwrap().contains("看報快摘")); let _ = std::fs::remove_dir_all(d1); let _ = std::fs::remove_dir_all(d2); } }