Documentation
¶
Overview ¶
Package limits keeps the machine's subscription limits: rate-limits.json, one entry per provider merged field by field from every source that measures them (the agent's statusline, codexbar, Codex's usage endpoint, the Codex transcript), its watcher, and limits-history.jsonl for the burn-rate forecast.
Index ¶
- Constants
- Variables
- func APIProfile(preset string) string
- func CodexHome(env, home string) string
- func CodexbarBin(path string) string
- func ExhaustedReset(d Data, now float64) float64
- func ProfileKey(profile, account string) string
- func RotateHistory(file string, now float64) error
- func Sanitize(text string) string
- func ShouldRecord(prevT float64, prev *Windows, w Windows, now float64) bool
- func Watch(ctx context.Context, file string, onChange func(map[string]any))
- type Account
- type Cache
- type ClaudeLogin
- type CodexLogin
- type Credential
- type Data
- func CodexTranscriptLimits(path string, now float64) Data
- func FetchClaudeUsage(ctx context.Context, login ClaudeLogin, client *http.Client, url string, ...) (Data, error)
- func Merge(prev, next Data) Data
- func ParseClaudeUsage(body any, now float64) Data
- func ParseCodexUsage(body any, now float64) Data
- func ParseCodexbar(stdout []byte, now float64) (Data, string)
- func ParseDeepSeekBalance(body any, now float64) Data
- func ParseGrokCredits(body any, now float64) Data
- func ParseKimiUsage(body any, now float64) Data
- func ParseMoonshotBalance(body any, currency string, now float64) Data
- func ParseOpenRouterCredits(body any, now float64) Data
- func ParseZaiQuota(body any, now float64) Data
- func PollCodexUsageOnce(ctx context.Context, login CodexLogin, client *http.Client, url string, ...) (Data, error)
- func PollCodexbarOnce(ctx context.Context, bin string, run RunCodexbar, cache *Cache, ...) (Data, error)
- type History
- type HistoryReader
- type NamedWindow
- type Pollers
- type ProfileCache
- type Profiles
- type Record
- type RunCodexbar
- type Sample
- type Vendor
- type Window
- type Windows
Constants ¶
const ( SourceClaudeUsage = "claude-usage" ClaudeUsageURL = "https://api.anthropic.com/api/oauth/usage?skip_spend=1" // ClaudeUsageInterval: the CLI asks on its own /usage only; a few minutes keeps the numbers fresh without weight. ClaudeUsageInterval = 5 * time.Minute // ClaudeActiveSec: only while a Claude chat runs (its statusline came lately) is the account asked at all. ClaudeActiveSec = 10 * 60 )
const ( CodexUsageURL = "https://chatgpt.com/backend-api/wham/usage" CodexUsageInterval = 120 * time.Second )
const ( SourceCodexbar = "codexbar" SourceCodexUsage = "codex-usage" )
Sources.
const ( // ProfileMinInterval is the shortest time between two requests for one account. ProfileMinInterval = 5 * time.Minute // ProfileFailedInterval is how long a failed request is left alone. ProfileFailedInterval = 15 * time.Minute )
const ( SourceKimiUsages = "kimi-usages" SourceZaiQuota = "zai-quota" SourceGrokBilling = "grok-billing" SourceMoonshot = "moonshot-balance" SourceDeepSeek = "deepseek-balance" SourceOpenRouter = "openrouter-credits" )
Sources of the vendors.
const CodexLoginPrefix = "cx-"
CodexLoginPrefix starts the id of a profile that is one more sign-in of the Codex CLI.
const (
CodexbarInterval = 60 * time.Second
)
const HistoryKeepSec = 8 * 86400
HistoryKeepSec is how much history the rotation keeps.
const PrecedenceSec = 180
PrecedenceSec is how long a fresh value of a usage endpoint outranks the statusline and the Codex transcript: those echo what the CLI saw on its last request and would only make the percentage jump back and forth.
const WindowMonth = "month"
WindowMonth is the monthly pool some vendors have besides the two windows of Claude.
Variables ¶
var CodexbarArgs = []string{"usage", "--provider", "claude", "--source", "oauth", "--format", "json"}
CodexbarArgs is the fixed command line.
var Providers = []string{"claude", "codex"}
Providers are the entries rate-limits.json holds.
Functions ¶
func APIProfile ¶
APIProfile is the profile of a provider of the registry by API (internal/extproviders) made from that preset: its entries stand apart from the chat profiles', which may share a vendor's name.
func CodexbarBin ¶
CodexbarBin is the configured CLI when it is an absolute path; otherwise there is no poller at all.
func ExhaustedReset ¶ added in v0.15.40
ExhaustedReset is when the windows of an entry that ran out reset (unix seconds), the latest of them: what the limits say a chat held on its usage limit waits for. 0 when no window is at its limit, or none resets after now.
func ProfileKey ¶
ProfileKey is the key of an account's entry: the profile, and the account when the profile has more than one.
func RotateHistory ¶
RotateHistory keeps the last eight days; the file is replaced atomically and stays 0600. A missing file is left so.
func Sanitize ¶
Sanitize is error text safe to store and show: no e-mail addresses, no control characters, at most 200 units.
func ShouldRecord ¶
ShouldRecord is whether a provider's new state is worth a line: some window was measured after the previous line, and either a value changed or that line is a minute old.
Types ¶
type Account ¶
type Account struct {
Profile string
// Account names the account among the profile's (an email of a sign-in, the name of a saved key); empty for the
// only one.
Account string
// Credential is read when the request is made and never kept.
Credential func(ctx context.Context) (Credential, error)
}
Account is one account of a profile whose limits can be asked.
type Cache ¶
type Cache struct {
File string
// contains filtered or unexported fields
}
Cache is rate-limits.json. Every read-merge-write goes through one lock; the file is replaced, never rewritten in place, because other writers (a root timer copying limits between accounts) and the watcher read it at any moment.
type ClaudeLogin ¶
ClaudeLogin is the bearer of the machine's Claude sign-in and when it expires (epoch ms; 0 when unknown).
func ReadClaudeLogin ¶
func ReadClaudeLogin(dirs ...string) *ClaudeLogin
ReadClaudeLogin is the first sign-in found in the folders, in order (Claude Code's own, then the machine's managed sign-in); nil without one.
type CodexLogin ¶
CodexLogin is the ChatGPT login of Codex.
func ReadCodexLogin ¶
func ReadCodexLogin(codexHome string) *CodexLogin
ReadCodexLogin is the login in <codex home>/auth.json; nil for an API-key login or no login at all.
type Credential ¶
type Credential struct {
Token string
Login bool
// Account is the account of the sign-in the vendor wants named beside the token (Vendor.AccountHeader); "" for none.
Account string
}
Credential is what a request for the limits is authorised with: the saved key of the profile, or the token of the vendor CLI's sign-in (Login).
type Data ¶
Data is one provider's entry as it is stored: a JSON object whose fields beyond the windows are optional, so writers merge field by field and fields a writer does not know survive.
func CodexTranscriptLimits ¶
CodexTranscriptLimits reads the limits Codex wrote into the tail of its transcript; nil when there are none.
func FetchClaudeUsage ¶
func FetchClaudeUsage(ctx context.Context, login ClaudeLogin, client *http.Client, url string, now float64) (Data, error)
FetchClaudeUsage asks Anthropic once; nil data with an error on a refusal or a failure (the file keeps what it has).
func Merge ¶
Merge is one provider's merge: a window or a codexbar field is replaced only by a value measured later, so the statusline never wipes codexbar's plan, pace or extra windows, and a stale copy never overwrites a fresh one.
func ParseClaudeUsage ¶
ParseClaudeUsage is the plan's windows as the answer has them: the five hours and the week, null when the plan has none, and the weekly limit of a model as an extra window titled by the model. Nil when the answer is not usage.
func ParseCodexUsage ¶
ParseCodexUsage is both windows as the plan has them now. A Pro plan has only the weekly one, so the missing window is written as null and replaces whatever an older transcript copy left there. Nil when the answer has no window.
func ParseCodexbar ¶
ParseCodexbar reads codexbar's answer measured at now (epoch seconds): the provider data, or the failure message.
func ParseDeepSeekBalance ¶
ParseDeepSeekBalance reads DeepSeek's balance of a key: `balance_infos`, of which the dollar one is taken, else the first.
func ParseGrokCredits ¶
ParseGrokCredits reads the billing of a Grok subscription as the Grok CLI asks it: `config.creditUsagePercent` (else the spent over the cap) of the current period, weekly on today's plans. A period whose length is told and is a month goes to the monthly window.
func ParseKimiUsage ¶
ParseKimiUsage reads the answer of Kimi Code's usages: the weekly count in `usage`, the counted windows in `limits` (the five hours as 300 minutes), and on newer plans the shares in `usages` (`limit_5h`, `limit_7d`, `limit_month_total` with `used_ratio` 0..1), which replace a count of the same window.
func ParseMoonshotBalance ¶
ParseMoonshotBalance reads the balance of a Moonshot platform account: what is left to spend, in the currency of the platform the key is of.
func ParseOpenRouterCredits ¶
ParseOpenRouterCredits reads OpenRouter's credits: what was bought less what was spent, in dollars.
func ParseZaiQuota ¶
ParseZaiQuota reads the quota of a GLM Coding Plan (Z.ai and bigmodel.cn answer alike): `data.limits`, of which the TOKENS_LIMIT entries are the plan's windows, `unit` 3 × `number` 5 being the five hours and `unit` 6 × 1 the week, with `percentage` spent and `nextResetTime` in milliseconds. TIME_LIMIT is the monthly count of the plan's MCP tools, not of the model, and is left out.
func PollCodexUsageOnce ¶
func PollCodexUsageOnce(ctx context.Context, login CodexLogin, client *http.Client, url string, cache *Cache, clock func() float64) (Data, error)
PollCodexUsageOnce asks ChatGPT once and writes the answer (or the failure) as Codex's entry.
func PollCodexbarOnce ¶
func PollCodexbarOnce(ctx context.Context, bin string, run RunCodexbar, cache *Cache, clock func() float64) (Data, error)
PollCodexbarOnce runs codexbar once and writes the result (or the failure) as Claude's entry.
type History ¶
type History struct {
File string
// contains filtered or unexported fields
}
History appends to limits-history.jsonl. What it wrote last lives in memory only, so the first state after a start always gets a line.
type HistoryReader ¶
type HistoryReader struct {
File string
// contains filtered or unexported fields
}
HistoryReader keeps every record of the last eight days and reads only what was appended since its previous call. A file replaced (another inode) or cut shorter is read again from the start.
func (*HistoryReader) Read ¶
func (h *HistoryReader) Read(now float64) []Record
Read is every record of the last eight days before now (epoch seconds). The slice is the reader's own: callers do not change it.
type NamedWindow ¶
NamedWindow is one window of a record.
type Pollers ¶
type Pollers struct {
Cache *Cache
CodexbarBin string // absolute path, or empty for no codexbar poller
CodexHome string
Client *http.Client
URL string // the Codex usage endpoint
// ClaudeDirs are the folders of the machine's Claude sign-in, in order; none: no Claude usage poller.
ClaudeDirs []string
ClaudeURL string
Clock func() float64
RunCLI RunCodexbar
// Warn gets the failures that are only worth a log line.
Warn func(msg string, err error)
}
Pollers ask the usage endpoints on their own schedule. Each one is single-flight: a slow run delays the next instead of piling up.
type ProfileCache ¶
type ProfileCache struct {
File string
// contains filtered or unexported fields
}
ProfileCache is provider-limits.json: {"ts": …, "entries": {<key>: entry}}. The file is replaced, never rewritten in place.
func (*ProfileCache) Fail ¶
Fail notes a failed request on the account's entry and keeps what it last answered; with forget, nothing of it.
func (*ProfileCache) Keep ¶
func (c *ProfileCache) Keep(keys map[string]bool, now float64) error
Keep drops the entries of accounts that are no more (a removed key, a signed-out CLI).
func (*ProfileCache) Put ¶
func (c *ProfileCache) Put(a Account, data Data, now float64) error
Put stores an answer as the account's entry, whole: the vendor listed every window it has.
func (*ProfileCache) Read ¶
func (c *ProfileCache) Read() map[string]Data
Read is the stored entries; a missing or broken file is empty.
type Profiles ¶
type Profiles struct {
Cache *ProfileCache
// Accounts lists the accounts that have a credential now.
Accounts func() []Account
// Client sends the requests; nil is one that follows no redirect (a redirect would carry the credential to the host
// it points at).
Client *http.Client
// URL overrides a vendor's address (tests).
URL func(profile string, v Vendor) string
Clock func() float64
Warn func(msg string, err error)
// contains filtered or unexported fields
}
Profiles asks the vendors.
type Record ¶
type Record struct {
T float64
P string
W []NamedWindow
}
Record is one line of limits-history.jsonl as the forecast reads it: its windows that are whole tuples of finite numbers. The windows are kept in the record itself and their names shared, so a scan over a week of lines stays in cache.
type RunCodexbar ¶
RunCodexbar runs the CLI; codexbar exits 1 with a JSON error entry on stdout, which is more useful than the exit code.
type Sample ¶
type Sample struct {
T, U, R float64
}
Sample is one measurement of a window: epoch seconds, percent used, reset time.
type Vendor ¶
type Vendor struct {
Source string
URL string
// Auth puts the credential on the request the way the vendor's own client does.
Auth func(req *http.Request, token string)
// Parse is the entry of an answer; nil when it has nothing to show.
Parse func(body any, now float64) Data
// Refused says an answer that came as a success refuses the credential (Z.ai answers 200 with its own code); nil
// when the vendor refuses by the HTTP status alone.
Refused func(body any) bool
// LoginOnly: the request works with the CLI's sign-in only, a saved API key has no such answer.
LoginOnly bool
// Unofficial: the request is the vendor's internal one, known from outside its own sources. Its entry says so, and
// a failure leaves nothing of the last answer: what such a source said before it broke is not to be trusted.
Unofficial bool
// AccountHeader is the header the account of a sign-in goes in; "" when the vendor wants none.
AccountHeader string
// Host is the host a provider of the registry must point at for the request to be made with its key; empty for a
// chat profile, whose address the runtime owns.
Host string
}
Vendor is how one vendor's limits are asked.