feat(upstream): match the 2.x client's chat body byte for byte (#142)

The v2 gate fingerprints the body as well as the headers, and five details
still differed from a captured 2.1.1 request:

- The client sends max_completion_tokens: 32000 on every chat body. The
  gateway now adds it when the caller asked for no ceiling; an explicit
  max_tokens or max_completion_tokens still wins.
- Every client tool carries "strict": false, so a tool that omits the field
  is byte-different from the client's on every request that carries tools.
- The shell tool description names the shell the client actually has, so a
  Windows host advertises a different one than the captured Unix wording.
- Chat bodies keep the client's key order, model first. Go writes map keys
  alphabetically, which puts max_completion_tokens at the front where a real
  client starts with model.
- Bodies are encoded without HTML escaping. encoding/json writes \u003c,
  \u003e and \u0026 by default where JSON.stringify writes the characters,
  and tool descriptions are full of both.

The ordered encoder falls back to plain encoding/json for every lane except
the v2 chat one, and both re-encode points in the request path use it.

Co-authored-by: AiFLYF <AiFLYF@users.noreply.github.com>
This commit is contained in:
FLYFandAiFLYF authored and GitHub committed 2026-10-23 09:24:20 +08:00
1 parent f9ef5693ab
commit 5c5100c470
3 files changed
+135 -3

No files matched your search

