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)
This commit is contained in:
yetone
2026-11-07 20:19:50 +08:00
parent 922cc0ccf8
commit 3441035a2e
17 changed files with 879 additions and 14 deletions
+1
View File
@@ -306,6 +306,7 @@ recorded as a prediction failure (`noPrediction`).
- Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671).
- A member the user unchecked in its provider's model list is skipped (`unpicked` in [`group.go`](../../internal/provider/group.go), in `membersOff`; #3911, timonwong): the provider has picks and its served models lack it, as the Routing page strikes it, and the Routing card says it is not ready (`provider.ResolveRoute`). A provider with no picks still routes a model its list lacks (#2642), a decision model is still a decision group's, and a request naming the model itself still reaches it (`resolveIn` takes any `provider/model` of a provider that is on). `group_model_pick_test.go`.
- A member's suffix may join several levels with `+` (`provider/model:low+xhigh`, Garydesu on X): the agent picks among them. `provider.MemberLevels` splits it into `Member.Levels` and leaves `Effort` empty, so it isn't fixed; one level is still a fixed effort. The suffix is kept lowest first, each level once, and the whole stays the member's id, so its rules, fast, off and weight are keyed by it as for any member. The gateway fits the agent's ask to the member's own levels (`groupLevels` returns the candidate's `levels` first), and the group lists those for it to agents (`buildGroupEntries`), intersected with the other members' as usual. In the GUI the member's reasoning menu has "Several levels…". Tests: `TestMemberSeveralLevels` (provider), `TestMemberSeveralLevelsFollowAgent` (gateway), `group-member-levels.test.cjs`.
- A member that follows the group may map the level asked to the level sent (`Group.EffortMaps`, keyed by the member's id as Members spells it, json `effortMaps`; [`groupeffortmap.go`](../../internal/provider/groupeffortmap.go); LuckymanJC on Discord: a long task relayed across vendors, where one vendor's high is another's xhigh). With no map, or a level the map doesn't name, it goes as asked, so a group saved before is unchanged. `SaveGroup` keeps a map only for a plain member of the group (not one fixed at an effort or with several levels, not a `group/` member), drops pairs that send the level asked, and refuses a word that isn't a reasoning level. A member rename, a provider rename, a fold, a share and its import carry it (`renamedEffortMaps`: on a collision the map already spelled so wins). In the gateway the level asked is the model suffix's or the agent's pick, then the turn's pick, then the request's own (`askedLevel`: `agentEffort`, and `none` for an Anthropic request with thinking disabled); the map's target (`mappedLevel`, `ultra` read as `max`) is sent with `withFixedEffort`, fitted to the model's levels unless it is `none`, and the trace's try keeps the level asked (`mappedFrom`). A member's fixed effort and a rule's `UseEffort` still win. It is 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`). In the GUI the member's reasoning menu has "Map levels…": a level asked, then the one sent or "As asked". The CLI and TUI keep the map but don't edit it. Tests: `TestMemberEffortMap*` (gateway), `TestSaveGroupEffortMaps`, `TestGroupLevelsWithEffortMap` (provider), `group-member-effort-map.test.cjs`.
- A group offers agents the reasoning levels its members have in common (`groupEntries` in [`group.go`](../../internal/provider/group.go)), or the ones it names (`Group.Levels`, #295). A member that doesn't follow the agent's effort is left out of that: one fixed at an effort, one whose levels nothing knows (#597), one that thinks with no levels, one the user made reasonless, and one known not to think (`Entry.Quiet`), which the gateway sends no reasoning ask (`withoutReasoningAsk`, [`quiet.go`](../../internal/gateway/quiet.go)). A quiet member used to empty the group's levels, so Codex got its entry with no `supported_reasoning_levels`, showed no effort control and ran at its own medium (#2127, `TestGroupQuietMemberKeepsCodexEffortControl`).
- An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003, and Antigravity's, #4838). On an Antigravity account the level picks the family's variant, as a request's own effort does (`AntigravitySentID`, `TestAntigravityAgentEffort`). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then the effort the rule that put the member first sets (`Rule.UseEffort`), then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.
- In models.dev, entries from `deepseek`, `kimi-code-plan-cn` and `kimi-code-plan-global` gain `none` only when they have both a `toggle` and effort levels; the DeepSeek and Kimi APIs accepted that value in [#1098](https://github.com/yetone/magpie/issues/1098). Other providers keep their listed levels because their APIs may reject `none`; toggle-only entries remain level-less ([`mdModel.efforts`](../../internal/catalog/catalog.go)).
+35
View File
@@ -890,3 +890,38 @@ func agentEffort(proto provider.Protocol, body []byte) string {
}
return strings.ToLower(strings.TrimSpace(bodyEffort(proto, body)))
}
// askedLevel is the reasoning level a request asks for (agentEffort),
// and "none" for an Anthropic one that turns thinking off: a member's
// EffortMaps may send it a level all the same.
func askedLevel(proto provider.Protocol, body []byte) string {
if e := agentEffort(proto, body); e != "" || proto != provider.Anthropic {
return e
}
var v struct {
Thinking *struct {
Type string `json:"type"`
} `json:"thinking"`
}
if decodeJSON(body, &v) == nil && v.Thinking != nil && v.Thinking.Type == "disabled" {
return "none"
}
return ""
}
// mappedLevel is the level a member's map sends in place of in, and
// whether it names one. Codex's ultra is max with agents of its own, so
// a map from max takes it too.
func mappedLevel(to map[string]string, in string) (string, bool) {
if in == "" {
return "", false
}
if l, ok := to[in]; ok {
return l, true
}
if in == "ultra" {
l, ok := to["max"]
return l, ok
}
return "", false
}
+5 -1
View File
@@ -59,6 +59,10 @@ type candidate struct {
// (Member.Levels, "provider/model:low+high"): what the agent asks is
// sent at the nearest of them. nil for one fixed or following the group.
levels []string
// effortMap is, for a member following the group, the level it sends
// in place of the one asked for (Member.EffortMap); nil sends it as
// asked
effortMap map[string]string
// fast is set on a member the group sends in its vendor's fast mode
// (Group.Fast); ultra on an agent's fast pick sent Ultrafast (#1954)
fast, ultra bool
@@ -698,7 +702,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
// the same model at another effort is another member's
for _, l := range [][]candidate{cs, aside, left, barred} {
for i := range l {
l[i].effort, l[i].levels, l[i].fast = m.Effort, m.Levels, m.Fast
l[i].effort, l[i].levels, l[i].effortMap, l[i].fast = m.Effort, m.Levels, m.EffortMap, m.Fast
l[i].firstToken = innerFirstToken(m)
l[i].patience = innerPatience(m)
if len(m.Path) > 0 {
+28 -3
View File
@@ -3576,7 +3576,32 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// one, a suffix and the turn's pick are more particular
fixed = withinLevels(agentPick, levels)
}
if ruled != "" {
// a member that sends another level than the one asked (its
// EffortMaps, LuckymanJC on Discord: one vendor's high is
// another's xhigh) is sent that, whoever asked: a suffix, the
// agent's pick in magpie, the turn's pick or the agent itself. A
// rule's effort is the user's for this member already
mappedFrom, mapped := "", ""
if c.effort == "" && ruled == "" && len(c.effortMap) > 0 {
in := fixed
if in == "" && effort != "" {
in = withinLevels(effort, levels)
}
if in == "" {
in = withinLevels(askedLevel(from, attemptBody), levels)
}
if to, ok := mappedLevel(c.effortMap, in); ok {
mappedFrom, mapped = in, to
}
}
if mapped != "" {
// "none" turns its reasoning off; another level is asked at
// the one its model has nearest, as a fixed member's is
if mapped != "none" {
mapped = fitLevel(mapped, c.p.Efforts(c.model))
}
attemptBody = withFixedEffort(from, attemptBody, mapped)
} else if ruled != "" {
// asked even of a request that asked for no reasoning, as a
// member fixed at an effort is; already fitted to its levels
attemptBody = withFixedEffort(from, attemptBody, ruled)
@@ -3681,7 +3706,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
window := windowOf(c.p, c.model) // as the route's end reads it
s.trace.update(tr, func(t *Route) {
t.imageProvider = c.p.ID
t.Tries = append(t.Tries, Try{ID: c.rest, Model: c.model, Effort: sent, Picked: picked, Fixed: fixed, RuleEffort: ruled, Fast: fast, Start: began})
t.Tries = append(t.Tries, Try{ID: c.rest, Model: c.model, Effort: sent, Picked: picked, Fixed: fixed, RuleEffort: ruled, MappedFrom: mappedFrom, Fast: fast, Start: began})
t.window = window
if t.Prompt != nil && !t.Done {
t.Prompt = livePrompt(t.Prompt, window)
@@ -3950,7 +3975,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
wentTier = at.tier
ended = time.Now()
try := Try{ID: c.rest, Model: c.model, Effort: wentAt, Picked: picked, Fixed: fixed, RuleEffort: ruled, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: ended.Sub(began).Milliseconds(), Error: call.Error, Queued: queued,
try := Try{ID: c.rest, Model: c.model, Effort: wentAt, Picked: picked, Fixed: fixed, RuleEffort: ruled, MappedFrom: mappedFrom, Fast: fast, Start: began, Done: true, Status: call.Status, Millis: ended.Sub(began).Milliseconds(), Error: call.Error, Queued: queued,
Served: call.Usage.Served, Upstream: call.Usage.Upstream, Pin: c.p.ClinePassAsked(c.model), Tier: wentTier, TierServed: call.Usage.Tier, Auto: autoPicked(),
Net: nt.timing(began, queued), SentBy: sentBy(c.p)}
if resetFirst != nil {
+201
View File
@@ -0,0 +1,201 @@
package gateway
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// setEffortMaps gives group/r's members (as Members spells them) these
// effort maps.
func setEffortMaps(t *testing.T, maps map[string]map[string]string) {
t.Helper()
g, _, _ := provider.FindGroup("group/r")
g.EffortMaps = nil
for id, to := range maps {
g.SetMemberEffortMap(id, to)
}
if err := provider.SaveGroup(g); err != nil {
t.Fatal(err)
}
}
// A member with an effort map (LuckymanJC on Discord: one vendor's high
// is another's xhigh) is sent the level its map names for the one asked,
// in each API's words, and a level the map doesn't name as it was asked.
func TestMemberEffortMap(t *testing.T) {
s, a, _ := ruled(t)
if err := provider.SetModelEfforts("a/small", []string{"low", "medium", "high", "xhigh"}); err != nil {
t.Fatal(err)
}
setEffortMaps(t, map[string]map[string]string{"a/small": {"high": "xhigh", "low": "medium", "none": "low"}})
for _, c := range []struct{ asked, want, from string }{
{"high", "xhigh", "high"},
{"low", "medium", "low"},
{"medium", "medium", ""}, // not in the map: as asked
{"xhigh", "xhigh", ""},
{"none", "low", "none"},
} {
out, r := postOK(t, s, "", chat("hi", nil, 0, `,"reasoning_effort":"`+c.asked+`"`))
if sent := sentBody(t, a); !strings.Contains(out, "from ka") || sent["reasoning_effort"] != c.want {
t.Errorf("chat asked %s: sent %v", c.asked, sent["reasoning_effort"])
}
if len(r.Tries) != 1 || r.Tries[0].Effort != c.want || r.Tries[0].MappedFrom != c.from || r.Tries[0].Fixed != "" {
t.Errorf("chat asked %s: traced %+v", c.asked, r.Tries)
}
}
// a request asking for no reasoning (a session title) is left without
postOK(t, s, "", chat("hi", nil, 0, ""))
if sent := sentBody(t, a); sent["reasoning_effort"] != nil {
t.Errorf("no ask: sent %v", sent["reasoning_effort"])
}
// Responses
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"group/r","input":"hi","reasoning":{"effort":"high","summary":"auto"}}`)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if sent := sentBody(t, a); sent["reasoning_effort"] != "xhigh" {
t.Errorf("responses high: sent %v", sent["reasoning_effort"])
}
// Anthropic: its effort, its budget, and thinking turned off ("none")
anthropic := func(body string) map[string]any {
t.Helper()
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
return sentBody(t, a)
}
if sent := anthropic(`{"model":"group/r","max_tokens":64000,"thinking":{"type":"adaptive"},"output_config":{"effort":"high"},"messages":[{"role":"user","content":"hi"}]}`); sent["reasoning_effort"] != "xhigh" {
t.Errorf("anthropic effort high: sent %v", sent["reasoning_effort"])
}
if sent := anthropic(`{"model":"group/r","max_tokens":64000,"thinking":{"type":"enabled","budget_tokens":4096},"messages":[{"role":"user","content":"hi"}]}`); sent["reasoning_effort"] != "medium" {
t.Errorf("anthropic budget 4096 (low): sent %v", sent["reasoning_effort"])
}
if sent := anthropic(`{"model":"group/r","max_tokens":64000,"thinking":{"type":"disabled"},"messages":[{"role":"user","content":"hi"}]}`); sent["reasoning_effort"] != "low" {
t.Errorf("anthropic thinking off: sent %v", sent["reasoning_effort"])
}
// a model's suffix is asked through the map too
postOK(t, s, "", strings.Replace(chat("hi", nil, 0, `,"reasoning_effort":"low"`), `"group/r"`, `"group/r:high"`, 1))
if sent := sentBody(t, a); sent["reasoning_effort"] != "xhigh" {
t.Errorf("group/r:high: sent %v", sent["reasoning_effort"])
}
// a level the model hasn't is sent at its nearest
setEffortMaps(t, map[string]map[string]string{"a/small": {"high": "max"}})
postOK(t, s, "", chat("hi", nil, 0, `,"reasoning_effort":"high"`))
if sent := sentBody(t, a); sent["reasoning_effort"] != "xhigh" {
t.Errorf("high to max on a model up to xhigh: sent %v", sent["reasoning_effort"])
}
}
// Without a map a member is sent the level asked, as before; each
// member's map is its own, the one fallen back to included.
func TestMemberEffortMapPerMember(t *testing.T) {
s, a, b := ruled(t)
if err := provider.SetModelEfforts("b/big", []string{"low", "medium", "high", "xhigh"}); err != nil {
t.Fatal(err)
}
postOK(t, s, "", chat("hi", nil, 0, `,"reasoning_effort":"high"`))
if sent := sentBody(t, a); sent["reasoning_effort"] != "high" {
t.Fatalf("no map: sent %v", sent["reasoning_effort"])
}
setEffortMaps(t, map[string]map[string]string{"b/big": {"high": "xhigh"}})
postOK(t, s, "", chat("hi", nil, 0, `,"reasoning_effort":"high"`))
if sent := sentBody(t, a); sent["reasoning_effort"] != "high" {
t.Fatalf("a without a map: sent %v", sent["reasoning_effort"])
}
a.mu.Lock()
a.fail = 500
a.mu.Unlock()
out, r := postOK(t, s, "", chat("hi", nil, 0, `,"reasoning_effort":"high"`))
if sent := sentBody(t, b); !strings.Contains(out, "from kb") || sent["reasoning_effort"] != "xhigh" {
t.Fatalf("fallback to b: sent %v (%s)", sent, out)
}
last := r.Tries[len(r.Tries)-1]
if last.Model != "big" || last.Effort != "xhigh" || last.MappedFrom != "high" || r.Tries[0].MappedFrom != "" {
t.Fatalf("fallback traced %+v", r.Tries)
}
}
// The map is asked after the group's classifier picks the turn's level
// (effort=auto): the pick is what the member is asked for.
func TestMemberEffortMapOverAuto(t *testing.T) {
s, a, _, j := jevved(t, provider.EffortAuto)
if err := provider.SetModelEfforts("a/small", []string{"low", "medium", "high", "xhigh"}); err != nil {
t.Fatal(err)
}
setEffortMaps(t, map[string]map[string]string{"a/small": {"high": "xhigh"}})
j.score = 2.4 // high
_, r := postOK(t, s, "s1", chat("redesign the scheduler", nil, 0, `,"reasoning_effort":"low"`))
if sent := sentBody(t, a); sent["reasoning_effort"] != "xhigh" {
t.Fatalf("sent %v", sent["reasoning_effort"])
}
if r.Rule == nil || r.Rule.Pick != "high" || r.Tries[0].MappedFrom != "high" || r.Tries[0].Effort != "xhigh" {
t.Fatalf("traced %+v %+v", r.Rule, r.Tries)
}
}
// A member fixed at an effort keeps it: a map on it is not kept.
func TestMemberEffortMapNotOnFixed(t *testing.T) {
s, a, _ := ruled(t)
setMembers(t, []string{"a/small:low", "b/big"})
setEffortMaps(t, map[string]map[string]string{"a/small:low": {"high": "xhigh"}})
if g, _, _ := provider.FindGroup("group/r"); g.EffortMaps != nil {
t.Fatalf("kept %v", g.EffortMaps)
}
postOK(t, s, "", chat("hi", nil, 0, `,"reasoning_effort":"high"`))
if sent := sentBody(t, a); sent["reasoning_effort"] != "low" {
t.Fatalf("sent %v", sent["reasoning_effort"])
}
}
// /v1/models offers, for a member with a map, the levels its map is asked
// for besides its model's own.
func TestMemberEffortMapLevelsListed(t *testing.T) {
s, _, _ := ruled(t)
if err := provider.SetModelEfforts("a/small", []string{"low", "medium", "high"}); err != nil {
t.Fatal(err)
}
if err := provider.SetModelEfforts("b/big", []string{"medium", "high", "xhigh"}); err != nil {
t.Fatal(err)
}
setEffortMaps(t, map[string]map[string]string{"a/small": {"xhigh": "high"}})
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
got := levelsListed(t, rec.Body.Bytes(), "group/r")
if strings.Join(got, ",") != "medium,high,xhigh" {
t.Fatalf("levels %v", got)
}
}
// levelsListed are the reasoning levels /v1/models' body lists for id.
func levelsListed(t *testing.T, body []byte, id string) []string {
t.Helper()
var list struct {
Data []struct {
ID string `json:"id"`
Levels []struct {
Effort string `json:"effort"`
} `json:"supported_reasoning_levels"`
} `json:"data"`
}
if err := json.Unmarshal(body, &list); err != nil {
t.Fatalf("%v: %s", err, body)
}
for _, m := range list.Data {
if m.ID == id {
var out []string
for _, l := range m.Levels {
out = append(out, l.Effort)
}
return out
}
}
t.Fatalf("%s not listed: %s", id, body)
return nil
}
+4 -1
View File
@@ -448,7 +448,10 @@ type Try struct {
Fixed string `json:"fixed,omitempty"`
// RuleEffort: the reasoning the group's rule asks the member for
// (Rule.UseEffort, #2633), which Effort is whatever was asked
RuleEffort string `json:"ruleEffort,omitempty"`
RuleEffort string `json:"ruleEffort,omitempty"`
// MappedFrom: the level asked for, which the group's member it went
// to sends Effort in place of (Group.EffortMaps)
MappedFrom string `json:"mappedFrom,omitempty"`
Fast bool `json:"fast,omitempty"` // sent in its vendor's fast mode, as the group's member it went to is
Start time.Time `json:"start"`
Done bool `json:"done"`
+42 -8
View File
@@ -5681,9 +5681,14 @@ function routingPage(part) {
const opt = (v, f) => v === undefined ? v : f(v);
// a member's weight is a whole number; anything else is none
const weightsOf = (v) => Object.fromEntries(Object.entries(v && typeof v === "object" && !Array.isArray(v) ? v : {}).filter(([, n]) => Number.isInteger(n)));
// a member's effort map is levels to levels (provider.Group.EffortMaps)
const isObj = (v) => v && typeof v === "object" && !Array.isArray(v);
const words = ["none", "minimal", "low", "medium", "high", "xhigh", "max"]; // provider.MemberEfforts
const effortMapsOf = (v) => Object.fromEntries(Object.entries(isObj(v) ? v : {}).filter(([, m]) => isObj(m))
.map(([id, m]) => [id, Object.fromEntries(Object.entries(m).filter(([a, b]) => words.includes(a) && words.includes(b)))]));
const group = (g) => ({ ...g, id: String(g.id ?? ""), name: typeof g.name === "string" && g.name ? g.name : String(g.id ?? ""),
members: ids(g.members), memberInfo: objs(g.memberInfo), holds: ids(g.holds), offers: ids(g.offers), shared: ids(g.shared), patterns: objs(g.patterns),
match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), levels: opt(g.levels, ids), weights: opt(g.weights, weightsOf),
match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), levels: opt(g.levels, ids), weights: opt(g.weights, weightsOf), effortMaps: opt(g.effortMaps, effortMapsOf),
rules: opt(g.rules, (rs) => objs(rs).map((r) => ({ ...r, agents: opt(r.agents, ids), folders: opt(r.folders, ids), exceptFolders: opt(r.exceptFolders, ids) }))) });
const refs = (v) => objs(v).filter((m) => typeof m.id === "string");
return { ...x, groups: objs(x.groups).filter((g) => typeof g.id === "string" && g.id).map(group),
@@ -5811,7 +5816,7 @@ function routingPage(part) {
// there, rather than leaving the slot empty.
const openGroupEditor = async (g) => {
if (groupDirty() && !(await confirmDiscard())) return false;
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
gEdit = { id: g.id, draft: { name: g.name, members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink, unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: patienceOf(g.patience), context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } };
renderGroups();
return true;
};
@@ -6572,7 +6577,7 @@ function routingPage(part) {
closeProtoMenu();
if (v === cur || (groupDirty() && !(await confirmDiscard()))) return b.focus({ preventScroll: true });
const n = opts.find(([id]) => id === v)?.[1] || v;
await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists },
await groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists },
t("{name}: {routing}", { name: g.name, routing: t(n) }));
// the rows were drawn anew: the keyboard stays on this one's routing
gList.querySelector(`.rt-group[data-id="${CSS.escape(g.id)}"] .rt-groute`)?.focus({ preventScroll: true });
@@ -6705,7 +6710,7 @@ function routingPage(part) {
b.onclick = (e) => {
e.stopPropagation(); // the card opens the editor; this picks
if (on) return;
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, accounts: g.accounts || [], unlists: !!g.unlists },
groupAction("save", { id: g.id, name: g.name, members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists },
t("{name}: every request to {model}", { name: g.name, model: memberName(id) }));
};
box.append(b);
@@ -6719,6 +6724,7 @@ function routingPage(part) {
// and did nothing (悠悠哥 on Discord)
for (const k of ["members", "match", "matched", "fast", "off", "rules", "accounts"]) if (!Array.isArray(d[k])) d[k] = [];
if (!d.weights || typeof d.weights !== "object") d.weights = {};
if (!d.effortMaps || typeof d.effortMaps !== "object") d.effortMaps = {};
const ed = el("div", "editor rt-gedit");
ed.dataset.gslot = g ? g.id : "";
const h = el("div", "ehead");
@@ -6941,9 +6947,15 @@ function routingPage(part) {
if (!s && !deciderOf(id) && !drawerOf(id)) {
const [base, fixed] = splitMember(id);
const several = fixed.includes("+");
const fx = el("button", "rt-cond rt-fixed" + (fixed ? " on" : ""), fixed ? fixedWords(fixed) : t("Group's reasoning"));
// the levels it sends in place of those asked (LuckymanJC on
// Discord: one vendor's high is another's xhigh), for one that
// follows the group (provider.Group.EffortMaps)
const map = !fixed && d.effortMaps[id] && Object.keys(d.effortMaps[id]).length ? d.effortMaps[id] : null;
const pairs = map ? LEVELS.filter((v) => map[v]).map((v) => `${v} → ${map[v]}`).join(", ") : "";
const fx = el("button", "rt-cond rt-fixed" + (fixed || map ? " on" : ""), fixed ? fixedWords(fixed) : map ? t("Mapped reasoning") : t("Group's reasoning"));
fx.title = several ? t("The agent picks among {levels} reasoning, each sent at the model's nearest level", { levels: fixed.split("+").join(" / ") })
: fixed ? t("Sent at {level} reasoning whatever the agent asks, at the model's nearest level", { level: fixed }) : t("Reasons as the group's effort says");
: fixed ? t("Sent at {level} reasoning whatever the agent asks, at the model's nearest level", { level: fixed })
: map ? t("Sent {pairs}; other levels as asked", { pairs }) : t("Reasons as the group's effort says");
const levels = m?.efforts?.length ? m.efforts.filter((v) => LEVELS.includes(v)) : LEVELS.filter((v) => v !== "none" && v !== "minimal");
// the member under another id: its rules, fast, off, weight and
// pick go with it
@@ -6957,6 +6969,9 @@ function routingPage(part) {
d.fast = d.fast.map((x) => x === from ? to : x);
d.off = d.off.map((x) => x === from ? to : x);
if (d.weights[from]) { d.weights[to] = d.weights[from]; delete d.weights[from]; }
// a map goes with it while it follows the group; one fixed at
// a level, or among several, sends those
if (d.effortMaps[from]) { if (!splitMember(to)[1]) d.effortMaps[to] = d.effortMaps[from]; delete d.effortMaps[from]; }
if (d.pick === from) d.pick = to;
return true;
};
@@ -6974,14 +6989,33 @@ function routingPage(part) {
draw(); drawRules();
} }, fx, ev);
};
// a level asked, then the one sent for it: the model's own
// levels, or as asked; a member fixed at a level follows the
// group again once a level is mapped
const pickMap = (ev) => {
const have = (!fixed && d.effortMaps[id]) || {};
pickFrom("reasoning", fx, ev, LEVELS.map((v) => ({ value: v, label: v, note: have[v] ? `→ ${have[v]}` : t("As asked") })), (from) => {
pickFrom("reasoning", fx, ev, [{ value: "", label: t("As asked") }, ...levels.filter((v) => v !== from).map((v) => ({ value: v, label: v }))], (to) => {
if (fixed && !moveTo(base)) return;
if (fixed) drawRules();
const next = { ...(d.effortMaps[base] || {}) };
if (to && to !== from) next[from] = to; else delete next[from];
if (Object.keys(next).length) d.effortMaps[base] = next; else delete d.effortMaps[base];
draw();
}, have[from] || "");
});
};
fx.onclick = (ev) => pickFrom("reasoning", fx, ev, [
{ value: "", label: t("Follow the group"), note: t("as the group's effort says") },
...levels.map((v) => ({ value: v, label: fixedWords(v), note: t("whatever the agent asks") })),
...(levels.length > 1 ? [{ value: "+", label: t("Several levels…"), note: t("the agent picks among them") }] : []),
...(levels.length > 1 ? [{ value: "=", label: t("Map levels…"), note: t("a level in place of the one asked") }] : []),
], (v) => {
if (v === "+") { pickSeveral(ev); return; }
if (v === "=") { pickMap(ev); return; }
if (!v && !fixed) { delete d.effortMaps[id]; draw(); return; } // the group's, as asked
if (moveTo(v ? `${base}:${v}` : base)) { draw(); drawRules(); }
}, several ? "+" : fixed);
}, several ? "+" : map ? "=" : fixed);
row.append(fx);
// its vendor's fast mode, where the model has one: priority
// processing, Claude's fast mode (provider.CanFast)
@@ -8010,7 +8044,7 @@ function routingPage(part) {
if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn");
saveBtn.classList.add("busy");
// refused, Add can be pressed again (busy, it takes no clicks)
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: !!d.sink && sinkable(d.routing), firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() }))
.then(() => saveBtn.classList.remove("busy"));
};
// what goes wrong is said where it is seen, never a click that does nothing
@@ -311,6 +311,11 @@ magpie.strings({
"Reasons as the group's effort says": "推理强度按分组的设置",
"Follow the group": "跟随分组",
"Several levels…": "多个强度…",
"Mapped reasoning": "映射推理强度",
"Sent {pairs}; other levels as asked": "按 {pairs} 发送,其他强度按要求",
"Map levels…": "映射强度…",
"a level in place of the one asked": "以另一档强度代替所要求的",
"As asked": "按要求",
"the agent picks among them": "由 Agent 从中选择",
"The agent picks among {levels} reasoning, each sent at the model's nearest level": "由 Agent 在 {levels} 推理强度中选择,各取模型最接近的档位",
"{name} at that reasoning is in the group already": "{name} 以这个推理强度已经在分组里了",
@@ -979,6 +984,11 @@ magpie.strings({
"Reasons as the group's effort says": "推理強度按分組的設定",
"Follow the group": "跟隨分組",
"Several levels…": "多個強度…",
"Mapped reasoning": "映射推理強度",
"Sent {pairs}; other levels as asked": "按 {pairs} 傳送,其他強度按要求",
"Map levels…": "映射強度…",
"a level in place of the one asked": "以另一檔強度代替所要求的",
"As asked": "按要求",
"the agent picks among them": "由 Agent 從中選擇",
"The agent picks among {levels} reasoning, each sent at the model's nearest level": "由 Agent 在 {levels} 推理強度中選擇,各取模型最接近的檔位",
"{name} at that reasoning is in the group already": "{name} 以這個推理強度已經在分組裡了",
@@ -1645,6 +1655,11 @@ magpie.strings({
"Reasons as the group's effort says": "グループの推論レベルに従います",
"Follow the group": "グループに従う",
"Several levels…": "複数のレベル…",
"Mapped reasoning": "推論レベルを対応付け",
"Sent {pairs}; other levels as asked": "{pairs} で送信し、他のレベルは要求どおり",
"Map levels…": "レベルを対応付け…",
"a level in place of the one asked": "要求されたレベルの代わりに別のレベル",
"As asked": "要求どおり",
"the agent picks among them": "エージェントがその中から選びます",
"The agent picks among {levels} reasoning, each sent at the model's nearest level": "エージェントが {levels} の推論から選び、それぞれモデルの最も近いレベルで送ります",
"{name} at that reasoning is in the group already": "この推論レベルの {name} はすでにグループにあります",
@@ -2313,6 +2328,11 @@ magpie.strings({
"Reasons as the group's effort says": "Reasoning gemäß Effort der Gruppe",
"Follow the group": "Der Gruppe folgen",
"Several levels…": "Mehrere Stufen…",
"Mapped reasoning": "Zugeordnetes Reasoning",
"Sent {pairs}; other levels as asked": "Gesendet {pairs}; andere Stufen wie angefragt",
"Map levels…": "Stufen zuordnen…",
"a level in place of the one asked": "eine Stufe statt der angefragten",
"As asked": "Wie angefragt",
"the agent picks among them": "der Agent wählt daraus",
"The agent picks among {levels} reasoning, each sent at the model's nearest level": "Der Agent wählt unter {levels} Reasoning, jeweils auf der nächstgelegenen Stufe des Modells gesendet",
"{name} at that reasoning is in the group already": "{name} mit diesem Reasoning ist bereits in der Gruppe",
@@ -0,0 +1,204 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A group that relays one task across vendors sends each member the level
// the vendor means (LuckymanJC on Discord: one vendor's high is another's
// xhigh). In the group editor a member's reasoning menu has "Map levels…":
// a level asked, then the one sent for it, from the model's own levels or
// "As asked". The chip says the member is mapped and its title the pairs;
// the save carries effortMaps for that member only; a fixed level picked
// later drops the map, and so does "Follow the group". A member fixed at a
// level that gets a map follows the group again. Nothing on the page
// moves. In every language, Chromium and WebKit, at a wide and a narrow
// window.
const assert = require("node:assert/strict");
const fs = require("node:fs/promises");
const path = require("node:path");
const { test } = require("node:test");
const { chromium, webkit } = require("playwright");
const assets = path.resolve(__dirname, "../assets");
const models = [
{ id: "oa/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "OpenAI", icon: "generic", efforts: ["low", "medium", "high", "xhigh"], canFast: true },
{ id: "rl/glm-5", name: "glm-5", providerName: "Relay", icon: "generic", efforts: ["low", "high"] },
];
const groups = (members, effortMaps) => ({
models, pools: [],
groups: [{ id: "sol", name: "Sol", members, effortMaps, routing: "order", ready: true,
memberInfo: members.map((id) => ({ id, ready: true, canFast: id.startsWith("oa/") })) }],
});
const words = {
en: { edit: "Edit", save: "Save", map: "Map levels…", follow: "Follow the group", mapped: "Mapped reasoning", asked: "As asked",
title: "Sent low → medium, high → xhigh; other levels as asked" },
zh: { edit: "编辑", save: "保存", map: "映射强度…", follow: "跟随分组", mapped: "映射推理强度", asked: "按要求" },
"zh-TW": { edit: "編輯", save: "儲存", map: "映射強度…", follow: "跟隨分組", mapped: "映射推理強度", asked: "按要求" },
ja: { edit: "編集", save: "保存", map: "レベルを対応付け…", follow: "グループに従う", mapped: "推論レベルを対応付け", asked: "要求どおり" },
de: { edit: "Bearbeiten", save: "Speichern", map: "Stufen zuordnen…", follow: "Der Gruppe folgen", mapped: "Zugeordnetes Reasoning", asked: "Wie angefragt" },
};
function serve(lang, posts, members, maps) {
const state = { agents: [{ id: "codex", name: "Codex", path: "/test/codex", fields: [] }], profiles: [], settings: { lang, theme: "light" } };
return async (r) => {
const url = new URL(r.request().url());
const json = (data) => r.fulfill({ json: data });
if (url.pathname === "/boot.js") return r.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return r.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/gateway/trace") {
if (url.searchParams.get("wait")) return new Promise(() => {}); // nothing more comes
return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] });
}
if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] });
if (url.pathname === "/api/groups") return json(groups(members, maps));
if (url.pathname.startsWith("/api/groups/")) {
posts.push({ path: url.pathname, body: JSON.parse(r.request().postData() || "{}") });
return json(groups(members, maps));
}
if (url.pathname === "/api/providers") return json({ providers: [], presets: [], excluded: [], gateway: { running: true, window: true, url: "http://127.0.0.1:3999" } });
if (url.pathname.startsWith("/api/")) return json({});
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
await r.fulfill({ body: await fs.readFile(file), contentType });
};
}
async function open(engine, lang, width, members, t, maps) {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
const page = await (await browser.newContext({ viewport: { width, height: 1600 }, reducedMotion: "reduce" })).newPage();
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-group-member-effort-map.png`) });
}
await browser.close();
});
page.setDefaultTimeout(5000);
page.setDefaultNavigationTimeout(60000);
const errors = [], posts = [];
page.on("pageerror", (e) => errors.push(e.message));
await page.route("**/*", serve(lang, posts, members, maps));
await page.goto("http://magpie.test/?view=groups");
const card = page.locator(".rt-group", { hasText: "Sol" });
await card.waitFor();
return { page, card, errors, posts };
}
const keys = ["Map levels…", "a level in place of the one asked", "Mapped reasoning", "Sent {pairs}; other levels as asked", "As asked"];
const option = (page, text) => page.locator("#pop:not([hidden]) #list li:not(.group)", { has: page.locator(".v", { hasText: new RegExp("^" + text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "$") }) });
const shut = (page) => page.waitForFunction(() => document.querySelector("#pop").hidden);
async function save(page, w) {
const b = page.locator(".rt-gedit button.primary", { hasText: w.save });
await b.scrollIntoViewIfNeeded();
await b.click();
await page.waitForFunction(() => !document.querySelector(".rt-gedit"));
}
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of Object.keys(words)) {
for (const width of [1100, 420]) {
const w = words[lang];
test(`${engine} ${lang} ${width}px: a group's member maps the levels asked`, async (t) => {
const { page, card, errors, posts } = await open(engine, lang, width, ["oa/gpt-6.1-sol", "rl/glm-5"], t);
await card.locator("button", { hasText: w.edit }).click();
const ed = page.locator(".rt-gedit");
const row = (name) => ed.locator(".fbrow", { has: page.locator(".n", { hasText: name }) });
const chip = () => row("gpt-6.1-sol").locator("button.rt-fixed:not(.rt-fast)");
await chip().waitFor();
await chip().evaluate((x) => x.scrollIntoView({ block: "center" })); // by the test, as the reader would
await page.waitForTimeout(200);
const at = () => page.evaluate(() => [...document.querySelectorAll("*")].filter((e) => e.scrollTop && !e.closest("#pop")).map((e) => [e.id || e.className, e.scrollTop]).join(";") + "|" + Math.round(document.querySelector(".rt-gedit").getBoundingClientRect().top));
const before = await at();
const pair = async (from, to) => {
await chip().click();
await option(page, w.map).click();
// every level that can be asked
await option(page, from).waitFor();
assert.deepEqual(await page.locator("#pop #list li:not(.group) .v").allTextContents(), ["none", "minimal", "low", "medium", "high", "xhigh", "max"]);
await option(page, from).click();
// then as asked, or the model's own others
await option(page, w.asked).waitFor();
assert.deepEqual(await page.locator("#pop #list li:not(.group) .v").allTextContents(), [w.asked, ...["low", "medium", "high", "xhigh"].filter((v) => v !== from)]);
await option(page, to).click();
await shut(page);
};
await pair("high", "xhigh");
await pair("low", "medium");
await pair("max", "xhigh");
await pair("max", w.asked); // back to as asked
assert.equal((await chip().textContent()).trim(), w.mapped);
assert.match(await chip().getAttribute("class"), /\bon\b/);
if (lang === "en") assert.equal(await chip().getAttribute("title"), w.title);
assert((await chip().getAttribute("title")).includes("high → xhigh"));
assert.equal(await at(), before, "the picks moved nothing");
// the first menu has "map" as what it is now; the next menu says each pair
await chip().click();
await option(page, w.map).waitFor();
assert.match(await option(page, w.map).getAttribute("class"), /\bcur\b/);
await option(page, w.map).click();
await option(page, "high").waitFor();
assert.equal((await option(page, "high").locator(".n, .note").first().textContent()).trim(), "→ xhigh");
await page.keyboard.press("Escape");
await shut(page);
const fits = await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth);
assert(fits, "no sideways scroll");
const missing = await page.evaluate((keys) => keys.filter((k) => !I18N.zh[k] || !I18N["zh-TW"][k] || !I18N.ja[k] || !I18N.de[k]), keys);
assert.deepEqual(missing, [], "every string has each language");
await save(page, w);
const sent = posts.find((p) => p.path === "/api/groups/save");
assert.deepEqual(sent.body.members, ["oa/gpt-6.1-sol", "rl/glm-5"]);
assert.deepEqual(sent.body.effortMaps, { "oa/gpt-6.1-sol": { high: "xhigh", low: "medium" } });
assert.deepEqual(errors, []);
});
}
test(`${engine} ${lang}: a fixed level or the group drops a map, and a map frees a fixed one`, async (t) => {
const w = words[lang];
const { page, card, errors, posts } = await open(engine, lang, 1100, ["oa/gpt-6.1-sol", "rl/glm-5:high", "oa/gpt-6.1-sol:low"], t,
{ "oa/gpt-6.1-sol": { high: "xhigh" } });
await card.locator("button", { hasText: w.edit }).click();
const ed = page.locator(".rt-gedit");
const chips = ed.locator("button.rt-fixed:not(.rt-fast)");
await chips.first().waitFor();
assert.equal((await chips.nth(0).textContent()).trim(), w.mapped, "the saved map is read");
// a fixed level drops the map: back on the group, it isn't there
await chips.nth(0).click();
await option(page, w.follow).waitFor();
await page.locator("#pop:not([hidden]) #list li:not(.group)").nth(3).click(); // high
await shut(page);
assert.notEqual((await chips.nth(0).textContent()).trim(), w.mapped);
await chips.nth(0).click();
await option(page, w.follow).click();
await shut(page);
assert.notEqual((await chips.nth(0).textContent()).trim(), w.mapped);
// a mapped one back on the group's own
await chips.nth(0).click();
await option(page, w.map).click();
await option(page, "high").click();
await option(page, "xhigh").click();
await shut(page);
assert.equal((await chips.nth(0).textContent()).trim(), w.mapped);
await chips.nth(0).click();
await option(page, w.follow).click();
await shut(page);
assert.notEqual((await chips.nth(0).textContent()).trim(), w.mapped);
// a member fixed at high, mapped: low to high, and it follows the group
await chips.nth(1).click();
await option(page, w.map).click();
await option(page, "low").click();
await option(page, w.asked).waitFor();
await page.locator("#pop:not([hidden]) #list li:not(.group)").nth(1).click(); // the model's other level, high
await shut(page);
assert.equal((await chips.nth(1).textContent()).trim(), w.mapped);
await save(page, w);
const sent = posts.find((p) => p.path === "/api/groups/save");
assert.deepEqual(sent.body.members, ["oa/gpt-6.1-sol", "rl/glm-5", "oa/gpt-6.1-sol:low"]);
assert.deepEqual(sent.body.effortMaps, { "rl/glm-5": { low: "high" } });
assert.deepEqual(errors, []);
});
}
}
+1
View File
@@ -105,6 +105,7 @@ func (g *Group) canonicalRefs() {
g.Weights[c] = v
}
}
g.EffortMaps = renamedEffortMaps(g.EffortMaps, CanonicalRef)
for i := range g.Rules {
g.Rules[i].MapUses(CanonicalRef)
}
+9
View File
@@ -155,6 +155,14 @@ func foldRefs(f file, s *settings.Settings) map[string][]string {
for m, w := range g.Weights {
note(at+"weight"+strconv.Itoa(w), m)
}
for m, to := range g.EffortMaps {
pairs := make([]string, 0, len(to))
for from, l := range to {
pairs = append(pairs, from+">"+l)
}
slices.Sort(pairs)
note(at+"effortmap"+strings.Join(pairs, ","), m)
}
if g.Pick != "" {
note(at+"pick", g.Pick)
}
@@ -346,6 +354,7 @@ func foldWhere(candidates func([]Provider) [][]int) (int, error) {
g.Seen = compact(mapEach(g.Seen, ref))
g.Off = compact(mapEach(g.Off, ref))
g.Weights = renamedWeights(g.Weights, ref)
g.EffortMaps = renamedEffortMaps(g.EffortMaps, ref)
g.Classifier = ref(g.Classifier)
g.Pick = ref(g.Pick)
}
+36 -1
View File
@@ -258,6 +258,11 @@ type Group struct {
// weighs 1. Kept while the group routes otherwise, for when it is by
// weight again.
Weights map[string]int `json:"weights,omitempty"`
// EffortMaps are, for the members (as Members spells them) that
// follow the group's effort, the level each sends in place of the one
// asked for ("high" → "xhigh"): see groupeffortmap.go. A level not in
// a member's map is sent as asked.
EffortMaps map[string]map[string]string `json:"effortMaps,omitempty"`
// Family is a tag the group goes by in which agents are shown it
// (settings' Visible), with its id.
Family string `json:"family,omitempty"`
@@ -322,6 +327,10 @@ type Member struct {
// sent at the nearest of them. nil for a member fixed at one (Effort)
// or following the group.
Levels []string
// EffortMap is, for a member following the group's effort, the level
// it sends in place of the one asked for (Group.EffortMaps); nil
// sends it as asked.
EffortMap map[string]string
// Fast is set on a member the group sends in its vendor's fast mode
// (Group.Fast), where its model has one.
Fast bool
@@ -391,7 +400,7 @@ func (m Member) Groups() []string {
// Below is the member as the group at depth (0 the group itself, 1 the
// group in it Path[0] names, …) has it.
func (m Member) Below(depth int) Member {
out := Member{ID: m.Path[depth], Path: m.Path[depth:], Via: m.Via[depth:], Provider: m.Provider, Model: m.Model, Effort: m.Effort, Levels: m.Levels, Fast: m.Fast, At: m.At}
out := Member{ID: m.Path[depth], Path: m.Path[depth:], Via: m.Via[depth:], Provider: m.Provider, Model: m.Model, Effort: m.Effort, Levels: m.Levels, EffortMap: m.EffortMap, Fast: m.Fast, At: m.At}
// its other places in the same group at depth
for _, o := range m.Also {
if len(o.Path) > depth && slices.Equal(o.Path[:depth], m.Path[:depth]) {
@@ -441,6 +450,7 @@ func cloneGroups(gs []Group) []Group {
g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast)
g.Accounts, g.Seen = slices.Clone(g.Accounts), slices.Clone(g.Seen)
g.Weights = maps.Clone(g.Weights)
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string { return m })
if g.IntentSure != nil {
v := *g.IntentSure
g.IntentSure = &v
@@ -549,6 +559,12 @@ func withoutRemoved(g Group, have map[string]bool) Group {
}
return m
})
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string {
if gone(m) {
return ""
}
return m
})
return g
}
@@ -628,6 +644,7 @@ func (g Group) own() Group {
g.Accounts = slices.Clone(g.Accounts)
g.Seen = slices.Clone(g.Seen)
g.Weights = maps.Clone(g.Weights)
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string { return m })
g.Rules = slices.Clone(g.Rules)
for i, r := range g.Rules {
g.Rules[i].Agents = slices.Clone(r.Agents)
@@ -1118,6 +1135,9 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func(
}
fixed, levels := MemberLevels(effort)
mem := Member{ID: here[0], Path: here, Via: via, Provider: p, Model: m, Effort: fixed, Levels: levels, Fast: g.IsFast(id), At: at}
if fixed == "" && levels == nil {
mem.EffortMap = g.MemberEffortMap(id)
}
at++
if i, ok := seen[key]; ok {
// asked once, where it was met first; a rule naming this
@@ -1318,6 +1338,12 @@ func buildGroupEntries(entries []Entry) []Entry {
} else {
e.ImageInput = anyImageInput(e.ImageInput, imageInput)
}
// a member that sends other levels than the ones asked
// (EffortMaps) takes the levels its map is asked for too: the
// gateway sends them at the level they map to
if len(m.EffortMap) > 0 && !reasonless && !unknown && len(efforts) > 0 {
efforts = mappedLevels(efforts, m.EffortMap)
}
// a member the user gave several levels of its own offers them
// (Garydesu on X: one model at a few efforts, the agent picking);
// a group in the group that names its own levels offers them for
@@ -1567,6 +1593,9 @@ func SaveGroup(g Group) error {
if err := cleanWeights(entries, &g); err != nil {
return err
}
if err := cleanEffortMaps(entries, &g); err != nil {
return err
}
var was []string
if i := slices.IndexFunc(f.Groups, func(x Group) bool { return x.ID == g.ID }); i >= 0 {
was = f.Groups[i].Accounts
@@ -2066,6 +2095,12 @@ func RenameGroup(from, to string) error {
}
return m
})
f.Groups[i].EffortMaps = renamedEffortMaps(f.Groups[i].EffortMaps, func(m string) string {
if m == old {
return now
}
return m
})
if f.Groups[i].Classifier == old {
f.Groups[i].Classifier = now
}
+1
View File
@@ -208,6 +208,7 @@ func importGroup(text string, over bool) (Imported, error) {
return ok && !CanFast(p, id)
})
g.Weights = renamedWeights(g.Weights, func(m string) string { return here[strings.TrimSpace(m)] })
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string { return here[strings.TrimSpace(m)] })
if g.Routing != Manual && len(g.Off) == len(g.Members) {
g.Off = nil // the ones it sent to are gone: those left are on
}
+139
View File
@@ -0,0 +1,139 @@
package provider
// A group's member may send another level than the one asked for
// (Group.EffortMaps, LuckymanJC on Discord): a group relaying a task
// between vendors' models finds one vendor's "high" is another's
// "xhigh", so the member that reasons less at the same word is sent a
// level up. The map goes from the level asked — by the agent, the
// model's name, or the group's classifier — to the level sent; a level
// it doesn't name is sent as asked. It is kept beside Members, as
// Weights is, so a group without one reads and routes as before, and a
// member fixed at an effort (or following the agent among several) has
// none: its own effort already says what it is sent.
import (
"fmt"
"maps"
"slices"
"strings"
)
// MemberEffortMap is the levels the group's member id sends in place of
// the ones asked for; nil when it sends them as asked.
func (g Group) MemberEffortMap(id string) map[string]string { return g.EffortMaps[id] }
// SetMemberEffortMap has the group's member id send to[l] when l is
// asked; an empty map sends every level as asked.
func (g *Group) SetMemberEffortMap(id string, to map[string]string) {
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string {
if m == id {
return ""
}
return m
})
if to = cleanEffortMap(to); len(to) > 0 {
if g.EffortMaps == nil {
g.EffortMaps = map[string]map[string]string{}
}
g.EffortMaps[id] = to
}
}
// renamedEffortMaps is maps with each member as to spells it now, those
// it gives "" dropped; nil when none is left. Two members spelled as one
// keep the map of the one already spelled so, else the first's in the
// order of their spelling: a group shared from a magpie with OpenAI's
// model on two providers, imported where one serves both, keeps that
// one's own.
func renamedEffortMaps(m map[string]map[string]string, to func(string) string) map[string]map[string]string {
var out map[string]map[string]string
keys := slices.Sorted(maps.Keys(m))
for _, same := range []bool{true, false} {
for _, k := range keys {
n := to(k)
if n == "" || len(m[k]) == 0 || (n == k) != same {
continue
}
if _, ok := out[n]; ok {
continue
}
if out == nil {
out = map[string]map[string]string{}
}
out[n] = maps.Clone(m[k])
}
}
return out
}
// cleanEffortMap is to with its levels lowercase, the ones sent as asked
// left out; nil when none is left. A word that isn't a level is kept for
// checkEffortMap to refuse.
func cleanEffortMap(to map[string]string) map[string]string {
var out map[string]string
for from, l := range to {
from, l = strings.ToLower(strings.TrimSpace(from)), strings.ToLower(strings.TrimSpace(l))
if from == "" || l == "" || from == l {
continue
}
if out == nil {
out = map[string]string{}
}
out[from] = l
}
return out
}
// checkEffortMap refuses a map naming a word that isn't a level.
func checkEffortMap(id string, to map[string]string) error {
for from, l := range to {
for _, w := range []string{from, l} {
if !slices.Contains(MemberEfforts, w) {
return fmt.Errorf("%s maps %s to %s: a reasoning level is one of %s", id, from, l, strings.Join(MemberEfforts, ", "))
}
}
}
return nil
}
// cleanEffortMaps keeps g.EffortMaps to its members as Members spells
// them that follow the group's effort: one fixed at an effort, or among
// several, sends that, so a map on it is left out. A level that isn't
// one is refused.
func cleanEffortMaps(entries []Entry, g *Group) error {
var err error
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string {
id, _ := memberFastIn(entries, strings.TrimSpace(m))
id = cleanMember(entries, id)
to := cleanEffortMap(g.EffortMaps[m])
if e := checkEffortMap(id, to); e != nil && err == nil {
err = e
}
if _, effort := memberEffortIn(entries, id); effort != "" || len(to) == 0 || strings.HasPrefix(id, GroupPrefix) || !slices.Contains(g.Members, id) {
return ""
}
return id
})
for id, to := range g.EffortMaps {
g.EffortMaps[id] = cleanEffortMap(to)
}
return err
}
// mappedLevels are a model's efforts with the levels its member's map is
// asked for besides, in MemberEfforts' order, the model's own words that
// aren't one ("ultra") after them as it lists them.
func mappedLevels(efforts []string, to map[string]string) []string {
var out []string
for _, l := range MemberEfforts {
if _, asked := to[l]; asked || slices.Contains(efforts, l) {
out = append(out, l)
}
}
for _, l := range efforts {
if !slices.Contains(MemberEfforts, l) {
out = append(out, l)
}
}
return out
}
+146
View File
@@ -0,0 +1,146 @@
package provider
import (
"maps"
"slices"
"strings"
"testing"
)
// A group keeps each member's effort map (LuckymanJC on Discord) under
// the member as Members spells it, its levels lowercase: a level mapped
// to itself left out, a member fixed at an effort, a group in the group
// and one not in the group dropped, and a word that isn't a level
// refused. The map follows its member when it is renamed, its provider
// is, and when the group is shared to another magpie; the member it
// resolves to carries it.
func TestSaveGroupEffortMaps(t *testing.T) {
fastHome(t)
maps1 := func(id string) map[string]map[string]string {
t.Helper()
g, _, ok := FindGroup(GroupPrefix + id)
if !ok {
t.Fatalf("no group %s", id)
}
return g.EffortMaps
}
if err := SaveGroup(Group{ID: "in", Name: "In", Members: []string{"rl/claude-opus-5-5"}}); err != nil {
t.Fatal(err)
}
g := Group{ID: "relay", Name: "Relay",
Members: []string{"oa/gpt-6.1-sol", "rl/gpt-6.1-sol:high", "an/claude-opus-5-5", "group/in"},
EffortMaps: map[string]map[string]string{
"oa/gpt-6.1-sol:fast": {"HIGH": "xhigh", "low": "low"},
"rl/gpt-6.1-sol:high": {"high": "max"},
"an/claude-opus-5-5": {"medium": "medium"},
"group/in": {"high": "max"},
"an/claude-sonnet-5": {"high": "max"},
}}
if err := SaveGroup(g); err != nil {
t.Fatal(err)
}
want := map[string]map[string]string{"oa/gpt-6.1-sol": {"high": "xhigh"}}
if got := maps1("relay"); !maps.EqualFunc(got, want, maps.Equal) {
t.Fatalf("maps %v, want %v", got, want)
}
for _, bad := range []map[string]string{{"high": "huge"}, {"turbo": "high"}} {
b, _, _ := FindGroup(GroupPrefix + "relay")
b.SetMemberEffortMap("oa/gpt-6.1-sol", bad)
if err := SaveGroup(b); err == nil || !strings.Contains(err.Error(), "reasoning level") {
t.Fatalf("%v: %v", bad, err)
}
}
_, ms, _ := FindGroup(GroupPrefix + "relay")
i := slices.IndexFunc(ms, func(m Member) bool { return m.ID == "oa/gpt-6.1-sol" })
if i < 0 || ms[i].EffortMap["high"] != "xhigh" {
t.Fatalf("members %+v", ms)
}
for _, m := range ms {
if m.ID != "oa/gpt-6.1-sol" && m.EffortMap != nil {
t.Fatalf("%s carries %v", m.ID, m.EffortMap)
}
}
// renamed (the TUI changing a member's effort and back), its
// provider renamed
saved, _, _ := FindGroup(GroupPrefix + "relay")
saved.RenameMember("rl/gpt-6.1-sol:high", "rl/gpt-6.1-sol")
saved.SetMemberEffortMap("rl/gpt-6.1-sol", map[string]string{"medium": "high"})
saved.SetMemberEffortMap("an/claude-opus-5-5", map[string]string{"high": "max"})
if err := SaveGroup(saved); err != nil {
t.Fatal(err)
}
if err := Rename("rl", "relay"); err != nil {
t.Fatal(err)
}
want = map[string]map[string]string{"oa/gpt-6.1-sol": {"high": "xhigh"}, "relay/gpt-6.1-sol": {"medium": "high"}, "an/claude-opus-5-5": {"high": "max"}}
if got := maps1("relay"); !maps.EqualFunc(got, want, maps.Equal) {
t.Fatalf("after the renames %v, want %v", got, want)
}
// its effort changed and back: the map goes with it
moved, _, _ := FindGroup(GroupPrefix + "relay")
moved.RenameMember("oa/gpt-6.1-sol", "oa/gpt-6.1-sol:low")
if moved.MemberEffortMap("oa/gpt-6.1-sol:low")["high"] != "xhigh" || moved.MemberEffortMap("oa/gpt-6.1-sol") != nil {
t.Fatalf("after RenameMember %v", moved.EffortMaps)
}
// shared to another magpie, which has OpenAI's and Anthropic's
// models only on the relay: Anthropic's member's map goes to the
// relay's model; the relay's own map is kept where OpenAI's member
// is one with it
text, err := ShareGroup("relay")
if err != nil {
t.Fatal(err)
}
if err := DeleteGroup("relay"); err != nil {
t.Fatal(err)
}
for _, id := range []string{"oa", "an"} {
if err := Delete(id); err != nil {
t.Fatal(err)
}
}
want = map[string]map[string]string{"relay/gpt-6.1-sol": {"medium": "high"}, "relay/claude-opus-5-5": {"high": "max"}}
if _, err := ImportGroup(text); err != nil {
t.Fatal(err)
}
var back Group
for _, x := range Groups() {
if x.Name == "Relay" {
back = x
}
}
if !maps.EqualFunc(back.EffortMaps, want, maps.Equal) {
t.Fatalf("imported %v %v", back.Members, back.EffortMaps)
}
// an empty map sends every level as asked
back.SetMemberEffortMap("relay/claude-opus-5-5", nil)
back.SetMemberEffortMap("relay/gpt-6.1-sol", map[string]string{"high": "high"})
if back.EffortMaps != nil {
t.Fatalf("emptied %v", back.EffortMaps)
}
}
// The levels a group lists take, for a member with a map, the levels the
// map is asked for besides its model's own.
func TestGroupLevelsWithEffortMap(t *testing.T) {
effortHome(t)
if err := SetModelEfforts("a/m", []string{"low", "medium", "high"}); err != nil {
t.Fatal(err)
}
if err := SetModelEfforts("a/n", []string{"medium", "high", "xhigh", "max"}); err != nil {
t.Fatal(err)
}
if err := SaveGroup(Group{Name: "Mapped", Members: []string{"a/m", "a/n"}, EffortMaps: map[string]map[string]string{"a/m": {"xhigh": "high", "max": "high"}}}); err != nil {
t.Fatal(err)
}
i := slices.IndexFunc(Catalog(), func(e Entry) bool { return e.ID == GroupPrefix+"mapped" })
if i < 0 {
t.Fatal("not listed")
}
if got := Catalog()[i].Efforts; !slices.Equal(got, []string{"medium", "high", "xhigh", "max"}) {
t.Fatalf("levels %v", got)
}
}
+6
View File
@@ -266,4 +266,10 @@ func (g *Group) RenameMember(from, to string) {
}
return m
})
g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string {
if m == from {
return to
}
return m
})
}
+1
View File
@@ -150,6 +150,7 @@ func mapModelRefs(f *file, to func(string) string) {
g.Off[k] = to(m)
}
g.Weights = renamedWeights(g.Weights, to)
g.EffortMaps = renamedEffortMaps(g.EffortMaps, to)
g.Classifier = to(g.Classifier)
g.Pick = to(g.Pick)
}