gateway: a held key its owner lets see quotas is told those of the providers and accounts it may use, not none (#2216, Kenoia)
#1981 refused every quota route to a gateway key held to a budget, models
or accounts, so a Remote magpie set up with such a key showed none of the
providers it may use. A key's owner can now let it be told them:
access.Key.Quotas, set from the key's new "Quotas" badge on the Gateway
page or `magpie gateway-key quotas <id> on|off`. Off stays the default,
so #1981's answer is unchanged for every key until its owner says so.
With it on, /v1/magpie/quotas (and ?kept=1), /quotas/history,
/quotas/cards and POST /quotas/refresh go through scopeQuotas
(internal/gateway/quotas_scope.go):
- a provider is told only when the key may use every model the catalog
lists of it: a key with some of a provider's models is told nothing of
it, since the models it may not use spend the same quota;
- of those, only cards of accounts and keys AllowsAccount lets it use,
matched by the card's User against AccountIDs (a name two accounts
share needs both; a card no account is known by only where the key's
list names none of that provider's); a provider's only key's card,
named by no one, is that key's;
- cards read from another magpie (From) are never told;
- a refresh of a card outside the scope is 403 gateway_key_held, one
naming no card reads again only the scope's cards, not ReadAllCards;
- a scope with no card answers the cards routes 403 gateway_key_held, so
the remote shows the key's own card rather than "nothing read".
/v1/magpie/concurrency and /v1/magpie/usage still refuse a held key.
Run at the reviewed head:
- gofmt -l: clean; go vet ./... (darwin), GOOS=linux -tags nogui,
GOOS=windows: clean.
- go test -tags nogui -timeout 45m ./... in a sandbox HOME, after the
rebase onto 7be68467f (#2227's several limits; conflicts in access,
the CLI usage and test, keys.js and providers-accounts.md resolved by
keeping both): every package ok but internal/gateway, whose
TestTranslatedSilenceStillTimesOut went red once at load ~95 (its
400ms deadline also covers the response headers; filed #2248) and
passed 5 of 5 alone. Before the rebase the whole suite was ok, with
agent and gateway rerun at -timeout 40m after the 10m timeout under
load.
- TestHeldKeyToldItsOwnQuotas (new): a provider-wide key sees A only,
a key with A/m1 sees nothing of A, an account-held key sees only its
key's card, a provider's only key, a key told nothing gets 403 from
the cards route, Quotas-off still 403 everywhere, refreshes outside
the scope 403. Broken by hand, each red: scope returned nil (every
card told), every[id] forced true (partial models), the account check
skipped, the refresh check removed, the only-key rule removed, and the
told-none 403 removed. TestHeldKeyToldNoAccounts (#1981) still green.
- TestRemoteMagpieShowsHeldKeyItsQuotas (new): a magpie with this one as
its Remote magpie provider, through a key held to alpha's Two, shows
office/alpha's Two card beside the key's own; a key told none shows its
own card alone. Red with the told-none 403 removed ("nothing read on
that magpie yet").
- TestGatewayKeyQuotasCLI (new): show, on, off, bad values refused.
- GUI: gateway-key-quotas.test.cjs (new) in chromium and webkit, at 1100
and 420, in en, zh, zh-TW, ja, de: 20/20; red when the badge sends the
value it already has.
- The badge is a gateway key row's: off, it folds to no width until the
row is hovered (the row had no room left at 390px: gateway-connect-keys
went red in en until it did), and on a phone it is shown like the
row's other controls (phone-rows went red until its rule won).
- GUI, 119 files matching gateway|key|usage|quota|remote|i18n|caller|
web-|phone|narrow, both engines, concurrency 2: 1349/1385. The reds
besides phone-rows (since fixed, above): quota-count-wrap and
quota-name-translated webkit (#2228), usage-agents-hide (#2211) and
usage-fold chromium en/zh (#2163), each red alike on a fresh
origin/main. gateway-key-quotas, gateway-connect-keys, phone-rows and
gateway-key-groups rerun: 38/38; after the rebase every gateway-*,
phone-rows and key-limit file, both engines: 210/210.
Not tried: a real Remote magpie against a second machine with a held key;
the GUI badge in the Linux and Windows apps.
This commit is contained in:
+3
-2
@@ -71,8 +71,9 @@ user's subscription allowances, and `GET /v1/magpie/usage` and
|
||||
(with `session`, and `subagent`/`parent_agent` for a Claude Code
|
||||
subagent's call). They answer only this machine, or another with a gateway
|
||||
key; a key held to a budget, models or accounts sees its own calls and
|
||||
routes alone, and is refused the quotas (its own limit is
|
||||
`GET /v1/magpie/limit`).
|
||||
routes alone, and is refused the quotas unless its owner lets it see
|
||||
those of what it may use (`magpie gateway-key quotas <id> on`, #2216;
|
||||
its own limit is `GET /v1/magpie/limit`).
|
||||
Calls your app makes to its vendor itself can be reported with `POST
|
||||
/v1/magpie/usage/requests` (one record or up to 5000 a post, in
|
||||
`usage.jsonl`'s shape, each with a `rid`; past times are kept, so a
|
||||
|
||||
@@ -514,6 +514,7 @@ magpie gateway-key models <id> openai/gpt-5 anthropic/* # only these models
|
||||
magpie gateway-key models <id> all # every model
|
||||
magpie gateway-key accounts <id> codex/me@example.com # only these accounts
|
||||
magpie gateway-key accounts <id> all # every account
|
||||
magpie gateway-key quotas <id> on # told the quotas of what it may use
|
||||
```
|
||||
|
||||
Each gateway key can have its own **limit**: a token total, an estimated
|
||||
@@ -1738,6 +1739,21 @@ none of this magpie's accounts (#1981): `/v1/magpie/quotas`,
|
||||
reads its own limit from `GET /v1/magpie/limit`. Another magpie that uses
|
||||
such a key shows only that key's own card.
|
||||
|
||||
Its owner can let such a key be told the quotas of what it may use
|
||||
(#2216): the **Quotas** badge on the key's row (on hover; it reads
|
||||
*Quotas shown* while on), or `magpie gateway-key quotas <id> on` (`off`
|
||||
again, or no argument to see which). The four quota routes then tell it
|
||||
the cards of the providers whose every model it may use — a key held to
|
||||
some of a provider's models is told nothing of that provider, since the
|
||||
models it may not use spend the same quota — and of those only the
|
||||
accounts and keys it may use, account names and balances included. A
|
||||
card it isn't told is refused a refresh (403 `gateway_key_held`), and a
|
||||
refresh that names none reads again only the cards it is told. A key
|
||||
told none of the cards is answered `/v1/magpie/quotas/cards` 403
|
||||
`gateway_key_held` as before, so another magpie shows its own card, not
|
||||
that nothing was read. `/v1/magpie/concurrency` and `/v1/magpie/usage`
|
||||
still refuse it.
|
||||
|
||||
An app of your own can read the Usage page's numbers too.
|
||||
`GET /v1/magpie/usage?period=<today|week|month|all>` is the page's summary,
|
||||
the same JSON as the window's `/api/usage` (`path` is left out for another
|
||||
|
||||
@@ -242,6 +242,18 @@ own. `Route.callerKey` is set by `trace.beginFor` from the request's
|
||||
caller, so a route begun without it is told to no held key.
|
||||
`TestHeldKeyToldNoAccounts` covers every one of these from loopback and
|
||||
the LAN, for a key held each of the three ways and one held to nothing.
|
||||
A held key whose owner set `access.Key.Quotas` (#2216) is told the four
|
||||
quota routes through `scopeQuotas` (`quotas_scope.go`) instead: cards of
|
||||
providers whose every catalog model `modelAllowed` lets it use, and of
|
||||
those only accounts `AllowsAccount` lets it use, matched by the card's
|
||||
`User` against `AccountIDs` (a name two accounts share must be allowed
|
||||
both; a card no account is known by, only where the list names none of
|
||||
the provider's). Remote cards (`From`) are never told. A refresh of a
|
||||
card outside the scope is refused, one naming none reads the scope's
|
||||
cards only, and a scope with no card answers the cards routes as held.
|
||||
`TestHeldKeyToldItsOwnQuotas` covers each route for a provider-wide key,
|
||||
a key with some of a provider's models, an account-held key, a provider's
|
||||
only key, and a key told nothing, each red when its check is removed.
|
||||
|
||||
### Calls read from the agents' own files
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Used-up switch | When the account Codex or Claude Code is signed in to has used its allowance, the agent is signed in to the next account that is on and has room (#208). For Codex, *Only switch Codex's sign-in* (`SwitchOnly`, `SetSwitchOnly`) keeps magpie's `openai_base_url` failover out of Codex's config, so the switch is all magpie does (#1907); an unreadable providers.json reads as switch-only, so the failover is not written on a guess. | [`codex_switch.go`](../../internal/provider/codex_switch.go) |
|
||||
| Claude Code's proxy | Claude Code on its own subscription asks Anthropic itself, through the proxy its env names. While any Claude account has a proxy of its own (`AccountProxies`), the `env` of Claude Code's `settings.json` names the proxy of the account it is signed in to (#1807): `HTTPS_PROXY` and `HTTP_PROXY` set to that account's own, else the subscription's `Proxy` (`ProxyOfLogin`), and `NO_PROXY` to loopback; none for `direct` or a SOCKS proxy, which Claude Code can't use. It is written on every switch (`switchLogin`, the user's or `SwitchWhenSpent`), when the Claude subscription is saved, and at the gateway's look every `loginSwitchEvery` (a sign-in made in Claude Code itself). Claude Code reads its env at start, so only sessions started after the switch take it. A proxy key the user set (in either case) is theirs: magpie then writes none and takes out none of theirs. What magpie wrote is kept in `claude-proxy-env.json`, and a key is magpie's only while it holds that value. A `settings.json` that doesn't parse is left as it is. Its log lines name the proxy through `netproxy.Redact`, without its user and password (#1886); the env gets it whole. | [`claude_proxy_env.go`](../../internal/provider/claude_proxy_env.go) |
|
||||
| Routing groups | User-made groups from the Routing view, and auto-found groups of the same model across providers (derived, never stored). Members are `provider/model[:effort]`. A group can nest another (`group/<id>`); `SaveGroup` refuses loops. `Match` takes a glob or `re:` pattern (#766). A found group follows its providers: one switched off or removed leaves it, and one on again is back. A found group the user changed (an `auto-…` id stored) is read without the members of providers magpie no longer has (`withoutRemoved`, not written back, so a provider back under its id is back in it), except a manual group's pick, a rule's model, or all of them when none would be left. A switched-off provider's members stay in it, skipped by `membersIn`, and the Routing page says them as switched off (`memberJSON.providerOff`). The user's own groups keep their members. Three templates make a group in one click from the models the user has (`provider.Templates`, `AddTemplate`; the Routing page's cards before a first group and its Templates menu after, `magpie group template [kind] [name]`): `smart` sends a hard turn to the strongest model and an easy one or a compaction to a cheap one, asked by a classifier (the decision API when there is one, else the cheapest priced model that doesn't reason); `thrifty` starts on two cheap models of different providers and sends high reasoning to the strongest; `steady` fails over between the strongest model of up to three providers. A model is weighed by its maker's list price when known, else what its provider charges, else by its id's size words (`sizeOf`); one over `tooDear` (USD 100 a million output tokens) is never picked. A template that can't be made says what is missing (`Need`). It is saved under a name and id no group has (`freeGroupName`, shared with `CopyGroup`), never over one. A group is shared as text (`ShareGroup`, a group row's Copy to share): JSON marked `"magpie": "routing-group"` with a format `version` (`ShareVersion`), holding the group's members as it names them, patterns, routing, rules, classifier and settings. A group holds only `provider/model` ids, never a key, account or address, and the derived matches, found/hidden/off flags and the rules that hold by a folder (a path on the sharer's machine, `Rule.Folders`) stay behind; a pasted one is left out too. `ImportGroup` (the Routing page's Import, `POST /api/groups/import`) reads it with words or a code fence around it, refuses another text, a newer format or none (`ShareError`, said in the reader's language). A member whose provider the importer has is kept; else the same model (`AutoGroupOf`) under the first provider of theirs that serves it (`Instead`); else it is left out and named (`Missing`), with the rules that send to it, its place among the off and fast members, and a classifier gone takes the intent rules and auto effort with it. Nothing is added when no member is left; what is added gets a free name, never replacing a group. A group of patterns only that match nothing now (a plugin's models not listed) has no members: `/api/groups` says them, and an unmakeable template's, as `[]`, never `null`; the Routing page reads the response through `groupsFrom` and draws a group it still can't draw as one row saying so, so one bad group never hides the rest (#1585). | [`group.go`](../../internal/provider/group.go), [`grouptemplate.go`](../../internal/provider/grouptemplate.go), [`group_share.go`](../../internal/provider/group_share.go) |
|
||||
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=<remote>/~keys&user=<key name>`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) |
|
||||
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. A Claude account's windows Claude Code told as it answered (`NoteClaudeLimits`, kept in `claudeUsage` with their own `heardSeq`, which drops the account's `LoginUsage` reading) stand on its card over any reading started before them (`withHeardClaude`, #2206), so a magpie only requests reach still tells them. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Each key of a remote-magpie provider also gets a card of its own, under `<remote>/~keys`, one section per key (#1547, `remoteKeyCards` in `remote_key_limits.go`): the gateway key's limit as that magpie holds it, read from `GET /v1/magpie/limit` asked with that key alone, so a key never sees another's numbers. It shows a window per cap (tokens, spend) named for the period, used against the cap, with its reset, plus `GatewayKey` (what is left, calls, a cycle of days, used up); a key held to no limit shows `Unlimited`. It is kept for `remoteCardsFor` like the remote's cards and read again by the card's refresh (`?provider=<remote>/~keys&user=<key name>`). A read that fails keeps the last numbers, dated (`AsOf`); with none the card says why, never zero or no limit. A remote from before `/v1/magpie/limit` (404) says it is too old to tell (`errRemoteNoKeyLimit`). A remote that holds the key to a budget, models or accounts answers its cards 403 `gateway_key_held` (#1981, `errKeyHeld`): the cards kept from before are dropped and only the key's own card shows. Its owner can let the key be told the cards of what it may use (#2216, `magpie gateway-key quotas <id> on`); the remote then answers those, and 403 as before when that is none. A remote's cards are kept by provider and key (`remoteCardsID`), so a changed key never shows what the old one was told, and a read is kept only over one asked before it (`keepRemoteCards`). Cursor, Grok and a Kiro key keep the page's cards only. With Settings → Allowances → *Allowance reads* at *When I ask* (`QuotaReads == "asked"`, #1518: magpie started at login before the proxy app read by itself, direct), only a read the user asked for goes out: the Usage page or the tray panel's Allowances opened (no more than once in 30s, `quotasOpened`, #1588) or refreshed (`?asked=1`), a card's refresh (`RefreshUsage`), `magpie quota`, `magpie accounts`, `magpie quota wait` and the TUI's quotas (`Asked`). Any other read (`quotaReading` → `holdUnasked`) carries `netproxy.Hold`, so its requests fail before they leave, and every reader gives back what it last read, dated, or "not read yet" (`errNotAsked`): routing, the used-up switch, the menu bar and alerts go by that. An account refused for its quota (`StaleAllowance` → `markStaleRead`) or a key refused (`StaleKeyAllowance` → `refused`) is still read, once (`unheld`). Warm-up and check-in are not reads and are unchanged. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`quota_asked.go`](../../internal/provider/quota_asked.go) |
|
||||
| A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); a list that didn't ask gets no prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) |
|
||||
| A remote magpie's service tiers | A remote magpie's `/v1/models` gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. The list gives every client the tiers, not only a magpie asking with `X-Magpie-Drawers`: Cindy shows its Fast switch on a model whose `service_tiers` hold `priority` (#1914, `TestModelsListTiersForEveryClient`). | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`live.go`](../../internal/catalog/live.go) |
|
||||
| An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) |
|
||||
|
||||
@@ -128,6 +128,11 @@ type Key struct {
|
||||
// "<provider>/<account>": a signed-in account by its stable id, a
|
||||
// key by its fingerprint; none for every account, as keys always did.
|
||||
Accounts []string `json:"accounts,omitempty"`
|
||||
// Quotas lets a key held to a budget, models or accounts be told the
|
||||
// quotas of what it may use (#2216): the cards of the providers whose
|
||||
// every model it may use, of the accounts and keys it may use, names
|
||||
// and balances included. Off, it is told none (#1981).
|
||||
Quotas bool `json:"quotas,omitempty"`
|
||||
}
|
||||
|
||||
// Identity is the gateway key a request came with, its budget, the
|
||||
@@ -138,6 +143,7 @@ type Identity struct {
|
||||
More []Limit
|
||||
Models []string
|
||||
Accounts []string
|
||||
Quotas bool
|
||||
}
|
||||
type contextKey struct{}
|
||||
|
||||
@@ -260,6 +266,8 @@ type Change struct {
|
||||
// Accounts is what "accounts-key" sets (#905); none lets the key use
|
||||
// every account and key.
|
||||
Accounts []string `json:"accounts,omitempty"`
|
||||
// Quotas is what "quotas-key" sets (#2216).
|
||||
Quotas bool `json:"quotas,omitempty"`
|
||||
// Secret is the value "add-key" gives the new key, one its clients
|
||||
// already send (love1sbug on X: keys handed out from another gateway);
|
||||
// "" for one magpie makes.
|
||||
@@ -399,6 +407,8 @@ func Update(action string, in Change) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
keys[i].Accounts = as
|
||||
case "quotas-key":
|
||||
keys[i].Quotas = in.Quotas
|
||||
case "on-key", "off-key":
|
||||
keys[i].Off = action == "off-key"
|
||||
case "remove-key":
|
||||
@@ -413,7 +423,7 @@ func Update(action string, in Change) (string, error) {
|
||||
default:
|
||||
return "", fmt.Errorf("unknown key action %q", action)
|
||||
}
|
||||
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" {
|
||||
if defaultKey && action != "remove-key" && action != "rename-key" && action != "limit-key" && action != "reset-limit-key" && action != "models-key" && action != "accounts-key" && action != "quotas-key" {
|
||||
mirror = &keys[i]
|
||||
}
|
||||
}
|
||||
@@ -460,7 +470,7 @@ func Authenticate(secret string) (Identity, bool) {
|
||||
if k.Off {
|
||||
return Identity{}, false
|
||||
}
|
||||
return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: k.Models, Accounts: k.Accounts}, true
|
||||
return Identity{KeyID: k.ID, KeyName: k.Name, Limit: k.Limit, More: k.More, Models: k.Models, Accounts: k.Accounts, Quotas: k.Quotas}, true
|
||||
}
|
||||
}
|
||||
s := settings.Load()
|
||||
|
||||
@@ -36,6 +36,10 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyAccounts(out, args[1:])
|
||||
}
|
||||
if action == "quotas" {
|
||||
access.MigrateLegacyLANKeyBestEffort()
|
||||
return gatewayKeyQuotas(out, args[1:])
|
||||
}
|
||||
// add <name> --key <value>: the key keeps a value its clients already
|
||||
// send (love1sbug on X); "--key -" reads it from stdin, out of the
|
||||
// shell's history
|
||||
@@ -55,7 +59,7 @@ func gatewayKeysTo(out io.Writer, args []string) error {
|
||||
args = args[:2]
|
||||
}
|
||||
if (action == "list" && len(args) != 1) || (action != "list" && len(args) != 2) {
|
||||
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...]")
|
||||
return fmt.Errorf("usage: magpie gateway-key list | add <name> [--key <value> | --key -] | rotate <id> | remove <id> | limit <id> [list | off | reset [<n>] | remove <n> | [add] day|week|month|<N>d|<N>h [--tokens N] [--cost USD] [--cache-reads]] | models <id> [all | <provider>/<model>|<provider>/* ...] | accounts <id> [all | <provider>/<account>|<provider>/<key id> ...] | quotas <id> [on | off]")
|
||||
}
|
||||
switch action {
|
||||
case "list", "add", "rotate", "remove":
|
||||
@@ -451,3 +455,41 @@ func gatewayKeyAccounts(out io.Writer, args []string) error {
|
||||
_, err = fmt.Fprintf(out, "%s: only %s\n", k.Name, strings.Join(shown, ", "))
|
||||
return err
|
||||
}
|
||||
|
||||
// gatewayKeyQuotas shows or sets whether a key held to a budget, models
|
||||
// or accounts is told the quotas of what it may use (#2216): the cards of
|
||||
// the providers whose every model it may use, of its accounts and keys.
|
||||
//
|
||||
// magpie gateway-key quotas <id> whether it is
|
||||
// magpie gateway-key quotas <id> on|off tell it them, or none (#1981)
|
||||
func gatewayKeyQuotas(out io.Writer, args []string) error {
|
||||
usage := fmt.Errorf("usage: magpie gateway-key quotas <id> [on | off]")
|
||||
if len(args) == 0 || len(args) > 2 {
|
||||
return usage
|
||||
}
|
||||
id := args[0]
|
||||
if len(args) == 2 {
|
||||
if args[1] != "on" && args[1] != "off" {
|
||||
return usage
|
||||
}
|
||||
if _, err := access.Update("quotas-key", access.Change{Key: id, Quotas: args[1] == "on"}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
keys, err := access.List()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
i := slices.IndexFunc(keys, func(k access.Key) bool { return k.ID == id })
|
||||
if i < 0 {
|
||||
return fmt.Errorf("Key not found")
|
||||
}
|
||||
k := keys[i]
|
||||
switch {
|
||||
case !k.Quotas:
|
||||
_, err = fmt.Fprintf(out, "%s: told no quotas when held to a budget, models or accounts\n", k.Name)
|
||||
default:
|
||||
_, err = fmt.Fprintf(out, "%s: told the quotas of the providers and accounts it may use\n", k.Name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -392,3 +392,48 @@ func TestGatewayKeySeveralLimitsCLI(t *testing.T) {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// #2216: whether a key held to a budget, models or accounts is told the
|
||||
// quotas of what it may use; off, as every key was (#1981), it is told none.
|
||||
func TestGatewayKeyQuotasCLI(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
if err := settings.Save(settings.Settings{LAN: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
call := func(args ...string) (string, error) {
|
||||
var out bytes.Buffer
|
||||
err := gatewayKeysTo(&out, append([]string{"gateway-key"}, args...))
|
||||
return out.String(), err
|
||||
}
|
||||
if _, err := call("add", "Phone"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, _ := access.List()
|
||||
id := keys[0].ID
|
||||
off, on := "Phone: told no quotas when held to a budget, models or accounts\n", "Phone: told the quotas of the providers and accounts it may use\n"
|
||||
if got, err := call("quotas", id); err != nil || got != off {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if got, err := call("quotas", id, "on"); err != nil || got != on {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if keys, _ = access.List(); !keys[0].Quotas {
|
||||
t.Fatal("not kept on")
|
||||
}
|
||||
for _, args := range [][]string{{"quotas"}, {"quotas", id, "yes"}, {"quotas", id, "on", "off"}, {"quotas", "missing", "on"}, {"quotas", "missing"}} {
|
||||
if _, err := call(args...); err == nil {
|
||||
t.Error("accepted", args)
|
||||
}
|
||||
}
|
||||
if keys, _ = access.List(); !keys[0].Quotas {
|
||||
t.Fatal("a refused call turned it off")
|
||||
}
|
||||
if got, err := call("quotas", id, "off"); err != nil || got != off {
|
||||
t.Fatal(got, err)
|
||||
}
|
||||
if keys, _ = access.List(); keys[0].Quotas {
|
||||
t.Fatal("not kept off")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,6 +117,7 @@ const usage = `magpie — one place to pick every agent's model
|
||||
magpie gateway-key list|add <name>|rotate <id>|remove <id> manage the keys clients use to call a shared gateway
|
||||
magpie gateway-key limit <id> [list|off|reset [n]|remove <n>|[add] day|week|month|<N>d|<N>h --tokens N --cost USD --cache-reads] a key's own limits, and what it used
|
||||
magpie gateway-key models <id> [all|<provider>/<model>|<provider>/* ...] the models a key may use, every one unless it names some
|
||||
magpie gateway-key quotas <id> [on|off] whether a key held to a budget, models or accounts is told the quotas of what it may use
|
||||
magpie mcp image the image and video generation MCP server an agent is given from the library (stdio)
|
||||
magpie usage [today|7d|30d|all] tokens and cost per agent, model and subscription account (30d)
|
||||
magpie usage --csv [--account <name>] [today|7d|30d|all] every request as CSV (or one account's): the model asked for, sent and served, tokens, cost, time, status, account
|
||||
|
||||
+30
-13
@@ -651,24 +651,26 @@ func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
// asks of it while the gateway is shared or MAGPIE_ADDR puts it on the
|
||||
// network. A key held to a budget, models or accounts is someone else's
|
||||
// to use and is told none of it (refuseHeld), as are quotasHistory,
|
||||
// quotaCards, quotaCardsRefresh and concurrency.
|
||||
// quotaCards, quotaCardsRefresh and concurrency; one its owner lets be
|
||||
// told its quotas is told those of what it may use (scopeQuotas, #2216).
|
||||
func (s *Server) quotas(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
if refuseHeld(w, r, heldRefused) {
|
||||
scope, ok := scopeQuotas(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
// ?kept=1: what was last read, no vendor asked (magpie statusline,
|
||||
// run on every message, #1997)
|
||||
if r.URL.Query().Get("kept") == "1" {
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.KeptQuotaReport(time.Now())})
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": scope.quotas(provider.KeptQuotaReport(time.Now()))})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.QuotaReport(ctx, time.Now())})
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": scope.quotas(provider.QuotaReport(ctx, time.Now()))})
|
||||
}
|
||||
|
||||
// quotasHistory is what was left of each account's windows over time, as
|
||||
@@ -680,11 +682,12 @@ func (s *Server) quotasHistory(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
if refuseHeld(w, r, heldRefused) {
|
||||
scope, ok := scopeQuotas(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.QuotaHistories(provider.QuotaHistorySince(q.Get("days"), time.Now()), q.Get("provider"), q.Get("user"))})
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": scope.histories(provider.QuotaHistories(provider.QuotaHistorySince(q.Get("days"), time.Now()), q.Get("provider"), q.Get("user")))})
|
||||
}
|
||||
|
||||
// quotaCards is the Usage page's cards as this magpie last read them, for
|
||||
@@ -695,10 +698,11 @@ func (s *Server) quotaCards(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
if refuseHeld(w, r, heldRefused) {
|
||||
scope, ok := scopeQuotas(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.CachedCards(time.Now())})
|
||||
writeCards(w, r, scope)
|
||||
}
|
||||
|
||||
// remoteRefreshes is when another magpie last had each card read again
|
||||
@@ -720,7 +724,8 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's quotas are told to another machine only when magpie is shared on the local network (Settings → Share on local network) and the request carries its API key (Authorization: Bearer <key> or x-api-key: <key>)")
|
||||
return
|
||||
}
|
||||
if refuseHeld(w, r, heldRefused) {
|
||||
scope, ok := scopeQuotas(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, user := r.URL.Query().Get("provider"), r.URL.Query().Get("user")
|
||||
@@ -728,6 +733,13 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads only its own cards again")
|
||||
return
|
||||
}
|
||||
// a key told only some cards (#2216) has only those read again: a
|
||||
// card it isn't told is refused, as if held, and with none named
|
||||
// each card it is told is read, not every account here
|
||||
if scope != nil && id != "" && !scope.card(id, user) {
|
||||
refuseHeld(w, r, heldRefused)
|
||||
return
|
||||
}
|
||||
key := id + "|" + strings.ToLower(user)
|
||||
remoteRefreshes.Lock()
|
||||
due := time.Since(remoteRefreshes.at[key]) >= remoteRefreshGap
|
||||
@@ -737,14 +749,19 @@ func (s *Server) quotaCardsRefresh(w http.ResponseWriter, r *http.Request) {
|
||||
remoteRefreshes.Unlock()
|
||||
if due {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
|
||||
if id == "" {
|
||||
provider.ReadAllCards(ctx)
|
||||
} else {
|
||||
switch {
|
||||
case id != "":
|
||||
provider.RefreshUsage(ctx, id, user)
|
||||
case scope != nil:
|
||||
for _, q := range scope.cards(provider.CachedCards(time.Now())) {
|
||||
provider.RefreshUsage(ctx, q.Provider, q.User)
|
||||
}
|
||||
default:
|
||||
provider.ReadAllCards(ctx)
|
||||
}
|
||||
cancel()
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.CachedCards(time.Now())})
|
||||
writeCards(w, r, scope)
|
||||
}
|
||||
|
||||
func modelObject(e provider.Entry) map[string]any {
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A key held to a budget, models or accounts is told none of this
|
||||
// magpie's quotas (#1981), unless the key's owner lets it be told those
|
||||
// of what it may use (access.Key.Quotas, Kenoia, #2216). It is then told
|
||||
// a card only when:
|
||||
//
|
||||
// - the card's provider is one of this magpie's, in the catalog, and
|
||||
// the key may use every model the catalog lists of it: a key held to
|
||||
// some of a provider's models is told nothing of the provider, since
|
||||
// its quota is spent by the models the key may not use as well; and
|
||||
// - the card's account or key is one the key may use (AllowsAccount):
|
||||
// when the key's account list names the provider, the card's account
|
||||
// must be one it names, matched by who is signed in or the key's
|
||||
// name; a card no account of the provider is known by is told to no
|
||||
// such key.
|
||||
//
|
||||
// The quotas, their kept report, their history, the cards another magpie
|
||||
// reads and a card's refresh all go through it. The accounts' lanes
|
||||
// (/v1/magpie/concurrency) and the usage summary are still refused.
|
||||
|
||||
// quotaScope is what a held key with Quotas set may be told; nil is
|
||||
// everything, for a key held to nothing and this machine's owner.
|
||||
type quotaScope struct {
|
||||
who access.Identity
|
||||
every map[string]bool // provider id → the key may use every model of it
|
||||
refs map[string][]provider.AccountRef
|
||||
}
|
||||
|
||||
// scopeQuotas is the request's quota scope. It answers a held key that
|
||||
// may not be told quotas 403 (refuseHeld) and says so with ok false.
|
||||
func scopeQuotas(w http.ResponseWriter, r *http.Request) (*quotaScope, bool) {
|
||||
who := access.Caller(r.Context())
|
||||
if !heldKey(who) {
|
||||
return nil, true
|
||||
}
|
||||
if !who.Quotas {
|
||||
refuseHeld(w, r, heldRefused)
|
||||
return nil, false
|
||||
}
|
||||
return newQuotaScope(who, provider.Catalog()), true
|
||||
}
|
||||
|
||||
func newQuotaScope(who access.Identity, catalog []provider.Entry) *quotaScope {
|
||||
s := "aScope{who: who, every: map[string]bool{}, refs: map[string][]provider.AccountRef{}}
|
||||
for _, e := range catalog {
|
||||
if e.Group != "" || e.Provider.ID == "" {
|
||||
continue
|
||||
}
|
||||
id := e.Provider.ID
|
||||
ok, seen := s.every[id]
|
||||
if seen && !ok {
|
||||
continue
|
||||
}
|
||||
s.every[id] = modelAllowed(who, e.Provider, e.Model)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// provider says the key may be told provider id's quota at all.
|
||||
func (s *quotaScope) provider(id string) bool {
|
||||
if s == nil {
|
||||
return true
|
||||
}
|
||||
return s.every[id]
|
||||
}
|
||||
|
||||
// card says the key may be told the card of provider id's account user.
|
||||
func (s *quotaScope) card(id, user string) bool {
|
||||
if s == nil {
|
||||
return true
|
||||
}
|
||||
if !s.provider(id) {
|
||||
return false
|
||||
}
|
||||
if len(s.who.Accounts) == 0 {
|
||||
return true
|
||||
}
|
||||
refs, ok := s.refs[id]
|
||||
if !ok {
|
||||
p, err := provider.Find(id)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
refs = p.AccountIDs()
|
||||
s.refs[id] = refs
|
||||
}
|
||||
// a provider's only key has a card named by no one (cardKeys)
|
||||
if strings.TrimSpace(user) == "" && len(refs) == 1 {
|
||||
return s.who.AllowsAccount(id, refs[0].ID)
|
||||
}
|
||||
matched := false
|
||||
for _, a := range refs {
|
||||
if !strings.EqualFold(strings.TrimSpace(a.User), strings.TrimSpace(user)) {
|
||||
continue
|
||||
}
|
||||
// two accounts or keys shown by one name: the key may use both,
|
||||
// or is told neither's card
|
||||
if !s.who.AllowsAccount(id, a.ID) {
|
||||
return false
|
||||
}
|
||||
matched = true
|
||||
}
|
||||
if matched {
|
||||
return true
|
||||
}
|
||||
// a card no account is known by: only for a provider the key's list
|
||||
// names no account of, which it uses on every one
|
||||
return s.who.AllowsAccount(id, "")
|
||||
}
|
||||
|
||||
// cards is cs as the key may be told them.
|
||||
func (s *quotaScope) cards(cs []provider.SubscriptionQuota) []provider.SubscriptionQuota {
|
||||
if s == nil {
|
||||
return cs
|
||||
}
|
||||
out := []provider.SubscriptionQuota{}
|
||||
for _, q := range cs {
|
||||
if q.From == "" && s.card(q.Provider, q.User) {
|
||||
out = append(out, q)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// writeCards answers another magpie the cards the key may be told. A key
|
||||
// told none of the cards here is answered as held: the other magpie then
|
||||
// shows the key's own limit, not that nothing was read here, which a
|
||||
// refresh wouldn't change.
|
||||
func writeCards(w http.ResponseWriter, r *http.Request, s *quotaScope) {
|
||||
all := provider.CachedCards(time.Now())
|
||||
cs := s.cards(all)
|
||||
if len(cs) == 0 && len(all) > 0 {
|
||||
refuseHeld(w, r, heldRefused)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": cs})
|
||||
}
|
||||
|
||||
// quotas is qs as the key may be told them.
|
||||
func (s *quotaScope) quotas(qs []provider.Quota) []provider.Quota {
|
||||
if s == nil {
|
||||
return qs
|
||||
}
|
||||
out := []provider.Quota{}
|
||||
for _, q := range qs {
|
||||
if q.From == "" && s.card(q.Provider, q.User) {
|
||||
out = append(out, q)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// histories is hs as the key may be told them.
|
||||
func (s *quotaScope) histories(hs []provider.QuotaHistory) []provider.QuotaHistory {
|
||||
if s == nil {
|
||||
return hs
|
||||
}
|
||||
out := []provider.QuotaHistory{}
|
||||
for _, h := range hs {
|
||||
if s.card(h.Provider, h.User) {
|
||||
out = append(out, h)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// #2216 (Kenoia): a key held to models or accounts on a shared magpie was
|
||||
// told no quota at all (#1981), so the remote magpie it was set up on
|
||||
// showed none of the providers it may use. A key whose owner turns its
|
||||
// quotas on is told the cards of the providers whose every model it may
|
||||
// use, of the accounts and keys it may use, and nothing else: not another
|
||||
// provider's, not a provider's it may use only some models of, not an
|
||||
// account's it may not use.
|
||||
func TestHeldKeyToldItsOwnQuotas(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
seedKeptBalances(t)
|
||||
|
||||
ref := func(id, user string) string {
|
||||
t.Helper()
|
||||
p, err := provider.Find(id)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, a := range p.AccountIDs() {
|
||||
if a.User == user {
|
||||
return id + "/" + a.ID
|
||||
}
|
||||
}
|
||||
t.Fatalf("%s has no key %q", id, user)
|
||||
return ""
|
||||
}
|
||||
keys, secrets := newCaller(t, "Owner", "AlphaAll", "AlphaSome", "AlphaTwo", "BetaKey", "Budget", "Nothing")
|
||||
set := func(action string, c access.Change) {
|
||||
t.Helper()
|
||||
if _, err := access.Update(action, c); err != nil {
|
||||
t.Fatal(action, err)
|
||||
}
|
||||
}
|
||||
set("models-key", access.Change{Key: keys[1].ID, Models: []string{"alpha/*"}})
|
||||
set("models-key", access.Change{Key: keys[2].ID, Models: []string{"alpha/m1", "beta/*"}})
|
||||
set("models-key", access.Change{Key: keys[3].ID, Models: []string{"alpha/*"}})
|
||||
set("accounts-key", access.Change{Key: keys[3].ID, Accounts: []string{ref("alpha", "Two")}})
|
||||
set("accounts-key", access.Change{Key: keys[4].ID, Accounts: []string{ref("beta", provider.Mask("beta-key"))}})
|
||||
set("limit-key", access.Change{Key: keys[5].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}})
|
||||
set("models-key", access.Change{Key: keys[6].ID, Models: []string{"alpha/m2"}})
|
||||
for _, k := range append(keys[1:5:5], keys[6]) {
|
||||
set("quotas-key", access.Change{Key: k.ID, Quotas: true})
|
||||
}
|
||||
|
||||
h := lanGuard(New().Handler())
|
||||
do := func(method, path, secret string) (int, string) {
|
||||
r := httptest.NewRequest(method, path, nil)
|
||||
r.RemoteAddr = "192.168.1.9:5000"
|
||||
r.Header.Set("Authorization", "Bearer "+secret)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
told := func(path, b string) []string {
|
||||
t.Helper()
|
||||
var out struct {
|
||||
Data []struct{ Provider, User string }
|
||||
}
|
||||
if err := json.Unmarshal([]byte(b), &out); err != nil {
|
||||
t.Fatal(path, err, b)
|
||||
}
|
||||
var cards []string
|
||||
for _, q := range out.Data {
|
||||
if q.Provider == "alpha" || q.Provider == "beta" || q.Provider == "" {
|
||||
cards = append(cards, q.Provider+":"+strings.ToLower(q.User))
|
||||
continue
|
||||
}
|
||||
// another provider's card (an account another test signed in)
|
||||
cards = append(cards, q.Provider+":?")
|
||||
}
|
||||
slices.Sort(cards)
|
||||
return cards
|
||||
}
|
||||
every := []string{"alpha:one", "alpha:two", "beta:"}
|
||||
want := map[string][]string{
|
||||
"AlphaAll": {"alpha:one", "alpha:two"},
|
||||
"AlphaSome": {"beta:"}, // none of alpha's: m2 spends its quota too
|
||||
"AlphaTwo": {"alpha:two"},
|
||||
"BetaKey": every,
|
||||
}
|
||||
for _, path := range []string{"/v1/magpie/quotas?kept=1", provider.RemoteCardsPath} {
|
||||
for i, s := range secrets {
|
||||
name := keys[i].Name
|
||||
c, b := do("GET", path, s)
|
||||
switch name {
|
||||
case "Owner":
|
||||
if c != 200 {
|
||||
t.Fatalf("%s %s: %d %s", name, path, c, b)
|
||||
}
|
||||
got := told(path, b)
|
||||
for _, w := range every {
|
||||
if !slices.Contains(got, w) {
|
||||
t.Fatalf("%s %s: no %s card in %v", name, path, w, got)
|
||||
}
|
||||
}
|
||||
case "Nothing":
|
||||
// told no card here: the other magpie shows its own limit,
|
||||
// not "nothing read on that magpie yet"
|
||||
if path == provider.RemoteCardsPath {
|
||||
if c != http.StatusForbidden || !strings.Contains(b, provider.KeyHeldCode) {
|
||||
t.Errorf("%s %s: %d %s", name, path, c, b)
|
||||
}
|
||||
} else if c != 200 || len(told(path, b)) != 0 {
|
||||
t.Errorf("%s %s: %d %s", name, path, c, b)
|
||||
}
|
||||
case "Budget":
|
||||
if c != http.StatusForbidden || !strings.Contains(b, provider.KeyHeldCode) {
|
||||
t.Errorf("%s %s, quotas off: %d %s", name, path, c, b)
|
||||
}
|
||||
default:
|
||||
if c != 200 {
|
||||
t.Fatalf("%s %s: %d %s", name, path, c, b)
|
||||
}
|
||||
if got := told(path, b); !slices.Equal(got, want[name]) {
|
||||
t.Errorf("%s %s: told %v, want %v", name, path, got, want[name])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// the history and the report read afresh go by the same cards
|
||||
for _, path := range []string{"/v1/magpie/quotas", "/v1/magpie/quotas/history"} {
|
||||
for i, s := range secrets[1:5] {
|
||||
name := keys[i+1].Name
|
||||
c, b := do("GET", path, s)
|
||||
if c != 200 {
|
||||
t.Fatalf("%s %s: %d %s", name, path, c, b)
|
||||
}
|
||||
for _, card := range told(path, b) {
|
||||
if !slices.Contains(want[name], card) {
|
||||
t.Errorf("%s %s: told %s, may be told only %v", name, path, card, want[name])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// a card the key isn't told isn't read again for it
|
||||
for _, x := range []struct{ secret, card string }{
|
||||
{secrets[3], "provider=alpha&user=One"},
|
||||
{secrets[3], "provider=beta"},
|
||||
{secrets[2], "provider=alpha&user=Two"},
|
||||
{secrets[1], "provider=beta"},
|
||||
} {
|
||||
if c, b := do("POST", provider.RemoteRefreshPath+"?"+x.card, x.secret); c != http.StatusForbidden || !strings.Contains(b, provider.KeyHeldCode) {
|
||||
t.Errorf("refresh %s: %d %s", x.card, c, b)
|
||||
}
|
||||
}
|
||||
c, b := do("POST", provider.RemoteRefreshPath+"?provider=alpha&user=Two", secrets[3])
|
||||
if c != 200 {
|
||||
t.Fatalf("refresh its own card: %d %s", c, b)
|
||||
}
|
||||
// read again, a key with no balance to read has no card: only what
|
||||
// it is told may be left
|
||||
for _, card := range told("refresh", b) {
|
||||
if !slices.Contains(want["AlphaTwo"], card) {
|
||||
t.Errorf("refresh its own card: told %s", card)
|
||||
}
|
||||
}
|
||||
c, b = do("POST", provider.RemoteRefreshPath, secrets[1])
|
||||
if c != 200 {
|
||||
t.Fatalf("refresh every card it is told: %d %s", c, b)
|
||||
}
|
||||
for _, card := range told("refresh", b) {
|
||||
if !slices.Contains(want["AlphaAll"], card) {
|
||||
t.Errorf("refresh every card it is told: told %s", card)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// seedKeptBalances saves provider alpha with two keys, One and Two (models
|
||||
// m1 and m2), and beta with one key (o1), each key's balance kept on disk
|
||||
// (quotas.json) as last read.
|
||||
func seedKeptBalances(t *testing.T) {
|
||||
t.Helper()
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "alpha", Name: "Alpha", Key: "alpha-one", KeyName: "One",
|
||||
Keys: []provider.KeyAccount{{Name: "Two", Key: "alpha-two"}}, Chat: up.URL + "/v1", Models: []string{"m1", "m2"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.Save(provider.Provider{ID: "beta", Name: "Beta", Key: "beta-key", Chat: up.URL + "/v1", Models: []string{"o1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// each key's balance as last read, kept on disk (quotas.json)
|
||||
tag := func(key string) string {
|
||||
sum := sha256.Sum256([]byte(key))
|
||||
return "balance " + hex.EncodeToString(sum[:8])
|
||||
}
|
||||
at := time.Now().Add(-time.Minute)
|
||||
kept := map[string]any{}
|
||||
for _, k := range []struct{ id, key, user string }{{"alpha", "alpha-one", "One"}, {"alpha", "alpha-two", "Two"}, {"beta", "beta-key", ""}} {
|
||||
kept[k.id+"/"+tag(k.key)] = map[string]any{"at": at, "quota": provider.SubscriptionQuota{Provider: k.id, User: k.user, Balance: "$5.00", Windows: []provider.QuotaWindow{}}}
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "quotas.json"), mustJSON(kept), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider.ForgetKeptCardsForTest()
|
||||
provider.ForgetBalances()
|
||||
provider.ForgetPlanQuotas()
|
||||
|
||||
}
|
||||
|
||||
// #2216 from the other side: a magpie with that magpie as its provider,
|
||||
// through a key let see its quotas, shows the cards of what the key may
|
||||
// use beside the key's own; a key told none shows its own card alone, not
|
||||
// "nothing read on that magpie yet", which a refresh wouldn't change.
|
||||
func TestRemoteMagpieShowsHeldKeyItsQuotas(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
seedKeptBalances(t)
|
||||
keys, secrets := newCaller(t, "AlphaTwo", "Nothing")
|
||||
p, err := provider.Find("alpha")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var two string
|
||||
for _, a := range p.AccountIDs() {
|
||||
if a.User == "Two" {
|
||||
two = "alpha/" + a.ID
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
action string
|
||||
in access.Change
|
||||
}{
|
||||
{"models-key", access.Change{Key: keys[0].ID, Models: []string{"alpha/*"}}},
|
||||
{"accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{two}}},
|
||||
{"models-key", access.Change{Key: keys[1].ID, Models: []string{"alpha/m2"}}},
|
||||
{"quotas-key", access.Change{Key: keys[0].ID, Quotas: true}},
|
||||
{"quotas-key", access.Change{Key: keys[1].ID, Quotas: true}},
|
||||
} {
|
||||
if _, err := access.Update(c.action, c.in); err != nil {
|
||||
t.Fatal(c.action, err)
|
||||
}
|
||||
}
|
||||
gw := httptest.NewServer(lanGuard(New().Handler()))
|
||||
defer gw.Close()
|
||||
ctx := t.Context()
|
||||
shown := func(secret string) []string {
|
||||
t.Helper()
|
||||
if err := provider.Save(provider.Provider{ID: "office", Name: "Office", Preset: provider.RemoteMagpiePreset, Key: secret, Chat: gw.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
provider.ForgetRemoteCardsForTest()
|
||||
var out []string
|
||||
for _, q := range provider.RemoteCards(ctx) {
|
||||
switch {
|
||||
case q.Provider == "office/~keys":
|
||||
out = append(out, q.Provider+":"+q.Error) // the key's own
|
||||
case strings.HasPrefix(q.Provider, "office"):
|
||||
out = append(out, q.Provider+":"+strings.ToLower(q.User)+":"+q.Error)
|
||||
}
|
||||
}
|
||||
slices.Sort(out)
|
||||
return out
|
||||
}
|
||||
if got := shown(secrets[0]); !slices.Equal(got, []string{"office/alpha:two:", "office/~keys:"}) {
|
||||
t.Errorf("a key held to alpha's Two: %v", got)
|
||||
}
|
||||
if got := shown(secrets[1]); !slices.Equal(got, []string{"office/~keys:"}) {
|
||||
t.Errorf("a key told no card: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -2508,6 +2508,10 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
/* the models a key may use (#882): a long model's id is cut, and the
|
||||
badge gives way first on a narrow window */
|
||||
#gatewayKeys .amodels.key-models { display: inline-block; flex: 0 1 auto; min-width: 24px; max-width: 180px; line-height: 20px; overflow: hidden; text-overflow: ellipsis; }
|
||||
/* a key's quotas badge (#2216) takes no room until the row is hovered,
|
||||
and gives way before the row runs past a narrow window */
|
||||
#gatewayKeys .amodels.key-quotas { display: inline-block; flex: 0 1 auto; min-width: 0; line-height: 20px; overflow: hidden; text-overflow: ellipsis; }
|
||||
#gatewayKeys .acc:not(:hover) > .key-quotas:not(.set):not(:focus) { max-width: 0; padding: 0; margin-left: -9px; box-shadow: none; }
|
||||
/* the Settings row's picker: the key row's badge, always shown */
|
||||
.row.pref .proto.pick { flex: none; margin-left: auto; display: inline-flex; align-items: center; gap: 3px; height: 24px; padding: 0 6px 0 9px; font: inherit; font-size: 12px; color: var(--fg-2); border: 0; border-radius: 7px; background: var(--pill); white-space: nowrap; cursor: default; transition: background .12s, color .12s; }
|
||||
.row.pref .proto.pick svg { opacity: .7; transition: transform .15s var(--ease); }
|
||||
@@ -3435,6 +3439,8 @@ body.panel .modal { padding: 16px 12px; }
|
||||
body.web .acc :is(.text.quiet, .proto, .amodels, .alane) { opacity: 1; }
|
||||
body.web .accts.keys .acc > :is(.amodels, .proto, .alane, .text.quiet) { max-width: none !important; padding: 0 7px !important; flex-shrink: 0 !important; }
|
||||
body.web .accts.keys .acc > .alane:not(.set) { margin-left: 0 !important; }
|
||||
body.web #gatewayKeys .acc > .key-quotas { max-width: none !important; padding: 0 7px !important; margin-left: 0 !important; flex-shrink: 0; }
|
||||
body.web #gatewayKeys .acc > .key-quotas:not(.set) { box-shadow: inset 0 0 0 1px var(--line) !important; }
|
||||
}
|
||||
|
||||
/* Import from other apps: a checklist per app */
|
||||
|
||||
@@ -319,6 +319,13 @@ const I18N = {
|
||||
"Only these models: {list}": "仅限这些模型:{list}",
|
||||
"Any model, now and later": "任何模型,包括以后添加的",
|
||||
"Any model and any account, now and later": "任何模型和任何账号,包括以后添加的",
|
||||
"Quotas": "额度",
|
||||
"Quotas shown": "可看额度",
|
||||
"This key is told the quotas of the providers whose every model it may use, and of the accounts it may use, account names included. Click to stop.": "这个密钥能看到它可用全部模型的供应商、以及它可用账号的额度,包括账号名称。点击即可关闭。",
|
||||
"A key held to a budget, models or accounts is told no quotas. Click to tell it the quotas of the providers whose every model it may use, and of the accounts it may use, account names included.": "限定了额度、模型或账号的密钥看不到任何额度。点击后,它能看到可用全部模型的供应商、以及它可用账号的额度,包括账号名称。",
|
||||
"Show this key its quotas": "让这个密钥查看额度",
|
||||
"{name} is told no quotas": "{name} 看不到额度了",
|
||||
"{name} is told the quotas of what it may use": "{name} 现在能看到它可用部分的额度",
|
||||
"Only these accounts: {list}": "仅限这些账号:{list}",
|
||||
"Used: no {provider} account is picked": "会被使用:{provider} 没有勾选任何账号",
|
||||
"A provider with no account picked is used on every account; to keep the key off it, pick only other providers' models": "没勾选任何账号的供应商,它的所有账号都可用;要让此密钥用不了它,请只勾选其他供应商的模型",
|
||||
@@ -3880,6 +3887,13 @@ const I18N = {
|
||||
"Only these models: {list}": "僅限這些模型:{list}",
|
||||
"Any model, now and later": "任何模型,包括以後新增的",
|
||||
"Any model and any account, now and later": "任何模型和任何帳號,包括以後新增的",
|
||||
"Quotas": "額度",
|
||||
"Quotas shown": "可看額度",
|
||||
"This key is told the quotas of the providers whose every model it may use, and of the accounts it may use, account names included. Click to stop.": "這個金鑰能看到它可用全部模型的供應商、以及它可用帳號的額度,包括帳號名稱。點擊即可關閉。",
|
||||
"A key held to a budget, models or accounts is told no quotas. Click to tell it the quotas of the providers whose every model it may use, and of the accounts it may use, account names included.": "限定了額度、模型或帳號的金鑰看不到任何額度。點擊後,它能看到可用全部模型的供應商、以及它可用帳號的額度,包括帳號名稱。",
|
||||
"Show this key its quotas": "讓這個金鑰查看額度",
|
||||
"{name} is told no quotas": "{name} 看不到額度了",
|
||||
"{name} is told the quotas of what it may use": "{name} 現在能看到它可用部分的額度",
|
||||
"Only these accounts: {list}": "僅限這些帳號:{list}",
|
||||
"Used: no {provider} account is picked": "會被使用:{provider} 沒有勾選任何帳號",
|
||||
"A provider with no account picked is used on every account; to keep the key off it, pick only other providers' models": "沒勾選任何帳號的供應商,它的所有帳號都可用;要讓此金鑰用不了它,請只勾選其他供應商的模型",
|
||||
@@ -7403,6 +7417,13 @@ const I18N = {
|
||||
"Only these models: {list}": "これらのモデルのみ:{list}",
|
||||
"Any model, now and later": "今後追加されるものも含め、すべてのモデル",
|
||||
"Any model and any account, now and later": "今後追加されるものも含め、すべてのモデルとアカウント",
|
||||
"Quotas": "残量",
|
||||
"Quotas shown": "残量を表示",
|
||||
"This key is told the quotas of the providers whose every model it may use, and of the accounts it may use, account names included. Click to stop.": "このキーには、すべてのモデルを使えるプロバイダーと、使えるアカウントの残量が、アカウント名も含めて見えます。クリックで止めます。",
|
||||
"A key held to a budget, models or accounts is told no quotas. Click to tell it the quotas of the providers whose every model it may use, and of the accounts it may use, account names included.": "予算・モデル・アカウントを限定したキーには残量が見えません。クリックすると、すべてのモデルを使えるプロバイダーと、使えるアカウントの残量が、アカウント名も含めて見えるようになります。",
|
||||
"Show this key its quotas": "このキーに残量を見せる",
|
||||
"{name} is told no quotas": "{name} には残量が見えなくなりました",
|
||||
"{name} is told the quotas of what it may use": "{name} に使える分の残量が見えるようになりました",
|
||||
"Only these accounts: {list}": "これらのアカウントのみ:{list}",
|
||||
"Used: no {provider} account is picked": "使われます:{provider} のアカウントが一つも選ばれていません",
|
||||
"A provider with no account picked is used on every account; to keep the key off it, pick only other providers' models": "アカウントを一つも選んでいないプロバイダーは、すべてのアカウントで使われます。このキーで使わせないには、ほかのプロバイダーのモデルだけを選んでください",
|
||||
@@ -10943,6 +10964,13 @@ const I18N = {
|
||||
"Only these models: {list}": "Nur diese Modelle: {list}",
|
||||
"Any model, now and later": "Jedes Modell, auch künftige",
|
||||
"Any model and any account, now and later": "Jedes Modell und jedes Konto, auch künftige",
|
||||
"Quotas": "Kontingente",
|
||||
"Quotas shown": "Kontingente sichtbar",
|
||||
"This key is told the quotas of the providers whose every model it may use, and of the accounts it may use, account names included. Click to stop.": "Dieser Schlüssel sieht die Kontingente der Anbieter, deren Modelle er alle nutzen darf, und der Konten, die er nutzen darf, samt Kontonamen. Klicken zum Beenden.",
|
||||
"A key held to a budget, models or accounts is told no quotas. Click to tell it the quotas of the providers whose every model it may use, and of the accounts it may use, account names included.": "Ein auf Budget, Modelle oder Konten beschränkter Schlüssel sieht keine Kontingente. Klicken, damit er die Kontingente der Anbieter, deren Modelle er alle nutzen darf, und der Konten, die er nutzen darf, samt Kontonamen sieht.",
|
||||
"Show this key its quotas": "Diesem Schlüssel seine Kontingente zeigen",
|
||||
"{name} is told no quotas": "{name} sieht keine Kontingente mehr",
|
||||
"{name} is told the quotas of what it may use": "{name} sieht jetzt die Kontingente dessen, was er nutzen darf",
|
||||
"Only these accounts: {list}": "Nur diese Konten: {list}",
|
||||
"Used: no {provider} account is picked": "Wird genutzt: kein {provider}-Konto ist ausgewählt",
|
||||
"A provider with no account picked is used on every account; to keep the key off it, pick only other providers' models": "Ein Anbieter ohne ausgewähltes Konto wird mit jedem seiner Konten genutzt; um den Schlüssel davon fernzuhalten, wähle nur Modelle anderer Anbieter",
|
||||
|
||||
@@ -181,7 +181,7 @@ function renderGatewayKeys() {
|
||||
rm.onclick = () => askGatewayKey(k, false);
|
||||
const rotate = el("button", "text quiet", t("Rotate key"));
|
||||
rotate.onclick = () => askGatewayKey(k, true);
|
||||
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), el("span", "grow"), gatewayModelsBadge(k), gatewayLimitBadge(k), copyCallerKeyBtn(k), rotate, rm);
|
||||
row.append(tick, gatewayRename(k), el("span", "plan mono", k.masked), el("span", "grow"), gatewayModelsBadge(k), gatewayQuotasBadge(k), gatewayLimitBadge(k), copyCallerKeyBtn(k), rotate, rm);
|
||||
const under = gatewayLimit?.id === k.id ? [gatewayLimitEditor(k)] : keyUsed(k).map((u) => gatewayLimitLine(k, u));
|
||||
if (under.length) row.classList.add("with-limit"), row.append(...under);
|
||||
list.append(row);
|
||||
@@ -340,6 +340,30 @@ function gatewayModelsBadge(k) {
|
||||
return b;
|
||||
}
|
||||
|
||||
// ---- the quotas a gateway key is told (#2216) ----
|
||||
|
||||
// gatewayQuotasBadge turns on or off a key's being told the quotas of what
|
||||
// it may use: a key held to a budget, models or accounts is told none of
|
||||
// this magpie's quotas (#1981) unless it is on, and then only the cards of
|
||||
// the providers whose every model it may use, of the accounts it may use.
|
||||
// "Quotas" on hover when off, "Quotas shown" always when on.
|
||||
function gatewayQuotasBadge(k) {
|
||||
const b = el("button", "amodels key-quotas" + (k.quotas ? " set" : ""));
|
||||
b.type = "button";
|
||||
b.textContent = t(k.quotas ? "Quotas shown" : "Quotas");
|
||||
b.title = t(k.quotas
|
||||
? "This key is told the quotas of the providers whose every model it may use, and of the accounts it may use, account names included. Click to stop."
|
||||
: "A key held to a budget, models or accounts is told no quotas. Click to tell it the quotas of the providers whose every model it may use, and of the accounts it may use, account names included.");
|
||||
b.setAttribute("aria-label", t("Show this key its quotas"));
|
||||
b.setAttribute("aria-pressed", k.quotas ? "true" : "false");
|
||||
b.onclick = async (e) => {
|
||||
e.preventDefault();
|
||||
const out = await gatewayKeyAction("quotas-key", { key: k.id, quotas: !k.quotas });
|
||||
if (out) status(t(k.quotas ? "{name} is told no quotas" : "{name} is told the quotas of what it may use", { name: k.name }), "ok");
|
||||
};
|
||||
return b;
|
||||
}
|
||||
|
||||
// ---- a gateway key's own limit (#585) ----
|
||||
|
||||
// "days" is every N days from when the limit is set or reset (#1509),
|
||||
|
||||
+1
@@ -157,6 +157,7 @@ function fixture(lang, theme, events, options = {}) {
|
||||
}
|
||||
if (action === "models-key") k.models = body.models?.length ? body.models : undefined;
|
||||
if (action === "accounts-key") k.accounts = body.accounts?.length ? body.accounts : undefined;
|
||||
if (action === "quotas-key") k.quotas = body.quotas || undefined;
|
||||
if (action === "copy-key") secret = k.id === lanKeyID ? lanSecret : secrets.get(k.id);
|
||||
return json({ keys, secret });
|
||||
}
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
// A gateway key held to a budget, models or accounts is told no quotas
|
||||
// (#1981) unless its owner lets it be told those of what it may use
|
||||
// (#2216, Kenoia): a "Quotas" badge on the key's row, shown on hover while
|
||||
// off and always while on, sends "quotas-key".
|
||||
const assert = require("node:assert/strict");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { fixture } = require("./fixtures/caller-keys.cjs");
|
||||
|
||||
const words = {
|
||||
en: { label: "Show this key its quotas", off: "Quotas", on: "Quotas shown" },
|
||||
zh: { label: "让这个密钥查看额度", off: "额度", on: "可看额度" },
|
||||
"zh-TW": { label: "讓這個金鑰查看額度", off: "額度", on: "可看額度" },
|
||||
ja: { label: "このキーに残量を見せる", off: "残量", on: "残量を表示" },
|
||||
de: { label: "Diesem Schlüssel seine Kontingente zeigen", off: "Kontingente", on: "Kontingente sichtbar" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const width of [1100, 420]) {
|
||||
for (const [lang, w] of Object.entries(words)) {
|
||||
test(`${engine} ${width} ${lang}: a held key is let see its quotas`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const page = await (await browser.newContext({ viewport: { width, height: 700 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(6000);
|
||||
const events = [], errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", fixture(lang, "light", events, { lan: true, keyHolds: { server: { models: ["relay/*"], quotas: true }, work: { models: ["relay/*"] } } }));
|
||||
await page.goto("http://magpie.test/?view=gateway");
|
||||
await page.locator("#gatewayKeys .acc[data-key]").last().waitFor();
|
||||
const row = (id) => page.locator(`#gatewayKeys .acc[data-key="${id}"]`);
|
||||
const badge = (id) => row(id).getByRole("button", { name: w.label, exact: true });
|
||||
// on: said always, not only on hover
|
||||
await page.mouse.move(0, 0);
|
||||
assert.equal((await badge("server").textContent()).trim(), w.on);
|
||||
assert.equal(await badge("server").getAttribute("aria-pressed"), "true");
|
||||
assert.equal(await badge("server").evaluate((b) => getComputedStyle(b).opacity), "1");
|
||||
assert.ok((await badge("server").boundingBox()).width > 0, "an on badge is hidden");
|
||||
// off: on hover only
|
||||
assert.equal(await badge("work").getAttribute("aria-pressed"), "false");
|
||||
assert.equal(await badge("work").evaluate((b) => getComputedStyle(b).opacity), "0");
|
||||
const view = page.locator("#view-gateway");
|
||||
const scrolled = async () => [await view.evaluate((v) => v.scrollTop), await page.evaluate(() => window.scrollY)];
|
||||
const before = await scrolled();
|
||||
await row("work").hover();
|
||||
assert.equal((await badge("work").textContent()).trim(), w.off);
|
||||
await badge("work").click();
|
||||
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="work"] .key-quotas')?.getAttribute("aria-pressed") === "true");
|
||||
assert.deepEqual(events.filter((e) => e.action === "quotas-key").map((e) => e.body), [{ key: "work", quotas: true }]);
|
||||
assert.equal((await badge("work").textContent()).trim(), w.on);
|
||||
await row("server").hover();
|
||||
await badge("server").click();
|
||||
await page.waitForFunction(() => document.querySelector('#gatewayKeys .acc[data-key="server"] .key-quotas')?.getAttribute("aria-pressed") === "false");
|
||||
assert.deepEqual(events.filter((e) => e.action === "quotas-key").at(-1).body, { key: "server", quotas: false });
|
||||
assert.deepEqual(await scrolled(), before, "a click moved the page");
|
||||
// the row still fits: nothing runs past the window's edge
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert.ok(over <= 0, `the page scrolls sideways by ${over}px`);
|
||||
const rowBox = await row("server").boundingBox(), b = await badge("server").boundingBox();
|
||||
await row("server").hover();
|
||||
assert.ok(b.x >= rowBox.x && b.x + b.width <= rowBox.x + rowBox.width + 1, "the badge runs out of its row");
|
||||
assert.equal(await page.locator("select").count(), 0, "no native select");
|
||||
const lefts = await page.locator("#gatewayKeys .key-quotas").evaluateAll((els) => els.map((e) => getComputedStyle(e).borderLeftStyle));
|
||||
assert(lefts.every((s) => s === "none"), "a coloured left border");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"</
|
||||
<p><code>GET /v1/models</code> lists what the user has turned on: <code>id</code> (<code>provider/model</code>, or a routing group’s name, sent as it is), <code>display_name</code>, <code>owned_by</code> (the provider), <code>reasoning</code> and <code>supported_reasoning_levels</code> (<code>[{"effort":"low"},…]</code>), <code>context_window</code> and <code>max_output_tokens</code> when known, and <code>modalities</code> when magpie knows whether it takes images. List them from there rather than shipping a list: the user adds and removes providers in magpie. Reasoning is asked in your API’s own field (<code>reasoning_effort</code>, <code>reasoning.effort</code>, Anthropic’s <code>thinking</code> or <code>output_config.effort</code>). <code>?format=text</code> gives the ids one a line.</p>
|
||||
|
||||
<h3>Optional</h3>
|
||||
<p>Send <code>X-Magpie-Session: <id></code> with a conversation’s requests and <code>GET /v1/magpie/route?session=<id></code> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with <code>after=<seq>&wait=<s></code>). <code>GET /v1/magpie/quotas</code> lists the user’s subscription allowances, and <code>GET /v1/magpie/usage</code> and <code>/v1/magpie/usage/requests</code> the Usage page’s numbers and its requests (with <code>session</code>, and <code>subagent</code>/<code>parent_agent</code> for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls and routes alone, and is refused the quotas (its own limit is <code>GET /v1/magpie/limit</code>). Calls your app makes to its vendor itself can be reported with <code>POST /v1/magpie/usage/requests</code> (one record or up to 5000 a post, in <code>usage.jsonl</code>’s shape, each with a <code>rid</code>; past times are kept, so a history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">reference</a> has the details.</p>
|
||||
<p>Send <code>X-Magpie-Session: <id></code> with a conversation’s requests and <code>GET /v1/magpie/route?session=<id></code> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with <code>after=<seq>&wait=<s></code>). <code>GET /v1/magpie/quotas</code> lists the user’s subscription allowances, and <code>GET /v1/magpie/usage</code> and <code>/v1/magpie/usage/requests</code> the Usage page’s numbers and its requests (with <code>session</code>, and <code>subagent</code>/<code>parent_agent</code> for a Claude Code subagent’s call). They answer only this machine, or another with a gateway key; a key held to a budget, models or accounts sees its own calls and routes alone, and is refused the quotas unless its owner lets it see those of what it may use (<code>magpie gateway-key quotas <id> on</code>; its own limit is <code>GET /v1/magpie/limit</code>). Calls your app makes to its vendor itself can be reported with <code>POST /v1/magpie/usage/requests</code> (one record or up to 5000 a post, in <code>usage.jsonl</code>’s shape, each with a <code>rid</code>; past times are kept, so a history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The <a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">reference</a> has the details.</p>
|
||||
|
||||
<div class="callout"><b>Keep the user’s providers.</b> Add magpie as one more provider (named Magpie) beside the ones the user set up in your app, rather than replacing them, so turning magpie off is picking another provider.</div>
|
||||
|
||||
|
||||
@@ -117,7 +117,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"</
|
||||
<p><code>GET /v1/models</code> 列出用户打开的模型:<code>id</code>(<code>provider/model</code>,或路由组的名字,原样发送即可)、<code>display_name</code>、<code>owned_by</code>(供应商)、<code>reasoning</code> 与 <code>supported_reasoning_levels</code>(<code>[{"effort":"low"},…]</code>),已知时还有 <code>context_window</code>、<code>max_output_tokens</code>,以及 magpie 知道是否支持图片时的 <code>modalities</code>。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(<code>reasoning_effort</code>、<code>reasoning.effort</code>、Anthropic 的 <code>thinking</code> 或 <code>output_config.effort</code>)。<code>?format=text</code> 每行一个 id。</p>
|
||||
|
||||
<h3>可选</h3>
|
||||
<p>在同一会话的请求里带上 <code>X-Magpie-Session: <id></code>,<code>GET /v1/magpie/route?session=<id></code> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 <code>after=<seq>&wait=<s></code> 长轮询)。<code>GET /v1/magpie/quotas</code> 列出用户各订阅的额度,<code>GET /v1/magpie/usage</code> 和 <code>/v1/magpie/usage/requests</code> 给出用量页的统计和逐条请求(带 <code>session</code>;Claude Code 子代理的调用还有 <code>subagent</code>/<code>parent_agent</code>)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用和路由,额度一律不告诉它(它自己的限额见 <code>GET /v1/magpie/limit</code>)。你的应用直接发给厂商、不经过 magpie 的调用,可以用 <code>POST /v1/magpie/usage/requests</code> 上报(每次一条,或最多 5000 条,格式同 <code>usage.jsonl</code> 的一行,每条带 <code>rid</code>;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">参考文档</a>。</p>
|
||||
<p>在同一会话的请求里带上 <code>X-Magpie-Session: <id></code>,<code>GET /v1/magpie/route?session=<id></code> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 <code>after=<seq>&wait=<s></code> 长轮询)。<code>GET /v1/magpie/quotas</code> 列出用户各订阅的额度,<code>GET /v1/magpie/usage</code> 和 <code>/v1/magpie/usage/requests</code> 给出用量页的统计和逐条请求(带 <code>session</code>;Claude Code 子代理的调用还有 <code>subagent</code>/<code>parent_agent</code>)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用和路由,额度不告诉它,除非它的主人允许它看自己可用部分的额度(<code>magpie gateway-key quotas <id> on</code>;它自己的限额见 <code>GET /v1/magpie/limit</code>)。你的应用直接发给厂商、不经过 magpie 的调用,可以用 <code>POST /v1/magpie/usage/requests</code> 上报(每次一条,或最多 5000 条,格式同 <code>usage.jsonl</code> 的一行,每条带 <code>rid</code>;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见<a href="https://github.com/yetone/magpie/blob/main/docs/reference.md#connecting-anything-else">参考文档</a>。</p>
|
||||
|
||||
<div class="callout"><b>保留用户自己的供应商。</b>把 magpie 作为又一个供应商(名为 Magpie)加在用户已有的供应商旁边,而不是替换它们,这样关掉 magpie 就只是换选另一个供应商。</div>
|
||||
|
||||
|
||||
Reference in New Issue
Block a user