An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Accept unsigned thinking blocks from Anthropic-compatible providers
Danielad6243509e6a
diff --git a/kernel/agent/anthropic_test.go b/kernel/agent/anthropic_test.goindex 5bbfd1dc85..be725fddfc 100644--- a/kernel/agent/anthropic_test.go+++ b/kernel/agent/anthropic_test.go@@ -54,6 +54,109 @@ func TestAnthropicAgentToolHistoryRecovery(t *testing.T) {testNativeAgentToolHistoryRecovery(t, util.AnthropicProtocolMessages, "/v1/messages", "messages", "tool_result", writeAnthropicAgentResponse)}+func TestAnthropicAgentUnsignedToolHistoryRecovery(t *testing.T) {+ setupCompactionAgentTest(t)+ const toolName = "test_anthropic_unsigned_history"+ var executions atomic.Int32+ tools.SetTool(toolName, &tools.Tool{Name: toolName, Source: "native", ReadOnlyHint: true,+ InputSchema: tools.ToolSchema{Type: "object", Properties: map[string]tools.Property{"action": {Type: "string"}}},+ ActionEffects: map[string]tools.ToolEffects{"list": {LocalRead: true}},+ Handler: func(map[string]any) (tools.CallToolResult, error) {+ executions.Add(1)+ return tools.CallToolResult{Content: []tools.ContentItem{{Type: "text", Text: "found"}}}, nil+ }})+ t.Cleanup(func() { tools.RemoveTool(toolName) })+ 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)+ }+ var requests atomic.Int32+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var payload struct {+ Messages []struct {+ Role string `json:"role"`+ Content []json.RawMessage `json:"content"`+ } `json:"messages"`+ }+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {+ t.Error(err)+ }+ n := requests.Add(1)+ if n >= 2 {+ var thinkingBlocks, toolResults int+ for _, message := range payload.Messages {+ for _, raw := range message.Content {+ var block map[string]any+ if err := json.Unmarshal(raw, &block); err != nil {+ t.Error(err)+ }+ if block["type"] == "thinking" {+ thinkingBlocks+++ if message.Role != "assistant" || block["thinking"] != "reasoning" || block["signature"] != "" {+ t.Errorf("unsigned thinking changed: %s", raw)+ }+ }+ if block["type"] == "tool_result" {+ toolResults+++ content, ok := block["content"].(string)+ if message.Role != "user" || block["tool_use_id"] != "native_tool" || !ok || !strings.Contains(content, "found") {+ t.Errorf("tool result changed: %s", raw)+ }+ }+ }+ }+ if thinkingBlocks != int(n)-1 || toolResults != 1 {+ t.Errorf("native history was lost: thinking=%d tool results=%d request=%d", thinkingBlocks, toolResults, n)+ }+ }+ if n == 1 {+ writeAnthropicAgentResponse(t, w, "", "", toolName, true)+ } else {+ writeAnthropicAgentResponse(t, w, "", "answer", "", true)+ }+ }))+ defer server.Close()+ client := util.NewAIClientWithModel("key", server.URL, "test")+ run := func(userID string, revision int64, message string) string {+ t.Helper()+ turnID := ""+ for event := range AgentChat(context.Background(), client, util.AnthropicProtocolMessages, "test", "", 0,+ testSessionID, userID, revision, message, nil, "English", nil, EditorContext{}, nil, false,+ time.Second, 0, "", time.Second, time.Second) {+ if event.Type == "error" {+ t.Fatalf("unsigned thinking failed: %s", event.Error)+ }+ if event.Type == "turn" {+ turnID = event.TurnID+ }+ }+ if turnID == "" {+ t.Fatal("turn was not created")+ }+ return turnID+ }+ turnID := run("user-1", 1, "use tool")+ recovered, err := GetSession(testSessionID)+ if err != nil {+ t.Fatal(err)+ }+ recovered["expectedRevision"], recovered["commitTurnID"] = int64(1), turnID+ if _, canonical, err := SaveSessionState(marshalSession(t, recovered)); err != nil {+ t.Fatal(err)+ } else {+ canonical["entries"] = append(canonical["entries"].([]any), map[string]any{"id": "user-2", "type": "user", "content": "continue"})+ canonical["expectedRevision"] = int64(2)+ if _, _, err := SaveSessionState(marshalSession(t, canonical)); err != nil {+ t.Fatal(err)+ }+ }+ run("user-2", 3, "continue")+ if executions.Load() != 1 || requests.Load() != 3 {+ t.Fatalf("tool was repeated: executions=%d requests=%d", executions.Load(), requests.Load())+ }+}+func testNativeAgentToolHistoryRecovery(t *testing.T, protocol, path, inputKey, resultType string,writeResponse func(*testing.T, http.ResponseWriter, string, string, string, bool)) {for _, interrupted := range []bool{false, true} {diff --git a/kernel/util/anthropic.go b/kernel/util/anthropic.goindex 46825538c7..d05cd8a639 100644--- a/kernel/util/anthropic.go+++ b/kernel/util/anthropic.go@@ -377,11 +377,8 @@ func validateAnthropicHistory(blocks []json.RawMessage, calls []openai.ToolCall)return errors.New("invalid Anthropic conversation content")}switch block.Type {- case "text":- case "thinking":- if block.Signature == "" {- return errors.New("Anthropic thinking signature is missing")- }+ case "text", "thinking":+ // 兼容接口可返回无签名思考块,保留原始内容,由供应商校验其签名语义。case "redacted_thinking":if block.Data == "" {return errors.New("Anthropic redacted thinking is missing")diff --git a/kernel/util/anthropic_stream.go b/kernel/util/anthropic_stream.goindex 1b264cffe1..242d95f953 100644--- a/kernel/util/anthropic_stream.go+++ b/kernel/util/anthropic_stream.go@@ -180,7 +180,9 @@ func (s *anthropicStream) recv() (openai.ChatCompletionStreamResponse, error) {s.block["text"] = anthropicJSON(s.text.String())case "thinking":s.block["thinking"] = anthropicJSON(s.thinking.String())- s.block["signature"] = anthropicJSON(s.signature.String())+ if s.signature.Len() > 0 {+ s.block["signature"] = anthropicJSON(s.signature.String())+ }}if s.blockType == "tool_use" {if s.arguments.Len() > 0 {diff --git a/kernel/util/anthropic_test.go b/kernel/util/anthropic_test.goindex ea7c43a399..ba0d294a10 100644--- a/kernel/util/anthropic_test.go+++ b/kernel/util/anthropic_test.go@@ -118,6 +118,28 @@ var anthropicToolEvents = []string{}func TestAnthropicStreamAndNativeHistory(t *testing.T) {+ t.Run("signed thinking", func(t *testing.T) {+ testAnthropicStreamAndNativeHistory(t, anthropicToolEvents, "signed-opaque", true)+ })+ for _, signaturePresent := range []bool{true, false} {+ t.Run(fmt.Sprintf("unsigned thinking/signature present=%v", signaturePresent), func(t *testing.T) {+ var events []string+ for _, event := range anthropicToolEvents {+ if strings.Contains(event, `"type":"signature_delta"`) {+ continue+ }+ if !signaturePresent {+ event = strings.ReplaceAll(event, `,"signature":""`, "")+ }+ events = append(events, event)+ }+ testAnthropicStreamAndNativeHistory(t, events, "", signaturePresent)+ })+ }+}++func testAnthropicStreamAndNativeHistory(t *testing.T, events []string, signature string, signaturePresent bool) {+ t.Helper()server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/gateway/v1/messages" || r.Header.Get("x-api-key") != "override-key" ||r.Header.Get("anthropic-version") != "2023-06-01" || r.Header.Get("X-Custom") != "custom" {@@ -130,7 +152,7 @@ func TestAnthropicStreamAndNativeHistory(t *testing.T) {if !request.Stream || request.MaxTokens != 4096 || request.Model != "test" {t.Errorf("unexpected request: %+v", request)}- writeAnthropicEvents(w, anthropicToolEvents...)+ writeAnthropicEvents(w, events...)}))defer server.Close()client := NewAIClientWithModel("key", server.URL+"/gateway", "test", map[string]string{@@ -179,9 +201,16 @@ func TestAnthropicStreamAndNativeHistory(t *testing.T) {t.Fatalf("cumulative usage was not merged: %+v", usages)}native := stream.NativeContent()- if native == nil || len(native.Blocks) != 5 || !strings.Contains(string(native.Blocks[0]), "signed-opaque") {+ if native == nil || len(native.Blocks) != 5 {t.Fatalf("missing native thinking: %+v", native)}+ var thinkingBlock map[string]string+ if err := json.Unmarshal(native.Blocks[0], &thinkingBlock); err != nil {+ t.Fatal(err)+ }+ if value, present := thinkingBlock["signature"]; value != signature || present != signaturePresent || thinkingBlock["thinking"] != "Think" {+ t.Fatalf("native thinking or signature changed: %s", native.Blocks[0])+ }persisted, _ := json.Marshal(native)var restored AIMessageContentif err = json.Unmarshal(persisted, &restored); err != nil {@@ -266,8 +295,7 @@ func TestAnthropicIncompleteStreams(t *testing.T) {`{"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"a","name":"search","input":{}}}`,`{"type":"content_block_delta","index":0,"delta":{"type":"input_json_delta","partial_json":"{"}}`,`{"type":"content_block_stop","index":0}`}},- {"unsigned thinking", []string{anthropicToolEvents[0], anthropicToolEvents[3], anthropicToolEvents[4], anthropicToolEvents[7],- `{"type":"message_delta","delta":{"stop_reason":"end_turn"}}`, `{"type":"message_stop"}`}},+ {"unsigned thinking without stop", []string{anthropicToolEvents[0], anthropicToolEvents[3], anthropicToolEvents[4], anthropicToolEvents[7]}},} {t.Run(tc.name, func(t *testing.T) {server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {@@ -321,6 +349,33 @@ func TestAnthropicNonStreamingAndErrors(t *testing.T) {}}+func TestAnthropicNonStreamingThinkingSignatures(t *testing.T) {+ for _, tc := range []struct {+ name string+ signature string+ }{+ {"missing signature", ""},+ {"empty signature", `,"signature":""`},+ {"signed thinking", `,"signature":"signed-opaque"`},+ } {+ t.Run(tc.name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = fmt.Fprintf(w, `{"id":"msg","model":"test","content":[{"type":"thinking","thinking":"Think"%s},{"type":"text","text":"answer"}],"stop_reason":"end_turn"}`, tc.signature)+ }))+ defer server.Close()+ response, err := CreateOpenAICompletion(context.Background(), NewAIClientWithModel("", server.URL, "test"),+ AnthropicProtocolMessages, openai.ChatCompletionRequest{Model: "test", Messages: []openai.ChatCompletionMessage{{Role: "user", Content: "hello"}}}, nil)+ if err != nil {+ t.Fatal(err)+ }+ if len(response.Choices) != 1 || response.Choices[0].Message.Content != "answer" ||+ response.Choices[0].Message.ReasoningContent != "Think" || response.Choices[0].FinishReason != openai.FinishReasonStop {+ t.Fatalf("thinking or answer was lost: %+v", response)+ }+ })+ }+}+func TestAnthropicModelsPagination(t *testing.T) {calls := 0server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {