gateway: a reply names the model the agent asked for when it went out under another name (issennknight)
issennknight on Discord (#general): an agent asked for deepseek-v4.1-flash, which goes out as deepseek-v4.1-flash-1017 (settings' ModelIDs). The vendor's reply said -1017, magpie passed it back, and the agent warned that the model didn't match. Before, only MemberModel (#822) or X-Magpie-Response-Model: member rewrote a reply's model, and only to the group member's id. Now the default is nameAsked. When magpie sent the request under another name than the agent asked for (a model's own id, a routing group, a provider/model id), the reply names the asked model. That covers Chat and Anthropic `model`, Responses `response.model` (created, in_progress, completed), Anthropic `message.model` (message_start) and Gemini `modelVersion`, streamed and whole, translated paths and plugins included: it all goes through serve's one memberWriter. A vendor that sent back the wire name as asked keeps its own name, a dated -20261017 too. Usage rows, recent calls and the Routing page still record served = the vendor's name: the writer sits outside captureResponseWriter. Claude Code, Claude Desktop and Codex get the asked name (or the vendor's), never the member's id, as before. Streams are rewritten one complete line at a time (memberLines). A run with no "model" in it is written through as the same slice. Only a JSON reply that has a target at decide time is held whole, which is what MemberModel already did. A JSON body that doesn't parse (a reply cut short) goes on as it came. A request to a remote magpie now sends X-Magpie-Response-Model: vendor (passOnCaller). That magpie names the vendor's model, as before, so this one still records what served the call (TestRemoteMagpieGroupNotSwapped went red without it). Existing tests that held a native reply byte for byte now expect only its model renamed to the asked id (namedAs in member_test.go): passthrough_severed, stream_accounting, refusal, refusal_thinking, thinking_signature and vertex. The archive keeps the reply as the vendor sent it, under the vendor's name (archive_test). Also dropped: the openai-model header code. serve never relays that header, so the test for it could not pass. Run (mote, at this head rebased on origin/main15066f84f): - go test -tags nogui -count=1 -timeout 45m ./...: every package ok except internal/gui: TestSettingsSaveKeepsWhatItDoesNotSend (#4514, SearchAll fromb09349d17) and TestColdTurnsTaken (#4510). Both are filed, and neither touches this change. Three other sessions' suites ran on mote at the same time. The first full run (base80bcef18f) had internal/gateway red in 10 tests: the byte-for-byte tests above, the remote-magpie served test and the truncated JSON body. Each one was fixed as described. - Rebased on544b91ca8(no gateway files changed in between): go build ./..., go vet, then go test ./internal/gateway ./internal/settings ./internal/provider: all ok. - go vet -tags nogui ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./...: clean (cgo warnings only); gofmt -l clean. - go test -race -count=3 on the member and served tests: ok (122s). - the 10 formerly red tests with TestReplyNames, TestGeminiReplyNames, TestMemberLine, TestMemberWriter and Masked, after the rebase: ok. Red on the old code (the new tests over a git archive of the base): - TestReplyNamesAskedModel: 36 subtests fail (own id, group and provider id, x 6 protocol paths, x streamed or not), e.g. `the reply names "deepseek-v4.1-flash-1017", want "deepseek-v4.1-flash"`. - TestGeminiReplyNamesAskedModel: both subtests fail (modelVersion -1017). Broken by hand: dropping `|| m.wire == m.asked` from target() fails "as asked, dated" in 12 subtests. Real use: Codex 0.165.0 (codex exec --json) under a sandbox HOME and CODEX_HOME on mote. A fake Responses vendor always answered deepseek-v4.1-flash-1017, and a tee between Codex and `magpie serve` logged what Codex got. providers.json had d with deepseek-v4.1-flash and group fast; settings.json had modelIDs d/deepseek-v4.1-flash -> deepseek-v4.1-flash-1017. - old build: the vendor was asked for -1017; Codex got "model": "deepseek-v4.1-flash-1017" in response.created, in_progress and completed, both for -m deepseek-v4.1-flash and for -m group/fast. - new build: the vendor was still asked for -1017; Codex got "deepseek-v4.1-flash" and "group/fast"; the usage rows still say served deepseek-v4.1-flash-1017. Codex answered "pong" both times. Codex 0.165 itself shows no warning for a body model either way (its "model rerouted" reads the openai-model header), so the agent behind the report's warning was not the one run. Not tried: the reporter's own agent (not named) and Claude Code; the Responses WebSocket path (responses_ws.go's own frames); a compressed reply, which still goes through as it is; Antigravity's effort-variant wire, where the wire differs from the asked name on purpose.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -226,8 +226,11 @@ func TestArchiveWholeBodies(t *testing.T) {
|
||||
if a.Request.Body != body || a.Request.Size != int64(len(body)) || a.Request.Truncated {
|
||||
t.Errorf("request kept %d of %d, size %d, cut %v", len(a.Request.Body), len(body), a.Request.Size, a.Request.Truncated)
|
||||
}
|
||||
if a.Response.Body != rec.Body.String() || a.Response.Size != int64(rec.Body.Len()) || a.Response.Truncated {
|
||||
t.Errorf("response kept %d of %d, size %d, cut %v", len(a.Response.Body), rec.Body.Len(), a.Response.Size, a.Response.Truncated)
|
||||
// the reply as the vendor sent it, under its own model name;
|
||||
// the agent got the name it asked for
|
||||
sent := namedAs(rec.Body.String(), "m1")
|
||||
if a.Response.Body != sent || a.Response.Size != int64(len(sent)) || a.Response.Truncated {
|
||||
t.Errorf("response kept %d of %d, size %d, cut %v", len(a.Response.Body), len(sent), a.Response.Size, a.Response.Truncated)
|
||||
}
|
||||
if u := lastUsage(t); u.Archive == "" || u.Archive != c.Archive {
|
||||
t.Errorf("usage row names archive %q, the call %q", u.Archive, c.Archive)
|
||||
|
||||
@@ -1864,13 +1864,15 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
var maskedHits maskHits
|
||||
maskDone, sentWhole := false, false
|
||||
unmask := func() {}
|
||||
// the reply's model the member that answered, when asked for (#822).
|
||||
// Both writers hold a whole body until the handler is done, the namer
|
||||
askedFor := modelOf(body) // as it reaches serve, which an error in its stream names (keptAlive)
|
||||
// the reply's model the one asked for when it went out under another
|
||||
// name, or the member that answered, when asked for (#822). Both
|
||||
// writers hold a whole body until the handler is done, the namer
|
||||
// outside: the values are put back first, into the namer, and then it
|
||||
// writes what it holds. The other way round it wrote nothing, and the
|
||||
// values came back after it, into a buffer no one wrote: a 200 with
|
||||
// an empty body whenever a value was masked (#4129)
|
||||
w, r, named := withMemberNames(w, r)
|
||||
w, r, named := withMemberNames(w, r, from, askedFor)
|
||||
defer func() {
|
||||
unmask()
|
||||
named()
|
||||
@@ -1881,7 +1883,6 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
wholeBodies := usage.ObservedBodies() == usage.WholeBodies
|
||||
// a model asked for at an effort of its own (a Claude Code tier, #536)
|
||||
// is the model, every try of it asked for that effort
|
||||
askedFor := modelOf(body) // as it reaches serve, which an error in its stream names (keptAlive)
|
||||
asked, askedEffort := askedAt(askedFor)
|
||||
if askedEffort != "" {
|
||||
body = rewriteModel(body, asked)
|
||||
|
||||
@@ -159,8 +159,8 @@ func TestMemberWriterWrittenAfterFinish(t *testing.T) {
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
m := &memberWriter{w: rec}
|
||||
m.setMember("fake/m1")
|
||||
m := &memberWriter{w: rec, naming: nameMember, paths: memberPaths}
|
||||
m.setMember("fake/m1", "m1")
|
||||
m.Header().Set("Content-Type", tc.ct)
|
||||
m.WriteHeader(200)
|
||||
m.finish()
|
||||
|
||||
+168
-61
@@ -6,13 +6,20 @@ package gateway
|
||||
// counts usage by it puts every provider's glm-5.3-flash in one bucket.
|
||||
//
|
||||
// Every reply carries X-Magpie-Provider (the provider's id) and
|
||||
// X-Magpie-Model (magpie's provider/model id of the member that answered),
|
||||
// the body left as the vendor wrote it: agents read the body's model
|
||||
// themselves (Claude Code its features, Codex its catalog), so a name they
|
||||
// don't know there is not given them unasked. Settings' MemberModel, or a
|
||||
// request's X-Magpie-Response-Model: member, has the body's model say
|
||||
// magpie's id as well (memberWriter); the vendor's own name is still in
|
||||
// the usage log (Record.Served).
|
||||
// X-Magpie-Model (magpie's provider/model id of the member that answered).
|
||||
// The body's model is the one the agent asked for whenever the request
|
||||
// went out under another name — a group's member, an alias, a fallback,
|
||||
// a provider/model id, a name the user gave the model upstream — since
|
||||
// agents compare it with what they asked and warn when it differs
|
||||
// (issennknight on Discord: deepseek-v4.1-flash served as
|
||||
// deepseek-v4.1-flash-1017). A request that went out under the name it
|
||||
// asked for keeps the vendor's text, a dated name included. Settings'
|
||||
// MemberModel, or a request's X-Magpie-Response-Model: member, has the
|
||||
// body's model say magpie's id instead, except for the agents that read
|
||||
// it themselves (vendorNamed); X-Magpie-Response-Model: vendor keeps the
|
||||
// vendor's text. The vendor's own name is still in the usage log
|
||||
// (Record.Served) and on the Routing page: the request's capture is
|
||||
// inside this writer.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -33,14 +40,16 @@ const (
|
||||
responseModelHeader = "X-Magpie-Response-Model" // a request's: member, or vendor
|
||||
)
|
||||
|
||||
// vendorNamed are the agents whose replies always keep the vendor's model
|
||||
// name: they read it themselves.
|
||||
// vendorNamed are the agents whose replies never name the member: they
|
||||
// read the body's model themselves (Claude Code its features, Codex its
|
||||
// catalog), so they get the name they asked for, or the vendor's.
|
||||
var vendorNamed = []string{"claude", "claude-desktop", "codex"}
|
||||
|
||||
type memberKey struct{}
|
||||
|
||||
// noteMember says on the try's reply which provider and model answer it,
|
||||
// and tells the request's memberWriter, if it has one.
|
||||
// and tells the request's memberWriter, if it has one, with the name the
|
||||
// request goes out under.
|
||||
func noteMember(w http.ResponseWriter, r *http.Request, p provider.Provider, model string) {
|
||||
id := p.ID + "/" + model
|
||||
if hw, ok := w.(*holdWriter); ok {
|
||||
@@ -53,49 +62,71 @@ func noteMember(w http.ResponseWriter, r *http.Request, p provider.Provider, mod
|
||||
h.Set(modelHeader, id)
|
||||
}
|
||||
if mw, _ := r.Context().Value(memberKey{}).(*memberWriter); mw != nil {
|
||||
mw.setMember(id)
|
||||
mw.setMember(id, provider.UpstreamNameIn(wiresOf(r.Context()), p.ID, model))
|
||||
}
|
||||
}
|
||||
|
||||
// replyNaming is what the reply to r has its body's model say: the
|
||||
// member's id (namesMember), the vendor's own text (asked for with
|
||||
// X-Magpie-Response-Model: vendor), or else the model the agent asked
|
||||
// for, when the request went out under another name.
|
||||
type replyNaming int
|
||||
|
||||
const (
|
||||
nameAsked replyNaming = iota
|
||||
nameMember
|
||||
nameVendor
|
||||
)
|
||||
|
||||
func replyNamingOf(r *http.Request, agent string) replyNaming {
|
||||
switch strings.ToLower(strings.TrimSpace(r.Header.Get(responseModelHeader))) {
|
||||
case "member":
|
||||
return nameMember
|
||||
case "vendor":
|
||||
return nameVendor
|
||||
}
|
||||
if !settings.Shared().MemberModel {
|
||||
return nameAsked
|
||||
}
|
||||
for _, a := range vendorNamed {
|
||||
if agent == a {
|
||||
return nameAsked
|
||||
}
|
||||
}
|
||||
return nameMember
|
||||
}
|
||||
|
||||
// namesMember is whether the reply to r has its body's model say the
|
||||
// member's id.
|
||||
func namesMember(r *http.Request, agent string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(r.Header.Get(responseModelHeader))) {
|
||||
case "member":
|
||||
return true
|
||||
case "vendor":
|
||||
return false
|
||||
}
|
||||
if !settings.Shared().MemberModel {
|
||||
return false
|
||||
}
|
||||
for _, a := range vendorNamed {
|
||||
if agent == a {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
return replyNamingOf(r, agent) == nameMember
|
||||
}
|
||||
|
||||
// withMemberNames wraps w, when the reply to r names the member, in a
|
||||
// memberWriter, which the tries tell their member (noteMember). The func
|
||||
// returned writes what it holds, once the handler is done.
|
||||
func withMemberNames(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *http.Request, func()) {
|
||||
if !namesMember(r, agentOf(r)) {
|
||||
// withMemberNames wraps w in a memberWriter, which the tries tell their
|
||||
// member (noteMember), for a reply from protocol from to a request that
|
||||
// asked for model asked. The func returned writes what it holds, once
|
||||
// the handler is done.
|
||||
func withMemberNames(w http.ResponseWriter, r *http.Request, from provider.Protocol, asked string) (http.ResponseWriter, *http.Request, func()) {
|
||||
naming := replyNamingOf(r, agentOf(r))
|
||||
if naming == nameVendor || naming == nameAsked && asked == "" {
|
||||
return w, r, func() {}
|
||||
}
|
||||
mw := &memberWriter{w: w}
|
||||
mw := &memberWriter{w: w, naming: naming, asked: asked, paths: memberPathsOf(from)}
|
||||
return mw, r.WithContext(context.WithValue(r.Context(), memberKey{}, mw)), mw.finish
|
||||
}
|
||||
|
||||
// memberWriter puts the member's id for the model a reply names: in each
|
||||
// event of a stream as it goes, in a JSON body once it is whole. An error,
|
||||
// or a body of another kind, goes as it is.
|
||||
// memberWriter puts the name the reply should say (target) for the model
|
||||
// it names: in each event of a stream as it goes, in a JSON body once it
|
||||
// is whole. An error, or a body of another kind, goes as it is.
|
||||
type memberWriter struct {
|
||||
w http.ResponseWriter
|
||||
w http.ResponseWriter
|
||||
naming replyNaming
|
||||
asked string // the model the agent asked for
|
||||
paths []string // where the protocol's replies name their model
|
||||
|
||||
mu sync.Mutex
|
||||
member string
|
||||
member string // the provider/model id of the try that answers
|
||||
wire string // the name that try goes out under
|
||||
|
||||
mode int // memberUnknown, …
|
||||
buf bytes.Buffer
|
||||
@@ -109,9 +140,9 @@ const (
|
||||
memberWhole
|
||||
)
|
||||
|
||||
func (m *memberWriter) setMember(id string) {
|
||||
func (m *memberWriter) setMember(id, wire string) {
|
||||
m.mu.Lock()
|
||||
m.member = id
|
||||
m.member, m.wire = id, wire
|
||||
m.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -121,6 +152,21 @@ func (m *memberWriter) memberID() string {
|
||||
return m.member
|
||||
}
|
||||
|
||||
// target is the name the reply's model says, "" for the vendor's own:
|
||||
// the member's id, or the model asked for unless the try went out
|
||||
// under that very name.
|
||||
func (m *memberWriter) target() string {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.naming == nameMember {
|
||||
return m.member
|
||||
}
|
||||
if m.wire == "" || m.wire == m.asked {
|
||||
return ""
|
||||
}
|
||||
return m.asked
|
||||
}
|
||||
|
||||
func (m *memberWriter) Header() http.Header { return m.w.Header() }
|
||||
|
||||
// Unwrap is for http.ResponseController.
|
||||
@@ -129,21 +175,24 @@ func (m *memberWriter) Unwrap() http.ResponseWriter { return m.w }
|
||||
func (m *memberWriter) decide(code int, first []byte) {
|
||||
h := m.w.Header()
|
||||
ct := h.Get("Content-Type")
|
||||
target := m.target()
|
||||
switch {
|
||||
case code >= 400, m.memberID() == "":
|
||||
case code >= 400:
|
||||
m.mode = memberAsIs
|
||||
case h.Get("Content-Encoding") != "" && !strings.EqualFold(h.Get("Content-Encoding"), "identity"):
|
||||
m.mode = memberAsIs
|
||||
case strings.Contains(ct, "event-stream"),
|
||||
ct == "" && (bytes.HasPrefix(first, []byte("data:")) || bytes.HasPrefix(first, []byte("event:"))):
|
||||
// a stream's lines are read whatever the name is now: a held
|
||||
// stream's keepalive decides before the try that answers is known
|
||||
m.mode = memberStream
|
||||
case strings.Contains(ct, "json"):
|
||||
case target != "" && strings.Contains(ct, "json"):
|
||||
m.mode = memberWhole
|
||||
default:
|
||||
m.mode = memberAsIs
|
||||
}
|
||||
if m.mode != memberAsIs {
|
||||
h.Del("Content-Length") // the id isn't as long as the name
|
||||
h.Del("Content-Length") // the name put in isn't as long as the vendor's
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +214,7 @@ func (m *memberWriter) Write(p []byte) (int, error) {
|
||||
// it longer: no one would write it from the buffer, so it goes
|
||||
// now, named when it is the whole body (#4129)
|
||||
if json.Valid(p) {
|
||||
if _, err := m.w.Write(memberNamed(p, m.memberID())); err != nil {
|
||||
if _, err := m.w.Write(memberNamedAt(p, m.target(), m.paths)); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return len(p), nil
|
||||
@@ -174,16 +223,14 @@ func (m *memberWriter) Write(p []byte) (int, error) {
|
||||
}
|
||||
return m.buf.Write(p)
|
||||
case memberStream:
|
||||
// the whole lines go on in one write, named; the rest waits for
|
||||
// its end
|
||||
m.buf.Write(p)
|
||||
for {
|
||||
b := m.buf.Bytes()
|
||||
i := bytes.IndexByte(b, '\n')
|
||||
if i < 0 {
|
||||
break
|
||||
}
|
||||
line := memberLine(append([]byte(nil), b[:i+1]...), m.memberID())
|
||||
m.buf.Next(i + 1)
|
||||
if _, err := m.w.Write(line); err != nil {
|
||||
b := m.buf.Bytes()
|
||||
if end := bytes.LastIndexByte(b, '\n'); end >= 0 {
|
||||
_, err := m.w.Write(memberLines(b[:end+1], m.target(), m.paths))
|
||||
m.buf.Next(end + 1)
|
||||
if err != nil {
|
||||
return len(p), err
|
||||
}
|
||||
}
|
||||
@@ -213,17 +260,59 @@ func (m *memberWriter) finish() {
|
||||
}
|
||||
b := m.buf.Bytes()
|
||||
if m.mode == memberWhole {
|
||||
b = memberNamed(b, m.memberID())
|
||||
b = memberNamedAt(b, m.target(), m.paths)
|
||||
} else {
|
||||
b = memberLine(b, m.memberID())
|
||||
b = memberLines(b, m.target(), m.paths)
|
||||
}
|
||||
m.w.Write(b)
|
||||
m.buf.Reset()
|
||||
}
|
||||
|
||||
// modelKey is in every event or body that names a model, "modelVersion"
|
||||
// included: one without it is passed on unread.
|
||||
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) {
|
||||
return b
|
||||
}
|
||||
var out []byte
|
||||
for i := 0; i < len(b); {
|
||||
j := bytes.IndexByte(b[i:], '\n')
|
||||
if j < 0 {
|
||||
j = len(b)
|
||||
} else {
|
||||
j += i + 1
|
||||
}
|
||||
line := b[i:j]
|
||||
named := line
|
||||
if bytes.Contains(line, modelKey) {
|
||||
named = memberLineAt(line, name, paths)
|
||||
}
|
||||
if out == nil && !bytes.Equal(named, line) {
|
||||
out = append(make([]byte, 0, len(b)+64), b[:i]...)
|
||||
}
|
||||
if out != nil {
|
||||
out = append(out, named...)
|
||||
}
|
||||
i = j
|
||||
}
|
||||
if out == nil {
|
||||
return b
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// memberLine is an event stream's line with the member's id for the
|
||||
// model its data names.
|
||||
func memberLine(line []byte, id string) []byte {
|
||||
return memberLineAt(line, id, memberPaths)
|
||||
}
|
||||
|
||||
// memberLineAt is memberLine for the paths a protocol's events have.
|
||||
func memberLineAt(line []byte, id string, paths []string) []byte {
|
||||
rest, ok := bytes.CutPrefix(line, []byte("data:"))
|
||||
if !ok {
|
||||
return line
|
||||
@@ -239,7 +328,7 @@ func memberLine(line []byte, id string) []byte {
|
||||
if len(data) == 0 || data[0] != '{' {
|
||||
return line
|
||||
}
|
||||
named := memberNamed(data, id)
|
||||
named := memberNamedAt(data, id, paths)
|
||||
if len(named) == len(data) && bytes.Equal(named, data) {
|
||||
return line
|
||||
}
|
||||
@@ -250,17 +339,35 @@ func memberLine(line []byte, id string) []byte {
|
||||
}
|
||||
|
||||
// memberPaths are where each API's reply names its model: Chat's and a
|
||||
// whole Anthropic message's model, a Responses event's response.model,
|
||||
// Anthropic's message_start's message.model, Gemini's modelVersion.
|
||||
// whole Anthropic message's or Responses response's model, a Responses
|
||||
// event's response.model, Anthropic's message_start's message.model,
|
||||
// Gemini's modelVersion.
|
||||
var memberPaths = []string{"model", "response.model", "message.model", "modelVersion"}
|
||||
|
||||
// memberNamed is a JSON object with id for the model it names.
|
||||
func memberNamed(b []byte, id string) []byte {
|
||||
if id == "" {
|
||||
// memberPathsOf are the memberPaths a reply in protocol from has.
|
||||
func memberPathsOf(from provider.Protocol) []string {
|
||||
switch from {
|
||||
case provider.Chat:
|
||||
return []string{"model"}
|
||||
case provider.Responses:
|
||||
return []string{"model", "response.model"}
|
||||
case provider.Anthropic:
|
||||
return []string{"model", "message.model"}
|
||||
case provider.Gemini:
|
||||
return []string{"modelVersion"}
|
||||
}
|
||||
return memberPaths
|
||||
}
|
||||
|
||||
// memberNamedAt is a JSON object with id for the model it names at
|
||||
// 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) {
|
||||
return b
|
||||
}
|
||||
name, _ := json.Marshal(id)
|
||||
for _, path := range memberPaths {
|
||||
for _, path := range paths {
|
||||
v := gjson.GetBytes(b, path)
|
||||
if v.Type != gjson.String || v.Index <= 0 || v.Str == id {
|
||||
continue
|
||||
|
||||
+200
-13
@@ -2,9 +2,15 @@ package gateway
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
@@ -15,9 +21,10 @@ import (
|
||||
// A reply from a group says which member answered it (#822): its
|
||||
// X-Magpie-Provider and X-Magpie-Model headers always, relayed or
|
||||
// translated, streamed or not, after a failover too; its body's model the
|
||||
// vendor's own name, unless MemberModel (or the request's
|
||||
// group the agent asked for, unless MemberModel (or the request's
|
||||
// X-Magpie-Response-Model: member) asks for magpie's provider/model id
|
||||
// there — never for Claude Code or Codex, which read it themselves.
|
||||
// there — never for Claude Code or Codex, which read it themselves — or
|
||||
// X-Magpie-Response-Model: vendor for the vendor's own name.
|
||||
func TestReplyNamesMember(t *testing.T) {
|
||||
bodies := map[string]string{
|
||||
"/v1/messages": `{"model":"group/auto","max_tokens":100,"messages":[{"role":"user","content":"hi"}]`,
|
||||
@@ -44,14 +51,15 @@ func TestReplyNamesMember(t *testing.T) {
|
||||
on bool // MemberModel
|
||||
header string // X-Magpie-Response-Model
|
||||
token string // the agent's key
|
||||
member bool // the body names the member
|
||||
want string // the model the body names
|
||||
}{
|
||||
{"default", false, "", "", false},
|
||||
{"on", true, "", "", true},
|
||||
{"asked", false, "member", "", true},
|
||||
{"on, vendor asked", true, "vendor", "", false},
|
||||
{"on, codex", true, "", TokenFor("codex"), false},
|
||||
{"on, claude code", true, "", TokenFor("claude"), false},
|
||||
{"default", false, "", "", "group/auto"},
|
||||
{"on", true, "", "", "b/glm-5.3-flash"},
|
||||
{"asked", false, "member", "", "b/glm-5.3-flash"},
|
||||
{"on, vendor asked", true, "vendor", "", served},
|
||||
{"vendor asked", false, "vendor", "", served},
|
||||
{"on, codex", true, "", TokenFor("codex"), "group/auto"},
|
||||
{"on, claude code", true, "", TokenFor("claude"), "group/auto"},
|
||||
} {
|
||||
name := pa.name + "/" + c.name
|
||||
if stream {
|
||||
@@ -117,10 +125,7 @@ func TestReplyNamesMember(t *testing.T) {
|
||||
if p, m := rec.Header().Get(providerHeader), rec.Header().Get(modelHeader); p != "b" || m != "b/glm-5.3-flash" {
|
||||
t.Errorf("headers say %q %q", p, m)
|
||||
}
|
||||
want := served
|
||||
if c.member {
|
||||
want = "b/glm-5.3-flash"
|
||||
}
|
||||
want := c.want
|
||||
names := modelsNamed(rec.Body.String(), stream)
|
||||
if len(names) == 0 {
|
||||
t.Fatalf("no model named in %s", rec.Body)
|
||||
@@ -130,6 +135,9 @@ func TestReplyNamesMember(t *testing.T) {
|
||||
t.Fatalf("the reply names %q, want %q:\n%s", n, want, rec.Body)
|
||||
}
|
||||
}
|
||||
if r := lastRoute(s); r.Served != served {
|
||||
t.Errorf("the route says %q served it, want the vendor's %q", r.Served, served)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -178,3 +186,182 @@ func TestMemberLine(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A reply names the model the agent asked for whenever the request went
|
||||
// out under another name, since agents compare the two and warn when they
|
||||
// differ (issennknight on Discord: deepseek-v4.1-flash, which the user
|
||||
// lists by that id, went out as deepseek-v4.1-flash-1017 and came back
|
||||
// so named): a model the user lists by an id of theirs, a group, a
|
||||
// provider/model id. One that went out under the name asked for keeps
|
||||
// the vendor's own text, its dated name. The route and the usage log
|
||||
// keep the vendor's name either way.
|
||||
func TestReplyNamesAskedModel(t *testing.T) {
|
||||
paths := []struct {
|
||||
name string
|
||||
proto provider.Protocol // the vendor's
|
||||
agent string // the agent's endpoint
|
||||
}{
|
||||
{"anthropic", provider.Anthropic, "/v1/messages"},
|
||||
{"chat", provider.Chat, "/v1/chat/completions"},
|
||||
{"responses", provider.Responses, "/v1/responses"},
|
||||
{"chat from anthropic", provider.Anthropic, "/v1/chat/completions"},
|
||||
{"anthropic from chat", provider.Chat, "/v1/messages"},
|
||||
{"responses from chat", provider.Chat, "/v1/responses"},
|
||||
}
|
||||
cases := []struct {
|
||||
name string
|
||||
asked string
|
||||
ids map[string]string // settings' ModelIDs
|
||||
served string // what the vendor's reply says
|
||||
header string // X-Magpie-Response-Model
|
||||
want string
|
||||
}{
|
||||
{"own id", "deepseek-v4.1-flash", map[string]string{"d/deepseek-v4.1-flash": "deepseek-v4.1-flash-1017"}, "deepseek-v4.1-flash-1017", "", "deepseek-v4.1-flash"},
|
||||
{"own id, vendor asked", "deepseek-v4.1-flash", map[string]string{"d/deepseek-v4.1-flash": "deepseek-v4.1-flash-1017"}, "deepseek-v4.1-flash-1017", "vendor", "deepseek-v4.1-flash-1017"},
|
||||
{"group", "group/fast", nil, "deepseek-v4.1-flash-1017", "", "group/fast"},
|
||||
{"provider id", "d/deepseek-v4.1-flash", nil, "deepseek-v4.1-flash", "", "d/deepseek-v4.1-flash"},
|
||||
{"as asked, dated", "deepseek-v4.1-flash", nil, "deepseek-v4.1-flash-20261017", "", "deepseek-v4.1-flash-20261017"},
|
||||
}
|
||||
for _, pa := range paths {
|
||||
for _, stream := range []bool{false, true} {
|
||||
for _, c := range cases {
|
||||
name := pa.name + "/" + c.name
|
||||
if stream {
|
||||
name += "/stream"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
fresh(t)
|
||||
var mu sync.Mutex
|
||||
var sent []string // the models the vendor was asked for
|
||||
serve := servedBy(pa.proto, c.served)
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
mu.Lock()
|
||||
sent = append(sent, gjson.GetBytes(b, "model").Str)
|
||||
mu.Unlock()
|
||||
r.Body = io.NopCloser(bytes.NewReader(b))
|
||||
serve(w, r)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
p := provider.Provider{ID: "d", Name: "D", Key: "k", Models: []string{"deepseek-v4.1-flash"}}
|
||||
switch pa.proto {
|
||||
case provider.Chat:
|
||||
p.Chat = up.URL + "/v1"
|
||||
case provider.Responses:
|
||||
p.Responses = up.URL + "/v1"
|
||||
case provider.Anthropic:
|
||||
p.Anthropic = up.URL
|
||||
}
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{Name: "fast", Routing: provider.Ordered, Members: []string{"d/deepseek-v4.1-flash"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if c.ids != nil {
|
||||
if err := settings.Save(settings.Settings{ModelIDs: c.ids}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
m, _ := json.Marshal(c.asked)
|
||||
body := `{"model":` + string(m) + `,"max_tokens":100,"messages":[{"role":"user","content":"hi"}]`
|
||||
if pa.agent == "/v1/responses" {
|
||||
body = `{"model":` + string(m) + `,"input":"hi"`
|
||||
}
|
||||
if stream {
|
||||
body += `,"stream":true`
|
||||
}
|
||||
req := httptest.NewRequest("POST", pa.agent, strings.NewReader(body+"}"))
|
||||
if c.header != "" {
|
||||
req.Header.Set(responseModelHeader, c.header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
s := New()
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
mu.Lock()
|
||||
t.Logf("sent as %v", sent)
|
||||
mu.Unlock()
|
||||
names := modelsNamed(rec.Body.String(), stream)
|
||||
if len(names) == 0 {
|
||||
t.Fatalf("no model named in %s", rec.Body)
|
||||
}
|
||||
for _, n := range names {
|
||||
if n != c.want {
|
||||
t.Fatalf("the reply names %q, want %q:\n%s", n, c.want, rec.Body)
|
||||
}
|
||||
}
|
||||
if r := lastRoute(s); r.Served != c.served {
|
||||
t.Errorf("the route says %q served it, want the vendor's %q", r.Served, c.served)
|
||||
}
|
||||
if calls := s.Recent(); len(calls) == 0 || calls[0].Usage.Served != c.served {
|
||||
t.Errorf("the log says %+v served it, want the vendor's %q", calls, c.served)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A Gemini agent asks in the URL, and the reply's modelVersion names that
|
||||
// model when the request went out under another name.
|
||||
func TestGeminiReplyNamesAskedModel(t *testing.T) {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(fmt.Sprint("stream ", stream), func(t *testing.T) {
|
||||
fresh(t)
|
||||
up := httptest.NewServer(servedBy(provider.Chat, "deepseek-v4.1-flash-1017"))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "d", Name: "D", Key: "k", Chat: up.URL + "/v1", Models: []string{"deepseek-v4.1-flash"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := settings.Save(settings.Settings{ModelIDs: map[string]string{"d/deepseek-v4.1-flash": "deepseek-v4.1-flash-1017"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := "/v1beta/models/deepseek-v4.1-flash:generateContent"
|
||||
if stream {
|
||||
path = "/v1beta/models/deepseek-v4.1-flash:streamGenerateContent?alt=sse"
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(`{"contents":[{"role":"user","parts":[{"text":"hi"}]}]}`)))
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "hi") {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body)
|
||||
}
|
||||
names := modelsNamed(rec.Body.String(), stream)
|
||||
if len(names) == 0 {
|
||||
t.Fatalf("no model named in %s", rec.Body)
|
||||
}
|
||||
for _, n := range names {
|
||||
if n != "deepseek-v4.1-flash" {
|
||||
t.Fatalf("the reply names %q:\n%s", n, rec.Body)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A run of a stream's lines is named line by line, and a run that names
|
||||
// no model, or a name of "", is the same slice back.
|
||||
func TestMemberLines(t *testing.T) {
|
||||
in := []byte("event: response.created\ndata: {\"response\":{\"model\":\"v\"}}\n\nevent: response.output_text.delta\ndata: {\"delta\":\"hi\"}\n\ndata: {\"model\":\"v\"}\n")
|
||||
want := "event: response.created\ndata: {\"response\":{\"model\":\"asked\"}}\n\nevent: response.output_text.delta\ndata: {\"delta\":\"hi\"}\n\ndata: {\"model\":\"v\"}\n"
|
||||
if got := string(memberLines(in, "asked", memberPathsOf(provider.Responses)[1:])); got != want {
|
||||
t.Errorf("got %q, want %q", got, want)
|
||||
}
|
||||
plain := []byte("data: {\"delta\":\"hi\"}\n\n")
|
||||
if got := memberLines(plain, "asked", memberPaths); &got[0] != &plain[0] {
|
||||
t.Error("a run with no model was copied")
|
||||
}
|
||||
if got := memberLines(in, "", memberPaths); &got[0] != &in[0] {
|
||||
t.Error("no name copied the run")
|
||||
}
|
||||
}
|
||||
|
||||
// namedAs is a reply as an agent that asked for asked gets it: every model
|
||||
// it names is that one (memberWriter), the rest as the vendor wrote it.
|
||||
func namedAs(reply, asked string) string {
|
||||
return replyModels.ReplaceAllString(reply, `"$1"$2"`+asked+`"`)
|
||||
}
|
||||
|
||||
var replyModels = regexp.MustCompile(`"(model|modelVersion)"(\s*:\s*)"[^"]*"`)
|
||||
|
||||
@@ -130,13 +130,14 @@ func TestLoopCutMidLine(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A whole stream goes through untouched, nothing added after its end.
|
||||
// A whole stream goes through untouched, nothing added after its end,
|
||||
// but for the model it names: the one the agent asked for (memberWriter).
|
||||
func TestPassthroughStreamWhole(t *testing.T) {
|
||||
fresh(t)
|
||||
f := &fake{reply: anthropicStart + anthropicText + anthropicStop}
|
||||
setup(t, "anthropic", f)
|
||||
code, body := postMessages(t, `{"model":"fake/m1","stream":true,"max_tokens":8,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || body != anthropicStart+anthropicText+anthropicStop {
|
||||
if code != 200 || body != namedAs(anthropicStart+anthropicText+anthropicStop, "fake/m1") {
|
||||
t.Fatalf("a whole stream was changed: %d %q", code, body)
|
||||
}
|
||||
}
|
||||
@@ -163,7 +164,7 @@ func TestPassthroughResponsesBigLastEvent(t *testing.T) {
|
||||
f := &fake{reply: reply}
|
||||
setup(t, "responses", f)
|
||||
code, body := post(t, "/v1/responses", `{"model":"fake/m1","stream":true,"input":"hi"}`)
|
||||
if code != 200 || body != reply {
|
||||
if code != 200 || body != namedAs(reply, "fake/m1") {
|
||||
t.Fatalf("a whole stream with a big last event was changed: %d, %d bytes added", code, len(body)-len(reply))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,7 +259,7 @@ func TestRefusalAfterContentPassesThrough(t *testing.T) {
|
||||
scriptedOn(t, "b", provider.Anthropic, b)
|
||||
refusalGroup(t, "a/m", "b/m")
|
||||
code, body := sendTo(New(), "/v1/messages", `{"model":"group/g","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || body != late || b.n != 0 {
|
||||
if code != 200 || body != namedAs(late, "group/g") || b.n != 0 {
|
||||
t.Fatalf("messages: %d %s (b %d)", code, body, b.n)
|
||||
}
|
||||
// translated for Codex, it is the incomplete reply it was
|
||||
@@ -276,13 +276,13 @@ func TestRefusalAfterContentPassesThrough(t *testing.T) {
|
||||
scriptedOn(t, "b", provider.Anthropic, b)
|
||||
refusalGroup(t, "a/m", "b/m")
|
||||
code, body = sendTo(New(), "/v1/messages", `{"model":"group/g","max_tokens":10,"stream":true,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || body != anthropicAnswer || b.n != 0 {
|
||||
if code != 200 || body != namedAs(anthropicAnswer, "group/g") || b.n != 0 {
|
||||
t.Fatalf("answer: %d %s (b %d)", code, body, b.n)
|
||||
}
|
||||
whole := `{"id":"m2","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"whole"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":2}}`
|
||||
a.replies = []reply{{200, "", whole}}
|
||||
code, body = sendTo(New(), "/v1/messages", `{"model":"group/g","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if code != 200 || strings.TrimSpace(body) != whole || b.n != 0 {
|
||||
if code != 200 || strings.TrimSpace(body) != namedAs(whole, "group/g") || b.n != 0 {
|
||||
t.Fatalf("whole: %d %s (b %d)", code, body, b.n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -100,7 +100,7 @@ func TestRefusalAfterThinkingFailsOver(t *testing.T) {
|
||||
scriptedOn(t, "a", provider.Anthropic, a)
|
||||
scriptedOn(t, "b", provider.Anthropic, b)
|
||||
refusalGroup(t, "a/m", "b/m")
|
||||
if code, body := sendTo(New(), "/v1/messages", claudeCodeAsk); code != 200 || body != anthropicThoughtThenAnswered || b.n != 0 {
|
||||
if code, body := sendTo(New(), "/v1/messages", claudeCodeAsk); code != 200 || body != namedAs(anthropicThoughtThenAnswered, "group/g") || b.n != 0 {
|
||||
t.Fatalf("answered: %d %s (b %d)", code, body, b.n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,8 +124,13 @@ func boundedSession(v string) string {
|
||||
// X-Magpie-Session and the agent's own header (session_id, …) — so the
|
||||
// other magpie records the call under it and keeps a conversation on its
|
||||
// account by it rather than by its first message (#672). Only a remote
|
||||
// magpie is sent them; a vendor never is.
|
||||
// magpie is sent them; a vendor never is. It is asked, too, to name the
|
||||
// vendor's model in its reply, as it did before a reply named the model
|
||||
// asked for: this magpie records what served the call from it (served,
|
||||
// swapped, routed; TestRemoteMagpieGroupNotSwapped), and gives its own
|
||||
// agent the name it asked for itself.
|
||||
func passOnCaller(ctx context.Context, req *http.Request) {
|
||||
req.Header.Set(responseModelHeader, "vendor")
|
||||
c, ok := ctx.Value(callerCtx{}).(caller)
|
||||
if !ok {
|
||||
return
|
||||
|
||||
@@ -71,6 +71,7 @@ func TestStreamFailureAccounting(t *testing.T) {
|
||||
|
||||
// Native stream errors are relayed byte for byte, including an
|
||||
// error event without a final newline, and still reach the request log.
|
||||
// Only the model a reply names is the one the agent asked for.
|
||||
func TestNativeStreamFailureAccounting(t *testing.T) {
|
||||
const failure = "synthetic stream failure"
|
||||
for _, c := range []struct {
|
||||
@@ -100,7 +101,7 @@ func TestNativeStreamFailureAccounting(t *testing.T) {
|
||||
s := New()
|
||||
w := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(w, httptest.NewRequest("POST", c.path, strings.NewReader(c.body)))
|
||||
if w.Code != 200 || w.Body.String() != reply {
|
||||
if w.Code != 200 || w.Body.String() != namedAs(reply, "fake/m1") {
|
||||
t.Fatalf("native stream was changed: %d %s", w.Code, w.Body)
|
||||
}
|
||||
state, recent := s.Trace(context.Background(), 0, 0), s.Recent()
|
||||
|
||||
@@ -119,7 +119,7 @@ func TestMessagesThinkingIsSigned(t *testing.T) {
|
||||
|
||||
// TestSignedThinkingRelayedAsItCame: a reply whose thinking is signed
|
||||
// already (Anthropic's own) goes to the client byte for byte, its
|
||||
// signature as Anthropic wrote it.
|
||||
// signature as Anthropic wrote it; only its model is the one asked for.
|
||||
func TestSignedThinkingRelayedAsItCame(t *testing.T) {
|
||||
signed := strings.NewReplacer(
|
||||
`"content_block":{"type":"thinking","thinking":""}`, `"content_block":{"type":"thinking","thinking":"","signature":""}`,
|
||||
@@ -140,7 +140,7 @@ func TestSignedThinkingRelayedAsItCame(t *testing.T) {
|
||||
if code != 200 {
|
||||
t.Fatalf("status %d: %s", code, body)
|
||||
}
|
||||
if body != tt.reply {
|
||||
if body != namedAs(tt.reply, "fake/m1") {
|
||||
t.Errorf("signed reply changed on its way:\n got %s\nwant %s", body, tt.reply)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -703,7 +703,7 @@ func TestVertexGeminiClients(t *testing.T) {
|
||||
const safety = `[{"category":"HARM_CATEGORY_HARASSMENT","threshold":"BLOCK_NONE"}]`
|
||||
out = vertexAsk(t, s, "/v1beta/models/google-vertex/gemini-2.5-flash:generateContent",
|
||||
`{"contents":[{"role":"user","parts":[{"text":"List three primary colours."}]}],"safetySettings":`+safety+`,"generationConfig":`+gen+`}`)
|
||||
if out != vertexColours {
|
||||
if out != namedAs(vertexColours, "google-vertex/gemini-2.5-flash") {
|
||||
t.Errorf("answered whole %s", out)
|
||||
}
|
||||
a = v.last(t)
|
||||
|
||||
@@ -334,9 +334,14 @@ type Settings struct {
|
||||
CheckinOff []string `json:"checkinOff,omitempty"`
|
||||
// MemberModel has a reply's model name the routing group's member
|
||||
// that answered, as magpie's provider/model id (workbuddy/glm-5.3-flash),
|
||||
// rather than the vendor's own name for it, for agents that count
|
||||
// usage by the reply's model (#822). Claude Code, Claude Desktop and
|
||||
// Codex always get the vendor's name: they read it themselves.
|
||||
// for agents that count usage by the reply's model (#822). Off, as by
|
||||
// default, a reply sent under another name than the one asked for (a
|
||||
// group's member, a model's own id, a provider/model id) names the
|
||||
// model the agent asked for (issennknight on Discord: an agent warned
|
||||
// that deepseek-v4.1-flash came back as deepseek-v4.1-flash-1017);
|
||||
// one the vendor named as asked keeps the vendor's name, a dated one
|
||||
// too. Claude Code, Claude Desktop and Codex never get the member's
|
||||
// id: they read the name themselves (gateway's replyNamingOf).
|
||||
MemberModel bool `json:"memberModel,omitempty"`
|
||||
// NoLoopGuard lets a streamed reply run on when its reasoning or text
|
||||
// is stuck in a loop of the same few lines (#1359). Off, as by
|
||||
|
||||
Reference in New Issue
Block a user