Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797

Daniel49a6468d5bef
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 266fcd2720..f933c25d2f 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -958,7 +958,7 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editor
sb.WriteString("\n\n")
sb.WriteString("## Skill Management\n")
- sb.WriteString("Use the skill tool to manage reusable skills: \"save\" (create/update; provide name + SKILL.md content with YAML frontmatter ---\\nname: ...\\ndescription: ...\\n--- and markdown body), \"remove\", \"rename\" (name + new_name), \"list\".")
+ sb.WriteString("Use the skill tool to manage reusable skills: \"save\" (create/update; provide name + SKILL.md content with YAML frontmatter ---\\nname: ...\\ndescription: ...\\n--- and markdown body), \"install\" (download & install a skill from a remote source — pass url; accepts 'owner/repo' shorthand like Tencent/WeChatReading, a full GitHub URL, a raw SKILL.md URL, or a release zip URL; installed globally), \"remove\", \"rename\" (name + new_name), \"list\". When the user says \"install xxx skill\" or pastes a command like \"npx skills add owner/repo -g\", extract the owner/repo and call skill.install.")
sb.WriteString("\n\nReply in ")
sb.WriteString(util.I18nTerm(language, "_label"))
diff --git a/kernel/mcp/tools/skill.go b/kernel/mcp/tools/skill.go
index 20ecabd396..b11ffd66b2 100644
--- a/kernel/mcp/tools/skill.go
+++ b/kernel/mcp/tools/skill.go
@@ -26,13 +26,14 @@ import (
var SkillTool = &Tool{
Name: "skill",
- Description: "Skill operations: load(name), save(name, content), remove(name), rename(name, new_name), list().\n\n" + skillListDesc(),
+ Description: "Skill operations: load(name), save(name, content), install(url), remove(name), rename(name, new_name), list().\n\n" + skillListDesc(),
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation", Enum: []string{"load", "save", "remove", "rename", "list"}},
+ "action": {Type: "string", Description: "Operation", Enum: []string{"load", "save", "install", "remove", "rename", "list"}},
"name": {Type: "string", Description: "Skill name (directory name)"},
"content": {Type: "string", Description: "SKILL.md full content with YAML frontmatter (for save)"},
+ "url": {Type: "string", Description: "Skill source for install: 'owner/repo' shorthand (e.g. Tencent/WeChatReading), a full GitHub URL, a raw SKILL.md URL, or a release zip URL"},
"new_name": {Type: "string", Description: "New skill name (for rename)"},
},
Required: []string{"action"},
@@ -51,6 +52,8 @@ func skillHandler(args map[string]interface{}) (CallToolResult, error) {
return skillLoad(args)
case "save":
return skillSave(args)
+ case "install":
+ return skillInstall(args)
case "remove":
return skillRemove(args)
case "rename":
@@ -59,7 +62,7 @@ func skillHandler(args map[string]interface{}) (CallToolResult, error) {
return skillList(args)
}
return CallToolResult{
- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [load, save, remove, rename, list]"}},
+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [load, save, install, remove, rename, list]"}},
IsError: true,
}, nil
}
@@ -118,6 +121,37 @@ func skillSave(args map[string]interface{}) (CallToolResult, error) {
}, nil
}
+func skillInstall(args map[string]interface{}) (CallToolResult, error) {
+ rawURL, _ := args["url"].(string)
+ if rawURL == "" {
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "url is required for install (owner/repo shorthand, GitHub URL, raw SKILL.md URL, or release zip URL)"}},
+ IsError: true,
+ }, nil
+ }
+
+ result, err := util.InstallSkill(rawURL)
+ if err != nil {
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: "install failed: " + err.Error()}},
+ IsError: true,
+ }, nil
+ }
+
+ var sb strings.Builder
+ sb.WriteString(fmt.Sprintf("installed %d skill(s):\n", len(result.Names)))
+ for i, name := range result.Names {
+ desc := ""
+ if i < len(result.Descriptions) {
+ desc = result.Descriptions[i]
+ }
+ sb.WriteString("- **" + name + "**: " + desc + "\n")
+ }
+ return CallToolResult{
+ Content: []ContentItem{{Type: "text", Text: sb.String()}},
+ }, nil
+}
+
func skillRemove(args map[string]interface{}) (CallToolResult, error) {
name, _ := args["name"].(string)
if name == "" {
diff --git a/kernel/util/skill.go b/kernel/util/skill.go
index 3378b08f10..06e5d94439 100644
--- a/kernel/util/skill.go
+++ b/kernel/util/skill.go
@@ -17,13 +17,19 @@
package util
import (
+ "errors"
"fmt"
+ "io"
+ "net/url"
"os"
"path/filepath"
+ "regexp"
"strings"
"github.com/88250/gulu"
"github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/httpclient"
+ "github.com/siyuan-note/logging"
)
type SkillInfo struct {
@@ -215,3 +221,360 @@ func firstLine(text string) string {
}
return text
}
+
+// InstallSkillResult 记录一次安装落地的 skill 列表
+type InstallSkillResult struct {
+ Names []string `json:"names"`
+ Descriptions []string `json:"descriptions"`
+}
+
+// skill 下载体上限(与 web_fetch 的文件下载上限一致)
+const maxSkillDownloadBytes = 10 * 1024 * 1024
+
+// ownerRepoPattern 匹配 owner/repo 简写,如 Tencent/WeChatReading
+var ownerRepoPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*$`)
+
+// skillsAddPattern 从 "npx skills add owner/repo ..." 这类命令里提取 owner/repo
+var skillsAddPattern = regexp.MustCompile(`(?:^|\s)([A-Za-z0-9][A-Za-z0-9._-]*/[A-Za-z0-9][A-Za-z0-9._-]*)(?:\s|$)`)
+
+// normalizedSkillSource 描述归一化后的下载源
+type normalizedSkillSource struct {
+ downloadURL string // 实际 GET 的地址
+ isZip bool // 是否按 zip 解压处理(codeload / release zip / Content-Type 判定为 zip)
+ branch string // codeload 分支,空表示无需回退;main 失败回退 master
+}
+
+// InstallSkill 从 GitHub 仓库或直链下载并安装 skill 到 SkillsDir()。
+// 支持的输入:owner/repo 简写、整条 "npx skills add owner/repo -g" 命令、
+// 完整 GitHub 仓库/子目录/commit URL、raw SKILL.md 直链、release zip 直链。
+func InstallSkill(rawURL string) (*InstallSkillResult, error) {
+ rawURL = strings.TrimSpace(rawURL)
+ if rawURL == "" {
+ return nil, errors.New("skill source is required")
+ }
+
+ src, err := normalizeSkillURL(rawURL)
+ if err != nil {
+ return nil, err
+ }
+
+ data, contentType, err := downloadSkillSource(src)
+ if err != nil {
+ return nil, err
+ }
+
+ // 按内容类型或来源判定处理方式
+ isZip := src.isZip || strings.HasPrefix(contentType, "application/zip") ||
+ strings.HasPrefix(contentType, "application/x-zip-compressed")
+
+ if isZip {
+ return installFromZip(data)
+ }
+
+ // 文本:当作单个 SKILL.md
+ if strings.HasPrefix(contentType, "text/") || strings.HasPrefix(strings.TrimSpace(string(data)), "---") {
+ return installFromSingleSkillMD(data)
+ }
+
+ return nil, fmt.Errorf("unsupported skill source (content-type: %s); expected a zip archive or a SKILL.md text file", contentType)
+}
+
+// normalizeSkillURL 把各种输入归一化为下载源
+func normalizeSkillURL(raw string) (normalizedSkillSource, error) {
+ raw = strings.TrimSpace(raw)
+
+ // 1. 整条 "npx skills add owner/repo ..." 命令:提取 owner/repo
+ if strings.Contains(raw, "skills add") || strings.Contains(raw, "skills@") {
+ if m := skillsAddPattern.FindStringSubmatch(raw); len(m) == 2 {
+ return codeloadSource(m[1], "main"), nil
+ }
+ }
+
+ // 2. owner/repo 简写(无 scheme、无点、单个 /)
+ if !strings.Contains(raw, "://") && !strings.Contains(raw, "//") && ownerRepoPattern.MatchString(raw) {
+ return codeloadSource(raw, "main"), nil
+ }
+
+ // 3. 带 scheme 的 URL
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme == "" || u.Host == "" {
+ return normalizedSkillSource{}, fmt.Errorf("unrecognized skill source: %s", raw)
+ }
+
+ switch u.Host {
+ case "github.com":
+ return normalizeGitHubURL(u)
+ case "raw.githubusercontent.com":
+ // 直接 GET 单个 SKILL.md(或其它文本文件)
+ return normalizedSkillSource{downloadURL: u.String()}, nil
+ default:
+ // 其它直链(release zip、自建站点等):直接 GET,是否 zip 交由 Content-Type 判定
+ return normalizedSkillSource{downloadURL: u.String()}, nil
+ }
+}
+
+// codeloadSource 构造 codeload zip 下载源,branch 用于 main→master 回退
+func codeloadSource(ownerRepo, branch string) normalizedSkillSource {
+ return normalizedSkillSource{
+ downloadURL: "https://codeload.github.com/" + ownerRepo + "/zip/refs/heads/" + branch,
+ isZip: true,
+ branch: branch,
+ }
+}
+
+// normalizeGitHubURL 处理 github.com 的各种路径形态
+func normalizeGitHubURL(u *url.URL) (normalizedSkillSource, error) {
+ // /owner/repo/tree/<branch> 或 /owner/repo/tree/<branch>/<path>
+ // /owner/repo/commit/<sha>
+ // /owner/repo/releases/download/<tag>/<asset>
+ // /owner/repo(默认分支)
+ parts := strings.Split(strings.Trim(u.Path, "/"), "/")
+ if len(parts) < 2 {
+ return normalizedSkillSource{}, fmt.Errorf("invalid github URL: %s", u.String())
+ }
+ ownerRepo := parts[0] + "/" + parts[1]
+
+ // releases/download/<tag>/<asset>
+ if len(parts) >= 5 && parts[2] == "releases" && parts[3] == "download" {
+ // release 资源通常是 zip;是否 zip 交由 Content-Type 最终判定,这里先标 isZip
+ return normalizedSkillSource{downloadURL: u.String(), isZip: strings.HasSuffix(parts[4], ".zip")}, nil
+ }
+
+ // tree/<branch>[/path] 或 blob/<branch>/...
+ if len(parts) >= 4 && (parts[2] == "tree" || parts[2] == "blob") {
+ branch := parts[3]
+ if parts[2] == "blob" {
+ // blob 指向单个文件,走 raw
+ rawPath := strings.Join(parts[4:], "/")
+ return normalizedSkillSource{
+ downloadURL: "https://raw.githubusercontent.com/" + ownerRepo + "/" + branch + "/" + rawPath,
+ }, nil
+ }
+ return codeloadSource(ownerRepo, branch), nil
+ }
+
+ // commit/<sha>
+ if len(parts) >= 4 && parts[2] == "commit" {
+ sha := parts[3]
+ return normalizedSkillSource{
+ downloadURL: "https://codeload.github.com/" + ownerRepo + "/zip/" + sha,
+ isZip: true,
+ }, nil
+ }
+
+ // 纯仓库地址:默认 main,失败回退 master
+ return codeloadSource(ownerRepo, "main"), nil
+}
+
+// downloadSkillSource 下载 skill 源,返回字节、Content-Type
+func downloadSkillSource(src normalizedSkillSource) (data []byte, contentType string, err error) {
+ u, perr := url.Parse(src.downloadURL)
+ if perr != nil || u.Host == "" {
+ return nil, "", fmt.Errorf("invalid download URL: %s", src.downloadURL)
+ }
+ if cerr := CheckHostSSRF(u.Hostname()); cerr != nil {
+ return nil, "", cerr
+ }
+
+ data, contentType, err = fetchBytes(src.downloadURL)
+ if err == nil {
+ return data, contentType, nil
+ }
+
+ // codeload main 分支 404 时回退 master
+ if src.isZip && src.branch == "main" {
+ ownerRepo := strings.TrimPrefix(strings.TrimPrefix(src.downloadURL, "https://codeload.github.com/"), "http://codeload.github.com/")
+ ownerRepo = strings.TrimSuffix(ownerRepo, "/zip/refs/heads/main")
+ fallback := codeloadSource(ownerRepo, "master")
+ data, contentType, ferr := fetchBytes(fallback.downloadURL)
+ if ferr != nil {
+ return nil, "", fmt.Errorf("download failed (tried main and master): %v", err)
+ }
+ return data, contentType, nil
+ }
+ return nil, "", err
+}
+
+// fetchBytes 执行带大小限制的 GET
+func fetchBytes(rawURL string) (data []byte, contentType string, err error) {
+ resp, err := httpclient.NewBrowserRequest().Get(rawURL)
+ if err != nil {
+ return nil, "", errors.New("download failed: " + err.Error())
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode >= 400 {
+ return nil, "", fmt.Errorf("download failed: HTTP %d", resp.StatusCode)
+ }
+
+ contentType = resp.Header.Get("Content-Type")
+ body, err := io.ReadAll(io.LimitReader(resp.Body, maxSkillDownloadBytes+1))
+ if err != nil {
+ return nil, "", errors.New("read body failed: " + err.Error())
+ }
+ if len(body) > maxSkillDownloadBytes {
+ return nil, "", errors.New("skill source too large (limit 10MB)")
+ }
+ return body, contentType, nil
+}
+
+// installFromZip 解压 zip 并安装其中的 skill
+func installFromZip(data []byte) (*InstallSkillResult, error) {
+ tmpRoot := filepath.Join(TempDir, "skill-install", gulu.Rand.String(7))
+ if err := os.MkdirAll(tmpRoot, 0755); err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(tmpRoot)
+
+ zipPath := filepath.Join(tmpRoot, "src.zip")
+ if err := os.WriteFile(zipPath, data, 0644); err != nil {
+ return nil, err
+ }
+ unzipDir := filepath.Join(tmpRoot, "unzip")
+ if err := os.MkdirAll(unzipDir, 0755); err != nil {
+ return nil, err
+ }
+ // gulu.Zip.Unzip 已内置 zip-slip 路径穿越防护
+ if err := gulu.Zip.Unzip(zipPath, unzipDir); err != nil {
+ return nil, errors.New("unzip failed: " + err.Error())
+ }
+
+ skillDirs := findSkillDirs(unzipDir)
+ if len(skillDirs) == 0 {
+ return nil, errors.New("no SKILL.md found in the archive")
+ }
+ return installSkillDirs(skillDirs, unzipDir)
+}
+
+// findSkillDirs 在解压根下查找含 SKILL.md 的目录,返回相对 root 的路径
+// 识别三种结构:根 SKILL.md / skills/<name>/SKILL.md / <name>/SKILL.md(单层包裹)
+func findSkillDirs(root string) []string {
+ // 1. 根目录直接有 SKILL.md
+ if gulu.File.IsExist(filepath.Join(root, "SKILL.md")) {
+ return []string{"."}
+ }
+
+ entries, err := os.ReadDir(root)
+ if err != nil {
+ return nil
+ }
+
+ // 2. skills/<name>/SKILL.md —— 集合仓库
+ var collection []string
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ if e.Name() == "skills" {
+ skillsDir := filepath.Join(root, "skills")
+ subs, serr := os.ReadDir(skillsDir)
+ if serr != nil {
+ continue
+ }
+ for _, s := range subs {
+ if s.IsDir() && gulu.File.IsExist(filepath.Join(skillsDir, s.Name(), "SKILL.md")) {
+ collection = append(collection, filepath.Join("skills", s.Name()))
+ }
+ }
+ if len(collection) > 0 {
+ return collection
+ }
+ }
+ }
+
+ // 3. <name>/SKILL.md —— 单层包裹(codeload zip 默认包一层 repo-name/)
+ var wrapped []string
+ for _, e := range entries {
+ if !e.IsDir() {
+ continue
+ }
+ if gulu.File.IsExist(filepath.Join(root, e.Name(), "SKILL.md")) {
+ wrapped = append(wrapped, e.Name())
+ }
+ }
+ return wrapped
+}
+
+// installSkillDirs 把若干相对 root 的 skill 目录落地到 SkillsDir()
+func installSkillDirs(relDirs []string, root string) (*InstallSkillResult, error) {
+ result := &InstallSkillResult{}
+ for _, rel := range relDirs {
+ srcDir := filepath.Join(root, rel)
+ if !gulu.File.IsSubPath(root, srcDir) {
+ continue
+ }
+ skillMdPath := filepath.Join(srcDir, "SKILL.md")
+ b, err := filelock.ReadFile(skillMdPath)
+ if err != nil {
+ logging.LogWarnf("read SKILL.md [%s] failed: %s", skillMdPath, err)
+ continue
+ }
+ fm, _ := parseSkillFrontmatter(string(b))
+ name := fm["name"]
+ if name == "" {
+ name = filepath.Base(rel)
+ if name == "." {
+ name = filepath.Base(root)
+ }
+ }
+ if verr := validateSkillName(name); verr != nil {
+ logging.LogWarnf("skip invalid skill name [%s]: %s", name, verr)
+ continue
+ }
+
+ destDir := filepath.Join(SkillsDir(), name)
+ if err := os.MkdirAll(SkillsDir(), 0755); err != nil {
+ return nil, err
+ }
+ // 覆盖式安装:先清旧目录
+ if gulu.File.IsExist(destDir) {
+ os.RemoveAll(destDir)
+ }
+ if err := filelock.Copy(srcDir, destDir); err != nil {
+ return nil, fmt.Errorf("install skill %s failed: %s", name, err)
+ }
+ result.Names = append(result.Names, name)
+ desc := fm["description"]
+ if desc == "" {
+ desc = firstLine(strings.TrimSpace(strings.TrimPrefix(string(b), frontmatterBlock(string(b)))))
+ }
+ result.Descriptions = append(result.Descriptions, desc)
+ }
+ if len(result.Names) == 0 {
+ return nil, errors.New("no valid skill installed")
+ }
+ return result, nil
+}
+
+// installFromSingleSkillMD 把单个 SKILL.md 文本内容落地为一个 skill
+func installFromSingleSkillMD(data []byte) (*InstallSkillResult, error) {
+ content := string(data)
+ fm, body := parseSkillFrontmatter(content)
+ name := fm["name"]
+ if name == "" {
+ return nil, errors.New("SKILL.md frontmatter missing 'name' field")
+ }
+ if err := validateSkillName(name); err != nil {
+ return nil, err
+ }
+ if err := SaveSkill(name, content); err != nil {
+ return nil, err
+ }
+ return &InstallSkillResult{
+ Names: []string{name},
+ Descriptions: []string{firstLine(body)},
+ }, nil
+}
+
+// frontmatterBlock 返回文本开头的 frontmatter 块(含分隔符),无则返回空
+func frontmatterBlock(text string) string {
+ t := strings.TrimSpace(text)
+ if !strings.HasPrefix(t, "---") {
+ return ""
+ }
+ end := strings.Index(t[3:], "\n---")
+ if end < 0 {
+ return ""
+ }
+ return t[:3+end+4]
+}