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

Daniela285d9469f77
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts
index b664ff195b..b1170af758 100644
--- a/app/src/layout/dock/AgentChat.ts
+++ b/app/src/layout/dock/AgentChat.ts
@@ -5,7 +5,7 @@ import {fetchAgentSSE, IEditorContext, ISSEResult} from "../../util/agentSSE";
import {mountComposer} from "./AgentComposer";
import {getAllEditor} from "../getAll";
import "./frontendActions";
-import {lookupAction} from "./frontendActions";
+import {listActions, lookupAction} from "./frontendActions";
import {AgentSession, SessionStore} from "./SessionStore";
import {AgentSessionPanel} from "./AgentSessionPanel";
import {getDockByType} from "../tabUtil";
@@ -836,6 +836,9 @@ export class AgentChat extends Model {
const text = sendData.text;
const refs = sendData.references;
const editorContext = this.captureEditorContext();
+ const pluginActions = listActions()
+ .filter(a => a.name.startsWith("plugin__") && a.description)
+ .map(a => ({name: a.name, description: a.description as string}));
if (!text || this.isStreaming) {
return;
}
@@ -884,6 +887,7 @@ export class AgentChat extends Model {
this.getSelectedModel(),
undefined,
editorContext,
+ pluginActions,
);
}
diff --git a/app/src/layout/dock/frontendActions.ts b/app/src/layout/dock/frontendActions.ts
index 09d92d03b5..02b5da3e77 100644
--- a/app/src/layout/dock/frontendActions.ts
+++ b/app/src/layout/dock/frontendActions.ts
@@ -18,6 +18,7 @@ import type {App} from "../../index";
export interface IAction {
name: string;
+ description?: string;
handler: (args: Record<string, unknown>, app: App) => Promise<{result?: string; error?: string}>;
}
@@ -38,6 +39,12 @@ export const registerAction = (a: IAction) => {
export const lookupAction = (name: string): IAction | undefined => actionRegistry.get(name);
+export const listActions = (): IAction[] => Array.from(actionRegistry.values());
+
+export const unregisterAction = (name: string) => {
+ actionRegistry.delete(name);
+};
+
/// #if !MOBILE
registerAction({
name: "open_setting",
diff --git a/app/src/plugin/index.ts b/app/src/plugin/index.ts
index d86ccec045..955b4a36f0 100644
--- a/app/src/plugin/index.ts
+++ b/app/src/plugin/index.ts
@@ -23,6 +23,7 @@ import {uninstall} from "./uninstall";
import {addPluginDock, afterLoadPlugin, loadPlugins} from "./loader";
import {normalizeStoragePath} from "../util/pathName";
import {Kernel} from "./kernel";
+import {registerAction} from "../layout/dock/frontendActions";
export class Plugin {
private app: App;
@@ -51,6 +52,9 @@ export class Plugin {
public setting: Setting;
public statusBarIcons: Element[] = [];
public commands: ICommand[] = [];
+ // Full names of agent actions this plugin registered (plugin__<name>__<action>), tracked
+ // so they can be unregistered on uninstall.
+ public agentActions: string[] = [];
public models: {
/// #if !MOBILE
[key: string]: (options: { tab: Tab, data: any }) => Custom
@@ -410,6 +414,22 @@ export class Plugin {
/// #endif
}
+ // Register a frontend action that the AI agent can discover and invoke. The action is exposed
+ // to the LLM under the full name "plugin__<pluginName>__<name>" with the given description, and
+ // is dispatched via the "frontend" tool. On uninstall, all registered actions are removed.
+ public addAgentAction(options: {
+ name: string,
+ description: string,
+ handler: (args: Record<string, unknown>, app: App) => Promise<{result?: string; error?: string}>
+ }): string {
+ const fullName = "plugin__" + this.name + "__" + options.name;
+ if (!this.agentActions.includes(fullName)) {
+ registerAction({name: fullName, description: options.description, handler: options.handler});
+ this.agentActions.push(fullName);
+ }
+ return fullName;
+ }
+
public addDock(options: {
config: IPluginDockTab,
data: any,
diff --git a/app/src/plugin/uninstall.ts b/app/src/plugin/uninstall.ts
index 0ff21a1b98..3b641ce1e0 100644
--- a/app/src/plugin/uninstall.ts
+++ b/app/src/plugin/uninstall.ts
@@ -1,7 +1,7 @@
import {App} from "../index";
import {Plugin} from "./index";
/// #if !MOBILE
-import {getAllModels} from "../layout/getAll";
+import {getAllEditor, getAllModels} from "../layout/getAll";
import {resizeTopBar} from "../layout/util";
import {setTabPosition} from "../layout/tabUtil";
/// #endif
@@ -10,7 +10,7 @@ import {ipcRenderer} from "electron";
/// #endif
import {Constants} from "../constants";
import {setStorageVal} from "../protyle/util/compatibility";
-import {getAllEditor} from "../layout/getAll";
+import {unregisterAction} from "../layout/dock/frontendActions";
export const uninstall = (app: App, name: string, isReload: boolean) => {
app.plugins.find((plugin: Plugin, index) => {
@@ -52,6 +52,8 @@ export const uninstall = (app: App, name: string, isReload: boolean) => {
plugin.topBarIcons.splice(i, 1);
i--;
}
+ // rm agent actions
+ plugin.agentActions.forEach(name => unregisterAction(name));
/// #if !MOBILE
// rm statusBar
plugin.statusBarIcons.forEach(item => {
diff --git a/app/src/util/agentSSE.ts b/app/src/util/agentSSE.ts
index f492731850..afd6fbb44e 100644
--- a/app/src/util/agentSSE.ts
+++ b/app/src/util/agentSSE.ts
@@ -67,6 +67,7 @@ export async function fetchAgentSSE(
model?: string,
regenerate?: boolean,
editorContext?: IEditorContext,
+ pluginActions?: Array<{name: string; description: string}>,
): Promise<void> {
try {
const body: Record<string, unknown> = {message: message, language: language, references: references};
@@ -74,6 +75,7 @@ export async function fetchAgentSSE(
if (model) { body.model = model; }
if (regenerate) { body.regenerate = regenerate; }
if (editorContext) { body.editorContext = editorContext; }
+ if (pluginActions && pluginActions.length > 0) { body.pluginActions = pluginActions; }
const response = await fetch("/api/ai/agent/chat", {
method: "POST",
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index a4f8325308..99135c6502 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -240,6 +240,15 @@ type EditorContext struct {
VisibleBlockIDs []string `json:"visibleBlockIDs,omitempty"` // 视口内可见块 ID 列表(已截断至上限)
}
+// 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
+// invoke them. Structurally identical to EditorContext: browser-owned state, refreshed per message.
+type PluginAction struct {
+ Name string `json:"name"` // full name: plugin__<pluginName>__<actionName>
+ Description string `json:"description"` // purpose description for the LLM
+}
+
type checkpointThinkingStep struct {
Reasoning string `json:"reasoning"`
Text string `json:"text"`
@@ -269,7 +278,7 @@ type agentCheckpoint struct {
AlwaysAllow bool `json:"alwaysAllow,omitempty"`
}
-func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userMessage string, language string, references []Reference, editorCtx EditorContext, regenerate bool, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {
+func AgentChat(ctx context.Context, client *openai.Client, model string, sessionID string, userMessage string, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {
ch := make(chan AgentEvent, 100)
go func() {
@@ -317,14 +326,14 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
checkpointMsgs = truncated
checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "user", Content: userMessage})
- messages = checkpointMessagesToOpenAI(checkpointMsgs, language, references, editorCtx)
+ messages = checkpointMessagesToOpenAI(checkpointMsgs, language, references, editorCtx, pluginActions)
}
}
}
if messages == nil {
checkpointMsgs = []AgentMessage{{Role: "user", Content: userMessage}}
- messages = buildInitialMessages(userMessage, language, references, editorCtx)
+ messages = buildInitialMessages(userMessage, language, references, editorCtx, pluginActions)
}
temperature := kernelModel.Conf.AI.Agent.Temperature
@@ -846,7 +855,7 @@ func handleFrontendTool(ctx context.Context, tc openai.ToolCall, ch chan<- Agent
return fr.result
}
-func buildSystemPrompt(language string, references []Reference, editorCtx EditorContext) string {
+func buildSystemPrompt(language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction) string {
var sb strings.Builder
sb.WriteString(systemPrompt)
sb.WriteString("\n\n<env>\nWorkspace: ")
@@ -876,6 +885,19 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editor
sb.WriteString("Use the skill tool to load a skill when a task matches its description.")
}
+ if len(pluginActions) > 0 {
+ 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 {
+ sb.WriteString("- ")
+ sb.WriteString(a.Name)
+ sb.WriteString(": ")
+ sb.WriteString(a.Description)
+ sb.WriteString("\n")
+ }
+ sb.WriteString("</plugin_actions>")
+ }
+
sb.WriteString("\n\n")
sb.WriteString("## Skill Management\n")
sb.WriteString("You can create, update, and delete skills using the skill tool:\n")
@@ -973,9 +995,9 @@ func buildSystemPrompt(language string, references []Reference, editorCtx Editor
return sb.String()
}
-func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext) []openai.ChatCompletionMessage {
+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)},
+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, references, editorCtx, pluginActions)},
{Role: openai.ChatMessageRoleUser, Content: userMessage},
}
}
@@ -997,9 +1019,9 @@ func loadCheckpoint(sessionID string) *agentCheckpoint {
return &cp
}
-func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, references []Reference, editorCtx EditorContext) []openai.ChatCompletionMessage {
+func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, references []Reference, editorCtx EditorContext, pluginActions []PluginAction) []openai.ChatCompletionMessage {
msgs := []openai.ChatCompletionMessage{
- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, references, editorCtx)},
+ {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, references, editorCtx, pluginActions)},
}
for cmi := range checkpointMsgs {
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 5878074c79..14850a7dc1 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -38,7 +38,8 @@ type agentChatReq struct {
Message string `json:"message"`
Language string `json:"language"`
References []agent.Reference `json:"references"`
- EditorContext agent.EditorContext `json:"editorContext"`
+ EditorContext agent.EditorContext `json:"editorContext"`
+ PluginActions []agent.PluginAction `json:"pluginActions"`
Model string `json:"model,omitempty"`
Regenerate bool `json:"regenerate"`
}
@@ -98,7 +99,7 @@ func agentChat(c *gin.Context) {
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
- eventCh = agent.AgentChat(ctx, client, selectedModel.Name, req.SessionID, req.Message, req.Language, req.References, req.EditorContext, req.Regenerate, confirmTimeout, maxRetries)
+ eventCh = agent.AgentChat(ctx, client, selectedModel.Name, req.SessionID, req.Message, req.Language, req.References, req.EditorContext, req.PluginActions, req.Regenerate, confirmTimeout, maxRetries)
sessionsMu.Lock()
runningSessions[req.SessionID] = &runningSession{eventCh: eventCh}
sessionsMu.Unlock()
diff --git a/kernel/mcp/tools/frontend.go b/kernel/mcp/tools/frontend.go
index 5cae1bc1ec..92ecf6e66a 100644
--- a/kernel/mcp/tools/frontend.go
+++ b/kernel/mcp/tools/frontend.go
@@ -27,11 +27,11 @@ var FrontendTool = &Tool{
"- 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).",
+ "- open_search: Open the global search dialog. Optional: query (pre-filled search keyword).\nPlugins may register additional actions; see the <plugin_actions> section in the context for available plugin actions and use their full name (e.g. plugin__myplugin__myaction)",
InputSchema: ToolSchema{
Type: "object",
Properties: map[string]Property{
- "action": {Type: "string", Description: "Operation", Enum: []string{"open_setting", "focus_block", "open_document", "open_search"}},
+ "action": {Type: "string", Description: "Operation"},
"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)"},
},