mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
- Skip both cache_control walks with a byte-level precheck when the body
has at most 4 cache_control keys, no thinking block and no 1h TTL; skip
the block-limit walk when only 1h is present. Bodies containing \u
escapes always take the original path.
- Replace gjson Array() materialization with Get("0")/ForEach in the
beta, toolset, tool-rewrite, web-search and system-preview helpers.
- Build the Claude Code mimic debug line lazily; it is only read on
credential-scope errors.
- Compute the billing-header fingerprint once instead of per block.
Differential tests copy the previous implementations verbatim and
compare byte for byte across edge cases and 3000 randomized bodies.
Batching TTL rewrites with sjson ReplaceInPlace was rejected because it
resolves duplicate keys differently.
Common ~32KB Claude Code request: enforceCacheControlLimit 100us/21
allocs -> 21.6us/0 allocs; helper set 47.6us/103KB -> 37.9us/69KB;
debug line 9.1us/53 allocs -> ~0.
171 lines
4.3 KiB
Go
171 lines
4.3 KiB
Go
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"github.com/Wei-Shaw/sub2api/internal/pkg/claude"
|
|
"github.com/tidwall/gjson"
|
|
"github.com/tidwall/sjson"
|
|
)
|
|
|
|
// Verbatim legacy copies used only by equivalence tests.
|
|
|
|
func legacyBuildToolNameRewriteFromBody(body []byte) *ToolNameRewrite {
|
|
tools := gjson.GetBytes(body, "tools")
|
|
if !tools.IsArray() {
|
|
return nil
|
|
}
|
|
|
|
mimicableNames := make([]string, 0)
|
|
toolsArr := tools.Array()
|
|
for _, t := range toolsArr {
|
|
if !shouldMimicToolName(t.Get("type").String()) {
|
|
continue
|
|
}
|
|
name := t.Get("name").String()
|
|
if name == "" {
|
|
continue
|
|
}
|
|
mimicableNames = append(mimicableNames, name)
|
|
}
|
|
|
|
dynamic := buildDynamicToolMap(mimicableNames)
|
|
|
|
rw := &ToolNameRewrite{
|
|
Forward: make(map[string]string),
|
|
Reverse: make(map[string]string),
|
|
}
|
|
for _, name := range mimicableNames {
|
|
fake := sanitizeToolName(name, dynamic)
|
|
if fake == name {
|
|
continue
|
|
}
|
|
rw.Forward[name] = fake
|
|
rw.Reverse[fake] = name
|
|
}
|
|
if len(rw.Forward) == 0 {
|
|
return nil
|
|
}
|
|
|
|
rw.ReverseOrdered = make([][2]string, 0, len(rw.Reverse))
|
|
for fake, real := range rw.Reverse {
|
|
rw.ReverseOrdered = append(rw.ReverseOrdered, [2]string{fake, real})
|
|
}
|
|
sort.SliceStable(rw.ReverseOrdered, func(i, j int) bool {
|
|
return len(rw.ReverseOrdered[i][0]) > len(rw.ReverseOrdered[j][0])
|
|
})
|
|
|
|
return rw
|
|
}
|
|
|
|
func legacyApplyToolsLastCacheBreakpoint(body []byte) []byte {
|
|
body = legacyStripDeferredToolCacheControl(body)
|
|
tools := gjson.GetBytes(body, "tools")
|
|
if !tools.IsArray() {
|
|
return body
|
|
}
|
|
arr := tools.Array()
|
|
if len(arr) == 0 {
|
|
return body
|
|
}
|
|
lastIdx := -1
|
|
for idx, tool := range arr {
|
|
if isDeferredLoadingTool(tool) {
|
|
continue
|
|
}
|
|
lastIdx = idx
|
|
}
|
|
if lastIdx == -1 {
|
|
return body
|
|
}
|
|
|
|
existingCC := arr[lastIdx].Get("cache_control")
|
|
|
|
if existingCC.Exists() && existingCC.Get("ttl").String() != "" {
|
|
return body
|
|
}
|
|
|
|
if existingCC.Exists() {
|
|
if next, err := sjson.SetBytes(body, fmt.Sprintf("tools.%d.cache_control.ttl", lastIdx), claude.DefaultCacheControlTTL); err == nil {
|
|
body = next
|
|
}
|
|
return body
|
|
}
|
|
|
|
raw := fmt.Sprintf(`{"type":"ephemeral","ttl":%q}`, claude.DefaultCacheControlTTL)
|
|
if next, err := sjson.SetRawBytes(body, fmt.Sprintf("tools.%d.cache_control", lastIdx), []byte(raw)); err == nil {
|
|
body = next
|
|
}
|
|
return body
|
|
}
|
|
|
|
func legacyStripDeferredToolCacheControl(body []byte) []byte {
|
|
tools := gjson.GetBytes(body, "tools")
|
|
if !tools.IsArray() {
|
|
return body
|
|
}
|
|
for idx, tool := range tools.Array() {
|
|
if !isDeferredLoadingTool(tool) || !tool.Get("cache_control").Exists() {
|
|
continue
|
|
}
|
|
if next, err := sjson.DeleteBytes(body, fmt.Sprintf("tools.%d.cache_control", idx)); err == nil {
|
|
body = next
|
|
}
|
|
}
|
|
return body
|
|
}
|
|
|
|
func legacyFilterSonnet55ToolsetBeta(header string, body []byte, modelID string) string {
|
|
if at := strings.IndexByte(modelID, '@'); at >= 0 {
|
|
modelID = modelID[:at] // Vertex's dated model ID
|
|
}
|
|
if !claude.IsSonnet55(modelID) && !claude.IsHaiku55(modelID) {
|
|
return header
|
|
}
|
|
for _, tool := range gjson.GetBytes(body, "tools").Array() {
|
|
switch tool.Get("type").String() {
|
|
case "computer_toolset_20260801", "browser_toolset_20260801":
|
|
if !containsBetaToken(header, claude.BetaFineGrainedToolStreaming) {
|
|
return header
|
|
}
|
|
return stripBetaTokensWithSet(header, map[string]struct{}{claude.BetaFineGrainedToolStreaming: {}})
|
|
}
|
|
}
|
|
return header
|
|
}
|
|
|
|
func legacySyncBillingHeaderVersion(body []byte, userAgent string) []byte {
|
|
version := ExtractCLIVersion(userAgent)
|
|
if version == "" {
|
|
return body
|
|
}
|
|
|
|
systemResult := gjson.GetBytes(body, "system")
|
|
if !systemResult.Exists() || !systemResult.IsArray() {
|
|
return body
|
|
}
|
|
|
|
replacement := "cc_version=" + version
|
|
idx := 0
|
|
systemResult.ForEach(func(_, item gjson.Result) bool {
|
|
text := item.Get("text")
|
|
if text.Exists() && text.Type == gjson.String &&
|
|
strings.HasPrefix(text.String(), "x-anthropic-billing-header") {
|
|
fingerprintedReplacement := replacement + "." + computeClaudeCodeFingerprint(body, version)
|
|
newText := ccVersionWithFingerprintInBillingRe.ReplaceAllString(text.String(), fingerprintedReplacement)
|
|
newText = ccVersionInBillingRe.ReplaceAllString(newText, replacement)
|
|
if newText != text.String() {
|
|
if updated, err := sjson.SetBytes(body, fmt.Sprintf("system.%d.text", idx), newText); err == nil {
|
|
body = updated
|
|
}
|
|
}
|
|
}
|
|
idx++
|
|
return true
|
|
})
|
|
|
|
return body
|
|
}
|