gateway: Claude Code's model discovery is shown every model by an id it keeps

Claude Code's Gateway Model Discovery (CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY)
puts in /model only the ids matching /(claude|anthropic)/i: Tvi in the
2.1.316 bundle, te.data.data.filter((se)=>/(claude|anthropic)/i.test(se.id)),
on GET <ANTHROPIC_BASE_URL>/v1/models?limit=1000 with User-Agent
claude-code/<version> (Xs(), not claude-cli/) and anthropic-version:
2023-06-01. A remote magpie's Kimi, GLM and DeepSeek never showed (zent00
on X, tweet 2121440002244747428).

That request alone (claudeCodeDiscovers: the User-Agent and the header,
never another magpie) is now shown a chat model whose id says neither by
Claude Desktop's alias anthropic/magpie-<n> (aliasFor), which unprefixed
already serves as the model for every client, before any provider's
model of that spelling; no Claude id is spelled so. Its display_name is
the agents' list name, which /model shows. Ids Claude Code keeps, names a
gateway key gives models, and every other client's list are unchanged; a
bare-id row it wouldn't keep is left out (its full id's row is there).
"anthropic/<magpie id>" was not used: a provider named anthropic (the
Anthropic preset's id) serves any model asked by that spelling. Zero
config, so no switch.

Run:
- TestClaudeCodeDiscoveryKeepsEveryModel, on mote: red on the old
  gateway.go ("not shown anthropic/magpie-9301644634 for auto/kimi-k3"),
  green with the change; with the anthropic-version check broken by hand
  it fails on the claude-cli/ client. TestCindyDiscovery and the Desktop
  tests green.
- Real Claude Code 2.1.316 binary on mote, sandbox HOME, against the
  gateway with a fake Anthropic upstream: its cache gateway-models.json
  held {"id":"anthropic/magpie-4484984192","display_name":"DeepSeek V4 ·
  DeepSeek"}; `claude -p --model anthropic/magpie-4484984192` answered
  PONG and the upstream was asked model deepseek-v4. Claude Code warns it
  assumes a 200k window for an id it doesn't know, as for any non-Claude
  id.
- gofmt -l: clean. Package vets/builds and go test ./internal/gateway
  started on mote; the full suite (go vet, GOOS=linux/windows vet,
  builds, go test -tags nogui -timeout 45m ./...) is queued under
  mote's suite.lock and runs after the push, per the ship-at-once rule;
  its reds get their own commits.
Not tried: interactive /model screen (the rows come from that cache
file), a real remote magpie over LAN with a gateway key.
This commit is contained in:
yetone
2026-11-14 11:43:27 +08:00
parent c5b40bf898
commit 90932ed1fa
4 changed files with 189 additions and 3 deletions
+4
View File
@@ -1308,6 +1308,10 @@ A gateway key's models (`Key.Models`, [`access/models.go`](../../internal/access
A key may also name a model its own way (`Key.Aliases`, `aliases-key`, the row menu's Model names, `magpie gateway-key aliases <id> name=provider/model …`): `/v1/models` for that key lists the name in the model's place, and a request that names it goes to the model. A name is a single word (no space, `*` or `re:`) and a name differing only in case is one name; the model must be one the key may use (`ModelAllowed` over its own models and accounts), and when the key later loses the model the name is refused (403) and unlisted. `identifyCaller` rewrites the name once, where the caller's `Identity` is attached to the request ([`gateway/key_aliases.go`](../../internal/gateway/key_aliases.go)): the JSON body's `model` (any route, a body of up to 32MB that isn't compressed), Gemini's `/v1beta/models/<name>:method`, and `GET /v1/models/<name>`; so every later check sees the real model. Limits: a reply still names the real model, Gemini's list (`/v1beta/models`) is not renamed, a non-JSON or compressed body is not read for a name, and an issued key has no names (`TestGatewayKeyAliasRenamesAModel`).
## Claude Code's Gateway Model Discovery
Claude Code with `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY` set asks `GET /v1/models?limit=1000` of its `ANTHROPIC_BASE_URL` (User-Agent `claude-code/<version>`, `anthropic-version: 2023-06-01`) and puts in `/model` only the ids matching `/(claude|anthropic)/i` (2.1.316's bundle), so a remote magpie's Kimi, GLM or DeepSeek were left out (zent00 on X). For that request alone (`claudeCodeDiscovers` in [`claude_discovery.go`](../../internal/gateway/claude_discovery.go): the User-Agent and the header; never another magpie), a chat model whose id says neither is listed by Claude Desktop's alias `anthropic/magpie-<n>` (`aliasFor`), which `unprefixed` serves as the model for every client before any provider's model of that spelling, and every row's `display_name` is the agents' list name (`provider.LabelsFor`), which `/model` shows. An id Claude Code keeps stays as it is; a name the calling key gives a model stays the user's; a bare-id row (`BareModelIDs`) it wouldn't keep is left out, its full id's row being listed already. `anthropic/<magpie id>` is not used: a provider named `anthropic` (the Anthropic preset's id) serves any model asked of it by that spelling. Every other client sees the ids unchanged (`TestClaudeCodeDiscoveryKeepsEveryModel`).
## Short-lived gateway keys
A gateway key may expire (`access.Key.Expires`), and one issued under another
+62
View File
@@ -0,0 +1,62 @@
package gateway
import (
"net/http"
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/lazyre"
"github.com/yetone/magpie/internal/provider"
)
// Claude Code lists a gateway's models in /model when the user sets
// CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY (its Gateway Model Discovery,
// 2.1.316), but it keeps only the ids that say claude or anthropic. Its
// check (Tvi in its bundle, and its gateway login's pt) is
//
// te.data.data.filter((se) => /(claude|anthropic)/i.test(se.id))
//
// on GET <ANTHROPIC_BASE_URL>/v1/models?limit=1000, sent with
// "anthropic-version: 2023-06-01" and its own User-Agent
// ("claude-code/2.1.316", Xs(), not the claude-cli/ one its turns carry).
// A remote magpie's Kimi, GLM and DeepSeek were left out of /model whole
// (zent00 on X). Shown to that request, a model whose id says neither is
// listed by the alias Claude Desktop is shown it by, anthropic/magpie-<n>
// (aliasFor), which no Claude model's id says and which unprefixed
// serves as the model for every client, before any provider's model of
// that spelling. "anthropic/" put in front of magpie's id would read better,
// but a provider named anthropic (the Anthropic preset's id) serves any
// model asked of it by that spelling. Its label is display_name, the name
// the agents' lists give the model. Every other client, and Claude Code
// asking any other way, is shown the ids as they are.
var claudeCodeKept = lazyre.New(`(?i)(claude|anthropic)`)
// claudeCodeDiscovers is Claude Code's Gateway Model Discovery asking for
// the list: its User-Agent (claude-code/, or claude-cli/ as its turns
// say it) and the anthropic-version header it sends.
func claudeCodeDiscovers(r *http.Request) bool {
if r.Header.Get("anthropic-version") == "" {
return false
}
ua := agentUA(r.Context(), r.Header)
return strings.HasPrefix(ua, "claude-code/") || claudeCodeUA(ua)
}
// claudeCodeListed is the id Claude Code's discovery is shown a row by,
// id being the row's id and e the model it is: id itself when Claude Code
// keeps it or the calling key gives it a name (the user's own, put there
// by aliasNames), else e's alias. A row by a bare id
// (settings.BareModelIDs) that Claude Code wouldn't keep is left out
// (""): it is the model its full id's row is listed by already.
func claudeCodeListed(who access.Identity, e provider.Entry, id string, bare bool) string {
if claudeCodeKept.MatchString(id) {
return id
}
if _, ok := who.AliasOf(id); ok {
return id
}
if bare {
return ""
}
return aliasFor(e.ID)
}
+109
View File
@@ -0,0 +1,109 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/provider"
)
// Claude Code's Gateway Model Discovery keeps only the ids that say
// claude or anthropic (/(claude|anthropic)/i in its 2.1.316 bundle), so a
// remote magpie's Kimi and DeepSeek were in no /model (zent00 on X). Its
// request is shown every model by an id it keeps, each served as the model
// it stands for; an id it keeps already, a provider named anthropic's
// included, stays as it is; and every other client, Claude Code's turns'
// claude-cli/ without the discovery's header among them, is shown the
// ids as they were.
func TestClaudeCodeDiscoveryKeepsEveryModel(t *testing.T) {
fresh(t)
os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755)
data := `{"ds":{"models":{"deepseek-v4":{"id":"deepseek-v4","name":"DeepSeek V4"}}},"km":{"models":{"kimi-k3":{"id":"kimi-k3","name":"Kimi K3"},"claude-opus-4-8":{"id":"claude-opus-4-8","name":"Claude Opus 4.8"}}}}`
if err := os.WriteFile(catalog.CachePath(), []byte(data), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
for _, p := range []provider.Provider{
{ID: "ds", Name: "DeepSeek", Catalog: "ds", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"deepseek-v4"}},
{ID: "km", Name: "Moonshot", Catalog: "km", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"kimi-k3", "claude-opus-4-8"}},
// a provider named anthropic, which serves any model asked of it
// as anthropic/<model>: km's kimi-k3 is never listed so
{ID: "anthropic", Name: "Mine", Key: "k", Anthropic: "http://127.0.0.1:1", Models: []string{"km/kimi-k3"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
list := func(ua string, version bool) map[string]string {
req := httptest.NewRequest("GET", "/v1/models?limit=1000", nil)
req.Header.Set("User-Agent", ua)
if version {
req.Header.Set("anthropic-version", "2023-06-01")
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, req)
var out struct {
Data []struct {
ID string `json:"id"`
Display string `json:"display_name"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
got := map[string]string{}
for _, m := range out.Data {
got[m.ID] = m.Display
}
return got
}
got := list("claude-code/2.1.316", true)
want := map[string]string{
aliasFor("ds/deepseek-v4"): "ds/deepseek-v4",
aliasFor("km/kimi-k3"): "km/kimi-k3",
aliasFor("auto/kimi-k3"): "auto/kimi-k3", // the routing group of both kimi-k3s
// kept as they are
"km/claude-opus-4-8": "km/claude-opus-4-8",
"anthropic/km/kimi-k3": "anthropic/km/kimi-k3",
}
for id, real := range want {
if _, ok := got[id]; !ok {
t.Fatalf("Claude Code's discovery was not shown %s for %s: %v", id, real, got)
}
if !claudeCodeKept.MatchString(id) {
t.Fatalf("Claude Code leaves out %s", id)
}
if u := unprefixed(id); u != real {
t.Fatalf("%s is served as %s, want %s", id, u, real)
}
}
if len(got) != len(want) {
t.Fatalf("Claude Code's discovery was shown %v", got)
}
if d := got[aliasFor("ds/deepseek-v4")]; d != "DeepSeek V4 · DeepSeek" {
t.Fatalf("its /model names the row by display_name, got %q", d)
}
for _, c := range []struct {
ua string
version bool
}{
{"claude-cli/2.1.316 (external, cli)", false},
{"OpenAI/Go 1.0", false},
{"curl/8.0", true},
} {
other := list(c.ua, c.version)
if _, ok := other["ds/deepseek-v4"]; !ok || len(other) != 5 {
t.Fatalf("%s was shown %v", c.ua, other)
}
for id := range other {
if magpieAliasAsked(id) {
t.Fatalf("%s was shown Claude Code's ids: %v", c.ua, other)
}
}
}
}
+14 -3
View File
@@ -1763,12 +1763,21 @@ func (s *Server) listModels(w http.ResponseWriter, r *http.Request) {
labels = append(labels, labels[b.Of])
}
}
// for Claude Code's Gateway Model Discovery: an id it keeps
// (claude_discovery.go)
discovers, who := !magpie && claudeCodeDiscovers(r), access.Caller(r.Context())
for i, e := range rows {
m := modelObject(e)
toolsTold(m, e)
if id, ok := ids[i]; ok {
id, bare := ids[i]
if bare {
m["id"] = id
}
if discovers {
if m["id"] = claudeCodeListed(who, e, m["id"].(string), bare); m["id"] == "" {
continue
}
}
if magpie {
if how := webSearchOf(e, searches); how != "" {
m["web_search"] = how
@@ -1811,8 +1820,10 @@ func (s *Server) listModels(w http.ResponseWriter, r *http.Request) {
// for Cindy: the same name as its display_name, which its
// model discovery (parseModelsListResponse) names a row by
// before name, so magpie's GLM-5.3-Flash of three providers
// read three times the same in its picker (cdredfox on X)
if agent == "cindy" {
// read three times the same in its picker (cdredfox on X);
// and for Claude Code's discovery, whose /model names a row
// by display_name alone
if agent == "cindy" || discovers {
m["display_name"] = labels[i]
}
if agent == "cursor-local" {