diff --git a/internal/gateway/anthropic_shapes.go b/internal/gateway/anthropic_shapes.go index 93aad66bd..042399e67 100644 --- a/internal/gateway/anthropic_shapes.go +++ b/internal/gateway/anthropic_shapes.go @@ -1,7 +1,6 @@ package gateway import ( - "bytes" "encoding/json" "strings" @@ -373,7 +372,7 @@ func hasDeferredTools(body []byte) bool { getIn(body, "messages").ForEach(func(_, m gjson.Result) bool { m.Get("content").ForEach(func(_, b gjson.Result) bool { found = deferredBlock(b.Get("type").String()) || - b.Get("type").String() == "tool_result" && bytes.Contains([]byte(b.Get("content").Raw), []byte(`"tool_definition"`)) + b.Get("type").String() == "tool_result" && strings.Contains(b.Get("content").Raw, `"tool_definition"`) return !found }) return !found @@ -422,7 +421,7 @@ func withoutDeferredTools(body []byte) []byte { have[name.String()] = true } } - if b.Get("type").String() == "tool_result" && bytes.Contains([]byte(b.Get("content").Raw), []byte(`"tool_definition"`)) { + if b.Get("type").String() == "tool_result" && strings.Contains(b.Get("content").Raw, `"tool_definition"`) { // a ToolSearch answer carrying the definition itself: the // definition joins the tools and the block goes as the // reference the result takes (#5404) diff --git a/internal/gateway/body_has.go b/internal/gateway/body_has.go index cd082d26e..9dc35c499 100644 --- a/internal/gateway/body_has.go +++ b/internal/gateway/body_has.go @@ -78,3 +78,13 @@ func rarestByte(sep string) int { } return k } + +// bodyHasBytes is bodyHas for a needle kept as bytes. +func bodyHasBytes(b, sep []byte) bool { return bodyIndex(b, bytesStr(sep)) >= 0 } + +// bodyIndexBytes is bodyIndex for a needle kept as bytes. +func bodyIndexBytes(b, sep []byte) int { return bodyIndex(b, bytesStr(sep)) } + +// bytesStr reads b as a string without copying it; b must not change +// while the string is in use. +func bytesStr(b []byte) string { return unsafe.String(unsafe.SliceData(b), len(b)) } diff --git a/internal/gateway/chat_text_parts.go b/internal/gateway/chat_text_parts.go index 912ed56ad..f833574a2 100644 --- a/internal/gateway/chat_text_parts.go +++ b/internal/gateway/chat_text_parts.go @@ -1,7 +1,6 @@ package gateway import ( - "bytes" "strings" "github.com/tidwall/gjson" @@ -25,7 +24,7 @@ import ( // other byte of the body stays as sent, and a body with no such list // comes back as it was. func textPartsAsString(body []byte) []byte { - if !bytes.Contains(body, contentParts) && !bytes.Contains(body, contentPartsSpace) { + if !bodyHasBytes(body, contentParts) && !bodyHasBytes(body, contentPartsSpace) { return body } msgs := gjson.GetBytes(body, "messages") diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go index cd6f2766f..7b4a15c3b 100644 --- a/internal/gateway/chattidy.go +++ b/internal/gateway/chattidy.go @@ -155,20 +155,20 @@ func (t *chatTidy) lines(b []byte) []byte { // needsTidy reports whether a line carries any of the shapes chatTidy // mends. func needsTidy(line []byte) bool { - return bytes.Contains(line, emptyReasoning) || - bytes.Contains(line, emptyFinishReason) || - bytes.Contains(line, emptyToolName) || - bytes.Contains(line, emptyToolCalls) || - bytes.Contains(line, contentParts) || - bytes.Contains(line, contentPartsSpace) || - bytes.Contains(line, toolCallsField) || - bytes.Contains(line, functionCallField) + return bodyHasBytes(line, emptyReasoning) || + bodyHasBytes(line, emptyFinishReason) || + bodyHasBytes(line, emptyToolName) || + bodyHasBytes(line, emptyToolCalls) || + bodyHasBytes(line, contentParts) || + bodyHasBytes(line, contentPartsSpace) || + bodyHasBytes(line, toolCallsField) || + bodyHasBytes(line, functionCallField) } // needs is needsTidy, a finish_reason once a choice made a call, and a // usage that may tell its cache in names OpenAI's clients don't read. func (t *chatTidy) needs(b []byte) bool { - return needsTidy(b) || len(t.called) > 0 && bytes.Contains(b, finishReasonField) || mayMendUsage(b) + return needsTidy(b) || len(t.called) > 0 && bodyHasBytes(b, finishReasonField) || mayMendUsage(b) } var ( @@ -185,11 +185,11 @@ var ( // prompt_tokens_details' own. A usage in OpenAI's names alone, every // OpenAI reply, is left unread. func mayMendUsage(b []byte) bool { - if !bytes.Contains(b, usageField) { + if !bodyHasBytes(b, usageField) { return false } for _, f := range otherCacheFields { - if bytes.Contains(b, f) { + if bodyHasBytes(b, f) { return true } } @@ -721,8 +721,8 @@ func (t *chatWhole) write(b []byte) []byte { func (t *chatWhole) flush() []byte { b := t.buf t.buf = nil - parts := bytes.Contains(b, contentParts) || bytes.Contains(b, contentPartsSpace) - if !parts && !mayWriteCalls(b, t.names) && !bytes.Contains(b, toolCallsField) && !mayMendUsage(b) { + parts := bodyHasBytes(b, contentParts) || bodyHasBytes(b, contentPartsSpace) + if !parts && !mayWriteCalls(b, t.names) && !bodyHasBytes(b, toolCallsField) && !mayMendUsage(b) { return b } var reply map[string]json.RawMessage @@ -1032,7 +1032,7 @@ func withoutMessageReasoning(body []byte, fields []string) []byte { func editMessages(body []byte, fields []string, edit func(m map[string]json.RawMessage) bool) []byte { has := false for _, f := range fields { - has = has || bytes.Contains(body, []byte(`"`+f+`"`)) + has = has || bodyHas(body, `"`+f+`"`) } if !has { return body diff --git a/internal/gateway/claude_cache.go b/internal/gateway/claude_cache.go index cdca12341..844cf7cdb 100644 --- a/internal/gateway/claude_cache.go +++ b/internal/gateway/claude_cache.go @@ -1,7 +1,6 @@ package gateway import ( - "bytes" "encoding/json" "fmt" "hash" @@ -177,7 +176,7 @@ func askedCacheTTL(a *aRequest) string { for _, t := range a.Tools { take(t.CacheControl) } - if bytes.Contains(a.System, cacheControlField) { + if bodyHasBytes(a.System, cacheControlField) { var system []struct { CacheControl json.RawMessage `json:"cache_control"` } @@ -191,7 +190,7 @@ func askedCacheTTL(a *aRequest) string { if ttl == "1h" { break } - if !bytes.Contains(m.Content, cacheControlField) { + if !bodyHasBytes(m.Content, cacheControlField) { continue } var blocks []struct { diff --git a/internal/gateway/claude_signin.go b/internal/gateway/claude_signin.go index 0ec365d22..4c3212645 100644 --- a/internal/gateway/claude_signin.go +++ b/internal/gateway/claude_signin.go @@ -101,7 +101,7 @@ func (w *signInWriter) Write(b []byte) (int, error) { w.wrote = true _, err := w.ResponseWriter.Write(body) return n, err - case bytes.HasPrefix(b, []byte("event: error\n")) && bytes.Contains(bytes.ToLower(b), []byte("x-api-key")): + case bytes.HasPrefix(b, []byte("event: error\n")) && bodyHas(bytes.ToLower(b), "x-api-key"): // a stream's error, after its 200 went b = xAPIKey.ReplaceAll(b, []byte("API key")) } diff --git a/internal/gateway/claude_subscription.go b/internal/gateway/claude_subscription.go index eada8724c..503cd6d78 100644 --- a/internal/gateway/claude_subscription.go +++ b/internal/gateway/claude_subscription.go @@ -3097,7 +3097,7 @@ func cutAfterReply(b []byte, msg string) int { } line := b[at : at+nl] at += nl + 1 - if !bytes.Contains(line, mark) { + if !bodyHasBytes(line, mark) { continue } var l struct { @@ -3153,7 +3153,7 @@ func cutBeforeCalls(b []byte, ids []string) int { start := at at += nl + 1 for _, id := range ids { - if bytes.Contains(line, []byte(`"id":"`+id+`"`)) { + if bodyHas(line, `"id":"`+id+`"`) { return start } } @@ -3206,7 +3206,7 @@ func cutAfter(b, mark []byte, uuid string) int { } line := b[at : at+nl] at += nl + 1 - if !bytes.Contains(line, mark) { + if !bodyHasBytes(line, mark) { continue } var l struct { diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 55ae0c471..83256f1ac 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -1925,7 +1925,7 @@ func withoutUnreadable(body, msg []byte) ([]byte, bool) { // (passthrough_refused.go) return withoutPassthrough(body, f) } - if !foreignReasoning.Match(msg) && !bytes.Contains(bytes.ToLower(msg), []byte("not found")) { + if !foreignReasoning.Match(msg) && !bodyHas(bytes.ToLower(msg), "not found") { return nil, false } if m := unreadableItem.FindSubmatch(msg); m != nil { @@ -3539,7 +3539,7 @@ func forVendor(p provider.Provider, body []byte, compaction bool) []byte { if compaction { body = developerItemsAsSystem(body) } - if !slices.ContainsFunc(openaiOnly, func(k []byte) bool { return bytes.Contains(body, k) }) || !forVendorChanges(body) { + if !slices.ContainsFunc(openaiOnly, func(k []byte) bool { return bodyHasBytes(body, k) }) || !forVendorChanges(body) { return body } q, err := rawObject(body) @@ -3661,7 +3661,7 @@ func forVendorChanges(body []byte) bool { } if inc, found, ok := topMember(body, "include"); !ok { return false - } else if found && bytes.Contains(inc, []byte(`"`+outputReplay+`"`)) { + } else if found && bodyHas(inc, `"`+outputReplay+`"`) { return true } return anyInputItem(body, func(it []byte) bool { @@ -4104,7 +4104,7 @@ func summaryTooLarge(rec *recorder) bool { // 'rs_…' not found", #1008), which a relay in front of them passes on. func itemNotFound(rec *recorder) bool { b := rec.body.Bytes() - return rec.status == http.StatusBadRequest && unreadableItem.Match(b) && bytes.Contains(bytes.ToLower(b), []byte("not found")) + return rec.status == http.StatusBadRequest && unreadableItem.Match(b) && bodyHas(bytes.ToLower(b), "not found") } // inputKindRefused is a summary request turned away for a kind of item in diff --git a/internal/gateway/effort_update.go b/internal/gateway/effort_update.go index 9c1d6195a..fda8681db 100644 --- a/internal/gateway/effort_update.go +++ b/internal/gateway/effort_update.go @@ -22,7 +22,6 @@ package gateway // thread's state costs one cache miss, as before. import ( - "bytes" "crypto/sha256" "encoding/json" "os" @@ -119,7 +118,7 @@ func withEffortUpdates(conv, who, model, effort string, body []byte) ([]byte, bo _, prev := q["previous_response_id"] _, managed := q["context_management"] if prev || managed || string(q["truncation"]) == `"auto"` || effort == "" || effort == "none" || - bytes.Contains(q["input"], []byte(`"configuration_update"`)) { + bodyHas(q["input"], `"configuration_update"`) { delete(effortThreads.m, k) return nil, false } diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index e5fdd22d6..baf108f46 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -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 bodyHas(body, "NOT_FOUND") || bytes.Contains(bytes.ToLower(body), []byte("not found")) + return bodyHas(body, "NOT_FOUND") || bodyHas(bytes.ToLower(body), "not found") } // retiredWords are how a vendor says the model is retired, though its @@ -3034,7 +3034,7 @@ func (h *holdWriter) see(b []byte) { buf = append([]byte{'\n'}, b...) // the stream starts a line } for _, m := range streamEnds { - if bytes.Contains(buf, m) { + if bodyHasBytes(buf, m) { h.ended = true return } @@ -3501,7 +3501,7 @@ func mayCall(b []byte) bool { // a reply that has begun goes through this. func mayRefuse(ev []byte) bool { for _, w := range refusalSays { - if bytes.Contains(ev, w) { + if bodyHasBytes(ev, w) { return true } } diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 8976586cc..5a2481a31 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -8318,7 +8318,7 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to r.MaxTokens, req, filledOutput = 0, &r, false continue } - if req.LoadedInPlace && refusesField(res.StatusCode, b, additionalToolsItem) && bytes.Contains(body, []byte(`"`+additionalToolsItem+`"`)) { + if req.LoadedInPlace && refusesField(res.StatusCode, b, additionalToolsItem) && bodyHas(body, `"`+additionalToolsItem+`"`) { // an upstream that turns the item away is asked again with the // loaded tools among the others, and not sent it again: the // prompt's prefix changes from here, as before #2660, and the @@ -8991,7 +8991,7 @@ func refusedInMessages(status int, msg, body []byte) []string { return nil } if m := fieldAtPosition.FindSubmatch(msg); m != nil { - if f := string(m[1]); bytes.Contains(body, []byte(`"`+f+`"`)) { + if f := string(m[1]); bodyHas(body, `"`+f+`"`) { return []string{f} } } @@ -9014,7 +9014,7 @@ func refusedInMessages(status int, msg, body []byte) []string { } f, _ := loc[len(loc)-1].(string) if loc[0] == "messages" && slices.Contains(messageReasoning, f) && !slices.Contains(out, f) && - bytes.Contains(body, []byte(`"`+f+`"`)) { + bodyHas(body, `"`+f+`"`) { out = append(out, f) } return @@ -9114,7 +9114,7 @@ var cacheControlField = []byte("cache_control") // other request is one bytes.Contains away from this, a scan next to the // parse of the same body. func parseTranslated(from, to provider.Protocol, body []byte, advised bool) (*Request, error) { - if from == provider.Anthropic && to == provider.Anthropic && bytes.Contains(body, cacheControlField) { + if from == provider.Anthropic && to == provider.Anthropic && bodyHasBytes(body, cacheControlField) { if req, err := readAdvised(body, true, false, advised); err == nil { return afterParse(from, body, req) } @@ -10464,7 +10464,7 @@ func offAsNone(from provider.Protocol, body []byte) []byte { func saysOff(body []byte) bool { key := []byte(`effort"`) for rest := body; ; { - i := bytes.Index(rest, key) + i := bodyIndexBytes(rest, key) if i < 0 { return false } @@ -10739,7 +10739,7 @@ func asCompletionTokens(body []byte) []byte { func withoutFields(body []byte, fields ...string) []byte { found := false for _, f := range fields { - found = found || bytes.Contains(body, []byte(`"`+f+`"`)) + found = found || bodyHas(body, `"`+f+`"`) } if !found { return body diff --git a/internal/gateway/gemini_signature.go b/internal/gateway/gemini_signature.go index f91f9be39..0d19c517d 100644 --- a/internal/gateway/gemini_signature.go +++ b/internal/gateway/gemini_signature.go @@ -327,7 +327,7 @@ func (t *sigTidy) flush() []byte { } func (t *sigTidy) lines(b []byte) []byte { - if !bytes.Contains(b, thoughtSignatureField) { + if !bodyHasBytes(b, thoughtSignatureField) { return append([]byte(nil), b...) } var out []byte @@ -340,7 +340,7 @@ func (t *sigTidy) lines(b []byte) []byte { } body := bytes.TrimRight(line, "\r\n") data, ok := bytes.CutPrefix(body, []byte("data:")) - if !ok || !bytes.Contains(data, thoughtSignatureField) { + if !ok || !bodyHasBytes(data, thoughtSignatureField) { out = append(out, line...) continue } @@ -358,7 +358,7 @@ func (t *sigTidy) lines(b []byte) []byte { // carrying their signatures, noted as provider by's, and whether there // was one. func signReply(data []byte, by string) ([]byte, bool) { - if !bytes.Contains(data, thoughtSignatureField) { + if !bodyHasBytes(data, thoughtSignatureField) { return nil, false } var reply map[string]json.RawMessage @@ -499,7 +499,7 @@ var geminiSignatureField = []byte(`"thoughtSignature"`) // or a whole one (an object, or streamGenerateContent's array of them), // as provider by's. func noteGeminiSigners(b []byte, by string) { - if !bytes.Contains(b, geminiSignatureField) { + if !bodyHasBytes(b, geminiSignatureField) { return } note := func(r gjson.Result) { @@ -537,7 +537,7 @@ func noteGeminiSigners(b []byte, by string) { if d, ok := bytes.CutPrefix(line, []byte("data:")); ok { line = bytes.TrimSpace(d) } - if !bytes.Contains(line, geminiSignatureField) { + if !bodyHasBytes(line, geminiSignatureField) { continue } all(gjson.ParseBytes(line)) @@ -549,7 +549,7 @@ func noteGeminiSigners(b []byte, by string) { // nor any when keep is false: a function call that had one goes waved // through (skipSignature), a text without. func geminiBodySignatures(body []byte, by string, keep bool) []byte { - if !bytes.Contains(body, geminiSignatureField) { + if !bodyHasBytes(body, geminiSignatureField) { return body } var q map[string]json.RawMessage diff --git a/internal/gateway/grok_schema.go b/internal/gateway/grok_schema.go index 47e8e8f23..098d0d21e 100644 --- a/internal/gateway/grok_schema.go +++ b/internal/gateway/grok_schema.go @@ -23,10 +23,12 @@ import ( // as it goes upstream, or xAI's own API; every other model's tools go as // they came. func grokToolPatterns(p provider.Provider, to provider.Protocol, body []byte) []byte { - if p.VendorHost() != "api.x.ai" && !grokModel(gjson.GetBytes(body, "model").String()) { + // the cheap look first: most requests hold no pattern, and finding the + // model walks the whole body when it comes after the conversation + if !bodyHas(body, `"pattern"`) { return body } - if !bodyHas(body, `"pattern"`) { + if p.VendorHost() != "api.x.ai" && !grokModel(gjson.GetBytes(body, "model").String()) { return body } return toolPatterns(body, ecmaClassForRust) diff --git a/internal/gateway/history.go b/internal/gateway/history.go index 251adf539..d0ae08f87 100644 --- a/internal/gateway/history.go +++ b/internal/gateway/history.go @@ -854,7 +854,7 @@ func HistoryRoute(id int64, day time.Time) (Route, bool) { path := d.path var found Route readDay(path, func(line []byte) bool { - if !bytes.Contains(line, needle) { + if !bodyHasBytes(line, needle) { return true } if json.Unmarshal(line, &found) != nil || found.ID != id { diff --git a/internal/gateway/image_tool.go b/internal/gateway/image_tool.go index 63b269e46..19b0b58e1 100644 --- a/internal/gateway/image_tool.go +++ b/internal/gateway/image_tool.go @@ -31,7 +31,7 @@ func mayDropImageTool(p provider.Provider) bool { // withoutImageTool is a Responses body without Codex's image tool among its // tools, and whether it had it. func withoutImageTool(body []byte) ([]byte, bool) { - if !bytes.Contains(body, []byte(`"`+imageNamespace+`"`)) { + if !bodyHas(body, `"`+imageNamespace+`"`) { return body, false } dec := json.NewDecoder(bytes.NewReader(body)) diff --git a/internal/gateway/member.go b/internal/gateway/member.go index d137a4c1e..65bde7714 100644 --- a/internal/gateway/member.go +++ b/internal/gateway/member.go @@ -278,7 +278,7 @@ var modelKey = []byte(`"model`) // memberLines is a run of an event stream's lines with name for the model // each line's data names, the same slice when none is changed. func memberLines(b []byte, name string, paths []string) []byte { - if name == "" || !bytes.Contains(b, modelKey) { + if name == "" || !bodyHasBytes(b, modelKey) { return b } var out []byte @@ -291,7 +291,7 @@ func memberLines(b []byte, name string, paths []string) []byte { } line := b[i:j] named := line - if bytes.Contains(line, modelKey) { + if bodyHasBytes(line, modelKey) { named = memberLineAt(line, name, paths) } if out == nil && !bytes.Equal(named, line) { @@ -366,7 +366,7 @@ func memberPathsOf(from provider.Protocol) []string { // one of paths. func memberNamedAt(b []byte, id string, paths []string) []byte { // a body cut short goes on as it came: nothing is made up in it - if id == "" || !bytes.Contains(b, modelKey) || !json.Valid(b) { + if id == "" || !bodyHasBytes(b, modelKey) || !json.Valid(b) { return b } name, _ := json.Marshal(id) diff --git a/internal/gateway/refusal_handover.go b/internal/gateway/refusal_handover.go index 14e7f5e52..33442f1c5 100644 --- a/internal/gateway/refusal_handover.go +++ b/internal/gateway/refusal_handover.go @@ -372,7 +372,7 @@ func (s *splicedWriter) rewrite(ev []byte) []byte { for _, e := range edits { nd = append(nd[:e.at:e.at], append([]byte(e.to), nd[e.at+e.n:]...)...) } - at := bytes.Index(ev, data) + at := bodyIndexBytes(ev, data) if at < 0 { return ev } diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 3439ff571..2b8564d84 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -672,7 +672,7 @@ func dashScopeRate(p provider.Provider, status int, body []byte) bool { return false } w := wordsOf(body) - if bytes.Contains(bytes.ToLower(w), []byte("free allocated quota")) || longWords.Match(urlWords.ReplaceAll(w, nil)) { + if bodyHas(bytes.ToLower(w), "free allocated quota") || longWords.Match(urlWords.ReplaceAll(w, nil)) { return false } return dashScopeTokenRate.Match(w) @@ -1973,7 +1973,7 @@ func namesModel(words []byte, name string) bool { return b >= 'a' && b <= 'z' || b >= '0' && b <= '9' || b == '-' || b == '_' || b == '.' } for from := 0; ; { - i := bytes.Index(words[from:], n) + i := bodyIndexBytes(words[from:], n) if i < 0 { return false } diff --git a/internal/gateway/thinking_signature.go b/internal/gateway/thinking_signature.go index 54c24a053..cb4eede51 100644 --- a/internal/gateway/thinking_signature.go +++ b/internal/gateway/thinking_signature.go @@ -64,7 +64,7 @@ func (t *sigFieldTidy) flush() []byte { } func (t *sigFieldTidy) lines(b []byte) []byte { - if !bytes.Contains(b, thinkingType) { + if !bodyHasBytes(b, thinkingType) { return append([]byte(nil), b...) } var out []byte @@ -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) || !bodyHas(data, "content_block_start") { + if !ok || !bodyHasBytes(data, thinkingType) || !bodyHas(data, "content_block_start") { out = append(out, line...) continue } @@ -114,7 +114,7 @@ func signedStart(data []byte) ([]byte, bool) { // signedContent is a whole Messages reply whose thinking blocks without a // signature are given an empty one, and whether it had such a block. func signedContent(b []byte) ([]byte, bool) { - if !bytes.Contains(b, thinkingType) { + if !bodyHasBytes(b, thinkingType) { return nil, false } var reply map[string]json.RawMessage @@ -147,7 +147,7 @@ func signedContent(b []byte) ([]byte, bool) { // empty one, and whether it was one. A signature that isn't a string (a // null) is none too. func unsignedThinking(raw json.RawMessage) (json.RawMessage, bool) { - if !bytes.Contains(raw, thinkingType) { + if !bodyHasBytes(raw, thinkingType) { return nil, false } var block map[string]json.RawMessage diff --git a/internal/gateway/tool_args_cr.go b/internal/gateway/tool_args_cr.go index a741d86a6..2b62b0f6f 100644 --- a/internal/gateway/tool_args_cr.go +++ b/internal/gateway/tool_args_cr.go @@ -297,7 +297,7 @@ func (t *crTidy) cut() bool { // would not survive being said from where it lies. func (t *crTidy) lines(b []byte, copy bool) []byte { t.looked += len(b) - if !bytes.Contains(b, crSeq) && !t.cut() { + if !bodyHasBytes(b, crSeq) && !t.cut() { if copy { return append([]byte(nil), b...) } @@ -338,7 +338,7 @@ func (t *crTidy) lines(b []byte, copy bool) []byte { // to answer, goes as it came. func (t *crTidy) line(l []byte) ([]byte, bool) { t.looked += len(l) - if !bytes.Contains(l, crSeq) && !t.cut() { + if !bodyHasBytes(l, crSeq) && !t.cut() { return l, false } body := bytes.TrimRight(l, "\r\n") diff --git a/internal/gateway/tool_use_ids.go b/internal/gateway/tool_use_ids.go index 260c7c5b6..02f4cdb3d 100644 --- a/internal/gateway/tool_use_ids.go +++ b/internal/gateway/tool_use_ids.go @@ -53,7 +53,7 @@ func unsaltCallID(id string) (string, bool) { // turns: what the client holds, and would drop a reply's block over saying // again (#4910). func clientToolUseIDs(body []byte) map[string]bool { - if !bytes.Contains(body, toolUseType) { + if !bodyHasBytes(body, toolUseType) { return nil } var q struct { @@ -90,7 +90,7 @@ func clientToolUseIDs(body []byte) map[string]bool { // upstream that made the call gets its own again, on the call and on the // result answering it. The rest goes as it came. func saltedCallIDsBack(body []byte) []byte { - if !bytes.Contains(body, []byte(`"`+anthropicIDMark)) { + if !bodyHas(body, `"`+anthropicIDMark) { return body } var reply map[string]json.RawMessage @@ -181,7 +181,7 @@ func (t *toolUseIDs) flush() []byte { func (t *toolUseIDs) event(ev []byte) []byte { data := eventData(ev) - if len(data) == 0 || !bytes.Contains(data, toolUseType) || !gjson.ValidBytes(data) { + if len(data) == 0 || !bodyHasBytes(data, toolUseType) || !gjson.ValidBytes(data) { return ev } e := gjson.ParseBytes(data) @@ -225,7 +225,7 @@ func (t *toolUseIDs) event(ev []byte) []byte { // client already holds, or an earlier block of the reply said, go out // salted. func (t *toolUseIDs) whole(b []byte) []byte { - if !bytes.Contains(b, toolUseType) { + if !bodyHasBytes(b, toolUseType) { return b } var reply map[string]json.RawMessage diff --git a/internal/gateway/turndone.go b/internal/gateway/turndone.go index a8726ad23..d0f7c3b57 100644 --- a/internal/gateway/turndone.go +++ b/internal/gateway/turndone.go @@ -248,7 +248,7 @@ func (s *toolScan) add(p []byte) { // m's does, with any spaces between. func marked(b []byte, m replyMark) bool { for i := 0; ; { - j := bytes.Index(b[i:], m.key) + j := bodyIndexBytes(b[i:], m.key) if j < 0 { return false } @@ -266,7 +266,7 @@ func marked(b []byte, m replyMark) bool { func toolIn(b []byte) bool { for _, v := range toolValues { for i := 0; ; { - j := bytes.Index(b[i:], v) + j := bodyIndexBytes(b[i:], v) if j < 0 { break } @@ -278,7 +278,7 @@ func toolIn(b []byte) bool { } } for i := 0; ; { - j := bytes.Index(b[i:], geminiCall) + j := bodyIndexBytes(b[i:], geminiCall) if j < 0 { return false }