usage

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package usage fetches Claude subscription plan usage from Anthropic's OAuth usage endpoint — the same data the Claude Code CLI shows via /usage (5-hour session window, weekly window, and pay-as-you-go "extra usage").

This endpoint is NOT part of Anthropic's documented public API; it is the undocumented endpoint the Claude Code CLI uses, reconstructed from community reverse-engineering. Treat its shape as best-effort and degrade gracefully if it changes or disappears.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Extra

type Extra struct {
	IsEnabled     bool     `json:"is_enabled"`
	MonthlyLimit  *float64 `json:"monthly_limit"`
	UsedCredits   *float64 `json:"used_credits"`
	Utilization   *float64 `json:"utilization"`
	Currency      string   `json:"currency"`
	DecimalPlaces *int     `json:"decimal_places"`
}

Extra describes the pay-as-you-go ("extra usage") state. Pointer fields are null when extra usage is disabled or the value is not reported.

MonthlyLimit and UsedCredits are reported in the currency's MINOR units (e.g. cents), with DecimalPlaces giving the scale — so 2219 credits at 2 decimal places is 22.19. Use UsedAmount / MonthlyLimitAmount to get major units.

func (Extra) CurrencySymbol

func (e Extra) CurrencySymbol() string

CurrencySymbol maps the ISO currency code to a display symbol, falling back to the code itself (or "$" when unreported).

func (Extra) MonthlyLimitAmount

func (e Extra) MonthlyLimitAmount() (amount float64, ok bool)

MonthlyLimitAmount returns the extra-usage cap in major currency units. ok is false when the value is not reported.

func (Extra) UsedAmount

func (e Extra) UsedAmount() (amount float64, ok bool)

UsedAmount returns the extra-usage spend in major currency units. ok is false when the value is not reported.

type Fetcher added in v0.26.0

type Fetcher func(context.Context, *http.Client, string) (*Snapshot, error)

Fetcher permits provider-specific pollers.

type MoneyBucket added in v0.26.0

type MoneyBucket struct {
	ID        string `json:"id"`
	Label     string `json:"label"`
	Used      *int64 `json:"used_minor,omitempty"`
	Limit     *int64 `json:"limit_minor,omitempty"`
	Remaining *int64 `json:"remaining_minor,omitempty"`
	Currency  string `json:"currency,omitempty"`
	Decimals  *int   `json:"decimals,omitempty"`
}

MoneyBucket is an amount in minor units. Each pointer distinguishes an actual zero from an unreported value.

type MultiPoller added in v0.26.0

type MultiPoller struct {
	Pollers      map[string]*Poller
	StaticStatus map[string]ProviderStatus
	// contains filtered or unexported fields
}

MultiPoller serves independent provider caches. A failed provider does not hide healthy providers.

func (*MultiPoller) GetAll added in v0.26.0

func (m *MultiPoller) GetAll(ctx context.Context) (map[string]*Snapshot, map[string]ProviderStatus)

func (*MultiPoller) GetProvider added in v0.26.0

func (m *MultiPoller) GetProvider(ctx context.Context, provider string) (*Snapshot, error)

func (*MultiPoller) ObserveRateLimit added in v0.27.0

func (m *MultiPoller) ObserveRateLimit(provider, authKind string, fiveHour, sevenDay float64)

ObserveRateLimit records the latest account-wide plan windows reported by a provider response. Unknown windows (< 0) preserve their previous value, so a partial header set cannot erase useful telemetry from an earlier request. Values are fractions in [0,1], matching core.RateLimit.

func (*MultiPoller) StaticProviderStatus added in v0.26.0

func (m *MultiPoller) StaticProviderStatus(provider string) (ProviderStatus, bool)

StaticProviderStatus returns a provider state that is known without polling, such as an API-key account whose consumer-plan usage is unsupported.

type Plan added in v0.26.0

type Plan struct {
	Tier    string `json:"tier,omitempty"`
	Privacy string `json:"privacy,omitempty"`
}

Plan describes an account plan without making it a billing authority.

type Poller

type Poller struct {
	// contains filtered or unexported fields
}

