provider: a custom Balance URL can be asked with POST, for an endpoint that answers only a POST (#2368, yaofeng)
A custom provider's Balance URL was always asked with GET, so a balance
endpoint that takes only a POST answered 405 and the card never showed.
- Provider.BalanceMethod ("" or GET, or POST with no body). It applies to
the user's own Balance URL only; a vendor magpie knows is asked as
before. balanceMethodOf refuses any other value before anything is sent.
- CLI: `magpie provider set <id> balance.method=POST` (GET clears it; any
other value is refused and the saved one kept); `magpie provider <id>`
shows "from POST <url>".
- GUI: a GET/POST segmented control (segs, not a <select>) beside the
Balance URL in More endpoints, aria-labelled and titled in en, zh, zh-TW,
ja and de. Check balance and Save carry it; a preset's save keeps it.
- No vendor preset or name is added. A string amount ("0.94306040") was
already read by number(), so `$usd_balance` reads as any field does.
- docs/subsystems/providers-accounts.md says it.
Run:
- go test -run TestBalance ./internal/provider/: ok. New TestBalanceMethod:
a POST-only httptest server, POST (any case) reads $0.94 from a string
usd_balance, "" and GET are still GET (405 is an error), PUT, DELETE and
a CRLF value are refused with nothing sent.
- go test -run TestProviderSetBalanceMethod ./internal/cli/: ok.
- Broken by hand: the request always GET turns TestBalanceMethod red
("asked GET, want POST"); balanceMethodOf passing any method turns it red
(PUT and DELETE sent); the CLI taking any value turns
TestProviderSetBalanceMethod red; the Check balance body without
balanceMethod turns 20 of 21 balance-method.test.cjs cases red, and
origin/main's app.js all of them.
- GUI: balance-method.test.cjs 42/42 (Chromium and WebKit, 1100 and 420,
en, zh, zh-TW, ja, de, saved GET and POST: opens on the saved method,
named and titled in the language, fits beside the URL with no page
scroll, the other pick goes in the check and save bodies). Siblings:
balance-parts, balance-field-default, balance-fix, catalog-hint,
duplicate-pause, key-balance-card, local-address, provider-base-api,
provider-auth-header, provider-gemini, provider-search,
provider-url-each-api, gui-de, gui-ja, gui-zh-tw, i18n-keys: 250/250.
- Real use: the built binary in a sandbox HOME, a custom provider at a
local server that answers GET 405 and POST {"usd_balance":"0.94306040"}.
Default: "unavailable 405 Method Not Allowed"; balance.method=post:
"$0.94 from POST …/api/check-balance $usd_balance", the server saw one
POST with Content-Length 0 and the Bearer key; balance.method=PATCH
refused. NanoGPT itself was not asked (no key here).
- gofmt -l clean; go vet ./... (darwin), GOOS=linux and GOOS=windows
go vet -tags nogui ./..., GOOS=windows go vet ./...: ok.
Suite run here: HOME=<sandbox> go test -tags nogui -timeout 45m ./...: 62
ok, internal/gui FAIL only on TestSetAnswersWhileDevinAndProvidersHang
(a state took 11.97s, load ~180), open as #1375; it passes -count=2 alone.
Full suite: SUITE_LINE
This commit is contained in:
@@ -46,7 +46,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| An endpoint's catalog | A key's provider with no catalog of its own (none named, none from a preset) is priced from the models.dev catalog whose `api` is one of its endpoints (`EndpointCatalog`, `catalog.AtEndpoint`; a trailing slash and case don't count, and an Anthropic base, kept as its root, is also matched with its `/v1`). Only when exactly one catalog is at that address, and it isn't a plan's (an id with `-plan`, or a `membershipCatalogs` one): a plan lists its membership's $0, and two catalogs at one address can't be told apart. A subscription's account never gets one. A provider at AMD's own endpoint is priced from `amd`, which lists Qwen3.8-27B at $0, a price, where its maker sells no such model and it had none (#2052); a relay's endpoint matches nothing and its model stays unpriced, never priced at a reseller's guess. `magpie model price` names the catalog, and says how to give a price when none is known. | [`models.go`](../../internal/provider/models.go), [`catalog.go`](../../internal/catalog/catalog.go) |
|
||||
| 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) |
|
||||
| A plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (`ListPrice` → `pluginListPrice`, `plugin.Model.Cost`, read by `pluginPrice`: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (`pluginFree`, `plugin.Model.Free`: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, `TestPluginFreeModelCostsNothing`). A plugin that gives no price and doesn't say free leaves the model unpriced. | [`models.go`](../../internal/provider/models.go), [`plugins.go`](../../internal/provider/plugins.go), [`providers.go`](../../internal/plugin/providers.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. `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`). 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 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`). 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) |
|
||||
| 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 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 `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`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 every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. 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. 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) |
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// magpie provider set balance.method= takes GET or POST, in any case, and
|
||||
// keeps GET as the unset default; any other method is refused and leaves
|
||||
// the saved one alone (#2368).
|
||||
func TestProviderSetBalanceMethod(t *testing.T) {
|
||||
groupsHome(t)
|
||||
for _, c := range []struct{ v, want string }{
|
||||
{"POST", "POST"}, {"get", ""}, {" post ", "POST"}, {"", ""},
|
||||
} {
|
||||
if _, err := printed(t, func() error {
|
||||
return providerCmd([]string{"provider", "set", "a", "balance=https://relay.example.com/api/check-balance", "balance.method=" + c.v})
|
||||
}); err != nil {
|
||||
t.Fatalf("%q: %v", c.v, err)
|
||||
}
|
||||
if got := mustFind(t, "a").BalanceMethod; got != c.want {
|
||||
t.Fatalf("balance.method=%q kept %q, want %q", c.v, got, c.want)
|
||||
}
|
||||
}
|
||||
if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "balance.method=POST"}) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, v := range []string{"PUT", "DELETE", "POST\r\nX: y"} {
|
||||
err := providerCmd([]string{"provider", "set", "a", "balance.method=" + v})
|
||||
if err == nil || !strings.Contains(err.Error(), "GET|POST") {
|
||||
t.Errorf("balance.method=%q: %v", v, err)
|
||||
}
|
||||
if got := mustFind(t, "a").BalanceMethod; got != "POST" {
|
||||
t.Errorf("a refused %q left %q", v, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -31,7 +31,7 @@ const providerUsage = `usage:
|
||||
magpie provider <id> show one provider and its models
|
||||
magpie provider add <preset> <key> add a preset vendor e.g. magpie provider add deepseek sk-…
|
||||
again, it adds another (deepseek-2); k=v pairs too: id, name, header.X-Foo
|
||||
magpie provider add <name> k=v… add a custom vendor k: url, anthropic, responses, gemini, decide, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.token, models.url, search, user-agent,
|
||||
magpie provider add <name> k=v… add a custom vendor k: url, anthropic, responses, gemini, decide, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.method, balance.token, models.url, search, user-agent,
|
||||
access.key, access.secret (a Volcengine access key, or a Tencent Cloud SecretId and SecretKey, for its plan's windows)
|
||||
magpie provider set <id> k=v… change a provider's settings, with the same k=v pairs as add;
|
||||
codex=as-sent sends Codex's Responses requests as Codex sent them
|
||||
@@ -120,6 +120,8 @@ const providerUsage = `usage:
|
||||
requests as written; not for a local relay that passes them on to a vendor)
|
||||
magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000'
|
||||
magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %'
|
||||
magpie provider set my-relay balance.method=POST
|
||||
(a balance endpoint that answers only a POST: asked with no body)
|
||||
magpie provider set my-relay balance=https://relay.example.com/api/user/self balance.path='$data.quota / 500000' balance.token=<access token> header.New-Api-User=<user id>
|
||||
(a new-api relay's whole account: its access token and user id, from its personal settings)
|
||||
(balance.path: where the amount is in the reply, or a sum of those with + - * / and
|
||||
@@ -851,6 +853,9 @@ func showProvider(p provider.Provider) error {
|
||||
// where it was asked: a panel's key query when its account query
|
||||
// has no token left to ask with
|
||||
if u, field := provider.BalanceQuery(p); u != "" {
|
||||
if p.BalanceMethod != "" {
|
||||
u = strings.ToUpper(p.BalanceMethod) + " " + u
|
||||
}
|
||||
from = muted.Render(" from " + u + " " + field)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -998,6 +1003,17 @@ func applyPairs(p *provider.Provider, pairs []string) error {
|
||||
p.BalanceURL = v
|
||||
case "balance.path":
|
||||
p.BalancePath = v
|
||||
case "balance.method":
|
||||
// GET (the default) or POST, for an endpoint that answers
|
||||
// only a POST (#2368)
|
||||
switch strings.ToUpper(strings.TrimSpace(v)) {
|
||||
case "GET", "":
|
||||
p.BalanceMethod = ""
|
||||
case "POST":
|
||||
p.BalanceMethod = "POST"
|
||||
default:
|
||||
return fmt.Errorf("balance.method=GET|POST, not %q", v)
|
||||
}
|
||||
case "balance.token":
|
||||
p.BalanceToken = v
|
||||
case "access.key":
|
||||
|
||||
@@ -2815,6 +2815,8 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; }
|
||||
.editor input::placeholder, .acc input::placeholder { color: var(--faint); }
|
||||
.editor .pair { display: flex; gap: 8px; align-items: center; }
|
||||
.editor .pair input:first-child { flex: 1; }
|
||||
.editor .pair.bal-ask input { flex: 1; min-width: 0; }
|
||||
.editor .pair.bal-ask .segs { flex: none; align-self: center; }
|
||||
.editor .side { display: flex; gap: 4px; align-items: center; flex: none; min-width: 52px; justify-content: flex-end; }
|
||||
.editor .side .text { padding: 3px 6px; }
|
||||
.editor .headers .pair .side .text { display: inline-flex; align-items: center; justify-content: center; width: 24px; height: 24px; padding: 0; border-radius: 6px; }
|
||||
|
||||
@@ -8394,7 +8394,7 @@ function baseAPIOf(p) {
|
||||
|
||||
// draftOf is a saved provider as its editor's form holds it.
|
||||
function draftOf(p) {
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, searches: !!p.searches, unredacted: !!p.unredacted, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p) };
|
||||
}
|
||||
|
||||
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
|
||||
@@ -9181,7 +9181,16 @@ function drawEditor(p, presetID) {
|
||||
const bal = input(draft.balanceURL, "https://…/api/usage/token", "url");
|
||||
bal.classList.add("bal-url");
|
||||
bal.oninput = () => { draft.balanceURL = bal.value; balPath.placeholder = balanceFieldOf(bal.value); };
|
||||
inner.append(...field(t("Balance URL"), bal, t("Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page")));
|
||||
// how the URL is asked: GET, or POST with no body for a vendor that
|
||||
// answers only a POST (#2368)
|
||||
const method = segs([["", "GET"], ["POST", "POST"]], draft.balanceMethod === "POST" ? "POST" : "", (v) => { draft.balanceMethod = v; });
|
||||
method.classList.add("bal-method");
|
||||
method.setAttribute("role", "group");
|
||||
method.setAttribute("aria-label", t("Balance request method"));
|
||||
method.title = t("How the Balance URL is asked: GET, or POST with no body for a vendor that answers only a POST");
|
||||
const balAsk = el("div", "pair bal-ask");
|
||||
balAsk.append(method, bal);
|
||||
inner.append(...field(t("Balance URL"), balAsk, t("Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page")));
|
||||
const balPath = input(draft.balancePath, balanceFieldOf(draft.balanceURL));
|
||||
balPath.classList.add("bal-path");
|
||||
balPath.oninput = () => { draft.balancePath = balPath.value; };
|
||||
@@ -9198,7 +9207,7 @@ function drawEditor(p, presetID) {
|
||||
check.onclick = async () => {
|
||||
check.classList.add("busy");
|
||||
res.className = "bal-res wait"; res.textContent = "…"; res.title = "";
|
||||
const body = { id: p.id, balanceURL: (draft.balanceURL || "").trim(), balancePath: (draft.balancePath || "").trim(), headers: headersOf(draft.headers) };
|
||||
const body = { id: p.id, balanceURL: (draft.balanceURL || "").trim(), balancePath: (draft.balancePath || "").trim(), balanceMethod: draft.balanceMethod || "", headers: headersOf(draft.headers) };
|
||||
if (draft.balanceToken) body.balanceToken = draft.balanceToken;
|
||||
else if (draft.clearBalanceToken) body.clearBalanceToken = true;
|
||||
try {
|
||||
@@ -9258,7 +9267,7 @@ function drawEditor(p, presetID) {
|
||||
}
|
||||
body.baseAPI = draft.api === "openai" ? "chat" : draft.api;
|
||||
}
|
||||
if (custom) { body.icon = draft.icon || "generic"; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.modelsURL = (draft.modelsURL || "").trim(); }
|
||||
if (custom) { body.icon = draft.icon || "generic"; body.balanceURL = (draft.balanceURL || "").trim(); body.balancePath = (draft.balancePath || "").trim(); body.balanceMethod = draft.balanceMethod || ""; body.modelsURL = (draft.modelsURL || "").trim(); }
|
||||
if (p) { body.fallback = draft.fallback; body.unlisted = draft.unlisted; body.noModels = noneChosen(); body.modelPrefs = modelPrefsOfDraft(); Object.assign(body, routingOfDraft(p)); }
|
||||
body.searches = !!draft.searches && searchable();
|
||||
body.pinUpstream = !!draft.pinUpstream;
|
||||
|
||||
@@ -1795,6 +1795,8 @@ const I18N = {
|
||||
"Catalog": "目录",
|
||||
"Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "模型的显示名称、推理等级与官方价格;网关提供多家厂商的模型时全部列出,先匹配者优先",
|
||||
"Balance URL": "余额查询地址",
|
||||
"Balance request method": "余额查询方法",
|
||||
"How the Balance URL is asked: GET, or POST with no body for a vendor that answers only a POST": "余额查询地址的请求方法:GET,或不带请求体的 POST,用于只接受 POST 的接口",
|
||||
"Models URL": "模型列表地址",
|
||||
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "供应商的模型列表接口,不在基础地址下时填写;请求时会带上 Key",
|
||||
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "查询 Key 余额的接口,像对话请求一样带 Key 请求;地址或请求头中的 {key} 替换为各 Key 自身的值,用于 Key 放在 URL 中的接口(…?key={key});结果显示在用量页",
|
||||
@@ -5414,6 +5416,8 @@ const I18N = {
|
||||
"Catalog": "目錄",
|
||||
"Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "模型的顯示名稱、推理等級與官方價格;閘道提供多家廠商的模型時全部列出,先匹配者優先",
|
||||
"Balance URL": "餘額查詢位址",
|
||||
"Balance request method": "餘額查詢方法",
|
||||
"How the Balance URL is asked: GET, or POST with no body for a vendor that answers only a POST": "餘額查詢位址的請求方法:GET,或不帶請求本文的 POST,用於只接受 POST 的介面",
|
||||
"Models URL": "模型列表位址",
|
||||
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "供應商的模型列表介面,不在基礎位址下時填寫;請求時會帶上 Key",
|
||||
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "查詢 Key 餘額的介面,像對話請求一樣帶 Key 請求;位址或請求頭中的 {key} 替換為各 Key 自身的值,用於 Key 放在 URL 中的介面(…?key={key});結果顯示在用量頁",
|
||||
@@ -9010,6 +9014,8 @@ const I18N = {
|
||||
"Catalog": "カタログ",
|
||||
"Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "モデルの表示名、推論レベル、公式価格。複数ベンダーを提供するゲートウェイではすべて列挙し、最初に一致したものが使われます",
|
||||
"Balance URL": "残高 URL",
|
||||
"Balance request method": "残高リクエストのメソッド",
|
||||
"How the Balance URL is asked: GET, or POST with no body for a vendor that answers only a POST": "残高 URL へのリクエスト方法:GET、または POST しか受け付けないエンドポイント向けの本文なしの POST",
|
||||
"Models URL": "モデル URL",
|
||||
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "ベース URL の下にない場合の、ベンダーがモデル一覧を返す場所。キー付きで問い合わせます",
|
||||
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "ベンダーがキーの残量を返す場所。チャットリクエストと同様にキー付きで問い合わせます。URL やヘッダー内の {key} は各キー自身の値になります(キーを URL に含めるベンダー向け:…?key={key})。使用量ページに表示されます",
|
||||
@@ -12636,6 +12642,8 @@ const I18N = {
|
||||
"Catalog": "Katalog",
|
||||
"Display names, reasoning levels and list prices for the models; for a gateway that serves several vendors, list them all, first match wins": "Anzeigenamen, Reasoning-Stufen und Listenpreise der Modelle; bei einem Zugangspunkt, der Modelle mehrerer Anbieter bereitstellt, alle auflisten, der erste Treffer gilt",
|
||||
"Balance URL": "Guthaben-URL",
|
||||
"Balance request method": "Methode der Guthabenabfrage",
|
||||
"How the Balance URL is asked: GET, or POST with no body for a vendor that answers only a POST": "Wie die Guthaben-URL abgefragt wird: GET, oder POST ohne Body für einen Anbieter, der nur POST beantwortet",
|
||||
"Models URL": "Modelllisten-URL",
|
||||
"Where the vendor lists its models, when that isn't under the base URL; asked with the key": "Wo der Anbieter seine Modelle auflistet, falls nicht unter der Basis-URL; wird mit dem Schlüssel abgefragt",
|
||||
"Where the vendor tells what is left on the key, asked with it like a chat request; {key} in it or in a header is each key's own, for a vendor that takes the key in the URL (…?key={key}); shown on the Usage page": "Wo der Anbieter das Restguthaben des Schlüssels meldet, abgefragt mit dem Schlüssel wie eine Chat-Anfrage; {key} darin oder in einem Header steht für den jeweiligen Schlüssel, für Anbieter, die den Schlüssel in der URL erwarten (…?key={key}); angezeigt auf der Seite Nutzung",
|
||||
|
||||
@@ -131,9 +131,10 @@ type providerJSON struct {
|
||||
AccountNames map[string]string `json:"accountNames,omitempty"`
|
||||
AccountSeats map[string]string `json:"accountSeats,omitempty"`
|
||||
// where a custom provider's balance is asked (see provider.Balance)
|
||||
BalanceURL string `json:"balanceURL,omitempty"`
|
||||
BalancePath string `json:"balancePath,omitempty"`
|
||||
ModelsURL string `json:"modelsURL,omitempty"`
|
||||
BalanceURL string `json:"balanceURL,omitempty"`
|
||||
BalancePath string `json:"balancePath,omitempty"`
|
||||
BalanceMethod string `json:"balanceMethod,omitempty"`
|
||||
ModelsURL string `json:"modelsURL,omitempty"`
|
||||
// an account-wide balance token (provider.BalanceToken): whether the
|
||||
// vendor takes one, and whether one is saved; never the token itself
|
||||
BalanceToken struct {
|
||||
@@ -544,7 +545,7 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
|
||||
ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(),
|
||||
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
|
||||
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, ModelsURL: p.ModelsURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{},
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Unlisted: p.Unlisted, NoModels: p.ServesNone(), Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
|
||||
@@ -1510,6 +1511,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
if provider.Preset(in.Preset) != nil {
|
||||
in.BalanceURL = cmp.Or(in.BalanceURL, old.BalanceURL)
|
||||
in.BalancePath = cmp.Or(in.BalancePath, old.BalancePath)
|
||||
in.BalanceMethod = cmp.Or(in.BalanceMethod, old.BalanceMethod)
|
||||
in.ModelsURL = cmp.Or(in.ModelsURL, old.ModelsURL)
|
||||
}
|
||||
}
|
||||
@@ -1794,6 +1796,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
q := *p
|
||||
q.BalanceURL, q.BalancePath = strings.TrimSpace(in.BalanceURL), strings.TrimSpace(in.BalancePath)
|
||||
q.BalanceMethod = in.BalanceMethod
|
||||
if in.Headers != nil {
|
||||
q.Headers = in.Headers
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A custom provider's Balance URL is asked with GET unless the user picks
|
||||
// POST beside it, for a balance endpoint that answers only a POST (#2368,
|
||||
// yaofeng): Check balance and Save both carry the pick, a provider saved
|
||||
// with POST opens on POST, and the control is named in every language and
|
||||
// fits beside the URL at a narrow width.
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs/promises");
|
||||
const path = require("node:path");
|
||||
const { test } = require("node:test");
|
||||
const { chromium, webkit } = require("playwright");
|
||||
const { strings } = require("./strings.cjs");
|
||||
|
||||
const { I18N } = strings();
|
||||
const tr = (lang, s) => (lang === "en" ? s : I18N[lang]?.[s]);
|
||||
const assets = path.resolve(__dirname, "../assets");
|
||||
const relay = {
|
||||
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-…one" }, keyList: [],
|
||||
balanceURL: "https://relay.example.com/api/check-balance", balancePath: "$usd_balance",
|
||||
};
|
||||
|
||||
function server(posted, lang, provider) {
|
||||
const all = { providers: [provider], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (data) => route.fulfill({ json: data });
|
||||
if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = ${JSON.stringify({ lang, theme: "light", web: true })};` });
|
||||
if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" });
|
||||
if (url.pathname === "/api/state") return json({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
if (url.pathname === "/api/providers") return json(all);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/")) {
|
||||
const body = route.request().postDataJSON();
|
||||
posted.push({ action: url.pathname.slice("/api/provider/".length), body });
|
||||
if (url.pathname === "/api/provider/balance") return json({ ok: true, amount: "$0.94" });
|
||||
return json(all);
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) return json({});
|
||||
const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname);
|
||||
const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
test(engine + ": the Balance URL is asked with the method picked beside it", async (t) => {
|
||||
assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit");
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
for (const width of [1100, 420]) {
|
||||
for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) {
|
||||
for (const saved of ["", "POST"]) {
|
||||
await t.test(`${width}px ${lang} saved ${saved || "GET"}`, async () => {
|
||||
const context = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [], posted = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
await page.route("**/*", server(posted, lang, saved ? { ...relay, balanceMethod: saved } : relay));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: "Relay" }).click();
|
||||
await page.locator(".editor details.more summary").click();
|
||||
|
||||
const method = page.locator(".editor .bal-method");
|
||||
await method.waitFor();
|
||||
const name = tr(lang, "Balance request method");
|
||||
const tip = tr(lang, "How the Balance URL is asked: GET, or POST with no body for a vendor that answers only a POST");
|
||||
assert(name && tip, `${lang} has both new strings`);
|
||||
assert.equal(await method.getAttribute("aria-label"), name);
|
||||
assert.equal(await method.getAttribute("title"), tip);
|
||||
const pressed = async () => method.locator(".opt[aria-pressed=true]").textContent();
|
||||
assert.equal(await pressed(), saved || "GET", "it opens on the saved method");
|
||||
|
||||
const layout = await page.locator(".editor .bal-ask").evaluate((box) => {
|
||||
const b = box.getBoundingClientRect();
|
||||
const inside = (e) => { const r = e.getBoundingClientRect(); return r.left >= b.left - 1 && r.right <= b.right + 1 && r.width > 0; };
|
||||
return {
|
||||
segs: inside(box.querySelector(".segs")),
|
||||
url: inside(box.querySelector("input")) && box.querySelector("input").getBoundingClientRect().width >= 120,
|
||||
page: document.documentElement.scrollWidth <= innerWidth,
|
||||
};
|
||||
});
|
||||
assert.deepEqual(layout, { segs: true, url: true, page: true }, "the method and the URL fit side by side");
|
||||
|
||||
// pick the other one, then ask and save
|
||||
const to = saved ? "GET" : "POST";
|
||||
await method.getByRole("button", { name: to, exact: true }).click();
|
||||
assert.equal(await pressed(), to);
|
||||
assert.equal(posted.length, 0, "picking a method changes only the draft");
|
||||
const check = page.locator(".editor").getByRole("button", { name: tr(lang, "Check balance"), exact: true });
|
||||
const asked = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/provider/balance");
|
||||
await check.click();
|
||||
await asked;
|
||||
const want = to === "POST" ? "POST" : "";
|
||||
assert.equal(posted.find((p) => p.action === "balance").body.balanceMethod, want, "Check balance asks as the form has it");
|
||||
const saveName = tr(lang, "Save");
|
||||
const response = page.waitForResponse((r) => new URL(r.url()).pathname === "/api/provider/save");
|
||||
await page.locator(".editor .bar").getByRole("button", { name: saveName, exact: true }).click();
|
||||
await response;
|
||||
const body = posted.find((p) => p.action === "save").body;
|
||||
assert.equal(body.balanceMethod, want, "Save keeps the method");
|
||||
assert.equal(body.balanceURL, relay.balanceURL);
|
||||
assert.deepEqual(errors, []);
|
||||
await context.close();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1158,7 +1158,15 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts []Balanc
|
||||
return "", nil, nil, true, errSub2APIKeyUsageWithToken(p.BalanceURL)
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, withBalanceKey(src.url, p.Key, true), nil)
|
||||
method := http.MethodGet
|
||||
if p.BalanceURL != "" {
|
||||
// the method the user named goes with their own Balance URL only;
|
||||
// a vendor magpie knows is asked as it answers
|
||||
if method, err = balanceMethodOf(p.BalanceMethod); err != nil {
|
||||
return "", nil, nil, true, err
|
||||
}
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, method, withBalanceKey(src.url, p.Key, true), nil)
|
||||
if err != nil {
|
||||
return "", nil, nil, true, err
|
||||
}
|
||||
@@ -1234,6 +1242,19 @@ func balanceRead(ctx context.Context, p Provider) (amount string, parts []Balanc
|
||||
return amount, nil, nil, true, err
|
||||
}
|
||||
|
||||
// balanceMethodOf is the HTTP method a Balance URL is asked with: GET
|
||||
// when none is named, else GET or POST in any case. Another is an error,
|
||||
// never a GET in its place.
|
||||
func balanceMethodOf(m string) (string, error) {
|
||||
switch strings.ToUpper(strings.TrimSpace(m)) {
|
||||
case "", http.MethodGet:
|
||||
return http.MethodGet, nil
|
||||
case http.MethodPost:
|
||||
return http.MethodPost, nil
|
||||
}
|
||||
return "", fmt.Errorf("the balance method %q is neither GET nor POST", m)
|
||||
}
|
||||
|
||||
// sub2APIKeyLimits says the provider's Balance URL is a sub2api panel's
|
||||
// query for a key, whose reply tells the key's own limits when it has
|
||||
// some.
|
||||
|
||||
@@ -3,6 +3,7 @@ package provider
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -651,3 +652,55 @@ func TestBalanceKeyAsBearer(t *testing.T) {
|
||||
t.Fatalf("an access token went as %q (%v)", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
// A balance endpoint that answers only a POST is asked with one, with no
|
||||
// body, when the provider says so (#2368, yaofeng); a GET is still what
|
||||
// every other Balance URL gets, and a method that is neither is refused
|
||||
// rather than sent. The reply's amount comes as a string, read as any other
|
||||
// field is.
|
||||
func TestBalanceMethod(t *testing.T) {
|
||||
var asked []string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
asked = append(asked, r.Method+" "+string(b))
|
||||
if r.Method != http.MethodPost {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
w.Write([]byte(`{"error":"Method not allowed"}`))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"usd_balance":"0.94306040","nano_balance":"1.5"}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
base := Provider{ID: "relay", Chat: srv.URL + "/v1", Key: "sk-1", BalanceURL: srv.URL + "/api/check-balance", BalancePath: "$usd_balance"}
|
||||
for _, c := range []struct {
|
||||
method, want string
|
||||
ok bool
|
||||
}{
|
||||
{"POST", "POST ", true},
|
||||
{" post ", "POST ", true},
|
||||
{"", "GET ", false},
|
||||
{"GET", "GET ", false},
|
||||
} {
|
||||
p := base
|
||||
p.BalanceMethod = c.method
|
||||
asked = nil
|
||||
amount, ok, err := Balance(context.Background(), p)
|
||||
if len(asked) != 1 || asked[0] != c.want {
|
||||
t.Errorf("%q: asked %q, want %q", c.method, asked, c.want)
|
||||
}
|
||||
if c.ok && (err != nil || !ok || amount != "$0.94") {
|
||||
t.Errorf("%q: balance = %q %v %v", c.method, amount, ok, err)
|
||||
}
|
||||
if !c.ok && err == nil {
|
||||
t.Errorf("%q: a 405 read as %q", c.method, amount)
|
||||
}
|
||||
}
|
||||
for _, m := range []string{"PUT", "DELETE", "POST\r\nX: y"} {
|
||||
p := base
|
||||
p.BalanceMethod = m
|
||||
asked = nil
|
||||
if _, _, err := Balance(context.Background(), p); err == nil || len(asked) != 0 {
|
||||
t.Errorf("%q: err %v, asked %q", m, err, asked)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -313,6 +313,10 @@ type Provider struct {
|
||||
// magpie knows need neither.
|
||||
BalanceURL string `json:"balanceURL,omitempty"`
|
||||
BalancePath string `json:"balancePath,omitempty"`
|
||||
// BalanceMethod is how BalanceURL is asked: "" (or GET), or POST with
|
||||
// no body, for an endpoint that answers only a POST (#2368). Any other
|
||||
// is refused when the balance is read (balanceMethodOf).
|
||||
BalanceMethod string `json:"balanceMethod,omitempty"`
|
||||
// BalanceToken is what a vendor tells the whole account's balance to,
|
||||
// where a key is told only what is left on itself: AiHubMix's system
|
||||
// access token, or a new-api relay's for its /api/user/self named in
|
||||
|
||||
Reference in New Issue
Block a user