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
Daniel2cdbd3228a8d
diff --git a/app/src/assets/scss/business/_agentChat.scss b/app/src/assets/scss/business/_agentChat.scssindex 699256209f..4911db5ab1 100644--- a/app/src/assets/scss/business/_agentChat.scss+++ b/app/src/assets/scss/business/_agentChat.scss@@ -613,3 +613,60 @@font-size: 13px;color: var(--b3-theme-on-surface-light);}++// Todo list styles+.agent-chat__tool-card--todo {+ background: var(--b3-card-background);+ border: 1px solid var(--b3-border-color);+ border-radius: 6px;+ overflow: hidden;+}++.agent-chat__todo-header {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 10px 12px;+ font-size: 13px;+ font-weight: 500;+ color: var(--b3-theme-on-surface);+ border-bottom: 1px solid var(--b3-border-color);+ background: var(--b3-list-background);+}++.agent-chat__todo-items {+ padding: 4px 0;+}++.agent-chat__todo-item {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 6px 12px;+ font-size: 13px;+ line-height: 1.5;+ color: var(--b3-theme-on-surface);+}++.agent-chat__todo-item--completed {+ color: var(--b3-font-color2, #999);+ text-decoration: line-through;+}++.agent-chat__todo-item--in-progress {+ color: var(--b3-theme-primary, #3575f0);+}++.agent-chat__todo-item--pending {+ color: var(--b3-theme-on-surface);+}++.agent-chat__todo-item--cancelled {+ color: var(--b3-font-color2, #999);+ text-decoration: line-through;+}++.agent-chat__todo-status {+ flex-shrink: 0;+ font-size: 14px;+}diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.tsindex 4f0278c450..604468047e 100644--- a/app/src/layout/dock/AgentChat.ts+++ b/app/src/layout/dock/AgentChat.ts@@ -396,18 +396,22 @@ export class AgentChat extends Model {if (tc.result) {const rel = document.createElement("div");rel.className = "agent-chat__msg agent-chat__msg--tool";- rel.innerHTML = '<div class="agent-chat__tool-card agent-chat__tool-card--result" data-tool="' + tc.name + '">' ++ if (tc.name === "todo_write") {+ rel.innerHTML = this.renderTodoList(tc.result);+ } else {+ rel.innerHTML = '<div class="agent-chat__tool-card agent-chat__tool-card--result" data-tool="' + tc.name + '">' +'<div class="agent-chat__tool-header">' +'<span class="agent-chat__tool-icon">📄</span>' +'<span class="agent-chat__tool-title">' + (L.agentToolResult || "Tool result") + ": " + tc.name + "</span>" +"</div>" +'<pre class="agent-chat__tool-body fn__none">' + this.escapeHtml(tc.result) + "</pre>" +"</div>";- const rheader = rel.querySelector(".agent-chat__tool-header") as HTMLElement;- var rbody = rel.querySelector(".agent-chat__tool-body") as HTMLElement;- rheader.addEventListener("click", function () {- rbody.classList.toggle("fn__none");- });+ const rheader = rel.querySelector(".agent-chat__tool-header") as HTMLElement;+ var rbody = rel.querySelector(".agent-chat__tool-body") as HTMLElement;+ rheader.addEventListener("click", function () {+ rbody.classList.toggle("fn__none");+ });+ }this.messagesContainer.appendChild(rel);}}@@ -585,22 +589,51 @@ export class AgentChat extends Model {const el = document.createElement("div");el.className = "agent-chat__msg agent-chat__msg--tool";const L = window.siyuan.languages;- el.innerHTML = '<div class="agent-chat__tool-card agent-chat__tool-card--result" data-tool="' + name + '">' +++ if (name === "todo_write") {+ el.innerHTML = this.renderTodoList(result);+ } else {+ el.innerHTML = '<div class="agent-chat__tool-card agent-chat__tool-card--result" data-tool="' + name + '">' +'<div class="agent-chat__tool-header">' +'<span class="agent-chat__tool-icon">📄</span>' +'<span class="agent-chat__tool-title">' + (L.agentToolResult || "Tool result") + ": " + name + "</span>" +"</div>" +'<pre class="agent-chat__tool-body">' + this.escapeHtml(result) + "</pre>" +"</div>";- const header = el.querySelector(".agent-chat__tool-header") as HTMLElement;- const body = el.querySelector(".agent-chat__tool-body") as HTMLElement;- header.addEventListener("click", function () {- body.classList.toggle("fn__none");- });+ const header = el.querySelector(".agent-chat__tool-header") as HTMLElement;+ const body = el.querySelector(".agent-chat__tool-body") as HTMLElement;+ header.addEventListener("click", function () {+ body.classList.toggle("fn__none");+ });+ }this.insertBeforeAI(el);this.scrollToBottom();}+ private renderTodoList(result: string): string {+ const lines = result.split("\n");+ let html = '<div class="agent-chat__tool-card agent-chat__tool-card--todo">' ++ '<div class="agent-chat__todo-header">' ++ '<span class="agent-chat__tool-icon">📋</span>' ++ '<span class="agent-chat__tool-title">' + (window.siyuan.languages.agentTodoList || "Todo List") + "</span>" ++ "</div>" ++ '<div class="agent-chat__todo-items">';+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ if (line.startsWith("✅")) {+ html += '<div class="agent-chat__todo-item agent-chat__todo-item--completed"><span class="agent-chat__todo-status">✅</span>' + this.escapeHtml(line.substring(1).trim()) + "</div>";+ } else if (line.startsWith("🔄")) {+ html += '<div class="agent-chat__todo-item agent-chat__todo-item--in-progress"><span class="agent-chat__todo-status">🔄</span>' + this.escapeHtml(line.substring(1).trim()) + "</div>";+ } else if (line.startsWith("❌")) {+ html += '<div class="agent-chat__todo-item agent-chat__todo-item--cancelled"><span class="agent-chat__todo-status">❌</span>' + this.escapeHtml(line.substring(1).trim()) + "</div>";+ } else if (line.startsWith("○")) {+ html += '<div class="agent-chat__todo-item agent-chat__todo-item--pending"><span class="agent-chat__todo-status">○</span>' + this.escapeHtml(line.substring(1).trim()) + "</div>";+ }+ }+ html += "</div></div>";+ return html;+ }+private appendThinking(reasoning: string) {const L = window.siyuan.languages;let text = reasoning;diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 203e3cf955..2ec9b37f23 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -52,6 +52,14 @@ const systemPrompt = `You are a SiYuan AI assistant. You help users manage their- Be concise: summarize key findings rather than repeating large amounts of content.- Use markdown formatting for readability: bullet points, headings, code blocks for technical content.+## Todo Tracking+- For multi-step tasks (3+ distinct steps), use the todo_write tool to create a structured task list before starting work. This helps the user see your progress.+- Each call replaces the entire list. Include all tasks, marking each with the correct status.+- Status values: pending (not started), in_progress (currently working on), completed (done), cancelled (no longer needed).+- Mark a task as in_progress before starting work on it, and completed immediately after finishing.+- Update the todo list whenever status changes — call todo_write with the updated list.+- Skip todo_write for simple single-step requests. Only use it when there is meaningful multi-step work to track.+## Safety- Confirm before deleting documents, blocks, or data.- Confirm before moving or renaming important items.@@ -284,7 +292,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session}}- result := executeTool(tc)+ setCurrentTodoSession(sessionID)+ result := executeTool(tc)ch <- AgentEvent{Type: "tool_result",diff --git a/kernel/agent/tools.go b/kernel/agent/tools.goindex 1a96beaacf..ef761a999e 100644--- a/kernel/agent/tools.go+++ b/kernel/agent/tools.go@@ -39,23 +39,14 @@ func convertMCPToolsToOpenAI() []openai.Tool {return result}+func setCurrentTodoSession(sessionID string) {+ tools.SetCurrentTodoSessionID(sessionID)+}+func convertSchema(schema tools.ToolSchema) any {props := make(map[string]any)for name, prop := range schema.Properties {- p := map[string]any{- "type": prop.Type,- }- if prop.Description != "" {- p["description"] = prop.Description- }- if len(prop.Enum) > 0 {- enumVals := make([]any, len(prop.Enum))- for i, v := range prop.Enum {- enumVals[i] = v- }- p["enum"] = enumVals- }- props[name] = p+ props[name] = convertProperty(prop)}schemaMap := map[string]any{@@ -72,6 +63,40 @@ func convertSchema(schema tools.ToolSchema) any {return schemaMap}+func convertProperty(prop tools.Property) map[string]any {+ p := map[string]any{+ "type": prop.Type,+ }+ if prop.Description != "" {+ p["description"] = prop.Description+ }+ if len(prop.Enum) > 0 {+ enumVals := make([]any, len(prop.Enum))+ for i, v := range prop.Enum {+ enumVals[i] = v+ }+ p["enum"] = enumVals+ }+ if prop.Items != nil {+ p["items"] = convertProperty(*prop.Items)+ }+ if len(prop.Properties) > 0 {+ nested := make(map[string]any)+ for k, v := range prop.Properties {+ nested[k] = convertProperty(v)+ }+ p["properties"] = nested+ }+ if len(prop.Required) > 0 {+ reqVals := make([]any, len(prop.Required))+ for i, v := range prop.Required {+ reqVals[i] = v+ }+ p["required"] = reqVals+ }+ return p+}+func executeTool(toolCall openai.ToolCall) string {t, ok := tools.Registry[toolCall.Function.Name]if !ok {diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.goindex 9ad2f297a7..e40c329deb 100644--- a/kernel/mcp/tools/register.go+++ b/kernel/mcp/tools/register.go@@ -17,6 +17,15 @@package toolsvar Registry = map[string]*Tool{}+var currentTodoSessionID string++func SetCurrentTodoSessionID(sessionID string) {+ currentTodoSessionID = sessionID+}++func CurrentTodoSessionID() string {+ return currentTodoSessionID+}func register(t *Tool) {Registry[t.Name] = tdiff --git a/kernel/mcp/tools/todo.go b/kernel/mcp/tools/todo.gonew file mode 100644index 0000000000..7f9821069e--- /dev/null+++ b/kernel/mcp/tools/todo.go@@ -0,0 +1,121 @@+// 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 (+ "fmt"+ "strings"++ "github.com/siyuan-note/siyuan/kernel/model"+)++var TodoWriteTool = &Tool{+ Name: "todo_write",+ Description: "Create and maintain a structured task list for the current session. Use this to track progress during multi-step work. Each call replaces the entire list.\n- todos: Array of todo items, each with: content (task description), status (one of: pending, in_progress, completed, cancelled).",+ InputSchema: ToolSchema{+ Type: "object",+ Properties: map[string]Property{+ "todos": {+ Type: "array", Description: "The updated todo list",+ Items: &Property{+ Type: "object",+ Properties: map[string]Property{+ "content": {Type: "string", Description: "Brief task description"},+ "status": {Type: "string", Description: "Task status", Enum: []string{"pending", "in_progress", "completed", "cancelled"}},+ },+ Required: []string{"content", "status"},+ },+ },+ },+ Required: []string{"todos"},+ },+ Handler: todoWriteHandler,+}++func init() {+ register(TodoWriteTool)+}++func todoWriteHandler(args map[string]interface{}) (CallToolResult, error) {+ rawTodos, ok := args["todos"]+ if !ok {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "todo_write error: missing 'todos' parameter"}},+ IsError: true,+ }, nil+ }++ items, ok := rawTodos.([]interface{})+ if !ok {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "todo_write error: 'todos' must be an array"}},+ IsError: true,+ }, nil+ }++ todos := make([]model.AgentTodoItem, 0, len(items))+ for _, item := range items {+ obj, ok := item.(map[string]interface{})+ if !ok {+ continue+ }+ content, _ := obj["content"].(string)+ status, _ := obj["status"].(string)+ if content == "" {+ continue+ }+ if status != "pending" && status != "in_progress" && status != "completed" && status != "cancelled" {+ status = "pending"+ }+ todos = append(todos, model.AgentTodoItem{Content: content, Status: status})+ }++ // Save todos for this session+ if err := model.SaveAgentTodos(currentTodoSessionID, todos); err != nil {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "todo_write error: " + err.Error()}},+ IsError: true,+ }, nil+ }++ result := formatTodoResult(todos)+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: result}},+ }, nil+}++func formatTodoResult(todos []model.AgentTodoItem) string {+ if len(todos) == 0 {+ return "Todo list is empty."+ }++ var sb strings.Builder+ sb.WriteString("📋 Todo List\n\n")+ for _, t := range todos {+ switch t.Status {+ case "completed":+ sb.WriteString(fmt.Sprintf("✅ %s\n", t.Content))+ case "in_progress":+ sb.WriteString(fmt.Sprintf("🔄 %s\n", t.Content))+ case "cancelled":+ sb.WriteString(fmt.Sprintf("❌ %s\n", t.Content))+ default:+ sb.WriteString(fmt.Sprintf("○ %s\n", t.Content))+ }+ }+ return sb.String()+}diff --git a/kernel/mcp/tools/types.go b/kernel/mcp/tools/types.goindex e113feebdd..737f3c13a8 100644--- a/kernel/mcp/tools/types.go+++ b/kernel/mcp/tools/types.go@@ -30,9 +30,12 @@ type ToolSchema struct {}type Property struct {- Type string `json:"type"`- Description string `json:"description,omitempty"`- Enum []string `json:"enum,omitempty"`+ Type string `json:"type"`+ Description string `json:"description,omitempty"`+ Enum []string `json:"enum,omitempty"`+ Items *Property `json:"items,omitempty"`+ Properties map[string]Property `json:"properties,omitempty"`+ Required []string `json:"required,omitempty"`}type CallToolResult struct {diff --git a/kernel/model/todo.go b/kernel/model/todo.gonew file mode 100644index 0000000000..66bf3ed3fd--- /dev/null+++ b/kernel/model/todo.go@@ -0,0 +1,82 @@+// 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 model++import (+ "encoding/json"+ "os"+ "path/filepath"++ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type AgentTodoItem struct {+ Content string `json:"content"`+ Status string `json:"status"` // pending, in_progress, completed, cancelled+}++type AgentTodoList struct {+ SessionID string `json:"sessionID"`+ Todos []AgentTodoItem `json:"todos"`+}++func agentTodosDir() string {+ return filepath.Join(util.DataDir, "storage", "ai", "agent", "todos")+}++func agentTodosPath(sessionID string) string {+ return filepath.Join(agentTodosDir(), sessionID+".json")+}++func SaveAgentTodos(sessionID string, todos []AgentTodoItem) error {+ dir := agentTodosDir()+ if err := os.MkdirAll(dir, 0755); err != nil {+ return err+ }++ data := AgentTodoList{+ SessionID: sessionID,+ Todos: todos,+ }++ b, err := json.Marshal(data)+ if err != nil {+ return err+ }++ return filelock.WriteFile(agentTodosPath(sessionID), b)+}++func LoadAgentTodos(sessionID string) ([]AgentTodoItem, error) {+ path := agentTodosPath(sessionID)+ if _, err := os.Stat(path); os.IsNotExist(err) {+ return nil, nil+ }++ b, err := filelock.ReadFile(path)+ if err != nil {+ return nil, err+ }++ var data AgentTodoList+ if err := json.Unmarshal(b, &data); err != nil {+ return nil, err+ }++ return data.Todos, nil+}