plugin: gateway key limits are the Key limits plugin on the gateway's budget point (P3)

The last P3 point, after observer, router strategy, middleware and tool:
the budget point (internal/gwbudget). A plugin serves a Limiter while it
is on; the gateway asks gwbudget.Limiting before any request of a key held
to a limit goes to a provider (reserveFor: the chat APIs' keyLimited, the
search MCP server and the vision one). A request without a key, or of a
key with no limit, never asks it.

It fails closed. A key with a limit and no limiter served gets 503
gateway_key_limit_off, X-Should-Retry false, nothing sent, and a rejected
usage row. With none served, Limiting first asks the gateway's refresh
(pluginrt.Refresh, at most once a second, never from inside one), so a
limit set a moment ago turns the plugin on for the request that needs it.
A limit reached is the 429 gateway_key_limit with Retry-After and
X-Magpie-Limit-Reset, as before.

plugins/budget serves internal/budget's limiter (budget.Limiter). It is
Essential and in use while a gateway key has a limit, so it can only be
off while none has; a keys file that can't be read is an error, so it
stays on. KeepFresh watches the keys file too. What a key has used and
has left (/v1/magpie/limit, the Gateway page, the CLI) and budget.Append
stay in the core, so the ledger counts a key's use the same either way,
and the key editor's limit fields stay, since setting a limit is what
turns the plugin back on.

The builtins GUI test wheels to the Routing row as it did to Usage's: the
new row puts it below the fold in WebKit, where the page puts back a
scroll that isn't the reader's (scrollOnPurpose).

