Files
magpie/internal/provider/key_plans.go
T
yetone 6e6aba51c8 providers: a key may be for another plan of its vendor, sent to that plan's endpoints
yckonnnn on X uses Volcengine's pay as you go and its Agent Plan, and
wants a key of each in one provider. Each plan takes its own keys at its
own endpoints (/api/v3, /api/plan/v3, /api/coding/v3), and every key of
a provider went to the provider's one plan, so only one kind worked.

A key now may say which of its preset's Regions it is for
(KeyAccount.Plan; Provider.KeyPlan for the first key, as KeyProtocol).
None, or the provider's own plan, is the provider's plan, stored as
none: old configs read and write as before. Presets whose plans take
keys of their own (PresetDef.KeyPlans): zhipu, zai, stepfun,
stepfun-cn, xiaomi, baidu-qianfan, tencent-cloud, huaweicloud,
volcengine, siliconflow. Not: yylx (one key everywhere),
bailian-decision (decide only), bedrock and bedrock-mantle (regions of
one account).

Every reader of the region or a base URL, and what it does now:
- WithKey (keys.go): moves the key's copy to its plan (atKeyPlan:
  Chat, Responses, Anthropic, Decide, KeysURL, Website, Catalog via
  atRegionOf; a provider at a host of its own keeps that host) and marks
  it keyView. Every gateway key path goes through it: chat, Responses,
  Messages, count_tokens, failover, embeddings (serveRetrieval via
  onKeys), drawing (drawOnAccounts via perKeyBarred), key tests
  (test.go), key_models.go, gui/groups.go, markedKey.
- perKeyBarred (gateway/fallback.go): a key whose plan's list lacks the
  model (PlanServing) is not asked; only when no key's plan has it.
- fetch / fetchPerKey / planOnly (models.go): a mixed provider lists
  each key's plan, a NoList plan from its preset list with no request,
  pay as you go from /api/v3/models with its own key.
- planMedia (PlanEmbeddings, PlanDrawers, PlanVideos): every plan's.
- PlanQuotas (planquota.go): each key read at its own plan's source.
- volcPlanQuotas, tencentPlanQuotas: one view per plan (planViews).
- KeyBalances (balance.go): each key at its plan's host (SiliconFlow).
- startVideo / videoMaker (gateway/video.go): a mixed provider starts on
  a key whose plan makes the model (onKeys) and names it in the id
  (keyMark), so the poll goes to that key's plan.
- GUI: POST /api/keys/plan (SetKeyPlan, then the lists are read again);
  the editor keeps KeyPlan with an unchanged first key, typed() clears
  it with a new one; KeepSecrets, AddCopy, backup's withoutKeys carry it.
- app.js: planPicker, a plan chip in each key row (the app's own menu,
  openProtoMenu, through pickPill, which protoPicker now shares), shown
  for a KeyPlans preset while the provider has several keys or the key
  has a plan; i18n zh, zh-TW, ja, de.

A key's plan is not guessed from the key: Volcengine's keys carry
nothing that says their plan. Xiaomi's tp-, Tencent's sk-tp-, MiniMax's
sk-cp- and Bailian's sk-sp- are noted in code but not used.

Not done: a gateway key held to some keys (videoAsker) on a mixed
provider's video may pick another key; a mixed provider whose own plan
has no balance source while a key's plan has one is not read; keys left
out for their plan don't show in the Routing trace; StepFun's plan
windows are a sign-in per site, unchanged.

Credit: yckonnnn on X (tweet 2114657701305487483).

Run at this commit on origin/main 1bb8143b3 (macOS, go1.26.8):
- gofmt -l internal: clean. go vet ./..., GOOS=linux go vet -tags nogui
  ./..., GOOS=windows go vet ./...: clean.
