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

Daniel307f5b1a6041
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 4cd36325de..4866817161 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -266,22 +266,22 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
alwaysAllow["*"] = true
}
if len(cp.Messages) > 0 {
- truncated := cp.Messages
- if regenerate {
- lastUserIdx := -1
- for i := len(truncated) - 1; i >= 0; i-- {
- if truncated[i].Role == "user" {
- lastUserIdx = i
- break
+ truncated := cp.Messages
+ if regenerate {
+ lastUserIdx := -1
+ for i := len(truncated) - 1; i >= 0; i-- {
+ if truncated[i].Role == "user" {
+ lastUserIdx = i
+ break
+ }
+ }
+ if lastUserIdx >= 0 && truncated[lastUserIdx].Content == userMessage {
+ truncated = truncated[:lastUserIdx]
}
}
- if lastUserIdx >= 0 && truncated[lastUserIdx].Content == userMessage {
- truncated = truncated[:lastUserIdx]
- }
- }
- checkpointMsgs = truncated
- checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "user", Content: userMessage})
- messages = checkpointMessagesToOpenAI(checkpointMsgs, language, references)
+ checkpointMsgs = truncated
+ checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "user", Content: userMessage})
+ messages = checkpointMessagesToOpenAI(checkpointMsgs, language, references)
}
}
}
@@ -335,21 +335,20 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
keepTurns = 1
}
messages = compactMessages(messages, keepTurns)
+ checkpointMsgs = compactCheckpointMsgs(checkpointMsgs, keepTurns)
compactCount++
sendEvent(ch, AgentEvent{Type: "thinking", Reasoning: fmt.Sprintf("context limit reached, compacting to last %d turns...", keepTurns)})
continue
}
- logging.LogErrorf("agent API request failed: %s", streamErr.Error())
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(streamErr)})
- saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
- return
+ logging.LogErrorf("agent API request failed: %s", streamErr.Error())
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(streamErr)})
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
+ return
}
- defer stream.Close()
-
- var contentBuilder strings.Builder
- var reasoningBuilder strings.Builder
- var aggregatedToolCalls []openai.ToolCall
+ var contentBuilder strings.Builder
+ var reasoningBuilder strings.Builder
+ var aggregatedToolCalls []openai.ToolCall
for {
resp, recvErr := stream.Recv()
@@ -357,18 +356,20 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
if recvErr == io.EOF {
break
}
- logging.LogErrorf("agent stream error: %s", recvErr.Error())
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(recvErr)})
- content := contentBuilder.String()
- if content != "" || reasoningBuilder.String() != "" {
- checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content})
- }
- saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
- return
+ logging.LogErrorf("agent stream error: %s", recvErr.Error())
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: getAgentErrorMessage(recvErr)})
+ content := contentBuilder.String()
+ if content != "" || reasoningBuilder.String() != "" {
+ checkpointMsgs = append(checkpointMsgs, AgentMessage{Role: "assistant", Content: content})
+ }
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
+ stream.Close()
+ return
}
select {
case <-ctx.Done():
+ stream.Close()
return
default:
}
@@ -409,6 +410,8 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
}
+ stream.Close()
+
if len(aggregatedToolCalls) > 0 {
filtered := make([]openai.ToolCall, 0, len(aggregatedToolCalls))
for _, tc := range aggregatedToolCalls {
@@ -525,40 +528,40 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
}
- if !snapshotCreated && action != "" && !safeActions[action] && !(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)
- sendCriticalEvent(ctx, ch, AgentEvent{
- Type: "error",
- Error: "auto snapshot failed, operation aborted: " + err.Error(),
- })
-
- abortMsg := "Operation aborted due to snapshot failure"
- checkpointMsgs[assistantIdx].ToolCalls[i].Result = abortMsg
- messages = append(messages, openai.ChatCompletionMessage{
- Role: openai.ChatMessageRoleTool,
- Content: wrapToolOutput(abortMsg),
- ToolCallID: tc.ID,
- })
- sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: abortMsg})
-
- for j := i + 1; j < len(aggregatedToolCalls); j++ {
- checkpointMsgs[assistantIdx].ToolCalls[j].Result = abortMsg
+ if !snapshotCreated && action != "" && !safeActions[action] && !(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)
+ sendCriticalEvent(ctx, ch, AgentEvent{
+ Type: "error",
+ Error: "auto snapshot failed, operation aborted: " + err.Error(),
+ })
+
+ abortMsg := "Operation aborted due to snapshot failure"
+ checkpointMsgs[assistantIdx].ToolCalls[i].Result = abortMsg
messages = append(messages, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: wrapToolOutput(abortMsg),
- ToolCallID: aggregatedToolCalls[j].ID,
+ ToolCallID: tc.ID,
})
- sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: abortMsg})
+ sendEvent(ch, AgentEvent{Type: "tool_result", Name: tc.Function.Name, Result: abortMsg})
+
+ for j := i + 1; j < len(aggregatedToolCalls); j++ {
+ checkpointMsgs[assistantIdx].ToolCalls[j].Result = abortMsg
+ messages = append(messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleTool,
+ Content: wrapToolOutput(abortMsg),
+ ToolCallID: aggregatedToolCalls[j].ID,
+ })
+ sendEvent(ch, AgentEvent{Type: "tool_result", Name: aggregatedToolCalls[j].Function.Name, Result: abortMsg})
+ }
+ saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
+ return
}
- saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
- return
+ snapshotIDs = append(snapshotIDs, id)
+ snapshotCreated = true
+ sendCriticalEvent(ctx, ch, AgentEvent{Type: "snapshot", SnapshotID: id})
}
- snapshotIDs = append(snapshotIDs, id)
- snapshotCreated = true
- sendCriticalEvent(ctx, ch, AgentEvent{Type: "snapshot", SnapshotID: id})
- }
var resultStr string
if tc.Function.Name == "question" {
@@ -585,7 +588,7 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
checkpointMsgs[assistantIdx].ToolCalls[i].Result = resultStr
if tc.Function.Name != "question" {
- sig := tc.Function.Name + "::" + tc.Function.Arguments
+ sig := tc.Function.Name + "::action=" + action
if sig == doomLoop.prevSig && doomLoop.prevSig != "" {
doomLoop.count++
} else {
@@ -596,8 +599,14 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
}
}
- if doomLoop.count >= 3 {
- errMsg := "Repetitive tool calls detected: '" + doomLoop.prevName + "' called " + fmt.Sprintf("%d", doomLoop.count) + " times with the same arguments. Operation terminated."
+ if doomLoop.count == 3 {
+ messages = append(messages, openai.ChatCompletionMessage{
+ Role: openai.ChatMessageRoleSystem,
+ Content: "You have called '" + doomLoop.prevName + "' " + fmt.Sprintf("%d", doomLoop.count) + " times with the same action. Please try a different approach.",
+ })
+ }
+ if doomLoop.count >= 5 {
+ errMsg := "Repetitive tool calls detected: '" + doomLoop.prevName + "' called " + fmt.Sprintf("%d", doomLoop.count) + " times with the same action. Operation terminated."
sendCriticalEvent(ctx, ch, AgentEvent{Type: "error", Error: errMsg})
saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
return
@@ -608,7 +617,6 @@ func AgentChat(ctx context.Context, client *openai.Client, model string, session
saveCheckpoint(sessionID, checkpointMsgs, totalPrompt, totalCompletion, startTime, snapshotIDs, alwaysAllow)
roundsSinceCheckpoint = 0
}
- stream.Close()
continue
}
@@ -668,6 +676,9 @@ func GenerateTitle(client *openai.Client, model string, userMsg string, language
return title
}
+// safeActions 按 action 字符串全局匹配,命中即免 UI 确认。
+// 契约:此处列出的 action 名必须代表纯只读操作。
+// 新增工具时,写操作的 action 切勿与此表冲突,否则将静默豁免确认。
var safeActions = map[string]bool{
"get": true, "get_kramdown": true, "get_children": true, "breadcrumb": true,
"tree_stat": true, "dom": true, "batch_get": true, "batch_kramdown": true,
@@ -725,6 +736,11 @@ func handleQuestion(ctx context.Context, argsJSON string, ch chan<- AgentEvent,
var answer QuestionAnswer
select {
case answer = <-ch2:
+ case <-ctx.Done():
+ questionChannelsMu.Lock()
+ delete(questionChannels, questionID)
+ questionChannelsMu.Unlock()
+ return "Question cancelled."
case <-time.After(timeout):
questionChannelsMu.Lock()
delete(questionChannels, questionID)
@@ -869,9 +885,13 @@ func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string,
ToolCalls: toolCalls,
})
for _, tc := range cm.ToolCalls {
+ result := tc.Result
+ if result == "" {
+ result = "(result unavailable)"
+ }
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
- Content: tc.Result,
+ Content: result,
ToolCallID: tc.ID,
})
}
@@ -895,8 +915,8 @@ func saveCheckpoint(sessionID string, messages []AgentMessage, promptTokens int,
TotalDuration: time.Now().UnixMilli() - startTime,
CreatedAt: startTime,
UpdatedAt: time.Now().UnixMilli(),
- Snapshots: snapshotIDs,
- AlwaysAllow: alwaysAllow["*"],
+ Snapshots: snapshotIDs,
+ AlwaysAllow: alwaysAllow["*"],
}
dir := filepath.Join(util.DataDir, "storage", "ai", "agent", "sessions", sessionID)
diff --git a/kernel/agent/compaction.go b/kernel/agent/compaction.go
index 5d88c15e70..5f023d90d5 100644
--- a/kernel/agent/compaction.go
+++ b/kernel/agent/compaction.go
@@ -75,6 +75,7 @@ func extractSummary(msgs []openai.ChatCompletionMessage) string {
var sb strings.Builder
var toolNames []string
var userMsgs []string
+ var assistantMsgs []string
for _, m := range msgs {
switch m.Role {
@@ -91,12 +92,21 @@ func extractSummary(msgs []openai.ChatCompletionMessage) string {
for _, tc := range m.ToolCalls {
toolNames = append(toolNames, tc.Function.Name)
}
+ if text := strings.TrimSpace(m.Content); text != "" {
+ assistantMsgs = append(assistantMsgs, "- Assistant: "+firstSentence(text))
+ }
}
}
if len(userMsgs) > 0 {
sb.WriteString(strings.Join(userMsgs, "\n"))
}
+ if len(assistantMsgs) > 0 {
+ if sb.Len() > 0 {
+ sb.WriteString("\n")
+ }
+ sb.WriteString(strings.Join(assistantMsgs, "\n"))
+ }
if len(toolNames) > 0 {
if sb.Len() > 0 {
sb.WriteString("\n")
@@ -121,3 +131,110 @@ func extractSummary(msgs []openai.ChatCompletionMessage) string {
}
return sb.String()
}
+
+func compactCheckpointMsgs(msgs []AgentMessage, keepLastUserMessages int) []AgentMessage {
+ if len(msgs) <= 1 || keepLastUserMessages <= 0 {
+ return msgs
+ }
+
+ userCount := 0
+ cutIdx := 0
+ for i := len(msgs) - 1; i >= 0; i-- {
+ if msgs[i].Role == "user" {
+ userCount++
+ if userCount == keepLastUserMessages {
+ cutIdx = i
+ break
+ }
+ }
+ }
+
+ if cutIdx <= 0 {
+ return msgs
+ }
+
+ oldMsgs := msgs[:cutIdx]
+ summary := extractCheckpointSummary(oldMsgs)
+
+ compacted := make([]AgentMessage, 0, 1+len(msgs)-cutIdx)
+ compacted = append(compacted, AgentMessage{
+ Role: "system",
+ Content: "[Earlier conversation summarized]\n" + summary + "\n\nContinue based on the summary above.",
+ })
+ compacted = append(compacted, msgs[cutIdx:]...)
+
+ return compacted
+}
+
+func extractCheckpointSummary(msgs []AgentMessage) string {
+ var sb strings.Builder
+ var toolNames []string
+ var userMsgs []string
+ var assistantMsgs []string
+
+ for _, m := range msgs {
+ switch m.Role {
+ case "user":
+ text := strings.TrimSpace(m.Content)
+ if text != "" {
+ runes := []rune(text)
+ if len(runes) > 300 {
+ text = string(runes[:300]) + "..."
+ }
+ userMsgs = append(userMsgs, "- User: "+text)
+ }
+ case "assistant":
+ for _, tc := range m.ToolCalls {
+ toolNames = append(toolNames, tc.Name)
+ }
+ if text := strings.TrimSpace(m.Content); text != "" {
+ assistantMsgs = append(assistantMsgs, "- Assistant: "+firstSentence(text))
+ }
+ }
+ }
+
+ if len(userMsgs) > 0 {
+ sb.WriteString(strings.Join(userMsgs, "\n"))
+ }
+ if len(assistantMsgs) > 0 {
+ if sb.Len() > 0 {
+ sb.WriteString("\n")
+ }
+ sb.WriteString(strings.Join(assistantMsgs, "\n"))
+ }
+ if len(toolNames) > 0 {
+ if sb.Len() > 0 {
+ sb.WriteString("\n")
+ }
+ seen := map[string]int{}
+ var counts []string
+ for _, name := range toolNames {
+ seen[name]++
+ }
+ for name, count := range seen {
+ if count > 1 {
+ counts = append(counts, name+" ×"+strconv.Itoa(count))
+ } else {
+ counts = append(counts, name)
+ }
+ }
+ sb.WriteString("- Tools used: " + strings.Join(counts, ", "))
+ }
+
+ if sb.Len() == 0 {
+ return "(no content to summarize)"
+ }
+ return sb.String()
+}
+
+func firstSentence(text string) string {
+ runes := []rune(text)
+ if len(runes) <= 200 {
+ return text
+ }
+ sentence := string(runes[:200])
+ if idx := strings.IndexAny(sentence, ".。!?!?\n"); idx > 0 {
+ return sentence[:idx+1] + "..."
+ }
+ return sentence + "..."
+}
diff --git a/kernel/api/agent.go b/kernel/api/agent.go
index 05a79fbcf4..23b48c191a 100644
--- a/kernel/api/agent.go
+++ b/kernel/api/agent.go
@@ -345,7 +345,7 @@ func writeSSE(c *gin.Context, event agent.AgentEvent) error {
return writeSSEEvent(c, "done", map[string]interface{}{})
case "retry":
return writeSSEEvent(c, "retry", map[string]interface{}{
- "attempt": event.RetryAttempt,
+ "attempt": event.RetryAttempt,
"maxRetries": event.RetryMax,
})
case "question":
diff --git a/kernel/conf/ai.go b/kernel/conf/ai.go
index bd5c8e4aa1..d8749befba 100644
--- a/kernel/conf/ai.go
+++ b/kernel/conf/ai.go
@@ -27,9 +27,9 @@ import (
)
type AI struct {
- MCP *MCP `json:"mcp"`
- Embedding *Embedding `json:"embedding"`
- Agent *Agent `json:"agent"`
+ MCP *MCP `json:"mcp"`
+ Embedding *Embedding `json:"embedding"`
+ Agent *Agent `json:"agent"`
Providers []*Provider `json:"providers"`
Scenarios []*Scenario `json:"scenarios"`
}
@@ -44,23 +44,23 @@ type Agent struct {
}
type Embedding struct {
- ID string `json:"id,omitempty"`
- DisplayName string `json:"displayName,omitempty"`
- Enabled bool `json:"enabled,omitempty"`
- APIKey string `json:"apiKey"`
- BaseURL string `json:"baseURL"`
- Name string `json:"name"`
- Timeout int `json:"timeout"`
+ ID string `json:"id,omitempty"`
+ DisplayName string `json:"displayName,omitempty"`
+ Enabled bool `json:"enabled,omitempty"`
+ APIKey string `json:"apiKey"`
+ BaseURL string `json:"baseURL"`
+ Name string `json:"name"`
+ Timeout int `json:"timeout"`
}
type Provider struct {
- ID string `json:"id,omitempty"`
- DisplayName string `json:"displayName,omitempty"`
- Enabled bool `json:"enabled,omitempty"`
- APIKey string `json:"apiKey"`
- BaseURL string `json:"baseURL"`
- RequestTimeout int `json:"requestTimeout"`
- Models []*Model `json:"models"`
+ ID string `json:"id,omitempty"`
+ DisplayName string `json:"displayName,omitempty"`
+ Enabled bool `json:"enabled,omitempty"`
+ APIKey string `json:"apiKey"`
+ BaseURL string `json:"baseURL"`
+ RequestTimeout int `json:"requestTimeout"`
+ Models []*Model `json:"models"`
}
type Model struct {
@@ -486,7 +486,7 @@ func migrateEmbedding(raw map[string]any) *Embedding {
ID: getString(raw, "id"),
DisplayName: getString(raw, "name"),
Enabled: getBool(raw, "enabled"),
- APIKey: getString(raw, "apiKey"),
+ APIKey: getString(raw, "apiKey"),
BaseURL: getString(raw, "apiBaseURL"),
Name: getString(raw, "apiModel"),
Timeout: getInt(raw, "apiTimeout"),