diff --git a/docs/integrating.md b/docs/integrating.md index 868cb3206..b73f950cf 100644 --- a/docs/integrating.md +++ b/docs/integrating.md @@ -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 diff --git a/docs/reference.md b/docs/reference.md index 3b77443ea..f884315a3 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1608,7 +1608,9 @@ decided, before the vendor is asked. `after=&wait=` (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=` is the page's summary, the same JSON as the window's `/api/usage` (`path` is left out for another diff --git a/docs/subsystems/gateway-sessions.md b/docs/subsystems/gateway-sessions.md index d4b58a286..448b9fea5 100644 --- a/docs/subsystems/gateway-sessions.md +++ b/docs/subsystems/gateway-sessions.md @@ -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 diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 5296d59a2..4113b7b17 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -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/`); `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 `/~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=/~keys&user=`). 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 `/~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=/~keys&user=`). 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) | diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index d0728c92e..2c1207151 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.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) { diff --git a/internal/gateway/codex_titles.go b/internal/gateway/codex_titles.go index ec812d91c..14d2c167f 100644 --- a/internal/gateway/codex_titles.go +++ b/internal/gateway/codex_titles.go @@ -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() diff --git a/internal/gateway/concurrency.go b/internal/gateway/concurrency.go index a9af7297a..c9c9e6332 100644 --- a/internal/gateway/concurrency.go +++ b/internal/gateway/concurrency.go @@ -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()}) } diff --git a/internal/gateway/decide.go b/internal/gateway/decide.go index f702b0cc5..e4ca8416e 100644 --- a/internal/gateway/decide.go +++ b/internal/gateway/decide.go @@ -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() diff --git a/internal/gateway/decide_group.go b/internal/gateway/decide_group.go index 483da86b8..050695e21 100644 --- a/internal/gateway/decide_group.go +++ b/internal/gateway/decide_group.go @@ -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 { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 121a3327a..e28b9fe89 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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 or x-api-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 or x-api-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 or x-api-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 or x-api-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 } diff --git a/internal/gateway/quotas_held_key_test.go b/internal/gateway/quotas_held_key_test.go new file mode 100644 index 000000000..d09cd734b --- /dev/null +++ b/internal/gateway/quotas_held_key_test.go @@ -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) + } + } + } +} diff --git a/internal/gateway/session_route.go b/internal/gateway/session_route.go index b346f49bf..9a4d1e885 100644 --- a/internal/gateway/session_route.go +++ b/internal/gateway/session_route.go @@ -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= and // wait= 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 or x-api-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...) diff --git a/internal/gateway/trace.go b/internal/gateway/trace.go index 3b148f260..3b01eed71 100644 --- a/internal/gateway/trace.go +++ b/internal/gateway/trace.go @@ -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() diff --git a/internal/gateway/trace_test.go b/internal/gateway/trace_test.go index e8d6b09c9..ac80c05ef 100644 --- a/internal/gateway/trace_test.go +++ b/internal/gateway/trace_test.go @@ -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) } } diff --git a/internal/gateway/usage_api.go b/internal/gateway/usage_api.go index cd2ffe3fc..72f65bd10 100644 --- a/internal/gateway/usage_api.go +++ b/internal/gateway/usage_api.go @@ -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"))) diff --git a/internal/provider/remote_quotas.go b/internal/provider/remote_quotas.go index 81bcee047..e83ac1ad9 100644 --- a/internal/provider/remote_quotas.go +++ b/internal/provider/remote_quotas.go @@ -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) diff --git a/internal/provider/remote_quotas_test.go b/internal/provider/remote_quotas_test.go index fc849990a..d2354f03d 100644 --- a/internal/provider/remote_quotas_test.go +++ b/internal/provider/remote_quotas_test.go @@ -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) + } + } +} diff --git a/site/public/docs/integrate.html b/site/public/docs/integrate.html index bfae5ed75..ab137e4ec 100644 --- a/site/public/docs/integrate.html +++ b/site/public/docs/integrate.html @@ -116,7 +116,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"GET /v1/models lists what the user has turned on: id (provider/model, or a routing group’s name, sent as it is), display_name, owned_by (the provider), reasoning and supported_reasoning_levels ([{"effort":"low"},…]), context_window and max_output_tokens when known, and modalities 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 (reasoning_effort, reasoning.effort, Anthropic’s thinking or output_config.effort). ?format=text gives the ids one a line.

Optional

-

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the 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. 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 history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The reference has the details.

+

Send X-Magpie-Session: <id> with a conversation’s requests and GET /v1/magpie/route?session=<id> says which model a routing group picked for the turn and the fallbacks it tried, before the first token (long-poll with after=<seq>&wait=<s>). GET /v1/magpie/quotas lists the 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 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 history can be backfilled). They show on the Usage page as reported, and never count against a key’s limit. The reference has the details.

Keep the user’s providers. 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.
diff --git a/site/public/docs/ja/remote.html b/site/public/docs/ja/remote.html index be2f2485f..548ddf2b6 100644 --- a/site/public/docs/ja/remote.html +++ b/site/public/docs/ja/remote.html @@ -126,7 +126,7 @@ magpie provider refresh office # 一覧を再取得

クォータと使用量

-

使用量ページ、メニューバー、magpie quota には、共有する magpie のサブスクリプションカードがその名前付きで(Codex · office、id office/codex)、向こうが最後に読んだ内容で表示されます。ベンダーに問い合わせるのはサインインを持つコンピューターだけです。このコンピューターでカードを更新すると、向こうがもう一度読みます(最大で 30 秒に 1 回)。Codex のリセットや WorkBuddy のチェックインは、向こうのコンピューターのアプリ、TUI、CLI で行います。

+

使用量ページ、メニューバー、magpie quota には、共有する magpie のサブスクリプションカードがその名前付きで(Codex · office、id office/codex)、向こうが最後に読んだ内容で表示されます。ベンダーに問い合わせるのはサインインを持つコンピューターだけです。このコンピューターでカードを更新すると、向こうがもう一度読みます(最大で 30 秒に 1 回)。Codex のリセットや WorkBuddy のチェックインは、向こうのコンピューターのアプリ、TUI、CLI で行います。向こうが予算・モデル・アカウントで制限したキーにはカードは一切渡されず、ここにはそのキー自身のカードと上限だけが表示されます。

共有する magpie は、このコンピューターのリクエストを、送ってきたゲートウェイキーの名前と応答したアカウントで記録します。

うまくいかないとき

diff --git a/site/public/docs/remote.html b/site/public/docs/remote.html index d68d6c306..d8a99050b 100644 --- a/site/public/docs/remote.html +++ b/site/public/docs/remote.html @@ -126,7 +126,7 @@ magpie provider refresh office # fetch its list again

Quotas and usage

-

The Usage page, the menu bar and magpie quota show the shared magpie’s subscription cards, named with it (Codex · office, id office/codex), 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.

+

The Usage page, the menu bar and magpie quota show the shared magpie’s subscription cards, named with it (Codex · office, id office/codex), 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.

The shared magpie counts this computer’s requests under the name of the gateway key it sends, with the account that answered.

When it doesn’t work

diff --git a/site/public/docs/zh/integrate.html b/site/public/docs/zh/integrate.html index 3fb0e7c20..c952f6041 100644 --- a/site/public/docs/zh/integrate.html +++ b/site/public/docs/zh/integrate.html @@ -116,7 +116,7 @@ curl -s http://127.0.0.1:3425/v1/models -H "Authorization: Bearer magpie-acme"GET /v1/models 列出用户打开的模型:id(provider/model,或路由组的名字,原样发送即可)、display_name、owned_by(供应商)、reasoning 与 supported_reasoning_levels([{"effort":"low"},…]),已知时还有 context_window、max_output_tokens,以及 magpie 知道是否支持图片时的 modalities。请从这里读取,而不是内置一份列表:用户会在 magpie 里增删供应商。推理强度用你所用 API 自己的字段传(reasoning_effort、reasoning.effort、Anthropic 的 thinking 或 output_config.effort)。?format=text 每行一个 id。

可选

-

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用。你的应用直接发给厂商、不经过 magpie 的调用,可以用 POST /v1/magpie/usage/requests 上报(每次一条,或最多 5000 条,格式同 usage.jsonl 的一行,每条带 rid;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见参考文档。

+

在同一会话的请求里带上 X-Magpie-Session: <id>,GET /v1/magpie/route?session=<id> 就能在第一个 token 之前告诉你路由组为这一轮选了哪个模型、尝试过哪些后备(用 after=<seq>&wait=<s> 长轮询)。GET /v1/magpie/quotas 列出用户各订阅的额度,GET /v1/magpie/usage 和 /v1/magpie/usage/requests 给出用量页的统计和逐条请求(带 session;Claude Code 子代理的调用还有 subagent/parent_agent)。它们只回答本机,或带网关密钥的其他机器;限了额度、模型或账号的密钥只看得到自己的调用和路由,额度一律不告诉它(它自己的限额见 GET /v1/magpie/limit)。你的应用直接发给厂商、不经过 magpie 的调用,可以用 POST /v1/magpie/usage/requests 上报(每次一条,或最多 5000 条,格式同 usage.jsonl 的一行,每条带 rid;过去的时间照原样保留,所以可以补录历史)。它们在用量页上标为上报,且从不计入密钥的限额。细节见参考文档。

保留用户自己的供应商。把 magpie 作为又一个供应商(名为 Magpie)加在用户已有的供应商旁边,而不是替换它们,这样关掉 magpie 就只是换选另一个供应商。
diff --git a/site/public/docs/zh/remote.html b/site/public/docs/zh/remote.html index b94d039c5..e7833ab7a 100644 --- a/site/public/docs/zh/remote.html +++ b/site/public/docs/zh/remote.html @@ -126,7 +126,7 @@ magpie provider refresh office # 重新获取列表

额度与用量

-

用量页、菜单栏和 magpie quota 会显示共享 magpie 的订阅卡片,带上它的名字(Codex · office,id office/codex),内容是那边最近一次读取的结果:只有保存登录的电脑去问厂商。在本机刷新卡片会让那边再读一次,最多每 30 秒一次。Codex 重置或 WorkBuddy 签到要在那台电脑上,用它自己的应用、TUI 或 CLI 来做。

+

用量页、菜单栏和 magpie quota 会显示共享 magpie 的订阅卡片,带上它的名字(Codex · office,id office/codex),内容是那边最近一次读取的结果:只有保存登录的电脑去问厂商。在本机刷新卡片会让那边再读一次,最多每 30 秒一次。Codex 重置或 WorkBuddy 签到要在那台电脑上,用它自己的应用、TUI 或 CLI 来做。那边限了额度、模型或账号的密钥看不到它的任何卡片:本机只显示这把密钥自己的卡片和它的限额。

共享的 magpie 把本机的请求记在本机所用网关密钥的名字下,并记下应答的账号。

出问题时