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.
382 lines
11 KiB
Go
382 lines
11 KiB
Go
package gateway
|
|
|
|
// A reply says which of magpie's providers and models answered it (#822):
|
|
// the body's model is the vendor's own name for it (glm-5.3-flash), which
|
|
// names neither the provider nor the group's member, so an agent that
|
|
// 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'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"
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
|
|
"github.com/tidwall/gjson"
|
|
"github.com/yetone/magpie/internal/provider"
|
|
"github.com/yetone/magpie/internal/settings"
|
|
)
|
|
|
|
const (
|
|
providerHeader = "X-Magpie-Provider"
|
|
modelHeader = "X-Magpie-Model"
|
|
responseModelHeader = "X-Magpie-Response-Model" // a request's: member, or vendor
|
|
)
|
|
|
|
// 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, 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 {
|
|
// watch's keepAlive may send them meanwhile
|
|
hw.note(providerHeader, p.ID)
|
|
hw.note(modelHeader, id)
|
|
} else {
|
|
h := w.Header()
|
|
h.Set(providerHeader, p.ID)
|
|
h.Set(modelHeader, id)
|
|
}
|
|
if mw, _ := r.Context().Value(memberKey{}).(*memberWriter); mw != nil {
|
|
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 {
|
|
return replyNamingOf(r, agent) == nameMember
|
|
}
|
|
|
|
// 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, naming: naming, asked: asked, paths: memberPathsOf(from)}
|
|
return mw, r.WithContext(context.WithValue(r.Context(), memberKey{}, mw)), mw.finish
|
|
}
|
|
|
|
// 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
|
|
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 // the provider/model id of the try that answers
|
|
wire string // the name that try goes out under
|
|
|
|
mode int // memberUnknown, …
|
|
buf bytes.Buffer
|
|
finished bool
|
|
}
|
|
|
|
const (
|
|
memberUnknown = iota
|
|
memberAsIs
|
|
memberStream
|
|
memberWhole
|
|
)
|
|
|
|
func (m *memberWriter) setMember(id, wire string) {
|
|
m.mu.Lock()
|
|
m.member, m.wire = id, wire
|
|
m.mu.Unlock()
|
|
}
|
|
|
|
func (m *memberWriter) memberID() string {
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
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.
|
|
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.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 target != "" && strings.Contains(ct, "json"):
|
|
m.mode = memberWhole
|
|
default:
|
|
m.mode = memberAsIs
|
|
}
|
|
if m.mode != memberAsIs {
|
|
h.Del("Content-Length") // the name put in isn't as long as the vendor's
|
|
}
|
|
}
|
|
|
|
func (m *memberWriter) WriteHeader(code int) {
|
|
if m.mode == memberUnknown {
|
|
m.decide(code, nil)
|
|
}
|
|
m.w.WriteHeader(code)
|
|
}
|
|
|
|
func (m *memberWriter) Write(p []byte) (int, error) {
|
|
if m.mode == memberUnknown {
|
|
m.decide(http.StatusOK, p)
|
|
}
|
|
switch m.mode {
|
|
case memberWhole:
|
|
if m.finished {
|
|
// written after finish, by a writer inside this one that held
|
|
// 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(memberNamedAt(p, m.target(), m.paths)); err != nil {
|
|
return 0, err
|
|
}
|
|
return len(p), nil
|
|
}
|
|
return m.w.Write(p)
|
|
}
|
|
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)
|
|
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
|
|
}
|
|
}
|
|
if m.finished && m.buf.Len() > 0 { // no finish is left to write it
|
|
_, err := m.w.Write(m.buf.Bytes())
|
|
m.buf.Reset()
|
|
return len(p), err
|
|
}
|
|
return len(p), nil
|
|
}
|
|
return m.w.Write(p)
|
|
}
|
|
|
|
func (m *memberWriter) Flush() {
|
|
if m.mode == memberWhole && !m.finished {
|
|
return // sent whole, once it is
|
|
}
|
|
if f, ok := m.w.(http.Flusher); ok {
|
|
f.Flush()
|
|
}
|
|
}
|
|
|
|
func (m *memberWriter) finish() {
|
|
m.finished = true
|
|
if m.buf.Len() == 0 {
|
|
return
|
|
}
|
|
b := m.buf.Bytes()
|
|
if m.mode == memberWhole {
|
|
b = memberNamedAt(b, m.target(), m.paths)
|
|
} else {
|
|
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
|
|
}
|
|
at := len(line) - len(rest)
|
|
trimmed := bytes.TrimLeft(rest, " ")
|
|
at += len(rest) - len(trimmed)
|
|
end := len(line)
|
|
for end > at && (line[end-1] == '\n' || line[end-1] == '\r') {
|
|
end--
|
|
}
|
|
data := line[at:end]
|
|
if len(data) == 0 || data[0] != '{' {
|
|
return line
|
|
}
|
|
named := memberNamedAt(data, id, paths)
|
|
if len(named) == len(data) && bytes.Equal(named, data) {
|
|
return line
|
|
}
|
|
out := make([]byte, 0, len(line)+len(named)-len(data))
|
|
out = append(out, line[:at]...)
|
|
out = append(out, named...)
|
|
return append(out, line[end:]...)
|
|
}
|
|
|
|
// memberPaths are where each API's reply names its model: Chat's and a
|
|
// 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"}
|
|
|
|
// 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 paths {
|
|
v := gjson.GetBytes(b, path)
|
|
if v.Type != gjson.String || v.Index <= 0 || v.Str == id {
|
|
continue
|
|
}
|
|
out := make([]byte, 0, len(b)+len(name))
|
|
out = append(out, b[:v.Index]...)
|
|
out = append(out, name...)
|
|
b = append(out, b[v.Index+len(v.Raw):]...)
|
|
}
|
|
return b
|
|
}
|