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: Improve Agent structured tool argument compatibility https://github.com/siyuan-note/siyuan/issues/18847
Daniele9e5c7b8311d
diff --git a/kernel/agent/agent.go b/kernel/agent/agent.goindex 5db125db43..67c557bd65 100644--- a/kernel/agent/agent.go+++ b/kernel/agent/agent.go@@ -209,6 +209,27 @@ func buildDoomSignature(name, action string, args map[string]any) string {return sig.String()}+func (tracker *doomLoopTracker) record(name, action string, args map[string]any, failed bool) {+ if name == "frontend" {+ return+ }+ if !failed {+ tracker.prevSig = ""+ tracker.prevName = ""+ tracker.count = 0+ return+ }++ sig := buildDoomSignature(name, action, args)+ if sig == tracker.prevSig && tracker.prevSig != "" {+ tracker.count+++ return+ }+ tracker.prevSig = sig+ tracker.prevName = name+ tracker.count = 1+}+var confirmChannelsMu sync.Mutexvar confirmChannels = make(map[string]*confirmWaiter)@@ -1120,10 +1141,17 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagRoundID: roundID,}parsedArgs := make([]map[string]any, len(aggregatedToolCalls))+ parseErrors := make([]error, len(aggregatedToolCalls))var roundAttachments []AgentAttachmentfor i, tc := range aggregatedToolCalls {- args := parseToolArgs(tc.Function.Arguments)+ registration := roundCapabilities.registration(tc.Function.Name)+ var schema mcptools.ToolSchema+ if registration != nil {+ schema = registration.InputSchema+ }+ args, parseErr := parseCapabilityArgs(tc.Function.Arguments, schema)parsedArgs[i] = args+ parseErrors[i] = parseErrcheckpointMsg.ToolCalls = append(checkpointMsg.ToolCalls, AgentToolCall{ID: tc.ID,Name: tc.Function.Name,@@ -1170,7 +1198,12 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagArguments: args,})- toolInputErr := validateCapabilityCall(ctx, registration, args)+ toolInputErr := parseErrors[i]+ if toolInputErr != nil {+ toolInputErr = fmt.Errorf("invalid capability arguments: %w", toolInputErr)+ } else {+ toolInputErr = validateCapabilityCall(ctx, registration, args)+ }requiresConfirm, forcedConfirm := false, falseif toolInputErr == nil {requiresConfirm, forcedConfirm = capabilityConfirmRequirement(@@ -1374,9 +1407,9 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagresultStr = toolInputErr.Error()isErr = true} else if tc.Function.Name == "question" {- resultStr = handleQuestion(ctx, tc.Function.Arguments, roundID, ch, 5*time.Minute)+ resultStr = handleQuestion(ctx, args, roundID, ch, 5*time.Minute)} else if registration.isBrowser() {- executed := handleBrowserCapability(ctx, tc, registration, ch, confirmTimeout)+ executed := handleBrowserCapability(ctx, tc, registration, args, ch, confirmTimeout)resultStr = executed.TextisErr = executed.IsErrorexecutionUnknown = executed.ExecutionUnknown@@ -1432,26 +1465,10 @@ func AgentChat(ctx context.Context, client *openai.Client, protocol, model, imagreturn}- // 死循环检测:只有 question/frontend 之外的普通工具参与,- // 且仅当本次调用失败或无返回(即"卡住反复重试"的真死循环特征)时才累加计数。+ // 死循环检测:只有 frontend 之外的工具参与,且仅当本次调用失败或无返回+ // (即“卡住反复重试”的真死循环特征)时才累加计数。// 成功的工具调用一定产生了有用的副作用,不应计入。- if tc.Function.Name != "question" && tc.Function.Name != "frontend" {- if isErr || strings.TrimSpace(rawResult) == "" {- sig := buildDoomSignature(tc.Function.Name, action, args)- if sig == doomLoop.prevSig && doomLoop.prevSig != "" {- doomLoop.count++- } else {- doomLoop.prevSig = sig- doomLoop.prevName = tc.Function.Name- doomLoop.count = 1- }- } else {- // 成功调用:重置基准,避免误把后续合理调用连成"重复"。- doomLoop.prevSig = ""- doomLoop.prevName = ""- doomLoop.count = 0- }- }+ doomLoop.record(tc.Function.Name, action, args, isErr || strings.TrimSpace(rawResult) == "")}if len(roundAttachments) > 0 {// 历史图片的文字分析仍保留在上下文中,只携带最近一轮图片,避免请求体随会话无限增长。@@ -1712,8 +1729,7 @@ func needsLocalSnapshot(toolName, action string) bool {}}-func handleQuestion(ctx context.Context, argsJSON, roundID string, ch chan<- AgentEvent, timeout time.Duration) string {- args := parseToolArgs(argsJSON)+func handleQuestion(ctx context.Context, args map[string]any, roundID string, ch chan<- AgentEvent, timeout time.Duration) string {questionID := ast.NewNodeID()ch2 := make(chan QuestionAnswer, 1)questionChannelsMu.Lock()@@ -1795,11 +1811,10 @@ func finishConfirmWait(confirmID string, ch chan confirmResult) (confirmResult,// handleBrowserCapability 通过 SSE 把前端能力调用发送到浏览器,并等待浏览器回传结果。func handleBrowserCapability(ctx context.Context, tc openai.ToolCall, registration *capabilityRegistration,- ch chan<- AgentEvent, timeout time.Duration) executedToolResult {- if !capabilityStillExecutable(registration, parseToolArgs(tc.Function.Arguments)) {+ args map[string]any, ch chan<- AgentEvent, timeout time.Duration) executedToolResult {+ if !capabilityStillExecutable(registration, args) {return executedToolResult{Text: "Browser capability is disabled or no longer available.", IsError: true}}- args := parseToolArgs(tc.Function.Arguments)callID := ast.NewNodeID()ch2 := make(chan browserCapabilityResult, 1)browserCapabilityChannelsMu.Lock()diff --git a/kernel/agent/tools.go b/kernel/agent/tools.goindex 618ce74e19..7780671e3e 100644--- a/kernel/agent/tools.go+++ b/kernel/agent/tools.go@@ -20,6 +20,7 @@ import ("context""encoding/json""fmt"+ "html""maps""strings"@@ -94,7 +95,10 @@ func executeTool(ctx context.Context, tc openai.ToolCall, sessionID string) execfunc executeCapability(ctx context.Context, tc openai.ToolCall, sessionID string,registration *capabilityRegistration) executedToolResult {- args := parseToolArgs(tc.Function.Arguments)+ args, err := parseCapabilityArgs(tc.Function.Arguments, registration.InputSchema)+ if err != nil {+ return executedToolResult{Text: "invalid capability arguments: " + err.Error(), IsError: true}+ }if err := validateCapabilityCall(ctx, registration, args); err != nil {return executedToolResult{Text: err.Error(), IsError: true}}@@ -328,22 +332,216 @@ func resultToString(result tools.CallToolResult) string {return "(empty result)"}-func parseToolArgs(argsJSON string) map[string]any {- args := map[string]any{}- if argsJSON == "" {- return args+// parseCapabilityArgs 根据能力 schema 解析并规范化模型返回的参数。+func parseCapabilityArgs(argsJSON string, schema tools.ToolSchema) (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 {+ 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+}- dec := json.NewDecoder(strings.NewReader(argsJSON))- dec.UseNumber()- _ = dec.Decode(&args)+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+ }+}- for k, v := range args {- if num, ok := v.(json.Number); ok {- if f, err := num.Float64(); err == nil {- args[k] = f+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)+ }}}}- return args}diff --git a/kernel/agent/tools_test.go b/kernel/agent/tools_test.goindex ffc4214131..c36f156616 100644--- a/kernel/agent/tools_test.go+++ b/kernel/agent/tools_test.go@@ -105,6 +105,125 @@ 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,+ )+ 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"])+ }+ 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"])+ }+}++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)+ if err != nil {+ t.Fatal(err)+ }+ if args["arguments"] != `{"value":1}` {+ t.Fatalf("declared arguments property was modified: %#v", args)+ }+}++func TestParseCapabilityArgsRejectsInvalidJSON(t *testing.T) {+ if _, err := parseCapabilityArgs(`{"questions":[`, tools.QuestionTool.InputSchema); 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")+ }+}++func TestDoomLoopTracksFailedQuestionCalls(t *testing.T) {+ var tracker doomLoopTracker+ for i := 0; i < doomLoopStopThreshold; i++ {+ tracker.record("question", "", map[string]any{}, true)+ }+ if tracker.count != doomLoopStopThreshold || tracker.prevName != "question" {+ t.Fatalf("failed question calls were not tracked: %#v", tracker)+ }++ tracker.record("question", "", map[string]any{}, false)+ if tracker.count != 0 || tracker.prevSig != "" || tracker.prevName != "" {+ t.Fatalf("successful question call did not reset tracker: %#v", tracker)+ }+}+func TestResultToStringUsesStructuredContent(t *testing.T) {result := resultToString(tools.CallToolResult{StructuredContent: map[string]any{"status": "ok"},@@ -386,7 +505,7 @@ func TestQuestionEventIncludesRoundID(t *testing.T) {events := make(chan AgentEvent, 1)resultCh := make(chan string, 1)go func() {- resultCh <- handleQuestion(context.Background(), `{"questions":[]}`, roundID, events, time.Second)+ resultCh <- handleQuestion(context.Background(), map[string]any{"questions": []any{}}, roundID, events, time.Second)}()event := <-events@@ -457,7 +576,7 @@ func TestBrowserCapabilityValidatesStructuredOutput(t *testing.T) {go func() {resultCh <- handleBrowserCapability(context.Background(), openai.ToolCall{Function: openai.FunctionCall{Name: validationTool.Name, Arguments: `{}`},- }, registration, events, time.Second)+ }, registration, map[string]any{}, events, time.Second)}()event := <-eventsif event.Type != "browser_capability_call" {