An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:sparkles: AI Agent https://github.com/siyuan-note/siyuan/issues/17797
Danielc63fec9632ac
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex b89114a566..e2b43a5278 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -58,6 +58,7 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their- Modify: block.update replaces ONE block's content with new markdown — it does NOT create or append new blocks. To both modify and add, call block.update first, then block.append/prepend/insert as separate calls.- Organize: document.move (full document), document.rename (title), block.move (single content block), document.delete.- Attributes: attr.get/set on any block. Database/attribute views: database.item_add (rows), database.key_add (columns), database.render (view). Create database blocks via database tools, never via the file tool.+- Icons: attr.set only changes a document BLOCK's icon — it cannot set a NOTEBOOK's icon. For notebooks use notebook.set_icon (a specific emoji) or notebook.random_icon (random emoji, optionally scoped by id; omit id to randomize ALL notebooks).## Response Guidelines- Reply in the user's language. When mentioning documents/blocks the user can open, format them as markdown links: [title](siyuan://blocks/<blockID>). Only use block IDs actually returned by a tool call (block.get/get_children/breadcrumb/batch_get/search); never fabricate IDs. For general mentions without a specific block, plain text is fine.@@ -122,8 +123,13 @@ const ()// toolSignatureKeys 列出各工具里真正"区分一次调用"的关键参数。-// 这些参数会并入死循环签名,避免 agent 对不同 url/query/sql 的合法连续调用被误判;+// 这些参数会并入死循环签名,避免 agent 对不同 url/query/id 的合法连续调用被误判;// 同时对同一参数反复调用(真死循环)仍能正确触发终止。+//+// 选键原则:只纳入稳定的"目标标识符"类参数(id/ids/path/label/name/keyword/notebook/url 等),+// 不纳入易变的"内容值"类参数(data/markdown/content/value/memo/title 等)。+// 此外,object/array 类参数(如 attr 的 attrs、block 的 items)经 fmt.Sprint 字符串化后+// 顺序不稳定(map 迭代无序),会削弱签名稳定性,故一律排除。var toolSignatureKeys = map[string][]string{"web_fetch": {"url", "format"},"web_search": {"query"},@@ -131,10 +137,28 @@ var toolSignatureKeys = map[string][]string{"sql": {"sql", "stmt"},"search": {"query", "keyword"},"outline": {"id", "doc_id"},- "system": {"action"},- "workspace": {"action"},- "sync": {"action"},- "todo_write": {"todos"},++ "attr": {"id", "ids"},+ "block": {"id", "ids", "parentID", "nextID", "previousID"},+ "document": {"id", "path", "notebook", "keyword"},+ "database": {"id", "keyID", "itemID", "itemIDs", "keyword"},+ "ref": {"id", "keyword"},+ "notebook": {"id", "name"},+ "tag": {"label", "old", "new", "keyword"},+ "bookmark": {"label", "old", "new"},+ "dailynote": {"notebook"},+ "template": {"id", "path", "name", "keyword"},+ "history": {"path", "notebook", "query"},+ "repo": {"id", "left", "right", "name", "keyword"},+ "asset": {"id", "path"},+ "import": {"notebook", "path"},+ "export": {"id"},+ "skill": {"name", "url"},++ "system": {"action"},+ "workspace": {"action"},+ "sync": {"action"},+ "todo_write": {"todos"},}// buildDoomSignature 用 toolName + action + 关键参数构造死循环签名。diff --git a/kernel/mcp/tools/block.go b/kernel/mcp/tools/block.goindex 97af11b0e0..cc1fddb1a7 100644--- a/kernel/mcp/tools/block.go+++ b/kernel/mcp/tools/block.go@@ -20,6 +20,7 @@ import ("fmt""strings"+ "github.com/88250/lute/ast""github.com/siyuan-note/siyuan/kernel/filesys""github.com/siyuan-note/siyuan/kernel/model""github.com/siyuan-note/siyuan/kernel/treenode"@@ -296,13 +297,9 @@ func blockUpdate(args map[string]interface{}) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "data is required"}}, IsError: true}, nil}- if dataType == "markdown" {- var err error- data, err = markdownToBlockDOM(data)- if err != nil {- return CallToolResult{Content: []ContentItem{{Type: "text", Text: "convert markdown failed: " + err.Error()}}, IsError: true}, nil- }- }+ // markdown 转 DOM 时 Lute 会给块生成全新的随机 ID,update 前必须把原块 id 钉回去,+ // 否则块 ID 每次更新都会变,后续按原 id 操作会报 block not found+ data = pinBlockID(data, dataType, id)transactions := []*model.Transaction{{DoOperations: []*model.Operation{{@@ -321,6 +318,42 @@ func blockUpdate(args map[string]interface{}) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "block updated"}}}, nil}+// pinBlockID 把原块 id 钉回 markdown/dom 数据,保证 update 不改变块 ID。+// 参照 HTTP API /api/block/updateBlock 的 id 复位逻辑(block_op.go updateBlock 非 Document 分支)。+func pinBlockID(data, dataType, id string) string {+ luteEngine := util.NewLute()+ if dataType == "markdown" {+ var err error+ data, err = markdownToBlockDOM(data)+ if err != nil {+ return data+ }+ }++ tree := luteEngine.BlockDOM2Tree(data)+ if nil == tree || nil == tree.Root || nil == tree.Root.FirstChild {+ return data+ }++ // 更新列表项时 markdown 会渲染成 NodeList>ListItem,需要先把列表项提升到根下,渲染器才能正常工作+ // 使用 API `api/block/updateBlock` 更新列表项时渲染错误 https://github.com/siyuan-note/siyuan/issues/4658+ if ast.NodeList == tree.Root.FirstChild.Type {+ tree.Root.AppendChild(tree.Root.FirstChild.FirstChild) // 将列表下的第一个列表项移到文档结尾+ tree.Root.FirstChild.Unlink() // 删除列表+ if nil != tree.Root.FirstChild && ast.NodeKramdownBlockIAL == tree.Root.FirstChild.Type {+ tree.Root.FirstChild.Unlink() // 继续删除列表 IAL+ }+ }++ if nil != tree.Root.FirstChild {+ tree.Root.FirstChild.SetIALAttr("id", id)+ } else {+ tree.Root.AppendChild(treenode.NewParagraph(id))+ }++ return luteEngine.Tree2BlockDOM(tree, luteEngine.RenderOptions, luteEngine.ParseOptions)+}+func blockDelete(args map[string]interface{}) (CallToolResult, error) {id, _ := args["id"].(string)if id == "" {diff --git a/kernel/mcp/tools/emojis.go b/kernel/mcp/tools/emojis.gonew file mode 100644index 0000000000..3ff2a55a4a--- /dev/null+++ b/kernel/mcp/tools/emojis.go@@ -0,0 +1,81 @@+// SiYuan - Refactor your thinking+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package tools++import (+ "math/rand"+ "os"+ "path/filepath"+ "sync"++ "github.com/88250/gulu"++ "github.com/siyuan-note/siyuan/kernel/util"+)++// builtinEmojiUnicodes 缓存内置 emoji 的全部 unicode 码点(来自 appearance/emojis/conf.json)。+// 与前端 getRandomEmoji() 数据源一致,但刻意排除用户自定义图片,+// 保持随机图标风格统一、避免误用用户的重要图片。+var (+ builtinEmojiUnicodes []string+ builtinEmojiUnicodesOnce sync.Once+)++// loadBuiltinEmojiUnicodes 懒加载内置 emoji 的 unicode 列表。+// 失败时回退到一个固定码点,调用方始终拿到可用值。+func loadBuiltinEmojiUnicodes() {+ builtinEmojiUnicodesOnce.Do(func() {+ confPath := filepath.Join(util.AppearancePath, "emojis", "conf.json")+ data, err := os.ReadFile(confPath)+ if err != nil {+ builtinEmojiUnicodes = []string{"1f4d6"}+ return+ }++ var conf []map[string]any+ if err = gulu.JSON.UnmarshalJSON(data, &conf); err != nil {+ builtinEmojiUnicodes = []string{"1f4d6"}+ return+ }++ for _, category := range conf {+ items, ok := category["items"].([]any)+ if !ok {+ continue+ }+ for _, item := range items {+ e, ok := item.(map[string]any)+ if !ok {+ continue+ }+ if u, ok := e["unicode"].(string); ok && u != "" {+ builtinEmojiUnicodes = append(builtinEmojiUnicodes, u)+ }+ }+ }++ if len(builtinEmojiUnicodes) == 0 {+ builtinEmojiUnicodes = []string{"1f4d6"}+ }+ })+}++// randomEmoji 返回一个随机的内置 emoji unicode 码点(如 "1f4d6")。+func randomEmoji() string {+ loadBuiltinEmojiUnicodes()+ return builtinEmojiUnicodes[rand.Intn(len(builtinEmojiUnicodes))]+}diff --git a/kernel/mcp/tools/notebook.go b/kernel/mcp/tools/notebook.goindex 924c2bd0d5..13b48b22c6 100644--- a/kernel/mcp/tools/notebook.go+++ b/kernel/mcp/tools/notebook.go@@ -28,13 +28,14 @@ import (var NotebookTool = &Tool{Name: "notebook",- Description: "Notebook management. Actions: list(), open(id), close(id), create(name), rename(id, name), remove(id).",+ Description: "Notebook management. Actions: list(), open(id), close(id), create(name), rename(id, name), remove(id), set_icon(id, icon), random_icon(id?).",InputSchema: ToolSchema{Type: "object",Properties: map[string]Property{- "action": {Type: "string", Description: "Operation", Enum: []string{"list", "open", "close", "create", "rename", "remove"}},- "id": {Type: "string", Description: "Notebook ID (for open, close, rename, remove)"},+ "action": {Type: "string", Description: "Operation", Enum: []string{"list", "open", "close", "create", "rename", "remove", "set_icon", "random_icon"}},+ "id": {Type: "string", Description: "Notebook ID (for open, close, rename, remove, set_icon, random_icon)"},"name": {Type: "string", Description: "Notebook name (for create, rename)"},+ "icon": {Type: "string", Description: "Notebook icon (for set_icon). Emoji hex codepoint like \"1f4ca\", emoji character like \"📊\", custom image path like \"1/b3log.png\", or dynamic icon URL like \"api/icon/getDynamicIcon?type=8&color=%23d23f31&content=SiYuan&id=xxx\""},},Required: []string{"action"},},@@ -60,9 +61,13 @@ func notebookHandler(args map[string]interface{}) (CallToolResult, error) {return notebookRename(args)case "remove":return notebookRemove(args)+ case "set_icon":+ return notebookSetIcon(args)+ case "random_icon":+ return notebookRandomIcon(args)}return CallToolResult{- Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [list, open, close, create, rename, remove]"}},+ Content: []ContentItem{{Type: "text", Text: "unknown action '" + action + "', expected one of: [list, open, close, create, rename, remove, set_icon, random_icon]"}},IsError: true,}, nil}@@ -175,3 +180,72 @@ func notebookClose(args map[string]interface{}) (CallToolResult, error) {return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook closed: " + id}}}, nil}++func notebookSetIcon(args map[string]interface{}) (CallToolResult, error) {+ id, _ := args["id"].(string)+ icon, _ := args["icon"].(string)+ if id == "" {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "id is required"}}, IsError: true}, nil+ }++ // 校验笔记本存在,避免对一个不存在的 id 静默写入图标。+ exists := false+ if notebooks, err := model.ListNotebooks(); err == nil {+ for _, nb := range notebooks {+ if nb.ID == id {+ exists = true+ break+ }+ }+ }+ if !exists {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook not found: " + id}}, IsError: true}, nil+ }++ // icon 取值格式与 attr 工具一致;SetBoxIcon 内部对自定义图片名做 XSS 过滤。+ model.SetBoxIcon(id, icon)+ util.PushReloadFiletree()++ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook icon set: " + id + " -> " + icon}}}, nil+}++func notebookRandomIcon(args map[string]interface{}) (CallToolResult, error) {+ id, _ := args["id"].(string)++ notebooks, err := model.ListNotebooks()+ if err != nil {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "list notebooks failed: " + err.Error()}}, IsError: true}, nil+ }++ // 目标范围:传 id 仅换该笔记本;不传 id 则对全部笔记本各随机换一个。+ targets := notebooks+ if id != "" {+ var found bool+ for _, nb := range notebooks {+ if nb.ID == id {+ targets = []*model.Box{nb}+ found = true+ break+ }+ }+ if !found {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "notebook not found: " + id}}, IsError: true}, nil+ }+ }+ if len(targets) == 0 {+ return CallToolResult{Content: []ContentItem{{Type: "text", Text: "no notebooks to update"}}, IsError: true}, nil+ }++ var sb strings.Builder+ sb.WriteString(fmt.Sprintf("Randomized icons for %d notebook(s):\n", len(targets)))+ for _, nb := range targets {+ oldIcon := nb.Icon+ newIcon := randomEmoji()+ model.SetBoxIcon(nb.ID, newIcon)+ sb.WriteString(fmt.Sprintf("- %s (id: %s): %s -> %s\n", nb.Name, nb.ID, oldIcon, newIcon))+ }++ util.PushReloadFiletree()++ return CallToolResult{Content: []ContentItem{{Type: "text", Text: sb.String()}}}, nil+}