Repository navigation
feat(gateway): read each upstream's balance - #321
Merged
Merged
Conversation
Users of relays and pay-as-you-go keys want to see what is left before a
request fails for lack of money. Each upstream now has a balance read
from its own balance endpoint, with its own key and proxy:
- openrouter (key limit, or account credits when the key has none),
deepseek, moonshot, sub2api (quota/rate limits, subscription windows,
wallet, today's cost), newapi (quota, or what an unlimited key spent),
and thinkwatch (an enterprise gateway's per-key windows and the month's
cost).
- `providers[].balance` picks the source; `auto`, the default, knows the
OpenRouter, DeepSeek and Moonshot hosts and asks any other relay once
which kind it is. The answer stays in memory; it is never written to
config. ChatGPT and Z.ai accounts and Bedrock have their quota elsewhere
and never read a balance.
- Reads happen at start, at most once a minute after a request through
the upstream ends (a guard dropped with the response body or the
WebSocket turn, so a client disconnect counts too), every ten minutes
otherwise, and on demand. A failed read keeps the last good reading and
records why. Reading never touches forwarding.
Protocol 46: `ProviderView.balance` and `balance_setting`,
`ProviderInput.balance`, `ProviderTestResult.balance` ("Check connection"
reads it too), the `balance_updated` event and
`POST /providers/{name}/balance/refresh`.
An unknown `balance:` value is refused like every other closed set
(`config.unknown_variant`), which keeps the line number and lets the
safe-mode repair put it back to `auto`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This was referenced Oct 10, 2026
Merged
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Every upstream can now show what is left to spend, read from its own balance endpoint with its own key and proxy (ThinkWatch User-Agent,
Accept,Authorization: Bearer <key>and nothing else; 10 s per request; paths go on the origin ofbase_url, not on a base path such as/anthropic).openrouter/api/v1/key, then/api/v1/creditswhen the key has no limitdeepseek/user/balancemoonshot/v1/users/me/balance.cn, USD on.ai)sub2api/v1/usagequota_limited: quota + rate-limit windows;unrestricted: daily/weekly/monthly windows and/or wallet;expires_at;usage.today.costas spent (today)newapi/v1/dashboard/billing/subscription+/usageaccess_untilas expirythinkwatch/v1/usagelimitsentry a window (unit = kind, withscope),usage.cost_usd_monthas spent (month),expires_atproviders[].balance: auto | off | openrouter | deepseek | moonshot | sub2api | newapi | thinkwatch, defaultauto(not written).autoknowsopenrouter.ai,api.deepseek.com,api.moonshot.cn/.ai; any other host (except Anthropic's, OpenAI's and Gemini's own) is asked once:/v1/usagewith a stringmode→ sub2api (with alimitsarray → thinkwatch), else/v1/dashboard/billing/subscriptionwithhard_limit_usd/system_hard_limit_usd→ newapi. The answer that identified it is reused as the first reading. Kept in memory only. Neither → no balance and no more asking (until address, credential or setting change); unreachable/5xx → asked again after 10 min, never on traffic.read_at_ms) and setserror. Nothing here is on the forwarding path.tw_gateway::balances::parse) and a pure timing tracker (balances::tracker) are unit-tested; the fetch is thin.Protocol (CONTROL_API_VERSION 46)
Balance { source, read_at_ms, wallet: Money|null, quota: BalanceQuota|null, windows: BalanceWindow[], expires_at_ms, spent: Spent|null, error: Msg|null },BalanceWindow.scope: "key"|"user"|null,Spent.period: "today"|"month"|"total".ProviderView.balance: Balance | null,ProviderView.balance_setting: BalanceSetting(what config says, so the edit dialog can send it back),ProviderInput.balance?: BalanceSetting,ProviderTestResult.balance: Balance | null(read only when the check passed).{ kind: "balance_updated", id, provider, at_ms }.POST /providers/{name}/balance/refresh→Balance; 404control.balance_nonewhen the upstream has nothing to read, 404control.upstream_not_foundwhen it does not exist.New messages
control.balance_none— Upstream{upstream}has no balance to read.gw.balance.rejected— The balance could not be read: the upstream rejected the key (HTTP {status}).gw.balance.status— The balance could not be read: the upstream answered HTTP {status}.gw.balance.unrecognized— The balance could not be read: the answer is in an unrecognized format.gw.balance.timeout— The balance could not be read: no answer within {secs} seconds.gw.balance.connect— The balance could not be read: the upstream could not be reached.gw.balance.request_failed— The balance could not be read: {detail}An unknown
balance:value uses the existingconfig.unknown_variant(field, value, allowed values, line number), so the safe-mode one-click repair resets it toauto.Checks
cargo fmt --all -- --check,cargo clippy --workspace --all-targets -- -D warnings: cleanenv -u HTTP_PROXY -u HTTPS_PROXY -u http_proxy -u https_proxy cargo test --workspace: 3374 passed, 0 failed./scripts/smoke.sh: 82 passed, 0 failed (two new checks: the refresh endpoint and the overview fields)UPDATE_CONFIG_DOCS=1 cargo test -p tw-config --test manual,UPDATE_MSG_CODES=1 cargo test -p twcore --test msg_codes; TypeScript export checked withcargo run -p tw-api --features ts --example export_ts🤖 Generated with Claude Code