Documentation
¶
Overview ¶
Package ccusage reads each pooled Claude account's SUBSCRIPTION UTILIZATION — the numbers Claude Code's `/usage` screen shows (the 5-hour session window, the 7-day window, and the per-model windows when the account has them) — and keeps the latest reading per (owner, account), numbers only.
The endpoint ¶
Endpoint is the one Claude Code's `/usage` calls. Read from the CLI bundle (2.1.289): `GET ${BASE_API_URL}/api/oauth/usage` with BASE_API_URL `https://api.anthropic.com`, the OAuth access token as `Authorization: Bearer`, and `anthropic-beta: oauth-2025-04-20` (the CLI's OAuth beta, sent beside every OAuth bearer it holds). Its answer is a JSON object whose window keys (`five_hour`, `seven_day`, `seven_day_opus`, `seven_day_sonnet`, …) are each null or `{"utilization": <percent 0-100>, "resets_at": "<RFC 3339>"}` (the CLI's own schema describes utilization as "Percentage of the window used, 0-100"), plus a `limits` array whose per-model weekly rows carry `scope.model.display_name`, `percent` and `resets_at`. One live call (a full-scope claude.ai login) answered 200 in exactly that shape, with `five_hour` null (no session window open) and dozens of other null keys.
🔴 A `setup-token` IS REFUSED THERE. The pool's tokens are `claude setup-token` tokens, which the CLI mints inference-only (scope `user:inference`); the endpoint answers them 403 `permission_error` ("OAuth token does not meet scope requirement user:profile"), measured against a pool token, and it rate-limits hard (429 with a Retry-After of about an hour). So an account's token gets ONE discovery call to it; a 2xx keeps the endpoint for that token, a 401/403 retires it for that token for good.
The probe (every other token) ¶
ProbeURL is a minimal inference call — `POST /v1/messages`, max_tokens 1, one user message, on ProbeModel — which a setup-token CAN make, and whose answer carries the subscription's state in `anthropic-ratelimit-unified-*` headers (ParseRateLimitHeaders): per window (`5h` five_hour, `7d` seven_day, `7d_oi` seven_day_overage_included, `overage`; the CLI bundle's own map) `-utilization` (a 0-1 FRACTION, stored here ×100 as a percent like the endpoint's), `-reset` (unix seconds) and `-status`, plus the overall `-status`, `-reset` and `-representative-claim`. A window whose headers are absent is absent (a measured 200 carried 7d headers and no 5h ones). It costs one output token of quota, so its default interval is 15 minutes, and an account the pool marks rate-limited is not probed until its reset.
🔴 A READING HOLDS NO CREDENTIAL. The token is read from the account pool at the moment of the call and sent in one header; no error, log line or stored row carries it. A row carries the token's ccpool.Fingerprint only, so a refusal mark expires when the token is replaced.
Index ¶
- Constants
- Variables
- func Attribute(now time.Time, agentUses []AgentUse, jobs []JobCount, officerOf OfficerOf) map[string]UsedBy
- func Backoff(interval time.Duration, streak int, retryAfter time.Duration) time.Duration
- func CheckPushURL(u string) error
- func PushInstance(explicit, publicURL string) (string, error)
- type AgentUse
- type Fetcher
- type HTTPFetcher
- type JobCount
- type JobUse
- type OfficerOf
- type OfficerUse
- type PGStore
- func (s *PGStore) AgentsSince(ctx context.Context, owner int64, since, now time.Time) ([]AgentUse, error)
- func (s *PGStore) JobCounts(ctx context.Context, owner int64, now time.Time) ([]JobCount, error)
- func (s *PGStore) Latest(ctx context.Context, owner int64) (map[string]Row, error)
- func (s *PGStore) Save(ctx context.Context, owner int64, r Row) error
- type Poller
- type PoolUse
- type Pusher
- type Reading
- type Result
- type Row
- type StepConfig
- type Store
- type Usage
- type UsedBy
- type Window
Constants ¶
const ( Day = 24 * time.Hour Week = 7 * 24 * time.Hour )
The two windows usage is counted over.
const ( // KindNoToken: the account has no token to read with. No call is made. KindNoToken = "no_token" // inference call at all. Not read again until its token changes. KindUnauthorized = "unauthorized" // KindForbidden: the probe answered 403. Not read again until its token // changes. (A 403 from the usage endpoint is not this: it only retires the // endpoint for the token, Row.UsageAPI.) KindForbidden = "forbidden" // KindRateLimited: the probe answered 429. The account backs off // (Row.NextAt), doubling per consecutive 429, at least Retry-After. KindRateLimited = "rate_limited" // KindCooling: the account pool marks the account rate-limited (a turn on // it hit its limit) and its cooldown has not ended, so it is not probed // until then (Row.NextAt). KindCooling = "cooling" // KindError: anything else (a 5xx, a network error, an answer with no // rate-limit headers). The next pass tries again. KindError = "error" )
Why an account's latest attempt did not produce a reading (Row.ErrorKind). "" is a good reading.
const ( // UsageAPIUntried: never called with this token; the next read makes the // one discovery call. UsageAPIUntried = "" // UsageAPIOK: a call with this token succeeded; it is read that way. UsageAPIOK = "ok" // UsageAPIRefused: the endpoint refused this token (401/403, a setup-token // without the profile scope); it is never called with it again. UsageAPIRefused = "refused" )
The usage endpoint's state for an account's CURRENT token (Row.UsageAPI).
const ( DefaultInterval = 15 * time.Minute MinInterval = 5 * time.Minute MaxInterval = 24 * time.Hour // MaxBackoff caps a rate-limited account's wait. MaxBackoff = 6 * time.Hour )
Poll interval bounds and default (MUSTER_CC_USAGE_POLL_INTERVAL). The probe spends a token of quota per account per read, hence 15 minutes.
const ( PushReasonBuild = "build" PushReasonTimeout = "timeout" PushReasonTransport = "transport" PushReason4xx = "http_4xx" PushReason5xx = "http_5xx" PushReasonOther = "http_other" // PushReasonCanceled: muster was shutting down mid-push. PushReasonCanceled = "canceled" )
Why a push failed: muster_cc_usage_push_failures_total's `reason`, a closed vocabulary (never a URL, a status code or an account).
const ( ProbeURL = "https://api.anthropic.com/v1/messages" ProbeModel = "claude-haiku-4-5-20251001" )
ProbeURL and ProbeModel are the one-token probe (see the package doc).
const ( SourceUsageAPI = "usage_api" SourceRateLimitHeaders = "ratelimit_headers" )
Where a reading came from (Row.Source).
const ( FiveHour = "five_hour" SevenDay = "seven_day" )
The two windows every subscription account has.
const ( MaxWindows = 24 MaxResponseBody = 1 << 20 )
Bounds on what one reading may hold, so an answer of an unexpected shape cannot grow a row without limit.
const BetaHeader = "oauth-2025-04-20"
BetaHeader is the anthropic-beta value the CLI sends with an OAuth bearer.
const Endpoint = "https://api.anthropic.com/api/oauth/usage"
Endpoint is Claude Code's `/usage` endpoint (see the package doc).
const MaxPushInstance = 64
MaxPushInstance bounds the pushed source_instance label.
const PushTimeout = 10 * time.Second
PushTimeout bounds one push, connection to answer.
Variables ¶
var ErrNotUsage = errors.New("ccusage: not a usage answer")
ErrNotUsage is a body that is not a usage answer: not a JSON object, or an Anthropic error object.
var Kinds = []string{"", KindNoToken, KindUnauthorized, KindForbidden, KindRateLimited, KindCooling, KindError}
Kinds is every ErrorKind a row may hold ("" included), in the order the migration's CHECK spells them (TestKindsMatchTheMigration).
Functions ¶
func Attribute ¶
func Attribute(now time.Time, agentUses []AgentUse, jobs []JobCount, officerOf OfficerOf) map[string]UsedBy
Attribute is who used each account, by account name. An agent counts in a window when it was active inside it (LastActive at or after now minus the window); an agent with no account is not counted.
func Backoff ¶
Backoff is a rate-limited account's wait after its streak-th consecutive 429: interval doubled per 429 (interval·2^streak), at least retryAfter, at most MaxBackoff.
func CheckPushURL ¶
CheckPushURL is why u cannot be the push target, or nil. It must be an absolute https URL with a host and no userinfo; plain http is allowed only to a loopback host (a test's server), since the request carries the bearer.
func PushInstance ¶
PushInstance is the source_instance label: explicit (≤ MaxPushInstance characters, refused otherwise), else the public URL's host when it fits, else "muster".
Types ¶
type AgentUse ¶
AgentUse is one claude-code agent that ran in the last week: its name, account and worker pool, and when it last ran (now for a live agent, else when it stopped).
type Fetcher ¶
type Fetcher interface {
// Usage calls the usage endpoint.
Usage(ctx context.Context, token string) Result
// Probe makes the one-token Messages call and reads its headers.
Probe(ctx context.Context, token string) Result
}
Fetcher makes the two calls with one token.
type HTTPFetcher ¶
type HTTPFetcher struct {
Client *http.Client
// URL and ProbeURL are the endpoints; "" is [Endpoint] / [ProbeURL].
URL string
ProbeURL string
}
HTTPFetcher is the real Fetcher.
type JobUse ¶
JobUse is the jobs one requester (a service caller's X-Muster-Actor, "" for none) ran on an account.
type OfficerOf ¶
OfficerOf says which officer pool an agent name is an instance of: the officer id and its pool ("routine", "judgement", or "" for an untiered officer), and whether that pool reaches its model through muster's LLM proxy (onProxy). ok is false for any other agent.
type OfficerUse ¶
type OfficerUse struct {
Officer string `json:"officer"`
Pool string `json:"pool,omitempty"`
Instances int `json:"instances"`
}
OfficerUse is the instances of one officer pool that ran on an account.
type PGStore ¶
type PGStore struct {
// contains filtered or unexported fields
}
PGStore is Store on cc_account_usage (migration 0108), plus the attribution reads over agents and jobs. Every query names the owner: the tables are under row-level security, which scopes a user principal on its own, and the owner predicate keeps a scope-all caller from merging two owners' accounts of one name (ccpool.PGStore's rule).
func (*PGStore) AgentsSince ¶
func (s *PGStore) AgentsSince(ctx context.Context, owner int64, since, now time.Time) ([]AgentUse, error)
AgentsSince is every one of owner's claude-code agents on an account that is live now or stopped at or after since, with when it was last active (now for a live one).
func (*PGStore) JobCounts ¶
JobCounts is owner's jobs created in the last week, by the account their last turn ran on and their requester, counted over the last day and week before now.
type Poller ¶
type Poller struct {
// Source is the account pool's source (internal/credentials.Plane): the
// accounts, and their tokens, read at each pass.
Source ccpool.Source
Store Store
Fetch Fetcher
// Cooling is when the account pool's rate-limit cooldown for an account
// ends (ccpool.Pool.CoolingUntil; zero when it is not cooling). nil: no
// account is ever cooling. A read error is logged and treated as cooling
// for one interval: the probe spends quota, so it fails toward not probing.
Cooling func(ctx context.Context, owner int64, account string) (time.Time, error)
// Owner is the user whose accounts are read: the operator (user 1), whose
// environment pool this is. Members' own accounts are not polled.
Owner int64
Interval time.Duration
Logger *log.Logger
Now func() time.Time
// AfterPass, when set, runs once after each pass (Run), whether or not the
// pass read anything: the usage pusher (Pusher.PushAfterPass,
// MUSTER_CC_USAGE_PUSH_URL). It runs in the poll loop, so one cycle makes
// at most one call of it, and a slow one delays the next pass rather than
// overlapping it.
AfterPass func(ctx context.Context)
}
Poller reads every account of Owner on each pass and saves one Row per account.
type Pusher ¶
type Pusher struct {
URL string
Token string
// Body is the request body for a push made at now: the readings exactly as
// GET /api/cc-accounts/usage answers them, with the instance label and
// read_at (api.Server.CCUsagePushBody).
Body func(ctx context.Context, now time.Time) ([]byte, error)
Client *http.Client
Logger *log.Logger
Now func() time.Time
// Timeout bounds one push; 0 is PushTimeout.
Timeout time.Duration
}
Pusher PUTs the readings to an external dashboard once per poll cycle (Poller.AfterPass). It holds no state across pushes: a failed push is logged and counted, and the next cycle's push carries the newer readings — there is no retry inside a cycle.
🔴 THE TOKEN IS IN ONE HEADER AND NOWHERE ELSE, and the body is never logged: a failure is logged as its class (a status, timeout, transport error), never the URL's query, the request or the answer's body.
func (*Pusher) Push ¶
Push makes one push and reports its failure reason ("" for a 204). It is Poller.AfterPass's shape once wrapped (PushAfterPass).
func (*Pusher) PushAfterPass ¶
PushAfterPass is Push as a Poller.AfterPass.
type Reading ¶
type Reading struct {
Windows map[string]Window
Status string
RepresentativeClaim string
ResetsAt *time.Time
}
Reading is one answer: its windows, by name (a window sent as null, or with no headers, is absent), and — from the probe's headers only — the overall status, the window that decides it and when it resets.
func Parse ¶
Parse reads a 200 answer of Endpoint.
Every top-level key whose value is an object carrying `utilization` is a window (the endpoint adds windows under new names; a key that is null, or an object without `utilization` such as `spend`, is not; nor is one whose utilization and resets_at are both null, such as an `extra_usage` money block that is off). Each `limits[]` row with a model scope is a per-model weekly window, `seven_day_model:<display name, lowercased>`, from its `percent` — unless a top-level key already carries that name. At most MaxWindows, by name.
func ParseRateLimitHeaders ¶
ParseRateLimitHeaders reads the `anthropic-ratelimit-unified-*` headers of a Messages answer (see the package doc). ok is false when the answer carries none of them. A garbage value is dropped (that value only): a utilization that is not a finite number in [0, 100], a reset that is not unix seconds, a status that is not a short word.
type Result ¶
type Result struct {
// Status is the HTTP status; 0 when no answer came (Err set).
Status int
// Reading is the parsed answer: the usage endpoint's body on a 200, or the
// probe's rate-limit headers on any status (HasReading says it had them).
Reading Reading
HasReading bool
// RetryAfter is a 429's Retry-After, when it stated seconds.
RetryAfter time.Duration
// Err is a transport failure or an unreadable 200. It never carries the
// token or a body.
Err error
}
Result is one call of the usage endpoint or of the probe.
type Row ¶
type Row struct {
Account string
// Windows, Source, Status, RepresentativeClaim and ReadAt are the latest
// GOOD reading (kept through later failed attempts); ReadAt zero for never.
Windows map[string]Window
// Source is where the reading came from: SourceUsageAPI or
// SourceRateLimitHeaders ("" for none yet).
Source string
// Status and RepresentativeClaim are the probe's overall
// `anthropic-ratelimit-unified-status` / `-representative-claim` ("" from
// the usage endpoint).
Status string
RepresentativeClaim string
ReadAt time.Time
// CheckedAt is the latest attempt, good or not.
CheckedAt time.Time
// ErrorKind and Error say why the latest attempt produced no reading
// (Kind*); both "" after a good one.
ErrorKind string
Error string
// TokenFP is the ccpool.Fingerprint of the token the latest attempt used:
// a refusal, a backoff and UsageAPI hold only while the token is unchanged.
TokenFP string
// UsageAPI is the usage endpoint's state for this token (UsageAPI*), and
// UsageAPINextAt when it may be called again after a 429 from it.
UsageAPI string
UsageAPINextAt time.Time
// RateLimitStreak is the probe's consecutive 429s; NextAt the earliest next
// attempt of any kind (zero: the next pass).
RateLimitStreak int
NextAt time.Time
}
Row is the latest reading of one of an owner's accounts, and what the latest attempt made of it. Numbers and short reasons only: no token, no body.
func Step ¶
func Step(ctx context.Context, prev Row, account, token string, now time.Time, cfg StepConfig, fetch Fetcher) (Row, bool)
Step is one account's turn of a pass, pure but for fetch: the row to save and whether there is one (false: nothing was attempted, prev stands).
- No token: KindNoToken, no call.
- A 401 or 403 from the PROBE on this token: no call until the token is replaced (a dead token costs one call, not one per interval).
- A wait still running (NextAt after now) on this token: no call.
- The usage endpoint first, when this token has never been tried on it (one discovery call) or a call with it succeeded. A 2xx is the reading (SourceUsageAPI). A 401/403 retires the endpoint for this token and a 429 rests it until Retry-After; both fall through to the probe.
- The probe, unless the pool marks the account cooling (KindCooling, no call until the cooldown ends). Its rate-limit headers are the reading (SourceRateLimitHeaders); an overall status `rejected` waits until its reset. A 429 backs off (Backoff, at least Retry-After).
A failed attempt keeps the last good reading; a 429 whose headers carry a reading stores it, since those numbers are current.
type StepConfig ¶
type StepConfig struct {
Interval time.Duration
CoolingUntil time.Time
// CoolingUnknown: the pool's cooldown could not be read, and CoolingUntil
// is a stand-in one interval ahead (only the message differs).
CoolingUnknown bool
}
StepConfig is what Step needs beside the row: the poll interval, and when the account pool's cooldown for the account ends (zero: not cooling).
type Store ¶
type Store interface {
Latest(ctx context.Context, owner int64) (map[string]Row, error)
Save(ctx context.Context, owner int64, r Row) error
}
Store keeps the latest Row per (owner, account).
type Usage ¶
type Usage struct {
Officers []OfficerUse `json:"officers"`
Jobs []JobUse `json:"jobs"`
// PoolWorkers are the job workers (agents in a worker pool); their work
// is the Jobs above.
PoolWorkers []PoolUse `json:"pool_workers"`
// InteractiveAgents is every other claude-code agent: an agent someone
// dispatched or talks to (the chief included).
InteractiveAgents int `json:"interactive_agents"`
}
Usage is what ran on one account over one window.
type UsedBy ¶
UsedBy is an account's Usage over the last day and the last week.
func EmptyUsedBy ¶
func EmptyUsedBy() UsedBy
EmptyUsedBy is UsedBy for an account nothing ran on (every list empty, not null, so a client reads the same shape either way).
type Window ¶
type Window struct {
Utilization *float64 `json:"utilization"`
ResetsAt *time.Time `json:"resets_at"`
// Status is the window's own status from the probe's headers ("allowed",
// "allowed_warning", "rejected"); "" from the usage endpoint.
Status string `json:"status,omitempty"`
}
Window is one rate-limit window: how much of it is used, in percent (0-100, and past 100 when usage runs past the cap), and when it resets. Either may be absent (nil) when the endpoint sent null.