Skip to content

feat(gateway): read each upstream's balance - #321

Merged
fylorn merged 1 commit into
mainfrom
feat/upstream-balances
Oct 10, 2026
Merged

fylorn merged 1 commit into
mainfrom
feat/upstream-balances

Conversation

@fylorn

@fylorn fylorn commented Oct 10, 2026

Copy link
Copy Markdown
Contributor

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 of base_url, not on a base path such as /anthropic).

source endpoint(s) becomes
openrouter /api/v1/key, then /api/v1/credits when the key has no limit quota (USD), or wallet = credits − usage
deepseek /user/balance wallet: the first currency with money, else the first
moonshot /v1/users/me/balance wallet (CNY on .cn, USD on .ai)
sub2api /v1/usage quota_limited: quota + rate-limit windows; unrestricted: daily/weekly/monthly windows and/or wallet; expires_at; usage.today.cost as spent (today)
newapi /v1/dashboard/billing/subscription + /usage quota (USD, usage in cents); an unlimited key (≥ 1e8) only reports spent (total); access_until as expiry
thinkwatch /v1/usage every limits entry a window (unit = kind, with scope), usage.cost_usd_month as spent (month), expires_at
  • Config: providers[].balance: auto | off | openrouter | deepseek | moonshot | sub2api | newapi | thinkwatch, default auto (not written). auto knows openrouter.ai, api.deepseek.com, api.moonshot.cn / .ai; any other host (except Anthropic's, OpenAI's and Gemini's own) is asked once: /v1/usage with a string mode → sub2api (with a limits array → thinkwatch), else /v1/dashboard/billing/subscription with hard_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.
  • Never read: ChatGPT accounts, Z.ai / BigModel hosts, Bedrock, OAuth credentials, upstreams without a key, disabled upstreams.
  • When: at start; at most once per 60 s after a request through the upstream ends (a guard dropped with the response body / WebSocket turn, so client disconnects count); every 10 min otherwise; on demand. A failed read keeps the last good reading (and its read_at_ms) and sets error. Nothing here is on the forwarding path.
  • Pure parsers (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).
  • Event { kind: "balance_updated", id, provider, at_ms }.
  • POST /providers/{name}/balance/refresh → Balance; 404 control.balance_none when the upstream has nothing to read, 404 control.upstream_not_found when 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 existing config.unknown_variant (field, value, allowed values, line number), so the safe-mode one-click repair resets it to auto.

Checks

  • cargo fmt --all -- --check, cargo clippy --workspace --all-targets -- -D warnings: clean
  • env -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 with cargo run -p tw-api --features ts --example export_ts
  • No real third-party service is called by any test; every server is a local fake.

🤖 Generated with Claude Code

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>
@fylorn
fylorn merged commit f90456a into main Oct 10, 2026
5 checks passed
@fylorn
fylorn deleted the feat/upstream-balances branch October 10, 2026 14:42
This was referenced Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant