gateway: the body's key checks look for the needle's rarest byte

Each request ran ~45 bytes.Contains over its whole body to ask whether
a key is there at all ("developer", "compaction, "display", the
passthrough key...). Most needles begin with a quote, JSON's commonest
byte, so bytes.Index stopped at every quote, gave up on that and
compared at every byte: on a 2 MB body ~9 ms a request, 36% of the
gateway's CPU in BenchmarkLargeRequest's profile.

bodyHas/bodyIndex find the needle's rarest byte (a static rank of the
bytes JSON, English and code use most) with IndexByte and compare the
needle only there; a needle of common bytes only hands the rest to
strings.Index after 64 misses, so it is never slower than before, and
it allocates nothing (a []byte(sep) of a needle over 32 bytes did).
148 literal and constant needles in internal/gateway use it, and
mayHoldHEIC's "eXB" walk uses bodyIndex.

mayHoldOddBase64 walked every byte through a switch (~2 ms a 2 MB
body); a run it looks for ends a string, so it now looks back from each
quote with a class table and gives the same answer.

Run on mica (Apple M6) at this tree:
- BenchmarkBodyHas, 7 needles over a 2 MB body: 4.43 ms -> 0.38 ms,
  0 allocs (was 1).
- BenchmarkLargeRequest -benchtime 200x, before -> after:
  anthropic 31.2 -> 28.9 ms, anthropic-group 31.4 -> 27.8,
  chat 35.7 -> 32.8, responses 39.8 -> 29.8.
- go vet ./internal/gateway; gofmt -l clean.
- go test ./internal/gateway -count 1 -timeout 45m: ok (858s).
- Broken by hand: bodyIndex's start off by one -> TestBodyIndexIsIndex
  red (wrong index on 5 needles and the random bodies); the URL-safe
  class never counted -> TestOddBase64LooksAsItWalked red. Both green
  again restored.

TestBodyIndexIsIndex holds bodyIndex to bytes.Index on a large
conversation and 3000 random bodies of common and rare bytes;
TestOddBase64LooksAsItWalked holds the new check to the old byte walk
(kept in the test) on 20000 random bodies and the three protocols'
large conversations.

Real account: the built app (mote, sandbox HOME) sent a 6KB request to
DeepSeek on /v1/responses and /v1/messages, both 200 "pong". Not
tried: Codex (the sandbox's sign-in is stale, and renewing it there
would rotate the live refresh token).
This commit is contained in:
yetone
2026-11-14 05:51:42 +08:00
parent 08f77528f4
commit 63c91cae5f
73 changed files with 392 additions and 190 deletions
+3 -3
View File
@@ -49,7 +49,7 @@ func fromLite(body []byte) []byte {
// to be one.
func withoutLiteMetadata(body []byte) []byte {
const marker = "ws_request_header_x_openai_internal_codex_responses_lite"
if !bytes.Contains(body, []byte(marker)) {
if !bodyHas(body, marker) {
return body
}
r, found, ok := topMember(body, "client_metadata")
@@ -74,7 +74,7 @@ func withoutLiteMetadata(body []byte) []byte {
// withoutReasoningContext is body without reasoning.context, the rest of
// reasoning and every other member byte for byte as they were.
func withoutReasoningContext(body []byte) []byte {
if !bytes.Contains(body, []byte(`"context"`)) {
if !bodyHas(body, `"context"`) {
return body
}
r, found, ok := topMember(body, "reasoning")
@@ -138,7 +138,7 @@ const liteNamespace = "functions"
// 4 MB conversation, held at once by each request in flight, so a few
// subagents at once took the app toward 2 GB (XiaoYin_OK on X).
func liftAdditionalTools(body []byte) []byte {
if !bytes.Contains(body, []byte(`"additional_tools"`)) {
if !bodyHas(body, `"additional_tools"`) {
return body
}
in, found, ok := topMember(body, "input")
+2 -3
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"strings"
@@ -30,7 +29,7 @@ import (
// advisor's model is the client's to name, and the vendor runs it on the
// user's account, so a key held to some models is held here too.
func advisorTools(body []byte, p provider.Provider, upstream string, wires map[string]string, allowed func(model string) bool) []byte {
if !bytes.Contains(body, []byte(`"advisor_`)) {
if !bodyHas(body, `"advisor_`) {
return body
}
tools := gjson.GetBytes(body, "tools")
@@ -158,7 +157,7 @@ func advisorGoneIn(text string) (string, bool) {
// tools, which Claude Code answers "No such tool available: advisor"
// (JackChou on Discord).
func withoutAdvisor(raw json.RawMessage, gone map[string]bool) (json.RawMessage, bool) {
if len(gone) == 0 || !bytes.Contains(raw, []byte("dvisor")) {
if len(gone) == 0 || !bodyHas(raw, "dvisor") {
return raw, false
}
var msgs []map[string]json.RawMessage
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -50,7 +49,7 @@ const advisorUses = 3
// it serves on p's model on API to: Claude Code asked for one, the
// upstream doesn't run it itself, and magpie serves its model.
func advisedHere(p provider.Provider, from, to provider.Protocol, model string, body []byte, wires map[string]string) bool {
if from != provider.Anthropic || !bytes.Contains(body, []byte(`"advisor_`)) {
if from != provider.Anthropic || !bodyHas(body, `"advisor_`) {
return false
}
adv := ""
+3 -3
View File
@@ -345,7 +345,7 @@ func readAdvised(body []byte, clientMarks, facts, advised bool) (*Request, error
// turnEffort is the last effort a message of an Anthropic request carries
// in its own output_config; "" when none does.
func turnEffort(body []byte) string {
if !bytes.Contains(body, []byte(`"output_config"`)) {
if !bodyHas(body, `"output_config"`) {
return ""
}
last := ""
@@ -404,7 +404,7 @@ func anthropicReplaysThinking(host, model string) bool {
// group that falls from Claude to DeepSeek sends both (#1611). Every other
// message, and a body with nothing to change, goes byte for byte.
func withThinkingOnToolTurns(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tool_use"`)) && !bytes.Contains(body, []byte(`"redacted_thinking"`)) {
if !bodyHas(body, `"tool_use"`) && !bodyHas(body, `"redacted_thinking"`) {
return body
}
var q map[string]json.RawMessage
@@ -2007,7 +2007,7 @@ func newID() string {
// to every request offering it (#646). A schema that has none is sent as
// it came.
func objectSchema(schema json.RawMessage) json.RawMessage {
if !bytes.Contains(schema, []byte(`Of"`)) {
if !bodyHas(schema, `Of"`) {
return schema
}
var m map[string]any
+8 -8
View File
@@ -188,7 +188,7 @@ func (s *Server) withoutRefusedShapes(p provider.Provider, body []byte) []byte {
if !s.fits(p.ID, shapeSafeguards, provider.Anthropic) && gjson.GetBytes(body, "safeguards").Exists() {
body = withoutFields(body, "safeguards")
}
if !bytes.Contains(body, []byte(`"display"`)) && !bytes.Contains(body, []byte(`"output_config"`)) {
if !bodyHas(body, `"display"`) && !bodyHas(body, `"output_config"`) {
return body
}
if d := gjson.GetBytes(body, "thinking.display"); d.Exists() {
@@ -230,7 +230,7 @@ func withDisplay(body []byte, all bool) []byte {
// hasTurnEffort is a request with an output_config on one of its messages.
func hasTurnEffort(body []byte) bool {
if !bytes.Contains(body, []byte(`"output_config"`)) {
if !bodyHas(body, `"output_config"`) {
return false
}
found := false
@@ -284,7 +284,7 @@ func withoutTurnEffort(body []byte) []byte {
// none (a turn's effort alone) is left out. The other messages stay as they
// were sent.
func withSystemOnTop(body []byte) []byte {
if !bytes.Contains(body, []byte(`"system"`)) {
if !bodyHas(body, `"system"`) {
return body
}
var v struct {
@@ -366,7 +366,7 @@ func deferredBlock(typ string) bool {
// blocks refuses there too (#5404). A tool_reference inside a tool_result
// (ToolSearch's older answer) is not one.
func hasDeferredTools(body []byte) bool {
if !bytes.Contains(body, []byte(`"tool_addition"`)) && !bytes.Contains(body, []byte(`"tool_removal"`)) && !bytes.Contains(body, []byte(`"tool_reference"`)) && !bytes.Contains(body, []byte(`"tool_definition"`)) {
if !bodyHas(body, `"tool_addition"`) && !bodyHas(body, `"tool_removal"`) && !bodyHas(body, `"tool_reference"`) && !bodyHas(body, `"tool_definition"`) {
return false
}
found := false
@@ -527,7 +527,7 @@ func toolLoadedText(name string) string {
// toolRefs are the tools a tool_result's content names in tool_reference
// blocks, as Claude Code's ToolSearch answers, in their order.
func toolRefs(content json.RawMessage) []string {
if !bytes.Contains(content, []byte(`"tool_reference"`)) {
if !bodyHas(content, `"tool_reference"`) {
return nil
}
var names []string
@@ -557,7 +557,7 @@ func refsOnly(c gjson.Result) bool {
// hasRefsOnlyResult is a request with a tool_result holding only
// tool_reference blocks.
func hasRefsOnlyResult(body []byte) bool {
if !bytes.Contains(body, []byte(`"tool_reference"`)) {
if !bodyHas(body, `"tool_reference"`) {
return false
}
found := false
@@ -648,7 +648,7 @@ func withRefsSaid(body []byte) []byte {
// refsRefused is a refusal that names tool_reference other than as what
// the endpoint expected.
func refsRefused(errBody []byte) bool {
if !bytes.Contains(errBody, []byte("tool_reference")) {
if !bodyHas(errBody, "tool_reference") {
return false
}
return refsNamed.Match(refsExpected.ReplaceAll(errBody, nil))
@@ -657,7 +657,7 @@ func refsRefused(errBody []byte) bool {
// hasResultRefs is a request with a tool_reference block in a
// tool_result's content.
func hasResultRefs(body []byte) bool {
if !bytes.Contains(body, []byte(`"tool_reference"`)) {
if !bodyHas(body, `"tool_reference"`) {
return false
}
found := false
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"slices"
"strings"
@@ -252,7 +251,7 @@ func autoModeClassifierBody(model string, body []byte) []byte {
// Claude Code's auto mode classifier asking about an action. The bytes
// are looked at before the body is parsed: every request passes here.
func autoModeClassifierAsk(body []byte) bool {
if !bytes.Contains(body, []byte("<transcript>")) || !bytes.Contains(body, []byte("<block>")) && !bytes.Contains(body, []byte("<severity>")) {
if !bodyHas(body, "<transcript>") || !bodyHas(body, "<block>") && !bodyHas(body, "<severity>") {
return false
}
req, err := parseAnthropic(body)
+31 -17
View File
@@ -1,6 +1,7 @@
package gateway
import (
"bytes"
"encoding/base64"
"encoding/json"
"sort"
@@ -57,30 +58,43 @@ func stdBase64(s string) (string, bool) {
// isn't a multiple of four. Standard base64 of an image has '+' or '/'
// every few dozen characters, which ends a URL-safe run, and prose has
// spaces; a body it says yes to wrongly is only walked for nothing.
//
// It looks back from each quote, not at every byte: a run ends a string
// only there, and prose stops the look a word back. Its byte-by-byte walk
// took ~2 ms of each 2 MB request (BenchmarkLargeRequest).
func mayHoldOddBase64(body []byte) bool {
const least = 64
start, odd := -1, false
for i, c := range body {
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '+', c == '/', c == '=':
if start < 0 {
start, odd = i, false
for i := 0; ; i++ {
q := bytes.IndexByte(body[i:], '"')
if q < 0 {
return false
}
i += q
start, odd := i, false
for start > 0 {
k := base64Class[body[start-1]]
if k == 0 {
break
}
case c == '-' || c == '_':
if start < 0 {
start = i
}
odd = true
default:
if start >= 0 && c == '"' && i-start >= least && (odd || (i-start)%4 != 0) {
return true
}
start = -1
odd = odd || k == 2
start--
}
if i-start >= least && (odd || (i-start)%4 != 0) {
return true
}
}
return false
}
// base64Class is 1 for a byte of standard base64 (with '='), 2 for one
// only URL-safe base64 has, 0 for the rest.
var base64Class = func() (t [256]uint8) {
for _, c := range []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=") {
t[c] = 1
}
t['-'], t['_'] = 2, 2
return t
}()
// stdBase64Body is the body with each image's inline base64, and each
// Gemini inlineData part's whatever its type (a PDF, a recording), written
// as standard, padded base64; the body as it came when there is none.
+1 -1
View File
@@ -107,7 +107,7 @@ func (s *Server) fitUserBetas(p provider.Provider, h http.Header) {
// bodyBetas fits a body's anthropic_beta list, as Bedrock's InvokeModel
// takes betas, the way betas fits the header's.
func (s *Server) bodyBetas(p provider.Provider, body []byte) []byte {
if !bytes.Contains(body, []byte(`"anthropic_beta"`)) {
if !bodyHas(body, `"anthropic_beta"`) {
return body
}
list := gjson.GetBytes(body, "anthropic_beta")
+1 -1
View File
@@ -43,7 +43,7 @@ func dropsBillingLine(p provider.Provider, to provider.Protocol, model, wire str
// it. Everything else goes as it was sent, byte for byte; a body without
// the line is body itself.
func withoutBillingLine(body []byte) []byte {
if !bytes.Contains(body, []byte("x-anthropic-billing-header:")) {
if !bodyHas(body, "x-anthropic-billing-header:") {
return body
}
sys := gjson.GetBytes(body, "system")
+80
View File
@@ -0,0 +1,80 @@
package gateway
import (
"bytes"
"strings"
"unsafe"
)
// bodyHas is bytes.Contains(b, sep) for the request path's many "is this
// key in the body at all" checks. Most of their needles begin with a
// quote, the commonest byte in JSON: bytes.Index stops at every quote,
// soon gives up on that, and compares at every byte of the body, ~45
// times a request. A 2 MB body spent ~9 ms a request there, a third of
// the gateway's CPU (BenchmarkLargeRequest). bodyHas looks for the
// needle's rarest byte instead, which the CPU finds many bytes at a
// time, and compares the needle only where that byte is.
func bodyHas(b []byte, sep string) bool { return bodyIndex(b, sep) >= 0 }
// bodyIndex is bytes.Index(b, sep), found as bodyHas finds it.
func bodyIndex(b []byte, sep string) int {
if len(sep) < 2 || len(b) < 1024 {
return indexStr(b, sep)
}
k := rarestByte(sep)
c := sep[k]
misses := 0
for i := k; i < len(b); {
j := bytes.IndexByte(b[i:], c)
if j < 0 {
return -1
}
at := i + j - k
if at+len(sep) > len(b) {
return -1
}
if string(b[at:at+len(sep)]) == sep {
return at
}
i += j + 1
// a needle of only common bytes stops too often: what is left
// goes to bytes.Index, which is no slower than before
if misses++; misses > 64 && misses*64 > i {
if n := indexStr(b[at+1:], sep); n >= 0 {
return at + 1 + n
}
return -1
}
}
return -1
}
// indexStr is strings.Index over b, which a []byte(sep) of a long
// needle would have copied to the heap on each call.
func indexStr(b []byte, sep string) int {
return strings.Index(unsafe.String(unsafe.SliceData(b), len(b)), sep)
}
// commonBytes are the bytes JSON, English and code use most, commonest
// first; a byte not here is rarer than all of them.
const commonBytes = " \"etaoinsrhldcu:,mpf{}gy_wb.\nv/k-x0123456789TISACE\\"
// byteRank is a byte's place in commonBytes counted from the end: higher
// is commoner, 0 is rare.
var byteRank = func() (r [256]uint8) {
for i := range len(commonBytes) {
r[commonBytes[i]] = uint8(len(commonBytes) - i)
}
return r
}()
// rarestByte is the index of sep's rarest byte, the last of equals.
func rarestByte(sep string) int {
k := 0
for i := 1; i < len(sep); i++ {
if byteRank[sep[i]] <= byteRank[sep[k]] {
k = i
}
}
return k
}
+132
View File
@@ -0,0 +1,132 @@
package gateway
import (
"bytes"
"math/rand/v2"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// TestBodyIndexIsIndex holds bodyIndex to bytes.Index: needles at the
// start, the end, across where the search gives up on rare bytes, absent,
// and made only of common bytes.
func TestBodyIndexIsIndex(t *testing.T) {
body := largeConversation(provider.Responses, "fake/m1", 20_000)
needles := []string{`"developer"`, `"compaction`, "image/hei", `image\/hei`, `"display"`,
`"output_config"`, passthroughKey, `"type"`, `" "`, " ", `e"`, "eXB", `"input"`,
string(body[:40]), string(body[len(body)-40:]), string(body[len(body)/2 : len(body)/2+9]), "zzzzQ"}
for _, n := range needles {
if got, want := bodyIndex(body, n), bytes.Index(body, []byte(n)); got != want {
t.Errorf("bodyIndex(%q) = %v, want %v", n, got, want)
}
}
r := rand.New(rand.NewPCG(1, 2))
alpha := []byte(` "eta:,{}vXQ\`)
for range 3000 {
b := make([]byte, 1024+r.IntN(4096))
for i := range b {
b[i] = alpha[r.IntN(len(alpha))]
}
var n string
if r.IntN(2) == 0 {
at := r.IntN(len(b) - 8)
n = string(b[at : at+2+r.IntN(6)])
} else {
nb := make([]byte, 2+r.IntN(5))
for i := range nb {
nb[i] = alpha[r.IntN(len(alpha))]
}
n = string(nb)
}
if got, want := bodyIndex(b, n), bytes.Index(b, []byte(n)); got != want {
t.Fatalf("bodyIndex(%q) = %v, want %v in %q", n, got, want, b)
}
}
if !bodyHas([]byte(strings.Repeat("a", 2000)+`"display"`), `"display"`) {
t.Error("missed a needle at the very end")
}
}
func BenchmarkBodyHas(b *testing.B) {
body := largeConversation(provider.Responses, "fake/m1", 300_000)
needles := []string{`"developer"`, `"compaction`, "image/hei", `"display"`, `"output_config"`, passthroughKey, `"text"`}
for _, f := range []struct {
name string
has func([]byte, string) bool
}{{"contains", func(b []byte, s string) bool { return bytes.Contains(b, []byte(s)) }}, {"bodyHas", bodyHas}} {
b.Run(f.name, func(b *testing.B) {
b.SetBytes(int64(len(body) * len(needles)))
for range b.N {
for _, n := range needles {
f.has(body, n)
}
}
})
}
}
// oddBase64Walk is mayHoldOddBase64 as it walked every byte, the answer
// its look back from each quote must give.
func oddBase64Walk(body []byte) bool {
const least = 64
start, odd := -1, false
for i, c := range body {
switch {
case c >= 'A' && c <= 'Z', c >= 'a' && c <= 'z', c >= '0' && c <= '9', c == '+', c == '/', c == '=':
if start < 0 {
start, odd = i, false
}
case c == '-' || c == '_':
if start < 0 {
start = i
}
odd = true
default:
if start >= 0 && c == '"' && i-start >= least && (odd || (i-start)%4 != 0) {
return true
}
start = -1
}
}
return false
}
func TestOddBase64LooksAsItWalked(t *testing.T) {
r := rand.New(rand.NewPCG(3, 4))
alpha := []byte(`AZaz09+/=-_" :`)
yes := 0
for range 20000 {
b := make([]byte, r.IntN(400))
// long runs of one alphabet, so a run reaches 64
for i := 0; i < len(b); {
n := 1 + r.IntN(90)
pick := alpha[:10+r.IntN(5)]
for j := 0; j < n && i < len(b); j++ {
b[i] = pick[r.IntN(len(pick))]
i++
}
if i < len(b) {
b[i] = alpha[10+r.IntN(4)]
i++
}
}
want := oddBase64Walk(b)
if want {
yes++
}
if got := mayHoldOddBase64(b); got != want {
t.Fatalf("mayHoldOddBase64(%q) = %v, want %v", b, got, want)
}
}
if yes < 100 {
t.Fatalf("only %d of the bodies held odd base64: the test reaches too little", yes)
}
for _, p := range []provider.Protocol{provider.Responses, provider.Chat, provider.Anthropic} {
body := largeConversation(p, "fake/m1", 20_000)
if got, want := mayHoldOddBase64(body), oddBase64Walk(body); got != want {
t.Errorf("%s: %v, want %v", p, got, want)
}
}
}
+3 -3
View File
@@ -980,7 +980,7 @@ func geminiCompat(host, model string) bool {
// thinking's type, and where the gateway and every other Chat API read it.
// A request that says reasoning_effort itself is left as it is.
func thinkingEffort(body []byte) []byte {
if !bytes.Contains(body, []byte(`"effort"`)) {
if !bodyHas(body, `"effort"`) {
return body
}
var v struct {
@@ -1004,7 +1004,7 @@ func thinkingEffort(body []byte) []byte {
// for every route, and no field an upstream doesn't know. A
// prompt_cache_key the body has already is the one kept.
func cacheKeyCamel(body []byte) []byte {
if !bytes.Contains(body, []byte(`"promptCacheKey"`)) {
if !bodyHas(body, `"promptCacheKey"`) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -1067,7 +1067,7 @@ func refusesThinkingConfig(status int, body []byte) bool {
return false
}
b := bytes.ToLower(body)
return bytes.Contains(b, []byte("extra_body")) || bytes.Contains(b, []byte("thinking")) || bytes.Contains(b, []byte("include_thoughts"))
return bodyHas(b, "extra_body") || bodyHas(b, "thinking") || bodyHas(b, "include_thoughts")
}
// aiStudioThinking is the thinking_config asking Gemini for its thoughts at
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
@@ -21,7 +20,7 @@ import (
// type), one with no name, and a request that doesn't parse are as they
// came; a tool's other fields stay beside its function.
func shapeChatTools(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tools"`)) {
if !bodyHas(body, `"tools"`) {
return body
}
tools := gjson.GetBytes(body, "tools")
+2 -2
View File
@@ -893,7 +893,7 @@ func asReasoningContent(m map[string]json.RawMessage, think string) {
// reasoning_content alone) and sends it again on every later turn. A body
// without such a turn comes back byte for byte.
func silentAssistantsOut(body []byte) []byte {
if !bytes.Contains(body, []byte(`"assistant"`)) {
if !bodyHas(body, `"assistant"`) {
return body
}
var q map[string]json.RawMessage
@@ -1143,7 +1143,7 @@ func mistralThinking(body []byte) []byte {
// join into one first, as joinSplitCalls does for the translations. A
// body whose exchange pairs comes back byte for byte.
func toolPairsOut(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tool`)) {
if !bodyHas(body, `"tool`) {
return body
}
var q map[string]json.RawMessage
+1 -1
View File
@@ -96,7 +96,7 @@ func wantsClientCache(r *http.Request, from provider.Protocol) bool {
// for its marks.
func classifierClientCache(from provider.Protocol, body []byte) bool {
return from == provider.Anthropic &&
bytes.Contains(body, []byte("cache_control")) &&
bodyHas(body, "cache_control") &&
autoModeClassifierAsk(body)
}
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"context"
"fmt"
"log"
@@ -60,7 +59,7 @@ const claudeNoRoomSaid = "Claude Code processes are running, as many as may run
// claudeNoRoom says whether a failed reply is the bridge's 503 for a full
// claudeRoom.
func claudeNoRoom(status int, body []byte) bool {
return status == 503 && bytes.Contains(body, []byte(claudeNoRoomSaid))
return status == 503 && bodyHas(body, claudeNoRoomSaid)
}
func (e *claudeFull) Error() string {
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
@@ -55,7 +54,7 @@ func claudePart(block json.RawMessage, summary Part) Part {
// redacted) goes. Every other item, and a body with none, goes byte for
// byte.
func withoutClaudeSeals(body []byte) []byte {
if !bytes.Contains(body, []byte(claudeseal.Mark)) {
if !bodyHas(body, claudeseal.Mark) {
return body
}
var q map[string]json.RawMessage
+1 -1
View File
@@ -82,7 +82,7 @@ func (w *signInWriter) Write(b []byte) (int, error) {
}
code := w.held
w.held = 0
if code != http.StatusUnauthorized && (code != http.StatusForbidden || !bytes.Contains(b, []byte("OAuth token has been revoked"))) {
if code != http.StatusUnauthorized && (code != http.StatusForbidden || !bodyHas(b, "OAuth token has been revoked")) {
// any other error, at its status
if xAPIKey.Match(b) {
b = xAPIKey.ReplaceAll(b, []byte("API key"))
+1 -1
View File
@@ -4006,7 +4006,7 @@ type lockedWriter struct{ run *subscriptionRun }
func (w *lockedWriter) Write(p []byte) (int, error) {
// the interactive mode's helper says on its own line why it ended
// (claudetui.Run)
if bytes.Contains(p, []byte("claude-tui: ")) {
if bodyHas(p, "claude-tui: ") {
for _, l := range strings.Split(string(p), "\n") {
if why, ok := strings.CutPrefix(l, "claude-tui: "); ok {
log.Printf("claude: %s", why)
+9 -9
View File
@@ -1718,7 +1718,7 @@ func codexAccountOut(status int, body []byte) bool {
if status == http.StatusUnauthorized {
return false
}
if status == http.StatusForbidden && bytes.Contains(body, []byte("usage_not_included")) {
if status == http.StatusForbidden && bodyHas(body, "usage_not_included") {
return true
}
switch failure(status, body) {
@@ -2886,7 +2886,7 @@ func refusesInput(status int, b []byte) bool {
// request goes back 400 "Item with id 'rs_…' not found" (#1008); its
// summary was the model's notes to itself, which no model reads back.
func withoutBareReasoning(body []byte) []byte {
if !bytes.Contains(body, []byte(`"reasoning"`)) || !anyInputItem(body, func(it []byte) bool {
if !bodyHas(body, `"reasoning"`) || !anyInputItem(body, func(it []byte) bool {
r := reasoningOf(it)
return r.typeOK && r.encOK && r.reasoning && !r.sealed
}) {
@@ -3040,7 +3040,7 @@ func refusesReasoningText(status int, b, body []byte) bool {
// than its text, so the item goes, as codexInput leaves it out for one of
// Codex's own models.
func withoutReasoningText(body []byte) []byte {
if !bytes.Contains(body, []byte(`"reasoning"`)) || !anyInputItem(body, func(it []byte) bool {
if !bodyHas(body, `"reasoning"`) || !anyInputItem(body, func(it []byte) bool {
r := reasoningOf(it)
return r.typeOK && r.contentOK && r.reasoning && r.text
}) {
@@ -3103,7 +3103,7 @@ func refusesCitationOffsets(status int, b []byte) bool {
// with it. Such an annotation goes; the text, and a citation with its
// offsets, stay as they came.
func withoutOffsetlessCitations(body []byte) []byte {
if !bytes.Contains(body, []byte(`"annotations"`)) || !anyInputItem(body, itemCitesWithoutOffsets) {
if !bodyHas(body, `"annotations"`) || !anyInputItem(body, itemCitesWithoutOffsets) {
return body
}
q, err := rawObject(body)
@@ -3173,7 +3173,7 @@ func withoutOffsetlessCitations(body []byte) []byte {
// output_text annotation without the offsets OpenAI's schema wants, read
// as the scan reads it, without decoding the conversation.
func itemCitesWithoutOffsets(it []byte) bool {
if !bytes.Contains(it, []byte(`"annotations"`)) {
if !bodyHas(it, `"annotations"`) {
return false
}
for _, part := range elementsOf(memberOrNil(it, "content")) {
@@ -3206,7 +3206,7 @@ var openaiItemPrefix = map[string]string{
// call's output names it by as it was, and the rest of the request byte
// for byte.
func callItemIDs(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tool_search_call"`)) && !bytes.Contains(body, []byte(`"custom_tool_call"`)) {
if !bodyHas(body, `"tool_search_call"`) && !bodyHas(body, `"custom_tool_call"`) {
return body
}
if !anyInputItem(body, func(it []byte) bool {
@@ -3388,7 +3388,7 @@ var itemKindPrefix = map[string]string{
// with each other character as "_"; a call's call_id, which its output
// names it by, stays as it was.
func plainItemIDs(body []byte) []byte {
if !bytes.Contains(body, []byte(`"id"`)) {
if !bodyHas(body, `"id"`) {
return body
}
if !anyInputItem(body, func(it []byte) bool {
@@ -3639,7 +3639,7 @@ func keepsAccessPrograms(p provider.Provider, in http.Header) bool {
// withoutAccessPrograms is body without its top-level access_programs, the
// rest byte for byte (withoutTopMember).
func withoutAccessPrograms(body []byte) []byte {
if !bytes.Contains(body, []byte(`"access_programs"`)) {
if !bodyHas(body, `"access_programs"`) {
return body
}
return withoutTopMember(body, "access_programs")
@@ -3693,7 +3693,7 @@ func forVendorChanges(body []byte) bool {
// takes developer alone, never comes here. The message stays where it
// stood, so a thread's cached prefix keeps its shape (#502).
func developerItemsAsSystem(body []byte) []byte {
if !bytes.Contains(body, []byte(`"developer"`)) {
if !bodyHas(body, `"developer"`) {
return body
}
var q map[string]json.RawMessage
+1 -1
View File
@@ -106,5 +106,5 @@ func edgeSaidDrop(status int, head []byte) bool {
// codexReset says a failure is a large request's reset codexDropped read:
// no account's fault, and asked again.
func codexReset(status int, body []byte) bool {
return status == http.StatusServiceUnavailable && bytes.Contains(body, []byte(codexResetSaid))
return status == http.StatusServiceUnavailable && bodyHas(body, codexResetSaid)
}
+1 -1
View File
@@ -41,7 +41,7 @@ import (
// refuses "low" itself, and it is left as sent. WebP, which Go's standard
// library doesn't decode, is left as sent too.
func codexImagesFit(p provider.Provider, to provider.Protocol, body []byte) []byte {
if p.Account == nil || p.Account.Agent != "codex" || to != provider.Responses || !bytes.Contains(body, []byte(`input_image`)) {
if p.Account == nil || p.Account.Agent != "codex" || to != provider.Responses || !bodyHas(body, `input_image`) {
return body
}
// One walk of the body: each input item, and the parts of the items
+1 -1
View File
@@ -181,7 +181,7 @@ func (t *codexLimitsTap) look() {
line := bytes.TrimSpace(t.buf[:i])
t.buf = t.buf[i+1:]
data, ok := bytes.CutPrefix(line, []byte("data:"))
if !ok || !bytes.Contains(data, []byte(`"codex.rate_limits"`)) {
if !ok || !bodyHas(data, `"codex.rate_limits"`) {
continue
}
if ls := codexEventLimits(bytes.TrimSpace(data), time.Now()); len(ls) > 0 {
+3 -3
View File
@@ -44,7 +44,7 @@ type spawnChoice struct{ slug, name string }
// spawn_agent tool naming every model of the catalog that Codex was handed
// there, not only the first five. lead is the request's model.
func spawnAgentModels(r *http.Request, body []byte, lead string, codexPath bool) []byte {
if !bytes.Contains(body, []byte(`"spawn_agent"`)) || !bytes.Contains(body, []byte("Available model overrides")) {
if !bodyHas(body, `"spawn_agent"`) || !bodyHas(body, "Available model overrides") {
return body
}
choices := spawnChoices(r, lead, codexPath)
@@ -70,7 +70,7 @@ func spawnAgentModels(r *http.Request, body []byte, lead string, codexPath bool)
// in a tool_search_output, not in tools (Gearclickist on Discord, after
// v0.1.1214). Codex sends that output as it got it on every turn, so
// it is widened the same way on each.
if input, found, _ := topMember(body, "input"); found && bytes.Contains(input, []byte("tool_search_output")) {
if input, found, _ := topMember(body, "input"); found && bodyHas(input, "tool_search_output") {
if in, ok := moreSpawnInput(input, choices); ok {
set["input"] = in
}
@@ -95,7 +95,7 @@ func moreSpawnInput(input []byte, choices []spawnChoice) ([]byte, bool) {
for raw[i] != ']' {
at := i
i = skipJSONValue(raw, i)
if el := raw[at:i]; el[0] == '{' && bytes.Contains(el, []byte("tool_search_output")) {
if el := raw[at:i]; el[0] == '{' && bodyHas(el, "tool_search_output") {
if it, ok := moreSpawnItem(el, choices); ok {
out = append(append(out, raw[last:at]...), it...)
last = i
+1 -2
View File
@@ -17,7 +17,6 @@ package gateway
// isn't asked to go on (prefill.go).
import (
"bytes"
"context"
"encoding/json"
"errors"
@@ -133,7 +132,7 @@ func spends(ev Event) bool {
// a reply said nothing, and is the empty reply's to answer (#667), not a
// cut one's.
func geminiEnds(data []byte) bool {
if !bytes.Contains(data, []byte(`"finishReason"`)) && bytes.Contains(data, []byte(`"candidates"`)) {
if !bodyHas(data, `"finishReason"`) && bodyHas(data, `"candidates"`) {
return false
}
type chunk struct {
+1 -1
View File
@@ -161,7 +161,7 @@ func conversationOutput(proto provider.Protocol, output []byte) ([]sessions.Part
if json.Valid(trim) {
t.Output, err = conversationJSON(proto, trim)
t.Cut = t.Cut || err != nil
} else if bytes.Contains(trim, []byte("data:")) {
} else if bodyHas(trim, "data:") {
var c collector
var completedItems []json.RawMessage
decode := decoder(proto)
+1 -1
View File
@@ -412,7 +412,7 @@ func derefLocal(top map[string]any, ref string) map[string]any {
return nil
}
raw, err := json.Marshal(target)
if err != nil || bytes.Contains(raw, []byte(`"$ref"`)) {
if err != nil || bodyHas(raw, `"$ref"`) {
return nil
}
dec := json.NewDecoder(bytes.NewReader(raw))
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"strconv"
"unicode/utf8"
@@ -34,7 +33,7 @@ func customToolRefused(model string) string { return "custom tools\x00" + model
// among its tools, in a namespace there, or in an input item that carries
// tools (Responses Lite's additional_tools, a tool search's output).
func hasCustomTool(body []byte) bool {
if !bytes.Contains(body, []byte(`"custom"`)) {
if !bodyHas(body, `"custom"`) {
return false
}
var m map[string]any
+2 -2
View File
@@ -23,7 +23,7 @@ func deepseekToolPatterns(p provider.Provider, to provider.Protocol, body []byte
if p.VendorPreset() != "deepseek" && provider.HostOf(p.Base(to)) != "api.deepseek.com" && p.VendorHost() != "api.deepseek.com" {
return body
}
if !bytes.Contains(body, []byte(`\\0`)) {
if !bodyHas(body, `\\0`) {
return body
}
return toolPatterns(body, unicodeNullEscape)
@@ -193,7 +193,7 @@ func deepseekTokenField(p provider.Provider, to provider.Protocol, body []byte)
if to != provider.Chat || p.VendorPreset() != "deepseek" && provider.HostOf(p.Base(to)) != "api.deepseek.com" && p.VendorHost() != "api.deepseek.com" && !deepseekModel(gjson.GetBytes(body, "model").String()) {
return body
}
if !bytes.Contains(body, []byte(`"max_completion_tokens"`)) || gjson.GetBytes(body, "max_tokens").Exists() {
if !bodyHas(body, `"max_completion_tokens"`) || gjson.GetBytes(body, "max_tokens").Exists() {
return body
}
v := gjson.GetBytes(body, "max_completion_tokens")
+2 -3
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"fmt"
"hash/fnv"
@@ -978,7 +977,7 @@ const desktopTitlePrompt = "You write short session titles."
// desktopTitle: the request's system prompt is Desktop's title prompt, as a
// string (Desktop's client) or one of its text blocks (Claude Code's).
func desktopTitle(body []byte) bool {
if !bytes.Contains(body, []byte(desktopTitlePrompt)) {
if !bodyHas(body, desktopTitlePrompt) {
return false
}
var v struct {
@@ -1017,7 +1016,7 @@ func small(body []byte) bool {
// hasTools: the request offers the model tools (Anthropic's, Chat's and
// Responses' "tools" alike).
func hasTools(body []byte) bool {
if !bytes.Contains(body, []byte(`"tools"`)) {
if !bodyHas(body, `"tools"`) {
return false
}
var v struct {
+2 -2
View File
@@ -1563,9 +1563,9 @@ func (t *tracked) Read(p []byte) (int, error) {
func stalledAt(got []byte, quiet time.Duration) string {
where := fmt.Sprintf("%s had come, and nothing more for the last %s", sizeOf(len(got)), quiet.Round(time.Second))
switch {
case bytes.Contains(got, []byte(`"b64_json"`)):
case bodyHas(got, `"b64_json"`):
return "it was sending the image itself as b64_json; " + where
case bytes.Contains(got, []byte(`"url"`)):
case bodyHas(got, `"url"`):
return "it was answering with the image's url, not the image; " + where
}
return "what came doesn't yet say whether the image was coming as a url or as b64_json; " + where
+2 -2
View File
@@ -245,7 +245,7 @@ func isUserItem(raw json.RawMessage) bool {
// effortUpdated is the effort the last configuration_update in a Responses
// request's input asks for: "" with none.
func effortUpdated(body []byte) string {
if !bytes.Contains(body, []byte(`"configuration_update"`)) {
if !bodyHas(body, `"configuration_update"`) {
return ""
}
e := ""
@@ -279,7 +279,7 @@ func updateEffort(it []byte) string {
// that reads the items isn't asked another by them, and the thread's
// prefix stays as it was. The body as it is when it has none.
func withEffortUpdated(body []byte, effort string) []byte {
if !bytes.Contains(body, []byte(`"configuration_update"`)) {
if !bodyHas(body, `"configuration_update"`) {
return body
}
q, err := rawObject(body)
+10 -10
View File
@@ -1736,7 +1736,7 @@ func codeAssistModelMissing(p provider.Provider, status int, body []byte) bool {
if p.Account.Agent != "antigravity" && p.Account.Agent != "gemini" {
return false
}
return bytes.Contains(body, []byte("NOT_FOUND")) || bytes.Contains(bytes.ToLower(body), []byte("not found"))
return bodyHas(body, "NOT_FOUND") || bytes.Contains(bytes.ToLower(body), []byte("not found"))
}
// retiredWords are how a vendor says the model is retired, though its
@@ -2235,7 +2235,7 @@ var transportWords = lazyre.New(`(?i)dial (tcp|udp)|connectex|wsarecv|wsasend|i/
// broke off or said nothing.
func transportFailed(body []byte) bool {
return transportWords.Match(body) || bytes.Contains(body, []byte(errEndedShort.Error())) ||
bytes.Contains(body, []byte(didNotStream)) || magpieSaid(string(body))
bodyHas(body, didNotStream) || magpieSaid(string(body))
}
// noteHeld keeps n as the most prompt tokens the provider's model has
@@ -2344,14 +2344,14 @@ func passing(status int, header http.Header, body []byte, again int) (time.Durat
case wait > longestPause:
return 0, false
case busyStatus(status):
if bytes.Contains(body, []byte(didNotStream)) || bytes.Contains(body, []byte(cutVoidWords)) {
if bodyHas(body, didNotStream) || bodyHas(body, cutVoidWords) {
// a void cut at its length fails the same every ask: the
// budget went to reasoning, and mostly would again — the same
// one asked again would burn it twice over before the error
// (#2972). A group's next member still is.
return 0, false
}
if bytes.Contains(body, []byte(emptyReply)) {
if bodyHas(body, emptyReply) {
// a model that answered nothing was asked again in place
// already (emptyRetries); asking the whole request again as
// often as a vendor's outage multiplied the two, nine asks of a
@@ -3491,9 +3491,9 @@ func (h *holdWriter) refusalAfter(b []byte) {
// too — the cost of missing one, a call the agent would run beside the
// next member's, is the greater.
func mayCall(b []byte) bool {
return bytes.Contains(b, []byte(`"tool_calls"`)) ||
bytes.Contains(b, []byte(`"tool_use"`)) ||
bytes.Contains(b, []byte(`"function_call"`))
return bodyHas(b, `"tool_calls"`) ||
bodyHas(b, `"tool_use"`) ||
bodyHas(b, `"function_call"`)
}
// mayRefuse is whether an event may be the safety filter's refusal, by the
@@ -3868,7 +3868,7 @@ func (h *holdWriter) started() bool {
// for a reply wanted whole (wantWhole), no answer (#2274). A filter's
// reason is a refusal, read before this (streamEvent).
func endedIncomplete(ev []byte) (string, bool) {
if !bytes.Contains(ev, []byte("incomplete")) {
if !bodyHas(ev, "incomplete") {
return "", false
}
var data []byte
@@ -4248,7 +4248,7 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
thinks = true // its reasoning, said to nobody yet
continue
}
if json.Unmarshal(p, &part) != nil || part.Text != "" || !bytes.Contains(p, []byte(`"text"`)) {
if json.Unmarshal(p, &part) != nil || part.Text != "" || !bodyHas(p, `"text"`) {
return eventContent, 0, "" // text, or a call
}
}
@@ -4274,7 +4274,7 @@ func streamEvent(ev []byte) (kind, status int, msg string) {
// safety buffering, moderation, a verification it recommends.
// Taken for content, it let the stream through, and the
// response.failed bio_policy after it went to Codex (#248)
if bytes.Contains(data, []byte(`"safety_buffering"`)) {
if bodyHas(data, `"safety_buffering"`) {
return eventBuffering, 0, ""
}
return eventLead, 0, ""
+8 -8
View File
@@ -397,7 +397,7 @@ func ServedAt(base string) Served {
Serves string `json:"serves"`
}
if decodeJSON(b, &info) != nil || info.Name != "magpie" {
return Served{Running: bytes.Contains(b, []byte(`"magpie"`)), Window: bytes.Contains(b, []byte(`"window":true`))}
return Served{Running: bodyHas(b, `"magpie"`), Window: bodyHas(b, `"window":true`)}
}
return Served{Running: true, Window: info.Window, Version: info.Version, Pid: info.Pid, Serves: info.Serves}
}
@@ -2298,7 +2298,7 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc {
// which magpie points here, #1301): the summary is magpie's to
// make, as on CodexPath, and magpie's summaries go back as text;
// a provider set to compact natively is asked Codex's own (#1099)
if bytes.Contains(body, []byte(`"compaction`)) {
if bodyHas(body, `"compaction`) {
var compact bool
if body, compact = codexInputAs(body, true, s.nativeCompactionFor(modelOf(body))); compact {
s.codexCompact(w, r, body)
@@ -3012,7 +3012,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// a video for a model its list says takes none is turned away, not
// left out for the model to answer the words alone (#6135); a group's
// members are picked by it below
if !isGroup && bytes.Contains(body, []byte("video")) && noVideo(p.ID, model) && hasCurrentVideo(from, body) {
if !isGroup && bodyHas(body, "video") && noVideo(p.ID, model) && hasCurrentVideo(from, body) {
call.Status, call.Error = 400, "model does not support video input"
writeError(w, from, 400, videoRefused(call.Model, ""))
turnedAway()
@@ -8769,7 +8769,7 @@ func cacheKeyOf(in http.Header, req *Request) string {
// doesn't take — Gemini's "Unknown name", Mistral's extra_forbidden,
// Groq's "unsupported" — by the field's name in the error.
func refusesField(status int, body []byte, field string) bool {
return badRequest(status) && bytes.Contains(body, []byte(field))
return badRequest(status) && bodyHas(body, field)
}
// hourMarksRefused is an upstream that turned away the hour-long cache
@@ -8779,7 +8779,7 @@ const hourMarksRefused = "cache_control.ttl"
// hourMarksRefusal is a 400 over a cache mark's ttl: a relay that knows no
// ttl, or a 1h mark after a 5m one.
func hourMarksRefusal(status int, b []byte) bool {
return badRequest(status) && bytes.Contains(b, []byte("ttl")) && bytes.Contains(b, []byte("cache_control"))
return badRequest(status) && bodyHas(b, "ttl") && bodyHas(b, "cache_control")
}
// tierField is the client's service tier as a request carries it upstream
@@ -9947,7 +9947,7 @@ func rewriteModel(body []byte, model string) []byte {
// accepts, but other Chat Completions backends (DeepSeek among them) reject
// the whole request; every backend accepts system, OpenAI included.
func developerAsSystem(body []byte) []byte {
if !bytes.Contains(body, []byte(`"developer"`)) {
if !bodyHas(body, `"developer"`) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -10712,7 +10712,7 @@ func withFields(body []byte, fields map[string]any) []byte {
// max_completion_tokens in place of max_tokens, as Bedrock's OpenAI
// endpoint takes it: its GPT models turn max_tokens away (#176).
func asCompletionTokens(body []byte) []byte {
if !bytes.Contains(body, []byte(`"max_tokens"`)) {
if !bodyHas(body, `"max_tokens"`) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -10777,7 +10777,7 @@ func refusesLoneToolChoice(p provider.Provider) bool {
// withoutLoneToolChoice leaves out a tool_choice sent with no tools; with
// none to choose from it says nothing.
func withoutLoneToolChoice(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tool_choice"`)) {
if !bodyHas(body, `"tool_choice"`) {
return body
}
var q struct {
+1 -1
View File
@@ -181,7 +181,7 @@ func geminiRequest(r *Request, model, agent string) (map[string]any, error) {
// (#934). The values that are the caller's own — a call's args, a
// result's response, the schemas — keep their keys as they are.
func geminiCamel(body []byte) []byte {
if !bytes.Contains(body, []byte("_")) {
if !bodyHas(body, "_") {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
+2 -2
View File
@@ -190,8 +190,8 @@ func googleExtra(sig string) map[string]any {
// A signature another provider gave (foreignSignature) goes to none, nor
// does any when keep is false (signatureRefused: asked again without).
func chatCallSignatures(body []byte, gemini bool, by string, keep bool) []byte {
signed := bytes.Contains(body, []byte(sigMark))
if !signed && !(gemini && bytes.Contains(body, []byte(`"tool_calls"`))) {
signed := bodyHas(body, sigMark)
if !signed && !(gemini && bodyHas(body, `"tool_calls"`)) {
return body
}
return editMessages(body, []string{"tool_calls", "tool_call_id"}, func(m map[string]json.RawMessage) bool {
+3 -3
View File
@@ -200,11 +200,11 @@ func (t *intTidy) flush() []byte {
func (t *intTidy) carries(b []byte) bool {
switch t.proto {
case provider.Responses:
return bytes.Contains(b, []byte(`function_call`))
return bodyHas(b, `function_call`)
case provider.Chat:
return bytes.Contains(b, []byte(`"tool_calls"`))
return bodyHas(b, `"tool_calls"`)
case provider.Anthropic:
return bytes.Contains(b, []byte(`"tool_use"`)) || bytes.Contains(b, []byte(`"input_json_delta"`))
return bodyHas(b, `"tool_use"`) || bodyHas(b, `"input_json_delta"`)
}
return false
}
+2 -2
View File
@@ -29,7 +29,7 @@ import (
// namespacedIn is the namespaced functions a Responses request offers or
// has called, by the flat name Grok is given them under.
func namespacedIn(body []byte) map[string]nsTool {
if !bytes.Contains(body, []byte(`"namespace"`)) {
if !bodyHas(body, `"namespace"`) {
return nil
}
var q struct {
@@ -174,7 +174,7 @@ func (t *nsTidy) restore(data []byte) ([]byte, bool) {
// carries reports whether b may hold a call restore names again: a
// function call, or a custom tool's to one renamed.
func (t *nsTidy) carries(b []byte) bool {
return bytes.Contains(b, []byte(`"function_call"`)) || t.back != nil && bytes.Contains(b, []byte(`"custom_tool_call"`))
return bodyHas(b, `"function_call"`) || t.back != nil && bodyHas(b, `"custom_tool_call"`)
}
// call names a function_call to a namespaced function by its name and
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"strings"
"github.com/tidwall/gjson"
@@ -27,7 +26,7 @@ func grokToolPatterns(p provider.Provider, to provider.Protocol, body []byte) []
if p.VendorHost() != "api.x.ai" && !grokModel(gjson.GetBytes(body, "model").String()) {
return body
}
if !bytes.Contains(body, []byte(`"pattern"`)) {
if !bodyHas(body, `"pattern"`) {
return body
}
return toolPatterns(body, ecmaClassForRust)
+2 -2
View File
@@ -76,11 +76,11 @@ var heicEncode = encodeHEIC
// mayHoldHEIC is whether the body may have a HEIC in it: an image/heic or
// image/heif type, or the base64 of an HEVC still's ftyp.
func mayHoldHEIC(body []byte) bool {
if bytes.Contains(body, []byte("image/hei")) || bytes.Contains(body, []byte(`image\/hei`)) {
if bodyHas(body, "image/hei") || bodyHas(body, `image\/hei`) {
return true
}
for rest := body; ; {
i := bytes.Index(rest, []byte("eXB"))
i := bodyIndex(rest, "eXB")
if i < 0 {
return false
}
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/yetone/magpie/internal/provider"
@@ -29,7 +28,7 @@ func takesOriginalDetail(p provider.Provider) bool {
// "original" sent as "high", the closest an API without it has, as a Chat
// upstream is sent it (chatDetail); the body as it came when it has none.
func originalAsHigh(body []byte) []byte {
if !bytes.Contains(body, []byte(`"original"`)) {
if !bodyHas(body, `"original"`) {
return body
}
out, err := walkImages(provider.Responses, body, func(im imageAt) (json.RawMessage, error) {
+2 -2
View File
@@ -26,7 +26,7 @@ func kimiToolEnumTypes(p provider.Provider, to provider.Protocol, body []byte) [
if !isKimi(p, to) {
return body
}
if !bytes.Contains(body, []byte(`"enum"`)) && !bytes.Contains(body, []byte(`"const"`)) {
if !bodyHas(body, `"enum"`) && !bodyHas(body, `"const"`) {
return body
}
tools := gjson.GetBytes(body, "tools")
@@ -302,7 +302,7 @@ func leadingInt(s string) (int, string) {
// ref to nowhere, or never ends, leaves its schemas as they were. Written
// in place, like kimiToolEnumTypes', after which it runs.
func kimiToolRefTypes(p provider.Provider, to provider.Protocol, body []byte) []byte {
if !isKimi(p, to) || !bytes.Contains(body, []byte(`"$ref"`)) {
if !isKimi(p, to) || !bodyHas(body, `"$ref"`) {
return body
}
tools := gjson.GetBytes(body, "tools")
+1 -1
View File
@@ -149,7 +149,7 @@ func (g *loopGuard) feed(b []byte) (loopTrip, bool) {
// eventWords is what one event of a reply says, in any protocol: its
// reasoning and its text. Calls, starts, stops and usage say nothing here.
func eventWords(ev []byte) (think, text string) {
if !bytes.Contains(ev, []byte(`delta`)) && !bytes.Contains(ev, []byte(`candidates`)) {
if !bodyHas(ev, `delta`) && !bodyHas(ev, `candidates`) {
return "", "" // most events that aren't content, without reading them
}
var data []byte
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
@@ -27,7 +26,7 @@ import (
// tools. A request with no message tools, or one that doesn't parse, is
// as it came.
func liftMessageTools(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tools"`)) {
if !bodyHas(body, `"tools"`) {
return body
}
if len(gjson.GetBytes(body, "messages.#.tools").Array()) == 0 {
+3 -3
View File
@@ -48,7 +48,7 @@ const (
// compactionTriggerIn says whether a Responses request's input holds
// Codex's compaction_trigger.
func compactionTriggerIn(body []byte) bool {
if !bytes.Contains(body, []byte(`"compaction_trigger"`)) {
if !bodyHas(body, `"compaction_trigger"`) {
return false
}
for _, it := range getIn(body, "input").Array() {
@@ -63,7 +63,7 @@ func compactionTriggerIn(body []byte) bool {
// a Responses request's input that a vendor sealed: magpie's own
// ("magpie1:") are text by the time a request is sent, and aren't.
func sealedCompactions(body []byte) []string {
if !bytes.Contains(body, []byte(`"compaction`)) {
if !bodyHas(body, `"compaction`) {
return nil
}
var out []string
@@ -602,7 +602,7 @@ func (c *compactionWatch) sealed() string {
}
for line := range bytes.SplitSeq(b, []byte("\n")) {
data, ok := bytes.CutPrefix(bytes.TrimSpace(line), []byte("data:"))
if !ok || !bytes.Contains(data, []byte(`"compaction`)) {
if !ok || !bodyHas(data, `"compaction`) {
continue
}
ev := gjson.ParseBytes(bytes.TrimSpace(data))
+1 -1
View File
@@ -44,7 +44,7 @@ func (s *Server) foldsRoots(p provider.Provider, model string, proto provider.Pr
// tools' parameters (a Messages tool's input_schema) have an object root,
// and whether any was changed.
func objectRootsBody(proto provider.Protocol, body []byte) ([]byte, bool) {
if (proto != provider.Chat && proto != provider.Responses && proto != provider.Anthropic) || !bytes.Contains(body, []byte(`Of"`)) {
if (proto != provider.Chat && proto != provider.Responses && proto != provider.Anthropic) || !bodyHas(body, `Of"`) {
return body, false
}
dec := json.NewDecoder(bytes.NewReader(body))
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"context"
"net/http"
"strings"
@@ -90,7 +89,7 @@ func inferredKind(in http.Header, from provider.Protocol, body []byte) string {
// your most recent action in 3-5 words."). The bytes are looked at first:
// every request passes here.
func agentSummaryAsk(body []byte) bool {
if !bytes.Contains(body, []byte("3-5 words")) {
if !bodyHas(body, "3-5 words") {
return false
}
req, err := parseAnthropic(body)
+1 -1
View File
@@ -573,7 +573,7 @@ func (o *ollamaWriter) finish() {
// that says "options" is left as it came, and a body without the word is
// not read at all.
func withoutOllamaOptions(body []byte) []byte {
if !bytes.Contains(body, []byte(`"options"`)) {
if !bodyHas(body, `"options"`) {
return body
}
return withoutTopMember(body, "options")
+1 -1
View File
@@ -20,7 +20,7 @@ func toolOneOfAsAnyOf(p provider.Provider, to provider.Protocol, body []byte) []
if !(p.IsCline() || p.IsKilo() || provider.HostOf(p.Base(to)) == "openrouter.ai") {
return body
}
if !bytes.Contains(body, []byte(`"oneOf"`)) {
if !bodyHas(body, `"oneOf"`) {
return body
}
tools := gjson.GetBytes(body, "tools")
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"strconv"
@@ -130,7 +129,7 @@ func withoutPassthroughIf(body []byte, drop func(field string) bool) ([]byte, bo
// withoutRefusedPassthrough is body without the passthrough members
// providerID turned away before.
func (s *Server) withoutRefusedPassthrough(providerID string, proto provider.Protocol, body []byte) []byte {
if proto != provider.Responses || !bytes.Contains(body, []byte(passthroughKey)) {
if proto != provider.Responses || !bodyHas(body, passthroughKey) {
return body
}
if !s.fits(providerID, passthroughRefused(""), proto) {
+2 -3
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"context"
"net/http"
"slices"
@@ -71,8 +70,8 @@ func busy(status int, body []byte) bool {
switch {
case busyStatus(status):
return failure(status, body) == failOther && !protectionRefused(status, body) &&
!bytes.Contains(body, []byte(didNotStream)) &&
!bytes.Contains(body, []byte(cutVoidWords)) &&
!bodyHas(body, didNotStream) &&
!bodyHas(body, cutVoidWords) &&
!queued(body)
case status == 429:
return failure(status, body) == failRate && !creditWords.Match(wordsOf(body)) && !walled(body)
+1 -1
View File
@@ -479,7 +479,7 @@ func prevElsewhere(r *http.Request, p provider.Provider, body []byte, force bool
return body
}
n := a.total - a.fresh
if n <= 0 || !bytes.Contains(body, []byte(`"id"`)) {
if n <= 0 || !bodyHas(body, `"id"`) {
return body
}
var q map[string]json.RawMessage
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
@@ -235,7 +234,7 @@ func withoutRefusedCarry(ctx context.Context, p provider.Provider, req *Request)
// when any of it wasn't already, so that asking again leaves something
// out.
func refuseCarried(key, who string, from provider.Protocol, body []byte) bool {
if from == provider.Responses || !bytes.Contains(body, []byte(reasonTail)) {
if from == provider.Responses || !bodyHas(body, reasonTail) {
return false
}
req, err := parseRequest(from, body, false, true)
+2 -2
View File
@@ -129,7 +129,7 @@ func (t *reasoningTidy) flush() []byte {
}
func (t *reasoningTidy) lines(b []byte) []byte {
if !bytes.Contains(b, []byte(`"reasoning"`)) {
if !bodyHas(b, `"reasoning"`) {
return append([]byte(nil), b...)
}
var out []byte
@@ -142,7 +142,7 @@ func (t *reasoningTidy) lines(b []byte) []byte {
}
body := bytes.TrimRight(line, "\r\n")
data, ok := bytes.CutPrefix(body, []byte("data:"))
if !ok || !bytes.Contains(data, []byte(`"reasoning"`)) {
if !ok || !bodyHas(data, `"reasoning"`) {
out = append(out, line...)
continue
}
+8 -9
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"cmp"
"encoding/json"
"fmt"
@@ -173,7 +172,7 @@ func searchFound(tools []rTool) string {
// Codex as unsealed (callTo's encrypted_function_args), so an upstream that
// honours the mark must not seal them (#613).
func unsealed(schema json.RawMessage) json.RawMessage {
if !bytes.Contains(schema, []byte(`"encrypted"`)) {
if !bodyHas(schema, `"encrypted"`) {
return schema
}
var v any
@@ -208,7 +207,7 @@ func unsealed(schema json.RawMessage) json.RawMessage {
// "encrypted" (MultiAgentV2's spawn_agent message): an upstream that
// honours the mark answers the call with that argument sealed.
func asksSealing(body []byte) bool {
if !bytes.Contains(body, []byte(`"encrypted"`)) {
if !bodyHas(body, `"encrypted"`) {
return false
}
var q struct {
@@ -245,7 +244,7 @@ func asksSealing(body []byte) bool {
}
marked := func(schema json.RawMessage) bool {
var v any
return bytes.Contains(schema, []byte(`"encrypted"`)) && decodeJSON(schema, &v) == nil && mark(v)
return bodyHas(schema, `"encrypted"`) && decodeJSON(schema, &v) == nil && mark(v)
}
for _, t := range q.Tools {
if marked(t.Parameters) {
@@ -740,7 +739,7 @@ func toolResultItem(t string) bool {
// whole exchanges stays where it is, and a request with nothing inside a
// run comes back byte for byte.
func joinToolRuns(body []byte) []byte {
if !bytes.Contains(body, []byte(`_call"`)) {
if !bodyHas(body, `_call"`) {
return body
}
var q map[string]json.RawMessage
@@ -936,7 +935,7 @@ func orphanedToolOutputs(body []byte) []byte {
// orphanedToolOutputs, and one naming a call another request carried
// (previous_response_id) stays as it is.
func pairToolItems(body []byte) []byte {
if !bytes.Contains(body, []byte(`_call"`)) {
if !bodyHas(body, `_call"`) {
return body
}
var q map[string]json.RawMessage
@@ -1012,7 +1011,7 @@ func pairToolItems(body []byte) []byte {
// pages, never what they said, and the reply after it says what was
// found, so nothing the model read is lost.
func withoutSearchCalls(body []byte) []byte {
if !bytes.Contains(body, []byte(`"web_search_call"`)) {
if !bodyHas(body, `"web_search_call"`) {
return body
}
var q map[string]json.RawMessage
@@ -1156,8 +1155,8 @@ func replaysReasoning(model, host string) bool {
// be passed back to the API" (#1104, #1592, #1822). A body with nothing to
// give comes back byte for byte.
func withReasoningText(body []byte) []byte {
if !bytes.Contains(body, []byte(`"reasoning"`)) && !bytes.Contains(body, []byte(`_call"`)) &&
!bytes.Contains(body, []byte(`_output"`)) {
if !bodyHas(body, `"reasoning"`) && !bodyHas(body, `_call"`) &&
!bodyHas(body, `_output"`) {
return body
}
var q map[string]json.RawMessage
+6 -6
View File
@@ -134,7 +134,7 @@ func plainUnavailable(c candidate, status int, body []byte) bool {
}
return failureOf(c, status, body) == failOther && !vendorOverloaded(status, body) &&
!modelRefused(status, body) && !codexReset(status, body) && !protectionRefused(status, body) &&
!bytes.Contains(body, []byte(didNotStream)) && refusalWords(status, body) != ""
!bodyHas(body, didNotStream) && refusalWords(status, body) != ""
}
// idRun is a run in an error's words that differs from one try to the
@@ -569,7 +569,7 @@ func carriedStatus(status int, body []byte) int {
// failure says why a reply failed.
func failure(status int, body []byte) string {
status = carriedStatus(status, body)
if status == http.StatusBadGateway && (proxyDown.Match(body) || bytes.Contains(body, []byte(closedUnsentWords)) || bytes.Contains(body, []byte(stalledWords))) {
if status == http.StatusBadGateway && (proxyDown.Match(body) || bodyHas(body, closedUnsentWords) || bodyHas(body, stalledWords)) {
// the proxy didn't take the connection, or the network closed
// each new one before the request was sent (errClosedUnsent):
// nothing reached the vendor, and the account is as good as it
@@ -597,7 +597,7 @@ func failure(status int, body []byte) string {
// Kimi's "exceeded model token limit" is the conversation's
// length, not the plan's
return failOther
case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !bytes.Contains(body, []byte("insufficient_quota")):
case status == 402 && usedUpWords.Match(body) && !creditWords.Match(body) && !bodyHas(body, "insufficient_quota"):
// a 402 that says a usage limit and nothing of money is out of
// quota, not of credit: Factory's "You've reached your weekly
// standard usage limit (resets in …). Switch to Droid Core …" is
@@ -605,7 +605,7 @@ func failure(status int, body []byte) string {
// account out of credit it rested Droid Core with it (#1979)
return failQuota
case status == 402, creditWords.Match(body) && (status != 429 || brokeWords.Match(body)),
bytes.Contains(body, []byte("insufficient_quota")) && !minuteRate(body):
bodyHas(body, "insufficient_quota") && !minuteRate(body):
return failCredit
case status == 429 && resetsWhen.Match(body):
// out until the time it names, in whichever language it said so:
@@ -729,7 +729,7 @@ func grokBalanceOut(p provider.Provider, status int, body []byte) bool {
// plugin puts it (provider.ZCodeRestrictedHint, plugins#348). magpie's own
// words, which no vendor says, so they are read whoever answered.
func restrictedSaid(status int, body []byte) bool {
return status >= 400 && (bytes.Contains(body, []byte(provider.WBRestrictedHint)) || bytes.Contains(body, []byte(provider.ZCodeRestrictedHint)))
return status >= 400 && (bodyHas(body, provider.WBRestrictedHint) || bodyHas(body, provider.ZCodeRestrictedHint))
}
// restrictedRefused says p's vendor restricted the account: magpie's words
@@ -1449,7 +1449,7 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo
// account alike (mimi001234); none is set aside
return Rest{Why: why, Status: status, By: "off", Until: now}
}
if status == http.StatusBadGateway && bytes.Contains(body, []byte(openCodeBare)) {
if status == http.StatusBadGateway && bodyHas(body, openCodeBare) {
// OpenCode's bare 400 (openCodeBareRefusal, #3740) is about the
// request, not the key: the key's other requests go through, so
// none is set aside and the failure counts nowhere
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"cmp"
"context"
"encoding/json"
@@ -285,7 +284,7 @@ var searchHosts = map[provider.Protocol][]string{
func searchAsked(proto provider.Protocol, body []byte) bool {
// bytes, not string(body): each conversion copied the whole body, three
// times a request (a 200KB body: 640KB and 3ms)
if !bytes.Contains(body, []byte("web_search")) && !bytes.Contains(body, []byte("oogle_search")) && !bytes.Contains(body, []byte("googleSearch")) {
if !bodyHas(body, "web_search") && !bodyHas(body, "oogle_search") && !bodyHas(body, "googleSearch") {
return false
}
req, err := parse(proto, body)
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/yetone/magpie/internal/provider"
@@ -58,7 +57,7 @@ func includeTaken(host, v string) bool {
// with neither, goes as it came.
func forArkSearch(p provider.Provider, body []byte) []byte {
if p.Account != nil || provider.HostOf(p.Base(provider.Responses)) != arkHost ||
!bytes.Contains(body, []byte("web_search")) && !bytes.Contains(body, []byte(`"include"`)) {
!bodyHas(body, "web_search") && !bodyHas(body, `"include"`) {
return body
}
q, err := rawObject(body)
+2 -3
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"cmp"
"context"
"net/http"
@@ -37,7 +36,7 @@ type searchTally struct {
func (t *searchTally) see(proto provider.Protocol, b []byte) {
switch proto {
case provider.Anthropic:
if !bytes.Contains(b, []byte("server_tool_use")) {
if !bodyHas(b, "server_tool_use") {
return
}
v := gjson.ParseBytes(b)
@@ -49,7 +48,7 @@ func (t *searchTally) see(proto provider.Protocol, b []byte) {
t.said = max(t.said, int(u.Get("server_tool_use.web_search_requests").Int()))
}
case provider.Responses:
if !bytes.Contains(b, []byte("web_search_call")) {
if !bodyHas(b, "web_search_call") {
return
}
v := gjson.ParseBytes(b)
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"encoding/json"
"net/http"
"strings"
@@ -54,7 +53,7 @@ func requestSessionMetadata(h http.Header, body []byte) sessionMetadata {
// (#3394). A long body is checked and split once (topMember), so it is
// asked straight away: Codex sends client_metadata last, after the
// conversation, and looking for the word walked all of it each time.
if (len(body) >= validMemoMin || bytes.Contains(body, []byte("client_metadata"))) && metadataOf(body, &metadata) {
if (len(body) >= validMemoMin || bodyHas(body, "client_metadata")) && metadataOf(body, &metadata) {
if raw := metadata["x-codex-turn-metadata"]; len(raw) > 0 {
var text string
if json.Unmarshal(raw, &text) == nil {
+1 -1
View File
@@ -144,7 +144,7 @@ func speechUsage(tail []byte) (int, int) {
for i := len(lines) - 1; i >= 0; i-- {
l := bytes.TrimSpace(lines[i])
l = bytes.TrimSpace(bytes.TrimPrefix(l, []byte("data:")))
if !bytes.Contains(l, []byte(`"usage"`)) {
if !bodyHas(l, `"usage"`) {
continue
}
var a struct {
+1 -1
View File
@@ -33,7 +33,7 @@ const toolStrictRefused = "tools[].strict"
// its function tools (a Responses namespace's included), and whether any
// was.
func withoutToolStrict(proto provider.Protocol, body []byte) ([]byte, bool) {
if (proto != provider.Chat && proto != provider.Responses) || !bytes.Contains(body, []byte(`"strict"`)) {
if (proto != provider.Chat && proto != provider.Responses) || !bodyHas(body, `"strict"`) {
return body, false
}
dec := json.NewDecoder(bytes.NewReader(body))
+2 -2
View File
@@ -976,8 +976,8 @@ func (t *textCallTidy) line(line []byte) []byte {
// written into its text, for a request that offered names: one of
// textCallMarks' words is in it, however its JSON escapes the brackets.
func mayWriteCalls(b []byte, names map[string]bool) bool {
return names != nil && (bytes.Contains(b, []byte("tool_call")) || bytes.Contains(b, []byte("DSML")) ||
bytes.Contains(b, []byte("invoke name=")) || bytes.Contains(b, []byte("function_calls")))
return names != nil && (bodyHas(b, "tool_call") || bodyHas(b, "DSML") ||
bodyHas(b, "invoke name=") || bodyHas(b, "function_calls"))
}
// wholeTextCalls reads the calls written into the content of a whole Chat
+2 -3
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
@@ -99,7 +98,7 @@ func (s *Server) refuseThinking(owner string, keys []string) {
// refused before; an assistant message left with nothing goes too. A body
// with none of them goes byte for byte.
func (s *Server) withoutRefusedThinking(p provider.Provider, body []byte) []byte {
if !bytes.Contains(body, []byte(`thinking"`)) {
if !bodyHas(body, `thinking"`) {
return body
}
owner := thinkingOwner(p)
@@ -251,7 +250,7 @@ func (s *Server) withoutForeignThinking(p provider.Provider, body []byte) []byte
}
func withoutForeignThinking(p provider.Provider, body []byte) []byte {
if !bytes.Contains(body, []byte(`"signature"`)) && !thinkingTyped.Match(body) {
if !bodyHas(body, `"signature"`) && !thinkingTyped.Match(body) {
return body
}
model := modelOf(body)
+1 -1
View File
@@ -77,7 +77,7 @@ func (t *sigFieldTidy) lines(b []byte) []byte {
}
body := bytes.TrimRight(line, "\r\n")
data, ok := bytes.CutPrefix(body, []byte("data:"))
if !ok || !bytes.Contains(data, thinkingType) || !bytes.Contains(data, []byte("content_block_start")) {
if !ok || !bytes.Contains(data, thinkingType) || !bodyHas(data, "content_block_start") {
out = append(out, line...)
continue
}
+1 -2
View File
@@ -8,7 +8,6 @@ package gateway
// doesn't offer Ultrafast is asked for priority in its place.
import (
"bytes"
"context"
"encoding/json"
"strings"
@@ -89,7 +88,7 @@ func noteWireTier(ctx context.Context, to provider.Protocol, body []byte) {
// an Anthropic usage's service_tier. "" when it says none, which is never
// read as the tier that was asked.
func upstreamTier(b []byte) string {
if !bytes.Contains(b, []byte(`"service_tier"`)) {
if !bodyHas(b, `"service_tier"`) {
return ""
}
var v struct {
+3 -3
View File
@@ -22,7 +22,7 @@ import (
// no tool_search_call turns the whole request away (#1171 tcxp001, the
// compaction on Anyrouter; #1755 FivePink, Xiaomi MiMo).
func searchAsFunction(body []byte) ([]byte, bool) {
if !bytes.Contains(body, []byte(`"tool_search`)) {
if !bodyHas(body, `"tool_search`) {
return body, false
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -143,7 +143,7 @@ func (t *searchTidy) flush() []byte {
}
func searchLines(b []byte) []byte {
if !bytes.Contains(b, []byte(`"tool_search"`)) {
if !bodyHas(b, `"tool_search"`) {
return append([]byte(nil), b...)
}
var out []byte
@@ -160,7 +160,7 @@ func searchLines(b []byte) []byte {
}
func searchLine(line []byte) []byte {
if !bytes.Contains(line, []byte(`"tool_search"`)) {
if !bodyHas(line, `"tool_search"`) {
return line
}
body := bytes.TrimRight(line, "\r\n")
+3 -3
View File
@@ -130,7 +130,7 @@ func (f *firstToken) mark(d time.Duration, n int) {
// The end of a reply (Responses' response.completed, which says the whole
// reply again) carries none.
func flowContent(ev []byte) bool {
return bytes.Contains(ev, []byte("delta")) || bytes.Contains(ev, []byte(`"parts"`))
return bodyHas(ev, "delta") || bodyHas(ev, `"parts"`)
}
// flowMs is how long the content of a reply took to come from its decode's
@@ -195,8 +195,8 @@ func timingKind(ev []byte) (content, text, reasoning, hidden bool) {
}
// only deltas, a tool call's start and Gemini's parts carry any: the
// rest go by unread
if len(data) == 0 || !(bytes.Contains(data, []byte("delta")) || bytes.Contains(data, []byte(`"parts"`)) ||
bytes.Contains(data, []byte("content_block_start")) || bytes.Contains(data, []byte("output_item.added")) || bytes.Contains(data, []byte("encrypted_content"))) {
if len(data) == 0 || !(bodyHas(data, "delta") || bodyHas(data, `"parts"`) ||
bodyHas(data, "content_block_start") || bodyHas(data, "output_item.added") || bodyHas(data, "encrypted_content")) {
return false, false, false, hidden
}
var v struct {
+2 -2
View File
@@ -237,8 +237,8 @@ func (s *toolScan) add(p []byte) {
break
}
}
s.ended = s.ended || bytes.Contains(b, []byte("data: [DONE]")) || bytes.Contains(b, []byte("data:[DONE]")) ||
bytes.Contains(b, []byte("event: message_stop")) || bytes.Contains(b, []byte("event:message_stop"))
s.ended = s.ended || bodyHas(b, "data: [DONE]") || bodyHas(b, "data:[DONE]") ||
bodyHas(b, "event: message_stop") || bodyHas(b, "event:message_stop")
}
keep := min(len(b), 64) // longer than any value with its colon and spaces
s.tail = append(s.tail[:0:0], b[len(b)-keep:]...)
+2 -2
View File
@@ -21,7 +21,7 @@ import (
// choice's content is the model's, and providerAttempts inside routing
// lists every provider tried, not the one that answered.
func upstreamOf(b []byte) string {
if !bytes.Contains(b, []byte(`"provider"`)) && !bytes.Contains(b, []byte(`"finalProvider"`)) {
if !bodyHas(b, `"provider"`) && !bodyHas(b, `"finalProvider"`) {
return ""
}
type routed struct {
@@ -71,7 +71,7 @@ func upstreamOf(b []byte) string {
// what the upstream said of it — a relay's "end_turn" after a few words,
// or nothing at all (蓝猫 on Discord). "" when this one says none.
func upstreamStop(b []byte) string {
if !bytes.Contains(b, []byte(`stop_reason"`)) && !bytes.Contains(b, []byte(`finish_reason"`)) && !bytes.Contains(b, []byte(`"response.`)) {
if !bodyHas(b, `stop_reason"`) && !bodyHas(b, `finish_reason"`) && !bodyHas(b, `"response.`) {
return ""
}
var v struct {
+1 -2
View File
@@ -1,7 +1,6 @@
package gateway
import (
"bytes"
"cmp"
"fmt"
"mime"
@@ -99,7 +98,7 @@ func currentVideo(r *Request) bool {
// hasCurrentVideo is currentVideo of a body as the client sent it. Most
// bodies name no video at all and are not parsed.
func hasCurrentVideo(from provider.Protocol, body []byte) bool {
if !bytes.Contains(body, []byte("video")) {
if !bodyHas(body, "video") {
return false
}
req, err := parse(from, body)
+2 -2
View File
@@ -38,8 +38,8 @@ var zhipuImageRefusal = lazyre.New(`必须传入file_id、file_url、file_data
// the base64 of a RIFF file's head, wherever its base64 starts (a webp
// sent under another type is one too, as a HEIC sent as image/jpeg is).
func mayHoldWebP(body []byte) bool {
return bytes.Contains(body, []byte("image/webp")) || bytes.Contains(body, []byte(`image\/webp`)) ||
bytes.Contains(body, []byte("UklG"))
return bodyHas(body, "image/webp") || bodyHas(body, `image\/webp`) ||
bodyHas(body, "UklG")
}
// webpAsJPEG is the body with each webp in it written again as JPEG (PNG
+3 -3
View File
@@ -50,7 +50,7 @@ func xaiBody(p provider.Provider, proto provider.Protocol, body []byte) []byte {
// withoutNullReasoningContent is a Responses body with the null content of
// a reasoning item gone (#3392).
func withoutNullReasoningContent(body []byte) []byte {
if !bytes.Contains(body, []byte(`"reasoning"`)) || !bytes.Contains(body, []byte(`"content"`)) {
if !bodyHas(body, `"reasoning"`) || !bodyHas(body, `"content"`) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -85,7 +85,7 @@ func withoutNullReasoningContent(body []byte) []byte {
// folded into the top-level system, its text and blocks as they came
// (#3392).
func systemTurnsFolded(body []byte) []byte {
if !bytes.Contains(body, []byte(`"messages"`)) || !bytes.Contains(body, []byte(`"system"`)) {
if !bodyHas(body, `"messages"`) || !bodyHas(body, `"system"`) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))
@@ -153,7 +153,7 @@ func systemTurnsFolded(body []byte) []byte {
// input_schema (Anthropic), parameters (Responses) and function's
// parameters (chat).
func withoutNullToolRequired(body []byte) []byte {
if !bytes.Contains(body, []byte(`"tools"`)) || !bytes.Contains(body, []byte(`"required"`)) {
if !bodyHas(body, `"tools"`) || !bodyHas(body, `"required"`) {
return body
}
dec := json.NewDecoder(bytes.NewReader(body))