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
Daniel325f68c8b587
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.tsindex b8761336a0..b664ff195b 100644--- a/app/src/layout/dock/AgentChat.ts+++ b/app/src/layout/dock/AgentChat.ts@@ -4,6 +4,8 @@ import {App} from "../../index";import {fetchAgentSSE, IEditorContext, ISSEResult} from "../../util/agentSSE";import {mountComposer} from "./AgentComposer";import {getAllEditor} from "../getAll";+import "./frontendActions";+import {lookupAction} from "./frontendActions";import {AgentSession, SessionStore} from "./SessionStore";import {AgentSessionPanel} from "./AgentSessionPanel";import {getDockByType} from "../tabUtil";@@ -1075,6 +1077,9 @@ export class AgentChat extends Model {this.appendSnapshotInfo(event.snapshotID, snapshotEntryId);}break;+ case "frontend_tool_call":+ this.handleFrontendToolCall(event.callID, event.arguments);+ break;}} catch (e) {console.error("agent SSE event handler error:", e, event);@@ -1837,6 +1842,39 @@ export class AgentChat extends Model {await this.saveSession();}+ private async handleFrontendToolCall(callID: string, args: Record<string, unknown>) {+ // Resolve the action name ("frontend" tool calls carry the action in args.action).+ const action = (args.action as string | undefined) || "";+ const handler = lookupAction(action);+ if (!handler) {+ await this.postFrontendResult(callID, `Unknown frontend action: ${action}`, true);+ return;+ }+ try {+ const outcome = await handler.handler(args, this.app);+ const result = outcome.result || "";+ const error = outcome.error || "";+ await this.postFrontendResult(callID, error ? error : result, !!error);+ } catch (e) {+ await this.postFrontendResult(callID, `Frontend action threw: ${(e as Error).message}`, true);+ }+ }++ private async postFrontendResult(callID: string, result: string, isError: boolean) {+ try {+ const resp = await fetch("/api/ai/agent/frontendToolResult", {+ method: "POST",+ headers: {"Content-Type": "application/json"},+ body: JSON.stringify({callID, result, isError}),+ });+ if (!resp.ok) {+ console.error("agent frontend result request failed:", resp.status);+ }+ } catch (e) {+ console.error("agent frontend result request error:", e);+ }+ }+private appendQuestion(questionID: string, args: Record<string, unknown>) {this.finishActiveThinking();this.flushThinkingStep();diff --git a/app/src/layout/dock/frontendActions.ts b/app/src/layout/dock/frontendActions.tsnew file mode 100644index 0000000000..09d92d03b5--- /dev/null+++ b/app/src/layout/dock/frontendActions.ts@@ -0,0 +1,131 @@+// 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/>.++import type {App} from "../../index";++export interface IAction {+ name: string;+ handler: (args: Record<string, unknown>, app: App) => Promise<{result?: string; error?: string}>;+}++// Centralized action registry. Data structure is a registry so that plugins can register their+// own frontend actions in a future version (via Plugin.addAction() -> registerAction). The first+// version only loads built-in actions, but the lookup layer is already registry-shaped, so adding+// plugin support later requires zero changes to the dispatch path.+//+// IMPORTANT: this module must NOT have any top-level value imports beyond the registry itself.+// The built-in actions below pull in config/editor/search modules that participate in import+// cycles with the layout/plugin graph, so they are loaded lazily via dynamic import() inside the+// handlers (which are async). This keeps `import {lookupAction}` cycle-free.+const actionRegistry = new Map<string, IAction>();++export const registerAction = (a: IAction) => {+ actionRegistry.set(a.name, a);+};++export const lookupAction = (name: string): IAction | undefined => actionRegistry.get(name);++/// #if !MOBILE+registerAction({+ name: "open_setting",+ handler: async (args, app) => {+ const query = (args.query as string | undefined)?.trim();+ const {openSetting} = await import("../../config");+ // openSetting() has a quirk: if a settings dialog already exists, it DESTROYS it and+ // returns the destroyed dialog (the splice from window.siyuan.dialogs is deferred via+ // setTimeout, so it can't be detected synchronously). To guarantee the panel is visible+ // after this call, check first: if one is already open, reuse it; otherwise open fresh.+ const existing = window.siyuan.dialogs.find(d => d.element.querySelector(".config__tab-container"));+ let dialog = existing;+ if (!dialog) {+ dialog = openSetting(app);+ }+ if (query) {+ // The settings panel has a built-in search box (wired by initConfigSearch in+ // config/index.ts). Fill it and dispatch an "input" event to trigger live filtering,+ // which surfaces matching config items.+ const input = dialog.element.querySelector(".config__side .b3-text-field") as HTMLInputElement;+ if (input) {+ input.value = query;+ input.dispatchEvent(new Event("input", {bubbles: true}));+ }+ return {result: `Opened the settings panel and filtered by "${query}".`};+ }+ return {result: "Opened the settings panel."};+ },+});++registerAction({+ name: "focus_block",+ handler: async (args) => {+ const id = args.id as string | undefined;+ if (!id) {+ return {error: "missing required argument: id"};+ }+ const {getAllEditor} = await import("../getAll");+ // Find the editor whose document contains this block, then scroll it into view.+ let blockEl: HTMLElement | null = null;+ for (const editor of getAllEditor()) {+ const el = editor.protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) as HTMLElement | null;+ if (el) {+ blockEl = el;+ break;+ }+ }+ if (!blockEl) {+ return {error: `Block ${id} is not loaded in any open editor. Use open_document to open it first.`};+ }+ blockEl.scrollIntoView({behavior: "smooth", block: "center"});+ // Briefly highlight the block so the user can spot it.+ blockEl.classList.add("protyle-wysiwyg--hl");+ setTimeout(() => blockEl?.classList.remove("protyle-wysiwyg--hl"), 2000);+ return {result: `Focused block ${id} in the active editor.`};+ },+});++registerAction({+ name: "open_document",+ handler: async (args, app) => {+ const id = args.id as string | undefined;+ if (!id) {+ return {error: "missing required argument: id"};+ }+ try {+ const [{openFileById}, {Constants}] = await Promise.all([+ import("../../editor/util"),+ import("../../constants"),+ ]);+ await openFileById({app, id, action: [Constants.CB_GET_FOCUS]});+ return {result: `Opened document ${id}.`};+ } catch (e) {+ return {error: `Failed to open document ${id}: ${(e as Error).message}`};+ }+ },+});++registerAction({+ name: "open_search",+ handler: async (args, app) => {+ const query = (args.query as string | undefined)?.trim();+ const [{openSearch}, {Constants}] = await Promise.all([+ import("../../search/spread"),+ import("../../constants"),+ ]);+ await openSearch({app, hotkey: Constants.DIALOG_GLOBALSEARCH, key: query});+ return {result: query ? `Opened search dialog with query "${query}".` : "Opened search dialog."};+ },+});+/// #endifdiff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.tsindex db5c86cb87..f492731850 100644--- a/app/src/util/agentSSE.ts+++ b/app/src/util/agentSSE.ts@@ -40,6 +40,11 @@ export type ISSEResult = {} | {type: "snapshot";snapshotID: string;+} | {+ type: "frontend_tool_call";+ callID: string;+ name: string;+ arguments: Record<string, unknown>;};export type IEditorContext = {@@ -206,6 +211,13 @@ function buildSSEResult(event: string, data: Record<string, unknown>): ISSEResulreturn {type: "reasoning", token: data.token as string};case "snapshot":return {type: "snapshot", snapshotID: data.snapshotID as string};+ case "frontend_tool_call":+ return {+ type: "frontend_tool_call",+ callID: data.callID as string,+ name: data.name as string,+ arguments: (data.arguments || {}) as Record<string, unknown>,+ };default:return null;}diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex b134a321f2..a4f8325308 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -153,6 +153,26 @@ func AnswerQuestion(id string, answers []string) {}}+// frontendCallResult carries the result of a frontend tool action back from the browser.+type frontendCallResult struct {+ result string+ isError bool+}++var frontendCallChannelsMu sync.Mutex+var frontendCallChannels = make(map[string]chan frontendCallResult)++// FrontendToolResult is called by the API handler when the browser POSTs the outcome of a+// frontend tool action. It unblocks the agent goroutine waiting in handleFrontendTool.+func FrontendToolResult(callID string, result string, isError bool) {+ frontendCallChannelsMu.Lock()+ ch, ok := frontendCallChannels[callID]+ frontendCallChannelsMu.Unlock()+ if ok {+ ch <- frontendCallResult{result: result, isError: isError}+ }+}+func sendEvent(ch chan<- AgentEvent, ev AgentEvent) {select {case ch <- ev:@@ -181,6 +201,7 @@ type AgentEvent struct {Reasoning stringConfirmID stringQuestionID string+ CallID stringError stringPromptTokens intCompletionTokens int@@ -543,7 +564,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session}}- if !snapshotCreated && action != "" && !safeActions[action] && !(tc.Function.Name == "repo" && action == "create") {+ if !snapshotCreated && action != "" && !safeActions[action] && tc.Function.Name != "frontend" && !(tc.Function.Name == "repo" && action == "create") {id, err := kernelModel.IndexRepo("AI agent auto snapshot")if err != nil {logging.LogErrorf("agent auto snapshot failed: %s", err)@@ -582,6 +603,9 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, sessionif tc.Function.Name == "question" {resultStr = handleQuestion(ctx, tc.Function.Arguments, ch, 5*time.Minute)doomLoop = doomLoopTracker{}+ } else if tc.Function.Name == "frontend" {+ resultStr = handleFrontendTool(ctx, tc, ch, confirmTimeout)+ doomLoop = doomLoopTracker{}} else {resultStr = executeTool(tc, sessionID)}@@ -602,7 +626,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session})checkpointMsgs[assistantIdx].ToolCalls[i].Result = resultStr- if tc.Function.Name != "question" {+ if tc.Function.Name != "question" && tc.Function.Name != "frontend" {sig := tc.Function.Name + "::action=" + actionif sig == doomLoop.prevSig && doomLoop.prevSig != "" {doomLoop.count++@@ -774,6 +798,54 @@ func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent,return strings.Join(answer.Answers, ", ")}+// handleFrontendTool dispatches a frontend tool action to the browser via SSE and blocks until+// the browser POSTs the result (or the context is cancelled / timeout fires). It mirrors+// handleQuestion's structure exactly — the only difference is the channel registry and the+// event type ("frontend_tool_call").+func handleFrontendTool(ctx context.Context, tc openai.ToolCall, ch chan<- AgentEvent, timeout time.Duration) string {+ args := parseToolArgs(tc.Function.Arguments)+ callID := fmt.Sprintf("%d", time.Now().UnixNano())+ if len(callID) > 12 {+ callID = callID[:12]+ }++ sendCriticalEvent(ctx, ch, AgentEvent{+ Type: "frontend_tool_call",+ CallID: callID,+ Name: tc.Function.Name,+ Arguments: args,+ })++ ch2 := make(chan frontendCallResult, 1)+ frontendCallChannelsMu.Lock()+ frontendCallChannels[callID] = ch2+ frontendCallChannelsMu.Unlock()++ var fr frontendCallResult+ select {+ case fr = <-ch2:+ case <-ctx.Done():+ frontendCallChannelsMu.Lock()+ delete(frontendCallChannels, callID)+ frontendCallChannelsMu.Unlock()+ return "Frontend action cancelled."+ case <-time.After(timeout):+ frontendCallChannelsMu.Lock()+ delete(frontendCallChannels, callID)+ frontendCallChannelsMu.Unlock()+ return "Frontend action timed out (no response from the editor)."+ }++ frontendCallChannelsMu.Lock()+ delete(frontendCallChannels, callID)+ frontendCallChannelsMu.Unlock()++ if fr.isError {+ return "Frontend action failed: " + fr.result+ }+ return fr.result+}+func buildSystemPrompt(language string, references []Reference, editorCtx EditorContext) string {var sb strings.Buildersb.WriteString(systemPrompt)diff --git a/kernel/api/agent.go b/kernel/api/agent.goindex 47aafb265c..7da5196840 100644--- a/kernel/api/agent.go+++ b/kernel/api/agent.go@@ -189,6 +189,26 @@ func agentChatQuestion(c *gin.Context) {c.JSON(http.StatusOK, ret)}+type agentFrontendResultReq struct {+ CallID string `json:"callID"`+ Result string `json:"result"`+ IsError bool `json:"isError"`+}++func agentChatFrontendResult(c *gin.Context) {+ req := &agentFrontendResultReq{}+ if err := c.ShouldBindJSON(req); err != nil {+ ret := gulu.Ret.NewResult()+ ret.Code = -1+ ret.Msg = "invalid request: " + err.Error()+ c.JSON(http.StatusOK, ret)+ return+ }+ agent.FrontendToolResult(req.CallID, req.Result, req.IsError)+ ret := gulu.Ret.NewResult()+ c.JSON(http.StatusOK, ret)+}+type agentTitleReq struct {Message string `json:"message"`Model string `json:"model"`@@ -354,6 +374,12 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {"questionID": event.QuestionID,"arguments": event.Arguments,})+ case "frontend_tool_call":+ return writeSSEEvent(c, "frontend_tool_call", map[string]interface{}{+ "callID": event.CallID,+ "name": event.Name,+ "arguments": event.Arguments,+ })case "snapshot":return writeSSEEvent(c, "snapshot", map[string]string{"snapshotID": event.SnapshotID})}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 184782a1b9..d4d9cb5651 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -528,6 +528,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/ai/agent/chat", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChat)ginServer.Handle("POST", "/api/ai/agent/confirm", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatConfirm)ginServer.Handle("POST", "/api/ai/agent/question", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatQuestion)+ ginServer.Handle("POST", "/api/ai/agent/frontendToolResult", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, agentChatFrontendResult)ginServer.Handle("POST", "/api/ai/agent/title", model.CheckAuth, model.CheckAdminRole, agentChatTitle)ginServer.Handle("POST", "/api/ai/agent/lsSessions", model.CheckAuth, model.CheckAdminRole, lsSessions)ginServer.Handle("POST", "/api/ai/agent/getSession", model.CheckAuth, model.CheckAdminRole, getSession)diff --git a/kernel/mcp/tools/frontend.go b/kernel/mcp/tools/frontend.gonew file mode 100644index 0000000000..5cae1bc1ec--- /dev/null+++ b/kernel/mcp/tools/frontend.go@@ -0,0 +1,52 @@+// 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++// FrontendTool exposes UI actions (open settings, focus block, open document, open search) to+// the agent. The Handler is a fallback stub: in the agent loop, "frontend" tool calls are+// special-cased and dispatched to agent.handleFrontendTool, which streams the action to the+// browser over SSE and blocks until the browser responds. The stub exists only so that+// convertMCPToolsToOpenAI() lists this tool for the LLM.+var FrontendTool = &Tool{+ Name: "frontend",+ Description: "Frontend/UI actions in the SiYuan editor. These execute in the browser and may change what the user sees (open panels, scroll, navigate). The result tells you whether the action succeeded.\n" ++ "- open_setting: Open the settings panel. Optional: query (search keyword to filter config items and locate a specific setting).\n" ++ "- focus_block: Scroll the active editor to focus a specific block. Requires: id (block ID).\n" ++ "- open_document: Open a document by its root block ID in a new tab. Requires: id.\n" ++ "- open_search: Open the global search dialog. Optional: query (pre-filled search keyword).",+ InputSchema: ToolSchema{+ Type: "object",+ Properties: map[string]Property{+ "action": {Type: "string", Description: "Operation", Enum: []string{"open_setting", "focus_block", "open_document", "open_search"}},+ "id": {Type: "string", Description: "Block or document ID (for focus_block and open_document)"},+ "query": {Type: "string", Description: "Search keyword (for open_setting to locate a config item, for open_search to pre-fill the search box)"},+ },+ Required: []string{"action"},+ },+ Handler: frontendHandler,+}++func init() {+ register(FrontendTool)+}++func frontendHandler(args map[string]interface{}) (CallToolResult, error) {+ return CallToolResult{+ Content: []ContentItem{{Type: "text", Text: "frontend actions are only available in the interactive agent chat (not via direct tool invocation)"}},+ IsError: true,+ }, nil+}