Files
magpie/internal/provider/remote_key_limits.go
T
yetone 1c9747f611 usage: a Remote magpie provider's gateway keys each show their own limit, used and left, period and reset on the Usage page (#1547, PennyVibe)
A computer that uses another magpie through gateway keys that magpie gave
it saw the other magpie's subscription cards, but not what each key may
still spend there.

What changed:
- provider/remote_key_limits.go: each key of a remote-magpie provider
  gets a section on one card, "<remote>/~keys", read from the remote's
  existing GET /v1/magpie/limit asked with that key alone (the endpoint
  answers only the calling key, from access.Caller; nothing in the
  request picks another key, so a key never sees another's numbers).
  A window per cap (tokens, spend) named for its period (today / this
  week / this month / this cycle), used against the cap, with its
  reset; SubscriptionQuota.GatewayKey carries what is left, calls, the
  cycle's days, used up and unpriced calls. A key with no limit shows
  one "Limit: Unlimited" window. Kept for remoteCardsFor like the
  remote's cards; the card's refresh reads the named key again.
- A failed read keeps the last numbers, dated (AsOf); with nothing read
  the section says why, never zero and never "no limit". A remote from
  before /v1/magpie/limit (404) says it is too old to tell.
- GUI: the card is named "Gateway keys · <remote>" (main page and the
  tray panel), a line under each key says the cycle, calls and "used
  up", and the two new errors are said plainly; strings in zh, zh-TW,
  ja, de.
- magpie quota (CLI) shows the same cards; a window with no cap now
  reads "Limit unlimited" there, not "Limit 0%" (quotaCell).
- docs: providers-accounts (Allowance), gateway-routing (Remote magpie
  APIs, verification), reference (/v1/magpie/limit).

Run:
- New tests fail on the old code: TestRemoteMagpieKeyLimits (provider)
  and TestRemoteMagpieKeyLimitCards (gateway, a real Handler, real chat
  requests moving the numbers) with the key cards taken out of
  RemoteCards; usage-remote-key-limits.test.cjs on HEAD's app.js.
  TestKeyLimitTellsOnlyTheCaller guards what was already so (key A can't
  read key B by query, header or no key from the LAN), so it passes on
  both. TestQuotaCell's unlimited case reads "Limit 0%" on the old code.
- provider, gateway -count=3; go test -tags nogui ./... (full suite).
- GUI: the new test in chromium and webkit x en/zh/zh-TW/ja/de x
  900/400px (20 pass); the whole GUI suite.
- gofmt -l clean; go vet -tags nogui darwin, linux, windows.
- Real two-magpie run, both this build, sandbox HOMEs, 127.0.0.1:38461
  (remote) and :38471 (local); the upstream was a fake OpenAI server
  (fixed 175 tokens a reply). Remote keys laptop (1000 tokens/day), desk
  (5000/week), spare (no limit); local "office" Remote magpie with all
  three, routing rotate. After 17 chats through the local gateway,
  magpie quota on the local read laptop 1050/1000 (100%), desk
  1050/5000 (21%), spare unlimited (in --json; the text line read
  "Limit 0%", which the quotaCell change above fixes), matching the remote's own
  gateway-key list; laptop's spent key was passed over (every chat
  200). With the remote stopped each key said it couldn't be reached,
  never 0. Not run against a real vendor, nor a real magpie older than
  /v1/magpie/limit (unit-tested with a 404).
2026-10-11 09:10:44 +08:00

254 lines
8.6 KiB
Go

