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.
166 lines
5.7 KiB
Go
166 lines
5.7 KiB
Go
package gateway
|
|
|
|
import (
|
|
"context"
|
|
"net"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"sync"
|
|
"unicode"
|
|
|
|
"github.com/yetone/magpie/internal/usage"
|
|
)
|
|
|
|
// A request passed on to another computer's magpie (a Remote magpie
|
|
// provider) goes as magpie's own, with magpie's User-Agent and the other
|
|
// magpie's key, so that magpie knew it only as "magpie" (Jorben on Discord).
|
|
// It now names the agent it came from (AgentHeader) and the computer
|
|
// (ViaHeader), and the other magpie keeps them in its usage, as "Claude
|
|
// Code · via <computer>". They are a label and nothing more: what magpie
|
|
// does with the request — the models an agent is shown, its stand-ins, a
|
|
// routing group's rules — still goes by who sent it, and they are taken
|
|
// only from a magpie's request (its User-Agent), one a client on the
|
|
// network could send only with the key anyway, and could name itself any
|
|
// agent by its User-Agent as well. No vendor is ever sent them: they come
|
|
// off every request as it arrives, and go on only to a remote magpie.
|
|
const (
|
|
AgentHeader = "X-Magpie-Agent"
|
|
ViaHeader = "X-Magpie-Via"
|
|
)
|
|
|
|
// caller is who a request is recorded as: its agent, and the computer it
|
|
// was passed on from, "" for this one. session and native are the session
|
|
// the caller named (sessionOf's X-Magpie-Session, and the agent's own
|
|
// header nativeSessionOf takes, by its name), passed on to a remote magpie
|
|
// with the request (#672).
|
|
type caller struct {
|
|
agent, via string
|
|
session string
|
|
native [2]string // header, value
|
|
// compact is DSH's compaction mark as it came, passed on with the
|
|
// session so the other magpie records the call as one (#2505)
|
|
compact string
|
|
// ua is the User-Agent the request came with, as it came: the one a
|
|
// provider that passes the agent's on is sent (userAgentFor)
|
|
ua string
|
|
}
|
|
|
|
type callerCtx struct{}
|
|
|
|
// withCaller notes on each request who it is recorded as, and takes the
|
|
// headers that said so off it.
|
|
func withCaller(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
ctx := context.WithValue(r.Context(), callerCtx{}, callerFrom(r))
|
|
if searchingFrom(r) {
|
|
// another magpie's search: only the model itself searches
|
|
ctx = context.WithValue(ctx, searchingKey{}, true)
|
|
}
|
|
r.Header.Del(AgentHeader)
|
|
r.Header.Del(ViaHeader)
|
|
r.Header.Del(SearchingHeader)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// callerFrom reads who r is recorded as from its headers, before withCaller
|
|
// takes magpie's own off: the one rule for every place that names a
|
|
// request's agent (usage, sessions, the routing trace, the masking log,
|
|
// the requests in flight), so another magpie's request is shown as the
|
|
// agent that made it there, never as "magpie" (linkaww on Discord: the
|
|
// masking log named magpie where usage named Pi).
|
|
func callerFrom(r *http.Request) caller {
|
|
c := caller{agent: agentOf(r), session: boundedSession(r.Header.Get(SessionHeader)), ua: r.Header.Get("User-Agent")}
|
|
if dshCompacts(r.Header) {
|
|
c.compact = boundedSession(r.Header.Get(dshCompactHeader))
|
|
}
|
|
for _, h := range sessionHeaders {
|
|
if v := boundedSession(r.Header.Get(h)); v != "" {
|
|
c.native = [2]string{h, v}
|
|
break
|
|
}
|
|
}
|
|
if strings.HasPrefix(r.Header.Get("User-Agent"), "magpie/") {
|
|
if a := label(r.Header.Get(AgentHeader)); a != "" {
|
|
c.agent = usage.AgentOf(a)
|
|
c.via = label(r.Header.Get(ViaHeader))
|
|
if c.via == "" {
|
|
c.via, _, _ = net.SplitHostPort(r.RemoteAddr)
|
|
}
|
|
}
|
|
}
|
|
return c
|
|
}
|
|
|
|
// callerOf is who the request is recorded as.
|
|
func callerOf(r *http.Request) caller {
|
|
if c, ok := r.Context().Value(callerCtx{}).(caller); ok {
|
|
return c
|
|
}
|
|
return caller{agent: agentOf(r)}
|
|
}
|
|
|
|
// label is a header's name for an agent or a computer, if it is a fit one
|
|
// to show: short, one word of printable characters.
|
|
func label(v string) string {
|
|
v = strings.TrimSpace(v)
|
|
if v == "" || len(v) > 64 || strings.IndexFunc(v, func(r rune) bool { return !unicode.IsPrint(r) || unicode.IsSpace(r) }) >= 0 {
|
|
return ""
|
|
}
|
|
return v
|
|
}
|
|
|
|
// boundedSession is a session header's value as magpie keeps it: trimmed,
|
|
// at most 128 bytes, as sessionOf takes it.
|
|
func boundedSession(v string) string {
|
|
v = strings.TrimSpace(v)
|
|
return v[:min(len(v), 128)]
|
|
}
|
|
|
|
// passOnCaller names, on a request to a remote magpie, the agent it is for
|
|
// and the computer it comes from: the one it was passed on from, else this.
|
|
// The session the caller named goes on too, as it named it — magpie's
|
|
// 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. 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
|
|
}
|
|
if c.session != "" {
|
|
req.Header.Set(SessionHeader, c.session)
|
|
}
|
|
if c.native[0] != "" {
|
|
req.Header.Set(c.native[0], c.native[1])
|
|
}
|
|
if c.compact != "" {
|
|
req.Header.Set(dshCompactHeader, c.compact)
|
|
}
|
|
if c.agent == "" {
|
|
return
|
|
}
|
|
req.Header.Set(AgentHeader, c.agent)
|
|
if c.via == "" {
|
|
c.via = hostName()
|
|
}
|
|
if c.via != "" {
|
|
req.Header.Set(ViaHeader, c.via)
|
|
}
|
|
}
|
|
|
|
// hostName is this computer's name as people know it (MacBook-Pro, not
|
|
// MacBook-Pro.local).
|
|
var hostName = sync.OnceValue(func() string {
|
|
h, _ := os.Hostname()
|
|
h, _, _ = strings.Cut(h, ".")
|
|
return label(h)
|
|
})
|