+1 -1
View File
@@ -612,7 +612,7 @@ func (g *Gateway) prepareRouteBodies(from wire.Protocol, route models.Route, inp
if effort := g.resolvedEffort(jsonutil.StringAt(upstreamPayload, "model"), tier, protocol); effort != "" {
wire.ForcedEffort(protocol, upstreamPayload, effort)
}
encoded, err := json.Marshal(upstreamPayload)
encoded, err := jsonutil.Marshal(upstreamPayload)
if err != nil {
return nil, errors.New("request contains unsupported JSON values")
}
+112 -2
View File
@@ -13,6 +13,7 @@ import (
"net/http"
"net/url"
"regexp"
"runtime"
"slices"
"sort"
"strconv"
@@ -200,7 +201,7 @@ func stripStaleReasoningInputs(route models.Route, bodies map[config.Tier][]byte
out[tier] = body
continue
}
encoded, err := json.Marshal(payload)
encoded, err := jsonutil.Marshal(payload)
if err != nil {
out[tier] = body
continue
@@ -679,10 +680,13 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
} else if ensureV2Tools(payload, protocol) {
changed = true
}
if !v1 && protocol == wire.Chat && ensureV2CompletionLimit(payload) {
changed = true
}
if !changed {
return body, alias
}
encoded, err := json.Marshal(payload)
encoded, err := encodeAnonymousBody(payload, protocol, v1)
if err != nil {
// The alias is dropped with the failed re-encode: the body never left
// the gateway, so there is nothing downstream to restore.
@@ -691,6 +695,94 @@ func prepareAnonymousBody(body []byte, protocol wire.Protocol, v1 bool) ([]byte,
return encoded, alias
}
// v2CompletionLimit is the max_completion_tokens a 2.x client puts on every
// chat body, so the free tier always sees the same ceiling.
const v2CompletionLimit = 32000
// ensureV2CompletionLimit adds the client's own max_completion_tokens when the
// caller did not ask for a ceiling. A caller-supplied max_tokens or
// max_completion_tokens wins, so an explicit limit is still honoured. It
// reports whether the payload changed.
func ensureV2CompletionLimit(payload map[string]any) bool {
if _, ok := payload["max_completion_tokens"]; ok {
return false
}
if _, ok := payload["max_tokens"]; ok {
return false
}
payload["max_completion_tokens"] = v2CompletionLimit
return true
}
// v2ChatKeyOrder is the order the 2.x client's JSON.stringify emits the keys of
// a chat body in. Go serialises a map alphabetically, which puts
// max_completion_tokens first where a real client starts with model; the bytes
// parse the same either way, but the gateway exists to be indistinguishable, so
// the skeleton is written in the client's order.
var v2ChatKeyOrder = []string{"model", "messages", "tools", "stream", "stream_options", "max_completion_tokens"}
// marshalV2ChatBody encodes a chat payload with v2ChatKeyOrder first and any
// remaining keys sorted after it. Values still go through encoding/json, so
// only the key order differs from a plain marshal.
func marshalV2ChatBody(payload map[string]any) ([]byte, error) {
var buffer bytes.Buffer
buffer.WriteByte('{')
written := make(map[string]bool, len(payload))
first := true
write := func(key string) error {
value, ok := payload[key]
if !ok {
return nil
}
keyJSON, err := jsonutil.Marshal(key)
if err != nil {
return err
}
valueJSON, err := jsonutil.Marshal(value)
if err != nil {
return err
}
if !first {
buffer.WriteByte(',')
}
first = false
buffer.Write(keyJSON)
buffer.WriteByte(':')
buffer.Write(valueJSON)
written[key] = true
return nil
}
for _, key := range v2ChatKeyOrder {
if err := write(key); err != nil {
return nil, err
}
}
rest := make([]string, 0, len(payload))
for key := range payload {
if !written[key] {
rest = append(rest, key)
}
}
sort.Strings(rest)
for _, key := range rest {
if err := write(key); err != nil {
return nil, err
}
}
buffer.WriteByte('}')
return buffer.Bytes(), nil
}
// encodeAnonymousBody renders a shaped anonymous payload in the byte layout the
// lane's client produces: 2.x chat bodies keep the client's key order, every
// other lane keeps plain encoding/json.
func encodeAnonymousBody(payload map[string]any, protocol wire.Protocol, v1 bool) ([]byte, error) {
if !v1 && protocol == wire.Chat {
return marshalV2ChatBody(payload)
}
return jsonutil.Marshal(payload)
}
// ensureAnonymousChatUsage keeps token usage available when a non-streaming
// request is forced onto the Chat SSE path. OpenAI-compatible Chat streams
// require stream_options.include_usage for the final usage event. It reports
@@ -948,6 +1040,17 @@ func anonymousToolName(protocol wire.Protocol, item any) string {
return jsonutil.StringAt(entry, "name")
}
// v2ShellDescription renders the shell tool description for the host platform.
// The 2.x client describes the shell it actually has, so a Windows host says
// powershell where a Unix host says bash. The captured definition ships the
// Unix wording, which would advertise a shell a Windows gateway does not have.
func v2ShellDescription(base string) string {
if runtime.GOOS != "windows" {
return base
}
return strings.Replace(base, "on Linux using bash", "on Windows using powershell", 1)
}
// v2Toolset returns the wire-shaped genuine CLI 2.x definitions for the given
// tool names on a v2 gate. A nil names selects every v2CoreTools entry.
func v2Toolset(protocol wire.Protocol, names []string) []any {
@@ -977,6 +1080,9 @@ func v2Tool(protocol wire.Protocol, name string) map[string]any {
parameters = definition.Parameters
}
}
if name == "shell" {
description = v2ShellDescription(description)
}
switch protocol {
case wire.Chat:
return map[string]any{
@@ -985,6 +1091,10 @@ func v2Tool(protocol wire.Protocol, name string) map[string]any {
"name": name,
"description": description,
"parameters": parameters,
// The 2.x client marks every tool strict:false, so a tool that
// omits the field is byte-different from the client's on every
// request that carries tools.
"strict": false,
},
}
case wire.Anthropic:
+22
View File
@@ -0,0 +1,22 @@
package jsonutil
import (
"bytes"
"encoding/json"
)
// Marshal encodes value the way the JavaScript clients this gateway imitates
// do. encoding/json escapes '<', '>' and '&' as \u003c, \u003e and \u0026 by
// default; JSON.stringify never does. A body carrying those escapes is
// byte-different from a real client's on every request whose text contains an
// angle bracket or ampersand, and tool descriptions and code snippets are full
// of both, so upstream request bodies go through here instead.
func Marshal(value any) ([]byte, error) {
var buffer bytes.Buffer
encoder := json.NewEncoder(&buffer)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(value); err != nil {
return nil, err
}
return bytes.TrimSuffix(buffer.Bytes(), []byte("\n")), nil
}