package provider
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"math"
"net/http"
"sync"
"time"
)
// A remote magpie's gateway keys (#1547, PennyVibe): a computer that uses
// another magpie with a gateway key that magpie gave it saw the other
// magpie's subscriptions on its Usage page, but not what the key itself
// may still spend there. Each key of a remote-magpie provider now has a
// card of its own: its limit, what it used and has left of it, the period
// and when it resets, or "no limit".
//
// The other magpie tells a key its own limit and nothing else
// (RemoteKeyLimitPath, answered by the gateway's keyLimit for the key the
// request carries, and only that one). So each key is asked with itself:
// a key never sees another key's numbers, here or there.
// RemoteKeyLimitPath is the gateway's answer of the calling key's limit.
const RemoteKeyLimitPath = "/v1/magpie/limit"
// remoteKeyCard is the card id the keys' cards go under, after the
// remote's ("office/~keys"): no provider id has a "~", so it never meets
// a card the remote has.
const remoteKeyCard = "~keys"
// errRemoteNoKeyLimit is a remote magpie too old to tell a key its limit.
const errRemoteNoKeyLimit = "remote magpie is too old to tell this key's limit; update magpie on that computer"
// GatewayKeyLimit is a remote gateway key's limit as its card carries it.
// Windows on the card show each cap; this says what they don't.
type GatewayKeyLimit struct {
// Limited is false for a key the remote holds to no limit.
Limited bool `json:"limited"`
// Period is "day", "week", "month" or "days" (a cycle of Days days).
Period string `json:"period,omitempty"`
Days int `json:"days,omitempty"`
Start time.Time `json:"start,omitzero"`
Reset time.Time `json:"reset,omitzero"`
Calls int `json:"calls,omitempty"`
// TokensLeft and CostLeft are what is left of each cap there is.
TokensLeft *int64 `json:"tokensLeft,omitempty"`
CostLeft *float64 `json:"costLeft,omitempty"`
// Spent: the remote refuses the key until Reset.
Spent bool `json:"spent,omitempty"`
// Unpriced calls add nothing to the cost, so it reads low.
Unpriced int `json:"unpriced,omitempty"`
}
// remoteKeyAnswer is RemoteKeyLimitPath's answer (budget.Status, as the
// gateway's keyLimit sends it).
type remoteKeyAnswer struct {
Limited *bool `json:"limited"`
Key string `json:"key"`
Limit *struct {
Period string `json:"period"`
Days int `json:"days"`
Start time.Time `json:"start"`
Reset time.Time `json:"reset"`
Calls int `json:"calls"`
Tokens int64 `json:"tokens"`
Cost float64 `json:"cost"`
Unpriced int `json:"unpriced"`
TokenLimit int64 `json:"tokenLimit"`
CostLimit float64 `json:"costLimit"`
TokensLeft int64 `json:"tokensLeft"`
CostLeft float64 `json:"costLeft"`
Spent bool `json:"spent"`
} `json:"limit"`
}
type remoteKeyRead struct {
at time.Time // when it was last asked
readAt time.Time // when got was read; zero before any
got *remoteKeyAnswer
err string
}
var remoteKeyCache struct {
sync.Mutex
m map[string]remoteKeyRead // by provider id and key fingerprint
}
// remoteKeys are p's keys in use, each with the name its card goes by:
// the name the user gave it here, else the key masked; a name two keys
// share has each one's masked key after it.
func remoteKeys(p Provider) (names []string, keys []string) {
on := p.KeysOn()
seen := map[string]int{}
for _, k := range on {
seen[k.Name]++
}
for _, k := range on {
n := k.Name
if n == "" {
n = Mask(k.Key)
} else if seen[n] > 1 {
n += " · " + Mask(k.Key)
}
names, keys = append(names, n), append(keys, k.Key)
}
return names, keys
}
// remoteKeyCards are p's keys' cards: each read from the remote when
// what is kept here is older than remoteCardsFor, or fresh is asked for
// the key named only (every key when only is "").
func remoteKeyCards(ctx context.Context, p Provider, fresh bool, only string) []SubscriptionQuota {
names, keys := remoteKeys(p)
out := make([]SubscriptionQuota, len(keys))
var wg sync.WaitGroup
for i := range keys {
wg.Add(1)
go func() {
defer wg.Done()
out[i] = remoteKeyCardOf(ctx, p, names[i], keys[i], fresh && (only == "" || only == names[i]))
}()
}
wg.Wait()
return out
}
func remoteKeyCardOf(ctx context.Context, p Provider, name, key string, fresh bool) SubscriptionQuota {
id := p.ID + "\x00" + keyID(key)
c := &remoteKeyCache
c.Lock()
r, ok := c.m[id]
c.Unlock()
if !ok || fresh || time.Since(r.at) >= remoteCardsFor {
got, err := askRemoteKeyLimit(ctx, p, key)
r.at = time.Now()
if err != nil {
// what was read before stays, dated: a failed read is not
// "no limit" and not "nothing used"
r.err = err.Error()
} else {
r.got, r.readAt, r.err = got, r.at, ""
}
c.Lock()
if c.m == nil {
c.m = map[string]remoteKeyRead{}
}
c.m[id] = r
c.Unlock()
}
from := remoteName(p)
q := SubscriptionQuota{Provider: p.ID + "/" + remoteKeyCard, Name: from, Icon: "magpie", User: name, Kind: "plan", From: from, Windows: []QuotaWindow{}}
if r.got == nil {
q.Error = r.err
return q
}
at := r.readAt
q.ReadAt = &at
if r.err != "" {
q.AsOf = &at
}
q.GatewayKey, q.Windows = keyLimitCard(r.got)
return q
}
// keyLimitCard is what a key's card shows of the remote's answer: a
// window for each cap, named for its period, or one window with no limit.
func keyLimitCard(a *remoteKeyAnswer) (*GatewayKeyLimit, []QuotaWindow) {
l := a.Limit
if !*a.Limited || l == nil {
return &GatewayKeyLimit{}, []QuotaWindow{{Name: "Limit", Unlimited: true}}
}
g := &GatewayKeyLimit{Limited: true, Period: l.Period, Days: l.Days, Start: l.Start, Reset: l.Reset, Calls: l.Calls, Spent: l.Spent, Unpriced: l.Unpriced}
reset := l.Reset
var ws []QuotaWindow
share := func(used, limit float64) float64 { return math.Min(100, math.Round(used/limit*1000)/10) }
if l.TokenLimit > 0 {
left := l.TokensLeft
g.TokensLeft = &left
ws = append(ws, QuotaWindow{Name: keyWindowName("Tokens", l.Period), Used: share(float64(l.Tokens), float64(l.TokenLimit)), ResetsAt: &reset,
Amount: float64(l.Tokens), Limit: float64(l.TokenLimit), Unit: "tokens"})
}
if l.CostLimit > 0 {
left := l.CostLeft
g.CostLeft = &left
ws = append(ws, QuotaWindow{Name: keyWindowName("Spend", l.Period), Used: share(l.Cost, l.CostLimit), ResetsAt: &reset,
Amount: math.Round(l.Cost*100) / 100, Limit: l.CostLimit, Unit: "USD"})
}
if ws == nil { // limited, with no cap it tells: an answer we can't read
return &GatewayKeyLimit{}, []QuotaWindow{{Name: "Limit", Unlimited: true}}
}
return g, ws
}
// keyWindowName is a cap's window as the GUI translates it: "Tokens
// today", "Spend this week", "Tokens this cycle".
func keyWindowName(what, period string) string {
switch period {
case "day":
return what + " today"
case "week":
return what + " this week"
case "month":
return what + " this month"
}
return what + " this cycle"
}
// askRemoteKeyLimit asks p's gateway, with key, for that key's limit.
func askRemoteKeyLimit(ctx context.Context, p Provider, key string) (*remoteKeyAnswer, error) {
ctx, cancel := context.WithTimeout(ctx, 8*time.Second)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, p.Anthropic+RemoteKeyLimitPath, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+key)
req.Header.Set("Accept", "application/json")
res, err := p.Do(http.DefaultClient, req)
if err != nil {
return nil, fmt.Errorf("%s %s: %w", errRemoteUnreachable, remoteName(p), err)
}
defer res.Body.Close()
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
switch {
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed:
return nil, errors.New(errRemoteNoKeyLimit)
case res.StatusCode == http.StatusForbidden:
return nil, errors.New(errRemoteNotShared)
case res.StatusCode == http.StatusUnauthorized:
return nil, errors.New(errRemoteKey)
case res.StatusCode < 200 || res.StatusCode >= 300:
var e struct {
Error struct {
Message string `json:"message"`
} `json:"error"`
}
if json.Unmarshal(b, &e) == nil && e.Error.Message != "" {
return nil, fmt.Errorf("%s: %s", remoteName(p), e.Error.Message)
}
return nil, fmt.Errorf("%s answered %s", remoteName(p), res.Status)
}
var a remoteKeyAnswer
if err := json.Unmarshal(b, &a); err != nil || a.Limited == nil {
// not the answer of a magpie's keyLimit: something else at that
// address, or a reply cut short
return nil, fmt.Errorf("%s answered its key's limit in a form magpie doesn't read", remoteName(p))
}
return &a, nil
}