- go test -count=1 -skip TestUnreadLoginsWriteErrorsKeepCredentials
  ./internal/provider/ ./internal/gateway/: ok (103s, 421s). The skipped
  test crashes the whole provider package on main (#3632, from 091153bf).
- TestCoreScriptBudget: ok, budgets not raised (app.js 1,307,430 bytes).
- GUI, chromium and webkit: key-*, provider*-*, add-sheet, i18n-keys,
  gui-de, gui-ja, gui-zh-tw (58 files): 956 of 956 pass. key-plan.test.cjs
  covers en, zh, zh-TW, ja and de at 420 and 1000px.
Earlier, at the same change on origin/main 9120acaff:
- go test -timeout 45m ./...: 71 packages ok, internal/gateway and
  internal/gui among them. internal/provider crashed on #3632 only; run
  again with that one test skipped, it passed.
- The whole GUI suite (node --test tests/*.test.cjs) did not finish: the
  disk ran out at about 319 tests and the run was stopped. Up to then the
  only reds were account-discovery in both engines, #3497, red on main.
Broken by hand: without atKeyPlan in WithKey, TestKeyPlanEndpoints,
TestKeyPlanModelList and TestKeyPlansEachToItsOwnEndpoint go red; without
the planless filter in perKeyBarred the gateway test goes red; without
the plan chip key-plan.test.cjs goes red.
Not tried: real Volcengine (or any other vendor's) keys of two plans in
one provider; the video path (startVideo with mixed plans) has no test of
its own; Windows and Linux were vetted, not run.
2026-10-26 20:37:07 +08:00

216 lines
6.0 KiB
Go

package provider
// A vendor may sell its plans and its pay as you go on keys of their own,
// each taken only at its own endpoints: Volcengine's Coding Plan at
// /api/coding, its Agent Plan at /api/plan, its pay as you go at /api/v3
// (yckonnnn on X, with one key of each in one provider). A key of such a
// preset (PresetDef.KeyPlans) may say which of its Regions it is for
// (KeyAccount.Plan, Provider.KeyPlan for the first): its requests go to
// that plan's endpoints, it is asked only for that plan's models, its
// model list is that plan's, and its windows and balance are read where
// that plan's are. A key that says none is on the provider's own plan, as
// every key was before.
import (
"net/url"
"strings"
)
// keyRegion is the region of p's preset a key's plan names, and the
// region p sits at; nil for a key on p's own plan, or a preset whose keys
// are all on one.
func (p Provider) keyRegion(plan string) (pr *PresetDef, r, cur *Region) {
if plan == "" {
return nil, nil, nil
}
pr = Preset(p.Preset)
if pr == nil || !pr.KeyPlans {
return nil, nil, nil
}
for i := range pr.Regions {
if pr.Regions[i].ID == plan {
r = &pr.Regions[i]
}
}
if r == nil {
return nil, nil, nil // a plan the preset no longer has: the provider's
}
cur = p.regionOf(pr)
if cur != nil && cur.ID == r.ID {
return nil, nil, nil
}
return pr, r, cur
}
// atKeyPlan is p at the endpoints of the plan a key is for (its Region),
// with that plan's key page, docs and catalog; p as it is for a key on its
// own plan. A provider asked at another host than its preset's (a mirror,
// a test's fake vendor) is asked at that host on the other plan too.
func (p Provider) atKeyPlan(plan string) Provider {
pr, r, cur := p.keyRegion(plan)
if r == nil {
return p
}
host := p.ownHost(cur)
p.atRegionOf(pr, *r)
if host != "" {
for _, u := range []*string{&p.Chat, &p.Responses, &p.Anthropic} {
*u = rehost(*u, host)
}
}
return p
}
// ownHost is the scheme and host p is asked at when they aren't its
// region's own, "" when they are.
func (p Provider) ownHost(cur *Region) string {
if cur == nil {
return ""
}
for _, e := range [][2]string{{p.Chat, cur.Chat}, {p.Responses, cur.Responses}, {p.Anthropic, cur.Anthropic}} {
if e[0] == "" || e[1] == "" {
continue
}
a, err1 := url.Parse(e[0])
b, err2 := url.Parse(e[1])
if err1 != nil || err2 != nil || strings.EqualFold(a.Host, b.Host) {
return ""
}
return a.Scheme + "://" + a.Host
}
return ""
}
// rehost is raw at host (scheme://host) instead of its own.
func rehost(raw, host string) string {
if raw == "" {
return ""
}
u, err := url.Parse(raw)
if err != nil {
return raw
}
h, err := url.Parse(host)
if err != nil {
return raw
}
u.Scheme, u.Host = h.Scheme, h.Host
return u.String()
}
// PlansMixed reports whether p's keys in use are on more than one of its
// preset's plans (KeyAccount.Plan).
func (p Provider) PlansMixed() bool { return p.plansMixed() }
// plansMixed reports whether a key of p in use is for another plan than
// p's own: only then do its keys differ in endpoints and models. Read
// from the keys themselves, not KeysOn, which a test counts per request.
func (p Provider) plansMixed() bool {
if p.Key == "" || p.keyView {
return false
}
pr := Preset(p.Preset)
if pr == nil || !pr.KeyPlans {
return false
}
if _, r, _ := p.keyRegion(p.KeyPlan); r != nil {
return true
}
for _, k := range p.Keys {
if k.Off || k.Key == "" || k.Key == p.Key {
continue
}
if _, r, _ := p.keyRegion(k.Plan); r != nil {
return true
}
}
return false
}
// planList is the models a plan has as the preset says, for a key at it:
// its region's own, or the preset's for a preset that lists nothing at a
// region that doesn't list either; with its embedding, drawing and video
// models. nil when the plan's models are its vendor's list's to say.
func (p Provider) planList() []string {
pr := Preset(p.Preset)
if pr == nil {
return nil
}
r := p.regionOf(pr)
if r == nil {
return nil
}
var out []string
switch {
case r.Models != nil:
out = append(out, r.Models...)
case pr.NoList && !r.Lists:
out = append(out, pr.Models...)
}
for _, l := range [][]string{r.Embeddings, r.Drawers, r.Videos} {
out = append(out, l...)
}
return out
}
// PlanServing is, for each of p's keys, whether the plan that key is for
// can serve model: false only when p's keys are on different plans
// (KeyAccount.Plan) and the key's plan names its models and leaves this
// one out — a pay-as-you-go model id sent to the Agent Plan's endpoint
// only answers 404. A model the user set the key to serve
// (AccountModels) it serves. Every key serves when p's keys are on one
// plan, as before.
func (p Provider) PlanServing(model string) func(KeyAccount) bool {
if !p.plansMixed() {
return func(KeyAccount) bool { return true }
}
lists := map[string][]string{} // each plan's, found once
return func(k KeyAccount) bool {
if m, ok := p.AccountModels[keyID(k.Key)]; ok && containsFold(m, model) {
return true
}
l, ok := lists[k.Plan]
if !ok {
l = p.atKeyPlan(k.Plan).planList()
lists[k.Plan] = l
}
return l == nil || containsFold(l, model)
}
}
func containsFold(l []string, s string) bool {
for _, x := range l {
if strings.EqualFold(x, s) {
return true
}
}
return false
}
// planViews is each provider of ps once for each plan its keys in use are
// on, at that plan's endpoints, with those keys alone: a plan's windows
// read with an access key (Volcengine's, Tencent Cloud's) are read for
// each plan a provider has a key of.
func planViews(ps []Provider) []Provider {
var out []Provider
for _, p := range ps {
if !p.plansMixed() {
out = append(out, p)
continue
}
at := map[string]int{}
for _, k := range p.KeysOn() {
q := p.atKeyPlan(k.Plan)
if i, ok := at[q.Chat+" "+q.Anthropic]; ok {
out[i].Keys = append(out[i].Keys, k)
continue
}
at[q.Chat+" "+q.Anthropic] = len(out)
q.setFirst(k)
q.Keys = nil
out = append(out, q)
}
}
return out
}