providers: each account of a subscription, and each key, can be kept for some of the provider's models only (#474: 增加账号级别的模型选项, a low-quota but verified account kept for the cheap models) — every account or key a provider had served every model it did, so one couldn't be spared for some. An account's or key's row in its provider's editor now has a models badge: a click opens the provider's models as chips, Save keeps the account for those picked, All models gives it every one again; one kept for some says how many, always shown. magpie provider account-models <id> [account|key [models…|all]] does the same and lists them. It is kept in providers.json as accountModels, an account by its name in lower case, a key by its id; one not in it serves every model, as before. The gateway never sends a model to an account or key whose list leaves it out, in every routing mode, in drag order, in a group and as a fallback, and never falls back to it all the same; the trace says it was left out as set to serve other models. When every account or key there is leaves the model out, the request is refused with a 403 saying so and how to change it, not "none of X's models is ready". TestKeyModelsNarrowCandidates, TestAccountModelsNeverChosen, TestAccountModelsCmd and account-models.test.cjs fail without the change. go vet, go build -tags nogui (darwin, GOOS=linux), GOOS=windows go build, go test -tags nogui ./... pass; account-models, click-scroll, old-webkit, account-arrange, account-proxy, account-return, routing-account-order, panel-routing, unlisted-models pass.

This commit is contained in:
yetone
2026-10-02 05:50:23 +08:00
parent 7de2b62191
commit 01d595817c
15 changed files with 801 additions and 13 deletions
+62
View File
@@ -0,0 +1,62 @@
package main
import (
"os"
"reflect"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// magpie provider account-models gives one key, by its name or its id, the
// models it alone serves; all gives it every one again, and a key the
// provider doesn't have is an error (#474).
func TestAccountModelsCmd(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("USERPROFILE", os.Getenv("HOME"))
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("DSH_HOME", "")
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k1", Keys: []provider.KeyAccount{{Name: "Team", Key: "k2"}}, Chat: "http://127.0.0.1:1/v1"}); err != nil {
t.Fatal(err)
}
stored := func() map[string][]string {
p, err := provider.Find("relay")
if err != nil {
t.Fatal(err)
}
return p.AccountModels
}
if err := providerCmd([]string{"provider", "account-models", "relay", "team", "cheap", "mini", "cheap"}); err != nil {
t.Fatal(err)
}
if got, want := stored(), map[string][]string{provider.KeyID("k2"): {"cheap", "mini"}}; !reflect.DeepEqual(got, want) {
t.Fatalf("by name: %v", got)
}
if err := providerCmd([]string{"provider", "account-models", "relay", provider.KeyID("k1"), "big"}); err != nil {
t.Fatal(err)
}
if got := stored(); len(got) != 2 || !reflect.DeepEqual(got[provider.KeyID("k1")], []string{"big"}) {
t.Fatalf("by id: %v", got)
}
// a save of the provider's other settings keeps them
p, _ := provider.Find("relay")
p.Models = []string{"cheap", "mini", "big"}
if err := provider.Save(*p); err != nil {
t.Fatal(err)
}
for _, ref := range []string{"team", provider.KeyID("k1")} {
if err := providerCmd([]string{"provider", "account-models", "relay", ref, "all"}); err != nil {
t.Fatal(err)
}
}
if got := stored(); got != nil {
t.Fatalf("all: %v", got)
}
if err := providerCmd([]string{"provider", "account-models", "relay", "nobody", "big"}); err == nil {
t.Fatal("an unknown key was taken")
}
if err := providerCmd([]string{"provider", "account-models", "relay"}); err != nil {
t.Fatal(err)
}
}
+140
View File
@@ -0,0 +1,140 @@
package gateway
import (
"encoding/json"
"reflect"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// A key set to serve some of its provider's models only is never a
// candidate for another, whatever the routing; it is one for those, and a
// key without a list of its own is one for every model, as before (#474).
func TestKeyModelsNarrowCandidates(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
for _, mode := range []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed} {
p := provider.Provider{ID: "narrow", Name: "Narrow", Chat: "https://example.invalid/v1", Key: "first", Keys: []provider.KeyAccount{{Key: "second"}, {Key: "third"}}, Routing: mode}
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
keysFor := func(model string) []string {
got, err := provider.Find(p.ID)
if err != nil {
t.Fatal(err)
}
var keys []string
for _, c := range perKey(*got, model, provider.Chat) {
keys = append(keys, c.p.Key)
}
return keys
}
// none set: every key for every model, as before
if got := keysFor("big"); !reflect.DeepEqual(got, []string{"first", "second", "third"}) {
t.Fatalf("mode=%q unset: %v", mode, got)
}
if err := provider.SetAccountModels(p.ID, provider.KeyID("first"), []string{"small"}); err != nil {
t.Fatal(err)
}
if got := keysFor("big"); !reflect.DeepEqual(got, []string{"second", "third"}) {
t.Fatalf("mode=%q big: %v", mode, got)
}
if got := keysFor("small"); !reflect.DeepEqual(got, []string{"first", "second", "third"}) {
t.Fatalf("mode=%q small: %v", mode, got)
}
// every key barred from big: none, never the provider's key all the same
for _, k := range []string{"second", "third"} {
if err := provider.SetAccountModels(p.ID, provider.KeyID(k), []string{"small"}); err != nil {
t.Fatal(err)
}
}
if got := keysFor("big"); len(got) != 0 {
t.Fatalf("mode=%q all barred: %v", mode, got)
}
// all again: as before
for _, k := range []string{"first", "second", "third"} {
if err := provider.SetAccountModels(p.ID, provider.KeyID(k), nil); err != nil {
t.Fatal(err)
}
}
if got := keysFor("big"); !reflect.DeepEqual(got, []string{"first", "second", "third"}) {
t.Fatalf("mode=%q reset: %v", mode, got)
}
if got, _ := provider.Find(p.ID); got.AccountModels != nil {
t.Fatalf("mode=%q reset kept %v", mode, got.AccountModels)
}
}
}
// An account of a subscription set to serve other models only is never
// sent a request for this one: every request goes to the other account,
// the trace telling it left out; with every account barred the request is
// refused with why, not sent to one all the same; unset, both serve it
// again (#474).
func TestAccountModelsNeverChosen(t *testing.T) {
heads := twoAccounts(t)
s := New()
post := func() (int, string) { return pinnedPost(t, s, "/v1/responses", "codex/gpt-5.5", "") }
if err := provider.SetAccountModels("codex", "Me@example.com", []string{"gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
for _, mode := range []string{"", provider.Ordered, provider.Rotate, provider.LeastUsed} {
if err := provider.SetRouting("codex", mode); err != nil {
t.Fatal(err)
}
for i := 0; i < 3; i++ {
*heads = nil
code, body := post()
if code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("mode=%q: %d %s", mode, code, body)
}
if len(*heads) != 1 || (*heads)[0].Get("chatgpt-account-id") != "acct-2" {
t.Fatalf("mode=%q: upstream %v", mode, *heads)
}
}
}
r := s.trace.routes[len(s.trace.routes)-1]
if len(r.Order) != 1 || r.Order[0].Who != "spare@example.com" || len(r.Left) != 1 || !r.Left[0].Barred || r.Left[0].Who != "me@example.com" {
t.Fatalf("trace order %+v left %+v", r.Order, r.Left)
}
// the model it is set to serve still goes to it first
*heads = nil
if code, body := pinnedPost(t, s, "/v1/responses", "codex/gpt-5.4-mini", ""); code != 200 || len(*heads) != 1 {
t.Fatalf("its own model: %d %s", code, body)
}
if err := provider.SetAccountModels("codex", "spare@example.com", []string{"gpt-5.4-mini"}); err != nil {
t.Fatal(err)
}
*heads = nil
code, body := post()
if code != 403 || len(*heads) != 0 || !strings.Contains(body, "gpt-5.5") || !strings.Contains(body, "own list of models") {
t.Fatalf("all barred: %d %s, upstream %v", code, body, *heads)
}
var e struct {
Error struct{ Message string }
}
if json.Unmarshal([]byte(body), &e) != nil || e.Error.Message == "" {
t.Fatalf("all barred, not an error the client reads: %s", body)
}
for _, u := range []string{"me@example.com", "spare@example.com"} {
if err := provider.SetAccountModels("codex", u, nil); err != nil {
t.Fatal(err)
}
}
if err := provider.SetRouting("codex", provider.Rotate); err != nil {
t.Fatal(err)
}
seen := map[string]bool{}
for i := 0; i < 4; i++ {
*heads = nil
if code, body := post(); code != 200 || len(*heads) != 1 {
t.Fatalf("unset: %d %s", code, body)
}
seen[(*heads)[0].Get("chatgpt-account-id")] = true
}
if !seen["acct-1"] || !seen["acct-2"] {
t.Fatalf("unset, rotating, both serve it again: %v", seen)
}
}
+54 -6
View File
@@ -120,6 +120,14 @@ func perKey(p provider.Provider, model string, from provider.Protocol) []candida
// protocol that suits the request best, and the others are tried only
// after them, in the order they suit it.
func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, aside, left []candidate) {
out, aside, left, _ = perKeyBarred(p, model, from)
return out, aside, left
}
// perKeyBarred is perKeyOf, and the accounts or keys the user set not to
// serve the model (provider.AccountModels, #474): never tried, whatever
// else there is — none, when every one of them is.
func perKeyBarred(p provider.Provider, model string, from provider.Protocol) (out, aside, left, barred []candidate) {
if p.Account != nil {
also := p.AlsoOn()
var all []candidate
@@ -131,6 +139,13 @@ func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, a
for i, q := range also {
all = append(all, candidate{p: q, model: model, rest: p.ID + "@" + q.Account.User, rank: i + 1})
}
all = slices.DeleteFunc(all, func(c candidate) bool {
if p.AccountServes(c.p.Account.User, model) {
return false
}
barred = append(barred, c)
return true
})
// an account whose plan lacks the model (a Free one behind a Plus)
// would only answer 400; it is tried only when none lists it
for _, c := range all {
@@ -141,9 +156,9 @@ func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, a
}
}
if len(out) == 0 {
return all, nil, nil
return all, nil, nil, barred
}
return out, nil, left
return out, nil, left, barred
}
keys := p.KeysOn()
var unlisted []candidate
@@ -156,6 +171,10 @@ func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, a
if len(keys) > 1 {
rest += "#" + provider.KeyID(k.Key)
}
if !p.AccountServes(provider.KeyID(k.Key), model) {
barred = append(barred, candidate{p: q, model: model, rest: rest, rank: i})
continue
}
if !p.Serves(k, model) {
// the vendor lists the model to another key only
unlisted = append(unlisted, candidate{p: q, model: model, rest: rest, rank: i})
@@ -166,8 +185,11 @@ func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, a
if len(out) == 0 {
out, unlisted = unlisted, nil // no key lists it: try them all the same
}
if len(out) == 0 && len(barred) > 0 {
return nil, nil, nil, barred
}
if len(out) == 0 {
return []candidate{{p: p, model: model, rest: p.ID}}, nil, nil
return []candidate{{p: p, model: model, rest: p.ID}}, nil, nil, nil
}
sort.SliceStable(out, func(i, j int) bool { return keyFit(out[i].p, model, from) < keyFit(out[j].p, model, from) })
pool := out[:0:0]
@@ -178,7 +200,7 @@ func perKeyOf(p provider.Provider, model string, from provider.Protocol) (out, a
aside = append(aside, c)
}
}
return pool, aside, unlisted
return pool, aside, unlisted, barred
}
// keyFit ranks how well a key suits a request, best first: 0 fits, 1 needs
@@ -234,7 +256,8 @@ func (s *Server) candidates(p provider.Provider, model string, from provider.Pro
func (s *Server) plan(p provider.Provider, model string, from provider.Protocol) ([]candidate, planned) {
var pl planned
add := func(q provider.Provider, m string, fallback bool) []candidate {
cs, aside, left := perKeyOf(q, m, from)
cs, aside, left, barred := perKeyBarred(q, m, from)
pl.left = append(pl.left, barredOf(barred, q, fallback, from, nil)...)
cs, wg := weigh(q, cs, m, from)
for i, c := range cs {
w := weighed(c, q, wg, fallback, from)
@@ -287,7 +310,8 @@ func (s *Server) planGroup(g provider.Group, ms []provider.Member, from provider
// those unlisted it gathers for planGroup to put last.
func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.Protocol, pl *planned, asides *[]candidate, wAsides *[]Weighed) []candidate {
keys := func(m provider.Member) []candidate {
cs, aside, left := perKeyOf(m.Provider, m.Model, from)
cs, aside, left, barred := perKeyBarred(m.Provider, m.Model, from)
pl.left = append(pl.left, barredOf(barred, m.Provider, false, from, m.Groups())...)
// the effort the member is fixed at goes with each of its keys:
// the same model at another effort is another member's
for _, l := range [][]candidate{cs, aside, left} {
@@ -357,6 +381,30 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider.
return out
}
// barredOf is how the trace tells the accounts or keys the user set not
// to serve the model: left out, as those not listing it are.
func barredOf(cs []candidate, q provider.Provider, fallback bool, from provider.Protocol, via []string) []Weighed {
var out []Weighed
for _, c := range cs {
w := weighed(c, q, weighing{}, fallback, from)
w.Unlisted, w.Barred, w.Via = true, true, via
out = append(out, w)
}
return out
}
// barredError says why a request for model went nowhere when every account
// or key that could take it was set not to serve it.
func barredError(model string, ws []Weighed) string {
var names []string
for _, w := range ws {
if !slices.Contains(names, w.Name) {
names = append(names, w.Name)
}
}
return fmt.Sprintf("model %q is set not to be served by any account or key of %s: each one's own list of models leaves it out. Add it to an account's models in magpie (Providers → the account's Models), or pick another model", model, strings.Join(names, ", "))
}
// asideOf is how the trace tells the keys made for another protocol than
// those routed over: after them, in the order they suit the request.
func asideOf(cs []candidate, q provider.Provider, fallback bool, from provider.Protocol) []Weighed {
+7
View File
@@ -971,6 +971,13 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
} else {
cands, pl = s.plan(p, model, from)
}
if len(cands) == 0 && len(pl.left) > 0 && !slices.ContainsFunc(pl.left, func(w Weighed) bool { return !w.Barred }) {
// every account or key there is was set not to serve the model
call.Status, call.Error = 403, "every account barred"
writeError(w, from, 403, barredError(call.Model, pl.left))
turnedAway()
return
}
if len(cands) == 0 {
call.Status, call.Error = 404, "no member ready"
writeError(w, from, 404, fmt.Sprintf("none of %s's models is ready", call.Model))
+3
View File
@@ -168,6 +168,9 @@ type Weighed struct {
Speaks provider.Protocol `json:"speaks,omitempty"` // a key made for one protocol only
Rest *Rest `json:"rest,omitempty"` // resting after a failure, when the request came
Unlisted bool `json:"unlisted,omitempty"`
// Barred: left out as the user set it not to serve the model, its
// own list of models leaving it out (#474)
Barred bool `json:"barred,omitempty"`
// Rank: its place in its provider's own list of accounts or keys, the
// order the provider's page shows and a drag sets (#217); routing may
// weigh them in another
+13
View File
@@ -1562,6 +1562,19 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
.acc .proto:focus-visible { opacity: 1; }
.acc .proto.set { color: var(--fg-2); }
.acc .proto:hover, .acc .proto.open { color: var(--fg); background: var(--pill-hover); }
/* an account's or key's own models (#474): a badge like the key's protocol,
shown always once it keeps some only, and its picker under the row */
.acc .amodels { flex: none; display: inline-flex; align-items: center; height: 20px; padding: 0 7px; font: inherit; font-size: 11px; color: var(--muted); border: 0; border-radius: 5px; background: var(--pill); white-space: nowrap; cursor: default; transition: opacity .15s, background .12s, color .12s; }
.acc .amodels:not(.set) { opacity: 0; background: none; box-shadow: inset 0 0 0 1px var(--line); }
.acc:hover .amodels, .acc .amodels.open { opacity: 1; }
.acc .amodels:focus-visible { opacity: 1; }
.acc .amodels.set { color: var(--accent); background: var(--accent-soft); font-weight: 500; }
.acc .amodels:hover, .acc .amodels.open { color: var(--fg); background: var(--pill-hover); }
.accts .acc.with-am { flex-wrap: wrap; row-gap: 3px; }
.acc .acct-models { flex-basis: 100%; display: grid; gap: 7px; padding: 6px 0 2px 25px; cursor: auto; }
.acc .acct-models .acm-foot { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
.acc .acct-models .hint { font-size: 11px; color: var(--muted); line-height: 1.4; flex: 1 1 220px; }
.acc .acct-models .acm-foot .grow { flex: 0 0 0; }
.acc .n, .acc .rename { flex: 0 1 auto; }
.acc .plan { flex: none; }
#gatewayKeys .acc { min-width: 0; }
+68 -2
View File
@@ -6332,7 +6332,7 @@ function arrangeAccountRows(list, p) {
row.onpointerdown = (e) => {
if (accountArranging || e.target.closest("input, textarea, select, a, [contenteditable=true], button:not(.rename)")) return;
// Text selection is native; drag the row's background/empty space instead.
if (e.target.closest(".n:not(button), .plan, .aq")) return;
if (e.target.closest(".n:not(button), .plan, .aq, .acct-models")) return;
const current = [...list.children].filter((r) => r.dataset.accountId);
accountArranging = dragRows(e, row, row, list, current, (to) => move(row, to), () => {},
() => { if (!accountSaving) accountArrangementDone(); });
@@ -6387,7 +6387,11 @@ function renderAccounts(a, p) {
dot.title = on ? t("Stop using this account") : t("Use this account too");
dot.onclick = () => accountAction("login/" + (on ? "off" : "on"), { agent: a.agent, user: l.user });
}
row.append(dot, el("span", "n", l.user), el("span", "plan", accountPlan({ agent: a.agent, builtin: a.builtin, plan: l.plan })), el("span", "grow"));
row.append(dot, el("span", "n", l.user), el("span", "plan", accountPlan({ agent: a.agent, builtin: a.builtin, plan: l.plan })));
// its own models (#474), when there is another account to send the rest to
const [amPill, amBox] = ls.length > 1 || accountModelsOf(p, l.user).length ? accountModels(p, l.user, false, l.user) : [];
if (amPill) row.append(amPill);
row.append(el("span", "grow"));
if (l.active) {
const using = el("span", "using", l.paused ? t("Paused") : back ? t("First for now") : several ? t("First") : t("In use"));
if (back && !l.paused) using.title = t("{user} was nearly used up, so magpie signed {agent} in to this one; it goes back to {user} once that has room again", { user: back.user, agent: a.agentName });
@@ -6414,6 +6418,7 @@ function renderAccounts(a, p) {
}
row.append(accountQuota(l.lapsed ? { [l.user]: { error: l.lapsed } } : quota, l.user));
row.classList.add("with-aq"); // not :has(.aq), which Safari 15.0 lacks (#220)
if (amBox) row.append(amBox);
list.append(row);
}
if (a.agent === "codex" && providers?.codexDaemon) list.append(renderCodexDaemon(providers.codexDaemon));
@@ -6815,6 +6820,63 @@ async function accountAction(path, body, okMsg) {
}
}
// An account's or key's own models (#474): one of several can be kept for
// some of the provider's models only — a small allowance kept for the cheap
// ones — and the gateway never sends it another. Unset, it serves all the
// provider's, as before. The pill on its row says which it serves; a click
// opens the provider's models under it as chips, picked and saved apart
// from the editor's Save. acctModels is the row being picked: { id, ref,
// chosen }.
let acctModels = null;
function accountModelsOf(p, ref) { return p.accountModels?.[String(ref).toLowerCase()] || []; }
// It gives the pill, and the open picker the row ends with, or null.
function accountModels(p, ref, isKey, name) {
const own = accountModelsOf(p, ref);
const pill = el("button", "amodels" + (own.length ? " set" : ""), own.length ? t(own.length === 1 ? "1 model" : "{n} models", { n: own.length }) : t("All models"));
pill.title = own.length ? t("Serves only {models}", { models: own.join(", ") }) : t(isKey ? "Every model of the provider goes to this key. Click to keep it for some only" : "Every model of the provider goes to this account. Click to keep it for some only");
const open = acctModels?.id === p.id && acctModels.ref === ref;
pill.classList.toggle("open", open);
pill.setAttribute("aria-expanded", open ? "true" : "false");
pill.onclick = () => { acctModels = open ? null : { id: p.id, ref, chosen: [...own] }; renderProviders(); };
if (!open) return [pill, null];
const box = el("div", "acct-models");
const chips = el("div", "mchips");
// the models the provider serves agents, and any the account has that it no longer lists
const ids = p.models.filter((m) => m.on).map((m) => m.id);
for (const id of acctModels.chosen) if (!ids.includes(id)) ids.push(id);
const foot = el("div", "acm-foot");
const save = el("button", "text primary", t("Save"));
const post = async (allow, msg) => {
const was = acctModels;
acctModels = null;
if (!await accountAction("provider/accountmodels", { id: p.id, account: ref, allow }, msg)) { acctModels = was; renderProviders(); }
};
const draw = () => {
chips.replaceChildren();
for (const id of ids) {
const m = p.models.find((x) => x.id === id);
const on = acctModels.chosen.includes(id);
const c = el("button", "mchip" + (on ? " on" : ""));
c.append(el("span", "", m?.name && m.name !== id ? m.name : id));
if (m?.name && m.name !== id) c.title = id;
c.onclick = () => { acctModels.chosen = on ? acctModels.chosen.filter((x) => x !== id) : [...acctModels.chosen, id]; draw(); };
chips.append(c);
}
if (!ids.length) chips.append(el("span", "hint", t("Pick the provider's models first.")));
save.disabled = !acctModels.chosen.length;
};
draw();
save.onclick = () => { save.classList.add("busy"); post(acctModels.chosen, t("{who} serves only {models}", { who: name, models: acctModels.chosen.join(", ") })); };
const all = el("button", "text action", t("All models"));
all.title = t("Every model of the provider, as an account without a list of its own");
all.onclick = () => own.length ? post([], t("{who} serves every model again", { who: name })) : (acctModels = null, renderProviders());
const x = el("button", "text", t("Cancel"));
x.onclick = () => { acctModels = null; renderProviders(); };
foot.append(el("span", "hint", t(isKey ? "Only the models picked go to this key; the others go to the provider's other keys." : "Only the models picked go to this account; the others go to the provider's other accounts.")), el("span", "grow"), all, x, save);
box.append(chips, foot);
return [pill, box];
}
// renderKeyAccounts: a key provider's accounts, one per key, the same list
// a subscription has. addingKey holds the half-typed new one.
let addingKey = null;
@@ -6847,6 +6909,9 @@ function renderKeyAccounts(p) {
if (k.name) row.append(el("span", "plan mono", k.masked));
const proto = protoPicker(p, k.protocol, (v) => accountAction("keys/protocol", { id: p.id, ref: k.id, protocol: v }));
if (proto) row.append(proto);
// its own models (#474), when there is another key to send the rest to
const [amPill, amBox] = p.keyList.length > 1 || accountModelsOf(p, k.id).length ? accountModels(p, k.id, true, k.name || k.masked) : [];
if (amPill) row.append(amPill);
row.append(el("span", "grow"));
if (!k.active || several) {
const rm = el("button", "text quiet", t("Remove"));
@@ -6859,6 +6924,7 @@ function renderKeyAccounts(p) {
first.onclick = () => { first.classList.add("busy"); accountAction("keys/use", { id: p.id, ref: k.id }, t("{name} tries {key} first", { name: p.name, key: k.name || k.masked })); };
row.append(first);
}
if (amBox) row.append(amBox), row.classList.add("with-am");
list.append(row);
}
if (addingKey?.id === p.id) {
+11
View File
@@ -1758,6 +1758,17 @@ const I18N = {
"back in {d}": "{d}后恢复",
"back at {time} · in {d}": "{time} 恢复 · 还有 {d}",
"its plan doesn't list {model}": "套餐不包含 {model}",
"set to serve other models, not {model}": "已设为只用于其他模型,不含 {model}",
"{who} is left out: it is set to serve other models, not {model}.": "{who} 不参与:它已设为只用于其他模型,不含 {model}。",
"Serves only {models}": "只用于 {models}",
"Every model of the provider goes to this account. Click to keep it for some only": "供应商的所有模型都会用到这个账号。点击可只留给部分模型",
"Every model of the provider goes to this key. Click to keep it for some only": "供应商的所有模型都会用到这个 Key。点击可只留给部分模型",
"Pick the provider's models first.": "请先选择供应商的模型。",
"{who} serves only {models}": "{who} 只用于 {models}",
"{who} serves every model again": "{who} 重新用于全部模型",
"Every model of the provider, as an account without a list of its own": "供应商的全部模型,和没有单独设置模型的账号一样",
"Only the models picked go to this account; the others go to the provider's other accounts.": "只有选中的模型会用这个账号,其他模型交给该供应商的其他账号。",
"Only the models picked go to this key; the others go to the provider's other keys.": "只有选中的模型会用这个 Key,其他模型交给该供应商的其他 Key。",
"{name}'s list for this key has no {model}": "{name} 给这个 key 的模型列表里没有 {model}",
"answering…": "回答中…",
"answering another request…": "在回答另一个请求…",
+5 -2
View File
@@ -183,7 +183,8 @@
const where = (w) => w.kind === "provider" || !w.who ? w.name || w.provider : `${w.name || w.provider} · ${w.who}`;
// why one is left out: an account's plan lacks the model; a key's list
// from its vendor does — relays list each key its own group's models
const unlistedWord = (w) => w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model });
// or the user set the account or key to serve other models only (#474)
const unlistedWord = (w) => w.barred ? t("set to serve other models, not {model}", { model: w.model }) : w.kind === "key" ? t("{name}'s list for this key has no {model}", { name: w.name, model: w.model }) : t("its plan doesn't list {model}", { model: w.model });
const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine";
const renews = (w) => (w.renews || []).map((s) => known0(s) ? at(s) : 0);
@@ -297,7 +298,9 @@
}
const pooled = r.order.find((x) => !x.aside && x.kind === "key");
for (const x of r.order.filter((x) => x.aside)) out.push(t("{who} is made for {api}, not {other} as the keys routed over are, so it isn't one of them: it's tried after them.", { who: who(x), api: API[x.speaks] || x.speaks || t("any API"), other: API[pooled?.speaks] || pooled?.speaks || t("any API") }));
for (const x of r.left || []) out.push(x.kind === "key"
for (const x of r.left || []) out.push(x.barred
? t("{who} is left out: it is set to serve other models, not {model}.", { who: who(x), model: x.model })
: x.kind === "key"
? t("{who} is left out: {name} lists {model} to its other keys, not this one.", { who: who(x), name: x.name, model: x.model })
: t("{who} is left out: its plan doesn't list {model}.", { who: who(x), model: x.model }));
return out;
+19 -1
View File
@@ -59,6 +59,9 @@ type providerJSON struct {
// the proxy of each of a subscription's accounts that has one of its
// own, by its name in lower case; the others follow Proxy
AccountProxies map[string]string `json:"accountProxies,omitempty"`
// the models each account or key the user narrowed serves alone, by
// its name in lower case or its key's id (#474); the others serve all
AccountModels map[string][]string `json:"accountModels,omitempty"`
// where a custom provider's balance is asked (see provider.Balance)
BalanceURL string `json:"balanceURL,omitempty"`
BalancePath string `json:"balancePath,omitempty"`
@@ -245,7 +248,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(),
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Decide: p.Decide,
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, Headers: p.Headers, Searches: p.Searches, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, Headers: p.Headers, Searches: p.Searches, BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
Ready: p.Ready(), Chosen: p.Models, Models: []modelJSON{}, Agents: []providerAgent{},
Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Unlisted: p.Unlisted, Off: p.Off, Contexts: p.Contexts,
}
@@ -579,6 +582,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// Test, for test: models to send a request each, in place of
// one per endpoint
Test []string `json:"test"`
// Account and Allow, for accountmodels: the account (its name)
// or key (its id) and the models it alone serves, none for all
// the provider's (#474)
Account string `json:"account"`
Allow []string `json:"allow"`
// Typed, for test and models: the request carries the editor's
// form, which is tried as it stands before a Save (see typed)
Typed bool `json:"typed"`
@@ -675,6 +683,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if in.AccountProxies == nil && old != nil {
in.AccountProxies = old.AccountProxies
}
// each account's own models are set on their own, with
// accountmodels
if old != nil {
in.AccountModels = old.AccountModels
}
// a Zhipu key's team likewise: {} clears it
if in.ZhipuTeam == nil && old != nil {
in.ZhipuTeam = old.ZhipuTeam
@@ -755,6 +768,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
return
}
agent.SyncCatalog()
case "accountmodels":
if err := provider.SetAccountModels(in.ID, req.Account, req.Allow); err != nil {
fail(rw, err)
return
}
case "route":
if err := provider.SetRouting(in.ID, in.Routing); err != nil {
fail(rw, err)
+11
View File
@@ -1236,4 +1236,15 @@ Chinese:
```sh
node --test internal/gui/tests/agent-grip.test.cjs
`account-models.test.cjs` keeps an account of a subscription, and a key of a
provider, for some of the provider's models only (#474): an account with a
list of its own has a badge saying how many, always shown, and one without
says All models on hover; a click opens the provider's models under the row
as chips, Save waits for one picked and posts `provider/accountmodels` with
the account (or the key's id) and the models picked, All models posts none,
and the badge then says what it has. A click moves no row and scrolls
nothing; a subscription with one account has no badge; no border stripes,
every string has its Chinese. It runs in Chromium and WebKit, in English and
node --test internal/gui/tests/account-models.test.cjs
```
+198
View File
@@ -0,0 +1,198 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// Each account of a subscription, and each key, can be kept for some of the
// provider's models only (#474: 增加账号级别的模型选项). Its row has a badge:
// one kept for some says how many, always shown; one serving every model
// says All models, on hover. A click opens the provider's models under the
// row as chips; Save posts provider/accountmodels with the account (or the
// key's id) and the models picked, All models posts none. A click moves
// nothing and the page stays where it is. A subscription with one account
// has no badge. In English and Chinese.
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 fresh = () => ({
codex: {
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "gpt-6", name: "", on: true }, { id: "gpt-6-mini", name: "", on: true }, { id: "gpt-5", name: "", on: false }],
agents: [], fallback: [], headers: {}, keyList: [], proxy: "",
account: {
agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS",
logins: [
{ user: "me@example.com", plan: "PLUS", active: true, on: true },
{ user: "Spare@Example.com", plan: "PLUS", on: true },
],
},
accountModels: { "spare@example.com": ["gpt-6-mini"] },
},
claude: {
id: "claude", name: "Claude", icon: "claude-color", chat: "", responses: "", anthropic: "", catalog: "",
models: [{ id: "claude-opus-5", name: "", on: true }], agents: [], fallback: [], headers: {}, keyList: [], proxy: "",
account: { agent: "claude", agentName: "Claude Code", user: "solo@example.com", plan: "MAX", logins: [{ user: "solo@example.com", plan: "MAX", active: true, on: true }] },
},
relay: {
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "big", name: "", on: true }, { id: "cheap", name: "Cheap one", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, balanceToken: { takes: false, set: false }, proxy: "",
keyList: [{ id: "aaaaaaaaaa", name: "Team", masked: "sk-…one", on: true, active: true }, { id: "bbbbbbbbbb", name: "", masked: "sk-…two", on: true }],
},
});
function serve(lang, posts) {
const ps = fresh();
const providers = { providers: [ps.codex, ps.claude, ps.relay], presets: [], excluded: [], gateway: { running: true, window: true } };
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
return async (route) => {
const url = new URL(route.request().url());
const json = (data) => route.fulfill({ json: data });
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` });
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
if (url.pathname === "/api/state") return json(state);
if (url.pathname === "/api/providers") return json(providers);
if (url.pathname === "/api/groups") return json({ groups: [] });
if (url.pathname === "/api/plugins") return json({ plugins: [] });
if (url.pathname === "/api/provider/accountmodels" && route.request().method() === "POST") {
const body = route.request().postDataJSON();
posts.push(body);
const p = providers.providers.find((x) => x.id === body.id);
const am = { ...(p.accountModels || {}) };
if (body.allow.length) am[body.account.toLowerCase()] = body.allow;
else delete am[body.account.toLowerCase()];
p.accountModels = am;
return json(providers);
}
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 route.fulfill({ body: await fs.readFile(file), contentType });
};
}
const words = {
en: { all: "All models", one: "1 model", two: "2 models", save: "Save", only: "Serves only gpt-6-mini" },
zh: { all: "全部模型", one: "1 个模型", two: "2 个模型", save: "保存", only: "只用于 gpt-6-mini" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
const open = async (t, name, wait) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
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}-${name}-account-models.png`) });
}
await browser.close();
});
const page = await (await browser.newContext({ viewport: { width: 900, height: 760 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts));
await page.goto("http://magpie.test/?view=providers");
await page.locator(".row.provider", { hasText: name }).first().click();
await page.locator(wait).first().waitFor();
return { page, errors, posts };
};
const row = (page, id) => page.locator(`.editor .accts .acc[data-account-id="${id}"]`);
const pill = (page, id) => row(page, id).locator(".amodels");
const panel = (page, id) => row(page, id).locator(".acct-models");
const chips = (page, id) => panel(page, id).locator(".mchip").evaluateAll((cs) => cs.map((c) => `${c.textContent}${c.classList.contains("on") ? "*" : ""}`));
// what the page and its scrollers have scrolled
const scrolled = (page) => page.evaluate(() => [window.scrollY, ...[...document.querySelectorAll("*")].filter((e) => e.scrollTop > 0).map((e) => `${e.className}:${e.scrollTop}`)].join(" "));
// a click that leaves the row where it was and scrolls nothing
const still = async (page, id, b) => {
await b.scrollIntoViewIfNeeded();
await page.waitForTimeout(150);
const before = await row(page, id).evaluate((e) => Math.round(e.getBoundingClientRect().top)), sc = await scrolled(page);
await b.click();
await page.waitForTimeout(200);
assert.equal(await row(page, id).evaluate((e) => Math.round(e.getBoundingClientRect().top)), before, `${id}'s row moved`);
assert.equal(await scrolled(page), sc, "a click scrolled");
};
const posted = async (posts, n) => {
for (let i = 0; i < 60 && posts.length === n; i++) await new Promise((r) => setTimeout(r, 50));
return posts.at(-1);
};
test(`${engine} ${lang}: a Codex account is kept for some models, and given all again`, async (t) => {
const { page, errors, posts } = await open(t, "Codex", ".editor .accts .acc .amodels");
// the one kept for gpt-6-mini says so, always; the other says All models on hover only
assert.equal(await pill(page, "Spare@Example.com").textContent(), w.one);
assert.equal(await pill(page, "Spare@Example.com").getAttribute("title"), w.only);
assert.equal(await pill(page, "Spare@Example.com").evaluate((e) => getComputedStyle(e).opacity), "1");
assert.equal(await pill(page, "me@example.com").textContent(), w.all);
await page.mouse.move(0, 0);
await page.waitForTimeout(250);
assert.equal(await pill(page, "me@example.com").evaluate((e) => getComputedStyle(e).opacity), "0");
// me: the provider's models it serves agents, none picked; Save waits for one
await still(page, "me@example.com", pill(page, "me@example.com"));
assert.deepEqual(await chips(page, "me@example.com"), ["gpt-6", "gpt-6-mini"]);
const save = panel(page, "me@example.com").getByRole("button", { name: w.save, exact: true });
assert(await save.isDisabled());
await still(page, "me@example.com", panel(page, "me@example.com").locator(".mchip", { hasText: /^gpt-6$/ }));
assert.deepEqual(await chips(page, "me@example.com"), ["gpt-6*", "gpt-6-mini"]);
assert(await save.isEnabled());
let n = posts.length;
await save.click();
assert.deepEqual(await posted(posts, n), { id: "codex", account: "me@example.com", allow: ["gpt-6"] });
await panel(page, "me@example.com").waitFor({ state: "detached" });
assert.equal(await pill(page, "me@example.com").textContent(), w.one);
// the spare opens on what it has; All models gives it every one again
await still(page, "Spare@Example.com", pill(page, "Spare@Example.com"));
assert.deepEqual(await chips(page, "Spare@Example.com"), ["gpt-6", "gpt-6-mini*"]);
n = posts.length;
await panel(page, "Spare@Example.com").locator("button.action").click();
assert.deepEqual(await posted(posts, n), { id: "codex", account: "Spare@Example.com", allow: [] });
await page.locator(".editor .acct-models").waitFor({ state: "detached" });
assert.equal(await pill(page, "Spare@Example.com").textContent(), w.all);
const border = await page.evaluate(() => [...document.querySelectorAll(".accts .amodels, .acct-models, .acct-models *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1));
assert.deepEqual(border, [], "no border stripes");
const missing = await page.evaluate(() => [
"Serves only {models}",
"Every model of the provider goes to this account. Click to keep it for some only",
"Every model of the provider goes to this key. Click to keep it for some only",
"Pick the provider's models first.",
"{who} serves only {models}",
"{who} serves every model again",
"Every model of the provider, as an account without a list of its own",
"Only the models picked go to this account; the others go to the provider's other accounts.",
"Only the models picked go to this key; the others go to the provider's other keys.",
"set to serve other models, not {model}",
"{who} is left out: it is set to serve other models, not {model}.",
].filter((k) => !I18N.zh[k]));
assert.deepEqual(missing, [], "every string has its Chinese");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a key is kept for some models by its id`, async (t) => {
const { page, errors, posts } = await open(t, "Relay", ".editor .accts .acc .amodels");
assert.equal(await pill(page, "aaaaaaaaaa").textContent(), w.all);
await still(page, "aaaaaaaaaa", pill(page, "aaaaaaaaaa"));
assert.deepEqual(await chips(page, "aaaaaaaaaa"), ["big", "Cheap one"], "a model's own name, as the provider's chips");
await panel(page, "aaaaaaaaaa").locator(".mchip", { hasText: "Cheap one" }).click();
await panel(page, "aaaaaaaaaa").locator(".mchip", { hasText: "big" }).click();
const n = posts.length;
await panel(page, "aaaaaaaaaa").getByRole("button", { name: w.save, exact: true }).click();
assert.deepEqual(await posted(posts, n), { id: "relay", account: "aaaaaaaaaa", allow: ["cheap", "big"] });
await page.locator(".editor .acct-models").waitFor({ state: "detached" });
assert.equal(await pill(page, "aaaaaaaaaa").textContent(), w.two);
assert.equal(await pill(page, "bbbbbbbbbb").textContent(), w.all);
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: a subscription with one account has no models badge`, async (t) => {
const { page, errors } = await open(t, "Claude", ".editor .accts .acc");
assert.equal(await page.locator(".editor .accts .amodels").count(), 0);
assert.deepEqual(errors, []);
});
}
}
+143
View File
@@ -0,0 +1,143 @@
package provider
// An account's own models (#474): one account of several may be one the
// user keeps for some of the provider's models only — an account with a
// small allowance but a verified standing, kept for the cheap models so
// the big ones don't spend it. Its list is a subset of the provider's;
// an account without one serves every model the provider does, as before.
// The gateway never sends a model to an account whose list leaves it out
// (gateway/fallback.go).
import (
"fmt"
"slices"
"strings"
)
// AccountServes says whether the account or key ref (a signed-in
// account's name, a key's KeyID) is let serve model: true when it has no
// list of its own.
func (p Provider) AccountServes(ref, model string) bool {
ms, ok := p.AccountModels[accountKey(ref)]
return !ok || len(ms) == 0 || slices.Contains(ms, model)
}
// AccountRefs are the provider's accounts, or keys, as AccountModels
// knows them: a signed-in account's name, a key's KeyID.
func (p Provider) AccountRefs() []string {
var out []string
if p.Account == nil {
for _, k := range p.KeyList() {
out = append(out, k.ID)
}
return out
}
agent := p.Account.Agent
if p.IsPlugin() {
agent = p.ID
}
if p.Account.User != "" {
out = append(out, p.Account.User)
}
for _, l := range Logins(agent) {
if !slices.ContainsFunc(out, func(u string) bool { return accountKey(u) == accountKey(l.User) }) {
out = append(out, l.User)
}
}
return out
}
// accountRef is the account or key of p that ref names: a signed-in
// account by its name, a key by its KeyID or its name, in any case.
func (p Provider) accountRef(ref string) (string, bool) {
ref = strings.TrimSpace(ref)
for _, r := range p.AccountRefs() {
if accountKey(r) == accountKey(ref) {
return r, true
}
}
if p.Account == nil {
for _, k := range p.KeyList() {
if k.Name != "" && strings.EqualFold(k.Name, ref) {
return k.ID, true
}
}
}
return "", false
}
// SetAccountModels gives the account or key ref of the provider id the
// models it alone serves; none gives it every model the provider has again.
func SetAccountModels(id, ref string, models []string) error {
p, err := Find(id)
if err != nil {
return err
}
r, ok := p.accountRef(ref)
if !ok {
if p.Account == nil {
return fmt.Errorf("%s has no key %q", p.Name, ref)
}
return fmt.Errorf("%s has no account %q", p.Name, ref)
}
ms := normalModels(models)
if len(ms) == 0 && p.AccountModels[accountKey(r)] == nil {
return nil
}
am := map[string][]string{}
for k, v := range p.AccountModels {
am[k] = v
}
if len(ms) == 0 {
delete(am, accountKey(r))
} else {
am[accountKey(r)] = ms
}
p.AccountModels = am
return Save(*p)
}
// AccountModelsOf is the models the account or key ref of the provider id
// alone serves, and the account or key as AccountModels knows it; no
// models when it serves all the provider's.
func AccountModelsOf(id, ref string) (string, []string, error) {
p, err := Find(id)
if err != nil {
return "", nil, err
}
r, ok := p.accountRef(ref)
if !ok {
return "", nil, fmt.Errorf("%s has no account or key %q", p.Name, ref)
}
return r, p.AccountModels[accountKey(r)], nil
}
// normalModels is a list of model ids as it is kept: trimmed, each once,
// in the order given.
func normalModels(ms []string) []string {
var out []string
for _, m := range ms {
if m = strings.TrimSpace(m); m != "" && !slices.Contains(out, m) {
out = append(out, m)
}
}
return out
}
// normalAccountModels is m as it is kept: keys in lower case, lists
// normalized, accounts serving all the provider's models left out; nil
// for none.
func normalAccountModels(m map[string][]string) map[string][]string {
var out map[string][]string
for u, ms := range m {
u, ms = accountKey(u), normalModels(ms)
if u == "" || len(ms) == 0 {
continue
}
if out == nil {
out = map[string][]string{}
}
out[u] = ms
}
return out
}
+8 -2
View File
@@ -113,6 +113,11 @@ type Provider struct {
// of its own, by its name in lower case, as Proxy takes one; an
// account not in it follows Proxy (see ProxyChoice).
AccountProxies map[string]string `json:"accountProxies,omitempty"`
// AccountModels is, for a provider holding several accounts or keys,
// the models each one the user narrowed serves, and no others (#474):
// an account by its name in lower case, a key by its KeyID. One not in
// it serves every model the provider does (see account_models.go).
AccountModels map[string][]string `json:"accountModels,omitempty"`
// BalanceURL, when set, is where the vendor tells what is left on a
// key, asked with the key the way a chat request carries it; BalancePath
@@ -288,7 +293,7 @@ func All() []Provider {
}
pk := picks[a.ID]
a.Models, a.Unlisted, a.Off, a.Fallback, a.Routing, a.Affinity, a.Contexts, a.Family = pk.Models, pk.Unlisted, pk.Off, pk.Fallback, pk.Routing, pk.Affinity, pk.Contexts, pk.Family
a.Proxy, a.AccountProxies = pk.Proxy, pk.AccountProxies
a.Proxy, a.AccountProxies, a.AccountModels = pk.Proxy, pk.AccountProxies, pk.AccountModels
if a.ID == "cursor" { // picked before its efforts were one model
a.Models = cursorPicks(a.Models)
}
@@ -387,7 +392,7 @@ func Save(p Provider) error {
if p.ID == "kiro" {
key = p.Key
}
p = Provider{ID: p.ID, Key: key, Models: p.Models, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID)}
p = Provider{ID: p.ID, Key: key, Models: p.Models, Unlisted: p.Unlisted, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Affinity: p.Affinity, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID)}
} else {
p.AccountProxies = nil // a provider of a key has no accounts to proxy apart
if subscriptionID(p.ID) && !stored(p.ID) {
@@ -646,6 +651,7 @@ func normalize(p Provider) Provider {
p.Key = strings.TrimSpace(p.Key)
p.Proxy = strings.TrimSpace(p.Proxy)
p.AccountProxies = normalAccountProxies(p.AccountProxies)
p.AccountModels = normalAccountModels(p.AccountModels)
p.ZhipuTeam = p.ZhipuTeam.normal()
p.remoteMagpieEndpoints()
for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic, &p.Decide, &p.Website, &p.KeysURL} {
+59
View File
@@ -34,6 +34,8 @@ const providerUsage = `usage:
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
magpie provider fallback <id> <provider/model>… where requests go when it's out of quota or down (none clears)
magpie provider models <id> [ids…] fetch the vendor's model list, or choose which models to expose
magpie provider account-models <id> [account|key [ids…|all]]
the models one account or key alone serves; all: every model the provider has
magpie provider listed <id> yes|no no: its models serve only through routing groups, not in the list
magpie provider off|on <id> switch it off (kept, but no agent or request uses it), or on again
magpie provider test <id> [model…] send a tiny request through each endpoint, or to each model
@@ -402,6 +404,8 @@ func providerCmd(args []string) error {
os.Exit(1)
}
return nil
case "account-models", "account-model":
return accountModelsCmd(rest)
case "listed":
// no: the provider's models leave the list agents see and serve
// only through the routing groups they are in
@@ -915,6 +919,61 @@ func fetchedFrom(p provider.Provider) string {
return p.Name
}
// accountModelsCmd: `magpie provider account-models <id> [account|key
// [ids…|all]]` — the models one account or key of a provider alone serves
// (#474), each account's with none named, all for every one the provider has.
func accountModelsCmd(rest []string) error {
if len(rest) < 1 {
return fmt.Errorf("magpie provider account-models <id> [account|key [model ids…|all]]")
}
p, err := provider.Find(rest[0])
if err != nil {
return err
}
if len(rest) > 2 {
ms := rest[2:]
if len(ms) == 1 && (ms[0] == "all" || ms[0] == "-") {
ms = nil
}
if err := provider.SetAccountModels(p.ID, rest[1], ms); err != nil {
return err
}
}
refs := p.AccountRefs()
if len(rest) > 1 {
ref, _, err := provider.AccountModelsOf(p.ID, rest[1])
if err != nil {
return err
}
refs = []string{ref}
}
if len(refs) == 0 {
fmt.Println(muted.Render(p.Name + " has no account or key"))
return nil
}
label := map[string]string{}
for _, k := range p.KeyList() {
if k.Name != "" {
label[k.ID] = k.Name + " " + muted.Render(k.Masked+" · "+k.ID)
} else {
label[k.ID] = k.Masked + " " + muted.Render(k.ID)
}
}
for _, r := range refs {
name := r
if l, ok := label[r]; ok {
name = l
}
_, ms, _ := provider.AccountModelsOf(p.ID, r)
if len(ms) == 0 {
fmt.Println(name, muted.Render("· every model "+p.Name+" serves"))
} else {
fmt.Println(name, "· only", strings.Join(ms, ", "))
}
}
return nil
}
// printMoved says which agents a change moved off models it stopped
// serving (agent.Reseat).
func printMoved(moved []agent.Move) {