Files
magpie/internal/provider/autoref.go
T
yetone f99d27abc2 routing: a rule names several models, tried in order
monkeyin_92 on X: "can a rule take several models? Otherwise one rule
with several models is several rules." A rule now takes more than one
model (Rule.More after Rule.Use; `more` in the group's JSON, use=a,b
typed). They go first in that order: when the first fails or rests the
rule's next takes the request, ahead of the models the later matching
rules name and the group's others.

Every reader of Rule.Use goes through Uses/SetUses/MapUses/Without/Names
in grouprule.go:
- cleanRules: each must be the group's, each named once; a pause names one.
- gateway: ruleFor's turn hold, tool rounds and outgrown turns, compaction
  (the rule's first that takes the summary, the others in Small),
  ruleMembers/ruleOver/applyRule, nestedRules and ruleLed (the one a
  nested group's turn stays on), modelRuled, ruleEffort (useEffort asked
  of each), ThenUses (leaves out all of the rule's own). RuleHit.More is
  in the trace; Instead from More has Unready false, one from a later
  rule Unready true, as before.
- ruledEntry: what the group takes is what every one of them takes.
- provider rename, auto/ refs, groupfast, a member's removal (a rule
  goes with its last), ShareGroup and its import (one this magpie hasn't
  is left out of the rule).
- CLI `group rule add use=a,b` and its listing; `group models-=` keeps a
  rule's other models. The TUI shows them joined and keeps the rule when
  one is deleted.
- GUI (plugins/routing): a chip per model, a + for the next one, an ×
  on each while there is more than one, a chip picks another in its place
  (app menu, no native select); the card's tooltip and the trace's why
  ("…so c/mini, which the rule names after it, goes first"), nested too;
  en, zh, zh-TW, ja, de.

Old data: a rule of one model writes no `more`, so groups saved before
read and save unchanged (TestRuleMoreOnDisk). An older magpie reads `use`
alone: its requests go to the first model, the others are plain group
members in group order; if it saves the group, `more` is dropped.

Tests: TestRuleSeveralModelsInOrder, TestRuleEffortReachesTheRulesNextModel,
TestRuleCompactPassesOverTheRulesSmallModel (gateway); TestCleanRulesSeveralModels,
TestRuleMoreOnDisk, TestRuleWithout, TestParseRuleSeveralModels,
TestThenUsesLeavesOutTheRulesOwn, TestRuledEntrySeveralModels,
TestSharedGroupRuleSeveralModels, TestRuleMoreRenamedAndKept (provider);
TestGroupRuleSeveralModelsCmd (cli); TestGroupTakeOutKeepsARulesOtherModels
(tui); routing-rule-models.test.cjs. Broken by hand: ruleMembers on Use
alone turns the first two gateway tests red.

Run at this head:
- gofmt -l clean; go vet -tags nogui clean with GOOS=linux and GOOS=windows
  for provider, gateway, cli, tui.
- go test -tags nogui -timeout 45m: internal/provider, internal/cli,
  internal/tui ok; internal/gateway ok (384s); the new gateway tests
  again after; internal/gui budgets ok.
- GUI: every routing-*.test.cjs plus i18n-keys, click-scroll and
  group-member-drag, chromium and webkit (en, zh, zh-TW, ja, de where the
  file has them): 1319 pass, 57 red. routing-rule-models passes in both.
  The reds are in files that are red the same on origin/main 42976f9a0,
  run there just now: routing-pause (#3410), routing-intent-entry
  (#3408), routing-rule-effort (#3411), routing-rule-remove (#3096,
  #3094), routing-manual (#3409), routing-steady (#3412, #1804),
  routing-live-patch (#2174), routing-time (#3465). The other 10 reds are
  routing-rule-drag.test.cjs, which is the next commit's and not in this one.
- Real run, sandbox HOME, built binary: three fake OpenAI vendors, group
  Mix = three/m, one/m, two/m, rule `use=one/m,two/m tokens=1`. one/m
  answers 429: the request went one -> two (not three, the group's
  first); the next went straight to two, the trace saying
  instead=two/m with more=[two/m].

Not tried: a real vendor account; the TUI by hand; Windows and Linux
runs (vet only).

Rebased onto 5b2b3d3f5 (10 commits, gateway, gui and routing's
client.js among them) and run again at the rebased pair's head
68701dfe4: gofmt -l clean; GOOS=linux and windows vet -tags nogui of
provider, gateway, cli, tui clean; go test -tags nogui -timeout 45m
internal/provider (171s), cli, tui, gateway (422s), gui (budgets): all
ok; GUI routing-rule-drag, routing-rule-models, routing-compact,
i18n-keys, click-scroll, group-member-drag in both engines all pass;
routing-rule-remove red as on main (#3096, #3094).
2026-10-25 13:32:12 +08:00

219 lines
7.2 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
}
}
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> 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
}