Run at this head (on origin/main 9d97fd073):
- go test -count=1 -timeout 45m ./... at this head (after two runs cut short by a full disk): 63 ok, 1 red: internal/gui TestMainWindowCorners/macOS_26_SDK killed at its 40s deadline at load ~280 (#1936, no window change here); alone it passed.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows clean
- GUI, chromium and webkit: builtins, plugin-kernel, i18n-keys, gui-de,
  gui-ja, gui-zh-tw pass
- TestKeyLimitsOnAndOff, TestVisionMCPHeldToKeyLimit, TestKeyLimit*,
  plugins/budget tests

Broken by hand, each test went red: reserveFor ignoring Limiting's error,
Limiting letting a limited key through with none served, the refresh
never asked, Apply serving nothing, InUse counting keys with no limit,
InUse swallowing a read error, the vision and search MCP servers not
reserving, a refusal answered as 503 rather than 429.

Real use (built magpie, sandbox HOME/XDG_CONFIG_HOME, gateway on
127.0.0.1:3594, fake vendor on 3593, two gateway keys):
- no key with a limit: `plugin builtin off budget` turned it off; the
  key's request was 200
- `gateway-key limit <id> day --tokens 3`, then a request at once: 200,
  and the plugin read "on, in use"; the next 200, then 429 "has used 4 of
  its 3 ... tokens for this day"; turning it off was refused, "in use"
- the key with no limit: 200; /v1/magpie/limit answered the spent day
- limit removed: turned off; the key's request 200; a limit set again and
  a request at once: 200, "on, in use"
Not tried: the 503 in real use. With a key limited, the refresh turns the
plugin on before the request is refused (a hand-set `enabled: false` in
plugins.yml read "on, in use"); the 503 is the test's.
This commit is contained in:
yetone
2026-10-15 18:41:03 +08:00
parent dd25997a45
commit a1f7b8c13f
17 changed files with 525 additions and 45 deletions
+4 -1
View File
@@ -181,7 +181,10 @@ limits at once, each in its own window, and a request needs every one
the spent limit that resets last). The saved key keeps the first limit in
`limit`, which older magpie reads, and the rest in `moreLimits`. The answer's
`limit` is the one holding the key most (`budget.Binding`), what older
clients read, and `limits` is each of them (`budget.All`). A local magpie
clients read, and `limits` is each of them (`budget.All`). Holding a
key to its limits is the Key limits plugin's, on the gateway's budget
point ([Plugin runtime](plugin-runtime.md#gateway-extension-points-p3-budget)):
with it off, a key held to a limit gets 503 and nothing is sent. A local magpie
asks it with each of its remote-magpie keys for that key's card on its
Usage page (#1547), a window per limit's cap.
+18 -6
View File
@@ -9,11 +9,11 @@ runtime, the file and the window's switch) and P1 (the window's kernel: a
plugin's page, its error boundary, the kit it draws with and its settings
form, with the Gateway page as the first plugin to draw its own page), and
P2 so far (a page moved out of the core whole: its code, styles and words:
Sessions, Library, Routing and Usage), and P3 so far (the gateway's
Sessions, Library, Routing and Usage), and P3 (the gateway's
extension points: the observer, with OTel export as its first plugin; the
router strategy, with the routings besides Smart and the user's groups; and
the middleware point, with the JS gateway middleware and privacy masking;
and the tool point, with web search). OpenCode plugins (npm packages in
the tool point, with web search; and the budget point, with key limits). OpenCode plugins (npm packages in
the plugin host) are a different thing; see
[provider and plugin ownership](provider-plugins.md) and
[gateway middleware](gateway-middleware.md).
@@ -28,7 +28,7 @@ the plugin host) are a different thing; see
| Ctx | What `Apply` gets: `OnDispose(f)`, `Contribute(slot, key)`, `Provide(name, v)` (withdrawn when it goes), `Service(name)`, and its composed `Config`. Disposers run in reverse, each one's panic logged and the rest still run. | [`pluginrt.go`](../../internal/pluginrt/pluginrt.go) |
| plugins.yml | `appdir.Config()/plugins.yml`: `preset` (`essentials` or `all`) and `plugins`, rows of `{id, enabled, config}` holding only what the user set. | [`config.go`](../../internal/pluginrt/config.go) |
| Settings schema | `SchemaOf(Settings)` makes a JSON Schema object of the struct, in its fields' order (`x-order`): each exported field with a json name is a setting, of `bool`, an int, `float64` or `string`, with tags `title` (English; the window translates it), `description`, `enum` (comma separated) and `min`/`max`. Its values are the defaults. A field a form can't draw, or a tag that doesn't parse, panics at `Register`. `Schema.Validate` takes a value only as the schema allows it (a JSON float64 or a YAML int for an integer); `SetConfig(id, config)` writes the user's row through it, and `Compose` leaves out a value edited into plugins.yml by hand that it doesn't allow, so the default stands. | [`schema.go`](../../internal/pluginrt/schema.go), [`config.go`](../../internal/pluginrt/config.go) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `middleware` (P3), the JS gateway middleware, is Essential and in use while plugins.json has a middleware on (`middleware.On`). `redact` (P3), privacy masking, is Essential and in use while Settings → Privacy asks for any masking (`masking.Wanted`). `search` (P3), magpie's web search, is Essential and in use while a search API is set up or a searcher is picked. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
| Built-in plugins | `groups`, `library`, `otel`, `sessions`, `warmups` (P0), `gateway` (P1), the Gateway page, which is Essential and in use while a gateway key is there (`access.List`), and `routing` (P2), the Routing page, Essential and in use while the user has a routing group, since the page is where groups are made and changed. `rotation` (P3), the routings besides Smart, is Essential and in use while a provider or group is routed by one of them. `middleware` (P3), the JS gateway middleware, is Essential and in use while plugins.json has a middleware on (`middleware.On`). `redact` (P3), privacy masking, is Essential and in use while Settings → Privacy asks for any masking (`masking.Wanted`). `search` (P3), magpie's web search, is Essential and in use while a search API is set up or a searcher is picked. `budget` (P3), key limits, is Essential and in use while a gateway key has a limit. `usage` (P2), the Usage page, is Essential too, with no `InUse`: what it shows the gateway counts anyway, and the tray panel's Usage tab still shows the allowances with it off. The Gateway page's one setting, `callsPage` (10, 20, 50 or 100; 20), is how many recent calls the page shows at a time. The other five aren't Essential. Each one's `InUse` counts what the user made with it: routing groups not Auto and not hidden, library items given to agents, a collector sent to, gateway conversations recorded, warm-ups and check-ins on. | [`plugins/`](../../plugins) |
The boundary is checked by `TestPluginsImportOnlyCore`: no package outside
`plugins/` imports one (but `main.go`, through `plugins/all`), a plugin never
@@ -158,8 +158,8 @@ says one of its words, which goes back to i18n.js.
## Gateway extension points (P3): observer
P3 opens the gateway to plugins at four points: observer, router strategy,
middleware and tool. The observer is the first. It only reads, so it is
P3 opens the gateway to plugins at five points: observer, router strategy,
middleware, tool and budget. The observer is the first. It only reads, so it is
the safest to move first. `plugins/otel` is its first consumer, and with the
plugin off the gateway does no observing work.
@@ -231,7 +231,19 @@ it, on or off.
| Off | `searchServed` gates the three places every search path goes through: `canSearch` (the stand-in tool, `/v1/models`' search note to another magpie, the subscriptions' search, `CanSearch` for the agents' rows), `searchesOwn` (a Kimi Code or WorkBuddy plan's own search service, a Google sign-in's Gemini) and `webSearch` itself, which answers `errSearchOff` without asking a searcher or a search API. So off, a request with `web_search` goes to the vendor as it does with no searcher set up, and the MCP server and Codex's search say the plugin is off (`TestSearchOnAndOff`). | [`search.go`](../../internal/gateway/search.go), [`search_api.go`](../../internal/gateway/search_api.go), [`search_kimi.go`](../../internal/gateway/search_kimi.go) |
| `plugins/search` | Requires `settings` and `gateway`, Essential. Apply serves `gwtool.WebSearch`. `InUse` counts the search APIs set up (`provider.SearchAPIsSet`, the file alone) and a searcher picked in Settings (neither magpie's pick nor off); an unreadable providers.json or settings.json is an error, so it stays on. The gateway's `KeepFresh` watches both files, so a search API added from the CLI or the window turns it on within 2s. | [`search.go`](../../plugins/search/search.go) |
The last point is budget.
## Gateway extension points (P3): budget
The budget point holds a gateway key to the limits its owner set (#585,
#2227) before any of the key's requests goes to a provider. It is the last
of the P3 points. A request without a key, or of a key with no limit, never
asks it.
| Part | What it does | Source |
| --- | --- | --- |
| `gwbudget.Limiter` | `Reserve(who, body, model, now) (release, refused)`: lets a key's request in, holding what it is expected to use until release, or refuses it with a `Refusal` (`RetryAfter`, `ResetAt`). `Limit(l)` serves one until its remove; registering again stacks, and the last one serves. | [`gwbudget.go`](../../internal/gwbudget/gwbudget.go) |
| Fail closed | `Limiting(who)` is nil for a request with no key or a key with no limit, the served limiter otherwise, and `ErrUnlimited` when the key has a limit and none serves. With none it first asks the refresh (the gateway's is `pluginrt.Refresh`, set by `gwbudget.Refresh` in `ListenAndServe`), at most once a second and never from inside one, then looks again, so a limit set a moment ago turns the plugin on for the request that needs it. `reserveFor` is the gateway's one way in, for the chat APIs (`keyLimited`), the search MCP server and the vision one: a refusal is 429 `gateway_key_limit` with Retry-After and X-Magpie-Limit-Reset; `ErrUnlimited` is 503 `gateway_key_limit_off`, X-Should-Retry false, nothing sent, and a rejected usage row (`TestKeyLimitsOnAndOff`, `TestVisionMCPHeldToKeyLimit`). | [`gwbudget.go`](../../internal/gwbudget/gwbudget.go), [`key_limit.go`](../../internal/gateway/key_limit.go) |
| `plugins/budget` | Requires `settings` and `gateway`, Essential. Apply serves `budget.Limiter`, `internal/budget`'s windows and reservations as before. `InUse` counts the gateway keys with a limit (`access.List`); a keys file that can't be read is an error, so it stays on. Since it is in use whenever a key has a limit, it can only be off while none has; the 503 is for a refresh not yet seen or a plugins.yml edited by hand. The gateway's `KeepFresh` watches the keys file too, so a limit set from the CLI or the window turns it on within 2s. | [`budget.go`](../../plugins/budget/budget.go) |
| Stays in the core | What a key has used and has left (`budget.All`, `budget.Binding`) for `/v1/magpie/limit`, the Gateway page and the CLI, and `budget.Append`, so the usage ledger counts a key's use the same with the plugin on or off. The key editor's limit fields stay with the plugin off, since setting a limit is what turns it back on. | [`budget.go`](../../internal/budget/budget.go) |
## Source of truth and composing
+16
View File
@@ -39,6 +39,7 @@ import (
"time"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/settings"
"github.com/yetone/magpie/internal/usage"
@@ -315,6 +316,21 @@ func (r *Refusal) RetryAfter(now time.Time) int {
return max(int(r.Reset.Sub(now).Seconds()+0.999), 1)
}
// ResetAt is when the window resets.
func (r *Refusal) ResetAt() time.Time { return r.Reset }
// Limiter is Reserve as the gateway's budget point asks it
// (gwbudget.Limiter); plugins/budget serves it.
type Limiter struct{}
func (Limiter) Reserve(who access.Identity, body int64, model string, now time.Time) (func(), gwbudget.Refusal) {
release, refused := Reserve(who, body, model, now)
if refused != nil {
return nil, refused
}
return release, nil
}
// Reserve lets a request of who's in, holding a reservation for it until
// the release it returns is called, or refuses it. body is the request's
// size in bytes (-1 unknown) and model the model it named, for a cost cap
+98
View File
@@ -0,0 +1,98 @@
package gateway
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/gwbudget"
)
// The budget point with plugins/budget on and off, for a key held to a
// limit beside one that isn't. On, the limited key is let in while it has
// something left and refused with a 429 after. Off, the limited key is
// refused with a 503 and nothing is sent, in the chat API and the search
// MCP server alike (the vision one: TestVisionMCPHeldToKeyLimit), and the
// refusal is recorded; the key
// with no limit and a keyless request from this computer go on as before.
// A refresh that turns the plugin on lets the limited key's next request
// in at once.
func TestKeyLimitsOnAndOff(t *testing.T) {
fresh(t)
budget.Forget()
pinLimitClock(t)
calls := limitedUpstream(t, 0)
keys, secrets := newCaller(t, "Capped", "Free")
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 700})
s := New()
h := s.Handler()
call := func(secret string) *httptest.ResponseRecorder {
t.Helper()
r := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(chatReq))
if secret != "" {
r.Header.Set("Authorization", "Bearer "+secret)
} else {
r.RemoteAddr = "127.0.0.1:5000"
}
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
capped := access.Identity{KeyID: keys[0].ID, KeyName: "Capped", Limit: &access.Limit{Period: "day", Tokens: 700}}
mcp := func() error {
r := httptest.NewRequest("POST", SearchMCPPath, nil).WithContext(access.WithIdentity(t.Context(), capped))
_, err := s.searchMCPRun(r, "latest go")
return err
}
// on
if w := call(secrets[0]); w.Code != 200 {
t.Fatal("on: within the limit", w.Code, w.Body.String())
}
if w := call(secrets[0]); w.Code != 200 {
t.Fatal("on: within the limit", w.Code, w.Body.String())
}
if w := call(secrets[0]); w.Code != http.StatusTooManyRequests {
t.Fatal("on: a spent key let in", w.Code, w.Body.String())
}
if calls.Load() != 2 {
t.Fatalf("on: %d calls reached the provider", calls.Load())
}
// off
withoutLimits(t)
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 100000})
w := call(secrets[0])
if w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "Key limits plugin") || w.Header().Get("X-Should-Retry") != "false" {
t.Fatal("off: a limited key's request", w.Code, w.Body.String(), w.Header())
}
if calls.Load() != 2 {
t.Fatal("off: a limited key's request reached the provider")
}
if rec := lastUsage(t); !rec.Rejected || rec.CallerKeyID != keys[0].ID || rec.ErrType != "gateway_key_limit_off" || rec.Status != 503 {
t.Fatalf("off: refusal recorded as %+v", rec)
}
if err := mcp(); err == nil || !strings.Contains(err.Error(), "Key limits plugin") {
t.Errorf("off: the search MCP server said %v, not that the plugin is off", err)
}
if w := call(secrets[1]); w.Code != 200 {
t.Fatal("off: a key with no limit refused", w.Code, w.Body.String())
}
if w := call(""); w.Code != 200 {
t.Fatal("off: a keyless loopback request refused", w.Code, w.Body.String())
}
// the gateway's refresh turns it on for the request that needs it
var on func()
stop := gwbudget.Refresh(func() { on = gwbudget.Limit(budget.Limiter{}) })
defer stop()
gwbudget.ForgetRefreshForTest()
before := calls.Load()
if w := call(secrets[0]); w.Code != 200 || on == nil || calls.Load() != before+1 {
t.Fatal("a refresh that turned the plugin on still refused", w.Code, w.Body.String())
}
on()
}
+11 -1
View File
@@ -29,7 +29,9 @@ import (
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/awake"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/plugin"
@@ -500,9 +502,17 @@ func (s *Server) ListenAndServe(ctx context.Context) error {
}
})
defer stopMasking()
// as does a request of a gateway key held to a limit for plugins/budget
// (gwbudget.Limiting)
stopLimits := gwbudget.Refresh(func() {
if _, err := pluginrt.Refresh(); err != nil {
log.Printf("plugins: %v", err)
}
})
defer stopLimits()
freshCtx, stopFresh := context.WithCancel(ctx)
defer stopFresh()
go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path(), plugin.ListPath())
go pluginrt.KeepFresh(freshCtx, 2*time.Second, settings.Path(), provider.Path(), plugin.ListPath(), access.Path())
srv := &http.Server{Handler: lanGuard(s.Handler()), ReadHeaderTimeout: 30 * time.Second, IdleTimeout: 5 * time.Minute}
// the magpie serving the gateway, and only it, keeps the saved accounts
// signed in, so two never refresh one sign-in at once
+36 -10
View File
@@ -2,6 +2,7 @@ package gateway
import (
"bytes"
"errors"
"io"
"net/http"
"slices"
@@ -11,6 +12,7 @@ import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/usage"
)
@@ -28,7 +30,8 @@ const remoteKeyLimitHeader = "X-Magpie-Limit-Reset"
// keyLimited holds a gateway key's requests to its limit (#585, see
// package budget for the rules): one that would go over is refused with a
// 429 before any provider is asked, saying the key, the limit and when it
// resets; one let in holds a reservation until it ends. Reads, the
// resets; one let in holds a reservation until it ends. A key with a limit
// while plugins/budget is off is refused with a 503, and nothing is sent. Reads, the
// bridge's tool callbacks and counting tokens cost nothing and pass.
func keyLimited(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -51,17 +54,21 @@ func keyLimited(next http.Handler) http.Handler {
size, model = int64(len(b)), budget.ModelOf(b)
}
now := limitClock()
release, refused := budget.Reserve(who, size, model, now)
if refused != nil {
msg := refused.Error()
w.Header().Set("Retry-After", strconv.Itoa(refused.RetryAfter(now)))
// the Anthropic and OpenAI SDKs would otherwise retry a 429
release, err := reserveFor(who, size, model, now)
if err != nil {
status, errType := http.StatusServiceUnavailable, "gateway_key_limit_off"
var refused gwbudget.Refusal
if errors.As(err, &refused) {
status, errType = http.StatusTooManyRequests, "gateway_key_limit"
w.Header().Set("Retry-After", strconv.Itoa(refused.RetryAfter(now)))
w.Header().Set(remoteKeyLimitHeader, refused.ResetAt().Format(time.RFC3339))
}
// the Anthropic and OpenAI SDKs would otherwise retry a 429 or 503
w.Header().Set("X-Should-Retry", "false")
w.Header().Set(remoteKeyLimitHeader, refused.Reset.Format(time.RFC3339))
writeError(w, protoOfPath(r.URL.Path), http.StatusTooManyRequests, msg)
writeError(w, protoOfPath(r.URL.Path), status, err.Error())
c := callerOf(r)
appendUsage(r, usage.Record{Time: now, Agent: c.agent, Via: c.via, Requested: model, Status: http.StatusTooManyRequests, Rejected: true,
Error: msg, ErrType: "gateway_key_limit", Endpoint: r.URL.Path, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header)})
appendUsage(r, usage.Record{Time: now, Agent: c.agent, Via: c.via, Requested: model, Status: status, Rejected: true,
Error: err.Error(), ErrType: errType, Endpoint: r.URL.Path, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header)})
return
}
defer release()
@@ -69,6 +76,25 @@ func keyLimited(next http.Handler) http.Handler {
})
}
// reserveFor holds a request of who's to its key's limits through the
// gateway's budget point (gwbudget): its release, or why it isn't let in,
// a gwbudget.Refusal or, for a key held to a limit while no limiter serves
// it, gwbudget.ErrUnlimited. A request without a limit is let in as it is.
func reserveFor(who access.Identity, size int64, model string, now time.Time) (release func(), err error) {
l, err := gwbudget.Limiting(who)
if err != nil {
return nil, err
}
if l == nil {
return func() {}, nil
}
release, refused := l.Reserve(who, size, model, now)
if refused != nil {
return nil, refused
}
return release, nil
}
// protoOfPath is the API a path is of, for an error said its way.
func protoOfPath(path string) provider.Protocol {
switch {
+14
View File
@@ -8,6 +8,8 @@ import (
"testing"
"github.com/yetone/magpie/internal/agentenv"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/gwtool"
"github.com/yetone/magpie/internal/masking"
@@ -26,6 +28,7 @@ func TestMain(m *testing.M) {
groupsServed = provider.ServeGroups()
serveMiddleware()
searchOn = gwtool.Serve(gwtool.WebSearch)
limitsOn = gwbudget.Limit(budget.Limiter{})
code, err := isolatedTests(m)
if err != nil {
fmt.Fprintln(os.Stderr, err)
@@ -185,6 +188,17 @@ func withoutGroups(t *testing.T) {
// magpie's web search, as a user with it on has.
var searchOn func()
// limitsOn is plugins/budget on: the gateway's tests hold gateway keys to
// their limits, as a user with it on has.
var limitsOn func()
// withoutLimits is plugins/budget off for t, with no refresh to turn it
// on: a key held to a limit is refused with nothing sent.
func withoutLimits(t *testing.T) {
limitsOn()
t.Cleanup(func() { limitsOn = gwbudget.Limit(budget.Limiter{}) })
}
// withoutSearch is plugins/search off for t, in a process serving the
// gateway (gwtool.Gate): magpie's web search is neither offered nor
// answered.
+4 -5
View File
@@ -12,7 +12,6 @@ import (
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
)
// magpie's web search, the one a model that can't search is given
@@ -23,7 +22,7 @@ import (
// POST. It is a gateway route like the others: this computer calls it with
// any key, another one only while magpie is shared and with an enabled
// gateway key (lanGuard), a gateway key's limit holds each search
// (budget.Reserve), and a web page is turned away, as the MCP spec has a
// (reserveFor), and a web page is turned away, as the MCP spec has a
// server check Origin.
// SearchMCPPath is where the web search MCP server is served. It has two
@@ -185,9 +184,9 @@ func (s *Server) searchMCPRun(r *http.Request, query string) (string, error) {
if query == "" {
return "", searchMCPError("web_search needs a query")
}
release, refused := budget.Reserve(access.Caller(r.Context()), int64(len(query)), "", limitClock())
if refused != nil {
return "", refused
release, err := reserveFor(access.Caller(r.Context()), int64(len(query)), "", limitClock())
if err != nil {
return "", err
}
defer release()
ctx := context.WithValue(r.Context(), searchForKey{}, &CallFor{Agent: callerOf(r).agent, MCP: true})
+4 -5
View File
@@ -13,7 +13,6 @@ import (
"strings"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/provider"
)
@@ -23,7 +22,7 @@ import (
// (JonahFu on X), so an agent on a model that can't see, or any agent at
// all, can mount it as an analyze_image tool: Streamable HTTP at
// VisionMCPPath, served and guarded as SearchMCPPath is (serveMCP), a
// gateway key's limit holding each look (budget.Reserve).
// gateway key's limit holding each look (reserveFor).
// VisionMCPPath is where the image recognition MCP server is served.
const VisionMCPPath = "/mcp/magpie/vision"
@@ -124,9 +123,9 @@ func (s *Server) visionMCPRun(r *http.Request, image, prompt string) (string, er
}
return "", searchMCPError("magpie has no model that sees images: add a provider with one, or pick one in Settings → Models → Image recognition")
}
release, refused := budget.Reserve(access.Caller(r.Context()), int64(len(src)+len(prompt)), "", limitClock())
if refused != nil {
return "", refused
release, err := reserveFor(access.Caller(r.Context()), int64(len(src)+len(prompt)), "", limitClock())
if err != nil {
return "", err
}
defer release()
ctx := context.WithValue(r.Context(), describeForKey{}, describeFor{call: &CallFor{Agent: callerOf(r).agent, Missing: VisionMissing(), MCP: true}})
+12
View File
@@ -203,4 +203,16 @@ func TestVisionMCPHeldToKeyLimit(t *testing.T) {
if m := readMCP(t, visionPost(h, "127.0.0.1:5000", analyzeCall("data:image/png;base64,aGVsbG8=", ""))); m.Result.IsError {
t.Fatalf("keyless: %+v", m)
}
// plugins/budget off: a key held to a limit looks at nothing, however
// much it has left
withoutLimits(t)
setLimit(t, keys[0].ID, &access.Limit{Period: "day", Tokens: 100000})
looked := len(u.sent("eye"))
m = readMCP(t, visionPost(h, "127.0.0.1:5000", analyzeCall("data:image/png;base64,aGVsbG8=", ""), "Authorization", "Bearer "+secrets[0]))
if !m.Result.IsError || !strings.Contains(m.Result.Content[0].Text, "Key limits plugin") {
t.Fatalf("off: %+v", m)
}
if n := len(u.sent("eye")); n != looked {
t.Fatalf("off: a limited key's image was looked at")
}
}
+16
View File
@@ -773,6 +773,10 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "不能联网搜索的模型,借能搜索的提供商或搜索 API 来搜",
"1 search source set up": "已设置 1 个搜索来源",
"{n} search sources set up": "已设置 {n} 个搜索来源",
"Key limits": "密钥限额",
"Hold each gateway key to the tokens or estimated cost you set for it": "让每个网关密钥只用到你为它设的 Token 数或估算费用",
"1 key with a limit": "1 个密钥设了限额",
"{n} keys with a limit": "{n} 个密钥设了限额",
"In use, so it stays on": "正在使用,因此保持开启",
"Gateway page": "网关页面",
"The gateway's state and keys, how to connect a client, its models and recent calls": "网关的状态与密钥、客户端如何连接、它的模型和最近的调用",
@@ -4352,6 +4356,10 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "不能聯網搜尋的模型,借能搜尋的提供商或搜尋 API 來搜",
"1 search source set up": "已設定 1 個搜尋來源",
"{n} search sources set up": "已設定 {n} 個搜尋來源",
"Key limits": "密鑰限額",
"Hold each gateway key to the tokens or estimated cost you set for it": "讓每個閘道密鑰只用到你為它設的 Token 數或估算費用",
"1 key with a limit": "1 個密鑰設了限額",
"{n} keys with a limit": "{n} 個密鑰設了限額",
"In use, so it stays on": "正在使用,因此保持開啟",
"Gateway page": "閘道頁面",
"The gateway's state and keys, how to connect a client, its models and recent calls": "閘道的狀態與金鑰、用戶端如何連線、它的模型和最近的呼叫",
@@ -7903,6 +7911,10 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "ウェブ検索できないモデルは、検索できるプロバイダーか検索 API で検索します",
"1 search source set up": "1 個の検索元を設定済み",
"{n} search sources set up": "{n} 個の検索元を設定済み",
"Key limits": "キーの上限",
"Hold each gateway key to the tokens or estimated cost you set for it": "各ゲートウェイキーを、設定したトークン数か推定費用までに抑えます",
"1 key with a limit": "上限のあるキー 1 個",
"{n} keys with a limit": "上限のあるキー {n} 個",
"In use, so it stays on": "使用中のためオンのままです",
"Gateway page": "ゲートウェイページ",
"The gateway's state and keys, how to connect a client, its models and recent calls": "ゲートウェイの状態とキー、クライアントの接続方法、モデルと最近の呼び出し",
@@ -11468,6 +11480,10 @@ const I18N = {
"Models that can't search the web search with a provider that can, or a search API": "Modelle, die nicht im Web suchen können, suchen über einen Anbieter, der es kann, oder eine Such-API",
"1 search source set up": "1 Suchquelle eingerichtet",
"{n} search sources set up": "{n} Suchquellen eingerichtet",
"Key limits": "Schlüssel-Limits",
"Hold each gateway key to the tokens or estimated cost you set for it": "Jeden Gateway-Schlüssel auf die Tokens oder geschätzten Kosten begrenzen, die du für ihn festlegst",
"1 key with a limit": "1 Schlüssel mit Limit",
"{n} keys with a limit": "{n} Schlüssel mit Limit",
"In use, so it stays on": "In Gebrauch, daher bleibt es an",
"Gateway page": "Gateway-Seite",
"The gateway's state and keys, how to connect a client, its models and recent calls": "Zustand und Schlüssel des Gateways, wie sich ein Client verbindet, seine Modelle und letzten Aufrufe",
+4 -4
View File
@@ -44,14 +44,14 @@ func TestBuiltinSwitch(t *testing.T) {
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
t.Fatal(err)
}
if len(out) != 12 {
if len(out) != 13 {
t.Fatalf("the built-ins: %+v", out)
}
for _, b := range out {
// the Gateway, Routing and Usage pages, the routing strategies,
// the gateway middleware, privacy masking and web search are
// essential: on in every preset
if b.On != (b.ID == "library" || b.ID == "gateway" || b.ID == "middleware" || b.ID == "redact" || b.ID == "rotation" || b.ID == "routing" || b.ID == "search" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) {
// the gateway middleware, privacy masking, web search and key
// limits are essential: on in every preset
if b.On != (b.ID == "budget" || b.ID == "library" || b.ID == "gateway" || b.ID == "middleware" || b.ID == "redact" || b.ID == "rotation" || b.ID == "routing" || b.ID == "search" || b.ID == "usage") || b.On != (b.State == pluginrt.Active) {
t.Fatalf("after library on: %+v", out)
}
}
+19 -13
View File
@@ -19,6 +19,7 @@ const assets = path.resolve(__dirname, "../assets");
// as plugins/*'s manifests say them, in pluginrt.Registered's order (by id)
const PLUGINS = [
{ id: "budget", name: "Key limits", sub: "Hold each gateway key to the tokens or estimated cost you set for it", one: "1 key with a limit", many: "{n} keys with a limit" },
{ id: "gateway", name: "Gateway page", sub: "The gateway's state and keys, how to connect a client, its models and recent calls", one: "1 gateway key", many: "{n} gateway keys" },
{ id: "groups", name: "Routing groups", sub: "Several models agents pick as one: each request goes to the right one, and to the next when one fails", one: "1 group in use", many: "{n} groups in use" },
{ id: "library", name: "Library", sub: "Instructions, MCP servers, skills and hooks, kept once and given to every agent", one: "1 item given to agents", many: "{n} items given to agents" },
@@ -34,9 +35,9 @@ const PLUGINS = [
];
// a new install's (the Essentials preset): all off but the Gateway, Routing
// and Usage pages, the routing strategies, the gateway middleware, privacy
// masking and web search, which are essential, and two routing groups the
// user made
const START = { gateway: [true, 0], groups: [false, 2], library: [false, 0], middleware: [true, 0], otel: [false, 0], redact: [true, 0], rotation: [true, 0], routing: [true, 0], search: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] };
// masking, web search and key limits, which are essential, and two routing
// groups the user made
const START = { budget: [true, 0], gateway: [true, 0], groups: [false, 2], library: [false, 0], middleware: [true, 0], otel: [false, 0], redact: [true, 0], rotation: [true, 0], routing: [true, 0], search: [true, 0], sessions: [false, 0], usage: [true, 0], warmups: [false, 0] };
// the Gateway page's settings, as pluginrt.SchemaOf makes them
const GATEWAY_SCHEMA = {
@@ -170,13 +171,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
assert.deepEqual([rt.on, rt.disabled], ["true", false], `${where}: the Routing page, on`);
const ro = rows.find((r) => r.id === "rotation");
assert.deepEqual([ro.on, ro.disabled], ["true", false], `${where}: the routing strategies, on`);
for (const id of ["middleware", "redact", "search"]) {
for (const id of ["budget", "middleware", "redact", "search"]) {
const r = rows.find((r) => r.id === id);
assert.deepEqual([r.on, r.disabled], ["true", false], `${where}: ${id}, on`);
}
const us = rows.find((r) => r.id === "usage");
assert.deepEqual([us.on, us.disabled], ["true", false], `${where}: the Usage page, on`);
for (const r of rows.filter((r) => !["groups", "gateway", "middleware", "redact", "rotation", "routing", "search", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
for (const r of rows.filter((r) => !["budget", "groups", "gateway", "middleware", "redact", "rotation", "routing", "search", "usage"].includes(r.id))) assert.deepEqual([r.on, r.disabled, r.why], ["false", false, ""], `${where}: ${r.id}`);
await page.locator('#builtinList [data-id="groups"] [role="switch"]').click({ force: true });
await page.waitForTimeout(100);
assert.deepEqual(posts, [], `${where}: a locked switch posts nothing`);
@@ -208,20 +209,25 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
await page.locator('#builtinList [data-id="otel"] [role="switch"]').click();
await page.waitForSelector('#builtinList [data-id="otel"] [aria-checked="true"]');
assert.ok(await page.locator("#setTab-otel").evaluate((b) => getComputedStyle(b).display !== "none"), `${where}: Observability back`);
// Routing switched off: its tab and the panel's go, the page stays
// Routing switched off: its tab and the panel's go, the page stays.
// Its row and Usage's can be below the fold: the reader scrolls to
// them with the wheel, since the page puts back a scroll that isn't
// the reader's (scrollOnPurpose), a click's own too
const wheelTo = async (id) => {
const list = await page.locator("#builtinList").boundingBox();
await page.mouse.move(list.x + 20, list.y + 20);
await page.mouse.wheel(0, 400);
await page.waitForFunction((id) => { const r = document.querySelector(`#builtinList [data-id="${id}"] [role="switch"]`).getBoundingClientRect(), foot = document.querySelector("footer.foot"); return r.bottom <= Math.min(document.getElementById("view-plugins").getBoundingClientRect().bottom, foot && foot.offsetParent ? foot.getBoundingClientRect().top : Infinity); }, id);
};
await wheelTo("routing");
await page.locator('#builtinList [data-id="routing"] [role="switch"]').click();
await page.waitForSelector('#builtinList [data-id="routing"] [aria-checked="false"]');
assert.deepEqual(posts.at(-1), ["routing", false], where);
if (width >= 800) assert.deepEqual(await tabs(page), ["agents", "library", ...KEPT.slice(1).filter((k) => k !== "routing")], `${where}: Routing gone`);
assert.deepEqual(await viewShown(page), ["view-plugins"], `${where}: Plugins stays`);
// and Usage: its tab goes. Its row can be below the fold: the reader
// scrolls to it with the wheel, since the page puts back a scroll
// that isn't the reader's (scrollOnPurpose), a click's own too
// and Usage: its tab goes
const usageSwitch = page.locator('#builtinList [data-id="usage"] [role="switch"]');
const list = await page.locator("#builtinList").boundingBox();
await page.mouse.move(list.x + 20, list.y + 20);
await page.mouse.wheel(0, 400);
await page.waitForFunction(() => { const r = document.querySelector('#builtinList [data-id="usage"] [role="switch"]').getBoundingClientRect(); return r.bottom <= document.getElementById("view-plugins").getBoundingClientRect().bottom; });
await wheelTo("usage");
await usageSwitch.click();
await page.waitForSelector('#builtinList [data-id="usage"] [aria-checked="false"]');
assert.deepEqual(posts.at(-1), ["usage", false], where);
+124
View File
@@ -0,0 +1,124 @@
// Package gwbudget is the gateway's budget point (P3 of
// docs/subsystems/plugin-runtime.md): what holds a gateway key to the
// limits its owner set (#585). The gateway asks it before a key's request
// goes to any provider; plugins/budget serves internal/budget's limiter
// while it is on.
//
// It fails closed: a request of a key held to a limit is not sent while
// no limiter serves it (ErrUnlimited). A request without a key, or of a
// key with no limit, never asks it.
package gwbudget
import (
"errors"
"sync"
"sync/atomic"
"time"
"github.com/yetone/magpie/internal/access"
)
// Refusal is why a key's request was turned away, as the client is told.
type Refusal interface {
error
// RetryAfter is how long until the limit resets, in whole seconds.
RetryAfter(now time.Time) int
// ResetAt is when it resets.
ResetAt() time.Time
}
// Limiter lets a key's request in, holding what it is expected to use
// until release, or refuses it. body is the request's size in bytes (-1
// unknown) and model the model it named.
type Limiter interface {
Reserve(who access.Identity, body int64, model string, now time.Time) (release func(), refused Refusal)
}
var (
mu sync.Mutex
limiters []*Limiter
refresh func()
asking atomic.Bool
lastAsk atomic.Int64 // when the last refresh began, UnixNano
)
// Limit serves l until remove. Registering one while another is served
// stacks: the last serves until it is removed.
func Limit(l Limiter) (remove func()) {
e := &l
mu.Lock()
limiters = append(limiters, e)
mu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
mu.Lock()
defer mu.Unlock()
for i, x := range limiters {
if x == e {
limiters = append(limiters[:i:i], limiters[i+1:]...)
break
}
}
})
}
}
// Refresh sets what the gateway asks when a key held to a limit comes and
// no limiter is served: pluginrt's refresh, which turns the plugin on when
// a key has a limit. stop takes it away.
func Refresh(f func()) (stop func()) {
mu.Lock()
refresh = f
mu.Unlock()
var once sync.Once
return func() {
once.Do(func() {
mu.Lock()
refresh = nil
mu.Unlock()
})
}
}
func served() (Limiter, func()) {
mu.Lock()
defer mu.Unlock()
if n := len(limiters); n > 0 {
return *limiters[n-1], nil
}
return nil, refresh
}
// ForgetRefreshForTest lets the next Limiting refresh at once, as it
// would a second after the last one.
func ForgetRefreshForTest() { lastAsk.Store(0) }
// ErrUnlimited is the error a key's request gets when the key is held to
// a limit and nothing can hold it.
var ErrUnlimited = errors.New("this gateway key is held to a limit, but magpie's Key limits plugin isn't serving it, so nothing was sent; turn the plugin on in magpie's Settings → Plugins")
// Limiting is the limiter for who's request: nil, nil when who has no
// limit; ErrUnlimited when it has one and none serves. With none, one
// refresh is asked first (at most once a second, never from inside one),
// so a limit set a moment ago turns the plugin on for the request that
// needs it. Fail closed.
func Limiting(who access.Identity) (Limiter, error) {
if who.KeyID == "" || len(who.Limits()) == 0 {
return nil, nil
}
l, f := served()
if l == nil && f != nil {
now := time.Now().UnixNano()
if now-lastAsk.Load() >= int64(time.Second) && asking.CompareAndSwap(false, true) {
lastAsk.Store(now)
f()
asking.Store(false)
}
l, _ = served()
}
if l == nil {
return nil, ErrUnlimited
}
return l, nil
}
+1
View File
@@ -3,6 +3,7 @@
package all
import (
_ "github.com/yetone/magpie/plugins/budget"
_ "github.com/yetone/magpie/plugins/gateway"
_ "github.com/yetone/magpie/plugins/groups"
_ "github.com/yetone/magpie/plugins/library"
+47
View File
@@ -0,0 +1,47 @@
// Package budget holds each gateway key to the limits its owner set
// (#585): the tokens or estimated cost it may use in a window. While a key
// has a limit, it stays on.
//
// It is the limiter of the gateway's budget point (P3 of
// docs/subsystems/plugin-runtime.md): Apply serves internal/budget's, and
// the point fails closed: a request of a key held to a limit is not sent
// while no limiter serves it. What a key has used is the core's, read
// from the usage records, so the Settings page, `magpie keys` and
// /v1/magpie/limit tell it either way.
package budget
import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/budget"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/pluginrt"
)
func init() {
pluginrt.Register(pluginrt.Manifest{
ID: "budget", API: "^1", Requires: []string{"settings", "gateway"}, Essential: true,
Name: "Key limits", Sub: "Hold each gateway key to the tokens or estimated cost you set for it",
One: "1 key with a limit", Many: "{n} keys with a limit",
InUse: InUse,
Apply: func(c *pluginrt.Ctx) error {
c.OnDispose(gwbudget.Limit(budget.Limiter{}))
return nil
},
})
}
// InUse counts the gateway keys held to a limit; caller-keys.json that
// can't be read is not known, so it stays on.
func InUse() (int, error) {
keys, err := access.List()
if err != nil {
return 0, err
}
n := 0
for _, k := range keys {
if len(k.Limits()) > 0 {
n++
}
}
return n, nil
}
+97
View File
@@ -0,0 +1,97 @@
package budget
import (
"errors"
"os"
"path/filepath"
"testing"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwbudget"
"github.com/yetone/magpie/internal/pluginrt"
"github.com/yetone/magpie/internal/testenv"
)
func TestMain(m *testing.M) { testenv.Main(m) }
func manifest(t *testing.T) pluginrt.Manifest {
t.Helper()
for _, m := range pluginrt.Registered() {
if m.ID == "budget" {
return m
}
}
t.Fatal("budget not registered")
return pluginrt.Manifest{}
}
func sandbox(t *testing.T) {
t.Helper()
home := t.TempDir()
t.Setenv("HOME", home)
t.Setenv("USERPROFILE", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, "config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, "cache"))
}
// On serves the limiter, off doesn't, and a key held to a limit is then
// refused rather than let in unlimited; on again serves it.
func TestOnServesOffDoesNot(t *testing.T) {
sandbox(t)
who := access.Identity{KeyID: "k1", KeyName: "Capped", Limit: &access.Limit{Period: "day", Tokens: 100}}
rt := pluginrt.New([]pluginrt.Manifest{manifest(t)})
defer rt.Stop()
limited := func(want bool) {
t.Helper()
l, err := gwbudget.Limiting(who)
if want && (l == nil || err != nil) {
t.Fatalf("on: limiter %v, %v (%+v)", l, err, rt.Statuses())
}
if !want && (l != nil || !errors.Is(err, gwbudget.ErrUnlimited)) {
t.Fatalf("off: limiter %v, %v, not refused (%+v)", l, err, rt.Statuses())
}
}
limited(false)
rt.Reconcile(map[string]bool{"budget": true}, nil)
limited(true)
rt.Reconcile(map[string]bool{"budget": false}, nil)
limited(false)
rt.Reconcile(map[string]bool{"budget": true}, nil)
limited(true)
if l, err := gwbudget.Limiting(access.Identity{KeyID: "k2", KeyName: "Free"}); l != nil || err != nil {
t.Errorf("a key with no limit asked the limiter: %v, %v", l, err)
}
}
// In use while a key has a limit; a key without one doesn't count, and
// caller-keys.json that can't be read is an error, so it stays on.
func TestInUse(t *testing.T) {
sandbox(t)
count := func(want int) {
t.Helper()
if n, err := InUse(); err != nil || n != want {
t.Fatalf("InUse = %d, %v; want %d", n, err, want)
}
}
count(0)
for _, name := range []string{"Capped", "Free"} {
if _, err := access.Update("add-key", access.Change{Name: name}); err != nil {
t.Fatal(err)
}
}
count(0)
keys, err := access.List()
if err != nil {
t.Fatal(err)
}
if _, err := access.Update("limit-key", access.Change{Key: keys[0].ID, Limit: &access.Limit{Period: "day", Tokens: 700}}); err != nil {
t.Fatal(err)
}
count(1)
if err := os.WriteFile(access.Path(), []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
if _, err := InUse(); err == nil {
t.Error("an unreadable caller-keys.json counted as known")
}
}