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: Preserve streamed Agent tool arguments https://github.com/siyuan-note/siyuan/issues/18847
Daniel5d4fce1f1f21
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex cc75603230..430fc3eec4 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -1144,12 +1144,7 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagparseErrors := make([]error, len(aggregatedToolCalls))var roundAttachments []AgentAttachmentfor i, tc := range aggregatedToolCalls {- registration := roundCapabilities.registration(tc.Function.Name)- var schema mcptools.ToolSchema- if registration != nil {- schema = registration.InputSchema- }- args, parseErr := parseCapabilityArgs(tc.Function.Arguments, schema)+ args, parseErr := parseToolArgs(tc.Function.Arguments)parsedArgs[i] = argsparseErrors[i] = parseErrcheckpointMsg.ToolCalls = append(checkpointMsg.ToolCalls, AgentToolCall{diff --git a/kernel/agent/tool_call_stream.go b/kernel/agent/tool_call_stream.goindex 4ab28a461e..6d5a4d6c42 100644--- a/kernel/agent/tool_call_stream.go+++ b/kernel/agent/tool_call_stream.go@@ -93,9 +93,6 @@ func mergeStreamedToolCallArguments(existing, fragment string) string {if strings.HasPrefix(fragment, existing) {return fragment}- if strings.HasPrefix(existing, fragment) {- return existing- }if isCompleteToolCallArguments(existing) && isCompleteToolCallArguments(fragment) {return fragment}diff --git a/kernel/agent/tool_call_stream_test.go b/kernel/agent/tool_call_stream_test.goindex f2f4107020..f85a26b56e 100644--- a/kernel/agent/tool_call_stream_test.go+++ b/kernel/agent/tool_call_stream_test.go@@ -17,6 +17,7 @@package agentimport (+ "strings""testing""github.com/sashabaranov/go-openai"@@ -112,3 +113,60 @@ func TestToolCallStreamAccumulatorCumulativeArguments(t *testing.T) {t.Fatalf("cumulative arguments were duplicated: %#v", calls)}}++func TestMergeStreamedToolCallArgumentsKeepsPrefixLikeFragment(t *testing.T) {+ got := mergeStreamedToolCallArguments(`{"todos":[`, `{"`)+ want := `{"todos":[{"`+ if got != want {+ t.Fatalf("prefix-like fragment was dropped: got %q, want %q", got, want)+ }+}++func TestToolCallStreamAccumulatorFineGrainedArguments(t *testing.T) {+ fragments := []string{+ "{", `"`, "t", "odos", `"`, ": ", "[", `{"`, "content",+ `":`, ` "`, "a", `"}]`, "}",+ }+ want := strings.Join(fragments, "")++ var accumulator toolCallStreamAccumulator+ index := 0+ for _, fragment := range fragments {+ accumulator.Add([]openai.ToolCall{{+ Index: &index,+ Type: openai.ToolTypeFunction,+ Function: openai.FunctionCall{+ Arguments: fragment,+ },+ }})+ }++ calls := accumulator.ToolCalls()+ if len(calls) != 1 || calls[0].Function.Arguments != want {+ t.Fatalf("fine-grained arguments were corrupted: got %#v, want %q", calls, want)+ }+}++func TestToolCallStreamAccumulatorArbitraryNestedObject(t *testing.T) {+ fragments := []string{+ `{"action":"item_update","value":`, `{"`, `mSelect":[`, `{"`, `content":"low"}]}}`,+ }+ want := strings.Join(fragments, "")++ var accumulator toolCallStreamAccumulator+ index := 0+ for _, fragment := range fragments {+ accumulator.Add([]openai.ToolCall{{+ Index: &index,+ Type: openai.ToolTypeFunction,+ Function: openai.FunctionCall{+ Arguments: fragment,+ },+ }})+ }++ calls := accumulator.ToolCalls()+ if len(calls) != 1 || calls[0].Function.Arguments != want {+ t.Fatalf("nested arguments were corrupted: got %#v, want %q", calls, want)+ }+}diff --git a/kernel/agent/tools.go b/kernel/agent/tools.goindex 7780671e3e..afc9a6bc1f 100644--- a/kernel/agent/tools.go+++ b/kernel/agent/tools.go@@ -20,7 +20,6 @@ import ("context""encoding/json""fmt"- "html""maps""strings"@@ -95,7 +94,7 @@ func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) execfunc executeCapability(ctx context.Context, tc openai.ToolCall, sessionID string,registration *capabilityRegistration) executedToolResult {- args, err := parseCapabilityArgs(tc.Function.Arguments, registration.InputSchema)+ args, err := parseToolArgs(tc.Function.Arguments)if err != nil {return executedToolResult{Text: "invalid capability arguments: " + err.Error(), IsError: true}}@@ -332,216 +331,18 @@ func resultToString(result tools.CallToolResult) string {return "(empty result)"}-// parseCapabilityArgs 根据能力 schema 解析并规范化模型返回的参数。-func parseCapabilityArgs(argsJSON string, schema tools.ToolSchema) (map[string]any, error) {+// parseToolArgs 在流结束后解析完整的工具参数,避免把损坏的 JSON 误报为缺少 schema 字段。+func parseToolArgs(argsJSON string) (map[string]any, error) {if strings.TrimSpace(argsJSON) == "" {return map[string]any{}, nil}- schemaMap, _ := convertSchema(schema).(map[string]any)- args, err := decodeCapabilityArgsObject(argsJSON, schemaMap)- if err != nil {- return map[string]any{}, err- }-- // 部分兼容接口会把完整参数对象放入唯一的 arguments 字段中。- // 仅当 schema 本身没有该字段时解包,避免改变合法工具的参数语义。- if len(args) == 1 && !schemaDefinesProperty(schemaMap, "arguments") {- if wrapped, ok := args["arguments"]; ok {- switch value := wrapped.(type) {- case map[string]any:- args = value- case string:- decoded, decodeErr := decodeCapabilityArgsObject(unwrapStructuredString(value), schemaMap)- if decodeErr != nil {- return map[string]any{}, fmt.Errorf("wrapped tool arguments are invalid: %w", decodeErr)- }- args = decoded- default:- return map[string]any{}, fmt.Errorf("wrapped tool arguments must be a JSON object or object string")- }- }- }-- normalized := normalizeCapabilityValue(args, schemaMap)- if normalizedArgs, ok := normalized.(map[string]any); ok {- return normalizedArgs, nil- }- return args, nil-}--func decodeCapabilityArgsObject(raw string, schema map[string]any) (map[string]any, error) {var args map[string]any- if err := json.Unmarshal([]byte(raw), &args); err == nil && args != nil {- return args, nil- }-- repaired := repairMissingArrayObjectOpeners(raw, schema)- if repaired != raw {- if err := json.Unmarshal([]byte(repaired), &args); err == nil && args != nil {- return args, nil- }- }-- if err := json.Unmarshal([]byte(raw), &args); err != nil {+ if err := json.Unmarshal([]byte(argsJSON), &args); err != nil {return nil, fmt.Errorf("tool arguments are not valid JSON: %w", err)}- return nil, fmt.Errorf("tool arguments must be a JSON object")-}--func schemaDefinesProperty(schema map[string]any, name string) bool {- properties, _ := schema["properties"].(map[string]any)- _, ok := properties[name]- return ok-}--func normalizeCapabilityValue(value any, schema map[string]any) any {- if text, ok := value.(string); ok && schemaType(schema) != "string" {- if decoded, matched := decodeStructuredSchemaValue(text, schema); matched {- value = decoded- }- }-- switch typed := value.(type) {- case map[string]any:- properties, _ := schema["properties"].(map[string]any)- for name, child := range typed {- childSchema, _ := properties[name].(map[string]any)- if childSchema != nil {- typed[name] = normalizeCapabilityValue(child, childSchema)- }- }- case []any:- itemSchema, _ := schema["items"].(map[string]any)- if itemSchema != nil {- for i := range typed {- typed[i] = normalizeCapabilityValue(typed[i], itemSchema)- }- }- }- return value-}--func decodeStructuredSchemaValue(value string, schema map[string]any) (any, bool) {- for _, candidate := range []string{unwrapStructuredString(value), html.UnescapeString(unwrapStructuredString(value))} {- var decoded any- if json.Unmarshal([]byte(candidate), &decoded) == nil && capabilityValueMatchesSchema(decoded, schema) {- return normalizeCapabilityValue(decoded, schema), true- }- }- return nil, false-}--func unwrapStructuredString(value string) string {- trimmed := strings.TrimSpace(value)- if strings.HasPrefix(trimmed, "<![CDATA[") && strings.HasSuffix(trimmed, "]]>") {- return strings.TrimSuffix(strings.TrimPrefix(trimmed, "<![CDATA["), "]]>")- }- return trimmed-}--func capabilityValueMatchesSchema(value any, schema map[string]any) bool {- switch schemaType(schema) {- case "array":- _, ok := value.([]any)- return ok- case "object":- _, ok := value.(map[string]any)- return ok- case "boolean":- _, ok := value.(bool)- return ok- case "number", "integer":- _, ok := value.(float64)- return ok- case "null":- return value == nil- case "":- return false- default:- return false- }-}--func schemaType(schema map[string]any) string {- value, _ := schema["type"].(string)- return value-}--// repairMissingArrayObjectOpeners 修复兼容接口偶发丢失对象数组首个 {" 的参数。-func repairMissingArrayObjectOpeners(raw string, schema map[string]any) string {- keys := map[string]struct{}{}- collectArrayObjectPropertyNames(schema, keys)- if len(keys) == 0 {- return raw- }-- type insertion struct {- position int- text string- }- var insertions []insertion- for i := 0; i < len(raw); i++ {- if raw[i] != '[' {- continue- }- position := i + 1- for position < len(raw) && (raw[position] == ' ' || raw[position] == '\t' || raw[position] == '\r' || raw[position] == '\n') {- position++- }- for key := range keys {- if strings.HasPrefix(raw[position:], key+`":`) {- insertions = append(insertions, insertion{position: position, text: `{"`})- break- }- if strings.HasPrefix(raw[position:], `"`+key+`":`) {- insertions = append(insertions, insertion{position: position, text: `{`})- break- }- }- }- if len(insertions) == 0 {- return raw- }-- var builder strings.Builder- start := 0- for _, item := range insertions {- builder.WriteString(raw[start:item.position])- builder.WriteString(item.text)- start = item.position- }- builder.WriteString(raw[start:])- return builder.String()-}--func collectArrayObjectPropertyNames(schema map[string]any, keys map[string]struct{}) {- if schemaType(schema) == "array" {- if items, ok := schema["items"].(map[string]any); ok {- if schemaType(items) == "object" {- if properties, propertiesOK := items["properties"].(map[string]any); propertiesOK {- for name := range properties {- keys[name] = struct{}{}- }- }- }- collectArrayObjectPropertyNames(items, keys)- }- }- if properties, ok := schema["properties"].(map[string]any); ok {- for _, property := range properties {- if child, childOK := property.(map[string]any); childOK {- collectArrayObjectPropertyNames(child, keys)- }- }- }- for _, keyword := range []string{"anyOf", "oneOf", "allOf"} {- if variants, ok := schema[keyword].([]any); ok {- for _, variant := range variants {- if child, childOK := variant.(map[string]any); childOK {- collectArrayObjectPropertyNames(child, keys)- }- }- }+ if args == nil {+ return nil, fmt.Errorf("tool arguments must be a JSON object")}+ return args, nil}diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex c36f156616..9d54f431c7 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -105,107 +105,50 @@ func TestConvertSchemaPreservesRawJSONSchema(t *testing.T) {}}-func TestParseCapabilityArgsRepairsObjectArrayOpeners(t *testing.T) {- args, err := parseCapabilityArgs(- `{"questions":[header":"Test","question":"Continue?","options":[label":"Yes","description":"Continue now"}]}]}`,- tools.QuestionTool.InputSchema,+func TestParseToolArgsPreservesNestedValues(t *testing.T) {+ args, err := parseToolArgs(+ `{"todos":[{"content":"Task","status":"in_progress"}],"enabled":true,"count":2}`,)if err != nil {t.Fatal(err)}- questions, ok := args["questions"].([]any)- if !ok || len(questions) != 1 {- t.Fatalf("unexpected questions: %#v", args["questions"])- }- question, ok := questions[0].(map[string]any)- if !ok || question["header"] != "Test" {- t.Fatalf("unexpected question: %#v", questions[0])- }- options, ok := question["options"].([]any)- if !ok || len(options) != 1 {- t.Fatalf("unexpected options: %#v", question["options"])- }-}--func TestParseCapabilityArgsUnwrapsArgumentsObject(t *testing.T) {- args, err := parseCapabilityArgs(- `{"arguments":"{\"todos\":[{\"content\":\"Task\",\"status\":\"in_progress\"}]}"}`,- tools.TodoWriteTool.InputSchema,- )- if err != nil {- t.Fatal(err)- }- if _, exists := args["arguments"]; exists {- t.Fatalf("wrapped arguments were not removed: %#v", args)- }todos, ok := args["todos"].([]any)if !ok || len(todos) != 1 {t.Fatalf("unexpected todos: %#v", args["todos"])}-}--func TestParseCapabilityArgsDecodesSchemaStructuredStrings(t *testing.T) {- schema := tools.ToolSchema{- Type: "object",- Properties: map[string]tools.Property{- "items": {- Type: "array",- Items: &tools.Property{- Type: "object",- Properties: map[string]tools.Property{- "name": {Type: "string"},- },- },- },- "enabled": {Type: "boolean"},- "count": {Type: "number"},- "payload": {Type: "object"},- "text": {Type: "string"},- },- }- args, err := parseCapabilityArgs(- `{"items":"[{\"name\":\"A\"}]","enabled":"true","count":"2","payload":"{\"value\":1}","text":"{\"keep\":true}"}`,- schema,- )- if err != nil {- t.Fatal(err)- }- if _, ok := args["items"].([]any); !ok {- t.Fatalf("items were not decoded: %#v", args["items"])+ todo, ok := todos[0].(map[string]any)+ if !ok || todo["content"] != "Task" || todo["status"] != "in_progress" {+ t.Fatalf("unexpected todo: %#v", todos[0])}if args["enabled"] != true || args["count"] != float64(2) {- t.Fatalf("primitive values were not decoded: %#v", args)- }- if _, ok := args["payload"].(map[string]any); !ok {- t.Fatalf("payload was not decoded: %#v", args["payload"])- }- if args["text"] != `{"keep":true}` {- t.Fatalf("string value was modified: %#v", args["text"])+ t.Fatalf("unexpected primitive values: %#v", args)}}-func TestParseCapabilityArgsPreservesDeclaredArgumentsProperty(t *testing.T) {- schema := tools.ToolSchema{- Type: "object",- Properties: map[string]tools.Property{- "arguments": {Type: "string"},- },- }- args, err := parseCapabilityArgs(`{"arguments":"{\"value\":1}"}`, schema)+func TestParseToolArgsDoesNotRewriteValidStrings(t *testing.T) {+ args, err := parseToolArgs(`{"arguments":"{\"value\":1}","enabled":"true"}`)if err != nil {t.Fatal(err)}- if args["arguments"] != `{"value":1}` {- t.Fatalf("declared arguments property was modified: %#v", args)+ if args["arguments"] != `{"value":1}` || args["enabled"] != "true" {+ t.Fatalf("string values were rewritten: %#v", args)+ }++ empty, err := parseToolArgs(" ")+ if err != nil || len(empty) != 0 {+ t.Fatalf("empty arguments were not accepted: %#v, %v", empty, err)}}-func TestParseCapabilityArgsRejectsInvalidJSON(t *testing.T) {- if _, err := parseCapabilityArgs(`{"questions":[`, tools.QuestionTool.InputSchema); err == nil {+func TestParseToolArgsRejectsInvalidJSON(t *testing.T) {+ if _, err := parseToolArgs(`{"questions":[`); err == nil {t.Fatal("invalid JSON was accepted")}- if _, err := parseCapabilityArgs(`{"arguments":"not JSON"}`, tools.QuestionTool.InputSchema); err == nil {- t.Fatal("invalid wrapped JSON was accepted")+ if _, err := parseToolArgs(`null`); err == nil {+ t.Fatal("null arguments were accepted")+ }+ if _, err := parseToolArgs(`[]`); err == nil {+ t.Fatal("array arguments were accepted")}}