Files
magpie/internal/provider/autoref.go
T
yetone 3441035a2e routing: a group's member maps the reasoning level asked to the one sent
A Routing group that relays one long task across vendors sent every
member the same effort word, but one vendor's high is another's xhigh
(LuckymanJC on Discord). A member that follows the group may now carry
a map from the level asked to the level sent: Group.EffortMaps, json
effortMaps, keyed by the member's id as Members spells it.

- Default: no map, or a level the map doesn't name, goes as asked, so
  every group saved before is unchanged and nothing of the user's is
  overridden. A member fixed at an effort (or with several levels) and
  a rule's UseEffort still win over the map.
- SaveGroup keeps a map only for a plain member of the group (not
  :effort, not :a+b, not group/), drops pairs that send what was
  asked, lowercases, and refuses a word that isn't a reasoning level.
- Carried by member rename (groupfast RenameMember and the all-groups
  rename), provider rename, fold (and its fingerprint), share/import
  and CanonicalRef; on a collision the map already spelled so wins.
- Gateway: the level asked is the suffix's/agent pick, then the turn's
  pick, then the request's own (askedLevel: agentEffort, plus none for
  an Anthropic request with thinking disabled); the target is sent with
  withFixedEffort, fitted to the model's catalog levels unless none, and
  the trace's try records mappedFrom. Per candidate, so fallback and
  retries send each member its own; count_tokens sends no member effort.
- The group lists a mapped member's own levels plus the map's keys to
  agents (mappedLevels in buildGroupEntries).
- GUI: the member's reasoning menu has "Map levels…" (app menus only):
  a level asked, then As asked or one of the model's levels. The chip
  reads "Mapped reasoning", its title the pairs. Follow the group or a
  fixed level drops the map. zh, zh-TW, ja and de.
- docs/subsystems/gateway-routing.md says all of it.

Run (mote, at this tree):
- gofmt -l: clean. go vet (provider, gateway, gui), GOOS=linux go vet
  -tags nogui ./..., GOOS=windows go vet ./...: clean.
- go test ./internal/provider/: ok. go test -run
  'Effort|Level|Group|Fallback|Rule|Auto|Fixed' ./internal/gateway/: ok.
- node --test group-member-effort-map (30: chromium + webkit, en zh
  zh-TW ja de, 1100 and 420px) and group-member-levels: pass;
  i18n-en-no-cjk: pass. i18n-keys' "a plugin's words are its own" is
  red only for the three words it is red for on origin/main 922cc0ccf
  (#5332, #5426, #5482); this change's words are its own (two that Go
  source said too were reworded).
- go test -run 'Group|Budget|I18n' ./internal/gui/: ok.

Broken by hand, each red, then restored:
- gateway mappedLevel(nil, in): every TestMemberEffortMap* red.
- mappedLevels left out of buildGroupEntries: both levels tests red.
- group_share's rename left out: the import case red.
- RenameMember's rename left out: its case red.
- SaveGroup's cleanEffortMaps call left out: TestSaveGroupEffortMaps red.
- the editor save without effortMaps: 30 of 30 GUI red; moveTo's map
  cleanup left out: 10 of 30 red.

Not tried: a real cross-vendor relay with real accounts (the mapping is
checked on the request bodies the gateway sends to fake upstreams). The
CLI and TUI keep the map but have no editor for it. The full Go suite
and whole GUI suite run after the push, per the loop rules.

Reported-by: LuckymanJC (Discord)
2026-11-07 20:19:50 +08:00

235 lines
8.0 KiB
Go

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
}
}
g.EffortMaps = renamedEffortMaps(g.EffortMaps, CanonicalRef)
for i := range g.Rules {
g.Rules[i].MapUses(CanonicalRef)
}
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>, or an auto/<model> spelt otherwise than it is listed
// now (auto/glm-5-3-flash for auto/glm-5.3-flash), 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)
if strings.HasPrefix(s, AutoPrefix) {
s = CanonicalRef(s)
}
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(sharedGroups(), 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): the spelling models.dev gives the model most
// (catalog.Spelling: glm-5.3-flash whether the members serve glm-5-3-flash
// or glm-5.3-flash, XYenon on Discord), so the id doesn't follow the
// order the providers were added in, and the group's name is the one
// models.dev gives that spelling (autoGroups). Failing that, 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>. Every spelling it
// had before is still the group (CanonicalRef).
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) }
for _, m := range slices.Concat(own, alike) {
if s := catalog.Spelling(m); s != "" && !spaced(s) && "auto-"+Slug(sameModel(s)) == g.ID {
return s
}
}
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
}