limits

package
v0.16.397 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 27 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

View Source
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
)
View Source
const (
	CodexUsageURL      = "https://chatgpt.com/backend-api/wham/usage"
	CodexUsageInterval = 120 * time.Second
)
View Source
const (
	SourceCodexbar   = "codexbar"
	SourceCodexUsage = "codex-usage"
)

Sources.

View Source
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
)
View Source
const (
	SourceKimiUsages  = "kimi-usages"
	SourceZaiQuota    = "zai-quota"
	SourceGrokBilling = "grok-billing"
	SourceMoonshot    = "moonshot-balance"
	SourceDeepSeek    = "deepseek-balance"
	SourceOpenRouter  = "openrouter-credits"
)

Sources of the vendors.

View Source
const CodexLoginPrefix = "cx-"

CodexLoginPrefix starts the id of a profile that is one more sign-in of the Codex CLI.

View Source
const (
	CodexbarInterval = 60 * time.Second
)
View Source
const HistoryKeepSec = 8 * 86400

HistoryKeepSec is how much history the rotation keeps.

View Source
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.

View Source
const WindowMonth = "month"

WindowMonth is the monthly pool some vendors have besides the two windows of Claude.

Variables

View Source
var CodexbarArgs = []string{"usage", "--provider", "claude", "--source", "oauth", "--format", "json"}

CodexbarArgs is the fixed command line.

View Source
var Providers = []string{"claude", "codex"}

Providers are the entries rate-limits.json holds.

Functions

func APIProfile

func APIProfile(preset string) string

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 CodexHome

func CodexHome(env, home string) string

CodexHome is $CODEX_HOME, else ~/.codex.

func CodexbarBin

func CodexbarBin(path string) string

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

func ExhaustedReset(d Data, now float64) float64

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

func ProfileKey(profile, account string) string

ProfileKey is the key of an account's entry: the profile, and the account when the profile has more than one.

func RotateHistory

func RotateHistory(file string, now float64) error

RotateHistory keeps the last eight days; the file is replaced atomically and stays 0600. A missing file is left so.

func Sanitize

func Sanitize(text string) string

Sanitize is error text safe to store and show: no e-mail addresses, no control characters, at most 200 units.

func ShouldRecord

func ShouldRecord(prevT float64, prev *Windows, w Windows, now float64) bool

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.

func Watch

func Watch(ctx context.Context, file string, onChange func(map[string]any))

Watch reports the file's content every time its top-level `ts` changes: once at the start, then after writes settle. A directory that is missing or a watch that fails is retried every few seconds. It returns when ctx ends.

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.

func (Account) Key

func (a Account) Key() string

Key is the key of the account's entry.

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.

func (*Cache) Read

func (c *Cache) Read() map[string]Data

Read is the stored providers; a missing or broken file is empty.

func (*Cache) Write

func (c *Cache) Write(provider string, data Data) (map[string]any, error)

Write merges data into the provider's entry and returns the whole new content.

type ClaudeLogin

type ClaudeLogin struct {
	AccessToken string
	ExpiresAt   float64
}

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

type CodexLogin struct {
	AccessToken string
	AccountID   string
}

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

type Data = map[string]any

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

func CodexTranscriptLimits(path string, now float64) Data

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

func Merge(prev, next Data) Data

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

func ParseClaudeUsage(body any, now float64) Data

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

func ParseCodexUsage(body any, now float64) Data

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

func ParseCodexbar(stdout []byte, now float64) (Data, string)

ParseCodexbar reads codexbar's answer measured at now (epoch seconds): the provider data, or the failure message.

func ParseDeepSeekBalance

func ParseDeepSeekBalance(body any, now float64) Data

ParseDeepSeekBalance reads DeepSeek's balance of a key: `balance_infos`, of which the dollar one is taken, else the first.

func ParseGrokCredits

func ParseGrokCredits(body any, now float64) Data

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

func ParseKimiUsage(body any, now float64) Data

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

func ParseMoonshotBalance(body any, currency string, now float64) Data

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

func ParseOpenRouterCredits(body any, now float64) Data

ParseOpenRouterCredits reads OpenRouter's credits: what was bought less what was spent, in dollars.

func ParseZaiQuota

func ParseZaiQuota(body any, now float64) Data

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.

func (*History) Record

func (h *History) Record(cache map[string]any, now float64) error

Record appends a line for every provider of the content whose state is worth one; now is epoch seconds.

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

type NamedWindow struct {
	ID string
	W  Window
}

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.

func (*Pollers) Run

func (p *Pollers) Run(ctx context.Context)

Run polls until ctx ends: codexbar every minute when configured, Codex's usage every two minutes while the machine has a ChatGPT login of Codex (re-read every time, Codex refreshes it).

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

func (c *ProfileCache) Fail(a Account, message string, forget bool, now float64) error

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.

func (*Profiles) Refresh

func (p *Profiles) Refresh(ctx context.Context)

Refresh is one pass over the accounts.

func (*Profiles) Touch

func (p *Profiles) Touch()

Touch says someone looks at the limits: the accounts that were not asked lately are asked, in the background and one at a time. A pass that still runs is not doubled.

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.

func (Record) Get

func (r Record) Get(id string) (Window, bool)

Get is the record's window of an id.

type RunCodexbar

type RunCodexbar func(ctx context.Context, bin string, args []string) ([]byte, error)

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.

func SamplesOf

func SamplesOf(records []Record, provider, windowID string) []Sample

SamplesOf is one window of one provider, sorted by measurement time, one sample per measurement (the last line that carries it).

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.

func VendorOf

func VendorOf(profile string) (Vendor, bool)

VendorOf is how the limits of a profile are asked; ok is false for a profile that has no such request.

type Window

type Window [3]float64

Window is a history tuple: used %, resets at, measured at.

type Windows

type Windows struct {
	IDs    []string
	Tuples map[string]Window
}

Windows keeps the order the tuples are written in.

func HistoryWindows

func HistoryWindows(d Data) Windows

HistoryWindows is one provider as history tuples: 5 h, 7 d and codexbar's extra windows under their own ids.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL