AnyBot/src/skills.rs

1050 lines
45 KiB
Rust
Raw Normal View History

2026-11-11 08:19:06 +00:00
//! 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 `<data>/skills/<slug>/`:
//! - `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 `<data>/skills/<name>.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<PathBuf> {
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<Skill> {
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 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();
if trimmed.is_empty() || 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();
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<usize> = 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"),
_ => {}
}
}
}
}
let mut steps: Vec<ReplayStep> = 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,
..Default::default()
})
}
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::<Vec<_>>().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");
}
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<String> {
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 (`<folder>/SKILL.md` or `<folder>/skill.md`).
pub fn load_folder_skill(dir: &Path) -> Option<Skill> {
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 `<dir>/<slug>/SKILL.md` and legacy `<dir>/<name>.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 `<skill_dir>/<slug>/`.
pub fn write_skill_package(skill: &Skill, extra_files: &[(String, Vec<u8>)]) -> Result<PathBuf, String> {
let root = crate::memory::skill_dir();
let slug = slug_of(&skill.name);
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 `<slug>.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<Skill, String> {
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<u8>)> = 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<Skill>) {
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 `<data>/skills/` and `skills`.
pub fn install_builtin(slug_or_name: &str, skills: &mut Vec<Skill>) -> Result<String, String> {
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<PathBuf> {
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<String, String> {
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>) -> Result<String, String> {
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, k.instructions);
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<String>,
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<GitHubSpec> {
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<String, String> {
let mut files: Vec<(String, Vec<u8>)> = 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<u8>)>,
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::<Vec<_>>()
.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<u8>)> = 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<String, String> {
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
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<u8>)>);
/// 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<Package, String> {
2026-11-11 08:19:06 +00:00
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;
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
for r in discover_resources(dir) {
let bytes = std::fs::read(dir.join(&r)).map_err(|e| e.to_string())?;
2026-11-11 08:19:06 +00:00
total += bytes.len();
if total > MAX_PACKAGE_BYTES {
return Err("技能資料夾超過大小上限(6 MB)".into());
}
extra.push((r, bytes));
}
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
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<u8>)>, source: &str, enabled: bool) -> serde_json::Value {
use base64::Engine;
let files: Vec<serde_json::Value> = 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<serde_json::Value, String> {
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<serde_json::Value, String> {
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 `<data>/skills/<slug>/` and give back the skill as
/// the list keeps it.
pub fn install_package(v: &serde_json::Value) -> Result<Skill, String> {
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)
2026-11-11 08:19:06 +00:00
}
/// Universal installer: accepts `builtin:<slug>`, 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<String, String> {
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/<branch>/<file>.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}」"))
}
技能: / in the input picks one; on a brain's screen the brain adds, installs and deletes them; 設定 › 整合's lists keep their buttons clear - Typing / at the start of the input (computer and phone) lists the skills that are on: names that start with what is typed first, then names containing it, then descriptions (「/簡報」 finds pptx). A click, or ↑↓ and Enter/Tab, puts 「/name 」 in the input; Esc closes the list. Sent, the brain recognises 「/name」 and adds a line after the message telling the model to read that skill with use_skill first, so a phone or a message channel gets it too; a / that names no skill (a path) gets nothing. The phone asks the brain for the list again at each new /, so a skill added since is there. - On a screen, 加入 / 安裝 / 刪除 ran on the screen's own disk and only the list entry reached the brain: a GitHub skill's scripts stayed on the screen's computer, an install also pushed every skill in that computer's folder into the brain's list, and a deleted skill's folder stayed on the brain and came back at its next start. These now go to the brain (/api/sync/skill, the phone's own 「skill」 action): it fetches an address itself, a folder or .md file on the screen's computer goes up whole with its files, and a delete takes the folder too. 「把這台的 Bot 搬到大腦」 hands over skills the same way. A refused package leaves no folder behind. - 技能, 技能市集 and 連接器市集 rows: a long description took the whole row and 開啟 / 檢視 / 刪除 / 已加入 / 安裝 were drawn over it. The buttons are laid out first and the description ends in … before them (the whole of it on hover). - Screenshot mode: ANYBOT_SHOT_KEYS="ArrowDown@60;Enter@64" presses keys at given frames. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 08:54:58 +00:00
#[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");
}
}
2026-11-11 08:19:06 +00:00
#[cfg(test)]
mod tests {
use super::*;
#[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());
}
}