Documentation
¶
Overview ¶
Package usage counts the tokens the coding agents spent on this host (使用量) from their transcripts. A Scanner reads only what was added since its last scan and keeps what it counted in usage-index.json, so a restarted daemon does not read the transcripts again.
How a request is counted: one model request is one dedupe key (Claude: message.id:requestId). The same key seen again in the same file (a streamed response written as one line per content block, or a file rewritten in place) keeps the largest of each count; seen in another file (a resumed or forked conversation copies earlier lines into its new file) it stays counted for the file it was first seen in. The last line of a file counts once its newline is written.
Index ¶
- Constants
- func Counted() []string
- func KeychainService(configEnv string) string
- func MacKeychain(ctx context.Context, service string) ([]byte, error)
- type APIError
- type APISchedule
- type Account
- type Alert
- type Alerts
- type Limits
- func (l *Limits) ClearErrors(h string) (changed bool, err error)
- func (l *Limits) Record(h, configDir string, m Measurement) (changed bool, err error)
- func (l *Limits) RecordError(h, configDir string, e wire.UsageLimitError) (changed bool, err error)
- func (l *Limits) Report(now time.Time) []wire.UsageLimits
- type Measurement
- type PrivateAPI
- type RateLimits
- type Scanner
- type Stats
- type Window
Constants ¶
const ( AlertNearly = 80 AlertFull = 100 )
Alert thresholds: the share (percent) a window passes.
const ( // APIInterval: while the app is in front, at most once per 15 minutes. APIInterval = 15 * time.Minute // APIOpenedAfter: opening the usage screen calls it when the last call // is this old. APIOpenedAfter = 5 * time.Minute )
When the private API is called (PROTOCOL.md "Private API").
const ( ClaudeUsageURL = "https://api.anthropic.com/api/oauth/usage" CodexUsageURL = "https://chatgpt.com/backend-api/wham/usage" )
The endpoints.
const AlertFresh = time.Hour
AlertFresh is how old a measured value may be to be compared: a value measured before (a statusLine that stopped, a rollout written earlier) notifies nothing.
Variables ¶
This section is empty.
Functions ¶
func Counted ¶
func Counted() []string
Counted lists, in the order of harness.All, the harnesses whose usage is counted.
func KeychainService ¶
KeychainService is the macOS Keychain service Claude Code keeps its login in: "Claude Code-credentials", with "-" and the first 8 hex digits of the SHA-256 of configEnv (CLAUDE_CONFIG_DIR as set) when it is set.
Types ¶
type APIError ¶
type APIError struct {
Code string // wire.UsageErr*
Message string
// RetryAt is the end of a 429's Retry-After (zero: none given).
RetryAt time.Time
}
APIError is why a call measured nothing. Message never holds a token.
type APISchedule ¶
type APISchedule struct {
// contains filtered or unexported fields
}
APISchedule decides when one account's private API is called next. The zero value calls at once. Not safe for concurrent use.
func (*APISchedule) Done ¶
Done takes the result of a call made at now and returns the earliest time of the next call. After a failure the wait is 30 s × 2^n (n the failures in a row before it) up to 15 minutes; a 429 waits at least until its Retry-After; a refused, unscoped or missing token waits an hour.
func (*APISchedule) Due ¶
func (s *APISchedule) Due(now time.Time, foreground, opened bool) bool
Due reports whether to call at now: while the app is in front once the interval (or the wait after a failure) is over; when the usage screen was opened, once APIOpenedAfter has passed since the last success and no failure's wait lasts.
type Account ¶
Account is whose limits are measured: a harness and its configuration directory (a clean path, the key its windows are kept under). ConfigEnv is the harness's variable as set (CLAUDE_CONFIG_DIR; "" when unset), which names Claude Code's Keychain item.
type Alert ¶
type Alert struct {
Harness, ConfigDir, Window string
// ResetsAt is the window's reset time (unix ms) as first seen: the
// notifications of one window share it (their replace key).
ResetsAt int64
// Threshold is AlertNearly or AlertFull; 0 for the window having reset.
Threshold int
}
Alert is one notification to send about a limit window.
type Alerts ¶
type Alerts struct {
// contains filtered or unexported fields
}
Alerts remembers what was notified of each window. Safe for concurrent use.
func OpenAlerts ¶
OpenAlerts reads what was notified, kept at path; a missing, unreadable or other-version file gives nothing notified.
func (*Alerts) Check ¶
Check compares the limit windows (Limits.Report at now) with what was notified and returns what to notify now, oldest event first, recording it. A window whose share was measured more than AlertFresh before now is not compared; a window reporting a reset time later than the one seen (by more than sameWindow) is a new window. A window that reached AlertFull notifies its reset once, when its reset time passed or a new window came. The file is written whenever something changed; err is about writing it (what to notify is returned all the same).
type Limits ¶
type Limits struct {
// contains filtered or unexported fields
}
Limits holds the limit windows. Safe for concurrent use. The file is written after mu is released (Report never waits for the disk), from a snapshot taken under it; writeMu orders the writes, so an older snapshot never replaces a newer one.
func OpenLimits ¶
OpenLimits reads the limit windows kept at path; a missing, unreadable or other-version file gives none.
func (*Limits) ClearErrors ¶
ClearErrors drops the errors of every account of harness h, and the windows that had only an error: the private API was turned off for it.
func (*Limits) Record ¶
func (l *Limits) Record(h, configDir string, m Measurement) (changed bool, err error)
Record takes the windows one source measured for the account (h, configDir). A window replaces the one kept unless it is the same window (resets within sameWindow) measured earlier or with a lower share, or an older window: a session that reported last can hold an earlier value, and a restarted daemon records the newest rollout event again, however old. A window without a reset time (ResetsAt 0, or one kept with only an error) is always replaced. A window not among m.Windows keeps its value, as does the plan when m has none. A measurement of the private API clears the account's errors (it succeeded); any other keeps them. changed is whether a share, a reset time, the plan or an error changed; the file is written whenever a value was taken.
func (*Limits) RecordError ¶
RecordError keeps e as the last error of every window of the account (h, configDir), keeping their values; an account without windows gets five_hour and seven_day with only the error. changed is whether a window's error code or retry time changed; the file is written either way.
func (*Limits) Report ¶
func (l *Limits) Report(now time.Time) []wire.UsageLimits
Report is the limit windows as usage.get returns them at now: accounts in the registry's harness order, then by configuration directory; windows five_hour, seven_day, the weekly windows of one model, the others by id, then extra_usage. A window whose reset time has passed comes without its share, marked Reset.
type Measurement ¶
type Measurement struct {
Source string // wire.UsageSource*
Plan string // the account's plan, when the source tells it
Windows []Window
At time.Time // when it was measured
}
Measurement is what one source measured for an account.
type PrivateAPI ¶
type PrivateAPI struct {
Client *http.Client
// ClaudeURL and CodexURL replace the endpoints (tests).
ClaudeURL string
CodexURL string
// Keychain reads the password of a macOS Keychain generic password by
// its service (MacKeychain on macOS; nil: none, the credentials file
// only).
Keychain func(ctx context.Context, service string) ([]byte, error)
}
PrivateAPI calls the private APIs. The zero value calls the real ones with http.DefaultClient and reads no Keychain.
func (*PrivateAPI) Measure ¶
func (p *PrivateAPI) Measure(ctx context.Context, a Account, now time.Time) (Measurement, *APIError)
Measure calls the private API of a.Harness (claude or codex) at now and returns the windows it answered, with Source private_api.
type RateLimits ¶
type RateLimits struct {
At int64 `json:"at"` // unix ms of the event
Plan string `json:"plan,omitempty"` // the account's plan (codex plan_type: "plus")
Windows []Window `json:"windows"`
}
RateLimits are the limit windows a harness wrote in a transcript (codex: a token_count's rate_limits), with the time of the event.
type Scanner ¶
type Scanner struct {
// BeforeFile, when set, is called before each file a scan reads.
BeforeFile func(path string)
// contains filtered or unexported fields
}
Scanner counts usage. Scan is called by one goroutine at a time; Report may be called concurrently and never waits for file reads.
func Open ¶
func Open(path string, roots transcript.Roots) *Scanner
Open loads the index at path (missing, corrupt or of another version: empty) for the transcripts under roots.
func (*Scanner) RateLimits ¶
func (s *Scanner) RateLimits(h string) (rl RateLimits, ok bool)
RateLimits is the newest limit windows any transcript of harness h wrote (codex), by the time of the event; ok is false when none has any.
func (*Scanner) Report ¶
func (s *Scanner) Report(p wire.UsageGetParams) (wire.UsageGetResult, error)
Report sums the usage counted so far by the calendar days of p.TZ.
type Stats ¶
type Stats struct {
Files int // files read
Read int64 // bytes read
Changed bool // new usage was counted, or the first scan finished
}
Stats describes one scan.
type Window ¶
type Window struct {
ID string `json:"id"` // wire.UsageWindow*, or "<minutes>m"
UsedPercent float64 `json:"used_percent"` // share of the limit used, 0–100
ResetsAt int64 `json:"resets_at"` // unix ms
}
Window is one measurement of a limit window.
func ClaudeRateLimits ¶
func ClaudeRateLimits(raw json.RawMessage, at time.Time) []Window
ClaudeRateLimits reads the windows of Claude Code's statusLine rate_limits, received at at: five_hour and seven_day (readWindow). A window it cannot read is left out, as is anything else (spend_limit).