groups: a found group is listed as auto/<model id as the vendor spells it>

ZeroClover asked on X: Auto Group ids group/auto-<slug> can't be looked
up on models.dev. A found group is now listed and written as
auto/<model>, e.g. auto/claude-opus-5.5: /v1/models, the catalog, agent
configs, the GUI's Routing page and the CLI. Context and output limits
come from the model's metadata as before.

What stays the same:
- The internal id is still group/auto-<slug> (Group.Ref() gives the
  public one). Every old form is still accepted as input forever:
  provider.CanonicalRef turns auto/<model>[:level][[1m]] into it at the
  gateway (validateModel), keys, stats, affinity and usage, so both ids
  route to the same group and count as one.
- A key's model list allows a model by either id, group/* included
  (allows() in key_models.go).
- Hand-made groups stay group/<id>.
- A provider whose stored id is "auto" keeps its models: while one
  exists, found groups are listed by their old id (AutoRefsOn) and
  auto/<x> means that provider's model. Documented in
  docs/subsystems/gateway-routing.md.

Agent configs: SyncCatalog rewrites a field that holds a found group's
old id (renameFoundGroups), but only while the value is still what
applied.json says magpie wrote; a value the user set stays. A pick by
the old id written now is written as auto/<model> (Apply). Hidden,
picked and ordered model lists saved by the old id hold for the new one
(visible.go), and a bare model id still reaches its found group (bare.go).

Claude Code is given a dotted Claude version dashed (ClaudeSpelled), so
auto/claude-sonnet-4.5 sits in its settings as auto/claude-sonnet-4-5.
That routes to the same group, but with found groups off nothing reads
it back dotted, and Reseat took the field for changed and left the agent
on a group that was gone. Reseat now compares a group pick by its
canonical id (samePick). The old ids had no dots, so this is new with
auto/<model>.

Run at this tree (sandbox HOME, caches pinned):
- gofmt -l: clean. go vet ./...: clean on darwin, GOOS=linux -tags
  nogui, GOOS=windows.
- go test -p 4 -timeout 45m ./...: every package ok except agent and
  gateway, whose failures were the tests' expected ids (updated here)
  and two regressions now fixed (bare ids; desktop models hiding groups
  by prefix). Every failing test passes on rerun. Load average was
  ~210-290 from other sessions throughout.
- Reruns: provider, cli, codexcat ok. internal/gui: only
  TestSetAnswersWhileDevinAndProvidersHang fails (set slow/slow-1 took
  10.19s), and it fails the same in a git-archive export of 33dbdcc52.
- agent and gateway in full, -p 2 -timeout 120m: gateway ok (2996s).
  agent failed four tests that still expected the old ids
  (TestOmp/PiModelsAskedOnTheirNativeAPI, TestReseatFoundGroupsOff,
  TestReseatKeepsAFoundGroupWithAProviderOff); updating them showed the
  Reseat bug above. After the fix, go test -count=1 -timeout 120m
  ./internal/agent/: ok (1000s, load ~160-220).
- GUI files the change reaches, chromium and webkit: group-found-off and
  the routing files pass, except routing-bodies, routing-model-rest,
  routing-keys-fold and routing-request-metrics, which fail the same with
  33dbdcc52's JS.

Broken by hand and watched red, then restored: CanonicalRef in
validateModel (both-ids routing test), allows() (key tests both ways),
the Save refusal and AutoRefsOn checks in Ref/CanonicalRef (provider
named auto), catalog.Lists' preference (models.dev lookup of the part
after auto/), renameFoundGroups' applied.json check and its SyncCatalog
call (user values kept), PublicRef in visible.go, the codexcat prefix,
samePick in Reseat (TestReseatFoundGroupsOff: opus left on the gone
group).
TestBareModelIDsShared was red before the bare.go fix.

