diff --git a/internal/runtime/executor/helps/payload_replace.go b/internal/runtime/executor/helps/payload_replace.go index e52080467..a9121c843 100644 --- a/internal/runtime/executor/helps/payload_replace.go +++ b/internal/runtime/executor/helps/payload_replace.go @@ -9,79 +9,37 @@ import ( ) // replacePayloadUserTextDoc edits only existing protocol-defined user text fields. -// Paths are collected before writes, so no result views survive a document mutation. +// Changed values are collected before writes so traversal views remain valid. func replacePayloadUserTextDoc(doc *ojson.Doc, protocol, root string, rule *config.PayloadReplaceRule, noteWrite func(string)) bool { - selected := make(map[int]bool, len(rule.Target.Positions)) - for _, position := range rule.Target.Positions { - selected[position] = true - } - var paths []string protocol = strings.ToLower(strings.TrimSpace(protocol)) var arrayPath string + var gemini, responses bool switch protocol { case "openai", "claude": arrayPath = buildPayloadPath(root, "messages") case "codex", "responses", "response", "openai-response", "openai-responses", "meta": arrayPath = buildPayloadPath(root, "input") - if doc.Get(arrayPath).Type == ojson.String { - if rule.Target.All || selected[1] { - paths = append(paths, arrayPath) - } - } + responses = true case "gemini", "antigravity": arrayPath = buildPayloadPath(root, "contents") + gemini = true default: return false } - array := doc.Get(arrayPath) - if array.IsArray() { - position := 0 - for index, message := range array.Array() { - if !message.IsObject() || message.Get("role").String() != "user" { - continue - } - if protocol != "openai" && protocol != "claude" && protocol != "gemini" && protocol != "antigravity" { - if typ := message.Get("type"); typ.Exists() && (typ.Type != ojson.String || typ.String() != "message") { - continue - } - } - position++ - if !rule.Target.All && !selected[position] { - continue - } - messagePath := arrayPath + "." + strconv.Itoa(index) - if protocol == "gemini" || protocol == "antigravity" { - parts := message.Get("parts") - if !parts.IsArray() { - continue - } - for partIndex, part := range parts.Array() { - if part.IsObject() && part.Get("text").Type == ojson.String && !part.Get("thought").Bool() && - !part.Get("functionCall").Exists() && !part.Get("functionResponse").Exists() { - paths = append(paths, messagePath+".parts."+strconv.Itoa(partIndex)+".text") - } - } - continue - } - content := message.Get("content") - if content.Type == ojson.String { - paths = append(paths, messagePath+".content") - } else if content.IsArray() { - for blockIndex, block := range content.Array() { - if !block.IsObject() || block.Get("text").Type != ojson.String || block.Get("thought").Bool() { - continue - } - typ := block.Get("type").String() - if typ == "text" || (typ == "input_text" && protocol != "openai" && protocol != "claude") { - paths = append(paths, messagePath+".content."+strconv.Itoa(blockIndex)+".text") - } - } + var selected map[int]bool + lastPosition := 0 + if !rule.Target.All { + selected = make(map[int]bool, len(rule.Target.Positions)) + for _, position := range rule.Target.Positions { + selected[position] = true + if position > lastPosition { + lastPosition = position } } } - mutated := false - for _, path := range paths { - text := doc.Get(path).String() + type textChange struct{ path, value string } + var changes []textChange + collectChange := func(text string, messageIndex, blockIndex int) { updated := text for _, replacement := range rule.Replacements { for from, to := range replacement { @@ -89,13 +47,82 @@ func replacePayloadUserTextDoc(doc *ojson.Doc, protocol, root string, rule *conf } } if updated == text { - continue + return } - if errSet := doc.Set(path, updated); errSet != nil { + // Build paths only for changed text; no second document lookup is needed. + path := arrayPath + if messageIndex >= 0 { + if gemini { + path = arrayPath + "." + strconv.Itoa(messageIndex) + ".parts." + strconv.Itoa(blockIndex) + ".text" + } else if blockIndex >= 0 { + path = arrayPath + "." + strconv.Itoa(messageIndex) + ".content." + strconv.Itoa(blockIndex) + ".text" + } else { + path = arrayPath + "." + strconv.Itoa(messageIndex) + ".content" + } + } + changes = append(changes, textChange{path: path, value: updated}) + } + array := doc.Get(arrayPath) + if responses && array.Type == ojson.String { + if rule.Target.All || selected[1] { + collectChange(array.String(), -1, -1) + } + } else if array.IsArray() { + position := 0 + array.ForEach(func(index, message ojson.Result) bool { + if !message.IsObject() || message.Get("role").String() != "user" { + return true + } + if responses { + if typ := message.Get("type"); typ.Exists() && (typ.Type != ojson.String || typ.String() != "message") { + return true + } + } + position++ + keepScanning := rule.Target.All || position < lastPosition + if !rule.Target.All && !selected[position] { + return keepScanning + } + messageIndex := int(index.Int()) + if gemini { + if parts := message.Get("parts"); parts.IsArray() { + parts.ForEach(func(partIndex, part ojson.Result) bool { + text := part.Get("text") + if part.IsObject() && text.Type == ojson.String && !part.Get("thought").Bool() && + !part.Get("functionCall").Exists() && !part.Get("functionResponse").Exists() { + collectChange(text.String(), messageIndex, int(partIndex.Int())) + } + return true + }) + } + return keepScanning + } + content := message.Get("content") + if content.Type == ojson.String { + collectChange(content.String(), messageIndex, -1) + } else if content.IsArray() { + content.ForEach(func(blockIndex, block ojson.Result) bool { + text := block.Get("text") + if !block.IsObject() || text.Type != ojson.String || block.Get("thought").Bool() { + return true + } + typ := block.Get("type").String() + if typ == "text" || (typ == "input_text" && responses) { + collectChange(text.String(), messageIndex, int(blockIndex.Int())) + } + return true + }) + } + return keepScanning + }) + } + mutated := false + for _, change := range changes { + if errSet := doc.Set(change.path, change.value); errSet != nil { continue } mutated = true - noteWrite(path) + noteWrite(change.path) } return mutated } diff --git a/internal/runtime/executor/helps/payload_replace_bench_test.go b/internal/runtime/executor/helps/payload_replace_bench_test.go new file mode 100644 index 000000000..539defde1 --- /dev/null +++ b/internal/runtime/executor/helps/payload_replace_bench_test.go @@ -0,0 +1,72 @@ +package helps + +import ( + "strings" + "testing" + + "github.com/MoeForge/moego/json" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +func BenchmarkPayloadReplace(b *testing.B) { + for _, scenario := range []struct { + name string + protocol string + messages int + positions []int + all bool + match bool + }{ + {"ChatShortFirstTwo", "openai", 8, []int{1, 2}, false, true}, + {"ChatLongFirstTwo", "openai", 1000, []int{1, 2}, false, true}, + {"ChatLongFirstTwoNoMatch", "openai", 1000, []int{1, 2}, false, false}, + {"ChatLongLast", "openai", 1000, []int{500}, false, true}, + {"ChatAllMatch", "openai", 256, nil, true, true}, + {"ChatAllNoMatch", "openai", 1000, nil, true, false}, + {"GeminiLongFirstTwo", "gemini", 1000, []int{1, 2}, false, true}, + {"GeminiAllMatch", "gemini", 256, nil, true, true}, + {"GeminiAllNoMatch", "gemini", 1000, nil, true, false}, + } { + b.Run(scenario.name, func(b *testing.B) { + text := "hello " + strings.Repeat("ordinary text ", 32) + if scenario.match { + text = "you are hero " + text + } + messages := make([]any, scenario.messages) + for i := range messages { + role := "user" + if i%2 == 0 { + role = "assistant" + } + if scenario.protocol == "gemini" { + if role == "assistant" { + role = "model" + } + messages[i] = map[string]any{"role": role, "parts": []any{map[string]any{"text": text}, map[string]any{"text": text}}} + } else { + messages[i] = map[string]any{"role": role, "content": text} + } + } + key := "messages" + if scenario.protocol == "gemini" { + key = "contents" + } + body, errMarshal := json.Marshal(map[string]any{key: messages}) + if errMarshal != nil { + b.Fatal(errMarshal) + } + cfg := &config.Config{Payload: config.PayloadConfig{Replace: []config.PayloadReplaceRule{{ + Models: []config.PayloadModelRule{{Name: "*"}}, + Target: config.PayloadReplaceTarget{Role: "user", Positions: scenario.positions, All: scenario.all}, + Replacements: []config.PayloadReplacement{{"you are hero": "you are fool"}, {"hello": "hi"}}, + }}}} + if !scenario.match { + cfg.Payload.Replace[0].Replacements = cfg.Payload.Replace[0].Replacements[:1] + } + b.ReportAllocs() + for b.Loop() { + _ = ApplyPayloadConfigWithRoot(cfg, "model", scenario.protocol, "", body, nil, "", "") + } + }) + } +} diff --git a/internal/runtime/executor/helps/payload_replace_traversal_test.go b/internal/runtime/executor/helps/payload_replace_traversal_test.go new file mode 100644 index 000000000..67e92bcee --- /dev/null +++ b/internal/runtime/executor/helps/payload_replace_traversal_test.go @@ -0,0 +1,78 @@ +package helps + +import ( + "reflect" + "strings" + "testing" + + "github.com/MoeForge/moego/ojson" + "github.com/router-for-me/CLIProxyAPI/v8/internal/config" +) + +func TestPayloadReplaceDeferredWrites(t *testing.T) { + grown := strings.Repeat("expanded ", 512) + escaped := "\"\\\n你好" + for _, scenario := range []struct { + protocol, root, input string + changed []string + }{ + {"openai", "", `{"messages":[{"role":"assistant","content":"grow"},{"role":"user","content":"grow"},{"role":"user","content":[{"type":"text","text":"shrink"},{"type":"image_url","image_url":{"url":"grow"}},{"type":"text","text":"escaped"},{"type":"text","text":"unchanged"}]},{"role":"user","content":"grow"}]}`, []string{"messages.1.content", "messages.2.content.0.text", "messages.2.content.2.text"}}, + {"claude", "", `{"messages":[{"role":"user","content":"grow"},{"role":"user","content":[{"type":"text","text":"shrink"},{"type":"tool_result","content":"grow"},{"type":"text","text":"escaped"},{"type":"text","text":"unchanged"}]},{"role":"user","content":"grow"}]}`, []string{"messages.0.content", "messages.1.content.0.text", "messages.1.content.2.text"}}, + {"codex", "", `{"input":[{"type":"function_call_output","role":"user","content":"grow"},{"type":"message","role":"user","content":"grow"},{"role":"user","content":[{"type":"input_text","text":"shrink"},{"type":"input_image","image_url":"grow"},{"type":"input_text","text":"escaped"},{"type":"input_text","text":"unchanged"}]},{"role":"user","content":"grow"}]}`, []string{"input.1.content", "input.2.content.0.text", "input.2.content.2.text"}}, + {"gemini", "", `{"contents":[{"role":"model","parts":[{"text":"grow"}]},{"role":"user","parts":[{"text":"grow"}]},{"role":"user","parts":[{"text":"shrink"},{"functionResponse":{"response":{"text":"grow"}}},{"text":"escaped"},{"text":"unchanged"}]},{"role":"user","parts":[{"text":"grow"}]}]}`, []string{"contents.1.parts.0.text", "contents.2.parts.0.text", "contents.2.parts.2.text"}}, + {"antigravity", "request", `{"request":{"contents":[{"role":"user","parts":[{"text":"grow"}]},{"role":"user","parts":[{"text":"shrink"},{"inlineData":{"data":"grow"}},{"text":"escaped"},{"text":"unchanged"}]},{"role":"user","parts":[{"text":"grow"}]}]}}`, []string{"request.contents.0.parts.0.text", "request.contents.1.parts.0.text", "request.contents.1.parts.2.text"}}, + } { + for _, prepared := range []bool{false, true} { + name := scenario.protocol + "/raw" + if prepared { + name = scenario.protocol + "/prepared-doc" + } + t.Run(name, func(t *testing.T) { + doc := ojson.NewDocString(scenario.input) + if prepared { + if errSet := doc.Set("metadata.prepared", true); errSet != nil { + t.Fatal(errSet) + } + if errSet := doc.Set("metadata.counter", 7); errSet != nil { + t.Fatal(errSet) + } + } + want := ojson.NewDoc(doc.Bytes()) + for i, value := range []string{grown, "", escaped} { + if errSet := want.Set(scenario.changed[i], value); errSet != nil { + t.Fatal(errSet) + } + } + rule := &config.PayloadReplaceRule{ + Target: config.PayloadReplaceTarget{Role: "user", Positions: []int{2, 1, 2}}, + Replacements: []config.PayloadReplacement{{"grow": grown}, {"shrink": ""}, {"escaped": escaped}}, + } + var writes []string + if !replacePayloadUserTextDoc(doc, scenario.protocol, scenario.root, rule, func(path string) { writes = append(writes, path) }) { + t.Fatal("expected text changes") + } + if !reflect.DeepEqual(writes, scenario.changed) { + t.Fatalf("tracked writes = %v, want %v", writes, scenario.changed) + } + if !reflect.DeepEqual(ojson.ParseBytes(doc.Bytes()).Value(), ojson.ParseBytes(want.Bytes()).Value()) { + t.Fatalf("deferred writes changed unrelated content or lost text: %s", doc.Bytes()) + } + }) + } + } +} + +func TestPayloadReplaceNoOpDoesNotTrackWrites(t *testing.T) { + for _, replacements := range [][]config.PayloadReplacement{ + {{"absent": "replacement"}}, + {{"hero": "hero"}}, + {{"hero": "fool"}, {"fool": "hero"}}, + } { + doc := ojson.NewDocString(`{"messages":[{"role":"user","content":"hero"}]}`) + rule := &config.PayloadReplaceRule{Target: config.PayloadReplaceTarget{Role: "user", All: true}, Replacements: replacements} + changed := replacePayloadUserTextDoc(doc, "openai", "", rule, func(path string) { t.Errorf("no-op tracked write: %s", path) }) + if changed || doc.Get("messages.0.content").String() != "hero" { + t.Fatal("no-op changed the document") + } + } +}