package anthropic import ( "encoding/json" "fmt" "math" "time" ) // Window is a normalised rate-limit window: the shape everything else in // dipstick reasons about, independent of how the endpoint packages it. type Window struct { Kind string // "session" | "weekly_all" | "weekly_scoped" | ... Group string // "session" | "weekly" Percent int // 0-100 Severity string // "normal", and whatever else the server sends ResetsAt *time.Time // nil when the server does not say IsActive bool Model string // model name for scoped windows, empty otherwise } // Usage is the /api/oauth/usage response reduced to what we need. type Usage struct { Windows []Window // ExtraUsageEnabled: with credits on, 100% is no longer a wall. Showing it // as one would be a lie, so the flag travels up. ExtraUsageEnabled bool } // The raw shape, as it really is. Fields not listed here (tangelo, // iguana_necktie, nimbus_quill, seven_day_cowork, ...) are unannounced // features and are ignored on purpose: the endpoint is undocumented and adds // them without notice, so anything unrecognised must not break anything. type rawUsage struct { Limits []struct { Kind string `json:"kind"` Group string `json:"group"` Percent float64 `json:"percent"` Severity string `json:"severity"` ResetsAt *string `json:"resets_at"` IsActive bool `json:"is_active"` Scope *struct { Model *struct { DisplayName string `json:"display_name"` } `json:"model"` } `json:"scope"` } `json:"limits"` // Top-level fields: still present, still consistent with limits[], but // they carry no per-model breakdown (seven_day_opus and seven_day_sonnet // come back null). They only matter if limits[] disappears. FiveHour *rawLegacyWindow `json:"five_hour"` SevenDay *rawLegacyWindow `json:"seven_day"` ExtraUsage *struct { IsEnabled bool `json:"is_enabled"` } `json:"extra_usage"` } type rawLegacyWindow struct { // A float here (30.0), while limits[].percent is an integer. Not an // oversight: they are two representations of the same thing. Utilization float64 `json:"utilization"` ResetsAt *string `json:"resets_at"` } func parseTime(s *string) *time.Time { if s == nil || *s == "" { return nil } t, err := time.Parse(time.RFC3339, *s) if err != nil { return nil } return &t } func clampPercent(f float64) int { p := int(math.Round(f)) if p < 0 { return 0 } if p > 100 { return 100 } return p } // ParseUsage normalises the raw response. // // The source is limits[]: it is the only one carrying severity, is_active and // the model name of scoped windows. The top-level fields are the fallback for // when limits[] is missing or arrives empty. func ParseUsage(body []byte) (*Usage, error) { var raw rawUsage if err := json.Unmarshal(body, &raw); err != nil { return nil, fmt.Errorf("unreadable usage response: %w", err) } u := &Usage{} if raw.ExtraUsage != nil { u.ExtraUsageEnabled = raw.ExtraUsage.IsEnabled } for _, l := range raw.Limits { w := Window{ Kind: l.Kind, Group: l.Group, Percent: clampPercent(l.Percent), Severity: l.Severity, ResetsAt: parseTime(l.ResetsAt), IsActive: l.IsActive, } if l.Scope != nil && l.Scope.Model != nil { w.Model = l.Scope.Model.DisplayName } u.Windows = append(u.Windows, w) } if len(u.Windows) > 0 { return u, nil } // Fallback: limits[] absent. Rebuild the bare minimum. Severity stays // empty because we do not know it, and inventing one would be worse than // omitting it. if raw.FiveHour != nil { u.Windows = append(u.Windows, Window{ Kind: KindSession, Group: GroupSession, Percent: clampPercent(raw.FiveHour.Utilization), ResetsAt: parseTime(raw.FiveHour.ResetsAt), }) } if raw.SevenDay != nil { u.Windows = append(u.Windows, Window{ Kind: KindWeeklyAll, Group: GroupWeekly, Percent: clampPercent(raw.SevenDay.Utilization), ResetsAt: parseTime(raw.SevenDay.ResetsAt), }) } if len(u.Windows) == 0 { return nil, fmt.Errorf("no quota window in the response") } return u, nil } // Known names. Any other kind is still carried through: this is not a closed // set, only the subset dipstick can say something extra about. const ( KindSession = "session" KindWeeklyAll = "weekly_all" KindWeeklyScoped = "weekly_scoped" GroupSession = "session" GroupWeekly = "weekly" ) // Find returns the first window with the given kind. func (u *Usage) Find(kind string) *Window { for i := range u.Windows { if u.Windows[i].Kind == kind { return &u.Windows[i] } } return nil } // FetchUsage reads and normalises in one go. func FetchUsage() (*Usage, error) { body, err := RawUsage() if err != nil { return nil, err } return ParseUsage(body) }