usage

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 31 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 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

View Source
const (
	AlertNearly = 80
	AlertFull   = 100
)

Alert thresholds: the share (percent) a window passes.

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

View Source
const (
	ClaudeUsageURL = "https://api.anthropic.com/api/oauth/usage"
	CodexUsageURL  = "https://chatgpt.com/backend-api/wham/usage"
)

The endpoints.

View Source
const AgyTimeout = 30 * time.Second

AgyTimeout bounds one run of `agy -p /usage`.

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

View Source
const OmpTimeout = 15 * time.Second

OmpTimeout bounds one run of `omp usage`.

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

func KeychainService(configEnv string) string

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.

func MacKeychain

func MacKeychain(ctx context.Context, service string) ([]byte, error)

MacKeychain reads a generic password with /usr/bin/security.

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.

func (*APIError) Error

func (e *APIError) Error() string

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

func (s *APISchedule) Done(now time.Time, e *APIError) time.Time

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

type Account struct {
	Harness   string
	Dir       string
	ConfigEnv string
}

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 AgyUsage added in v0.25.0

type AgyUsage struct {
	Bin string
	Run func(ctx context.Context, bin string, args ...string) ([]byte, error)
}

AgyUsage runs Antigravity CLI's /usage. Run defaults to exec with AgyTimeout from os.TempDir.

func (AgyUsage) Measure added in v0.25.0

func (a AgyUsage) Measure(ctx context.Context, now func() time.Time) (Measurement, *APIError)

Measure runs `agy -p /usage --output-format json` and maps its answer (ParseAgyUsage); At is when the answer came.

type Alert

type Alert struct {
	Harness, ConfigDir, Window string
	// Label is the window's quota group (wire.UsageLimitWindow.Label).
	Label 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

func OpenAlerts(path string) *Alerts

OpenAlerts reads what was notified, kept at path; a missing, unreadable or other-version file gives nothing notified.

func (*Alerts) Check

func (a *Alerts) Check(accounts []wire.UsageLimits, now time.Time) (out []Alert, err error)

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

func OpenLimits(path string) *Limits

OpenLimits reads the limit windows kept at path; a missing, unreadable or other-version file gives none.

func (*Limits) ClearErrors

func (l *Limits) ClearErrors(h string) (changed bool, err error)

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) Has added in v0.25.0

func (l *Limits) Has(h, configDir string) bool

Has reports whether the account (h, configDir) has windows.

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 a source that can fail (the private API, omp, Antigravity's /usage) 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

func (l *Limits) RecordError(h, configDir string, e wire.UsageLimitError) (changed bool, err error)

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 windows of one model or quota group (in the order they were first measured), 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 OmpMeasurement added in v0.19.1

type OmpMeasurement struct {
	Harness string
	Measurement
}

OmpMeasurement is what omp told for the account of one harness.

func ParseOmpHistory added in v0.19.1

func ParseOmpHistory(b []byte) ([]OmpMeasurement, error)

ParseOmpHistory maps `omp usage --history --json`: the newest snapshot of every limit. A snapshot has no window length, so only the windows named in its limit id ("anthropic:5h", "anthropic:7d:fable") count.

func ParseOmpLive added in v0.19.1

func ParseOmpLive(b []byte) ([]OmpMeasurement, error)

ParseOmpLive maps `omp usage --json`: per provider the newest report (omp reports each account it holds), each limit given as a percentage with a window becoming a Window (ompWindowID).

type OmpUsage added in v0.19.1

type OmpUsage struct {
	Bin string
	Run func(ctx context.Context, bin string, args ...string) ([]byte, error)
}

OmpUsage runs omp's usage command. Run defaults to exec with OmpTimeout.

func (OmpUsage) History added in v0.19.1

func (o OmpUsage) History(ctx context.Context) ([]OmpMeasurement, *APIError)

History runs `omp usage --history --json --days 1` and takes the newest snapshot of every limit.

func (OmpUsage) Live added in v0.19.1

func (o OmpUsage) Live(ctx context.Context) ([]OmpMeasurement, *APIError)

Live runs `omp usage --json`.

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

Report sums the usage counted so far by the calendar days of p.TZ.

func (*Scanner) Scan

func (s *Scanner) Scan(stop <-chan struct{}) (Stats, error)

Scan reads what the transcripts gained since the last scan. It returns early, keeping what it read so far, when stop is closed.

func (*Scanner) ScannedAt

func (s *Scanner) ScannedAt() (done bool, at int64)

ScannedAt reports whether a scan finished since Open and when the last one did (unix ms). It never waits for a scan.

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
	Label       string  `json:"label,omitempty"` // the quota group of a scoped window
}

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).

func ParseAgyUsage added in v0.25.0

func ParseAgyUsage(b []byte) ([]Window, error)

ParseAgyUsage maps the answer of `agy -p /usage --output-format json`: every bucket with a remaining_fraction becomes a window — 5h five_hour, weekly seven_day, the buckets of Antigravity's own models plain, any other scoped "<base>_<scope>" and labelled with its group's name — in the order five_hour, seven_day, then the scoped ones in agy's group order, a group's 5h window before its weekly one (agy lists weekly first). A disabled bucket (no remaining_fraction), one of another window or with an empty scope is left out. An answer whose status is not SUCCESS or that carries no groups is an error.

Jump to

Keyboard shortcuts

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