Poller caches usage snapshots and refreshes them from the network at most once per minInterval. Concurrent callers single-flight through one fetch. Safe for concurrent use.

func NewPoller

func NewPoller(tokenFn TokenFunc) *Poller

NewPoller creates a Poller. tokenFn supplies the OAuth token on each refresh.

func NewProviderPoller added in v0.26.0

func NewProviderPoller(tokenFn TokenFunc, fetch Fetcher) *Poller

NewProviderPoller creates a generic provider poller. NewPoller remains the Anthropic compatibility constructor.

func (*Poller) Get

func (p *Poller) Get(ctx context.Context) (*Snapshot, error)

Get returns the latest usage snapshot, hitting the network only when the cached value is older than minInterval. It returns (nil, nil) when usage tracking is unavailable (no OAuth token). On a transient fetch error it serves the last good snapshot when one exists; otherwise it returns the error.

type ProviderStatus added in v0.26.0

type ProviderStatus struct {
	Available bool   `json:"available"`
	AuthKind  string `json:"auth_kind,omitempty"`
	Reason    string `json:"reason,omitempty"`
	Error     string `json:"error,omitempty"`
}

Status is returned even without a snapshot, so UIs never have to infer an API-key credential from absence. Values: pending, temporarily_unavailable, unsupported.

type Quota added in v0.26.0

type Quota struct {
	ID          string     `json:"id"`
	Label       string     `json:"label"`
	Utilization *float64   `json:"utilization,omitempty"`
	PeriodKind  string     `json:"period_kind,omitempty"`
	PeriodStart *time.Time `json:"period_start,omitempty"`
	PeriodEnd   *time.Time `json:"period_end,omitempty"`
}

Quota is a provider-neutral plan meter. Utilization is nil when the provider reports a period but not its consumption (zero is therefore preserved).

type Snapshot

type Snapshot struct {
	Provider  string        `json:"provider,omitempty"`
	AuthKind  string        `json:"auth_kind,omitempty"`
	Plan      Plan          `json:"plan,omitempty"`
	Quotas    []Quota       `json:"quotas,omitempty"`
	Money     []MoneyBucket `json:"money,omitempty"`
	FetchedAt time.Time     `json:"fetched_at"`
	Stale     bool          `json:"stale,omitempty"`
	Stability string        `json:"stability,omitempty"`

	FiveHour       *Window `json:"five_hour,omitempty"`
	SevenDay       *Window `json:"seven_day,omitempty"`
	SevenDayOpus   *Window `json:"seven_day_opus,omitempty"`
	SevenDaySonnet *Window `json:"seven_day_sonnet,omitempty"`
	Extra          Extra   `json:"extra_usage,omitempty"`
}

Snapshot is the generic, provider-qualified usage contract. The legacy Anthropic fields remain during migration for old REST clients and callers.

func Fetch

func Fetch(ctx context.Context, client *http.Client, token string) (*Snapshot, error)

Fetch retrieves a usage snapshot using the given OAuth access token.

func FetchXAI added in v0.26.0

func FetchXAI(ctx context.Context, client *http.Client, token string) (*Snapshot, error)

FetchXAI retrieves best-effort consumer plan data. It intentionally accepts only an OAuth token; callers must not invoke it for API-key authentication.

func (*Snapshot) NormalizeAnthropic added in v0.26.0

func (s *Snapshot) NormalizeAnthropic()

NormalizeAnthropic fills the generic fields while retaining the wire fields consumed by older clients.

type TokenFunc

type TokenFunc func(ctx context.Context) (token string, ok bool, err error)

TokenFunc returns the current Anthropic OAuth access token. ok is false when no OAuth credential is in use (e.g. a plain API key), in which case usage tracking is unavailable and the poller stays inert.

type Window

type Window struct {
	Utilization float64   `json:"utilization"`
	ResetsAt    time.Time `json:"resets_at"`
}

Window is a single rate-limit window (e.g. the 5-hour session window or the weekly window). Utilization is a percentage in [0, 100].

Jump to

Keyboard shortcuts

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