An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:zap: Improve agent prompt cache reuse https://github.com/siyuan-note/siyuan/issues/18307
Danielfe5eae4ae567
diff --git a/app/src/layout/dock/agent/AgentChat.ts b/app/src/layout/dock/agent/AgentChat.tsindex 945b59a64e..d2c47a5c0c 100644--- a/app/src/layout/dock/agent/AgentChat.ts+++ b/app/src/layout/dock/agent/AgentChat.ts@@ -49,6 +49,7 @@ type UserEntry = EntryBase & {content: string;blockHTML?: string;references?: AgentReference[];+ editorContext?: IEditorContext;timestamp?: number};@@ -1511,6 +1512,7 @@ export class AgentChat extends Model {content: text,blockHTML,references: refs.length > 0 ? refs : undefined,+ editorContext,timestamp: Date.now(),});if (this.entries.length === 1) {@@ -2611,6 +2613,7 @@ export class AgentChat extends Model {const lastUserEntry = targetEntry;const lastUserText = lastUserEntry.content;const editorContext = this.captureEditorContext();+ lastUserEntry.editorContext = editorContext;const pluginActions = this.getPluginActions();this.abortController = new AbortController();const requestSessionId = this.sessionId;diff --git a/app/src/layout/dock/agent/SessionStore.ts b/app/src/layout/dock/agent/SessionStore.tsindex b49d2c8663..410fd3b4e7 100644--- a/app/src/layout/dock/agent/SessionStore.ts+++ b/app/src/layout/dock/agent/SessionStore.ts@@ -55,6 +55,14 @@ export interface AgentSession {content?: string;blockHTML?: string;references?: Array<{id: string; title: string}>;+ editorContext?: {+ activeDocID?: string;+ activeDocTitle?: string;+ notebookID?: string;+ focusedBlockID?: string;+ selectedBlockIDs?: string[];+ visibleBlockIDs?: string[];+ };// thinking step:新格式只含 reasoning/reasoningContent/toolNames/content;// text/toolCalls 仅为读取老数据而保留为可选(渲染时归一化)。steps?: Array<{diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex c8e46f3120..4a4752dd96 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -23,8 +23,8 @@ import ("io""math/rand/v2""os"-"path/filepath"+ "sort""strings""sync""time"@@ -313,10 +313,12 @@ type AgentEvent struct {}type AgentMessage struct {- Role string `json:"role"`- Content string `json:"content"`- ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`- EntryID string `json:"entryID,omitempty"`+ Role string `json:"role"`+ Content string `json:"content"`+ References []Reference `json:"references,omitempty"`+ EditorContext *EditorContext `json:"editorContext,omitempty"`+ ToolCalls []AgentToolCall `json:"toolCalls,omitempty"`+ EntryID string `json:"entryID,omitempty"`}type AgentToolCall struct {@@ -344,6 +346,27 @@ type EditorContext struct {VisibleBlockIDs []string `json:"visibleBlockIDs,omitempty"` // 视口内可见块 ID 列表(已截断至上限)}+func cloneEditorContext(editorCtx EditorContext) *EditorContext {+ if editorCtx.ActiveDocID == "" && editorCtx.ActiveDocTitle == "" && editorCtx.NotebookID == "" &&+ editorCtx.FocusedBlockID == "" && len(editorCtx.SelectedBlockIDs) == 0 && len(editorCtx.VisibleBlockIDs) == 0 {+ return nil+ }+ cloned := editorCtx+ cloned.SelectedBlockIDs = append([]string(nil), editorCtx.SelectedBlockIDs...)+ cloned.VisibleBlockIDs = append([]string(nil), editorCtx.VisibleBlockIDs...)+ return &cloned+}++func newAgentUserMessage(content, entryID string, references []Reference, editorCtx EditorContext) AgentMessage {+ return AgentMessage{+ Role: "user",+ Content: content,+ References: append([]Reference(nil), references...),+ EditorContext: cloneEditorContext(editorCtx),+ EntryID: entryID,+ }+}+// PluginAction describes a frontend action registered by a plugin (via Plugin.addAction()).// The frontend serializes the list of currently-registered plugin actions into each chat// request, and the backend injects them into the system prompt so the LLM can discover and@@ -360,6 +383,7 @@ type SessionEntry struct {Type string `json:"type"` // user|thinking|assistant|confirm|snapshot|rollbackContent string `json:"content,omitempty"`References []Reference `json:"references,omitempty"`+ EditorContext *EditorContext `json:"editorContext,omitempty"`BlockHTML string `json:"blockHTML,omitempty"` // 仅 user,用于保留发送框的 BlockDOM 展示结构Steps []SessionEntryStep `json:"steps,omitempty"` // 仅 thinkingToolCalls []AgentToolCall `json:"toolCalls,omitempty"` // 仅 assistant@@ -483,9 +507,17 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session}checkpointMsgs = truncatedif regenerate || !currentUserExists {- checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "user", Content: userMessage, EntryID: userEntryID})+ checkpointMsgs = append(checkpointMsgs, newAgentUserMessage(userMessage, userEntryID, references, editorCtx))+ } else {+ for i := len(checkpointMsgs) - 1; i >= 0; i-- {+ if checkpointMsgs[i].Role == "user" {+ checkpointMsgs[i].References = append([]Reference(nil), references...)+ checkpointMsgs[i].EditorContext = cloneEditorContext(editorCtx)+ break+ }+ }}- messages = checkpointMessagesToOpenAI(checkpointMsgs, language, references, editorCtx, pluginActions)+ messages = checkpointMessagesToOpenAI(checkpointMsgs, language, pluginActions)}}if runtime, err := loadRuntimeState(sessionID); err == nil && runtime != nil && runtime.AlwaysAllow {@@ -494,7 +526,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session}if messages == nil {- checkpointMsgs = []AgentMessage{{Role: "user", Content: userMessage, EntryID: userEntryID}}+ checkpointMsgs = []AgentMessage{newAgentUserMessage(userMessage, userEntryID, references, editorCtx)}messages = buildInitialMessages(userMessage, language, references, editorCtx, pluginActions)}@@ -513,6 +545,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionturn.UserContent = rawUserMessageuserReferences := append([]Reference(nil), references...)turn.UserReferences = &userReferences+ turn.UserEditorContext = cloneEditorContext(editorCtx)}select {case <-ctx.Done():@@ -1292,7 +1325,7 @@ func finishFrontendWait(callID string, ch chan frontendCallResult) (frontendCall}}-func buildSystemPrompt(language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction) string {+func buildSystemPrompt(language string, pluginActions []PluginAction) string {var sb strings.Buildersb.WriteString(systemPrompt)sb.WriteString("\n\n<env>\nWorkspace: ")@@ -1323,6 +1356,10 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editor}if len(pluginActions) > 0 {+ pluginActions = append([]PluginAction(nil), pluginActions...)+ sort.Slice(pluginActions, func(i, j int) bool {+ return pluginActions[i].Name < pluginActions[j].Name+ })sb.WriteString("\n\n<plugin_actions>\n")sb.WriteString("The following frontend actions were registered by plugins. Invoke them via the \"frontend\" tool with action set to the full name shown below.\n")for _, a := range pluginActions {@@ -1345,8 +1382,18 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editorsb.WriteString("\n\nIn the user's language, a daily note is called: ")sb.WriteString(util.I18nTerm(language, "dailyNote"))sb.WriteString(". When the user asks to write or create this, use dailynote.create, not document.create.")+ return sb.String()+}++func buildUserMessageContent(userMessage string, references []Reference, editorCtx *EditorContext) string {+ if len(references) == 0 && editorCtx == nil {+ return userMessage+ }++ var sb strings.Builder+ sb.WriteString("<turn_context>\n")if len(references) > 0 {- sb.WriteString("\n\nThe user has referenced the following content blocks:\n")+ sb.WriteString("The user referenced the following content blocks when sending this message:\n")for _, ref := range references {sb.WriteString("- ")sb.WriteString(ref.Title)@@ -1354,11 +1401,10 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editorsb.WriteString(ref.ID)sb.WriteString(")\n")}- sb.WriteString("Use the block tools to fetch their actual content before responding.")+ sb.WriteString("Use the block tools to fetch their actual content before responding.\n")}- if editorCtx.ActiveDocID != "" || editorCtx.ActiveDocTitle != "" || editorCtx.NotebookID != "" ||- len(editorCtx.SelectedBlockIDs) > 0 || editorCtx.FocusedBlockID != "" || len(editorCtx.VisibleBlockIDs) > 0 {- sb.WriteString("\n\n<editor_context>\n")+ if editorCtx != nil {+ sb.WriteString("<editor_context>\n")sb.WriteString("This is the user's editor state at the moment they sent the message. It may be stale by now.\n")if editorCtx.ActiveDocID != "" || editorCtx.ActiveDocTitle != "" {sb.WriteString("Active document: ")@@ -1420,13 +1466,15 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editorsb.WriteString("Use the block tools (e.g. block with action \"get\") to fetch actual content before responding.")sb.WriteString("\n</editor_context>")}+ sb.WriteString("\n</turn_context>\n\n")+ sb.WriteString(userMessage)return sb.String()}func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction) []openai.ChatCompletionMessage {return []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, references, editorCtx, pluginActions)},- {Role: openai.ChatMessageRoleUser, Content: userMessage},+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, pluginActions)},+ {Role: openai.ChatMessageRoleUser, Content: buildUserMessageContent(userMessage, references, cloneEditorContext(editorCtx))},}}@@ -1492,7 +1540,16 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {e := &entries[i]switch e.Type {case "user":- msgs = append(msgs, AgentMessage{Role: "user", Content: e.Content, EntryID: e.ID})+ m := AgentMessage{+ Role: "user",+ Content: e.Content,+ References: append([]Reference(nil), e.References...),+ EntryID: e.ID,+ }+ if e.EditorContext != nil {+ m.EditorContext = cloneEditorContext(*e.EditorContext)+ }+ msgs = append(msgs, m)case "assistant":m := AgentMessage{Role: "assistant", Content: e.Content, EntryID: e.ID}if len(e.ToolCalls) > 0 {@@ -1510,16 +1567,16 @@ func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {return msgs}-func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction) []openai.ChatCompletionMessage {+func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, pluginActions []PluginAction) []openai.ChatCompletionMessage {msgs := []openai.ChatCompletionMessage{- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, references, editorCtx, pluginActions)},+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, pluginActions)},}for cmi := range checkpointMsgs {cm := &checkpointMsgs[cmi]switch cm.Role {case "user":- content := cm.Content+ content := buildUserMessageContent(cm.Content, cm.References, cm.EditorContext)if content == "" {content = " "}@@ -1594,10 +1651,16 @@ func agentMessagesToEntries(msgs []AgentMessage) []SessionEntry {if id == "" {id = fmt.Sprintf("cp_%d", i)}+ var editorCtx *EditorContext+ if m.EditorContext != nil {+ editorCtx = cloneEditorContext(*m.EditorContext)+ }entries = append(entries, SessionEntry{- ID: id,- Type: "user",- Content: m.Content,+ ID: id,+ Type: "user",+ Content: m.Content,+ References: append([]Reference(nil), m.References...),+ EditorContext: editorCtx,})case "assistant":id := m.EntryIDdiff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.gonew file mode 100644index 0000000000..530561d0aa--- /dev/null+++ b/kernel/agent/prompt_test.go@@ -0,0 +1,112 @@+// 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.++package agent++import (+ "strings"+ "testing"+)++func TestTurnContextStaysInUserMessage(t *testing.T) {+ const userMessage = "summarize this"+ references := []Reference{{ID: "ref-block", Title: "Referenced block"}}+ editorCtx := EditorContext{+ ActiveDocID: "active-doc",+ ActiveDocTitle: "Active document",+ FocusedBlockID: "focused-block",+ SelectedBlockIDs: []string{"selected-block"},+ }++ messages := buildInitialMessages(userMessage, "English", references, editorCtx, nil)+ if len(messages) != 2 {+ t.Fatalf("unexpected message count: %d", len(messages))+ }+ systemContent := messages[0].Content+ for _, marker := range []string{"ref-block", "active-doc", "focused-block", "selected-block"} {+ if strings.Contains(systemContent, marker) {+ t.Fatalf("turn context %q leaked into system prompt", marker)+ }+ if !strings.Contains(messages[1].Content, marker) {+ t.Fatalf("turn context %q is missing from user message", marker)+ }+ }+ if !strings.HasSuffix(messages[1].Content, userMessage) {+ t.Fatalf("raw user message is not preserved at the end: %q", messages[1].Content)+ }+}++func TestSystemPromptSortsPluginActions(t *testing.T) {+ actions := []PluginAction{+ {Name: "plugin__z__run", Description: "Run Z"},+ {Name: "plugin__a__run", Description: "Run A"},+ }++ forward := buildSystemPrompt("English", actions)+ reversed := buildSystemPrompt("English", []PluginAction{actions[1], actions[0]})+ if forward != reversed {+ t.Fatal("plugin action order changed the system prompt")+ }+ if strings.Index(forward, actions[1].Name) > strings.Index(forward, actions[0].Name) {+ t.Fatalf("plugin actions are not sorted in system prompt: %q", forward)+ }+}++func TestCheckpointMessagesKeepHistoricalTurnContexts(t *testing.T) {+ checkpoint := []AgentMessage{+ newAgentUserMessage("first question", "user-1", nil, EditorContext{ActiveDocID: "doc-a"}),+ {Role: "assistant", Content: "first answer", EntryID: "assistant-1"},+ newAgentUserMessage("second question", "user-2", nil, EditorContext{ActiveDocID: "doc-b"}),+ }++ messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)+ if len(messages) != 4 {+ t.Fatalf("unexpected message count: %d", len(messages))+ }+ if strings.Contains(messages[0].Content, "doc-a") || strings.Contains(messages[0].Content, "doc-b") {+ t.Fatalf("historical editor context leaked into system prompt: %q", messages[0].Content)+ }+ if !strings.Contains(messages[1].Content, "doc-a") || strings.Contains(messages[1].Content, "doc-b") {+ t.Fatalf("first user message has the wrong editor context: %q", messages[1].Content)+ }+ if !strings.Contains(messages[3].Content, "doc-b") || strings.Contains(messages[3].Content, "doc-a") {+ t.Fatalf("second user message has the wrong editor context: %q", messages[3].Content)+ }+}++func TestUserTurnContextSurvivesCheckpointRoundTrip(t *testing.T) {+ editorCtx := &EditorContext{+ ActiveDocID: "round-trip-doc",+ VisibleBlockIDs: []string{"visible-block"},+ }+ entries := []SessionEntry{{+ ID: "user-1",+ Type: "user",+ Content: "question",+ References: []Reference{{ID: "round-trip-ref", Title: "Reference"}},+ EditorContext: editorCtx,+ }}++ checkpoint := entriesToAgentMessages(entries)+ if len(checkpoint) != 1 || checkpoint[0].EditorContext == nil {+ t.Fatalf("entry context was not restored into checkpoint: %#v", checkpoint)+ }+ roundTripped := agentMessagesToEntries(checkpoint)+ if len(roundTripped) != 1 || roundTripped[0].EditorContext == nil {+ t.Fatalf("checkpoint context was not persisted into entry: %#v", roundTripped)+ }+ if roundTripped[0].EditorContext.ActiveDocID != "round-trip-doc" ||+ len(roundTripped[0].References) != 1 || roundTripped[0].References[0].ID != "round-trip-ref" {+ t.Fatalf("turn context changed during checkpoint round trip: %#v", roundTripped[0])+ }++ checkpoint[0].EditorContext.VisibleBlockIDs[0] = "changed"+ if editorCtx.VisibleBlockIDs[0] != "visible-block" || roundTripped[0].EditorContext.VisibleBlockIDs[0] != "visible-block" {+ t.Fatal("editor context slices were not cloned")+ }+}diff --git a/kernel/agent/runtime.go b/kernel/agent/runtime.goindex 54bcd7032f..53fea75875 100644--- a/kernel/agent/runtime.go+++ b/kernel/agent/runtime.go@@ -47,6 +47,7 @@ type agentRuntimeTurn struct {TargetUserEntryID string `json:"targetUserEntryID,omitempty"`UserContent string `json:"userContent,omitempty"`UserReferences *[]Reference `json:"userReferences,omitempty"`+ UserEditorContext *EditorContext `json:"userEditorContext,omitempty"`BaseRevision int64 `json:"baseRevision"`State string `json:"state"`Delta []AgentMessage `json:"delta,omitempty"`@@ -332,6 +333,11 @@ func applyRuntimeTurnToSessionLocked(session map[string]any, turn *agentRuntimeTdelete(entry, "references")}}+ if turn.UserEditorContext != nil {+ entry["editorContext"] = turn.UserEditorContext+ } else {+ delete(entry, "editorContext")+ }}// 当前 turn 的 assistant 内容以 runtime 为权威;前端只补充 thinking/confirm/question 等 UI 条目。diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.goindex fbb4186a5d..fe40d8bfa5 100644--- a/kernel/agent/session_test.go+++ b/kernel/agent/session_test.go@@ -299,7 +299,8 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "original prompt",- "references": []any{map[string]any{"id": "block-1", "title": "First block"}},+ "references": []any{map[string]any{"id": "block-1", "title": "First block"}},+ "editorContext": map[string]any{"activeDocID": "old-doc"},},map[string]any{"id": "assistant-1", "type": "assistant", "content": "old answer"},map[string]any{"id": "user-2", "type": "user", "content": "later prompt"},@@ -325,6 +326,7 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {}emptyReferences := []Reference{}turn.UserReferences = &emptyReferences+ turn.UserEditorContext = &EditorContext{ActiveDocID: "new-doc"}if err := beginRuntimeTurn(testSessionID, turn, false); err != nil {t.Fatal(err)}@@ -345,6 +347,10 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {if _, ok := entries[0].(map[string]any)["references"]; ok {t.Fatalf("references removed by the edit were restored: %#v", entries[0])}+ editorContext := entries[0].(map[string]any)["editorContext"].(*EditorContext)+ if editorContext.ActiveDocID != "new-doc" {+ t.Fatalf("regenerated editor context was not restored: %#v", entries[0])+ }recovered["expectedRevision"] = int64(1)revision, canonical, err := SaveSessionState(marshalSession(t, recovered))if err != nil || revision != 2 {@@ -354,6 +360,19 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {if len(committedEntries) != 2 || committedEntries[0].(map[string]any)["content"] != "edited prompt" {t.Fatalf("committed regenerate turn lost edited content: %#v", committedEntries)}+ committedEditorContext := committedEntries[0].(map[string]any)["editorContext"].(*EditorContext)+ if committedEditorContext.ActiveDocID != "new-doc" {+ t.Fatalf("committed regenerate turn lost editor context: %#v", committedEntries[0])+ }+ persisted, err := GetSession(testSessionID)+ if err != nil {+ t.Fatal(err)+ }+ persistedEntries := persisted["entries"].([]any)+ persistedEditorContext := persistedEntries[0].(map[string]any)["editorContext"].(map[string]any)+ if persistedEditorContext["activeDocID"] != "new-doc" {+ t.Fatalf("persisted regenerate turn lost editor context: %#v", persistedEntries[0])+ }}func TestRejectedNewSessionDoesNotCreateDirectory(t *testing.T) {diff --git a/kernel/mcp/tools/register.go b/kernel/mcp/tools/register.goindex 24da2aee96..529e7b6dc0 100644--- a/kernel/mcp/tools/register.go+++ b/kernel/mcp/tools/register.go@@ -17,6 +17,7 @@package toolsimport (+ "sort""strings""sync")@@ -64,6 +65,9 @@ func GetAllTools() []*Tool {for _, t := range Registry {result = append(result, t)}+ sort.Slice(result, func(i, j int) bool {+ return result[i].Name < result[j].Name+ })return result}diff --git a/kernel/mcp/tools/register_test.go b/kernel/mcp/tools/register_test.gonew file mode 100644index 0000000000..8450a34214--- /dev/null+++ b/kernel/mcp/tools/register_test.go@@ -0,0 +1,28 @@+// 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 "testing"++func TestGetAllToolsSorted(t *testing.T) {+ allTools := GetAllTools()+ for i := 1; i < len(allTools); i++ {+ if allTools[i-1].Name > allTools[i].Name {+ t.Fatalf("tools are not sorted: %q appears before %q", allTools[i-1].Name, allTools[i].Name)+ }+ }+}