provider: a relay added by hand finds its balance where relays tell it
The same relay user had added yylx.io by hand: no Balance URL, so no balance anywhere until they deleted it and imported it from the relay's site, whose link names the query (小鱼 of yylx.io, WeChat, 11-05). A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is now asked at its base's origin: /v1/usage (sub2api, $remaining), then /api/usage/token (new-api, $data.total_available / 500000), with the key's own auth and headers, as balanceRead asks. A 200 whose field reads is the query. It is kept in memory per origins and key (the key hashed), and so is finding none, for 6h (5 min when the relay can't be reached), so a poll asks once. Nothing is written to providers.json. The card, Check balance and `magpie provider show` (BalanceQuery) read the found URL; none found is no card, and the editor's "No Balance URL to ask". Never asked: a vendor's or local server's preset host (api.openai.com, api.anthropic.com, api.deepseek.com…), this computer, opencode.ai and api.cline.bot, a plan whose windows are its card. The subsystem page has the row. Run (mote, go1.26.8): - go vet ./internal/provider; go test -count=1 ./internal/provider: ok. - The new tests: a sub2api relay read at $10472.14 with /v1/usage asked 3 times over the probe, a Balance and a card poll; a new-api relay found after /v1/usage's 404; a relay answering HTML 200 everywhere has no card and is asked twice in all over two polls; the hosts left alone. Broken by hand: with the probe taken out of balanceRead, the three HandAdded tests fail (balance "" false; a card with no balance). Before this, TestOpenCodeZenSaysItTellsNoBalance caught the probe asking opencode.ai for OpenCode Go and a custom inference provider; those hosts are left out now. Real use (mote, sandbox HOME holding only the owner's yylx.io provider, copied with its key, removed after): `magpie provider yylx-hand` (no preset) and `magpie provider yylx` (鱼鱼连线's preset, Global region) both show "balance $19.97 from https://global.yylx.io/v1/usage $remaining". Not tried: a real new-api relay; a new-api relay that routes unknown /v1 paths to its upstream.
This commit is contained in:
@@ -71,6 +71,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) |
|
||||
| A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go) |
|
||||
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) |
|
||||
| A relay's balance found | A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is asked where relays tell a key its balance: the base's origin's `/v1/usage` (sub2api, `$remaining`), then `/api/usage/token` (new-api, `$data.total_available / 500000`), with the key's own auth and headers (`probesBalance`, `probeBalance`). A 200 whose field reads is the query; it is kept in memory for the origins and key, and so is finding none, for 6 hours (5 minutes when the relay couldn't be reached), so a poll asks it once. Nothing is written to the provider: the card reads the found URL, `BalanceQuery` names it, and none found means no card (`errNoBalance`) and *No Balance URL to ask* in the editor. Never asked: a model vendor's or local server's preset host, this computer, OpenCode and the Cline API (`noProbeHosts`), a plan's windows (`planQuotaSourceOf`). A hand-added yylx.io relay showed no balance until its operator had the user import it again (11-05). | [`balance_probe.go`](../../internal/provider/balance_probe.go) |
|
||||
| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A name picks its account wherever the account's own name does (`AccountByName`): the CLI's `accountNamed` (switch, forget, alias), the pool's `--accounts`, and `accountRef` (caps, models, weights, concurrency) after an exact name. It is refused when two accounts have it or it is another account's email or name, so it never picks by guess; `accountRef` then finds no account, as the GUI passes exact names (StringKe in #4532, `TestAccountsAliasPicksTheAccount`). A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else the plugin's, else `Seat`) with `Named` when it is the user's own, which Hide accounts leaves in sight (#3656), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. Records (a trace's `who`, usage's `ProviderAccount`) keep the vendor's name, the key the user's name is kept by, and every list of them looks the name up as it is shown (`AccountShown`, `AccountShownOf`, `AccountRef.Shown`), so a request from before a rename reads by the new name too: the Routing page's accounts and requests (`userShown` in `plugins/routing/client.js`, from `/api/providers`' `accountNames`), its Several accounts pools (`onOf`), the Usage page's Accounts and the request log's Account filter (`usageapi`), `magpie usage`, and a gateway key's accounts (`AccountNames`, `/api/caller-keys`). Before plugins#310 (a renamed Kiro account read by its old name on every request after) those showed the vendor's name. An account with no name of the user's own goes by the name its plugin's `usage()` gives it (`PluginUserOf`, the `user` of its last read: `loginUsageCache`, else `quotas.json`), else by its id: a Huawei Cloud CodeArts account kept by its IAM id `iam::<domain>:user:<name>` reads as the masked phone its card shows (#4416). `AccountShown`, `AccountShownOf` and `AccountLabelOf` (cards' `Alias`, `magpie accounts`, usageapi's Account filter, the quota alert) apply it, and the GUI has it as `/api/providers`' `accountUsers` (`accountShownOf` in app.js: the editor's rows, the per-account proxy lines, Routing's `userShown`, Hide accounts). The id stays the key everything is kept by; nothing stored changes. A read that fails keeps the last good `user`; nothing read yet, or a plugin whose windows are all model pools (not kept in `quotas.json`) after a restart, is its id until the next read. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
|
||||
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.go) |
|
||||
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call on a process's first ask, whatever the kept list's age, and hourly after (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. The magpie serving the gateway fetches it when it starts and whenever it is due, asked for or not (`KeepPartnersFresh`), so an app left open on another page still learns of a partner added. The file also says when the last fetch started (`tried`) and, when it failed, why (`error`, logged once until a fetch gets the list again), so a list that stops changing tells a fetch that fails from one that never came back (`tried` after `at`, no error) and from none asked (#3362). Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon, used as it is while its `iconUrl` stays the same; the prune after a save of `providers.json` (`pruneIcons`) leaves the logos of the partners listed now (`keptPartnerIcons`), as it leaves a plugin's. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
|
||||
|
||||
@@ -198,6 +198,11 @@ func keyQueryOf(p Provider) Provider {
|
||||
// without its token (keyQueryOf).
|
||||
func BalanceQuery(p Provider) (balanceURL, field string) {
|
||||
p = keyQueryOf(p)
|
||||
if u := probedBalanceURL(p); u != "" {
|
||||
// a relay added by hand, its query found (balance_probe.go)
|
||||
p.BalanceURL = u
|
||||
return u, balancePathOf(p)
|
||||
}
|
||||
return p.BalanceURL, p.BalancePath
|
||||
}
|
||||
|
||||
@@ -1316,6 +1321,11 @@ func balanceSegmentOf(raw, path string) (balanceSegment, error) {
|
||||
// its own has what its fullest window has left: what it can spend now.
|
||||
func Balance(ctx context.Context, p Provider) (amount string, ok bool, err error) {
|
||||
amount, _, _, ws, _, ok, err := balanceRead(ctx, p)
|
||||
if !ok && errors.Is(err, errNoBalance) {
|
||||
// a relay added by hand whose balance was found nowhere: no
|
||||
// balance to ask, as with no Balance URL
|
||||
return "", false, nil
|
||||
}
|
||||
if err == nil && amount == "" && len(ws) > 0 {
|
||||
left := ws[0].Limit - ws[0].Amount
|
||||
for _, w := range ws[1:] {
|
||||
@@ -1339,6 +1349,16 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts, split [
|
||||
// id typed as a header's name among them (userIDHeader)
|
||||
p.Headers = userIDHeader(p.Headers)
|
||||
src, ok := balanceSourceOf(p)
|
||||
if !ok && probesBalance(p) {
|
||||
// a relay added by hand: its balance where relays tell it, or
|
||||
// no card (balance_probe.go)
|
||||
u, found := probeBalance(ctx, p)
|
||||
if !found {
|
||||
return "", nil, nil, nil, false, false, errNoBalance
|
||||
}
|
||||
p.BalanceURL = u
|
||||
src, ok = balanceSourceOf(p)
|
||||
}
|
||||
if !ok && p.Account == nil && p.Key != "" && openCodeZen(p) {
|
||||
// a balance the vendor keeps from the key: said so, not left out
|
||||
return "", nil, nil, nil, false, true, errOpenCodeNoBalance
|
||||
@@ -1600,7 +1620,7 @@ func KeyBalances(ctx context.Context) []SubscriptionQuota {
|
||||
}
|
||||
src, ok := balanceSourceOf(p)
|
||||
zen := !ok && openCodeZen(p)
|
||||
if !ok && !clineKeyCard(p) && !zen {
|
||||
if !ok && !clineKeyCard(p) && !zen && !probesBalance(p) {
|
||||
continue
|
||||
}
|
||||
others := 0
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// A relay added by hand, with no Balance URL, is asked where relays tell a
|
||||
// key its balance: a sub2api relay's /v1/usage, then a new-api (one-api)
|
||||
// relay's /api/usage/token, both with the key alone. A relay imported from
|
||||
// its own site names its query; one typed in had none, so its balance
|
||||
// showed nowhere until the user found the field at the foot of the form
|
||||
// (小鱼 of yylx.io, 11-05: deleted and imported again, it worked).
|
||||
//
|
||||
// What is found is kept for the origin and key, and so is finding nothing,
|
||||
// for balanceProbeMiss: a poll asks again only after that.
|
||||
var balanceProbes = []string{sub2APIKeyUsage, newAPIKeyUsage}
|
||||
|
||||
// balanceProbeDown is how long a relay that couldn't be reached at all
|
||||
// is left before it is looked at again.
|
||||
const (
|
||||
balanceProbeMiss = 6 * time.Hour
|
||||
balanceProbeDown = 5 * time.Minute
|
||||
)
|
||||
|
||||
type probeFound struct {
|
||||
url string // "" when neither query told a balance
|
||||
until time.Time // when a miss is looked at again
|
||||
}
|
||||
|
||||
// probeLocal lets a test's relay on loopback be looked at.
|
||||
var probeLocal bool
|
||||
|
||||
var probed struct {
|
||||
sync.Mutex
|
||||
m map[string]probeFound
|
||||
}
|
||||
|
||||
// balanceProbeKey is what a probe is kept by: the origins and the key
|
||||
// (hashed, never kept as it is).
|
||||
func balanceProbeKey(origins []string, key string) string {
|
||||
return strings.Join(origins, " ") + " " + keyTag("probe", key)
|
||||
}
|
||||
|
||||
// probesBalance is a provider whose balance is looked for: added by hand
|
||||
// (no preset, no account, a key), with no Balance URL and no host magpie
|
||||
// knows the query of, and at a relay's address, never a model vendor's own
|
||||
// or this computer's.
|
||||
func probesBalance(p Provider) bool {
|
||||
if p.Account != nil || p.Key == "" || strings.TrimSpace(p.BalanceURL) != "" || !relayPreset(p.Preset) {
|
||||
return false
|
||||
}
|
||||
if _, ok := balanceSourceOf(p); ok || clineKeyCard(p) || openCodeZen(p) {
|
||||
return false
|
||||
}
|
||||
if _, ok := planQuotaSourceOf(p); ok {
|
||||
return false // a plan's windows are its card
|
||||
}
|
||||
return len(probeOrigins(p)) > 0
|
||||
}
|
||||
|
||||
// relayPreset is a provider added by hand, or from a relay's preset,
|
||||
// which names no balance query of its own (鱼鱼连线's, the same relay
|
||||
// as 小鱼's).
|
||||
func relayPreset(id string) bool {
|
||||
if id == "" {
|
||||
return true
|
||||
}
|
||||
for _, d := range presets {
|
||||
if d.ID == id {
|
||||
return d.Kind == KindRelay || d.Kind == KindPartner
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// noProbeHosts are relays whose keys are told their balance some other
|
||||
// way, or not at all: OpenCode's Zen and Go (openCodeZen, its plan) and
|
||||
// the Cline API (clineKeyCard).
|
||||
var noProbeHosts = []string{"opencode.ai", "api.cline.bot"}
|
||||
|
||||
// probeOrigins are the scheme and host of each base the provider names,
|
||||
// each once, leaving out a vendor's own host and a local one.
|
||||
func probeOrigins(p Provider) []string {
|
||||
var out []string
|
||||
for _, raw := range []string{p.Chat, p.Responses, p.Anthropic} {
|
||||
u, err := url.Parse(strings.TrimSpace(raw))
|
||||
if err != nil || u.Host == "" || (u.Scheme != "https" && u.Scheme != "http") {
|
||||
continue
|
||||
}
|
||||
if notProbed(u.Hostname()) {
|
||||
continue
|
||||
}
|
||||
o := u.Scheme + "://" + strings.ToLower(u.Host)
|
||||
if !contains(out, o) {
|
||||
out = append(out, o)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// notProbed is a host never asked a relay's query: this computer, or a
|
||||
// host a vendor's or a local server's preset names.
|
||||
func notProbed(host string) bool {
|
||||
host = strings.ToLower(host)
|
||||
if !probeLocal && (isLoopback(host) || strings.HasSuffix(host, ".localhost")) {
|
||||
return true
|
||||
}
|
||||
if contains(noProbeHosts, host) {
|
||||
return true
|
||||
}
|
||||
for _, d := range presets {
|
||||
if d.Kind != KindVendor && d.Kind != KindLocal {
|
||||
continue
|
||||
}
|
||||
bases := []string{d.Chat, d.Responses, d.Anthropic}
|
||||
for _, r := range d.Regions {
|
||||
bases = append(bases, r.Chat, r.Responses, r.Anthropic)
|
||||
}
|
||||
for _, b := range bases {
|
||||
if b != "" && strings.EqualFold(hostnameOf(b), host) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func hostnameOf(raw string) string {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return u.Hostname()
|
||||
}
|
||||
|
||||
// probedBalanceURL is the query found for p, without asking: "" when none
|
||||
// was found or none was looked for yet.
|
||||
func probedBalanceURL(p Provider) string {
|
||||
if !probesBalance(p) {
|
||||
return ""
|
||||
}
|
||||
probed.Lock()
|
||||
defer probed.Unlock()
|
||||
return probed.m[balanceProbeKey(probeOrigins(p), p.Key)].url
|
||||
}
|
||||
|
||||
// probeBalance looks for p's balance query, asking each origin's relay
|
||||
// queries in turn, and is what was found (false: none told a balance).
|
||||
// A query that answers 200 with its field read is the one; a failure to
|
||||
// reach the relay is not kept, so the next read looks again.
|
||||
func probeBalance(ctx context.Context, p Provider) (string, bool) {
|
||||
origins := probeOrigins(p)
|
||||
k := balanceProbeKey(origins, p.Key)
|
||||
probed.Lock()
|
||||
f, seen := probed.m[k]
|
||||
probed.Unlock()
|
||||
if seen && (f.url != "" || time.Now().Before(f.until)) {
|
||||
return f.url, f.url != ""
|
||||
}
|
||||
found, reached := "", false
|
||||
for _, o := range origins {
|
||||
for _, path := range balanceProbes {
|
||||
ok, answered := askProbe(ctx, p, o+path)
|
||||
reached = reached || answered
|
||||
if ok {
|
||||
found = o + path
|
||||
break
|
||||
}
|
||||
}
|
||||
if found != "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return "", false // cut short: nothing learnt
|
||||
}
|
||||
wait := balanceProbeMiss
|
||||
if !reached {
|
||||
wait = balanceProbeDown
|
||||
}
|
||||
probed.Lock()
|
||||
if probed.m == nil {
|
||||
probed.m = map[string]probeFound{}
|
||||
}
|
||||
probed.m[k] = probeFound{found, time.Now().Add(wait)}
|
||||
probed.Unlock()
|
||||
return found, found != ""
|
||||
}
|
||||
|
||||
// askProbe asks one relay query as balanceRead asks it, and is whether it
|
||||
// told a balance, and whether the relay answered at all.
|
||||
func askProbe(ctx context.Context, p Provider, raw string) (ok, answered bool) {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, raw, nil)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
for k, v := range AuthHeaders(p, Chat) {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
for k, v := range p.SentHeaders(ctx) {
|
||||
req.Header.Set(k, withBalanceKey(v, p.Key, false))
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return false, false
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return false, true
|
||||
}
|
||||
q := p
|
||||
q.BalanceURL, q.BalancePath = raw, ""
|
||||
amount, err := readBalancePath(b, balancePathOf(q))
|
||||
return err == nil && amount != "", true
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
)
|
||||
|
||||
func probeSandbox(t *testing.T) {
|
||||
t.Helper()
|
||||
isolate(t)
|
||||
h := t.TempDir()
|
||||
t.Setenv("HOME", h)
|
||||
t.Setenv("USERPROFILE", h)
|
||||
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
|
||||
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
|
||||
t.Setenv("PATH", h)
|
||||
for _, v := range agentenv.Vars {
|
||||
t.Setenv(v, "")
|
||||
}
|
||||
keyBalanceCache.data = nil
|
||||
probeLocal = true
|
||||
probed.Lock()
|
||||
probed.m = nil
|
||||
probed.Unlock()
|
||||
t.Cleanup(func() {
|
||||
keyBalanceCache.data = nil
|
||||
probeLocal = false
|
||||
probed.Lock()
|
||||
probed.m = nil
|
||||
probed.Unlock()
|
||||
})
|
||||
}
|
||||
|
||||
// A relay added by hand with no Balance URL (小鱼 of yylx.io, 11-05): its
|
||||
// balance is read where a sub2api relay tells a key it, its card shows it,
|
||||
// and the query is asked once, not on every read.
|
||||
func TestHandAddedRelayFindsItsBalance(t *testing.T) {
|
||||
probeSandbox(t)
|
||||
var asked atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/v1/usage" {
|
||||
asked.Add(1)
|
||||
if r.Header.Get("Authorization") != "Bearer sk-relay" {
|
||||
http.Error(w, `{"error":"invalid key"}`, http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"remaining":10472.14,"unit":"USD"}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := Provider{ID: "yylx", Name: "yylx", Chat: srv.URL + "/v1", Anthropic: srv.URL, Key: "sk-relay"}
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
amount, ok, err := Balance(context.Background(), p)
|
||||
if err != nil || !ok || amount != "$10472.14" {
|
||||
t.Fatalf("balance = %q %v %v, want $10472.14", amount, ok, err)
|
||||
}
|
||||
if u, field := BalanceQuery(p); u != srv.URL+"/v1/usage" || field != "$remaining" {
|
||||
t.Errorf("query = %q %q", u, field)
|
||||
}
|
||||
cards := KeyBalances(context.Background())
|
||||
if len(cards) != 1 || cards[0].Provider != "yylx" || cards[0].Balance != "$10472.14" {
|
||||
t.Fatalf("cards = %+v", cards)
|
||||
}
|
||||
if n := asked.Load(); n != 3 {
|
||||
t.Errorf("/v1/usage asked %d times, want 3 (the probe once, then each read)", n)
|
||||
}
|
||||
// the user's config is left as it was
|
||||
if q, _ := Find("yylx"); q.BalanceURL != "" {
|
||||
t.Errorf("Balance URL written: %q", q.BalanceURL)
|
||||
}
|
||||
}
|
||||
|
||||
// A new-api relay answers /v1/usage with 404: its key query is found next.
|
||||
func TestHandAddedNewAPIRelay(t *testing.T) {
|
||||
probeSandbox(t)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/usage/token" && r.Header.Get("Authorization") == "Bearer sk-n" {
|
||||
w.Write([]byte(`{"code":true,"data":{"total_available":1000000}}`))
|
||||
return
|
||||
}
|
||||
http.NotFound(w, r)
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := Provider{ID: "na", Name: "na", Chat: srv.URL + "/v1", Key: "sk-n"}
|
||||
amount, ok, err := Balance(context.Background(), p)
|
||||
if err != nil || !ok || amount != "$2.00" {
|
||||
t.Fatalf("balance = %q %v %v, want $2.00", amount, ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A relay that tells no balance at either query has no card, and is not
|
||||
// asked again on the next read.
|
||||
func TestHandAddedRelayWithNoBalance(t *testing.T) {
|
||||
probeSandbox(t)
|
||||
var asked atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked.Add(1)
|
||||
// a page that answers 200 to anything is not a balance
|
||||
w.Write([]byte(`<html>ok</html>`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p := Provider{ID: "none", Name: "none", Chat: srv.URL + "/v1", Key: "sk-x"}
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for range 2 {
|
||||
if amount, ok, err := Balance(context.Background(), p); ok || err != nil || amount != "" {
|
||||
t.Fatalf("balance = %q %v %v, want none", amount, ok, err)
|
||||
}
|
||||
if cards := KeyBalances(context.Background()); len(cards) != 0 {
|
||||
t.Fatalf("cards = %+v, want none", cards)
|
||||
}
|
||||
keyBalanceCache.data = nil
|
||||
}
|
||||
if n := asked.Load(); n != 2 {
|
||||
t.Errorf("asked %d times, want 2 (each query once)", n)
|
||||
}
|
||||
}
|
||||
|
||||
// What is never looked at: a provider with its own Balance URL or a
|
||||
// preset, a host magpie knows, a model vendor's own API, this computer.
|
||||
func TestBalanceProbeLeavesOthersAlone(t *testing.T) {
|
||||
for _, p := range []Provider{
|
||||
{Chat: "https://relay.example.com/v1", Key: "k", BalanceURL: "https://relay.example.com/x"},
|
||||
{Chat: "https://relay.example.com/v1", Key: "k", Preset: "deepseek"},
|
||||
{Chat: "https://opencode.ai/inference/custom/acme/v1", Key: "k"},
|
||||
{Chat: "https://opencode.ai/zen/go/v1", Key: "k", Preset: "opencode-go"},
|
||||
{Chat: "https://relay.example.com/v1"},
|
||||
{Chat: "https://api.deepseek.com/v1", Key: "k"},
|
||||
{Chat: "https://api.openai.com/v1", Key: "k"},
|
||||
{Anthropic: "https://api.anthropic.com", Key: "k"},
|
||||
{Chat: "http://127.0.0.1:11434/v1", Key: "k"},
|
||||
{Chat: "http://localhost:1234/v1", Key: "k"},
|
||||
} {
|
||||
if probesBalance(p) {
|
||||
t.Errorf("looked at: %+v", p)
|
||||
}
|
||||
}
|
||||
if !probesBalance(Provider{Chat: "https://app.yylx.io/v1", Key: "k"}) {
|
||||
t.Error("a relay added by hand is not looked at")
|
||||
}
|
||||
if !probesBalance(Provider{Chat: "https://app.yylx.io/v1", Key: "k", Preset: "yylx"}) {
|
||||
t.Error("a relay's preset is not looked at")
|
||||
}
|
||||
if got := strings.Join(probeOrigins(Provider{Chat: "https://R.example.com/v1", Responses: "https://r.example.com/v1", Anthropic: "https://r.example.com"}), ","); got != "https://r.example.com" {
|
||||
t.Errorf("origins = %q", got)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user