gateway: a gateway key held to a budget, models or accounts is told none of this magpie's accounts, only its own limit and routes (#1981)
321sssrt-bit shared magpie on the LAN with a gateway key held to a budget, and that key still read every account's quota and balance. A held key (heldKey: a budget, models or accounts) is someone else's to use, so it now gets 403 with code gateway_key_held (refuseHeld) on /v1/magpie/quotas, quotas/history, quotas/cards, POST quotas/refresh and /v1/magpie/concurrency. That holds from loopback as well as the LAN, the same as usageSummary already did. /v1/magpie/route tells it only the routes of its own requests. Route.callerKey is set by trace.beginFor at all five begin sites, so a route begun without it fails closed. It still reads its own limit at /v1/magpie/limit. Unrestricted keys and the local owner are unchanged. Client side (remote magpie): a 403 gateway_key_held drops the cards kept from before and shows only the key's own card, instead of "isn't shared". The cache is now keyed by provider and key (remoteCardsID), so a changed key never shows what the old one was told, and keepRemoteCards keeps a read only over one asked before it, so a slow pre-held answer can't bring cards back. Decided against letting an account-held key see its own accounts' cards: that would still show the host's account email and balance to the key's holder. Run: - New TestHeldKeyToldNoAccounts covers keys held by budget, models and accounts plus one held to nothing, from 127.0.0.1 and 192.168.1.9. Every route goes red with the refuseHeld calls or the route filter removed by hand. - New TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard goes red with the errKeyHeld mapping removed. TestRemoteMagpieCardsKeptByKey goes red with the cache keyed by p.ID alone. - gofmt -l and go vet (darwin, linux -tags nogui, windows) are clean. - go test -tags nogui ./internal/gateway ./internal/provider -count=1 passes in a sandbox HOME. Not tried: two real machines over the LAN; the tests drive the handler with LAN remote addresses. An older client shows "isn't shared" (or its cached cards until they expire) against an updated host until it updates too.
This commit is contained in:
+3
-1
@@ -70,7 +70,9 @@ user's subscription allowances, and `GET /v1/magpie/usage` and
|
||||
`/v1/magpie/usage/requests` the Usage page's numbers and its requests
|
||||
(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 alone.
|
||||
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`).
|
||||
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
|
||||
|
||||
+11
-1
@@ -1608,7 +1608,9 @@ decided, before the vendor is asked. `after=<seq>&wait=<seconds>` (up to 60)
|
||||
holds the answer until the route changes past the `seq` of the last one,
|
||||
so a UI can follow a turn with one request at a time. Only the session
|
||||
named is told; like `/v1/magpie/quotas`, it answers this machine, and
|
||||
another only with the key of a gateway shared on the local network.
|
||||
another only with the key of a gateway shared on the local network. A key
|
||||
held to a budget, to some models or to some accounts is told the routes of
|
||||
its own requests alone: another key's session answers `route: null`.
|
||||
|
||||
To show the one in use without a session, `GET /v1/magpie/quotas` (and
|
||||
`magpie quota --json`, the same list) has `lastServedAt` on each
|
||||
@@ -1616,6 +1618,14 @@ subscription account, plan and key that answered a request through the
|
||||
gateway in the last 30 days, and `last: true` on the latest. It is kept
|
||||
in `served.json` beside `providers.json`, so a restart keeps it.
|
||||
|
||||
A gateway key held to a budget, to some models or to some accounts is told
|
||||
none of this magpie's accounts (#1981): `/v1/magpie/quotas`,
|
||||
`/v1/magpie/quotas/history`, `/v1/magpie/quotas/cards`,
|
||||
`POST /v1/magpie/quotas/refresh` and `/v1/magpie/concurrency` answer it
|
||||
403 with `"code": "gateway_key_held"`, from this machine or another. It
|
||||
reads its own limit from `GET /v1/magpie/limit`. Another magpie that uses
|
||||
such a key shows only that key's own card.
|
||||
|
||||
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
|
||||
|
||||
@@ -235,6 +235,13 @@ summary and gets the ledger filtered to its own `CallerKey`, with its filter
|
||||
lists cut to its own rows (`usageapi.OwnPage`): the ledger's facets are drawn
|
||||
from every call in the period, so without the cut they would name other keys.
|
||||
`TestUsageOverGateway` covers both, and a red when either cut is removed.
|
||||
A held key is refused (`refuseHeld`, 403 `provider.KeyHeldCode`) the
|
||||
quotas, their history, kept cards and refresh, and `/v1/magpie/concurrency`
|
||||
(#1981); `/v1/magpie/route` tells it only routes whose `callerKey` is its
|
||||
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.
|
||||
|
||||
### Calls read from the agents' own files
|
||||
|
||||
|
||||
@@ -36,7 +36,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. 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`). 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. 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) |
|
||||
| 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) |
|
||||
| A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) and of Xiaomi MiMo's Token Plans (`xiaomi-token-plan-cn`, `-sgp`, `-ams`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Xiaomi MiMo model is priced at `xiaomi`'s list price at every region, and each region of the preset names its own catalog, pay as you go `xiaomi` alone (#1873). A Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone (`kimiCodePlans`): a relay's own `k3` keeps its own price. A catalog other than these that lists a model at $0 still prices it at $0: models.dev has truly free models (nvidia, modelscope). The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) |
|
||||
|
||||
@@ -714,7 +714,7 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
|
||||
captureTitle = link != nil && isTitleKind(kind)
|
||||
turn, scan := agentTurnOf(r, kind)
|
||||
tools = scan
|
||||
tr = s.trace.begin(Route{turn: turn, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: bodyTier(provider.Responses, body), Provider: "openai", Subagent: subagentPickOf(r),
|
||||
tr = s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(provider.Responses, body), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, callerOf(r).agent), imageProvider: imageProvider, TitleLink: link, Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, kind), Kind: kind, Model: model, Effort: effort, Tier: bodyTier(provider.Responses, body), Provider: "openai", Subagent: subagentPickOf(r),
|
||||
Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Effort: effort, Start: start}}})
|
||||
promptRead := s.inspectPrompt(tr, provider.Responses, body, body)
|
||||
end = func(status int, msg string, tokens, out int) {
|
||||
|
||||
@@ -400,7 +400,7 @@ func (s *Server) sentNowhere(w http.ResponseWriter, r *http.Request, body []byte
|
||||
kind := requestCallKind(r.Header, metadata)
|
||||
model := modelOf(body)
|
||||
seat := Weighed{ID: "magpie", Provider: "magpie", Name: "magpie", Who: who, Kind: "provider", Model: model}
|
||||
tr := s.trace.begin(Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), ParentSession: titleParentSession(r.Header, metadata, kind),
|
||||
tr := s.trace.beginFor(r, Route{Time: start, Agent: agentOf(r), Session: sessionOf(r.Header), ParentSession: titleParentSession(r.Header, metadata, kind),
|
||||
Kind: kind, Model: model, Provider: "magpie", Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}})
|
||||
writeTitleReply(w, fmt.Sprintf("resp_magpie_%d", start.UnixNano()), out, nil)
|
||||
ms := time.Since(start).Milliseconds()
|
||||
|
||||
@@ -239,6 +239,9 @@ func (s *Server) concurrency(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's concurrency is told to another machine only when magpie is shared on the local network and the request carries its API key")
|
||||
return
|
||||
}
|
||||
if refuseHeld(w, r, heldRefused) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "concurrency", "data": s.Lanes()})
|
||||
}
|
||||
|
||||
|
||||
@@ -490,7 +490,7 @@ func (s *Server) serveSystemOne(w http.ResponseWriter, r *http.Request) {
|
||||
seat := decideSeat(p, model)
|
||||
var used Usage
|
||||
who := callerOf(r)
|
||||
tr := s.trace.begin(Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: p.ID,
|
||||
tr := s.trace.beginFor(r, Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: p.ID,
|
||||
Order: []Weighed{seat}, Tries: []Try{{ID: seat.ID, Model: model, Start: start}}})
|
||||
end := func(status int, msg string, tokens int) {
|
||||
ms := time.Since(start).Milliseconds()
|
||||
|
||||
@@ -130,7 +130,7 @@ func (s *Server) serveDecisionGroup(w http.ResponseWriter, r *http.Request, body
|
||||
return
|
||||
}
|
||||
who := callerOf(r)
|
||||
tr := s.trace.begin(Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: cs[0].p.ID,
|
||||
tr := s.trace.beginFor(r, Route{Time: start, Agent: who.agent, Session: sessionOf(r.Header), Model: asked, Provider: cs[0].p.ID,
|
||||
Group: groupRef(g, ms), Order: pl.order, Left: pl.left})
|
||||
var skipped []string
|
||||
for i, c := range cs {
|
||||
|
||||
@@ -612,12 +612,17 @@ func (s *Server) info(w http.ResponseWriter, r *http.Request) {
|
||||
// same). It names the accounts and their balances, so it answers this
|
||||
// machine, and another only with an enabled gateway key, which lanGuard
|
||||
// asks of it while the gateway is shared or MAGPIE_ADDR puts it on the
|
||||
// network.
|
||||
// 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.
|
||||
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) {
|
||||
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())})
|
||||
@@ -632,6 +637,9 @@ 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) {
|
||||
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"))})
|
||||
}
|
||||
@@ -644,6 +652,9 @@ 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) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"object": "list", "data": provider.CachedCards(time.Now())})
|
||||
}
|
||||
|
||||
@@ -666,6 +677,9 @@ 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) {
|
||||
return
|
||||
}
|
||||
id, user := r.URL.Query().Get("provider"), r.URL.Query().Get("user")
|
||||
if strings.Contains(id, "/") || provider.IsRemoteCard(id) { // a card this magpie has from another: not passed on
|
||||
writeError(w, provider.Chat, http.StatusBadRequest, "this magpie reads only its own cards again")
|
||||
@@ -1938,7 +1952,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
capture.tools = tools
|
||||
}
|
||||
tierAsked := bodyTier(from, body) // the service tier the client asked for (#1784)
|
||||
tr := s.trace.begin(Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, Affinity: shown, Order: pl.order, Left: pl.left})
|
||||
tr := s.trace.beginFor(r, Route{turn: turn, dirOf: dirOf(from, plain), tools: tools, imageTurn: drawingTurnID(metadata.Turn), imageCaller: codexTurnKey(r, call.Agent), TitleLink: link, Pinned: pin, Time: start, Agent: call.Agent, Session: sessionOf(r.Header), Conv: convOf(r.Header, body), ParentSession: titleParentSession(r.Header, metadata, call.Kind), Kind: call.Kind, For: call.For, Model: call.Model, Effort: requestEffort(from, body), Tier: tierAsked, Provider: p.ID, Group: group, Rule: hit, Nested: nested, SealedTask: sealedTask, LeadAccount: leadAccount, Subagent: subagent, Affinity: shown, Order: pl.order, Left: pl.left})
|
||||
if telemetry != nil {
|
||||
telemetry.routeID = tr.ID
|
||||
}
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// #1981 (321sssrt-bit): magpie shared on the local network with a gateway
|
||||
// key held to a budget, models or accounts, and that key still read every
|
||||
// account's quota and balance from /v1/magpie/quotas. A held key is
|
||||
// someone else's to use: it is told none of this magpie's accounts, from
|
||||
// this computer or another, only its own limit and the routes of its own
|
||||
// requests. A key held to nothing is told what it was told before.
|
||||
func TestHeldKeyToldNoAccounts(t *testing.T) {
|
||||
fresh(t)
|
||||
t.Setenv("MAGPIE_ADDR", "")
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}],"usage":{"prompt_tokens":30,"completion_tokens":5}}`)
|
||||
}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "plan", Name: "Plan", Key: "upstream-secret", Chat: up.URL + "/v1", Models: []string{"m1"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys, secrets := newCaller(t, "Owner", "Budget", "Models", "Accounts")
|
||||
if _, err := access.Update("limit-key", access.Change{Key: keys[1].ID, Limit: &access.Limit{Period: "day", Tokens: 1_000_000}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := access.Update("models-key", access.Change{Key: keys[2].ID, Models: []string{"plan/*"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := provider.Find("plan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
as := p.AccountIDs()
|
||||
if len(as) == 0 {
|
||||
t.Fatal("no account to hold a key to")
|
||||
}
|
||||
if _, err := access.Update("accounts-key", access.Change{Key: keys[3].ID, Accounts: []string{"plan/" + as[0].ID}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := lanGuard(New().Handler())
|
||||
do := func(method, path, from, secret string, hdr ...string) (int, string) {
|
||||
var body io.Reader
|
||||
if method == "POST" && strings.HasPrefix(path, "/v1/chat") {
|
||||
body = strings.NewReader(chatReq)
|
||||
}
|
||||
r := httptest.NewRequest(method, path, body)
|
||||
r.RemoteAddr = from
|
||||
r.Header.Set("Authorization", "Bearer "+secret)
|
||||
for i := 0; i+1 < len(hdr); i += 2 {
|
||||
r.Header.Set(hdr[i], hdr[i+1])
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w.Code, w.Body.String()
|
||||
}
|
||||
// each key makes a request in a session of its own
|
||||
for i, s := range secrets {
|
||||
if c, b := do("POST", "/v1/chat/completions", "192.168.1.9:5000", s, SessionHeader, "sess-"+keys[i].Name); c != 200 {
|
||||
t.Fatal(keys[i].Name, c, b)
|
||||
}
|
||||
}
|
||||
told := []struct{ method, path string }{
|
||||
{"GET", "/v1/magpie/quotas"},
|
||||
{"GET", "/v1/magpie/quotas/history"},
|
||||
{"GET", provider.RemoteCardsPath},
|
||||
{"POST", provider.RemoteRefreshPath},
|
||||
{"GET", "/v1/magpie/concurrency"},
|
||||
}
|
||||
route := func(from, secret, session string) any {
|
||||
t.Helper()
|
||||
c, b := do("GET", "/v1/magpie/route?session="+session, from, secret)
|
||||
var out map[string]any
|
||||
if c != 200 || json.Unmarshal([]byte(b), &out) != nil {
|
||||
t.Fatal("route:", c, b)
|
||||
}
|
||||
return out["route"]
|
||||
}
|
||||
for _, from := range []string{"127.0.0.1:5000", "192.168.1.9:5000"} {
|
||||
for i, s := range secrets {
|
||||
name := keys[i].Name
|
||||
for _, x := range told {
|
||||
c, b := do(x.method, x.path, from, s)
|
||||
if i == 0 {
|
||||
if c != 200 {
|
||||
t.Errorf("%s from %s, a key held to nothing: %s %s: %d %s", name, from, x.method, x.path, c, b)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if c != http.StatusForbidden || !strings.Contains(b, provider.KeyHeldCode) || strings.Contains(b, "upstream") {
|
||||
t.Errorf("%s from %s: %s %s: %d %s", name, from, x.method, x.path, c, b)
|
||||
}
|
||||
}
|
||||
if c, b := do("GET", "/v1/magpie/limit", from, s); c != 200 {
|
||||
t.Errorf("%s from %s: its own limit: %d %s", name, from, c, b)
|
||||
}
|
||||
if route(from, s, "sess-"+name) == nil {
|
||||
t.Errorf("%s from %s: no route for its own session", name, from)
|
||||
}
|
||||
other := "sess-" + keys[(i+1)%len(keys)].Name
|
||||
if r := route(from, s, other); (i == 0) != (r != nil) {
|
||||
t.Errorf("%s from %s: another key's session %s: %v", name, from, other, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -98,7 +99,9 @@ func sessionRouteOf(r Route) SessionRoute {
|
||||
// session's latest route, null before it has one. With after=<seq> and
|
||||
// wait=<seconds> it waits, up to a minute, for the route to change past
|
||||
// seq. Like the quotas, it answers this machine, and another only with the
|
||||
// shared gateway's key.
|
||||
// shared gateway's key. A key held to a budget, models or accounts is told
|
||||
// only the routes of its own requests (#1981): a session id is not a
|
||||
// secret the key can be trusted to lack.
|
||||
func (s *Server) sessionRoute(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "magpie's routes 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>)")
|
||||
@@ -119,7 +122,11 @@ func (s *Server) sessionRoute(w http.ResponseWriter, r *http.Request) {
|
||||
after, _ := strconv.ParseInt(q.Get("after"), 10, 64)
|
||||
secs, _ := strconv.ParseFloat(q.Get("wait"), 64)
|
||||
wait := min(time.Duration(secs*float64(time.Second)), routeWaitMax)
|
||||
seq, route := s.trace.sessionLatest(r.Context(), session, after, wait)
|
||||
only := ""
|
||||
if who := access.Caller(r.Context()); heldKey(who) {
|
||||
only = who.KeyID
|
||||
}
|
||||
seq, route := s.trace.sessionLatest(r.Context(), session, only, after, wait)
|
||||
out := map[string]any{"session": session, "seq": seq, "route": nil}
|
||||
if route != nil {
|
||||
out["route"] = sessionRouteOf(*route)
|
||||
@@ -128,8 +135,9 @@ func (s *Server) sessionRoute(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// sessionLatest is a copy of session's latest route, and its seq; with
|
||||
// wait, it waits up to that long for it to change past after.
|
||||
func (t *trace) sessionLatest(ctx context.Context, session string, after int64, wait time.Duration) (int64, *Route) {
|
||||
// wait, it waits up to that long for it to change past after. With only
|
||||
// set, the routes of the requests made with that gateway key alone.
|
||||
func (t *trace) sessionLatest(ctx context.Context, session, only string, after int64, wait time.Duration) (int64, *Route) {
|
||||
deadline := time.NewTimer(max(wait, 0))
|
||||
defer deadline.Stop()
|
||||
for {
|
||||
@@ -137,7 +145,7 @@ func (t *trace) sessionLatest(ctx context.Context, session string, after int64,
|
||||
var seq int64
|
||||
var found *Route
|
||||
for i := len(t.routes) - 1; i >= 0; i-- {
|
||||
if r := t.routes[i]; r.Session == session {
|
||||
if r := t.routes[i]; r.Session == session && (only == "" || r.callerKey == only) {
|
||||
c := *r
|
||||
c.Order = append([]Weighed{}, r.Order...) // [] for none: the GUI reads it as a list
|
||||
c.Left = append([]Weighed(nil), r.Left...)
|
||||
|
||||
@@ -10,11 +10,13 @@ package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/access"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
@@ -24,6 +26,10 @@ const traceKeep = 60
|
||||
|
||||
// Route is one request's way through routing.
|
||||
type Route struct {
|
||||
// callerKey: the gateway key the request came with, so a key held to
|
||||
// a budget, models or accounts is told the routes of its own requests
|
||||
// alone (sessionLatest, #1981)
|
||||
callerKey string
|
||||
imageTurn string
|
||||
imageCaller string
|
||||
imageProvider string
|
||||
@@ -428,6 +434,14 @@ func (t *trace) changed() {
|
||||
}
|
||||
}
|
||||
|
||||
// beginFor begins req's route, marked with the gateway key req came with.
|
||||
// Every route of a request begins here, so a held key's own routes are
|
||||
// told it: one begun without (begin alone) is told to no held key.
|
||||
func (t *trace) beginFor(req *http.Request, r Route) *Route {
|
||||
r.callerKey = access.Caller(req.Context()).KeyID
|
||||
return t.begin(r)
|
||||
}
|
||||
|
||||
func (t *trace) begin(r Route) *Route {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
|
||||
@@ -133,7 +133,7 @@ func TestTraceOrderIsAList(t *testing.T) {
|
||||
if !strings.Contains(string(b), `"order":[]`) || strings.Contains(string(b), `"order":null`) {
|
||||
t.Fatalf("trace routes = %s, want order []", b)
|
||||
}
|
||||
if _, c := s.trace.sessionLatest(context.Background(), "", 0, 0); c == nil || c.Order == nil {
|
||||
if _, c := s.trace.sessionLatest(context.Background(), "", "", 0, 0); c == nil || c.Order == nil {
|
||||
t.Fatalf("session's latest route = %+v, want a non-nil order", c)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,13 +30,30 @@ func heldKey(who access.Identity) bool {
|
||||
return who.KeyID != "" && (who.Limit.Limited() || len(who.Models) > 0 || len(who.Accounts) > 0)
|
||||
}
|
||||
|
||||
// heldRefused is what a held key is told where this magpie's own accounts
|
||||
// would be: the quotas, their cards and history, a card's refresh and the
|
||||
// accounts' lanes (321sssrt-bit, #1981: a friend given a key with a
|
||||
// budget saw every account's card, email and balance on their Remote
|
||||
// magpie's Usage page). The key's own limit stays at /v1/magpie/limit.
|
||||
const heldRefused = "this gateway key is held to a budget, models or accounts, so it is told nothing of this magpie's accounts: GET /v1/magpie/limit tells it its own limit"
|
||||
|
||||
// refuseHeld answers a held key 403 with msg, marked with
|
||||
// provider.KeyHeldCode so another magpie shows the key's own card alone
|
||||
// rather than "isn't shared", and says whether it did.
|
||||
func refuseHeld(w http.ResponseWriter, r *http.Request, msg string) bool {
|
||||
if !heldKey(access.Caller(r.Context())) {
|
||||
return false
|
||||
}
|
||||
writeJSON(w, http.StatusForbidden, map[string]any{"error": map[string]any{"message": msg, "type": "permission_error", "code": provider.KeyHeldCode}})
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) usageSummary(w http.ResponseWriter, r *http.Request) {
|
||||
if !local(r) && !sharedWith(r) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, usageRefused)
|
||||
return
|
||||
}
|
||||
if heldKey(access.Caller(r.Context())) {
|
||||
writeError(w, provider.Chat, http.StatusForbidden, "this gateway key is held to a budget, models or accounts, so it is told its own calls alone: GET /v1/magpie/usage/requests")
|
||||
if refuseHeld(w, r, "this gateway key is held to a budget, models or accounts, so it is told its own calls alone: GET /v1/magpie/usage/requests") {
|
||||
return
|
||||
}
|
||||
out := usageapi.State(usageapi.PeriodOf(r.URL.Query().Get("period")))
|
||||
|
||||
@@ -3,6 +3,7 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
@@ -56,6 +57,17 @@ const errRemoteNotShared = "remote magpie isn't shared; turn on Share on local n
|
||||
// errRemoteKey is a remote magpie that didn't take this provider's key (401).
|
||||
const errRemoteKey = "remote magpie didn't take this key; use one of its enabled gateway keys"
|
||||
|
||||
// KeyHeldCode is the error code a gateway answers a key held to a budget,
|
||||
// models or accounts with, where its own accounts would be told (#1981):
|
||||
// the key is someone else's to use, and is told its own limit alone.
|
||||
const KeyHeldCode = "gateway_key_held"
|
||||
|
||||
// errKeyHeld is a remote magpie that holds this provider's key to a
|
||||
// budget, models or accounts: it tells the key's own card (remoteKeyCards)
|
||||
// and none of its accounts', so none is shown, not even one kept from
|
||||
// before the key was held.
|
||||
var errKeyHeld = errors.New("remote magpie holds this key to a budget, models or accounts")
|
||||
|
||||
// errRemoteUnreachable starts the error of a remote magpie that couldn't
|
||||
// be reached at all.
|
||||
const errRemoteUnreachable = "couldn't reach the remote magpie"
|
||||
@@ -128,6 +140,14 @@ type remoteCardsRead struct {
|
||||
at time.Time
|
||||
cards []SubscriptionQuota // as the remote has them, not yet named
|
||||
err string
|
||||
held bool // the remote holds the key: no card of its accounts is shown
|
||||
}
|
||||
|
||||
// remoteCardsID is what a remote's cards are kept here by: the provider
|
||||
// and its key, so cards read with one key are never shown under another
|
||||
// (a key replaced by one the remote holds shows none of them).
|
||||
func remoteCardsID(p Provider) string {
|
||||
return p.ID + "\x00" + keyID(p.Key)
|
||||
}
|
||||
|
||||
// ForgetRemoteCardsForTest drops the remote magpies' cards kept here, for
|
||||
@@ -186,26 +206,20 @@ func RemoteCards(ctx context.Context) []SubscriptionQuota {
|
||||
// fresh isn't asked. A remote that can't be asked keeps showing its last
|
||||
// cards, as old as they are; with none, one card says why.
|
||||
func remoteCards(ctx context.Context, p Provider, fresh bool) []SubscriptionQuota {
|
||||
id := remoteCardsID(p)
|
||||
c := &remoteCardCache
|
||||
c.Lock()
|
||||
r, ok := c.m[p.ID]
|
||||
r, ok := c.m[id]
|
||||
c.Unlock()
|
||||
if !ok || fresh || time.Since(r.at) >= remoteCardsFor {
|
||||
asked := time.Now()
|
||||
cards, err := askRemote(ctx, p, http.MethodGet, RemoteCardsPath)
|
||||
r.at = time.Now()
|
||||
if err != nil {
|
||||
r.err = err.Error()
|
||||
} else {
|
||||
r.cards, r.err = cards, ""
|
||||
}
|
||||
c.Lock()
|
||||
if c.m == nil {
|
||||
c.m = map[string]remoteCardsRead{}
|
||||
}
|
||||
c.m[p.ID] = r
|
||||
c.Unlock()
|
||||
r = keepRemoteCards(id, asked, cards, err)
|
||||
}
|
||||
name := remoteName(p)
|
||||
if r.held {
|
||||
return nil
|
||||
}
|
||||
if len(r.cards) == 0 {
|
||||
msg := r.err
|
||||
if msg == "" {
|
||||
@@ -277,18 +291,42 @@ func refreshRemote(ctx context.Context, p Provider, card, user string) {
|
||||
if len(q) > 0 {
|
||||
path += "?" + q.Encode()
|
||||
}
|
||||
asked := time.Now()
|
||||
if _, err := askRemote(ctx, p, http.MethodPost, path); err != nil {
|
||||
c := &remoteCardCache
|
||||
c.Lock()
|
||||
if r, ok := c.m[p.ID]; ok {
|
||||
r.err = err.Error()
|
||||
c.m[p.ID] = r
|
||||
}
|
||||
c.Unlock()
|
||||
keepRemoteCards(remoteCardsID(p), asked, nil, err)
|
||||
}
|
||||
remoteCards(ctx, p, true)
|
||||
}
|
||||
|
||||
// keepRemoteCards keeps what a read of a remote's cards asked at asked
|
||||
// got, and gives back what is now kept. A failed read keeps the cards
|
||||
// read before, with its error; a key the remote holds drops them. A read
|
||||
// that comes back after one asked later is not kept over it, so a slow
|
||||
// answer from before the key was held can't bring its cards back.
|
||||
func keepRemoteCards(id string, asked time.Time, cards []SubscriptionQuota, err error) remoteCardsRead {
|
||||
c := &remoteCardCache
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
r := c.m[id]
|
||||
if asked.Before(r.at) {
|
||||
return r
|
||||
}
|
||||
r.at = asked
|
||||
switch {
|
||||
case errors.Is(err, errKeyHeld):
|
||||
r.cards, r.err, r.held = nil, "", true
|
||||
case err != nil:
|
||||
r.err = err.Error()
|
||||
default:
|
||||
r.cards, r.err, r.held = cards, "", false
|
||||
}
|
||||
if c.m == nil {
|
||||
c.m = map[string]remoteCardsRead{}
|
||||
}
|
||||
c.m[id] = r
|
||||
return r
|
||||
}
|
||||
|
||||
// RemoteQuotaHistories is every remote magpie's quota history since days
|
||||
// ago, as its own GET /v1/magpie/quotas/history has it (read from its
|
||||
// disk, no vendor asked), the providers named as RemoteCards names them.
|
||||
@@ -342,6 +380,14 @@ func remoteJSON(ctx context.Context, p Provider, method, path string, dst any) e
|
||||
case res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed:
|
||||
return fmt.Errorf("%s", errRemoteNoShare)
|
||||
case res.StatusCode == http.StatusForbidden:
|
||||
var e struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(b, &e) == nil && e.Error.Code == KeyHeldCode {
|
||||
return errKeyHeld
|
||||
}
|
||||
return fmt.Errorf("%s", errRemoteNotShared)
|
||||
case res.StatusCode == http.StatusUnauthorized:
|
||||
return fmt.Errorf("%s", errRemoteKey)
|
||||
|
||||
@@ -23,6 +23,10 @@ type fakePeer struct {
|
||||
// nil is a magpie too old to answer it. limitAsks counts them.
|
||||
limits map[string]string
|
||||
limitAsks int
|
||||
// held is a remote that holds the key to a budget, models or
|
||||
// accounts (#1981): it answers everything but the key's own limit
|
||||
// with 403 gateway_key_held.
|
||||
held bool
|
||||
}
|
||||
|
||||
// peerCards are the cards the remote has, without its keys' own.
|
||||
@@ -61,6 +65,11 @@ func (f *fakePeer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(f.status)
|
||||
return
|
||||
}
|
||||
if f.held {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
w.Write([]byte(`{"error":{"message":"held","type":"permission_error","code":"` + KeyHeldCode + `"}}`))
|
||||
return
|
||||
}
|
||||
switch r.Method + " " + r.URL.Path {
|
||||
case "GET " + RemoteCardsPath:
|
||||
f.gets++
|
||||
@@ -368,3 +377,70 @@ func TestRemoteKeyNames(t *testing.T) {
|
||||
t.Errorf("%q", names)
|
||||
}
|
||||
}
|
||||
|
||||
// #1981: a remote magpie that holds this computer's key to a budget,
|
||||
// models or accounts tells it none of its accounts. The cards read before
|
||||
// the key was held go, and only the key's own card stays; a 403 for that
|
||||
// reason doesn't say the remote isn't shared.
|
||||
func TestRemoteMagpieHeldKeyShowsOnlyItsOwnCard(t *testing.T) {
|
||||
peer := &fakePeer{
|
||||
cards: []SubscriptionQuota{{Provider: "codex", Name: "Codex", User: "boss@x.com", Kind: "subscription", Windows: []QuotaWindow{{Name: "5h", Used: 40}}}},
|
||||
limits: map[string]string{"sk-magpie-office": `{"limited":true,"key":"laptop","limit":{"period":"day","reset":"2026-10-12T00:00:00Z","tokens":10,"tokenLimit":100,"tokensLeft":90}}`},
|
||||
}
|
||||
remoteQuotaHome(t, peer)
|
||||
ctx := context.Background()
|
||||
if cs := peerCards(RemoteCards(ctx)); len(cs) != 1 || cs[0].User != "boss@x.com" {
|
||||
t.Fatalf("before the key is held: %+v", cs)
|
||||
}
|
||||
peer.Lock()
|
||||
peer.held = true
|
||||
peer.Unlock()
|
||||
p, err := Find("office")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remoteCards(ctx, *p, true)
|
||||
all := RemoteCards(ctx)
|
||||
if cs := peerCards(all); len(cs) != 0 {
|
||||
t.Errorf("a held key still shows the remote's accounts: %+v", cs)
|
||||
}
|
||||
for _, q := range all {
|
||||
if strings.Contains(q.Error, "isn't shared") || strings.Contains(q.User, "boss") {
|
||||
t.Errorf("held card: %+v", q)
|
||||
}
|
||||
}
|
||||
if ks := keyCards(all); len(ks) != 1 {
|
||||
t.Errorf("the key's own card: %+v", ks)
|
||||
} else if k := ks[Mask(p.Key)]; k.GatewayKey == nil || !k.GatewayKey.Limited {
|
||||
t.Errorf("the key's own card: %+v", ks)
|
||||
}
|
||||
// a read asked before the held one came back after it: not kept
|
||||
keepRemoteCards(remoteCardsID(*p), time.Now().Add(-time.Hour), peer.cards, nil)
|
||||
if cs := peerCards(RemoteCards(ctx)); len(cs) != 0 {
|
||||
t.Errorf("a slow earlier read brought the cards back: %+v", cs)
|
||||
}
|
||||
}
|
||||
|
||||
// #1981: cards are kept by provider and key, so a key changed to another
|
||||
// doesn't show what the first key was told.
|
||||
func TestRemoteMagpieCardsKeptByKey(t *testing.T) {
|
||||
peer := &fakePeer{cards: []SubscriptionQuota{{Provider: "codex", Name: "Codex", User: "boss@x.com", Kind: "subscription"}}}
|
||||
remoteQuotaHome(t, peer)
|
||||
ctx := context.Background()
|
||||
if cs := peerCards(RemoteCards(ctx)); len(cs) != 1 {
|
||||
t.Fatalf("first key: %+v", cs)
|
||||
}
|
||||
p, err := Find("office")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.Key = "sk-magpie-other"
|
||||
if err := Save(*p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, q := range RemoteCards(ctx) {
|
||||
if q.User == "boss@x.com" {
|
||||
t.Errorf("another key shows the first key's card: %+v", q)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,7 +116,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 alone. 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 (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>
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ magpie provider refresh office <span class="c"># 一覧を再取得</span></pr
|
||||
</ul>
|
||||
|
||||
<h2 id="quotas"><a class="anchor" href="#quotas">クォータと使用量</a></h2>
|
||||
<p>使用量ページ、メニューバー、<code>magpie quota</code> には、共有する magpie のサブスクリプションカードがその名前付きで(<code>Codex · office</code>、id <code>office/codex</code>)、向こうが最後に読んだ内容で表示されます。ベンダーに問い合わせるのはサインインを持つコンピューターだけです。このコンピューターでカードを更新すると、向こうがもう一度読みます(最大で 30 秒に 1 回)。Codex のリセットや WorkBuddy のチェックインは、向こうのコンピューターのアプリ、TUI、CLI で行います。</p>
|
||||
<p>使用量ページ、メニューバー、<code>magpie quota</code> には、共有する magpie のサブスクリプションカードがその名前付きで(<code>Codex · office</code>、id <code>office/codex</code>)、向こうが最後に読んだ内容で表示されます。ベンダーに問い合わせるのはサインインを持つコンピューターだけです。このコンピューターでカードを更新すると、向こうがもう一度読みます(最大で 30 秒に 1 回)。Codex のリセットや WorkBuddy のチェックインは、向こうのコンピューターのアプリ、TUI、CLI で行います。向こうが予算・モデル・アカウントで制限したキーにはカードは一切渡されず、ここにはそのキー自身のカードと上限だけが表示されます。</p>
|
||||
<p>共有する magpie は、このコンピューターのリクエストを、送ってきたゲートウェイキーの名前と応答したアカウントで記録します。</p>
|
||||
|
||||
<h2 id="trouble"><a class="anchor" href="#trouble">うまくいかないとき</a></h2>
|
||||
|
||||
@@ -126,7 +126,7 @@ magpie provider refresh office <span class="c"># fetch its list again</span></
|
||||
</ul>
|
||||
|
||||
<h2 id="quotas"><a class="anchor" href="#quotas">Quotas and usage</a></h2>
|
||||
<p>The Usage page, the menu bar and <code>magpie quota</code> show the shared magpie’s subscription cards, named with it (<code>Codex · office</code>, id <code>office/codex</code>), as that magpie last read them: only the computer with the sign-ins asks the vendors. A card’s refresh here has it read that card once more, at most once every 30 seconds. A Codex reset or a WorkBuddy check-in is pressed on that computer, from its own app, TUI or CLI.</p>
|
||||
<p>The Usage page, the menu bar and <code>magpie quota</code> show the shared magpie’s subscription cards, named with it (<code>Codex · office</code>, id <code>office/codex</code>), as that magpie last read them: only the computer with the sign-ins asks the vendors. A card’s refresh here has it read that card once more, at most once every 30 seconds. A Codex reset or a WorkBuddy check-in is pressed on that computer, from its own app, TUI or CLI. A key that magpie holds to a budget, some models or some accounts is told none of its cards: only that key’s own card shows here, with its limit.</p>
|
||||
<p>The shared magpie counts this computer’s requests under the name of the gateway key it sends, with the account that answered.</p>
|
||||
|
||||
<h2 id="trouble"><a class="anchor" href="#trouble">When it doesn’t work</a></h2>
|
||||
|
||||
@@ -116,7 +116,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>)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用。你的应用直接发给厂商、不经过 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>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>
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ magpie provider refresh office <span class="c"># 重新获取列表</span></pr
|
||||
</ul>
|
||||
|
||||
<h2 id="quotas"><a class="anchor" href="#quotas">额度与用量</a></h2>
|
||||
<p>用量页、菜单栏和 <code>magpie quota</code> 会显示共享 magpie 的订阅卡片,带上它的名字(<code>Codex · office</code>,id <code>office/codex</code>),内容是那边最近一次读取的结果:只有保存登录的电脑去问厂商。在本机刷新卡片会让那边再读一次,最多每 30 秒一次。Codex 重置或 WorkBuddy 签到要在那台电脑上,用它自己的应用、TUI 或 CLI 来做。</p>
|
||||
<p>用量页、菜单栏和 <code>magpie quota</code> 会显示共享 magpie 的订阅卡片,带上它的名字(<code>Codex · office</code>,id <code>office/codex</code>),内容是那边最近一次读取的结果:只有保存登录的电脑去问厂商。在本机刷新卡片会让那边再读一次,最多每 30 秒一次。Codex 重置或 WorkBuddy 签到要在那台电脑上,用它自己的应用、TUI 或 CLI 来做。那边限了额度、模型或账号的密钥看不到它的任何卡片:本机只显示这把密钥自己的卡片和它的限额。</p>
|
||||
<p>共享的 magpie 把本机的请求记在本机所用网关密钥的名字下,并记下应答的账号。</p>
|
||||
|
||||
<h2 id="trouble"><a class="anchor" href="#trouble">出问题时</a></h2>
|
||||
|
||||
Reference in New Issue
Block a user