Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:recycle: Remove superseded agent helpers and test active paths https://github.com/siyuan-note/siyuan/issues/20231

Danielb8a926b6efb6
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.go
index 5cba63de78..073914f2f1 100644
--- a/kernel/agent/agent.go
+++ b/kernel/agent/agent.go
@@ -1742,12 +1742,6 @@ func capabilityEffects(registration *capabilityRegistration, action string) mcpt
return effects
}
-func needsCapabilityConfirm(registration *capabilityRegistration, action string, args map[string]any,
- allowSession bool, alwaysAllow map[string]bool) bool {
- required, _ := capabilityConfirmRequirement(registration, action, args, allowSession, alwaysAllow)
- return required
-}
-
func capabilityConfirmRequirement(registration *capabilityRegistration, action string, args map[string]any,
allowSession bool, alwaysAllow map[string]bool) (required, forced bool) {
if registration == nil {
@@ -2239,17 +2233,6 @@ func buildUserMessageContent(userMessage string, references []Reference, editorC
return sb.String()
}
-func buildInitialMessages(userMessage string, language string, references []Reference, editorCtx EditorContext, capabilities *capabilitySet, instructions ...string) []openai.ChatCompletionMessage {
- messages := []openai.ChatCompletionMessage{
- {Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities, instructions...)},
- {Role: openai.ChatMessageRoleUser, Content: buildUserMessageContent(userMessage, references, cloneEditorContext(editorCtx), capabilities)},
- }
- if attachmentMessage, ok := buildAttachmentMessage(agentMessageAttachments(AgentMessage{Role: "user", Content: userMessage})); ok {
- messages = append(messages, attachmentMessage)
- }
- return messages
-}
-
// skillsSegmentTokens 估算 system prompt 中 <available_skills> 段(含引导句)的 token 数。
// 该段在 buildSystemPrompt 内部拼成大字符串,这里独立重建同等内容计数,用于分类统计切出 skills 类。
func skillsSegmentTokens(counter *tokenCounter) int {
@@ -2291,7 +2274,7 @@ func loadCheckpoint(sessionID string) *agentCheckpoint {
// entriesToAgentMessages 把持久化的 entries 还原为 AgentMessage 视图。
// 仅 user/assistant(含 reasoningContent/toolCalls)参与;thinking/confirm/snapshot 等仅供 UI 展示,
-// 因此不进入 LLM 上下文。配合 checkpointMessagesToOpenAI 即可重建 OpenAI 消息。
+// 因此不进入 LLM 上下文。配合 checkpointMessagesToOpenAIWithSummary 即可重建 OpenAI 消息。
func entriesToAgentMessages(entries []SessionEntry) []AgentMessage {
var msgs []AgentMessage
for i := range entries {
@@ -2364,10 +2347,6 @@ func geminiToolCallProviderData(signature string) *AgentToolCallProviderData {
}
}
-func checkpointMessagesToOpenAI(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet) []openai.ChatCompletionMessage {
- return checkpointMessagesToOpenAIWithSummary(checkpointMsgs, language, capabilities, nil)
-}
-
func checkpointMessagesToOpenAIWithSummary(checkpointMsgs []AgentMessage, language string, capabilities *capabilitySet, compaction *runtimeCompaction, instructions ...string) []openai.ChatCompletionMessage {
msgs := []openai.ChatCompletionMessage{
{Role: openai.ChatMessageRoleSystem, Content: buildSystemPrompt(language, capabilities, instructions...)},
@@ -2600,67 +2579,11 @@ func responseOutputItemToInput(item json.RawMessage, fallback string) any {
}
}
-// agentMessagesToEntries 把后端运行期累积的 AgentMessage 派生为最小 entries,
-// 用于中途崩溃恢复的 checkpoint 兜底(仅 user/assistant + reasoningContent/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":
- id := m.EntryID
- 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,
- References: append([]Reference(nil), m.References...),
- EditorContext: editorCtx,
- })
- case "assistant":
- id := m.EntryID
- if id == "" {
- id = fmt.Sprintf("cp_%d", i)
- }
- e := SessionEntry{
- ID: id,
- Type: "assistant",
- Content: m.Content,
- ReasoningCont: m.ReasoningContent,
- NativeContent: util.CloneAIMessageContent(m.NativeContent),
- ResponseOutput: util.CloneOpenAIResponseOutput(m.ResponseOutput),
- ResponseOutputTokens: m.ResponseOutputTokens,
- RoundID: m.RoundID,
- ToolCalls: m.ToolCalls,
- }
- entries = append(entries, e)
- }
- }
- return entries
-}
-
var (
errModelRequestTimeout = errors.New("model request timeout")
errModelStreamIdleTimeout = errors.New("model stream idle timeout")
)
-func createStreamWithRetry(ctx context.Context, client *util.AIClient, req openai.ChatCompletionRequest, maxRetries int,
- requestTimeout, streamIdleTimeout time.Duration, retryDelay func(string, int) time.Duration,
- ch chan<- AgentEvent) (*util.OpenAICompletionStream, openai.ChatCompletionStreamResponse, context.CancelFunc, error) {
- return createProtocolStreamWithRetry(ctx, client, util.OpenAIProtocolChatCompletions, req, nil, maxRetries,
- requestTimeout, streamIdleTimeout, retryDelay, ch)
-}
-
func createProtocolStreamWithRetry(ctx context.Context, client *util.AIClient, protocol string,
req openai.ChatCompletionRequest, responseInput []any, maxRetries int, requestTimeout, streamIdleTimeout time.Duration,
retryDelay func(string, int) time.Duration,
diff --git a/kernel/agent/anthropic_test.go b/kernel/agent/anthropic_test.go
index f5f71f412d..beea78fcb7 100644
--- a/kernel/agent/anthropic_test.go
+++ b/kernel/agent/anthropic_test.go
@@ -70,7 +70,7 @@ func TestAnthropicAgentToolHistoryRecovery(t *testing.T) {
return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: "found"}}}, nil
}})
t.Cleanup(func() { tools.RemoveTool(toolName) })
- _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "native",
+ _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "native",
"createdAt": 1, "updatedAt": 1, "entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use tool"}}}))
if err != nil {
t.Fatal(err)
@@ -142,7 +142,7 @@ func TestAnthropicAgentToolHistoryRecovery(t *testing.T) {
}
canonical["entries"] = append(canonical["entries"].([]any), map[string]any{"id": "user-2", "type": "user", "content": "continue"})
canonical["expectedRevision"] = int64(2)
- if _, err = SaveSession(marshalSession(t, canonical)); err != nil {
+ if _, _, err = SaveSessionState(marshalSession(t, canonical)); err != nil {
t.Fatal(err)
}
run("user-2", 3, "continue", false)
@@ -231,14 +231,14 @@ func TestAnthropicCompactionPreservesRecentNativeHistory(t *testing.T) {
{ID: "assistant-2", Type: "assistant", Content: "recent answer", NativeContent: nativeHistoryContent("recent-signature", "recent answer")},
{ID: "user-3", Type: "user", Content: "continue"},
}
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "compact", "entries": entries})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "compact", "entries": entries})); err != nil {
t.Fatal(err)
}
capabilities := currentCapabilitiesForTest(t)
checkpoint := entriesToAgentMessages(entries)
- full := estimateProtocolRequestTokens("test", util.AnthropicProtocolMessages, checkpointMessagesToOpenAI(checkpoint, "English", nil), checkpoint, nil, capabilities.definitions)
+ full := estimateProtocolRequestTokens("test", util.AnthropicProtocolMessages, checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil), checkpoint, nil, capabilities.definitions)
recent := entriesToAgentMessages(entries[2:])
- base := estimateProtocolRequestTokens("test", util.AnthropicProtocolMessages, checkpointMessagesToOpenAI(recent, "English", nil), recent, nil, capabilities.definitions)
+ base := estimateProtocolRequestTokens("test", util.AnthropicProtocolMessages, checkpointMessagesToOpenAIWithSummary(recent, "English", nil, nil), recent, nil, capabilities.definitions)
limit := compactionTestContextLimit(t, full, base)
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -280,7 +280,7 @@ func TestAnthropicRegenerateUsesEditedHistory(t *testing.T) {
{ID: "user-2", Type: "user", Content: "obsolete prompt"},
{ID: "assistant-2", Type: "assistant", Content: "obsolete answer", NativeContent: nativeHistoryContent("obsolete-signature", "obsolete answer")},
}
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "regenerate", "entries": entries})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "regenerate", "entries": entries})); err != nil {
t.Fatal(err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -314,7 +314,7 @@ func TestAnthropicIncompleteToolDoesNotExecute(t *testing.T) {
return tools.CallToolResult{}, nil
}})
t.Cleanup(func() { tools.RemoveTool(toolName) })
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "entries": []SessionEntry{
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "entries": []SessionEntry{
{ID: "user-1", Type: "user", Content: "use tool"},
}})); err != nil {
t.Fatal(err)
diff --git a/kernel/agent/assistant_context_test.go b/kernel/agent/assistant_context_test.go
index 86afeb514d..f1cc000917 100644
--- a/kernel/agent/assistant_context_test.go
+++ b/kernel/agent/assistant_context_test.go
@@ -63,10 +63,6 @@ func TestResponsesContextPreservesEncryptedReasoningAndToolOutput(t *testing.T)
t.Fatalf("Responses output was duplicated as a reconstructed message: %s", payload)
}
- restored := entriesToAgentMessages(agentMessagesToEntries(messages))
- if len(restored) != 1 || len(restored[0].ResponseOutput) != 2 || restored[0].ResponseOutputTokens != 42 {
- t.Fatalf("Responses output was lost during entry persistence: %#v", restored)
- }
}
func TestResponsesContextProjectsMessageWithIncompatibleID(t *testing.T) {
@@ -162,7 +158,7 @@ func TestAgentChatResponsesToolContextSurvivesCommit(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use the tool"}},
}
- if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, session)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
@@ -313,7 +309,7 @@ func TestAgentChatResponsesToolContextSurvivesCommit(t *testing.T) {
"id": "user-2", "type": "user", "content": "continue",
})
canonical["expectedRevision"] = int64(2)
- if revision, err = SaveSession(marshalSession(t, canonical)); err != nil || revision != 3 {
+ if revision, _, err = SaveSessionState(marshalSession(t, canonical)); err != nil || revision != 3 {
t.Fatalf("save Responses follow-up failed: revision=%d, err=%v", revision, err)
}
@@ -409,7 +405,7 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use the tool"}},
}
- if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, session)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
@@ -497,7 +493,7 @@ func TestAgentChatRestoresCompleteAssistantContextAfterCommit(t *testing.T) {
"id": "user-2", "type": "user", "content": "continue",
})
canonical["expectedRevision"] = int64(2)
- revision, err = SaveSession(marshalSession(t, canonical))
+ revision, _, err = SaveSessionState(marshalSession(t, canonical))
if err != nil || revision != 3 {
t.Fatalf("save follow-up user message failed: revision=%d, err=%v", revision, err)
}
diff --git a/kernel/agent/attachments.go b/kernel/agent/attachments.go
index 970f0e3030..4fbf52c3a6 100644
--- a/kernel/agent/attachments.go
+++ b/kernel/agent/attachments.go
@@ -352,31 +352,6 @@ func containsAny(value string, candidates ...string) bool {
return false
}
-// createImageCompatibleStream 在上游明确拒绝图片且尚未产生输出时,使用纯文本请求投影兼容重试一次。
-func createImageCompatibleStream(
- ctx context.Context,
- client *util.AIClient,
- req openai.ChatCompletionRequest,
- capabilityKey string,
- forceDowngrade bool,
- maxRetries int,
- requestTimeout time.Duration,
- streamIdleTimeout time.Duration,
- retryDelay func(string, int) time.Duration,
- ch chan<- AgentEvent,
-) (
- stream *util.OpenAICompletionStream,
- firstResponse openai.ChatCompletionStreamResponse,
- cancel context.CancelFunc,
- requestMessages []openai.ChatCompletionMessage,
- downgraded bool,
- unsupportedDetected bool,
- err error,
-) {
- return createProtocolImageCompatibleStream(ctx, client, util.OpenAIProtocolChatCompletions, req, nil, capabilityKey,
- forceDowngrade, maxRetries, requestTimeout, streamIdleTimeout, retryDelay, ch)
-}
-
func createProtocolImageCompatibleStream(
ctx context.Context,
client *util.AIClient,
diff --git a/kernel/agent/attachments_test.go b/kernel/agent/attachments_test.go
index c40bd68fa9..c29092fc77 100644
--- a/kernel/agent/attachments_test.go
+++ b/kernel/agent/attachments_test.go
@@ -90,11 +90,11 @@ func TestCheckpointRestoresUserMessageImage(t *testing.T) {
{Role: "user", Content: "What is the title?", EntryID: "user-2"},
}
- initial := buildInitialMessages(checkpoint[0].Content, "English", nil, EditorContext{}, nil)
+ initial := checkpointMessagesToOpenAIWithSummary(checkpoint[:1], "English", nil, nil)
if len(initial) != 3 || !isAttachmentMessage(initial[2]) {
t.Fatalf("initial user image was not attached: %#v", initial)
}
- messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)
+ messages := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil)
if len(messages) != 5 || !isAttachmentMessage(messages[2]) {
t.Fatalf("user image was not restored after its message: %#v", messages)
}
@@ -295,8 +295,9 @@ func TestCreateImageCompatibleStreamDowngradesAndCaches(t *testing.T) {
defer server.Close()
call := func() {
- stream, _, cancel, requestMessages, downgraded, unsupportedDetected, err := createImageCompatibleStream(
- context.Background(), newTestOpenAIClient(server.URL), req, capabilityKey, false, 0,
+ stream, _, cancel, requestMessages, downgraded, unsupportedDetected, err := createProtocolImageCompatibleStream(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ req, nil, capabilityKey, false, 0,
time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),
)
if err != nil {
@@ -352,8 +353,9 @@ func TestCreateImageCompatibleStreamHandlesInitialSSEError(t *testing.T) {
}))
defer server.Close()
- stream, _, cancel, requestMessages, downgraded, unsupportedDetected, err := createImageCompatibleStream(
- context.Background(), newTestOpenAIClient(server.URL), req, "", false, 0,
+ stream, _, cancel, requestMessages, downgraded, unsupportedDetected, err := createProtocolImageCompatibleStream(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ req, nil, "", false, 0,
time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),
)
if err != nil {
@@ -407,8 +409,9 @@ func TestCreateImageCompatibleStreamKeepsTurnDowngradedAfterFallbackError(t *tes
}))
defer server.Close()
- _, _, _, _, downgraded, unsupportedDetected, err := createImageCompatibleStream(
- context.Background(), newTestOpenAIClient(server.URL), req, "", false, 0,
+ _, _, _, _, downgraded, unsupportedDetected, err := createProtocolImageCompatibleStream(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ req, nil, "", false, 0,
time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),
)
if err == nil || !downgraded || !unsupportedDetected {
@@ -416,8 +419,9 @@ func TestCreateImageCompatibleStreamKeepsTurnDowngradedAfterFallbackError(t *tes
err, downgraded, unsupportedDetected)
}
- stream, _, cancel, requestMessages, downgraded, repeatedDetection, err := createImageCompatibleStream(
- context.Background(), newTestOpenAIClient(server.URL), req, "", unsupportedDetected, 0,
+ stream, _, cancel, requestMessages, downgraded, repeatedDetection, err := createProtocolImageCompatibleStream(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ req, nil, "", unsupportedDetected, 0,
time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),
)
if err != nil {
@@ -450,8 +454,9 @@ func TestCreateImageCompatibleStreamKeepsUnrelatedValidationError(t *testing.T)
}))
defer server.Close()
- _, _, _, requestMessages, downgraded, unsupportedDetected, err := createImageCompatibleStream(
- context.Background(), newTestOpenAIClient(server.URL), req, "unrelated-error", false, 0,
+ _, _, _, requestMessages, downgraded, unsupportedDetected, err := createProtocolImageCompatibleStream(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ req, nil, "unrelated-error", false, 0,
time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 2),
)
if err == nil || downgraded || unsupportedDetected || !containsImageInput(requestMessages) || requests.Load() != 1 {
@@ -487,7 +492,7 @@ func TestCheckpointRestoresAttachmentAfterToolResults(t *testing.T) {
Attachments: []AgentAttachment{testAgentAttachment()},
}},
}}
- messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)
+ messages := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil)
if len(messages) != 4 {
t.Fatalf("unexpected restored message count: %d", len(messages))
}
@@ -561,7 +566,7 @@ func TestCheckpointKeepsOnlyLatestAttachmentBatch(t *testing.T) {
}},
},
}
- messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)
+ messages := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil)
encoded, err := json.Marshal(messages)
if err != nil {
t.Fatal(err)
@@ -655,7 +660,7 @@ func TestAgentChatSendsToolAttachmentToCurrentModel(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "look at the image"}},
}
- if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, session)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
diff --git a/kernel/agent/capability_test.go b/kernel/agent/capability_test.go
index 6a77af2c4b..b6433e9f2d 100644
--- a/kernel/agent/capability_test.go
+++ b/kernel/agent/capability_test.go
@@ -132,13 +132,13 @@ func TestCapabilityPolicyControlsExposureAndExecution(t *testing.T) {
Default: "allow",
Actions: map[string]string{"write": "confirm"},
}
- if needsCapabilityConfirm(backendRegistration, "delete", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(backendRegistration, "delete", nil, false, nil); required {
t.Fatal("capability auto approval was not applied")
}
- if !needsCapabilityConfirm(backendRegistration, "write", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(backendRegistration, "write", nil, false, nil); !required {
t.Fatal("action confirmation override was not applied")
}
- if !needsCapabilityConfirm(backendRegistration, "write", nil, true, nil) {
+ if required, _ := capabilityConfirmRequirement(backendRegistration, "write", nil, true, nil); !required {
t.Fatal("explicit confirmation was bypassed by the session approval mode")
}
@@ -227,14 +227,14 @@ func TestExplicitCapabilityConfirmationOverridesRiskAndSessionApproval(t *testin
Runtime: "kernel",
Tool: tools.SearchTool,
}
- if needsCapabilityConfirm(registration, "fulltext", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(registration, "fulltext", nil, false, nil); required {
t.Fatal("risk-based local search unexpectedly required confirmation")
}
required, forced := capabilityConfirmRequirement(registration, "semantic", nil, false, nil)
if !required || forced {
t.Fatal("risk-based semantic search did not require confirmation")
}
- if needsCapabilityConfirm(registration, "semantic", nil, true, nil) {
+ if required, _ := capabilityConfirmRequirement(registration, "semantic", nil, true, nil); required {
t.Fatal("session approval did not bypass risk-based confirmation")
}
@@ -250,7 +250,7 @@ func TestExplicitCapabilityConfirmationOverridesRiskAndSessionApproval(t *testin
if !required || !forced {
t.Fatal("session approval bypassed explicit capability confirmation")
}
- if needsCapabilityConfirm(registration, "semantic", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(registration, "semantic", nil, false, nil); required {
t.Fatal("action auto approval did not override capability confirmation")
}
}
diff --git a/kernel/agent/compaction.go b/kernel/agent/compaction.go
index 66cfe0bbb1..ceb22329c3 100644
--- a/kernel/agent/compaction.go
+++ b/kernel/agent/compaction.go
@@ -167,12 +167,6 @@ func compactionSummaryMessages(source string) []openai.ChatCompletionMessage {
}
}
-func createCompactionSummary(ctx context.Context, client *util.AIClient, model, source string, maxTokens, maxRetries int,
- requestTimeout, streamIdleTimeout time.Duration, ch chan<- AgentEvent) (summary string, promptTokens, completionTokens int, err error) {
- return createProtocolCompactionSummary(ctx, client, util.OpenAIProtocolChatCompletions, model, source, maxTokens,
- maxRetries, requestTimeout, streamIdleTimeout, ch)
-}
-
func createProtocolCompactionSummary(ctx context.Context, client *util.AIClient, protocol, model, source string,
maxTokens, maxRetries int, requestTimeout, streamIdleTimeout time.Duration,
ch chan<- AgentEvent) (summary string, promptTokens, completionTokens int, err error) {
@@ -280,11 +274,6 @@ func createResponseCompaction(ctx context.Context, client *util.AIClient, reques
return nil, 0, 0, lastErr
}
-func newRuntimeCompaction(entries []SessionEntry, coveredEntryCount int, summary string) (*runtimeCompaction, error) {
- return newRuntimeProtocolSummaryCompaction(
- entries, coveredEntryCount, summary, util.OpenAIProtocolChatCompletions)
-}
-
func newRuntimeProtocolSummaryCompaction(entries []SessionEntry, coveredEntryCount int, summary,
protocol string) (*runtimeCompaction, error) {
if coveredEntryCount <= 0 || len(entries) <= coveredEntryCount || entries[coveredEntryCount].ID == "" {
@@ -304,25 +293,3 @@ func newRuntimeProtocolSummaryCompaction(entries []SessionEntry, coveredEntryCou
UpdatedAt: time.Now().UnixMilli(),
}, nil
}
-
-func newRuntimeResponseCompaction(entries []SessionEntry, coveredEntryCount int,
- responseOutput []json.RawMessage, responseOutputTokens int) (*runtimeCompaction, error) {
- if coveredEntryCount <= 0 || len(entries) <= coveredEntryCount || entries[coveredEntryCount].ID == "" ||
- len(responseOutput) == 0 {
- return nil, errContextCannotBeCompacted
- }
- digest, err := compactionDigest(entries[:coveredEntryCount])
- if err != nil {
- return nil, err
- }
- return &runtimeCompaction{
- Version: compactionVersion,
- Protocol: util.OpenAIProtocolResponses,
- ResponseOutput: util.CloneOpenAIResponseOutput(responseOutput),
- ResponseOutputTokens: responseOutputTokens,
- CoveredEntryCount: coveredEntryCount,
- NextEntryID: entries[coveredEntryCount].ID,
- CoveredDigest: digest,
- UpdatedAt: time.Now().UnixMilli(),
- }, nil
-}
diff --git a/kernel/agent/compaction_context_test.go b/kernel/agent/compaction_context_test.go
index d018f2a58d..807140ecfe 100644
--- a/kernel/agent/compaction_context_test.go
+++ b/kernel/agent/compaction_context_test.go
@@ -116,7 +116,12 @@ func TestMessageCompactionSurvivesRecoveryAndInvalidatesEdits(t *testing.T) {
t.Fatal(err)
}
state.Summary = "progress"
- entries := agentMessagesToEntries(messages)
+ entries := []SessionEntry{
+ {ID: "user", Type: "user", Content: "goal"},
+ {ID: "assistant", Type: "assistant", RoundID: "turn_0", ToolCalls: []AgentToolCall{
+ {ID: "call", State: "finished", Result: "complete result"},
+ }},
+ }
entries[1].ID = "runtime_changed_entry_id"
if !validRuntimeCompaction(entries, state) {
t.Fatal("recovered assistant entry ID invalidated a stable compaction")
@@ -201,7 +206,7 @@ func testAgentChatCompactsCurrentTurnWithoutLosingRecovery(t *testing.T, withVar
}
t.Cleanup(func() { tools.RemoveTool(toolName) })
kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{tools.CapabilityIDForTool(tool): "allow"}}
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "long task", "entries": []SessionEntry{{ID: "user", Type: "user", Content: rawGoal}}})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "long task", "entries": []SessionEntry{{ID: "user", Type: "user", Content: rawGoal}}})); err != nil {
t.Fatal(err)
}
var modelRequests, summaryRequests atomic.Int32
@@ -285,7 +290,7 @@ func testAgentChatCompactsCurrentTurnWithoutLosingRecovery(t *testing.T, withVar
if err != nil || !validRuntimeCompaction(session.Entries, runtime.Compaction) {
t.Fatalf("recovered history could not reuse compaction: %+v %v", runtime, err)
}
- if _, err = SaveSession(marshalSession(t, recovered)); err != nil {
+ if _, _, err = SaveSessionState(marshalSession(t, recovered)); err != nil {
t.Fatal(err)
}
canonical, err := GetSessionState(testSessionID, false)
@@ -293,7 +298,7 @@ func testAgentChatCompactsCurrentTurnWithoutLosingRecovery(t *testing.T, withVar
t.Fatalf("committing recovery lost original history: %+v %v", canonical, err)
}
canonical["entries"] = append(canonical["entries"].([]any), map[string]any{"id": "user-2", "type": "user", "content": "continue"})
- revision, err := SaveSession(marshalSession(t, canonical))
+ revision, _, err := SaveSessionState(marshalSession(t, canonical))
if err != nil {
t.Fatal(err)
}
@@ -308,7 +313,7 @@ func testAgentChatCompactsCurrentTurnWithoutLosingRecovery(t *testing.T, withVar
if err != nil {
t.Fatal(err)
}
- revision, err = SaveSession(marshalSession(t, recovered))
+ revision, _, err = SaveSessionState(marshalSession(t, recovered))
if err != nil {
t.Fatal(err)
}
@@ -377,7 +382,8 @@ func TestCompactionSummaryRejectsTruncatedOutput(t *testing.T) {
writeTestStreamDone(t, w, flusher)
}))
defer server.Close()
- summary, _, _, err := createCompactionSummary(context.Background(), newTestOpenAIClient(server.URL), "test-model",
+ summary, _, _, err := createProtocolCompactionSummary(context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ "test-model",
"history", 512, 0, time.Second, time.Second, make(chan AgentEvent, 32))
if err == nil || summary != "" {
t.Fatalf("truncated summary was accepted: %q %v", summary, err)
@@ -394,12 +400,12 @@ func TestAgentChatReusesOnlyCompatibleCompaction(t *testing.T) {
{ID: "old-answer", Type: "assistant", Content: strings.Repeat("old result ", 12000)},
{ID: "current-user", Type: "user", Content: "continue"},
}
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "compatibility", "entries": entries})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "compatibility", "entries": entries})); err != nil {
t.Fatal(err)
}
state, err := newRuntimeMessageCompaction(entriesToAgentMessages(entries), 2, "openai", "test-model", compactionScopeKey("openai", "test-model", "provider"))
if name == "legacy" {
- state, err = newRuntimeCompaction(entries, 2, "original summary")
+ state, err = newRuntimeProtocolSummaryCompaction(entries, 2, "original summary", util.OpenAIProtocolChatCompletions)
}
if err != nil {
t.Fatal(err)
@@ -483,7 +489,7 @@ func testAgentChatNativeCompactsCurrentTurn(t *testing.T, failCompaction bool) {
}
t.Cleanup(func() { tools.RemoveTool(toolName) })
kernelModel.Conf.AI.Agent.CapabilityPolicy = &conf.CapabilityPolicy{Default: "deny", Overrides: map[string]string{tools.CapabilityIDForTool(tool): "allow"}}
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "native task", "entries": []SessionEntry{{ID: "user", Type: "user", Content: "complete task"}}})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "native task", "entries": []SessionEntry{{ID: "user", Type: "user", Content: "complete task"}}})); err != nil {
t.Fatal(err)
}
var requests, compactions atomic.Int32
@@ -570,7 +576,7 @@ func TestAgentChatCanceledCompactionKeepsCurrentTurn(t *testing.T) {
{ID: "user", Type: "user", Content: "complete the task"},
{ID: "assistant", Type: "assistant", RoundID: "old-round", ToolCalls: []AgentToolCall{{ID: "already-executed", Name: "test", Result: result, State: "finished"}}},
}
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "interrupted compaction", "entries": entries})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "interrupted compaction", "entries": entries})); err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
diff --git a/kernel/agent/compaction_test.go b/kernel/agent/compaction_test.go
index 5d51b57fb6..8b6ba42d0d 100644
--- a/kernel/agent/compaction_test.go
+++ b/kernel/agent/compaction_test.go
@@ -23,6 +23,7 @@ import (
"github.com/sashabaranov/go-openai"
kernelConf "github.com/siyuan-note/siyuan/kernel/conf"
kernelModel "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
func TestResponsesTokenBudgetIncludesOpaqueOutput(t *testing.T) {
@@ -109,8 +110,16 @@ func TestResponsesCompactionPreservesOpaqueOutput(t *testing.T) {
{ID: "assistant-1", Type: "assistant", Content: "old answer"},
{ID: "user-2", Type: "user", Content: "continue"},
}
- compaction, err := newRuntimeResponseCompaction(entries, 2, output, 4)
- if err != nil || !validRuntimeCompaction(entries, compaction) || compaction.ResponseOutputTokens != 4 {
+ digest, err := compactionDigest(entries[:2])
+ if err != nil {
+ t.Fatal(err)
+ }
+ compaction := &runtimeCompaction{
+ Version: compactionVersion, Protocol: util.OpenAIProtocolResponses,
+ ResponseOutput: output, ResponseOutputTokens: 4,
+ CoveredEntryCount: 2, NextEntryID: entries[2].ID, CoveredDigest: digest,
+ }
+ if !validRuntimeCompaction(entries, compaction) || compaction.ResponseOutputTokens != 4 {
t.Fatalf("response compaction is invalid: %#v, err=%v", compaction, err)
}
input := checkpointMessagesToOpenAIResponseInput(
@@ -200,7 +209,7 @@ func compactionTestEntries() []SessionEntry {
func TestRuntimeCompactionValidationUsesModelContextProjection(t *testing.T) {
entries := compactionTestEntries()
- compaction, err := newRuntimeCompaction(entries, 3, "Task and tool result retained")
+ compaction, err := newRuntimeProtocolSummaryCompaction(entries, 3, "Task and tool result retained", util.OpenAIProtocolChatCompletions)
if err != nil {
t.Fatal(err)
}
@@ -256,8 +265,9 @@ func TestCreateCompactionSummaryDoesNotSendTools(t *testing.T) {
}))
defer server.Close()
- summary, promptTokens, completionTokens, err := createCompactionSummary(
- context.Background(), newTestOpenAIClient(server.URL), "test-model", "history", 512, 0,
+ summary, promptTokens, completionTokens, err := createProtocolCompactionSummary(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ "test-model", "history", 512, 0,
time.Second, time.Second, make(chan AgentEvent, 1))
if err != nil {
t.Fatal(err)
@@ -284,8 +294,9 @@ func TestCreateCompactionSummaryPreservesProviderError(t *testing.T) {
}))
defer server.Close()
- _, _, _, err := createCompactionSummary(
- context.Background(), newTestOpenAIClient(server.URL), "test-model", "history", 512, 0,
+ _, _, _, err := createProtocolCompactionSummary(
+ context.Background(), newTestOpenAIClient(server.URL), util.OpenAIProtocolChatCompletions,
+ "test-model", "history", 512, 0,
time.Second, time.Second, make(chan AgentEvent, 1))
if err == nil {
t.Fatal("summary request unexpectedly succeeded")
@@ -308,7 +319,7 @@ func TestRuntimeCompactionPersistsBesideActiveTurn(t *testing.T) {
"updatedAt": int64(1),
"entries": entries,
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
turn := &agentRuntimeTurn{
@@ -322,7 +333,7 @@ func TestRuntimeCompactionPersistsBesideActiveTurn(t *testing.T) {
if err := beginRuntimeTurn(testSessionID, turn); err != nil {
t.Fatal(err)
}
- compaction, err := newRuntimeCompaction(entries, 3, "Persisted summary")
+ compaction, err := newRuntimeProtocolSummaryCompaction(entries, 3, "Persisted summary", util.OpenAIProtocolChatCompletions)
if err != nil {
t.Fatal(err)
}
@@ -363,16 +374,16 @@ func TestAgentChatCompactsBeforeSendingOversizedContext(t *testing.T) {
"updatedAt": int64(1),
"entries": entries,
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
checkpoint := entriesToAgentMessages(entries)
requestTools := currentCapabilitiesForTest(t).definitions
fullTokens := estimateChatRequestTokens(
- "test-model", checkpointMessagesToOpenAI(checkpoint, "English", nil), requestTools)
+ "test-model", checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil), requestTools)
recentTokens := estimateChatRequestTokens(
- "test-model", checkpointMessagesToOpenAI(entriesToAgentMessages(entries[2:]), "English", nil), requestTools)
+ "test-model", checkpointMessagesToOpenAIWithSummary(entriesToAgentMessages(entries[2:]), "English", nil, nil), requestTools)
contextLimit := compactionTestContextLimit(t, fullTokens, recentTokens)
if fullTokens <= contextInputBudget(contextLimit, 512) {
t.Fatalf("test context does not require compaction: full=%d, budget=%d", fullTokens,
@@ -454,7 +465,7 @@ func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {
"updatedAt": int64(1),
"entries": entries,
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
@@ -463,9 +474,9 @@ func TestAgentChatRegenerateCompactionUsesTruncatedEditedHistory(t *testing.T) {
newAgentUserMessage(editedTarget, "user-2", nil, EditorContext{}))
requestTools := currentCapabilitiesForTest(t).definitions
fullTokens := estimateChatRequestTokens(
- "test-model", checkpointMessagesToOpenAI(regenerateCheckpoint, "English", nil), requestTools)
+ "test-model", checkpointMessagesToOpenAIWithSummary(regenerateCheckpoint, "English", nil, nil), requestTools)
recentTokens := estimateChatRequestTokens(
- "test-model", checkpointMessagesToOpenAI(regenerateCheckpoint[2:], "English", nil), requestTools)
+ "test-model", checkpointMessagesToOpenAIWithSummary(regenerateCheckpoint[2:], "English", nil, nil), requestTools)
contextLimit := compactionTestContextLimit(t, fullTokens, recentTokens)
var requestCount atomic.Int32
@@ -550,15 +561,15 @@ func TestAgentChatRetriesOverflowAfterProactiveCompaction(t *testing.T) {
"updatedAt": int64(1),
"entries": entries,
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
requestTools := currentCapabilitiesForTest(t).definitions
fullTokens := estimateChatRequestTokens(
- "test-model", checkpointMessagesToOpenAI(entriesToAgentMessages(entries), "English", nil), requestTools)
+ "test-model", checkpointMessagesToOpenAIWithSummary(entriesToAgentMessages(entries), "English", nil, nil), requestTools)
afterFirstTokens := estimateChatRequestTokens(
- "test-model", checkpointMessagesToOpenAI(entriesToAgentMessages(entries[2:]), "English", nil), requestTools)
+ "test-model", checkpointMessagesToOpenAIWithSummary(entriesToAgentMessages(entries[2:]), "English", nil, nil), requestTools)
contextLimit := compactionTestContextLimit(t, fullTokens, afterFirstTokens)
var requestCount atomic.Int32
diff --git a/kernel/agent/decision_test.go b/kernel/agent/decision_test.go
index f9e3c80359..b1c306c6ed 100644
--- a/kernel/agent/decision_test.go
+++ b/kernel/agent/decision_test.go
@@ -34,7 +34,7 @@ func TestDecisionCapabilityAvailabilityAndApproval(t *testing.T) {
kernelModel.Conf.AI.Decision.Profiles["typesafe"].APIKey = "key"
set := check(true)
registration := set.registration("decision")
- if !tools.DecisionTool.AgentOnly || !needsCapabilityConfirm(registration, "evaluate", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(registration, "evaluate", nil, false, nil); !tools.DecisionTool.AgentOnly || !required {
t.Fatal("decision bypassed data egress/cost confirmation")
}
kernelModel.Conf.AI.Decision.Enabled = false
diff --git a/kernel/agent/gemini_parallel_tools_test.go b/kernel/agent/gemini_parallel_tools_test.go
index 9218243c21..8939ebfb69 100644
--- a/kernel/agent/gemini_parallel_tools_test.go
+++ b/kernel/agent/gemini_parallel_tools_test.go
@@ -85,7 +85,7 @@ func TestAgentChatPreservesUnindexedParallelGeminiToolCalls(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "use both tools"}},
}
- if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, session)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
diff --git a/kernel/agent/instructions_test.go b/kernel/agent/instructions_test.go
index c08d3aa9c5..259252582b 100644
--- a/kernel/agent/instructions_test.go
+++ b/kernel/agent/instructions_test.go
@@ -67,7 +67,7 @@ func TestAgentInstructionsTurnSnapshot(t *testing.T) {
sessionID := ast.NewNodeID()
session := map[string]any{"id": sessionID, "title": "instructions", "createdAt": 1, "updatedAt": 1,
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "test preferences"}}}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
for event := range AgentChat(context.Background(), newTestOpenAIClient(server.URL), "openai", "test-model", "", 0,
diff --git a/kernel/agent/plugin_workflow_test.go b/kernel/agent/plugin_workflow_test.go
index 0c570abf2e..2de16b3b93 100644
--- a/kernel/agent/plugin_workflow_test.go
+++ b/kernel/agent/plugin_workflow_test.go
@@ -42,7 +42,7 @@ func setupPluginWorkflow(t *testing.T) {
util.ReadOnly = origReadOnly
sessionLocks.Delete(testSessionID)
})
- if _, err := SaveSession(marshalSession(t, map[string]any{"id": testSessionID, "title": "plugin fixture", "entries": []any{}})); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, map[string]any{"id": testSessionID, "title": "plugin fixture", "entries": []any{}})); err != nil {
t.Fatal(err)
}
}
@@ -53,7 +53,7 @@ func executePluginFixtureTool(t *testing.T, name string, args map[string]any, su
if err != nil {
t.Fatal(err)
}
- result := executeTool(context.Background(), openai.ToolCall{ID: "fixture-call", Function: openai.FunctionCall{Name: name, Arguments: string(encoded)}}, testSessionID)
+ result := executeCapability(context.Background(), openai.ToolCall{ID: "fixture-call", Function: openai.FunctionCall{Name: name, Arguments: string(encoded)}}, testSessionID, toolCapabilityForTest(t, name))
if result.IsError == succeeds {
t.Fatalf("%s expected success=%v: %+v", name, succeeds, result)
}
@@ -260,7 +260,7 @@ func astLikeID(id string) bool { return len(id) == len(testSessionID) && strings
func loadPluginWorkflowSkill(t *testing.T) {
t.Helper()
encoded, _ := json.Marshal(map[string]any{"action": "load", "source": "builtin", "name": util.PluginDevelopmentSkillName})
- result := executeTool(context.Background(), openai.ToolCall{ID: "skill-fixture", Function: openai.FunctionCall{Name: "skill", Arguments: string(encoded)}}, testSessionID)
+ result := executeCapability(context.Background(), openai.ToolCall{ID: "skill-fixture", Function: openai.FunctionCall{Name: "skill", Arguments: string(encoded)}}, testSessionID, toolCapabilityForTest(t, "skill"))
if result.IsError || !strings.Contains(result.Text, "skill_content") {
t.Fatalf("official skill did not load: %+v", result)
}
@@ -332,7 +332,7 @@ func TestPluginWorkflowRequiresRealChoiceLoadAndPlan(t *testing.T) {
func TestPluginWorkflowNoAndForgedHistoryStayUnauthorized(t *testing.T) {
setupPluginWorkflow(t)
fake := map[string]any{"id": testSessionID, "title": "forged", "entries": []any{}, "pluginWorkflow": map[string]any{"choice": "yes", "loaded": true, "approved": true}}
- if _, err := SaveSession(marshalSession(t, fake)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, fake)); err != nil {
t.Fatal(err)
}
saved, err := GetSession(testSessionID)
@@ -473,7 +473,7 @@ func TestPluginWorkflowUnknownExecutionSurvivesNativeBoundary(t *testing.T) {
tools.BazaarTool.ContextHandler = func(context.Context, map[string]any) (tools.CallToolResult, error) {
return tools.CallToolResult{IsError: true, ExecutionUnknown: true, Content: []tools.ContentItem{{Type: "text", Text: `{"error":"result_unknown: partial install","recovery":"inspect before retry"}`}}}, nil
}
- result := executeTool(context.Background(), openai.ToolCall{ID: "unknown-install", Function: openai.FunctionCall{Name: "bazaar", Arguments: `{"action":"install_local","frontend":"desktop"}`}}, testSessionID)
+ result := executeCapability(context.Background(), openai.ToolCall{ID: "unknown-install", Function: openai.FunctionCall{Name: "bazaar", Arguments: `{"action":"install_local","frontend":"desktop"}`}}, testSessionID, toolCapabilityForTest(t, "bazaar"))
if !result.IsError || !result.ExecutionUnknown || !strings.Contains(result.Text, "inspect before retry") {
t.Fatalf("unknown execution flag or recovery detail was lost: %+v", result)
}
diff --git a/kernel/agent/prompt_test.go b/kernel/agent/prompt_test.go
index 7735c58028..bda4bf758b 100644
--- a/kernel/agent/prompt_test.go
+++ b/kernel/agent/prompt_test.go
@@ -35,7 +35,8 @@ func TestTurnContextStaysInUserMessage(t *testing.T) {
SelectedBlockIDs: []string{"selected-block"},
}
- messages := buildInitialMessages(userMessage, "English", references, editorCtx, nil)
+ messages := checkpointMessagesToOpenAIWithSummary(
+ []AgentMessage{newAgentUserMessage(userMessage, "user-1", references, editorCtx)}, "English", nil, nil)
if len(messages) != 2 {
t.Fatalf("unexpected message count: %d", len(messages))
}
@@ -158,7 +159,7 @@ func TestCheckpointMessagesKeepHistoricalTurnContexts(t *testing.T) {
newAgentUserMessage("second question", "user-2", nil, EditorContext{ActiveDocID: "doc-b"}),
}
- messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)
+ messages := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil)
if len(messages) != 4 {
t.Fatalf("unexpected message count: %d", len(messages))
}
@@ -173,7 +174,7 @@ func TestCheckpointMessagesKeepHistoricalTurnContexts(t *testing.T) {
}
}
-func TestUserTurnContextSurvivesCheckpointRoundTrip(t *testing.T) {
+func TestUserTurnContextRestoresFromEntries(t *testing.T) {
editorCtx := &EditorContext{
ActiveDocID: "round-trip-doc",
VisibleBlockIDs: []string{"visible-block"},
@@ -190,22 +191,18 @@ func TestUserTurnContextSurvivesCheckpointRoundTrip(t *testing.T) {
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])
+ if checkpoint[0].EditorContext.ActiveDocID != "round-trip-doc" ||
+ len(checkpoint[0].References) != 1 || checkpoint[0].References[0].ID != "round-trip-ref" {
+ t.Fatalf("turn context changed during checkpoint restoration: %#v", checkpoint[0])
}
checkpoint[0].EditorContext.VisibleBlockIDs[0] = "changed"
- if editorCtx.VisibleBlockIDs[0] != "visible-block" || roundTripped[0].EditorContext.VisibleBlockIDs[0] != "visible-block" {
+ if editorCtx.VisibleBlockIDs[0] != "visible-block" {
t.Fatal("editor context slices were not cloned")
}
}
-func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {
+func TestAssistantContextRestoresFromEntries(t *testing.T) {
const argumentsJSON = "{\n \"query\": \"SiYuan\",\n \"limit\": 9007199254740993\n}"
entries := []SessionEntry{{
ID: "assistant-1",
@@ -243,7 +240,7 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {
t.Fatalf("thought signature was not restored into request state: %q", got)
}
- messages := checkpointMessagesToOpenAI(checkpoint, "English", nil)
+ messages := checkpointMessagesToOpenAIWithSummary(checkpoint, "English", nil, nil)
if len(messages) != 3 {
t.Fatalf("unexpected rebuilt message count: %d", len(messages))
}
@@ -257,15 +254,6 @@ func TestAssistantContextSurvivesCheckpointRoundTrip(t *testing.T) {
t.Fatalf("tool result no longer matches the original call: %#v", messages[2])
}
- roundTripped := agentMessagesToEntries(checkpoint)
- if len(roundTripped) != 1 || roundTripped[0].ReasoningCont != entries[0].ReasoningCont ||
- roundTripped[0].RoundID != entries[0].RoundID ||
- len(roundTripped[0].ToolCalls) != 1 || roundTripped[0].ToolCalls[0].ID != "call-original" ||
- roundTripped[0].ToolCalls[0].ArgumentsJSON != argumentsJSON ||
- roundTripped[0].ToolCalls[0].ProviderData == nil || roundTripped[0].ToolCalls[0].ProviderData.Google == nil ||
- roundTripped[0].ToolCalls[0].ProviderData.Google.ThoughtSignature != "thought-signature" {
- t.Fatalf("assistant context changed during checkpoint round trip: %#v", roundTripped)
- }
}
func TestAvailableSkillsSegmentEscapesMetadata(t *testing.T) {
diff --git a/kernel/agent/session.go b/kernel/agent/session.go
index 0fc467b425..35d8b57366 100644
--- a/kernel/agent/session.go
+++ b/kernel/agent/session.go
@@ -312,11 +312,6 @@ func GetSessionState(id string, includeRuntime bool) (map[string]any, error) {
return session, nil
}
-func SaveSession(data []byte) (int64, error) {
- revision, _, err := SaveSessionState(data)
- return revision, err
-}
-
func SaveSessionState(data []byte) (int64, map[string]any, error) {
var meta sessionMeta
if err := gulu.JSON.UnmarshalJSON(data, &meta); err != nil || meta.ID == "" || !isValidSessionID(meta.ID) {
diff --git a/kernel/agent/session_test.go b/kernel/agent/session_test.go
index 53f564259c..73e39193e3 100644
--- a/kernel/agent/session_test.go
+++ b/kernel/agent/session_test.go
@@ -50,7 +50,7 @@ func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
"future": map[string]any{"enabled": true},
}
- revision, err := SaveSession(marshalSession(t, base))
+ revision, _, err := SaveSessionState(marshalSession(t, base))
if err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
@@ -81,7 +81,7 @@ func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
"entries": base["entries"],
"expectedRevision": int64(0),
}
- revision, err = SaveSession(marshalSession(t, stale))
+ revision, _, err = SaveSessionState(marshalSession(t, stale))
if !errors.Is(err, ErrSessionConflict) || revision != 1 {
t.Fatalf("expected revision conflict: revision=%d, err=%v", revision, err)
}
@@ -95,7 +95,7 @@ func TestSaveSessionRevisionConflictAndUnknownFields(t *testing.T) {
"expectedRevision": int64(1),
"lastCommittedTurnID": "forged-turn",
}
- revision, err = SaveSession(marshalSession(t, update))
+ revision, _, err = SaveSessionState(marshalSession(t, update))
if err != nil || revision != 2 {
t.Fatalf("save updated session failed: revision=%d, err=%v", revision, err)
}
@@ -126,7 +126,7 @@ func TestSessionPermissionCanBeRevoked(t *testing.T) {
"alwaysAllow": true,
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, base)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
session, err := GetSession(testSessionID)
@@ -184,7 +184,7 @@ func TestConfirmSessionPersistsAlwaysAllowBeforeAccepting(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, base)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
controller, err := registerSessionPermissionController(testSessionID)
@@ -228,7 +228,7 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, base)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
@@ -316,12 +316,12 @@ func TestRuntimeRecoveryCommitDoesNotDuplicateHistory(t *testing.T) {
}
wrongCommit["expectedRevision"] = int64(1)
wrongCommit["commitTurnID"] = "20260715120009-abcdefg"
- if revision, err := SaveSession(marshalSession(t, wrongCommit)); !errors.Is(err, ErrSessionConflict) || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, wrongCommit)); !errors.Is(err, ErrSessionConflict) || revision != 1 {
t.Fatalf("mismatched runtime commit was accepted: revision=%d, err=%v", revision, err)
}
recovered["expectedRevision"] = int64(1)
- if revision, err := SaveSession(marshalSession(t, recovered)); !errors.Is(err, ErrRuntimeNotFinalized) || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, recovered)); !errors.Is(err, ErrRuntimeNotFinalized) || revision != 1 {
t.Fatalf("running runtime turn was committed: revision=%d, err=%v", revision, err)
}
turn.State = "interrupted"
@@ -427,7 +427,7 @@ func TestRegenerateRuntimeRecoveryKeepsEditedUserContent(t *testing.T) {
map[string]any{"id": "assistant-2", "type": "assistant", "content": "later answer"},
},
}
- if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, base)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
@@ -518,7 +518,7 @@ func TestRejectedNewSessionDoesNotCreateDirectory(t *testing.T) {
"entries": []any{},
"expectedRevision": expectedRevision,
}
- if _, err := SaveSession(marshalSession(t, session)); !errors.Is(err, ErrSessionConflict) {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); !errors.Is(err, ErrSessionConflict) {
t.Fatalf("expected revision conflict, got %v", err)
}
if _, err := os.Stat(filepath.Join(sessionsDir(), sessionID)); !os.IsNotExist(err) {
@@ -543,7 +543,7 @@ func TestSaveSessionRejectsCorruptExistingData(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{},
}
- if _, err := SaveSession(marshalSession(t, data)); err == nil {
+ if _, _, err := SaveSessionState(marshalSession(t, data)); err == nil {
t.Fatal("corrupt existing session was overwritten")
}
raw, err := os.ReadFile(path)
@@ -564,7 +564,7 @@ func TestBeginRuntimeTurnRejectsStaleRevision(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, base)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
turn := &agentRuntimeTurn{
@@ -591,7 +591,7 @@ func TestFinalizeOrphanedTurnMakesRuntimeRecoverable(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if revision, err := SaveSession(marshalSession(t, base)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, base)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
turn := &agentRuntimeTurn{
@@ -633,7 +633,7 @@ func TestFinalizeOrphanedTurnMakesRuntimeRecoverable(t *testing.T) {
t.Fatalf("orphaned runtime recovery metadata is incomplete: %#v", recovered)
}
recovered["expectedRevision"] = int64(1)
- if revision, err := SaveSession(marshalSession(t, recovered)); err != nil || revision != 2 {
+ if revision, _, err := SaveSessionState(marshalSession(t, recovered)); err != nil || revision != 2 {
t.Fatalf("commit finalized orphan failed: revision=%d, err=%v", revision, err)
}
if turnID, err := RecoverableTurnID(testSessionID); err != nil || turnID != "" {
@@ -661,7 +661,7 @@ func TestGetSessionRejectsRuntimeWithoutUserAnchor(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
turn := &agentRuntimeTurn{
@@ -718,7 +718,7 @@ func TestGetSessionRejectsIncompatibleRuntimeMetadata(t *testing.T) {
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(runtimePath(testSessionID), marshalSession(t, test.runtime), 0644); err != nil {
diff --git a/kernel/agent/snippet_test.go b/kernel/agent/snippet_test.go
index 781631ba1b..2810500f43 100644
--- a/kernel/agent/snippet_test.go
+++ b/kernel/agent/snippet_test.go
@@ -24,7 +24,7 @@ func TestSnippetWritesAlwaysRequireExplicitConfirmation(t *testing.T) {
}
}
for _, action := range []string{"list", "get"} {
- if needsCapabilityConfirm(registration, action, nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(registration, action, nil, false, nil); required {
t.Fatalf("read %s unexpectedly requires confirmation", action)
}
}
diff --git a/kernel/agent/stream_timeout_test.go b/kernel/agent/stream_timeout_test.go
index 815082e67d..5c07730528 100644
--- a/kernel/agent/stream_timeout_test.go
+++ b/kernel/agent/stream_timeout_test.go
@@ -39,7 +39,7 @@ func TestStreamIdleTimeoutResetsAfterEachChunk(t *testing.T) {
defer server.Close()
client := newTestOpenAIClient(server.URL)
- stream, _, cancel, err := createStreamWithRetry(context.Background(), client, testChatRequest(), 0, time.Second, 250*time.Millisecond, noRetryDelay, make(chan AgentEvent, 1))
+ stream, _, cancel, err := createProtocolStreamWithRetry(context.Background(), client, util.OpenAIProtocolChatCompletions, testChatRequest(), nil, 0, time.Second, 250*time.Millisecond, noRetryDelay, make(chan AgentEvent, 1))
if err != nil {
t.Fatalf("create stream failed: %v", err)
}
@@ -194,7 +194,7 @@ func TestStreamIdleTimeoutAfterPartialResponse(t *testing.T) {
defer server.Close()
client := newTestOpenAIClient(server.URL)
- stream, _, cancel, err := createStreamWithRetry(context.Background(), client, testChatRequest(), 0, time.Second, 50*time.Millisecond, noRetryDelay, make(chan AgentEvent, 1))
+ stream, _, cancel, err := createProtocolStreamWithRetry(context.Background(), client, util.OpenAIProtocolChatCompletions, testChatRequest(), nil, 0, time.Second, 50*time.Millisecond, noRetryDelay, make(chan AgentEvent, 1))
if err != nil {
t.Fatalf("create stream failed: %v", err)
}
@@ -223,7 +223,7 @@ func TestCreateStreamRetriesFirstResponseTimeoutWithFreshContext(t *testing.T) {
events := make(chan AgentEvent, 2)
client := newTestOpenAIClient(server.URL)
- stream, first, cancel, err := createStreamWithRetry(context.Background(), client, testChatRequest(), 1, time.Second, 50*time.Millisecond, noRetryDelay, events)
+ stream, first, cancel, err := createProtocolStreamWithRetry(context.Background(), client, util.OpenAIProtocolChatCompletions, testChatRequest(), nil, 1, time.Second, 50*time.Millisecond, noRetryDelay, events)
if err != nil {
t.Fatalf("create stream failed: %v", err)
}
@@ -258,7 +258,7 @@ func TestCreateStreamRequestTimeoutAndZeroRetries(t *testing.T) {
defer server.Close()
client := newTestOpenAIClient(server.URL)
- _, _, cancel, err := createStreamWithRetry(context.Background(), client, testChatRequest(), 0, 50*time.Millisecond, time.Second, noRetryDelay, make(chan AgentEvent, 1))
+ _, _, cancel, err := createProtocolStreamWithRetry(context.Background(), client, util.OpenAIProtocolChatCompletions, testChatRequest(), nil, 0, 50*time.Millisecond, time.Second, noRetryDelay, make(chan AgentEvent, 1))
if cancel != nil {
cancel()
}
@@ -288,7 +288,7 @@ func TestCreateStreamRetriesRequestTimeoutWithFreshContext(t *testing.T) {
defer server.Close()
client := newTestOpenAIClient(server.URL)
- stream, first, cancel, err := createStreamWithRetry(context.Background(), client, testChatRequest(), 1, 50*time.Millisecond, time.Second, noRetryDelay, make(chan AgentEvent, 2))
+ stream, first, cancel, err := createProtocolStreamWithRetry(context.Background(), client, util.OpenAIProtocolChatCompletions, testChatRequest(), nil, 1, 50*time.Millisecond, time.Second, noRetryDelay, make(chan AgentEvent, 2))
if err != nil {
t.Fatalf("create stream failed: %v", err)
}
@@ -321,7 +321,7 @@ func TestAgentChatPartialStreamTimeoutSavesInterruptedWithoutRetry(t *testing.T)
"updatedAt": int64(1),
"entries": []any{map[string]any{"id": "user-1", "type": "user", "content": "hello"}},
}
- if revision, err := SaveSession(marshalSession(t, session)); err != nil || revision != 1 {
+ if revision, _, err := SaveSessionState(marshalSession(t, session)); err != nil || revision != 1 {
t.Fatalf("save initial session failed: revision=%d, err=%v", revision, err)
}
@@ -374,7 +374,7 @@ func TestCreateStreamAcceptsEmptySuccessfulResponse(t *testing.T) {
defer server.Close()
client := newTestOpenAIClient(server.URL)
- stream, _, cancel, err := createStreamWithRetry(context.Background(), client, testChatRequest(), 1, time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 1))
+ stream, _, cancel, err := createProtocolStreamWithRetry(context.Background(), client, util.OpenAIProtocolChatCompletions, testChatRequest(), nil, 1, time.Second, time.Second, noRetryDelay, make(chan AgentEvent, 1))
if err != nil {
t.Fatalf("create stream failed: %v", err)
}
diff --git a/kernel/agent/tools.go b/kernel/agent/tools.go
index 862079383a..b2fdb26afd 100644
--- a/kernel/agent/tools.go
+++ b/kernel/agent/tools.go
@@ -35,24 +35,6 @@ type executedToolResult struct {
ExecutionUnknown bool
}
-// validateToolCallInput 在确认和快照之前校验工具调用,避免无效调用被误判为写操作。
-func validateToolCallInput(ctx context.Context, toolName string, args map[string]any) (*tools.Tool, *tools.ToolValidator, error) {
- t, validator := tools.LookupToolWithValidator(toolName)
- if t == nil {
- return nil, nil, fmt.Errorf("unknown tool: %s", toolName)
- }
- if t.ContextHandler == nil && t.Handler == nil {
- return nil, nil, fmt.Errorf("tool handler unavailable: %s", toolName)
- }
- if ctx.Err() != nil {
- return nil, nil, fmt.Errorf("tool execution was cancelled before it started")
- }
- if err := validator.ValidateInputContext(ctx, args); err != nil {
- return nil, nil, fmt.Errorf("invalid tool arguments: %w", err)
- }
- return t, validator, nil
-}
-
func validateCapabilityCall(ctx context.Context, registration *capabilityRegistration, args map[string]any) error {
if registration == nil {
return fmt.Errorf("capability was not exposed in this model round")
@@ -81,22 +63,6 @@ func validateCapabilityCall(ctx context.Context, registration *capabilityRegistr
return nil
}
-// executeTool 执行单次工具调用。
-func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) executedToolResult {
- tool, validator := tools.LookupToolWithValidator(tc.Function.Name)
- if tool == nil {
- return executedToolResult{Text: "unknown tool: " + tc.Function.Name, IsError: true}
- }
- return executeCapability(ctx, tc, sessionID, &capabilityRegistration{
- ID: tools.CapabilityIDForTool(tool),
- ModelName: tool.Name,
- Source: tool.Source,
- Runtime: tool.Runtime,
- Tool: tool,
- Validator: validator,
- })
-}
-
func executeCapability(ctx context.Context, tc openai.ToolCall, sessionID string,
registration *capabilityRegistration) executedToolResult {
if registration != nil && registration.Tool != nil && (registration.Tool.Source == "native" || registration.Tool.Source == "") {
diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.go
index f6c82e585a..8cd03e1293 100644
--- a/kernel/agent/tools_test.go
+++ b/kernel/agent/tools_test.go
@@ -221,22 +221,35 @@ func TestExecuteToolPreservesModelAttachments(t *testing.T) {
})
t.Cleanup(func() { tools.RemoveTool(toolName) })
- result := executeTool(context.Background(), openai.ToolCall{
+ result := executeCapability(context.Background(), openai.ToolCall{
Function: openai.FunctionCall{Name: toolName, Arguments: `{}`},
- }, "")
+ }, "", toolCapabilityForTest(t, toolName))
if result.Text != "attached" || result.IsError || len(result.ModelAttachments) != 1 ||
string(result.ModelAttachments[0].Data) != "image" {
t.Fatalf("model attachment was not preserved: %#v", result)
}
}
-func TestValidateToolCallInputRejectsMissingActionBeforeConfirmation(t *testing.T) {
+func toolCapabilityForTest(t *testing.T, name string) *capabilityRegistration {
+ t.Helper()
+ tool, validator := tools.LookupToolWithValidator(name)
+ if tool == nil || validator == nil {
+ t.Fatalf("missing test capability: %s", name)
+ }
+ return &capabilityRegistration{
+ ID: tools.CapabilityIDForTool(tool), ModelName: tool.Name,
+ Source: tool.Source, Runtime: tool.Runtime, Tool: tool, Validator: validator,
+ }
+}
+
+func TestValidateCapabilityCallRejectsMissingActionBeforeConfirmation(t *testing.T) {
args := map[string]any{"id": "20260707184942-prjqwqo"}
- if _, _, err := validateToolCallInput(t.Context(), "outline", args); err == nil {
+ registration := toolCapabilityForTest(t, "outline")
+ if err := validateCapabilityCall(t.Context(), registration, args); err == nil {
t.Fatal("outline without its required action must fail validation before confirmation")
}
args["action"] = "get"
- if _, _, err := validateToolCallInput(t.Context(), "outline", args); err != nil {
+ if err := validateCapabilityCall(t.Context(), registration, args); err != nil {
t.Fatalf("valid outline arguments were rejected: %s", err)
}
}
@@ -382,15 +395,15 @@ func TestQueryToolActionEffects(t *testing.T) {
func TestBrowserCapabilityEffects(t *testing.T) {
native := &capabilityRegistration{ID: "native/frontend/open_search", ModelName: "frontend__open_search", Source: "native", Runtime: "browser"}
- if needsCapabilityConfirm(native, "", nil, false, nil) || needsCapabilitySnapshot(native, "") {
+ if required, _ := capabilityConfirmRequirement(native, "", nil, false, nil); required || needsCapabilitySnapshot(native, "") {
t.Fatal("built-in browser capability must not require confirmation or create a snapshot")
}
pluginUnknown := &capabilityRegistration{ID: "plugin/frontend/example/run", ModelName: "frontend__plugin_run", Source: "plugin", Runtime: "browser"}
- if !needsCapabilityConfirm(pluginUnknown, "", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(pluginUnknown, "", nil, false, nil); !required {
t.Fatal("plugin browser capability with unknown effects must require confirmation")
}
pluginRead := &capabilityRegistration{ID: "plugin/frontend/example/read", ModelName: "frontend__plugin_read", Source: "plugin", Runtime: "browser", Effects: tools.ToolEffects{LocalRead: true}, EffectsDeclared: true}
- if needsCapabilityConfirm(pluginRead, "", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(pluginRead, "", nil, false, nil); required {
t.Fatal("plugin browser capability declared local-read-only must not require confirmation")
}
pluginActions := &capabilityRegistration{
@@ -400,12 +413,13 @@ func TestBrowserCapabilityEffects(t *testing.T) {
"write": {LocalWrite: true},
},
}
- if needsCapabilityConfirm(pluginActions, "read", nil, false, nil) {
+ if required, _ := capabilityConfirmRequirement(pluginActions, "read", nil, false, nil); required {
t.Fatal("plugin browser action with explicit read effects must not require confirmation")
}
- if !needsCapabilityConfirm(pluginActions, "write", nil, false, nil) ||
- !needsCapabilityConfirm(pluginActions, "unknown", nil, false, nil) {
- t.Fatal("plugin browser write or undeclared action must require confirmation")
+ for _, action := range []string{"write", "unknown"} {
+ if required, _ := capabilityConfirmRequirement(pluginActions, action, nil, false, nil); !required {
+ t.Fatal("plugin browser write or undeclared action must require confirmation")
+ }
}
for _, action := range []string{"html", "preview"} {
if needsConfirm("export", action, nil) || needsLocalSnapshot("export", action) {
@@ -643,9 +657,9 @@ func TestExecuteToolPropagatesUnknownExecution(t *testing.T) {
})
t.Cleanup(func() { tools.RemoveTool(toolName) })
- result := executeTool(context.Background(), openai.ToolCall{
+ result := executeCapability(context.Background(), openai.ToolCall{
Function: openai.FunctionCall{Name: toolName, Arguments: `{}`},
- }, "")
+ }, "", toolCapabilityForTest(t, toolName))
if result.Text != "result unknown" || !result.IsError || !result.ExecutionUnknown {
t.Fatalf("unexpected tool result: %#v", result)
}
@@ -669,9 +683,9 @@ func TestExecuteToolRejectsInvalidStructuredOutput(t *testing.T) {
}
t.Cleanup(func() { tools.RemoveTool(toolName) })
- result := executeTool(context.Background(), openai.ToolCall{
+ result := executeCapability(context.Background(), openai.ToolCall{
Function: openai.FunctionCall{Name: toolName, Arguments: `{}`},
- }, "")
+ }, "", toolCapabilityForTest(t, toolName))
if !result.IsError || !result.ExecutionUnknown || !strings.Contains(result.Text, "must not be retried automatically") {
t.Fatalf("unexpected tool result: %#v", result)
}
@@ -698,9 +712,9 @@ func TestExecuteToolCancellationMarksExecutionUnknown(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
resultCh := make(chan executedToolResult, 1)
go func() {
- resultCh <- executeTool(ctx, openai.ToolCall{
+ resultCh <- executeCapability(ctx, openai.ToolCall{
Function: openai.FunctionCall{Name: toolName, Arguments: `{}`},
- }, "")
+ }, "", toolCapabilityForTest(t, toolName))
}()
<-started
cancel()
@@ -725,9 +739,9 @@ func TestExecuteToolDoesNotStartAfterCancellation(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
- result := executeTool(ctx, openai.ToolCall{
+ result := executeCapability(ctx, openai.ToolCall{
Function: openai.FunctionCall{Name: toolName, Arguments: `{}`},
- }, "")
+ }, "", toolCapabilityForTest(t, toolName))
if invoked || result.Text == "" || !result.IsError || result.ExecutionUnknown {
t.Fatalf("pre-cancelled tool was handled incorrectly: invoked=%v, result=%#v", invoked, result)
}
diff --git a/kernel/agent/variables_test.go b/kernel/agent/variables_test.go
index c7b5c928b2..6edfff767e 100644
--- a/kernel/agent/variables_test.go
+++ b/kernel/agent/variables_test.go
@@ -32,7 +32,7 @@ func TestAgentChatResolvesSavedUserVariables(t *testing.T) {
"id": testSessionID, "title": "variables", "createdAt": int64(1), "updatedAt": int64(1),
"entries": []SessionEntry{{ID: "user-1", Type: "user", Content: raw}},
}
- if _, err := SaveSession(marshalSession(t, session)); err != nil {
+ if _, _, err := SaveSessionState(marshalSession(t, session)); err != nil {
t.Fatal(err)
}
payloads := make(chan []openai.ChatCompletionMessage, 1)