Not verified: no real agent, vendor or models.dev client run; no run on
the Windows box. Settings pickers (vision, title model) holding a saved
group/auto-... value may show it as saved. codexcat can't tell a stored
"auto" provider apart, so its models lose the "text only" hint. The
pre-existing reds above are not filed.
This commit is contained in:
yetone
2026-10-20 00:18:51 +08:00
parent ef655acb40
commit 81a24cf8fe
75 changed files with 983 additions and 162 deletions
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -198,7 +198,7 @@ the core. The five other routings are the built-in plugin `rotation`'s.
| `plugins/rotation` | Requires `providers` and `gateway`, `Essential`. Apply registers every `routes.Builtin` and removes them when turned off. `InUse` counts the providers and groups providers.json routes by one of them (`provider.Routings`, the file alone, not the catalog); an unreadable providers.json is an error, so it stays on. The gateway's `KeepFresh` watches providers.json too, so a routing set from the CLI or the TUI turns it on within 2s. Off, the window's routing pickers (the provider editor, the Routing page's pools and groups) offer Smart alone: their options are marked `data-feature="rotation"` (`routingSegs`). | [`rotation.go`](../../plugins/rotation/rotation.go), [`provider.go`](../../internal/provider/provider.go), [`app.js`](../../internal/gui/assets/app.js) |
The user's own routing groups are the `groups` plugin's on this point. The
groups magpie finds (a model two providers serve, `auto-<model>`) stay the
groups magpie finds (a model two providers serve, `auto/<model>`) stay the
core's, as Smart does: they are how a model several providers serve is one
model with failover, which a user has with the Essentials preset,
where `groups` is off. `planGroup` and the walk over a group's members are
+6 -2
View File
@@ -591,6 +591,10 @@ func (a *Agent) Spell(key, v string) (string, error) {
if r := provider.RenamedRef(ref); r != ref {
refs = append(refs, r)
}
// a found group by its id before (group/auto-<slug>) is its auto/<model>
if r := provider.PublicRef(ref); r != ref {
refs = append(refs, r)
}
for _, r := range refs {
for _, o := range opts {
if o.Ref != "" && o.Ref == r {
@@ -623,7 +627,7 @@ func (a *Agent) notOffered(ref string, opts []Option) error {
if slices.ContainsFunc(opts, func(o Option) bool { return Own(o) && strings.HasPrefix(o.Value, pid+"/") }) {
return nil
}
ids := []string{ref, provider.RenamedRef(ref)}
ids := []string{ref, provider.RenamedRef(ref), provider.PublicRef(ref)}
shown, _ := provider.CatalogFor(a.ListsFor())
if slices.ContainsFunc(shown, func(e provider.Entry) bool { return slices.Contains(ids, e.ID) }) {
return nil // shown the agent: a field may offer fewer (Claude Desktop's tiers)
@@ -633,7 +637,7 @@ func (a *Agent) notOffered(ref string, opts []Option) error {
return fmt.Errorf("%s is one of magpie's models, but %s isn't shown it: magpie models %s says why, and magpie visible %s all shows it every model", ref, a.Name, a.ID, a.ID)
}
}
if pid+"/" == provider.GroupPrefix {
if pid+"/" == provider.GroupPrefix || provider.IsGroupRef(ref) {
return fmt.Errorf("magpie has no routing group %s (magpie models lists them)", ref)
}
if p, err := provider.Find(pid); err == nil && (p.ID == pid || slices.Contains(p.Was, pid)) {
+1 -1
View File
@@ -339,7 +339,7 @@ func anteProviderJSON(gw string) map[string]any {
// what it reasons at (anteProviderJSON says why), so its levels are left out
// with the rest of its capabilities.
func anteModelJSON(m catalog.Model) map[string]any {
group := strings.HasPrefix(m.ID, provider.GroupPrefix)
group := provider.IsGroupRef(m.ID)
e := map[string]any{"id": m.ID}
if m.Name != "" && m.Name != m.ID {
e["display_name"] = m.Name
+7 -2
View File
@@ -101,6 +101,11 @@ func (a *Agent) Apply(key, v string) error {
if f == nil {
return nil
}
// a found group named by its old id is written as it is listed now,
// auto/<model> (autoref.go)
if pub, ok := a.publicValue(v); ok {
v = pub
}
was := a.Values()
if err := f.Set(v); err != nil {
return err
@@ -314,8 +319,8 @@ func groupNamed(v string) string {
// magpie set (GroupFor takes it off; so does GroupFinder)
v = strings.TrimSuffix(strings.TrimSpace(v), "[1m]")
v = strings.TrimPrefix(v, magpieID+"/")
if strings.HasPrefix(v, provider.GroupPrefix) {
return v
if provider.IsGroupRef(v) {
return provider.CanonicalRef(v) // auto/<model> and group/auto-<slug> are one group
}
g, _ := provider.GroupFor(v)
return g
+95
View File
@@ -0,0 +1,95 @@
package agent
import (
"strings"
"github.com/yetone/magpie/internal/provider"
)
// A group magpie found is listed as auto/<model> (provider.Group.Ref); it
// was group/auto-<slug>, and agents magpie set to it then still say so.
// The gateway serves that id as it did, but the lists magpie writes into
// an agent's files name the group by its new id only, so an agent that
// checks its model against its list (OpenCode) would find it gone. On its
// next write of the agent's lists (SyncCatalog), magpie moves each field
// it set to the old id onto the new one; a field the user set themselves,
// or changed since magpie set it, stays as they left it.
// setToFoundGroups are the agents magpie set a field of to a found
// group's group/auto-<slug>, by id: those renameFoundGroups looks at, so
// a sync reads no other agent's files for it. None while a provider of
// the user's is called auto, and auto/<model> is its.
func setToFoundGroups() map[string]bool {
if !provider.AutoRefsOn() {
return nil
}
appliedMu.Lock()
defer appliedMu.Unlock()
var out map[string]bool
for id, ap := range appliedLoad() {
for _, v := range ap.Fields {
if strings.Contains(v, provider.GroupPrefix+"auto-") {
if out == nil {
out = map[string]bool{}
}
out[id] = true
break
}
}
}
return out
}
// renameFoundGroups moves a's fields that magpie set to a found group's
// group/auto-<slug> onto the group's auto/<model>, the agent's prefix and
// suffix kept. It answers whether it moved any.
func (a *Agent) renameFoundGroups() bool {
if a.Native != nil || len(a.Fields) == 0 {
return false
}
rec := appliedOf(a.ID).Fields
if len(rec) == 0 {
return false
}
moved := false
vals := a.Values()
for _, f := range a.Fields {
v := vals[f.Key]
// what magpie set, as it set it: a value of the user's own, or
// one changed since, is theirs
if want, ok := rec[f.Key]; !ok || v == "" || v != want || f.Set == nil {
continue
}
now, ok := a.publicValue(v)
if !ok {
continue
}
if a.Apply(f.Key, now) == nil {
moved = true
vals = a.Values()
}
}
return moved
}
// publicValue is v, an agent's value for a field, with a found group's
// group/auto-<slug> in it as the group's auto/<model>: its prefix
// (magpie/), an effort or [1m] after the id, and the agent's own suffix
// kept. ok is false when v names no such group, or one magpie has no
// group for now.
func (a *Agent) publicValue(v string) (string, bool) {
model, suffix, one := a.split(v)
if !one {
return v, false
}
i := strings.Index(model, provider.GroupPrefix+"auto-")
if i < 0 || i > 0 && model[i-1] != '/' {
return v, false
}
ref := model[i:]
pub := provider.PublicRef(ref)
if pub == ref {
return v, false
}
return model[:i] + pub + suffix, true
}
+82
View File
@@ -0,0 +1,82 @@
package agent
import (
"encoding/json"
"testing"
"github.com/yetone/magpie/internal/edit"
"github.com/yetone/magpie/internal/provider"
)
// An agent magpie set to a found group by its old id, group/auto-<slug>,
// is moved onto the group's auto/<model> on the next catalog sync, its
// other settings kept (ZeroClover on X); one whose field the user set
// themselves, or changed since magpie set it, keeps their value.
func TestFoundGroupRenamedOnlyWhereMagpieSetIt(t *testing.T) {
syncHome(t)
// relay and spare both serve glm-4.6: magpie finds the group
if err := provider.Save(provider.Provider{ID: "spare", Name: "Spare", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"glm-4.6"}}); err != nil {
t.Fatal(err)
}
if got := provider.PublicRef("group/auto-glm-4-6"); got != "auto/glm-4.6" {
t.Fatalf("the found group is listed as %q", got)
}
a, err := Find("opencode")
if err != nil {
t.Fatal(err)
}
if err := a.Apply("model", "relay/glm-4.6"); err != nil {
t.Fatal(err)
}
set := a.Values()["model"]
if set == "" {
t.Fatalf("nothing set: %v", a.Values())
}
// what an older magpie wrote and recorded: the group by its old id,
// beside a key of the user's own
old := "magpie/group/auto-glm-4-6"
if err := edit.SetJSON(a.Path, edit.KV{Path: "model", Value: old}, edit.KV{Path: "theme", Value: "mine"}); err != nil {
t.Fatal(err)
}
record(a.ID, "model", old)
SyncCatalog()
if got := a.Values()["model"]; got != "magpie/auto/glm-4.6" {
t.Fatalf("magpie's own value became %q, want magpie/auto/glm-4.6\n%s", got, readFile(a.Path))
}
if got := appliedOf(a.ID).Fields["model"]; got != "magpie/auto/glm-4.6" {
t.Errorf("applied.json holds %q", got)
}
var doc map[string]any
if err := json.Unmarshal([]byte(readFile(a.Path)), &doc); err != nil || doc["theme"] != "mine" {
t.Errorf("the user's own key: %v %v", doc["theme"], err)
}
if d := a.Drift(); d != nil {
t.Errorf("drift after the move: %+v", d)
}
// the user's own value, the group by its old id at an effort of their
// choosing, where magpie had set the group plain: theirs, kept
theirs := "magpie/group/auto-glm-4-6:high"
if err := edit.SetJSON(a.Path, edit.KV{Path: "model", Value: theirs}); err != nil {
t.Fatal(err)
}
record(a.ID, "model", old)
SyncCatalog()
if got := a.Values()["model"]; got != theirs {
t.Fatalf("the user's %q became %q", theirs, got)
}
// and one magpie never set: no record of the field at all
appliedMu.Lock()
m := appliedLoad()
delete(m, a.ID)
appliedSave(m)
appliedMu.Unlock()
if err := edit.SetJSON(a.Path, edit.KV{Path: "model", Value: old}); err != nil {
t.Fatal(err)
}
SyncCatalog()
if got := a.Values()["model"]; got != old {
t.Fatalf("the user's own %q became %q", old, got)
}
}
+1 -1
View File
@@ -61,7 +61,7 @@ func TestClaudePickerListsRoutingGroups(t *testing.T) {
t.Fatal(err)
}
main, _ := edit.GetJSON(path, "model")
if !strings.HasPrefix(main, "group/auto-deepseek-v4-1-flash") {
if !strings.HasPrefix(main, "auto/deepseek-v4.1-flash") {
t.Fatalf("model: %q\n%s", main, readFile(path))
}
opts := picker()
+1 -1
View File
@@ -1665,7 +1665,7 @@ func codexOwnViaMagpie(model string) string {
// codexOwnOf is the model of Codex's own a catalog id serves on a ChatGPT
// account (codexOwnViaMagpie's way back); "" for any other.
func codexOwnOf(id string) string {
if !isMagpie(id) || strings.HasPrefix(id, provider.GroupPrefix) {
if !isMagpie(id) || provider.IsGroupRef(id) {
return ""
}
p, model, ok := provider.Resolve(id)
+4 -4
View File
@@ -38,11 +38,11 @@ func TestCodexGroupByItsModelName(t *testing.T) {
}
path := filepath.Join(home, ".codex", "config.toml")
cfg := read()
if !strings.Contains(cfg, `model = "group/auto-gpt-6-1-sol"`) {
if !strings.Contains(cfg, `model = "auto/gpt-6.1-sol"`) {
t.Fatalf("set:\n%s", cfg)
}
// Codex names the group's model by its own name, nothing else changed
os.WriteFile(path, []byte(strings.Replace(cfg, `model = "group/auto-gpt-6-1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644)
os.WriteFile(path, []byte(strings.Replace(cfg, `model = "auto/gpt-6.1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644)
if !cx.Wired() {
t.Errorf("auth %q: not wired on gpt-6.1-sol:\n%s", auth, read())
}
@@ -58,7 +58,7 @@ func TestCodexGroupByItsModelName(t *testing.T) {
// has; beside the ChatGPT sign-in either is a pick in Codex's /model
// that still goes through magpie, not a change from outside (#2424)
for _, m := range []string{"gpt-6.1", "gpt-5.5"} {
os.WriteFile(path, []byte(strings.Replace(cfg, `model = "group/auto-gpt-6-1-sol"`, `model = "`+m+`"`, 1)), 0o644)
os.WriteFile(path, []byte(strings.Replace(cfg, `model = "auto/gpt-6.1-sol"`, `model = "`+m+`"`, 1)), 0o644)
d := cx.Drift()
if auth != "" && d != nil {
t.Errorf("auth %q: %s beside the sign-in: %+v", auth, m, d)
@@ -84,7 +84,7 @@ func TestCodexGroupByItsModelNameDisconnect(t *testing.T) {
t.Fatal(err)
}
path := filepath.Join(home, ".codex", "config.toml")
os.WriteFile(path, []byte(strings.Replace(read(), `model = "group/auto-gpt-6-1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644)
os.WriteFile(path, []byte(strings.Replace(read(), `model = "auto/gpt-6.1-sol"`, `model = "gpt-6.1-sol"`, 1)), 0o644)
if err := cx.Disconnect(); err != nil {
t.Fatal(err)
}
+1 -1
View File
@@ -155,7 +155,7 @@ func TestInferredGroupImagesReachAgentCatalogs(t *testing.T) {
if err := catalog.SaveLive("unknown", "https://example.test/v1", []catalog.Model{{ID: "claude-sonnet-4-5"}}); err != nil {
t.Fatal(err)
}
id := "group/auto-claude-sonnet-4-5"
id := "auto/claude-sonnet-4-5"
oc := magpieProviderJSON("opencode").(map[string]any)["models"].(map[string]any)[id].(map[string]any)
if _, ok := oc["attachment"]; ok || !reflect.DeepEqual(oc["modalities"].(map[string]any)["input"], []string{"text", "image"}) {
t.Fatalf("OpenCode group image input: %v", oc)
+4 -1
View File
@@ -54,7 +54,10 @@ func (a *Agent) Models() []string {
func modelRef(v string) string {
v = strings.TrimSuffix(strings.TrimSpace(v), "[1m]")
v = strings.TrimPrefix(v, magpieID+"/")
if strings.HasPrefix(v, provider.GroupPrefix) || isMagpie(v) {
if provider.IsGroupRef(v) {
return provider.CanonicalRef(v) // a found group by one id, whichever it was set to
}
if isMagpie(v) {
return v
}
return ""
+1 -1
View File
@@ -68,7 +68,7 @@ func TestOmpModelsAskedOnTheirNativeAPI(t *testing.T) {
"anth/claude-sonnet-5": "anthropic-messages",
"anth/claude-sonnet-4-5": "anthropic-messages",
"anth/kimi-k3": "anthropic-messages",
"group/auto-gpt-5-5": "openai-responses",
"auto/gpt-5.5": "openai-responses",
"group/mixed": nil,
} {
e, ok := entries[id]
+1 -1
View File
@@ -62,7 +62,7 @@ func TestPiModelsAskedOnTheirNativeAPI(t *testing.T) {
"relay/glm-4.6": nil,
"anth/claude-sonnet-5": "anthropic-messages",
"anth/kimi-k3": "anthropic-messages",
"group/auto-gpt-5-5": "openai-responses",
"auto/gpt-5.5": "openai-responses",
"group/gpts": "openai-responses",
"group/outer": "openai-responses",
"group/mixed": nil,
+19 -3
View File
@@ -98,7 +98,7 @@ func Reseat(change func() error) ([]Move, error) {
f := p.a.Field(p.key)
vals := p.a.Values()
// changed already, with another field
if f == nil || vals[p.key] != p.val {
if f == nil || !p.a.samePick(vals[p.key], p.val) {
continue
}
var to Option
@@ -121,6 +121,22 @@ func Reseat(change func() error) ([]Move, error) {
return moves, nil
}
// samePick: a field's value now is still the pick read before the change.
// A found group's auto/<model> reads back as written while the group is
// served, but Claude Code is given a dotted Claude version dashed
// (ClaudeSpelled), and with the group gone nothing takes
// auto/claude-sonnet-4-5 back to auto/claude-sonnet-4.5. Both are the one
// group by its canonical id, so the agent is still moved off it.
func (a *Agent) samePick(now, before string) bool {
if now == before {
return true
}
m1, s1, one1 := a.split(now)
m2, s2, one2 := a.split(before)
return one1 && one2 && s1 == s2 && provider.IsGroupRef(m1) &&
provider.CanonicalRef(m1) == provider.CanonicalRef(m2)
}
// served: magpie takes requests for the catalog model.
func served(ref string) bool {
_, _, ok := provider.Resolve(ref)
@@ -142,7 +158,7 @@ func sameModel(opts []Option, ref string) Option {
return Option{}
}
for _, o := range opts {
if o.Ref == "" || strings.HasPrefix(o.Ref, provider.GroupPrefix) || !served(o.Ref) {
if o.Ref == "" || provider.IsGroupRef(o.Ref) || !served(o.Ref) {
continue
}
if pid, m, _ := strings.Cut(o.Ref, "/"); provider.AutoGroupOf(pid, m) == gid {
@@ -158,7 +174,7 @@ func sameModel(opts []Option, ref string) Option {
want := modelKey(model)
var alike Option
for _, o := range opts {
if o.Ref == "" || strings.HasPrefix(o.Ref, provider.GroupPrefix) || !served(o.Ref) {
if o.Ref == "" || provider.IsGroupRef(o.Ref) || !served(o.Ref) {
continue
}
_, m, _ := strings.Cut(o.Ref, "/")
+21 -11
View File
@@ -68,12 +68,19 @@ func mustFind(t *testing.T, id string) *Agent {
}
func mustApply(t *testing.T, a *Agent, key, v string) {
t.Helper()
mustApplyAs(t, a, key, v, v)
}
// mustApplyAs applies v and expects want written: a found group picked by
// its old id is written as auto/<model>
func mustApplyAs(t *testing.T, a *Agent, key, v, want string) {
t.Helper()
if err := a.Apply(key, v); err != nil {
t.Fatalf("%s %s=%s: %v", a.ID, key, v, err)
}
if got := a.Field(key).Get(); got != v {
t.Fatalf("%s %s: %q, want %q", a.ID, key, got, v)
if got := a.Field(key).Get(); got != want {
t.Fatalf("%s %s: %q, want %q", a.ID, key, got, want)
}
}
@@ -214,9 +221,12 @@ func TestReseatUnmovable(t *testing.T) {
func TestReseatFoundGroupsOff(t *testing.T) {
reseatHome(t)
c, h := mustFind(t, "claude"), mustFind(t, "hermes")
mustApply(t, c, "model", "group/auto-gpt-5")
mustApply(t, c, "opus", "group/auto-claude-sonnet-4-5")
mustApply(t, h, "model", "magpie/group/auto-gpt-5")
// picked by the old ids, written as they are listed now. Opus's
// auto/claude-sonnet-4.5 is given Claude Code dashed, and with the
// group gone reads back as auto/claude-sonnet-4-5: still moved
mustApplyAs(t, c, "model", "group/auto-gpt-5", "auto/gpt-5")
mustApplyAs(t, c, "opus", "group/auto-claude-sonnet-4-5", provider.PublicRef("group/auto-claude-sonnet-4-5"))
mustApplyAs(t, h, "model", "magpie/group/auto-gpt-5", "magpie/auto/gpt-5")
moves, err := Reseat(func() error { return provider.SetAutoGroups(false) })
if err != nil {
t.Fatal(err)
@@ -229,7 +239,7 @@ func TestReseatFoundGroupsOff(t *testing.T) {
if got := h.Field("model").Get(); got != "magpie/cop/gpt-5" {
t.Errorf("hermes: %q", got)
}
if len(moves) != 3 || moves[0].From != "group/auto-gpt-5" || moves[0].To != "cop/gpt-5" {
if len(moves) != 3 || moves[0].From != "auto/gpt-5" || moves[0].To != "cop/gpt-5" {
t.Errorf("moves: %+v", moves)
}
// on again, nobody is moved back or elsewhere
@@ -246,17 +256,17 @@ func TestReseatFoundGroupsOff(t *testing.T) {
func TestReseatKeepsAFoundGroupWithAProviderOff(t *testing.T) {
reseatHome(t)
c, h := mustFind(t, "claude"), mustFind(t, "hermes")
mustApply(t, c, "model", "group/auto-gpt-5")
mustApplyAs(t, c, "model", "group/auto-gpt-5", "auto/gpt-5")
mustApply(t, c, "haiku", "cop/only-here")
mustApply(t, h, "model", "magpie/group/auto-gpt-5")
mustApplyAs(t, h, "model", "magpie/group/auto-gpt-5", "magpie/auto/gpt-5")
moves, err := Reseat(func() error { return provider.SetOff("cop", true) })
if err != nil {
t.Fatal(err)
}
if got := c.Field("model").Get(); got != "group/auto-gpt-5" {
if got := c.Field("model").Get(); got != "auto/gpt-5" {
t.Errorf("claude model with cop off: %q", got)
}
if got := h.Field("model").Get(); got != "magpie/group/auto-gpt-5" {
if got := h.Field("model").Get(); got != "magpie/auto/gpt-5" {
t.Errorf("hermes with cop off: %q", got)
}
if len(moves) != 1 || moves[0].Field != "haiku" || moves[0].From != "cop/only-here" {
@@ -269,7 +279,7 @@ func TestReseatKeepsAFoundGroupWithAProviderOff(t *testing.T) {
if moves, err = Reseat(func() error { return provider.SetOff("cop", false) }); err != nil || len(moves) != 0 {
t.Fatalf("on again: %+v %v", moves, err)
}
if got := c.Field("model").Get(); got != "group/auto-gpt-5" {
if got := c.Field("model").Get(); got != "auto/gpt-5" {
t.Errorf("claude model on again: %q", got)
}
}
+5
View File
@@ -45,10 +45,15 @@ func SyncCatalog() {
// the catalog built once for every agent's lists, not for each
// look-up of each (thousands at magpie's start, with 30 providers)
release := provider.Hold()
renaming := setToFoundGroups()
for _, a := range All() {
if a.Sync != nil {
_ = synced(a.Sync)
}
// a field magpie set to a found group's id before (autoref.go)
if renaming[a.ID] {
a.renameFoundGroups()
}
}
release()
syncing.Lock()
+8
View File
@@ -964,6 +964,14 @@ func Knows(id string) bool {
return ContextOf(id) > 0 || len(EffortsOf(id)) > 0 || Thinks(id)
}
// Lists reports whether models.dev lists a model by this very id (its
// last part, any case), not one found by another spelling: claude-opus-5.5
// only when that is how one of its providers spells it.
func Lists(id string) bool {
load()
return listed[bareID(id)]
}
// SeesImages reports whether models.dev says a model of this id takes
// images, as most of the providers it lists serving it do; for a vendor it
// doesn't list, serving a model it knows from others ("z-ai/glm-5.3" is
+12 -12
View File
@@ -260,7 +260,7 @@ func memberResolver(keep []string) func(string) (string, error) {
}
if model, effort := provider.MemberEffort(id); effort != "" {
// a model at an effort of its own: the model as any other is
if strings.HasPrefix(model, provider.GroupPrefix) {
if provider.IsGroupRef(model) {
return "", fmt.Errorf("%s is a group: its models reason as it says, so it takes no :%s", model, effort)
}
m, err := resolve(model)
@@ -269,8 +269,8 @@ func memberResolver(keep []string) func(string) (string, error) {
}
return provider.WithMemberEffort(m, effort), nil
}
if gid, ok := strings.CutPrefix(id, provider.GroupPrefix); ok {
// a group in the group: SaveGroup refuses one it would be in itself through
if gid, ok := strings.CutPrefix(provider.CanonicalRef(id), provider.GroupPrefix); ok {
// a group in the group: auto/<model> as group/auto-<slug>;: SaveGroup refuses one it would be in itself through
for _, g := range provider.Groups() {
if strings.EqualFold(g.ID, gid) && !g.Hidden {
return provider.GroupPrefix + g.ID, nil
@@ -583,7 +583,7 @@ func pickMember(members []string, v string) (string, error) {
// findGroup looks a group up by its id, its catalog id or its name.
func findGroup(ref string) (provider.Group, error) {
all := provider.Groups()
ref = strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/"), provider.GroupPrefix)
ref = strings.TrimPrefix(provider.CanonicalRef(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/")), provider.GroupPrefix)
for _, match := range []func(provider.Group) bool{
func(g provider.Group) bool { return g.ID == ref },
func(g provider.Group) bool { return strings.EqualFold(g.ID, ref) },
@@ -647,7 +647,7 @@ func groupCmd(args []string) error {
if err != nil {
return err
}
fmt.Println(green.Render("✓"), verb, bold.Render(g.Name), muted.Render("· agents pick it as "+provider.GroupPrefix+g.ID))
fmt.Println(green.Render("✓"), verb, bold.Render(g.Name), muted.Render("· agents pick it as "+g.Ref()))
return showGroup(g)
case "set", "edit":
if len(rest) < 2 {
@@ -660,7 +660,7 @@ func groupCmd(args []string) error {
fmt.Println(green.Render("✓"), "saved", bold.Render(g.Name))
if slices.ContainsFunc(rest[1:], func(kv string) bool { return strings.HasPrefix(strings.ToLower(kv), "name=") }) {
// a new name isn't a new id: say what agents still ask for
fmt.Println(muted.Render(" its id stays " + g.ID + ": agents ask for " + provider.GroupPrefix + g.ID + " (a client given the name may ask by the name too)"))
fmt.Println(muted.Render(" its id stays " + g.ID + ": agents ask for " + g.Ref() + " (a client given the name may ask by the name too)"))
}
return showGroup(g)
case "rm", "remove", "delete":
@@ -704,7 +704,7 @@ func groupCmd(args []string) error {
if err != nil {
return err
}
fmt.Println(green.Render("✓"), "copied", bold.Render(src.Name), "to", bold.Render(g.Name), muted.Render("· agents pick it as "+provider.GroupPrefix+g.ID))
fmt.Println(green.Render("✓"), "copied", bold.Render(src.Name), "to", bold.Render(g.Name), muted.Render("· agents pick it as "+g.Ref()))
return showGroup(g)
case "template", "templates", "tpl":
return templateCmd(rest)
@@ -814,7 +814,7 @@ func setGroup(ref string, pairs []string) (provider.Group, error) {
// removedOnly is a removed found group magpie doesn't find now (its model
// is down to one provider): only its record is left, to keep it removed.
func removedOnly(ref string) (string, bool) {
ref = strings.TrimPrefix(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/"), provider.GroupPrefix)
ref = strings.TrimPrefix(provider.CanonicalRef(strings.TrimPrefix(strings.TrimSpace(ref), "magpie/")), provider.GroupPrefix)
for _, id := range provider.RemovedGroups() {
if strings.EqualFold(id, ref) {
return id, true
@@ -1001,7 +1001,7 @@ func groups() error {
var rows []row
w := [3]int{}
for _, g := range shown {
r := row{name: bold.Render(g.Name), id: muted.Render(provider.GroupPrefix + g.ID)}
r := row{name: bold.Render(g.Name), id: muted.Render(g.Ref())}
if g.Auto {
r.name += " " + faint.Render("found")
}
@@ -1077,7 +1077,7 @@ func groups() error {
func showGroup(g provider.Group) error {
kv := func(k, v string) { fmt.Printf(" %s %s\n", muted.Render(pad(k, 9)), v) }
head := bold.Render(g.Name) + muted.Render(" "+provider.GroupPrefix+g.ID)
head := bold.Render(g.Name) + muted.Render(" "+g.Ref())
if g.Auto {
head += faint.Render(" found by magpie — changing it makes it yours")
}
@@ -1173,7 +1173,7 @@ func showGroup(g provider.Group) error {
// <id> +<model>` puts right (MOMO on Discord: opencode-go/deepseek-flash).
func whyNotServed(member string) string {
pid, model, ok := strings.Cut(member, "/")
if !ok || strings.HasPrefix(member, provider.GroupPrefix) {
if !ok || provider.IsGroupRef(member) {
return "not served"
}
p, err := provider.Find(pid)
@@ -1218,6 +1218,6 @@ func templateCmd(rest []string) error {
if err != nil {
return err
}
fmt.Println(green.Render("✓"), "added", bold.Render(g.Name), muted.Render("· agents pick it as "+provider.GroupPrefix+g.ID))
fmt.Println(green.Render("✓"), "added", bold.Render(g.Name), muted.Render("· agents pick it as "+g.Ref()))
return showGroup(g)
}
+1 -1
View File
@@ -236,7 +236,7 @@ func usesByProvider() map[string][]string {
}
v := a.Fields[0].Get()
v = strings.TrimPrefix(v, "magpie/")
if strings.HasPrefix(v, provider.GroupPrefix) {
if provider.IsGroupRef(v) {
continue // a routing group, of no one provider
}
if pid, _, ok := strings.Cut(v, "/"); ok {
+1 -1
View File
@@ -105,7 +105,7 @@ func visibleCmd(args []string) error {
} else {
known := visibleNames()
for i, n := range list {
n = strings.TrimPrefix(n, provider.GroupPrefix)
n = strings.TrimPrefix(provider.CanonicalRef(n), provider.GroupPrefix)
if !slices.ContainsFunc(known, func(k string) bool { return strings.EqualFold(k, n) }) {
return fmt.Errorf("%s is no family, provider or group (families: %s; magpie provider set <id> family=%s makes one)",
n, orNone(provider.Families()), n)
+1 -1
View File
@@ -239,7 +239,7 @@ func entriesAt(ms []catalog.Model, after int, effort string) []any {
}
if m.Images {
e.Modalities = append(e.Modalities, "image")
} else if !strings.HasPrefix(m.ID, "group/") {
} else if !strings.HasPrefix(m.ID, "group/") && !strings.HasPrefix(m.ID, "auto/") { // a routing group, a found one as auto/<model>
// Codex turns a pasted image away itself, saying only that the
// model doesn't take images; /model says where that is changed
// (KimYx0207 on X). The description still ends " via magpie",
+5 -4
View File
@@ -187,15 +187,16 @@ func TestCodexCatalogSaysTextOnly(t *testing.T) {
{ID: "probe/text", Name: "Text"},
{ID: "probe/sees", Name: "Sees", Images: true},
{ID: "group/words", Name: "Words"},
{ID: "auto/found", Name: "Found"}, // a group magpie found, as it is listed
}), &got)
if len(got.Models) != 3 {
if len(got.Models) != 4 {
t.Fatalf("%+v", got.Models)
}
text, sees, group := got.Models[0], got.Models[1], got.Models[2]
text, sees, group, found := got.Models[0], got.Models[1], got.Models[2], got.Models[3]
if !strings.Contains(text.Description, "text only") || !strings.Contains(text.Description, "Names & levels") || !catalog.MagpieAdded("", text.Slug, text.Description) {
t.Errorf("text-only model: %q", text.Description)
}
if sees.Description != "Sees via magpie" || group.Description != "Words via magpie" {
t.Errorf("a model that sees, and a group: %q, %q", sees.Description, group.Description)
if sees.Description != "Sees via magpie" || group.Description != "Words via magpie" || found.Description != "Found via magpie" {
t.Errorf("a model that sees, a group and a found one: %q, %q, %q", sees.Description, group.Description, found.Description)
}
}
+1 -1
View File
@@ -92,7 +92,7 @@ func advisorModel(p provider.Provider, model string, wires map[string]string) (s
if model == "" {
return "", false
}
if q, m, ok := provider.Resolve(model); ok && !strings.HasPrefix(model, provider.GroupPrefix) {
if q, m, ok := provider.Resolve(model); ok && !provider.IsGroupRef(model) {
if q.ID != p.ID {
return "", false
}
+89
View File
@@ -0,0 +1,89 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/provider"
)
// A group magpie found is listed as auto/<model> (ZeroClover on X), and
// served by that id and by its old group/auto-<slug> alike: one group, one
// route, one name in the usage log, whichever an agent sent.
func TestFoundGroupServedByBothIDs(t *testing.T) {
fresh(t)
a, b := &keyed{}, &keyed{}
serveOn(t, "a", "ka", []string{"glm-5.3"}, a)
serveOn(t, "b", "kb", []string{"glm-5.3"}, b)
s := New()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
var list struct{ Data []struct{ ID string } }
if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil {
t.Fatal(err)
}
var ids []string
for _, m := range list.Data {
ids = append(ids, m.ID)
}
if !slices.Contains(ids, "auto/glm-5.3") || slices.Contains(ids, "group/auto-glm-5-3") {
t.Fatalf("/v1/models: %v", ids)
}
for _, model := range []string{"auto/glm-5.3", "group/auto-glm-5-3", "auto/GLM-5.3", "auto/glm-5-3"} {
code, body := postAs(t, s, "", `{"model":"`+model+`","messages":[{"role":"user","content":"hi `+model+`"}]}`)
if code != 200 {
t.Fatalf("%s: %d %s", model, code, body)
}
r := s.trace.routes[len(s.trace.routes)-1]
if r.Group == nil || r.Group.ID != "auto-glm-5-3" {
t.Fatalf("%s, not routed as the found group: %+v", model, r)
}
if u := lastUsage(t); u.Requested != "group/auto-glm-5-3" {
t.Errorf("%s logged as asked for %q", model, u.Requested)
}
}
}
// A gateway key held to a found group passes for it by either id: one
// naming auto/<model>, as the lists now give it, for an agent left on the
// old id, and one naming the old id, or group/*, for auto/<model>. auto/*
// holds every found group by its new id. A key held to another group gets
// neither.
func TestKeyHeldToAFoundGroupByEitherID(t *testing.T) {
fresh(t)
serveOn(t, "a", "ka", []string{"glm-5.3", "x"}, &keyed{})
serveOn(t, "b", "kb", []string{"glm-5.3", "x"}, &keyed{})
if err := provider.SaveGroup(provider.Group{Name: "Other", Members: []string{"a/x"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
keys, secrets := newCaller(t, "k")
post := func(model string) int {
t.Helper()
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+model+`","messages":[{"role":"user","content":"hi"}]}`))
req.Header.Set("Authorization", "Bearer "+secrets[0])
s.Handler().ServeHTTP(rec, req)
return rec.Code
}
for _, held := range [][]string{{"auto/glm-5.3"}, {"auto/glm-5-3"}, {"group/auto-glm-5-3"}, {"group/*"}, {"auto/*"}, {"group/other"}} {
if _, err := access.Update("models-key", access.Change{Key: keys[0].ID, Models: held}); err != nil {
t.Fatal(err)
}
want := 200
if held[0] == "group/other" {
want = 403
}
for _, model := range []string{"auto/glm-5.3", "group/auto-glm-5-3"} {
if code := post(model); code != want {
t.Errorf("a key held to %v asking for %s: %d, want %d", held, model, code, want)
}
}
}
}
+2 -2
View File
@@ -28,7 +28,7 @@ import (
// one switched off or gone), with its status.
func decisionGroupOf(asked string) (g provider.Group, ms []provider.Member, ok bool, status int, err error) {
ref := strings.TrimSpace(asked)
explicit := strings.HasPrefix(ref, provider.GroupPrefix)
explicit := provider.IsGroupRef(ref)
if !explicit {
gid, found := provider.GroupFor(ref)
if !found {
@@ -262,7 +262,7 @@ func (e decideRefused) Unwrap() error { return e.err }
// answers, the one that failed resting as it would for a chat. ok is false
// when model names no decision group.
func (s *Server) askDecisionGroup(model string, intents []string, prev before, effort bool, text string) (v verdict, ok bool, err error) {
if !strings.HasPrefix(model, provider.GroupPrefix) {
if !provider.IsGroupRef(model) {
return verdict{}, false, nil
}
g, ms, found := provider.FindGroup(model)
+1 -1
View File
@@ -75,7 +75,7 @@ func TestClaudeDesktopPickedModels(t *testing.T) {
// its provider after it
hide := []string{"relay/deepseek-v4.1-flash", "opencode-go/glm-5"}
for id := range all {
if strings.HasPrefix(id, provider.GroupPrefix) {
if provider.IsGroupRef(id) {
hide = append(hide, id)
}
}
+1 -1
View File
@@ -567,7 +567,7 @@ func (s *Server) images(edit bool) http.HandlerFunc {
// other names a model on its own.
func drawingGroup(asked string, p provider.Provider, model string) (provider.Group, []provider.Member, bool) {
ref := asked
if !strings.HasPrefix(ref, provider.GroupPrefix) {
if !provider.IsGroupRef(ref) {
gid, ok := provider.GroupFor(ref)
if !ok {
return provider.Group{}, nil, false
+5 -3
View File
@@ -190,7 +190,7 @@ func claudeTierStandIn(r *http.Request, agent, asked string) string {
// session that started before it was switched off still asks for the model
// its agent was then on, and the agent has been moved since (#200).
func unserved(asked string) bool {
if asked == "" || strings.HasPrefix(asked, provider.GroupPrefix) {
if asked == "" || provider.IsGroupRef(asked) {
return false
}
if _, ok := provider.GroupFor(asked); ok {
@@ -1141,7 +1141,7 @@ func (s *Server) model(w http.ResponseWriter, r *http.Request) {
id := unprefixed(r.PathValue("id"))
shown := keyAllowed(r, provider.Catalog())
for _, e := range shown {
if e.ID == id {
if e.ID == id || e.Group != "" && provider.SameRef(e.ID, id) {
if agentOf(r) == ScienceID {
// by the alias it asked by, which it keeps what it reads
// under
@@ -6165,7 +6165,9 @@ func validateModel(model string) (string, error) {
// otherwise reads as Claude Opus 4 (provider.ClaudeSpelled)
return real, nil
}
return unflat(model), nil
// a found group's auto/<model> as group/auto-<slug>, the one id its
// key limits, routing, stats and usage rows know it by
return provider.CanonicalRef(unflat(model)), nil
}
// unflat is the catalog id a flat one stands for (provider.Unflat): MiniMax
+3 -3
View File
@@ -969,8 +969,8 @@ func TestModelsListReasoning(t *testing.T) {
t.Fatal(err)
}
want := map[string]string{
"a/sol": "low,medium,high,max", "b/sol": "medium,high", "group/auto-sol": "medium,high",
"a/mixed": "low,high", "b/mixed": "", "group/auto-mixed": "low,high", "a/plain": "",
"a/sol": "low,medium,high,max", "b/sol": "medium,high", "auto/sol": "medium,high",
"a/mixed": "low,high", "b/mixed": "", "auto/mixed": "low,high", "a/plain": "",
}
// a group reasons when any member does: b/mixed has no levels and a
// list that says nothing of reasoning, but a/mixed does, so the group
@@ -978,7 +978,7 @@ func TestModelsListReasoning(t *testing.T) {
// at a/mixed's levels: b/mixed is sent no reasoning ask (quiet.go), so
// it doesn't take them away (#2127: Codex showed no effort control for
// a group with none, and ran it at medium)
reasoning := map[string]bool{"group/auto-mixed": true}
reasoning := map[string]bool{"auto/mixed": true}
for _, m := range response.Data {
expected, ok := want[m.ID]
if !ok {
+1 -1
View File
@@ -240,7 +240,7 @@ func TestRoutingGroups(t *testing.T) {
ids = append(ids, e.ID)
}
}
if got := strings.Join(ids, " "); got != "group/auto-m a/m a/only-a b/vendor/m" {
if got := strings.Join(ids, " "); got != "auto/m a/m a/only-a b/vendor/m" {
t.Fatalf("catalog: %s", got)
}
if err := provider.SaveGroup(provider.Group{Name: "Mine", Members: []string{"b/vendor/m", "a/only-a"}, Routing: provider.Ordered}); err != nil {
+1 -1
View File
@@ -26,7 +26,7 @@ func TestGroupsOnAndOff(t *testing.T) {
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
list := rec.Body.String()
if strings.Contains(list, `"group/mine"`) != mine || !strings.Contains(list, `"group/auto-m"`) {
if strings.Contains(list, `"group/mine"`) != mine || !strings.Contains(list, `"auto/m"`) {
t.Fatalf("%s: models %s", when, list)
}
code, body := postAs(t, s, "", `{"model":"group/mine","messages":[{"role":"user","content":"hi"}]}`)
+1 -1
View File
@@ -357,7 +357,7 @@ func TestGroupWithUnknownImageCapabilityReachesUpstream(t *testing.T) {
}
}
for _, e := range provider.Catalog() {
if e.ID == "group/auto-claude-sonnet-4-5" {
if e.ID == "auto/claude-sonnet-4-5" {
if !e.Images || e.ImageInput == nil || !*e.ImageInput {
t.Fatalf("group image capability: %+v", e)
}
+33 -6
View File
@@ -16,9 +16,10 @@ import (
// is refused before any provider is asked. A model is held to by its
// provider's id and its own, "<provider>/<model>", whatever the agent
// called it. A routing group passes when the key names it, "group/<id>"
// (or "group/*", every group), and then every member of it does, through
// it; else only when every model in it does. A group the key names inside
// one it doesn't counts for its own members.
// (or "group/*", every group), a group magpie found by its auto/<model>
// too, either id passing for the other (allows), and then every member of
// it does, through it; else only when every model in it does. A group the
// key names inside one it doesn't counts for its own members.
// magpieChoseKey marks, in a request's context, a call magpie makes for a
// model the user picked in its settings rather than the caller (a web
@@ -52,20 +53,46 @@ func accountHolds(r *http.Request) (access.Identity, bool) {
return who, len(who.Accounts) > 0
}
// allows is who.Allows, a found group named by either of its ids: a key
// held to auto/<model> (as the model lists give it, any spelling of the
// model) may use group/auto-<slug>, the id the gateway routes it by, and
// one held to group/auto-<slug> or group/* the auto/<model> an agent asks
// for, which the gateway takes back to that id (validateModel). A pattern
// of auto/ ids ("auto/*") holds to the groups' auto/<model>.
func allows(who access.Identity, ids ...string) bool {
if who.Allows(ids...) {
return true
}
for _, id := range ids {
if !strings.HasPrefix(id, provider.GroupPrefix+"auto-") {
continue
}
if pub := provider.PublicRef(id); pub != id && who.Allows(pub) {
return true
}
for _, p := range who.Models {
if !strings.Contains(p, "*") && strings.HasPrefix(p, provider.AutoPrefix) && strings.EqualFold(provider.CanonicalRef(p), id) {
return true
}
}
}
return false
}
// modelAllowed says the key may use provider p's model.
func modelAllowed(who access.Identity, p provider.Provider, model string) bool {
return who.Allows(p.ID + "/" + model)
return allows(who, p.ID+"/"+model)
}
// memberAllowed says the key may use a routing group's member: the model,
// or a group it is reached through that the key names.
func memberAllowed(who access.Identity, m provider.Member) bool {
return who.Allows(append([]string{m.Provider.ID + "/" + m.Model}, m.Path...)...)
return allows(who, append([]string{m.Provider.ID + "/" + m.Model}, m.Path...)...)
}
// groupNamed says the key names the routing group g itself.
func groupNamed(who access.Identity, g provider.Group) bool {
return g.ID != "" && who.Allows(provider.GroupPrefix+g.ID)
return g.ID != "" && (allows(who, provider.GroupPrefix+g.ID) || who.Allows(g.Ref()))
}
// groupAllowed says the key may use the routing group g: it names it, or
+2 -2
View File
@@ -34,7 +34,7 @@ func TestProviderOff(t *testing.T) {
}
return strings.Join(ids, " ")
}
const all = "group/mine group/auto-m a/m a/only-a b/vendor/m b/only-b"
const all = "group/mine auto/m a/m a/only-a b/vendor/m b/only-b"
if got := catalog(); got != all {
t.Fatalf("catalog: %s", got)
}
@@ -46,7 +46,7 @@ func TestProviderOff(t *testing.T) {
if err != nil || !pb.Off || pb.Key != "kb" {
t.Fatalf("switched off, b is kept with its key: %+v %v", pb, err)
}
if got := catalog(); got != "group/mine group/auto-m a/m a/only-a" {
if got := catalog(); got != "group/mine auto/m a/m a/only-a" {
t.Fatalf("catalog with b off: %s", got)
}
if _, _, ok := provider.Resolve("b/vendor/m"); ok {
+2 -2
View File
@@ -392,7 +392,7 @@ func Searchers() []SearcherChoice {
}
var ms []catalog.Model
for _, m := range p.Available() {
if !strings.HasPrefix(m.ID, provider.GroupPrefix) && searchableModel(p, m.ID) {
if !provider.IsGroupRef(m.ID) && searchableModel(p, m.ID) {
ms = append(ms, m)
}
}
@@ -458,7 +458,7 @@ func smallReady(p provider.Provider, keep func(catalog.Model) bool, from provide
}
l := strings.ToLower(m.ID)
// a subscription's list can have what magpie wrote into its agent
if strings.HasPrefix(m.ID, provider.GroupPrefix) || (p.Account != nil && strings.Contains(m.ID, "/")) ||
if strings.HasPrefix(m.ID, provider.GroupPrefix) || strings.HasPrefix(m.ID, provider.AutoPrefix) || (p.Account != nil && strings.Contains(m.ID, "/")) ||
strings.ContainsAny(l, ":~") || slices.ContainsFunc([]string{"nano", "lite", "image", "audio", "tts", "embed", "free"}, func(w string) bool { return strings.Contains(l, w) }) {
continue
}
+1 -1
View File
@@ -1625,7 +1625,7 @@ func Handler(w Windows, gw *gateway.Server) http.Handler {
// Resolve intentionally accepts arbitrary names under a known
// provider. An approval reviewer must be a model or group magpie
// actually lists, including providers kept unlisted for routing.
if !slices.ContainsFunc(provider.Served(), func(e provider.Entry) bool { return e.ID == v }) {
if !slices.ContainsFunc(provider.Served(), func(e provider.Entry) bool { return e.ID == v || e.Group != "" && provider.SameRef(e.ID, v) }) {
fail(rw, fmt.Errorf("no model %s for Codex's auto-review", v))
return
}
@@ -1350,7 +1350,7 @@ function routingPage(part) {
s.pk = "group/" + info.id;
s.li.style.setProperty("--depth", d);
s.name.textContent = info.name || info.id;
s.id.textContent = "group/" + info.id;
s.id.textContent = info.ref || "group/" + info.id;
s.mode.textContent = t(modeOf(info.routing || "")[0]);
s.rules = info.rules ? t(info.rules === 1 ? "1 rule" : "{n} rules", { n: info.rules }) : "";
return s;
@@ -3793,7 +3793,7 @@ function routingPage(part) {
try { return hayMatches(g, words); } catch { return true; } // a group that can't be read is shown, flagged
}
function hayMatches(g, words) {
const hay = [g.name, g.id, "group/" + g.id, ...g.members.flatMap((id) => [id, memberLabel(g, id)]), ...(g.patterns || []).map((p) => p.pattern)].join("\n").toLowerCase();
const hay = [g.name, g.id, "group/" + g.id, g.ref || "", ...g.members.flatMap((id) => [id, memberLabel(g, id)]), ...(g.patterns || []).map((p) => p.pattern)].join("\n").toLowerCase();
return words.every((w) => hay.includes(w));
}
// rowOrFlag: a group's row, or when drawing it fails, a row that says so
@@ -3804,7 +3804,7 @@ function routingPage(part) {
const row = el("div", "rt-group off rt-gbad");
row.dataset.id = g.id;
const main = el("div", "main"), nm = el("div", "nm");
nm.append(el("b", "", String(g.name || g.id)), el("code", "mdl", "group/" + g.id));
nm.append(el("b", "", String(g.name || g.id)), el("code", "mdl", g.ref || "group/" + g.id));
main.append(nm, el("div", "mem", t("This group can't be shown: {error}", { error: e?.message || String(e) })));
row.append(el("span", "ics"), main);
return row;
@@ -4105,7 +4105,7 @@ function routingPage(part) {
const ics = el("span", "ics");
ics.append(stackIcon(groupIcons(g)));
const main = el("div", "main"), nm = el("div", "nm");
nm.append(el("b", "", g.name), el("code", "mdl", "group/" + g.id));
nm.append(el("b", "", g.name), el("code", "mdl", g.ref || "group/" + g.id));
if (g.auto) nm.append(el("small", "auto", t("found by magpie")));
main.append(nm, el("div", "mem", g.members.map((id) => memberLabel(g, id)).join(g.routing === "order" ? " → " : " · ")));
row.append(cb, ics, main);
@@ -4127,7 +4127,7 @@ function routingPage(part) {
s.onclick = (e) => { e.stopPropagation(); setFound(!on, s); };
const txt = el("div", "txt");
txt.append(el("b", "", t("Find groups on their own")), el("small", "", on
? t("A model two or more of your providers serve becomes a group of them (auto-…). Switch it off to list and serve only the groups you made or changed.")
? t("A model two or more of your providers serve becomes a group of them (auto/…). Switch it off to list and serve only the groups you made or changed.")
: t("Off: only the groups you made or changed are listed and served. An agent set to a found group is moved to its model from one provider, and a request still naming one goes there too.")));
gFound.replaceChildren(txt, s);
}
@@ -4161,7 +4161,7 @@ function routingPage(part) {
const ics = groupHandle(g, row);
const main = el("div", "main");
const nm = el("div", "nm");
nm.append(el("b", "", g.name), el("code", "mdl", "group/" + g.id));
nm.append(el("b", "", g.name), el("code", "mdl", g.ref || "group/" + g.id));
if (g.auto) nm.append(el("small", "auto", t("found by magpie")));
const manual = g.routing === "manual";
const sep = g.routing === "order" ? " → " : " · ";
@@ -4406,8 +4406,8 @@ function routingPage(part) {
return id;
};
const showId = () => {
idHint.textContent = t("Agents pick it as {id}", { id: "group/" + idOf() }) +
(g && idOf() !== g.id ? " · " + t("an agent set to {id} needs setting again", { id: "group/" + g.id }) : "");
idHint.textContent = t("Agents pick it as {id}", { id: g?.ref && idOf() === g.id ? g.ref : "group/" + idOf() }) +
(g && idOf() !== g.id ? " · " + t("an agent set to {id} needs setting again", { id: g.ref || "group/" + g.id }) : "");
};
// what the agents' lists will call it (#868: an agent's narrow menu
// cut it to "· rou…"); whether "· routing group" follows the name is
+4 -4
View File
@@ -127,7 +127,7 @@ magpie.strings({
"{n} groups removed": "已移除 {n} 个组",
"No group yet. New group makes one of any models you like.": "还没有路由组。「新建组」可组合任意模型。",
"Find groups on their own": "自动创建路由组",
"A model two or more of your providers serve becomes a group of them (auto-…). Switch it off to list and serve only the groups you made or changed.": "两个及以上供应商都提供的模型会自动成组(auto-…)。关闭后只列出和提供你新建或改过的组。",
"A model two or more of your providers serve becomes a group of them (auto/…). Switch it off to list and serve only the groups you made or changed.": "两个及以上供应商都提供的模型会自动成组(auto/…)。关闭后只列出和提供你新建或改过的组。",
"Off: only the groups you made or changed are listed and served. An agent set to a found group is moved to its model from one provider, and a request still naming one goes there too.": "已关闭:只列出和提供你新建或改过的组。选了自动组的 Agent 改用其中一个供应商的该模型,仍指定自动组的请求也发往那里。",
"Found groups are on": "已开启自动创建路由组",
"Found groups are off: only yours are listed and served": "已关闭自动创建路由组:只保留你自己的组",
@@ -666,7 +666,7 @@ magpie.strings({
"{n} groups removed": "已移除 {n} 個組",
"No group yet. New group makes one of any models you like.": "還沒有路由組。「新增組」可組合任意模型。",
"Find groups on their own": "自動建立路由組",
"A model two or more of your providers serve becomes a group of them (auto-…). Switch it off to list and serve only the groups you made or changed.": "兩個及以上供應商都提供的模型會自動成組(auto-…)。關閉後只列出和提供你新增或改過的組。",
"A model two or more of your providers serve becomes a group of them (auto/…). Switch it off to list and serve only the groups you made or changed.": "兩個及以上供應商都提供的模型會自動成組(auto/…)。關閉後只列出和提供你新增或改過的組。",
"Off: only the groups you made or changed are listed and served. An agent set to a found group is moved to its model from one provider, and a request still naming one goes there too.": "已關閉:只列出和提供你新增或改過的組。選了自動組的 Agent 改用其中一個供應商的該模型,仍指定自動組的請求也發往那裡。",
"Found groups are on": "已開啟自動建立路由組",
"Found groups are off: only yours are listed and served": "已關閉自動建立路由組:只保留你自己的組",
@@ -1185,7 +1185,7 @@ magpie.strings({
"{n} groups removed": "{n} 件のグループを削除しました",
"No group yet. New group makes one of any models you like.": "グループはまだありません。「新しいグループ」で好きなモデルをまとめられます。",
"Find groups on their own": "グループを自動で作成",
"A model two or more of your providers serve becomes a group of them (auto-…). Switch it off to list and serve only the groups you made or changed.": "2 つ以上のプロバイダが提供するモデルは、それらのグループ(auto-…)になります。オフにすると、自分で作成または変更したグループだけを一覧・提供します。",
"A model two or more of your providers serve becomes a group of them (auto/…). Switch it off to list and serve only the groups you made or changed.": "2 つ以上のプロバイダが提供するモデルは、それらのグループ(auto/…)になります。オフにすると、自分で作成または変更したグループだけを一覧・提供します。",
"Off: only the groups you made or changed are listed and served. An agent set to a found group is moved to its model from one provider, and a request still naming one goes there too.": "オフ:自分で作成または変更したグループだけを一覧・提供します。自動グループを選んでいるエージェントは、1 つのプロバイダのそのモデルに切り替わり、自動グループを指定したリクエストもそこへ送られます。",
"Found groups are on": "グループの自動作成はオンです",
"Found groups are off: only yours are listed and served": "グループの自動作成はオフです:自分のグループだけを一覧・提供します",
@@ -1715,7 +1715,7 @@ magpie.strings({
"{n} groups removed": "{n} Gruppen entfernt",
"No group yet. New group makes one of any models you like.": "Noch keine Gruppe. „Neue Gruppe“ fasst beliebige Modelle zusammen.",
"Find groups on their own": "Gruppen automatisch finden",
"A model two or more of your providers serve becomes a group of them (auto-…). Switch it off to list and serve only the groups you made or changed.": "Ein Modell, das zwei oder mehr Ihrer Anbieter bereitstellen, wird zu einer Gruppe aus ihnen (auto-…). Ausschalten, um nur selbst erstellte oder geänderte Gruppen aufzulisten und bereitzustellen.",
"A model two or more of your providers serve becomes a group of them (auto/…). Switch it off to list and serve only the groups you made or changed.": "Ein Modell, das zwei oder mehr Ihrer Anbieter bereitstellen, wird zu einer Gruppe aus ihnen (auto/…). Ausschalten, um nur selbst erstellte oder geänderte Gruppen aufzulisten und bereitzustellen.",
"Off: only the groups you made or changed are listed and served. An agent set to a found group is moved to its model from one provider, and a request still naming one goes there too.": "Aus: Nur selbst erstellte oder geänderte Gruppen werden aufgelistet und bereitgestellt. Ein Agent, der auf eine gefundene Gruppe eingestellt ist, wechselt zu deren Modell bei einem Anbieter, und eine Anfrage, die sie noch nennt, geht ebenfalls dorthin.",
"Found groups are on": "Gefundene Gruppen sind eingeschaltet",
"Found groups are off: only yours are listed and served": "Gefundene Gruppen sind ausgeschaltet: nur Ihre werden aufgelistet und bereitgestellt",
+4 -1
View File
@@ -66,7 +66,10 @@ func callerKeyRoutes(mux *http.ServeMux) {
accounts := []keyModelJSON{}
for _, e := range provider.Catalog() {
if e.Group != "" {
out = append(out, keyModelJSON{ID: e.ID, Name: cmp.Or(e.Name, e.Group), Group: true})
// by the id magpie keeps it by, group/<id>, as a key held to it
// before names it: a found group's auto/<model> passes for it
// (gateway's allows), and its name is what the picker shows
out = append(out, keyModelJSON{ID: provider.GroupPrefix + e.Group, Name: cmp.Or(e.Name, e.Group), Group: true})
continue
}
out = append(out, keyModelJSON{ID: e.Provider.ID + "/" + e.Model, Name: cmp.Or(e.Name, e.Model), Provider: e.Provider.ID, ProviderName: cmp.Or(e.Provider.Name, e.Provider.ID)})
+6 -2
View File
@@ -58,6 +58,9 @@ type groupJSON struct {
// Decides: it is a group of decision models, asked at /v1/systemone
// and by a group's classifier, never by an agent
Decides bool `json:"decides,omitempty"`
// Ref: the id agents pick it by (provider.Group.Ref): auto/<model> for
// a group magpie found, group/<id> for any other
Ref string `json:"ref"`
// ClassifierFailed: its classifier couldn't say the last time it was
// asked, and why (gateway.ClassifierFailure), which its card says
// (#1929): otherwise only each request's details did
@@ -256,13 +259,14 @@ func groupsState() groupsJSON {
}
gj.Patterns = append(gj.Patterns, provider.PatternHits(g)...)
gj.Decides = g.Decides()
gj.Ref = g.Ref()
if g.Classifier != "" {
if why, at, ok := classifierFailure(g.Classifier); ok {
gj.ClassifierFailed = &classifierFailedJSON{Error: why, At: at}
}
}
for _, e := range served {
if e.ID == provider.GroupPrefix+g.ID {
if e.Group == g.ID {
gj.Offers, gj.Shared = append(gj.Offers, e.Efforts...), append(gj.Shared, e.Shared...)
break
}
@@ -282,7 +286,7 @@ func groupsState() groupsJSON {
// a group in the group: what agents see of it
m.Group = true
for _, e := range served {
if e.ID == id {
if e.Group == gid {
_, ms, _ := find(id)
m.Ready, m.Name, m.Icon, m.On = true, e.Name, e.Provider.Icon, len(ms)
m.Context, m.Images, m.ImagesUnknown = e.Context, seesImages(e), imagesUnknown(e)
+1 -1
View File
@@ -541,7 +541,7 @@ func agentUses(agents []*agent.Agent, findGroup func(string) (provider.Group, []
for _, a := range agents {
u := agentUse{Agent: a}
v := agentModel(a)
if strings.HasPrefix(v, provider.GroupPrefix) {
if provider.IsGroupRef(v) {
u.group, u.members, u.inGroup = findGroup(v)
} else if pid, model, ok := strings.Cut(v, "/"); ok {
if _, err := provider.Find(pid); err == nil {
+1 -1
View File
@@ -121,7 +121,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
const missing = await page.evaluate(() => [
"Find groups on their own", "Found groups are on", "Found groups are off: only yours are listed and served",
"A model two or more of your providers serve becomes a group of them (auto-…). Switch it off to list and serve only the groups you made or changed.",
"A model two or more of your providers serve becomes a group of them (auto/…). Switch it off to list and serve only the groups you made or changed.",
"Off: only the groups you made or changed are listed and served. An agent set to a found group is moved to its model from one provider, and a request still naming one goes there too.",
"No group yet. New group makes one of any models you like.",
].filter((k) => !I18N.zh[k]));
+218
View File
@@ -0,0 +1,218 @@
package provider
// The id agents are given for a group magpie found (ZeroClover on X): "auto/<model>",
// the model's own id as a vendor spells it (auto/claude-opus-5.5), so that a
// client reading the part after the slash as a model id — as models.dev keys
// its models — knows the model. It was "group/auto-<slug>" (Slug's, dots
// dashed), which nothing outside magpie could read, and that id is still
// served as it was, forever: agents' configs, gateway keys, saved groups and
// rules hold it.
//
// Inside magpie a found group stays "group/auto-<slug>": providers.json's
// members, rules and classifiers, the gateway's routing, a key's limits and
// the usage log keep that one id, so a group is counted under one name
// whichever an agent sent (CanonicalRef, taken back in the gateway before
// anything reads the request). The catalog lists the group by its public id
// (Group.Ref), so every list and config that is built from the catalog —
// /v1/models, the model lists written into agents, the pickers — names it so.
//
// "auto" is not a provider's id: Save and Rename refuse it, and a plugin
// that calls its provider auto is auto-plugin (PluginID). One of the user's
// own saved as "auto" before keeps its models: while it is there, auto/<x>
// is its model x, and found groups are listed as group/auto-<slug> as before
// (autoRefsOn).
import (
"errors"
"slices"
"strings"
"unicode"
"github.com/yetone/magpie/internal/catalog"
)
// AutoPrefix starts the id agents are given for a group magpie found:
// "auto/<model>".
const AutoPrefix = "auto/"
// autoID is the provider id that would take auto/<model> for its own.
const autoID = "auto"
// errAutoID refuses "auto" as a new provider's id: auto/<model> names the
// groups magpie finds.
var errAutoID = errors.New(`"auto" starts the ids of the groups magpie finds (auto/<model>); pick another id`)
// autoRefsOn reports whether auto/<model> names found groups: unless the
// user has a provider of their own with the id "auto", saved before the
// id was kept for found groups, whose models it stays.
func autoRefsOn() bool { return !customIDs()[autoID] }
// AutoRefsOn is autoRefsOn, for the packages that spell a group's id.
func AutoRefsOn() bool { return autoRefsOn() }
// autoGroupOfRef is the group id auto/<model> names, model as any vendor
// spells it: the id magpie gives the group it finds for the model
// (AutoGroupID).
func autoGroupOfRef(model string) string { return AutoGroupID(model) }
// IsGroupRef reports whether ref names a routing group: group/<id>, or a
// found group's auto/<model>.
func IsGroupRef(ref string) bool {
_, ok := GroupIDOf(ref)
return ok
}
// CanonicalRef is ref as magpie keeps it: a found group's auto/<model> as
// group/auto-<slug>, an effort after it (":high") and Claude Code's [1m]
// mark kept; any other ref as it is. The gateway takes a request's model
// back to it before key limits, routing and the usage log see it, so the
// two ids of one group are one.
func CanonicalRef(ref string) string {
s := strings.TrimSpace(ref)
s, marked := strings.CutSuffix(s, "[1m]")
m, ok := strings.CutPrefix(s, AutoPrefix)
if !ok || strings.TrimSpace(m) == "" || !autoRefsOn() {
return ref
}
level := ""
if i := strings.LastIndex(m, ":"); i > 0 && slices.Contains(MemberEfforts, strings.ToLower(m[i+1:])) {
m, level = m[:i], ":"+strings.ToLower(m[i+1:])
}
gid := autoGroupOfRef(m)
if gid == "auto-" {
return ref
}
out := GroupPrefix + gid + level
if marked {
out += "[1m]"
}
return out
}
// canonicalRefs spells every model or group g names as magpie keeps it
// (CanonicalRef): a found group a picker listed as auto/<model> is stored
// as group/auto-<slug>, so its members, off and fast lists, weights, rules
// and classifier name it by one id. g's lists are its own (Group.own).
func (g *Group) canonicalRefs() {
for _, l := range [][]string{g.Members, g.Off, g.Fast} {
for i, v := range l {
l[i] = CanonicalRef(v)
}
}
for k, v := range g.Weights {
if c := CanonicalRef(k); c != k {
delete(g.Weights, k)
g.Weights[c] = v
}
}
for i := range g.Rules {
g.Rules[i].Use = CanonicalRef(g.Rules[i].Use)
}
g.Classifier = CanonicalRef(g.Classifier)
}
// SameRef reports whether a and b name the same model or group, a found
// group by either of its ids.
func SameRef(a, b string) bool {
return a == b || CanonicalRef(a) == CanonicalRef(b)
}
// Ref is the id agents pick the group by: auto/<model> for a group magpie
// found (one with an auto-… id whose members are that model), its model
// spelt as a vendor spells it; group/<id> for any other, and for every
// group while a provider of the user's is called auto.
func (g Group) Ref() string {
if g.Spelled != "" && autoRefsOn() {
return AutoPrefix + g.Spelled
}
return GroupPrefix + g.ID
}
// PublicRef is the id agents are given for ref: a found group's
// group/auto-<slug> as its auto/<model> (Group.Ref), its effort and [1m]
// mark kept; any other ref as it is, a found group magpie has none of now
// too.
func PublicRef(ref string) string {
s := strings.TrimSpace(ref)
s, marked := strings.CutSuffix(s, "[1m]")
gid, ok := strings.CutPrefix(s, GroupPrefix)
if !ok || !strings.HasPrefix(gid, "auto-") || !autoRefsOn() {
return ref
}
level := ""
if i := strings.LastIndex(gid, ":"); i > 0 {
gid, level = gid[:i], gid[i:]
}
g, ok := groupOf(Groups(), gid)
if !ok || g.Spelled == "" {
return ref
}
out := g.Ref() + level
if marked {
out += "[1m]"
}
return out
}
// spelledIn is how the model of a found group's id is spelt by a vendor
// (Group.Spelled): of the members whose model merges into the group by its
// own id (mergeKey), the first models.dev lists by that very spelling, else
// the first; failing those, the model the user said a member is the same
// as (settings' ModelSameAs). Without a vendor's prefix ("anthropic/").
// "" for a group whose id is not auto-…, or none of whose members is its
// model: one the user made, whatever it is called, stays group/<id>.
func spelledIn(g Group, same map[string]string) string {
if !strings.HasPrefix(g.ID, "auto-") {
return ""
}
var own, alike []string
for _, id := range g.Members {
if strings.HasPrefix(id, GroupPrefix) || IsPattern(id) {
continue
}
model, _ := MemberEffort(id)
pid, m, ok := strings.Cut(model, "/")
if !ok || m == "" {
continue
}
if v := same[pid+"/"+m]; v != "" {
if "auto-"+Slug(sameModel(v)) == g.ID {
alike = append(alike, lastPart(v))
}
continue
}
if "auto-"+Slug(sameModel(m)) == g.ID {
own = append(own, lastPart(m))
}
}
// an id a relay lists as its display name ("GPT-6 Sol") is no id to
// put in an agent's config: the one vendors agree on is, below
spaced := func(s string) bool { return strings.ContainsFunc(s, unicode.IsSpace) }
spacedOnly := len(own)+len(alike) > 0
own, alike = slices.DeleteFunc(own, spaced), slices.DeleteFunc(alike, spaced)
for _, s := range own {
if catalog.Lists(s) {
return s
}
}
if len(own) > 0 {
return own[0]
}
if len(alike) > 0 {
return alike[0]
}
if spacedOnly {
return strings.TrimPrefix(g.ID, "auto-")
}
return ""
}
// lastPart is a model's id without a vendor's prefix: what follows its
// last slash, trimmed.
func lastPart(m string) string {
m = strings.TrimSpace(m)
if i := strings.LastIndex(m, "/"); i >= 0 {
m = m[i+1:]
}
return m
}
+207
View File
@@ -0,0 +1,207 @@
package provider
import (
"errors"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/settings"
)
// autoRefHome is a sandbox HOME with two providers serving Claude Opus 5.5,
// each spelling it its own way, and a models.dev catalog listing it as
// Anthropic spells it, with its window and reply limit.
func autoRefHome(t *testing.T) {
t.Helper()
isolate(t)
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
if err := os.MkdirAll(filepath.Dir(catalog.CachePath()), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(catalog.CachePath(), []byte(`{"anthropic": {"models": {
"claude-opus-5.5": {"id":"claude-opus-5.5","name":"Claude Opus 5.5","limit":{"context":400000,"output":96000}}}}}`), 0o644); err != nil {
t.Fatal(err)
}
catalog.Reset()
t.Cleanup(catalog.Reset)
for id, m := range map[string]string{"a": "claude-opus-5-5", "b": "claude-opus-5.5"} {
if err := Save(Provider{ID: id, Name: id, Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{m, "x"}}); err != nil {
t.Fatal(err)
}
}
}
// A group magpie found is listed as auto/<model>, the model's id as a
// vendor spells it (ZeroClover on X), so a client looking the part after
// the slash up on models.dev finds the model; its old group/auto-<slug> is
// the same group, and a group the user made stays group/<id>.
func TestFoundGroupListedByItsModelsID(t *testing.T) {
autoRefHome(t)
if err := SaveGroup(Group{Name: "Mine", Members: []string{"a/x", "b/x"}}); err != nil {
t.Fatal(err)
}
refs := map[string]string{}
for _, g := range Groups() {
refs[g.ID] = g.Ref()
}
if refs["auto-claude-opus-5-5"] != "auto/claude-opus-5.5" {
t.Errorf("the found group's id: %q", refs["auto-claude-opus-5-5"])
}
if refs["mine"] != "group/mine" {
t.Errorf("the user's group's id: %q", refs["mine"])
}
var e Entry
for _, c := range Catalog() {
if c.Group == "auto-claude-opus-5-5" {
e = c
}
}
if e.ID != "auto/claude-opus-5.5" {
t.Fatalf("the catalog lists the group as %q", e.ID)
}
// what a client does with it: the model's id after auto/, on models.dev
model := strings.TrimPrefix(e.ID, AutoPrefix)
if catalog.ContextOf(model) != 400000 || catalog.OutputOf(model) != 96000 {
t.Errorf("models.dev has %s at %d/%d", model, catalog.ContextOf(model), catalog.OutputOf(model))
}
if e.Context != 400000 || e.Output != 96000 {
t.Errorf("the group's own limits: %d/%d", e.Context, e.Output)
}
for in, want := range map[string]string{
"auto/claude-opus-5.5": "group/auto-claude-opus-5-5",
"auto/anthropic/Claude-Opus-5.5": "group/auto-claude-opus-5-5",
"auto/claude-opus-5-5": "group/auto-claude-opus-5-5",
"auto/claude-opus-5.5:high[1m]": "group/auto-claude-opus-5-5:high[1m]",
"group/auto-claude-opus-5-5": "group/auto-claude-opus-5-5",
"a/claude-opus-5-5": "a/claude-opus-5-5",
"auto/": "auto/",
"openrouter/auto": "openrouter/auto",
} {
if got := CanonicalRef(in); got != want {
t.Errorf("CanonicalRef(%q) = %q, want %q", in, got, want)
}
}
for in, want := range map[string]string{
"group/auto-claude-opus-5-5": "auto/claude-opus-5.5",
"group/auto-claude-opus-5-5:high[1m]": "auto/claude-opus-5.5:high[1m]",
"group/mine": "group/mine",
"group/auto-gone": "group/auto-gone",
} {
if got := PublicRef(in); got != want {
t.Errorf("PublicRef(%q) = %q, want %q", in, got, want)
}
}
// both ids are served, as the one group
for _, id := range []string{"auto/claude-opus-5.5", "group/auto-claude-opus-5-5", "auto/claude-opus-5.5[1m]"} {
p, m, ok := Resolve(id)
if !ok || p.ID != e.Provider.ID || m != e.Model {
t.Errorf("Resolve(%q) = %q %q %v, want %q %q", id, p.ID, m, ok, e.Provider.ID, e.Model)
}
if gid, ok := GroupIDOf(id); !ok || gid != "auto-claude-opus-5-5" {
t.Errorf("GroupIDOf(%q) = %q %v", id, gid, ok)
}
}
// a group picked as a member by its new id is kept by its old one
if err := SaveGroup(Group{ID: "mine", Name: "Mine", Members: []string{"a/x", "auto/claude-opus-5.5"}}); err != nil {
t.Fatal(err)
}
for _, g := range Groups() {
if g.ID == "mine" && !slices.Equal(g.Members, []string{"a/x", "group/auto-claude-opus-5-5"}) {
t.Errorf("stored members: %v", g.Members)
}
}
}
// "auto" is no new provider's id: auto/<model> names found groups. One
// the user saved before keeps its models: while it is there, auto/<x> is
// its model x, and found groups are listed by their old ids.
func TestProviderNamedAuto(t *testing.T) {
autoRefHome(t)
if err := Save(Provider{ID: "auto", Name: "Auto", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"y"}}); !errors.Is(err, errAutoID) {
t.Fatalf("a new provider named auto: %v", err)
}
if err := Rename("a", "auto"); !errors.Is(err, errAutoID) {
t.Fatalf("renaming a provider to auto: %v", err)
}
if PluginID("auto") != "auto-plugin" || PluginID("group") != "group-plugin" {
t.Errorf("plugin ids: %q %q", PluginID("auto"), PluginID("group"))
}
// one in providers.json from before
raw, err := os.ReadFile(Path())
if err != nil {
t.Fatal(err)
}
s := strings.Replace(string(raw), `"providers": [`, `"providers": [{"id": "auto", "name": "Auto", "key": "k", "chat": "http://127.0.0.1:1/v1", "models": ["claude-opus-5.5", "y"]},`, 1)
if s == string(raw) {
t.Fatalf("providers.json: %s", raw)
}
if err := os.WriteFile(Path(), []byte(s), 0o600); err != nil {
t.Fatal(err)
}
if _, err := Find("auto"); err != nil {
t.Fatal(err)
}
if AutoRefsOn() {
t.Fatal("auto/<model> still names found groups beside a provider called auto")
}
for _, id := range []string{"auto/y", "auto/claude-opus-5.5"} {
p, m, ok := Resolve(id)
if !ok || p.ID != "auto" || m != strings.TrimPrefix(id, "auto/") {
t.Errorf("Resolve(%q) = %q %q %v: not the auto provider's model", id, p.ID, m, ok)
}
if CanonicalRef(id) != id {
t.Errorf("CanonicalRef(%q) = %q", id, CanonicalRef(id))
}
}
var listed []string
for _, e := range Catalog() {
if e.Group != "" {
listed = append(listed, e.ID)
}
}
if !slices.Contains(listed, "group/auto-claude-opus-5-5") || slices.ContainsFunc(listed, func(id string) bool { return strings.HasPrefix(id, AutoPrefix) }) {
t.Errorf("groups listed beside the auto provider: %v", listed)
}
// still the user's to save
p, _ := Find("auto")
p.Name = "Mine"
if err := Save(*p); err != nil {
t.Errorf("saving the stored auto provider: %v", err)
}
}
// A pick made one model at a time in an agent's lists, saved while a found
// group was listed as group/auto-<slug>, holds for it by auto/<model>: a
// group taken out stays out, one picked stays shown, and the order kept.
func TestFoundGroupPicksSavedByTheOldID(t *testing.T) {
autoRefHome(t)
old, now := "group/auto-claude-opus-5-5", "auto/claude-opus-5.5"
s := settings.Load()
s.HiddenModels = map[string][]string{"pi": {old}}
s.PickedModels = map[string][]string{"opencode": {old}}
s.OrderedModels = map[string][]string{"pi": {old, "a/x"}}
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if !ModelOff("pi")(now) {
t.Errorf("hidden as %s, listed as %s again", old, now)
}
if ModelOff("opencode")(now) {
t.Errorf("picked as %s, left out as %s", old, now)
}
if got := ModelOrder("pi"); !slices.Equal(got, []string{now, "a/x"}) {
t.Errorf("order: %v", got)
}
}
+1 -1
View File
@@ -77,7 +77,7 @@ func bareTarget(shown []Entry, all []Group, entries []Entry, id string) int {
if !strings.Contains(id, "/") {
if gid, ok := groupForIn(all, id); ok {
for i, e := range shown {
if e.ID == gid {
if e.ID == gid || e.Group != "" && GroupPrefix+e.Group == gid {
return i
}
}
+2 -2
View File
@@ -65,8 +65,8 @@ func Closest(asked string, n int) []string {
names := slices.Concat(nameWords(e.Name), nameWords(e.Default))
model := nameWords(e.Model)
var from []string
if strings.HasPrefix(e.ID, GroupPrefix) {
model = nameWords(strings.TrimPrefix(e.ID, GroupPrefix))
if e.Group != "" {
model = nameWords(e.Group)
} else {
from = slices.Concat(nameWords(e.Provider.ID), nameWords(e.Provider.Name))
}
+3 -2
View File
@@ -114,9 +114,10 @@ func ClaudeGroup(id string) bool {
}
// catalogID is an agent's model id as the catalog has it: magpie/ and
// Claude Code's [1m] mark taken off.
// Claude Code's [1m] mark taken off, a found group's auto/<model> as
// group/auto-<slug> (CanonicalRef).
func catalogID(id string) string {
return strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(id), "magpie/"), "[1m]")
return CanonicalRef(strings.TrimSuffix(strings.TrimPrefix(strings.TrimSpace(id), "magpie/"), "[1m]"))
}
func compactSet(s settings.Settings, id string, find func(string) (Group, []Member, bool)) int {
+1 -1
View File
@@ -19,7 +19,7 @@ import (
// "provider/model" whose provider answers model at its decision API, on
// or not. A group, or a member with an effort of its own, is not one.
func decidingMember(id string) bool {
if strings.HasPrefix(id, GroupPrefix) {
if IsGroupRef(id) {
return false
}
if IsDecider(id) {
+1 -1
View File
@@ -106,7 +106,7 @@ func SetFastTier(agent, id, tier string) error {
return fmt.Errorf("magpie knows no tier %q", tier)
}
if tier != "" {
if strings.HasPrefix(id, GroupPrefix) {
if IsGroupRef(id) {
return fmt.Errorf("%s is a routing group: its members are sent fast as it says, on the Routing page", id)
}
p, model, ok := Resolve(id)
+23 -14
View File
@@ -38,11 +38,12 @@ import (
// GroupPrefix starts a group's id in the catalog: "group/<id>".
const GroupPrefix = "group/"
// GroupIDOf is the group id a ref names ("group/<id>"), with spaces and the
// [1m] mark Claude Code puts on a 1M window taken off, as an agent's own
// settings carry it. ok is false for a ref that isn't a group's.
// GroupIDOf is the group id a ref names ("group/<id>", or a found group's
// "auto/<model>": CanonicalRef), with spaces and the [1m] mark Claude Code
// puts on a 1M window taken off, as an agent's own settings carry it. ok is
// false for a ref that isn't a group's.
func GroupIDOf(ref string) (string, bool) {
return strings.CutPrefix(strings.TrimSuffix(strings.TrimSpace(ref), "[1m]"), GroupPrefix)
return strings.CutPrefix(CanonicalRef(strings.TrimSuffix(strings.TrimSpace(ref), "[1m]")), GroupPrefix)
}
// Affinities are how long a conversation stays with the key or account that
@@ -236,6 +237,10 @@ type Group struct {
// Auto is set on a group magpie found: one model served by several
// providers. It is derived, never stored.
Auto bool `json:"auto,omitempty"`
// Spelled is how a vendor spells the model of a group magpie found
// (auto-…), which agents are given it by: auto/<Spelled> (Ref). It is
// derived from the members each time the groups are read, never stored.
Spelled string `json:"-"`
// Hidden is stored for a found group the user removed.
Hidden bool `json:"hidden,omitempty"`
// Disabled is a group of the user's switched off (PAMI on Discord):
@@ -419,15 +424,18 @@ func buildGroupsIn(entries []Entry) []Group {
if !served(f.Groups) { // plugins/groups is off: the user's own aren't served
out = slices.DeleteFunc(out, func(g Group) bool { return !g.Auto })
}
if f.NoAutoGroups {
return orderedGroups(out, f.GroupOrder)
}
for _, g := range foundGroups(entries) {
if slices.ContainsFunc(out, func(o Group) bool { return o.ID == g.ID }) {
continue // the user changed it: theirs now
if !f.NoAutoGroups {
for _, g := range foundGroups(entries) {
if slices.ContainsFunc(out, func(o Group) bool { return o.ID == g.ID }) {
continue // the user changed it: theirs now
}
g.Hidden = hidden[g.ID]
out = append(out, g)
}
g.Hidden = hidden[g.ID]
out = append(out, g)
}
same := heldSettings().ModelSameAs
for i := range out {
out[i].Spelled = spelledIn(out[i], same)
}
return orderedGroups(out, f.GroupOrder)
}
@@ -948,7 +956,7 @@ func buildGroupEntries(entries []Entry) []Entry {
if len(ms) == 0 || DecisionGroup(ms) {
continue // a decision group answers System One, no agent's conversation
}
e := Entry{ID: GroupPrefix + g.ID, Model: ms[0].Model, Name: g.Name, Provider: ms[0].Provider, Group: g.ID, Named: !g.Auto}
e := Entry{ID: g.Ref(), Model: ms[0].Model, Name: g.Name, Provider: ms[0].Provider, Group: g.ID, Named: !g.Auto}
var fixed []string // the efforts members are fixed at
levelled := false // a member that follows the agent's effort was met
// Codex's ultra (max, with Codex handing parts of the task to agents
@@ -1182,6 +1190,7 @@ func (e Entry) Quiet() bool {
// found makes it the user's.
func SaveGroup(g Group) error {
g = g.own() // cleaned below in place: the caller's lists stay as they were
g.canonicalRefs()
g.ID = strings.ToLower(strings.TrimSpace(g.ID))
g.Name = strings.TrimSpace(g.Name)
if g.ID == "" {
@@ -1226,7 +1235,7 @@ func SaveGroup(g Group) error {
return err
}
for i, m := range g.Members {
if model, effort := memberEffortIn(entries, m); effort != "" && strings.HasPrefix(model, GroupPrefix) {
if model, effort := memberEffortIn(entries, m); effort != "" && IsGroupRef(model) {
return fmt.Errorf("%s is a group: its models reason as it says, so it takes no effort of its own (:%s)", model, effort)
}
g.Members[i] = cleanMember(entries, m)
+2 -3
View File
@@ -4,7 +4,6 @@ import (
"encoding/json"
"os"
"slices"
"strings"
"testing"
)
@@ -40,7 +39,7 @@ func TestGroupOrder(t *testing.T) {
catalogGroups := func() []string {
var out []string
for _, e := range Catalog() {
if id, ok := strings.CutPrefix(e.ID, GroupPrefix); ok {
if id := e.Group; id != "" {
out = append(out, id)
}
}
@@ -59,7 +58,7 @@ func TestGroupOrder(t *testing.T) {
if got := catalogGroups(); !slices.Equal(got, want) {
t.Fatalf("catalog after SetGroupOrder(%s, two): %v", found, got)
}
if e := Catalog(); len(e) == 0 || e[0].ID != GroupPrefix+found {
if e := Catalog(); len(e) == 0 || e[0].Group != found {
t.Fatalf("the catalog's first model isn't %s", GroupPrefix+found)
}
b, err := os.ReadFile(Path())
+1 -1
View File
@@ -31,7 +31,7 @@ func TestOwnGroupsWaitOnThePlugin(t *testing.T) {
slices.Sort(ids)
return ids
}
both, found := []string{"group/auto-m", "group/mine"}, []string{"group/auto-m"}
both, found := []string{"auto/m", "group/mine"}, []string{"auto/m"}
check := func(when string, want []string) {
t.Helper()
if got := listed(); !slices.Equal(got, want) {
+1 -1
View File
@@ -241,7 +241,7 @@ func ImportGroup(text string) (Imported, error) {
// (AutoGroupOf) under the first provider here that serves it, in the
// Providers order; "" when none does. A member's own effort goes with it.
func memberHere(entries []Entry, all []Group, m string) string {
m = strings.TrimPrefix(strings.TrimSpace(m), "magpie/")
m = CanonicalRef(strings.TrimPrefix(strings.TrimSpace(m), "magpie/"))
model, effort := memberEffortIn(entries, m)
if gid, ok := strings.CutPrefix(model, GroupPrefix); ok {
if slices.ContainsFunc(all, func(g Group) bool { return g.ID == gid && !g.Hidden }) {
+2 -2
View File
@@ -57,8 +57,8 @@ func TestGroupImages(t *testing.T) {
got[g.ID] = g.Images
}
want := map[string]bool{
GroupPrefix + "auto-kimi-k3": true, GroupPrefix + "auto-glm-5-3": true,
GroupPrefix + "auto-deepseek-v4-1-flash": true, GroupPrefix + "auto-glm-5-2": false,
AutoPrefix + "kimi-k3": true, AutoPrefix + "glm-5.3": true,
AutoPrefix + "deepseek-v4.1-flash": true, AutoPrefix + "glm-5.2": false,
}
if !maps.Equal(got, want) {
t.Errorf("%v", got)
+3 -1
View File
@@ -89,8 +89,10 @@ func WithMemberEffort(model, effort string) string {
return model + ":" + effort
}
// cleanMember spells a member as it is kept: its effort lowercase.
// cleanMember spells a member as it is kept: its effort lowercase, a found
// group by group/auto-<slug> (CanonicalRef).
func cleanMember(entries []Entry, id string) string {
id = CanonicalRef(id) // a found group by the id magpie keeps it by
m, e := memberEffortIn(entries, id)
return WithMemberEffort(m, e)
}
+1 -1
View File
@@ -182,7 +182,7 @@ func cleanFast(entries []Entry, g *Group) error {
continue // taken out of the group
}
model, _ := memberEffortIn(entries, f)
if strings.HasPrefix(model, GroupPrefix) {
if IsGroupRef(model) {
return fmt.Errorf("%s is a group: its models are sent as it says, so it takes no :%s", model, FastWord)
}
if p, m, ok := resolveIn(entries, model); ok && !CanFast(p, m) {
+1 -1
View File
@@ -43,7 +43,7 @@ func TestFoundGroupStaysWithAProviderOff(t *testing.T) {
return out
}
listed := func() bool {
return slices.ContainsFunc(Served(), func(e Entry) bool { return e.ID == GroupPrefix+"auto-x" })
return slices.ContainsFunc(Served(), func(e Entry) bool { return e.ID == AutoPrefix+"x" })
}
all := []string{"a/x", "b/x", "c/x"}
if got := members(); !slices.Equal(got, all) {
+1 -1
View File
@@ -65,7 +65,7 @@ func TestAutoGroupsOff(t *testing.T) {
if got := ids(); !slices.Equal(got, []string{"auto-x", "mine"}) {
t.Fatalf("off: %v", got)
}
if got := catalog(); !slices.Equal(got, []string{"group/auto-x", "group/mine"}) {
if got := catalog(); !slices.Equal(got, []string{"auto/x", "group/mine"}) {
t.Fatalf("off, the catalog's groups: %v", got)
}
if _, _, ok := FindGroup("group/auto-kimi-k3"); ok {
+3 -3
View File
@@ -45,7 +45,7 @@ func modelNameIn(names map[string]string, pid, model string) (string, bool) {
// and the model.
func splitRef(ref string) (*Provider, string, error) {
r := strings.TrimPrefix(strings.TrimSpace(ref), "magpie/")
if strings.HasPrefix(r, GroupPrefix) {
if IsGroupRef(r) {
return nil, "", errors.New("that is a routing group, not a provider's model")
}
pid, model, ok := strings.Cut(r, "/")
@@ -213,7 +213,7 @@ func PriceKey(pid, model string) (string, bool) {
// reset` over a price still in the file would have the user believe it gone.
func DropModelPrice(key string) (bool, error) {
key = strings.TrimPrefix(strings.TrimSpace(key), "magpie/")
if strings.HasPrefix(key, GroupPrefix) {
if IsGroupRef(key) {
return false, errors.New("that is a routing group, not a provider's model")
}
pid, model, ok := strings.Cut(key, "/")
@@ -1166,7 +1166,7 @@ func SetUpstreamName(ref, name string) error {
// now.
func DropUpstreamName(key string) (bool, error) {
key = strings.TrimPrefix(strings.TrimSpace(key), "magpie/")
if strings.HasPrefix(key, GroupPrefix) {
if IsGroupRef(key) {
return false, errors.New("that is a routing group, not a provider's model")
}
pid, model, ok := strings.Cut(key, "/")
+2 -2
View File
@@ -94,7 +94,7 @@ func TestModelName(t *testing.T) {
if b.Name != "Sol" || b.Default != "" || b.Label() != "Sol · B" {
t.Fatalf("%+v %q", b, b.Label())
}
if g := entry(t, "group/auto-sol"); g.Name != "Sol" {
if g := entry(t, "auto/sol"); g.Name != "Sol" {
t.Fatalf("the group took a provider's name: %+v", g)
}
if p, m, ok := Resolve("a/sol"); !ok || p.ID != "a" || m != "sol" {
@@ -170,7 +170,7 @@ func TestModelEfforts(t *testing.T) {
if got := entry(t, "b/sol").Efforts; !slices.Equal(got, []string{"low", "medium", "high", "max"}) {
t.Fatal(got)
}
if got := entry(t, "group/auto-sol").Efforts; !slices.Equal(got, []string{"low", "high"}) {
if got := entry(t, "auto/sol").Efforts; !slices.Equal(got, []string{"low", "high"}) {
t.Fatal(got)
}
// the vendor is still asked at any level it has
+11 -6
View File
@@ -2545,6 +2545,13 @@ func entryIn(entries []Entry, id string) (Entry, bool) {
return e, true
}
}
if gid, ok := GroupIDOf(id); ok { // a found group by either of its ids
for _, e := range entries {
if e.Group == gid {
return e, true
}
}
}
return Entry{}, false
}
@@ -2561,11 +2568,9 @@ func Resolve(id string) (Provider, string, bool) {
// Claude Code's mark for a model with a 1M window; it drops it before
// asking, but a value in its settings still has it
id = strings.TrimSuffix(strings.TrimSpace(id), "[1m]")
if strings.HasPrefix(id, GroupPrefix) {
for _, e := range Catalog() {
if e.ID == id {
return e.Provider, e.Model, true
}
if IsGroupRef(id) {
if e, ok := entryIn(Catalog(), id); ok {
return e.Provider, e.Model, true
}
return Provider{}, "", false
}
@@ -2919,7 +2924,7 @@ func DropModelOutput(id string) (string, bool, error) {
// display name, and the same resolution outputOf reads it back under.
func outputKeyOf(id string) (string, error) {
r := strings.TrimPrefix(strings.TrimSpace(id), "magpie/")
if strings.HasPrefix(r, GroupPrefix) {
if IsGroupRef(r) {
return "", errorf("that is a routing group, not a provider's model")
}
pid, model, ok := strings.Cut(r, "/")
+4 -4
View File
@@ -39,7 +39,7 @@ func TestPlainNames(t *testing.T) {
return out
}
full := []string{"a/sol=My Sol · A", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}
full := []string{"a/sol=My Sol · A", "auto/sol=Sol · routing group", "b/sol=Sol · B"}
if got := codex(); !slices.Equal(got, full) {
t.Fatalf("by default: %q", got)
}
@@ -51,7 +51,7 @@ func TestPlainNames(t *testing.T) {
t.Fatalf("agents told %d times, setting %v", touched, settings.Load().PlainNames)
}
// the group found for sol and b's sol are both "Sol": they keep theirs
want := []string{"a/sol=My Sol", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}
want := []string{"a/sol=My Sol", "auto/sol=Sol · routing group", "b/sol=Sol · B"}
if got := codex(); !slices.Equal(got, want) {
t.Fatalf("plain: %q", got)
}
@@ -66,7 +66,7 @@ func TestPlainNames(t *testing.T) {
if err := settings.Save(s); err != nil {
t.Fatal(err)
}
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "group/auto-sol=Sol"}) {
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "auto/sol=Sol"}) {
t.Fatalf("plain, b hidden: %q", got)
}
if got := other(); !slices.Equal(got, []string{"My Sol", "Sol · B", "Sol · routing group"}) {
@@ -76,7 +76,7 @@ func TestPlainNames(t *testing.T) {
if err := SetPlainNames(false); err != nil {
t.Fatal(err)
}
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "group/auto-sol=Sol · routing group"}) || touched != 2 {
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "auto/sol=Sol · routing group"}) || touched != 2 {
t.Fatalf("off again: %q, told %d", got, touched)
}
}
+3 -2
View File
@@ -45,13 +45,14 @@ const (
// PluginID is the id magpie gives the provider OpenCode calls id: the same,
// unless a preset or a built-in subscription has it (google, openai,
// anthropic), or a provider of the user's own made before the plugin was
// installed (zenmux, #867), when it is id-plugin — but for a built-in moved
// installed (zenmux, #867), or "auto" or "group", which start the ids of
// routing groups, when it is id-plugin — but for a built-in moved
// onto the plugin, whose id the plugin has now.
func PluginID(id string) string {
if PluginServes(id) {
return id
}
if slices.Contains(accountIDs, id) || Preset(id) != nil || id == "magpie" || customIDs()[id] {
if slices.Contains(accountIDs, id) || Preset(id) != nil || id == "magpie" || id == autoID || id == strings.TrimSuffix(GroupPrefix, "/") || customIDs()[id] {
return id + "-plugin"
}
return id
+3
View File
@@ -782,6 +782,9 @@ func Save(p Provider) error {
if p.ID == strings.TrimSuffix(GroupPrefix, "/") {
return errors.New(`"group" starts the ids of routing groups; pick another id`)
}
if p.ID == autoID && !stored(p.ID) { // one saved before keeps it (autoRefsOn)
return errAutoID
}
if err := settings.CheckProxy(p.Proxy); err != nil {
return err
}
+2
View File
@@ -47,6 +47,8 @@ func Rename(from, to string) error {
return errors.New(`"magpie" is what agents call the gateway itself; pick another id`)
case to == strings.TrimSuffix(GroupPrefix, "/"):
return errors.New(`"group" starts the ids of routing groups; pick another id`)
case to == autoID:
return errAutoID
case subscriptionID(to):
return fmt.Errorf("%q is the id of the %s subscription; pick another", to, to)
}
+3 -3
View File
@@ -35,7 +35,7 @@ func TestSuffixMode(t *testing.T) {
if SuffixMode() != SuffixOn {
t.Fatalf("default %q", SuffixMode())
}
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}) {
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol · A", "auto/sol=Sol · routing group", "b/sol=Sol · B"}) {
t.Fatalf("on: %q", got)
}
@@ -45,7 +45,7 @@ func TestSuffixMode(t *testing.T) {
if s := settings.Load(); SuffixMode() != SuffixOwn || s.PlainNames || !s.PlainOwnNames || touched != 1 {
t.Fatalf("own: %q %+v, told %d", SuffixMode(), s, touched)
}
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}) {
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "auto/sol=Sol · routing group", "b/sol=Sol · B"}) {
t.Fatalf("own: %q", got)
}
if err := SetSuffixMode(SuffixOwn); err != nil || touched != 1 {
@@ -59,7 +59,7 @@ func TestSuffixMode(t *testing.T) {
t.Fatalf("off: %q %+v, told %d", SuffixMode(), s, touched)
}
// b's sol and the group found for it would both read "Sol": they keep theirs
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "b/sol=Sol · B", "group/auto-sol=Sol · routing group"}) {
if got := codex(); !slices.Equal(got, []string{"a/sol=My Sol", "auto/sol=Sol · routing group", "b/sol=Sol · B"}) {
t.Fatalf("off: %q", got)
}
+21 -8
View File
@@ -17,14 +17,19 @@ import (
// the two never differ.
// Names are what an entry answers to in a visibility: its family, and its
// provider's id or its group's id (as group/<id> too).
// provider's id or its group's id (as group/<id> too, and a found group's
// auto/<model>).
func (e Entry) Names() []string {
var out []string
if e.Family != "" {
out = append(out, e.Family)
}
if e.Group != "" {
return append(out, e.Group, GroupPrefix+e.Group)
out = append(out, e.Group, GroupPrefix+e.Group)
if e.ID != GroupPrefix+e.Group { // a found group's auto/<model>
out = append(out, e.ID)
}
return out
}
return append(out, e.Provider.ID)
}
@@ -90,17 +95,20 @@ func ListedFor(agent string) (listed, kept []Entry) {
return InOrder(agent, listed), kept
}
// HiddenModels are the ids of the entries taken out of agent's lists.
// HiddenModels are the ids of the entries taken out of agent's lists, a
// found group saved by its old id, group/auto-<slug>, by the one it is
// listed by now (PublicRef).
func HiddenModels(agent string) map[string]bool {
ids := heldSettings().HiddenModels[strings.ToLower(agent)]
out := make(map[string]bool, len(ids))
for _, id := range ids {
out[id] = true
out[PublicRef(id)] = true
}
return out
}
// PickedModels are the only entries agent's lists show, by id, and whether
// PickedModels are the only entries agent's lists show, by id (a found
// group by the id it is listed by now, PublicRef), and whether
// it is shown only those (#1337): a model not among them, one that came
// after the user switched to it among them, is not shown.
func PickedModels(agent string) (map[string]bool, bool) {
@@ -110,7 +118,7 @@ func PickedModels(agent string) (map[string]bool, bool) {
}
out := make(map[string]bool, len(ids))
for _, id := range ids {
out[id] = true
out[PublicRef(id)] = true
}
return out, true
}
@@ -308,9 +316,14 @@ func Families() []string {
}
// ModelOrder is the order the user put agent's models in (OrderedModels),
// by entry id; none when they never did.
// by entry id, a found group by the id it is listed by now (PublicRef);
// none when they never did.
func ModelOrder(agent string) []string {
return slices.Clone(heldSettings().OrderedModels[strings.ToLower(agent)])
ids := slices.Clone(heldSettings().OrderedModels[strings.ToLower(agent)])
for i, id := range ids {
ids[i] = PublicRef(id)
}
return ids
}
// SetModelOrder lists agent's models in this order, by entry id: the ones
+1 -1
View File
@@ -104,7 +104,7 @@ func buddyGateway(dir, id string) bool {
return false
}
id = id[len(local):]
return strings.HasPrefix(id, provider.GroupPrefix) || buddyGatewayIDs(dir)[id]
return provider.IsGroupRef(id) || buddyGatewayIDs(dir)[id]
}
// wbEntry is what is read of a models.json entry: its id and whose it is.
+1 -1
View File
@@ -91,7 +91,7 @@ func agentLabel(id string) string {
// goes only when models.dev knows it, else as "other"; a subscription's
// or plugin's ids are its vendor's.
func modelLabel(ref string) string {
if strings.HasPrefix(ref, provider.GroupPrefix) {
if provider.IsGroupRef(ref) {
return "group"
}
p, m, ok := provider.Resolve(ref)
+5 -5
View File
@@ -199,7 +199,7 @@ func memberOptions(skip []string, self string) []agent.Option {
// agents see too (a provider kept for routing groups, a group's
// with listed=no, #1783), as the Routing view's picker offers
for _, e := range provider.Served() {
if slices.Contains(skip, e.ID) || e.ID == provider.GroupPrefix+self {
if slices.Contains(skip, e.ID) || slices.Contains(skip, provider.CanonicalRef(e.ID)) || e.Group != "" && e.Group == self {
continue
}
note := e.Name
@@ -414,7 +414,7 @@ func (m model) updateGroup(msg tea.KeyMsg) (tea.Model, tea.Cmd) {
m.openClassifier(g)
case "E", "F":
// the model's own effort and fast mode, whatever the agent asks
if onRule || n == 0 || strings.HasPrefix(g.Members[m.gsel], provider.GroupPrefix) {
if onRule || n == 0 || provider.IsGroupRef(g.Members[m.gsel]) {
return m, nil
}
id := g.Members[m.gsel]
@@ -557,7 +557,7 @@ func (m model) viewGroups() string {
}
nameW, idW := 0, 0
for _, g := range m.groups {
nameW, idW = max(nameW, lipgloss.Width(dash(g.Name))), max(idW, lipgloss.Width(provider.GroupPrefix+g.ID))
nameW, idW = max(nameW, lipgloss.Width(dash(g.Name))), max(idW, lipgloss.Width(g.Ref()))
}
visible := max(3, m.h-7)
start := 0
@@ -576,7 +576,7 @@ func (m model) viewGroups() string {
if i == m.grow {
marker, name = sCursor.Render("▸ "), sNameOn.Render(padRight(dash(g.Name), nameW))
}
line := pad + marker + name + " " + sFaint.Render(padRight(provider.GroupPrefix+g.ID, idW))
line := pad + marker + name + " " + sFaint.Render(padRight(g.Ref(), idW))
if g.Hidden {
b.WriteString(line + "\n")
continue
@@ -612,7 +612,7 @@ func (m model) viewGroup() string {
var b strings.Builder
b.WriteString(m.header("routing", g.Name))
b.WriteString("\n\n")
head := []string{provider.GroupPrefix + g.ID, groupRouting(g), staysName(g.Affinity)}
head := []string{g.Ref(), groupRouting(g), staysName(g.Affinity)}
if g.Context > 0 {
head = append(head, "context "+fmtTokens(g.Context))
}
+7 -1
View File
@@ -149,5 +149,11 @@ func SameSpelled(sent, served string) bool {
// serving another model than asked (莫 on Discord: group/auto-… answered
// by deepseek/deepseek-v4.1-flash, marked a swap).
func GroupRouted(sent, served string) bool {
return strings.TrimSpace(served) != "" && strings.HasPrefix(strings.TrimSpace(sent), provider.GroupPrefix)
return strings.TrimSpace(served) != "" && remoteGroup(strings.TrimSpace(sent))
}
// remoteGroup reports whether id is a routing group's id as a magpie
// gives it: group/<id>, or auto/<model> for a group it found.
func remoteGroup(id string) bool {
return strings.HasPrefix(id, provider.GroupPrefix) || strings.HasPrefix(id, provider.AutoPrefix)
}
+1 -1
View File
@@ -168,7 +168,7 @@
<h3>1 つのモデルを複数のプロバイダで</h3>
<p>グループとは、1 つまたは複数のプロバイダのモデルを、エージェントが 1 つとして選べるようにまとめたものです。ピッカーの <em>Routing groups</em> の下に <code>group/&lt;id&gt;</code> として表示されます。2 つのプロバイダが同じ名前で提供しているモデルは、それだけでグループになります。<span class="ui">Routing</span> タブの <span class="ui">New group</span> では、好きなモデルを組み合わせてグループを作れます。グループで何ができるかは、最初のモデルが基準になります。</p>
<div class="callout"><b>何もしなくてもできるグループ。</b> すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ <code>group/auto-&lt;model&gt;</code> を自動で作ります。名前はベンダーごとの表記の違い(<code>deepseek/deepseek-chat</code>、<code>deepseek-chat</code>)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは <code>magpie group rm</code> で非表示にできます。</div>
<div class="callout"><b>何もしなくてもできるグループ。</b> すでに持っているモデルを提供する 2 つ目のプロバイダを追加すると(Claude サブスクリプションと Copilot の Claude Opus、DeepSeek 自身の API と OpenRouter の DeepSeek など)、magpie はそれを提供するすべてのプロバイダにまたがるグループ <code>auto/&lt;model&gt;</code>(モデル自身の ID。例: <code>auto/claude-opus-4.6</code>。以前の <code>group/auto-…</code> も引き続き使えます)を自動で作ります。名前はベンダーごとの表記の違い(<code>deepseek/deepseek-chat</code>、<code>deepseek-chat</code>)を吸収して照合されます。エージェントにこれを選ぶとリクエストがすべてに分散されます。不要なものは <code>magpie group rm</code> で非表示にできます。</div>
<div class="table-wrap"><table>
<tr><th>ルーティング</th><th>先に使われるもの</th></tr>
<tr><td>スマート <code>smart</code></td><td>デフォルトです。メンバーのアカウントとキーをまとめて扱い(グループ内のグループは 1 つとして扱います。下記参照)、クォータに余裕のあるサブスクリプションのうち、利用枠が最も早く更新されるもの。基準は週の枠です。週の枠がなく 5 時間枠だけのアカウント(Claude Enterprise)は 5 時間枠で判断されるため、それより後に週の枠が更新されるものすべてより先になります。リセットのないクレジット(WorkBuddy のパッケージはそれぞれの日に失効します)は、残りのうち最も早く失効する時点で判断されるため、クレジットが最も早く失効する WorkBuddy アカウントが先になります。失敗後に休止中のものは最後に回ります。</td></tr>
+1 -1
View File
@@ -168,7 +168,7 @@
<h3>One model over several providers</h3>
<p>A group is several models, from one provider or many, that an agent picks as one: <code>group/&lt;id&gt;</code>, under <em>Routing groups</em> in the picker. A model two of your providers serve under the same name becomes a group on its own; <span class="ui">New group</span> in the <span class="ui">Routing</span> tab makes one of any models you like. The first model answers for what the group can do.</p>
<div class="callout"><b>Groups you get without doing anything.</b> Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, <code>group/auto-&lt;model&gt;</code>, over every provider that serves it. The name is matched however each vendor spells it (<code>deepseek/deepseek-chat</code>, <code>deepseek-chat</code>). Pick it for an agent to spread its requests over all of them; <code>magpie group rm</code> hides one you don’t want.</div>
<div class="callout"><b>Groups you get without doing anything.</b> Add a second provider that serves a model you already have — Claude Opus from your Claude subscription and from Copilot, DeepSeek from its own API and from OpenRouter — and magpie makes it a group by itself, <code>auto/&lt;model&gt;</code> (the model's own id, as in <code>auto/claude-opus-4.6</code>; the older <code>group/auto-…</code> id still works), over every provider that serves it. The name is matched however each vendor spells it (<code>deepseek/deepseek-chat</code>, <code>deepseek-chat</code>). Pick it for an agent to spread its requests over all of them; <code>magpie group rm</code> hides one you don’t want.</div>
<div class="table-wrap"><table>
<tr><th>Routing</th><th>What goes first</th></tr>
<tr><td>Smart <code>smart</code></td><td>The default. Over the members’ accounts and keys together (a group in the group as one, see below): of the subscriptions with quota to spare, the one whose allowance renews soonest. The week decides; an account with five hours and no week (Claude Enterprise) goes by its five hours, so ahead of every week renewing later. Credits with no reset (WorkBuddy’s packages, each ending on its own day) count as renewing when the soonest of those left run out, so the WorkBuddy account whose credits end first goes first. One resting after a failure goes last.</td></tr>
+1 -1
View File
@@ -168,7 +168,7 @@
<h3>跨供应商的同一个模型</h3>
<p>路由组是几个模型(来自一个或多个供应商),Agent 把它当作一个来选:<code>group/&lt;id&gt;</code>,在选择列表的 <em>路由组</em> 下面。两个供应商用同一个名字提供的模型会自动成组;在 <span class="ui">路由</span> 标签页点 <span class="ui">新建组</span> 可以把任意模型组到一起。排第一的模型决定这个组对外的能力。</p>
<div class="callout"><b>不用手动建的组。</b>再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:<code>group/auto-&lt;模型&gt;</code>,包含所有提供这个模型的供应商。名字按各家不同的写法匹配(<code>deepseek/deepseek-chat</code> 和 <code>deepseek-chat</code> 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 <code>magpie group rm</code> 隐藏。</div>
<div class="callout"><b>不用手动建的组。</b>再加一个供应商,只要它提供的模型和已有的同名(比如 Claude 订阅和 Copilot 都有 Claude Opus,DeepSeek 官方 API 和 OpenRouter 都有 DeepSeek),magpie 就会自动把它们组成一个路由组:<code>auto/&lt;模型&gt;</code>(模型自己的 id,比如 <code>auto/claude-opus-4.6</code>;以前的 <code>group/auto-…</code> 也照样能用),包含所有提供这个模型的供应商。名字按各家不同的写法匹配(<code>deepseek/deepseek-chat</code> 和 <code>deepseek-chat</code> 算同一个)。给 Agent 选这个组,请求就会分摊到这些供应商上;不想要的可以用 <code>magpie group rm</code> 隐藏。</div>
<div class="table-wrap"><table>
<tr><th>路由</th><th>谁排在前面</th></tr>
<tr><td>智能 <code>smart</code></td><td>默认。把成员的账号和 Key 放在一起排(组里的路由组算一个,见下文):还有余量的订阅里,额度最先重置的排第一。看周额度的重置时间;只有 5 小时额度、没有周额度的账号(如 Claude Enterprise)看它的 5 小时重置,所以排在所有更晚重置的周额度前面。没有重置时间的积分(WorkBuddy 的积分包,各自到期)按剩余积分最早过期的时间算,所以积分最先过期的 WorkBuddy 账号排第一。失败后在休息的排最后。</td></tr>