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

Daniel17ffd7bf7ca5
diff --git a/app/src/layout/dock/AgentChat.ts b/app/src/layout/dock/AgentChat.ts
index 68018fba13..6c98294c7a 100644
--- a/app/src/layout/dock/AgentChat.ts
+++ b/app/src/layout/dock/AgentChat.ts
@@ -39,10 +39,11 @@ type SessionEntry =
type: "thinking";
steps: Array<{
reasoning: string;
- text: string;
- toolCalls: Array<{ name: string; result?: string }>;
- reasoningContent: string
- }>
+ reasoningContent: string;
+ toolNames?: string[];
+ content?: string
+ }>;
+ duration?: number
})
| (EntryBase & {
type: "assistant";
@@ -1205,7 +1206,7 @@ export class AgentChat extends Model {
private appendThinking(reasoning: string) {
const L = window.siyuan.languages;
if (this.currentThinkingText) {
- const doneText = this.currentThinkingText;
+ let doneText = this.currentThinkingText;
this.currentThinkingText = doneText;
const tc = this.currentToolCalls.map(function (t) {
return {name: t.name, result: t.result};
@@ -1220,7 +1221,7 @@ export class AgentChat extends Model {
this.currentThinkingText = "";
this.currentThinkingReasoning = reasoning;
this.currentThinkingReasoningContent = "";
- const text = L.agentThinking || "Thinking...";
+ let text = L.agentThinking || "Thinking...";
this.currentThinkingText = text;
@@ -2063,7 +2064,7 @@ export class AgentChat extends Model {
private finishActiveThinking() {
const L = window.siyuan.languages;
const dur = this.requestStartTime ? ((Date.now() - this.requestStartTime) / 1000).toFixed(1) + "s" : "";
- const doneText = L.agentThinkingDoneTime ? L.agentThinkingDoneTime.replace("%s", dur) : (L.agentThinking || "Thinking...");
+ let doneText = L.agentThinkingDoneTime ? L.agentThinkingDoneTime.replace("%s", dur) : (L.agentThinking || "Thinking...");
this.currentThinkingText = doneText || this.currentThinkingText;
const items = this.messagesContainer.querySelectorAll(
diff --git a/app/src/layout/dock/AgentMessageRenderer.ts b/app/src/layout/dock/AgentMessageRenderer.ts
index 7da8afb3c4..667156c82a 100644
--- a/app/src/layout/dock/AgentMessageRenderer.ts
+++ b/app/src/layout/dock/AgentMessageRenderer.ts
@@ -96,7 +96,7 @@ export const renderRetryCardHTML = (attempt: number, maxRetries: number): string
"</div>";
};
-export const renderToolsLineHTML = (newTools: Array<{name: string; result?: string}>): string => {
+export const renderToolsLineHTML = (newTools: Array<{name: string}>): string => {
let detailLines = "<div class=\"agent-chat__thinking-tools-line\"><span class=\"agent-chat__thinking-summary\">Tool calls:</span>";
for (let i = 0; i < newTools.length; i++) {
detailLines += '<span class="agent-chat__thinking-tool">' + escapeHtml(newTools[i].name) + "</span>";
@@ -105,13 +105,15 @@ export const renderToolsLineHTML = (newTools: Array<{name: string; result?: stri
return detailLines;
};
-export const createThinkingCardElement = (step: {reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string}): HTMLElement => {
+// createThinkingCardElement 用于流式过程中的单个思考卡片。
+// 工具调用只接收名字列表(arguments/result 在 assistant entry 存一份);
+// 标题文本由调用方传入(已通过 i18n 从 duration 生成)。
+export const createThinkingCardElement = (step: {reasoning: string; text: string; toolNames?: string[]; reasoningContent: string}): HTMLElement => {
let detail = "";
- if (step.toolCalls.length > 0) {
+ if (step.toolNames && step.toolNames.length > 0) {
detail += '<div class="agent-chat__thinking-tools-line"><span class="agent-chat__thinking-summary">Tool calls:</span>';
- for (let j = 0; j < step.toolCalls.length; j++) {
- const tc = step.toolCalls[j];
- detail += '<span class="agent-chat__thinking-tool">' + escapeHtml(tc.name) + "</span>";
+ for (let j = 0; j < step.toolNames.length; j++) {
+ detail += '<span class="agent-chat__thinking-tool">' + escapeHtml(step.toolNames[j]) + "</span>";
}
detail += "</div>";
}
diff --git a/app/src/layout/dock/SessionStore.ts b/app/src/layout/dock/SessionStore.ts
index b15323699d..5ec7ebaedc 100644
--- a/app/src/layout/dock/SessionStore.ts
+++ b/app/src/layout/dock/SessionStore.ts
@@ -26,9 +26,19 @@ export interface AgentSession {
id?: string;
type: "user" | "thinking" | "assistant" | "confirm" | "snapshot" | "rollback";
content?: string;
- steps?: Array<{reasoning: string; text: string; toolCalls: Array<{name: string; result?: string}>; reasoningContent: string}>;
+ // thinking step:新格式只含 reasoning/reasoningContent/toolNames/content;
+ // text/toolCalls 仅为读取老数据而保留为可选(渲染时归一化)。
+ steps?: Array<{
+ reasoning: string;
+ reasoningContent: string;
+ toolNames?: string[];
+ content?: string;
+ text?: string;
+ toolCalls?: Array<{name: string; result?: string}>
+ }>;
reasoningContent?: string;
toolCalls?: Array<{name: string; arguments?: Record<string, unknown>; result?: string}>;
+ duration?: number;
confirmName?: string;
confirmArgs?: Record<string, unknown>;
confirmID?: string;
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 1c75f5c58a..f2a106e6ac 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -18,7 +18,6 @@ package agent
import (
"context"
- "encoding/json"
"errors"
"fmt"
"io"
@@ -284,33 +283,47 @@ type PluginAction struct {
Description string `json:"description"` // purpose description for the LLM
}
-type checkpointThinkingStep struct {
- Reasoning string `json:"reasoning"`
- Text string `json:"text"`
- ToolCalls []checkpointBriefTC `json:"toolCalls"`
- ReasoningContent string `json:"reasoningContent"`
+// SessionEntry 与前端 SessionStore.ts 中 entries 元素一一对应,
+// 是会话持久化的唯一数据源(不再单独持久化 messages)。
+type SessionEntry struct {
+ ID string `json:"id,omitempty"`
+ Type string `json:"type"` // user|thinking|assistant|confirm|snapshot|rollback
+ Content string `json:"content,omitempty"`
+ Steps []SessionEntryStep `json:"steps,omitempty"` // 仅 thinking
+ ToolCalls []AgentToolCall `json:"toolCalls,omitempty"` // 仅 assistant
+ Duration float64 `json:"duration,omitempty"` // 秒(thinking/assistant 均可能带)
+ PromptTokens int `json:"promptTokens,omitempty"` // 仅 assistant
+ CompletionTok int `json:"completionTokens,omitempty"`
+ Timestamp int64 `json:"timestamp,omitempty"`
+ ReasoningCont string `json:"reasoningContent,omitempty"`
+ ConfirmName string `json:"confirmName,omitempty"`
+ ConfirmArgs map[string]interface{} `json:"confirmArgs,omitempty"`
+ ConfirmID string `json:"confirmID,omitempty"`
+ ConfirmStatus string `json:"confirmStatus,omitempty"`
+ SnapshotID string `json:"snapshotID,omitempty"`
}
-type checkpointBriefTC struct {
- Name string `json:"name"`
- Result string `json:"result,omitempty"`
+// SessionEntryStep 描述一次思考步骤。工具调用只保留名字列表,
+// arguments/result 仅在所属 assistant entry 的 ToolCalls 中存储,避免重复。
+type SessionEntryStep struct {
+ Reasoning string `json:"reasoning"`
+ ReasoningContent string `json:"reasoningContent,omitempty"`
+ ToolNames []string `json:"toolNames,omitempty"`
}
type agentCheckpoint struct {
- ID string `json:"id"`
- Title string `json:"title"`
- Titled bool `json:"titled"`
- Messages []AgentMessage `json:"messages"`
- Entries []json.RawMessage `json:"entries,omitempty"`
- PromptTokens int `json:"promptTokens"`
- CompletionTokens int `json:"completionTokens"`
- TotalDuration int64 `json:"totalDuration"`
- CreatedAt int64 `json:"createdAt"`
- UpdatedAt int64 `json:"updatedAt"`
- MessageHistory []string `json:"messageHistory,omitempty"`
- ThinkingSteps []checkpointThinkingStep `json:"thinkingSteps,omitempty"`
- Snapshots []string `json:"snapshots,omitempty"`
- AlwaysAllow bool `json:"alwaysAllow,omitempty"`
+ ID string `json:"id"`
+ Title string `json:"title"`
+ Titled bool `json:"titled"`
+ Entries []SessionEntry `json:"entries"`
+ PromptTokens int `json:"promptTokens"`
+ CompletionTokens int `json:"completionTokens"`
+ TotalDuration int64 `json:"totalDuration"`
+ CreatedAt int64 `json:"createdAt"`
+ UpdatedAt int64 `json:"updatedAt"`
+ MessageHistory []string `json:"messageHistory,omitempty"`
+ Snapshots []string `json:"snapshots,omitempty"`
+ 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, pluginActions []PluginAction, regenerate bool, confirmTimeout time.Duration, maxRetries int) <-chan AgentEvent {
@@ -345,8 +358,11 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
if cp.AlwaysAllow {
alwaysAllow["*"] = true
}
- if len(cp.Messages) > 0 {
- truncated := cp.Messages
+ if len(cp.Entries) > 0 {
+ // entries 是唯一持久化数据源。先转回 AgentMessage 视图用于
+ // 截断/重建逻辑(thinking/confirm/snapshot 不参与 LLM 上下文)。
+ loadedMsgs := entriesToAgentMessages(cp.Entries)
+ truncated := loadedMsgs
if regenerate {
lastUserIdx := -1
for i := len(truncated) - 1; i >= 0; i-- {
@@ -1062,6 +1078,33 @@ func loadCheckpoint(sessionID string) *agentCheckpoint {
return &cp
}
+// entriesToAgentMessages 把持久化的 entries 还原为 AgentMessage 视图。
+// 仅 user/assistant(含 toolCalls)参与;thinking/confirm/snapshot 等仅供 UI 展示,
+// 因此不进入 LLM 上下文。配合 checkpointMessagesToOpenAI 即可重建 OpenAI 消息。
+func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {
+ var msgs []AgentMessage
+ for i := range entries {
+ e := &entries[i]
+ switch e.Type {
+ case "user":
+ msgs = append(msgs, AgentMessage{Role: "user", Content: e.Content})
+ case "assistant":
+ m := AgentMessage{Role: "assistant", Content: e.Content}
+ if len(e.ToolCalls) > 0 {
+ m.ToolCalls = make([]AgentToolCall, len(e.ToolCalls))
+ for j := range e.ToolCalls {
+ m.ToolCalls[j] = e.ToolCalls[j]
+ if m.ToolCalls[j].ID == "" {
+ m.ToolCalls[j].ID = fmt.Sprintf("call_cp_%d_%d", i, j)
+ }
+ }
+ }
+ msgs = append(msgs, m)
+ }
+ }
+ return msgs
+}
+
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, pluginActions)},
@@ -1130,6 +1173,36 @@ func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string,
return msgs
}
+// agentMessagesToEntries 把后端运行期累积的 AgentMessage 派生为最小 entries,
+// 用于中途崩溃恢复的 checkpoint 兜底(仅 user/assistant + toolCalls,
+// 不含 thinking/confirm/snapshot —— 前端完成后会用完整 entries 覆盖)。
+func agentMessagesToEntries(msgs []AgentMessage) []SessionEntry {
+ if len(msgs) == 0 {
+ return nil
+ }
+ entries := make([]SessionEntry, 0, len(msgs))
+ for i := range msgs {
+ m := &msgs[i]
+ switch m.Role {
+ case "user":
+ entries = append(entries, SessionEntry{
+ ID: fmt.Sprintf("cp_%d", i),
+ Type: "user",
+ Content: m.Content,
+ })
+ case "assistant":
+ e := SessionEntry{
+ ID: fmt.Sprintf("cp_%d", i),
+ Type: "assistant",
+ Content: m.Content,
+ ToolCalls: m.ToolCalls,
+ }
+ entries = append(entries, e)
+ }
+ }
+ return entries
+}
+
func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int, completionTokens int, startTime int64, snapshotIDs []string, alwaysAllow map[string]bool) {
if sessionID == "" || !isValidSessionID(sessionID) {
return
@@ -1138,7 +1211,7 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,
cp := agentCheckpoint{
ID: sessionID,
Title: "AI Agent",
- Messages: messages,
+ Entries: agentMessagesToEntries(messages),
PromptTokens: promptTokens,
CompletionTokens: completionTokens,
TotalDuration: time.Now().UnixMilli() - startTime,
@@ -1170,9 +1243,9 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,
if len(old.MessageHistory) > 0 {
cp.MessageHistory = old.MessageHistory
}
- if len(old.ThinkingSteps) > 0 {
- cp.ThinkingSteps = old.ThinkingSteps
- }
+ // 后端中途 checkpoint 只能派生最小 entries(user/assistant/toolCalls)。
+ // 若磁盘上已有前端写入的完整 entries(含 thinking/confirm/snapshot),
+ // 优先保留它,避免后端兜底数据覆盖前端的富信息。
if len(old.Entries) > 0 {
cp.Entries = old.Entries
}
diff --git a/kernel/agent/session.go b/kernel/agent/session.go
index 594c8aa382..8a6fe712f8 100644
--- a/kernel/agent/session.go
+++ b/kernel/agent/session.go
@@ -301,7 +301,9 @@ func SaveSession(data []byte) error {
for k, v := range existingData {
if _, ok := newData[k]; !ok {
switch k {
- case "createdAt", "titled", "messageHistory", "thinkingSteps", "entries", "snapshots", "id", "messages", "alwaysAllow":
+ // messages 不再保留:以 entries 为唯一持久化数据源,
+ // 前端下次保存时会用 entries 覆盖,老 messages 字段自然清除。
+ case "createdAt", "titled", "messageHistory", "entries", "snapshots", "id", "alwaysAllow":
newData[k] = v
}
}