core

package
v0.9.6 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ModelNormalizationGroupLineage = "lineage"
	ModelNormalizationGroupRelease = "release"
)

Variables

Functions

func DeepCloneSnapshots added in v0.6.1

func DeepCloneSnapshots(m map[string]UsageSnapshot) map[string]UsageSnapshot

DeepCloneSnapshots returns a deep copy of a snapshot map where each snapshot is independently deep-cloned.

func DetailSectionLabel added in v0.8.0

func DetailSectionLabel(s DetailStandardSection) string

DetailSectionLabel returns a human-friendly label for a detail section ID.

func FallbackDisplayMetricKeys added in v0.6.12

func FallbackDisplayMetricKeys(metrics map[string]Metric) []string

func FirstNonEmpty added in v0.6.7

func FirstNonEmpty(values ...string) string

FirstNonEmpty returns the first non-blank string from values (trimmed).

func Float64Ptr added in v0.4.0

func Float64Ptr(v float64) *float64

func HasLanguageUsage added in v0.6.12

func HasLanguageUsage(s UsageSnapshot) bool

func HasMCPUsage added in v0.6.12

func HasMCPUsage(s UsageSnapshot) bool

func IncludeDetailMetricKey added in v0.6.12

func IncludeDetailMetricKey(key string) bool

func Int64Ptr added in v0.6.9

func Int64Ptr(v int64) *int64

Int64Ptr returns a pointer to the given int64 value.

func IsKnownDashboardStandardSection added in v0.6.5

func IsKnownDashboardStandardSection(section DashboardStandardSection) bool

IsKnownDashboardStandardSection reports whether section is a supported dashboard standard section identifier.

func IsKnownDetailStandardSection added in v0.8.0

func IsKnownDetailStandardSection(section DetailStandardSection) bool

IsKnownDetailStandardSection reports whether section is a supported detail standard section identifier.

func IsMCPToolMetricName added in v0.6.12

func IsMCPToolMetricName(name string) bool

func LocalMidnight added in v0.8.0

func LocalMidnight() time.Time

LocalMidnight returns midnight (00:00:00) of the current local day.

func MetricLabel added in v0.6.12

func MetricLabel(widget DashboardWidget, key string) string

func MetricUsedPercent added in v0.4.0

func MetricUsedPercent(key string, m Metric) float64

func NormalizeMetricLabel added in v0.6.12

func NormalizeMetricLabel(label string) string

func PrettifyMetricKey added in v0.6.12

func PrettifyMetricKey(key string) string

func SortedCompactStrings added in v0.6.12

func SortedCompactStrings(values []string) []string

func SortedStringKeys added in v0.6.12

func SortedStringKeys[V any](values map[string]V) []string

func Tracef added in v0.6.1

func Tracef(format string, args ...any)

Tracef logs a formatted message to stderr when OPENUSAGE_DEBUG is set. The env check result is cached after the first call.

Types

type AccountConfig

type AccountConfig struct {
	ID         string `json:"id"`
	Provider   string `json:"provider"`
	Auth       string `json:"auth,omitempty"`        // "api_key", "oauth", "cli", "local", "token"
	APIKeyEnv  string `json:"api_key_env,omitempty"` // env var name holding the API key
	ProbeModel string `json:"probe_model,omitempty"` // model to use for probe requests

	// Binary stores a CLI binary path for providers that execute a local command.
	// Provider-specific local data paths belong in ProviderPaths. Legacy Binary-based
	// data-path compatibility is handled inside the affected provider packages.
	Binary string `json:"binary,omitempty"`

	// BaseURL stores an HTTP API base URL for providers with configurable
	// endpoints. Provider-specific local data paths belong in ProviderPaths. Legacy
	// BaseURL-based data-path compatibility is handled inside provider packages.
	BaseURL string `json:"base_url,omitempty"`

	// ProviderPaths holds named provider-specific paths/URLs that are not part
	// of the shared account contract. Keys are provider-defined (for example
	// "tracking_db", "state_db", "stats_cache", "account_config").
	ProviderPaths map[string]string `json:"provider_paths,omitempty"`

	// Paths is a legacy persisted alias for provider-specific paths. New code
	// should use ProviderPaths through Path/SetPath helpers.
	Paths map[string]string `json:"paths,omitempty"`

	Token        string            `json:"-"` // runtime-only: access token (never persisted)
	RuntimeHints map[string]string `json:"-"` // runtime-only: non-persisted local/runtime hints
	ExtraData    map[string]string `json:"-"` // runtime-only: extra detection metadata (never persisted)
}

func MergeAccounts added in v0.5.0

func MergeAccounts(manual, autoDetected []AccountConfig) []AccountConfig

func (AccountConfig) Hint added in v0.6.12

func (c AccountConfig) Hint(key, fallback string) string

func (AccountConfig) Path added in v0.6.9

func (c AccountConfig) Path(key, fallback string) string

Path returns the named provider-specific path. It checks ProviderPaths first, then legacy Paths, then runtime hints, then legacy ExtraData fallbacks, then the fallback.

func (AccountConfig) PathMap added in v0.6.12

func (c AccountConfig) PathMap() map[string]string

PathMap returns a merged copy of provider-local paths, preferring ProviderPaths over legacy Paths.

func (AccountConfig) ResolveAPIKey

func (c AccountConfig) ResolveAPIKey() string

func (*AccountConfig) SetHint added in v0.6.12

func (c *AccountConfig) SetHint(key, value string)

func (*AccountConfig) SetPath added in v0.6.9

func (c *AccountConfig) SetPath(key, value string)

SetPath stores a named provider-specific path.

type ActualToolUsageEntry added in v0.6.12

type ActualToolUsageEntry struct {
	RawName string
	Calls   float64
}

func ExtractActualToolUsage added in v0.6.12

func ExtractActualToolUsage(s UsageSnapshot) ([]ActualToolUsageEntry, map[string]bool)

type AnalyticsCostSummary added in v0.6.12

type AnalyticsCostSummary struct {
	TotalCostUSD float64
	TodayCostUSD float64
	WeekCostUSD  float64
	BurnRateUSD  float64
}

func ExtractAnalyticsCostSummary added in v0.6.12

func ExtractAnalyticsCostSummary(s UsageSnapshot) AnalyticsCostSummary

type AnalyticsModelUsageEntry added in v0.6.12

type AnalyticsModelUsageEntry struct {
	Name         string
	CostUSD      float64
	InputTokens  float64
	OutputTokens float64
	Confidence   float64
	Window       string
}

func ExtractAnalyticsModelUsage added in v0.6.12

func ExtractAnalyticsModelUsage(s UsageSnapshot) []AnalyticsModelUsageEntry

type ChangeDetector added in v0.8.0

type ChangeDetector interface {
	HasChanged(acct AccountConfig, since time.Time) (bool, error)
}

ChangeDetector is an optional interface that UsageProvider implementations may implement to skip expensive Fetch() calls when data hasn't changed. Implementations should be cheap (stat() calls, not file reads). On error, callers assume changed=true (safe fallback).

type ClientBreakdownEntry added in v0.6.12

type ClientBreakdownEntry struct {
	Name       string
	Total      float64
	Input      float64
	Output     float64
	Cached     float64
	Reasoning  float64
	Requests   float64
	Sessions   float64
	SeriesKind string
	Series     []TimePoint
}

func ExtractClientBreakdown added in v0.6.12

func ExtractClientBreakdown(s UsageSnapshot) ([]ClientBreakdownEntry, map[string]bool)

func ExtractInterfaceClientBreakdown added in v0.6.12

func ExtractInterfaceClientBreakdown(s UsageSnapshot) ([]ClientBreakdownEntry, map[string]bool)

type Clock added in v0.6.12

type Clock interface {
	Now() time.Time
}

type CodeStatsConfig added in v0.5.5

type CodeStatsConfig struct {
	LinesAdded   string // metric key for lines added
	LinesRemoved string // metric key for lines removed
	FilesChanged string // metric key for files changed
	Commits      string // metric key for scored commits
	AIPercent    string // metric key for AI code %
	Prompts      string // metric key for total prompts
}

CodeStatsConfig maps metric keys to code statistics roles for graphical display.

type DashboardColorRole added in v0.2.0

type DashboardColorRole string
const (
	DashboardColorRoleAuto      DashboardColorRole = "auto"
	DashboardColorRoleGreen     DashboardColorRole = "green"
	DashboardColorRolePeach     DashboardColorRole = "peach"
	DashboardColorRoleLavender  DashboardColorRole = "lavender"
	DashboardColorRoleBlue      DashboardColorRole = "blue"
	DashboardColorRoleTeal      DashboardColorRole = "teal"
	DashboardColorRoleYellow    DashboardColorRole = "yellow"
	DashboardColorRoleSky       DashboardColorRole = "sky"
	DashboardColorRoleSapphire  DashboardColorRole = "sapphire"
	DashboardColorRoleMaroon    DashboardColorRole = "maroon"
	DashboardColorRoleFlamingo  DashboardColorRole = "flamingo"
	DashboardColorRoleRosewater DashboardColorRole = "rosewater"
)

type DashboardCompactRow added in v0.2.0

type DashboardCompactRow struct {
	Label       string
	Keys        []string
	Matcher     DashboardMetricMatcher
	MaxSegments int
}

type DashboardDisplayStyle added in v0.2.0

type DashboardDisplayStyle string
const (
	DashboardDisplayStyleDefault DashboardDisplayStyle = "default"
	// Detailed credits mode shows richer "remaining/today/week/models" messaging
	// when credit-like metrics are present.
	DashboardDisplayStyleDetailedCredits DashboardDisplayStyle = "detailed_credits"
)

type DashboardMetricGroupOverride added in v0.2.0

type DashboardMetricGroupOverride struct {
	Group string
	Label string
	Order int
}

type DashboardMetricMatcher added in v0.2.0

type DashboardMetricMatcher struct {
	Prefix string
	Suffix string
}

type DashboardRawGroup added in v0.2.0

type DashboardRawGroup struct {
	Label string
	Keys  []string
}

type DashboardResetStyle added in v0.2.0

type DashboardResetStyle string
const (
	DashboardResetStyleDefault DashboardResetStyle = "default"
	// Compact model resets mode groups many reset rows into model-oriented pills.
	DashboardResetStyleCompactModelResets DashboardResetStyle = "compact_model_resets"
)

type DashboardStandardSection added in v0.4.0

type DashboardStandardSection string

DashboardStandardSection identifies a normalized tile section.

const (
	DashboardSectionHeader           DashboardStandardSection = "header"
	DashboardSectionTopUsageProgress DashboardStandardSection = "top_usage_progress"
	DashboardSectionModelBurn        DashboardStandardSection = "model_burn"
	DashboardSectionClientBurn       DashboardStandardSection = "client_burn"
	DashboardSectionProjectBreakdown DashboardStandardSection = "project_breakdown"
	DashboardSectionToolUsage        DashboardStandardSection = "tool_usage"
	// DashboardSectionActualToolUsage is a legacy section ID kept for backward compatibility.
	// It is normalized to DashboardSectionToolUsage at runtime and config load.
	DashboardSectionActualToolUsage   DashboardStandardSection = "actual_tool_usage"
	DashboardSectionMCPUsage          DashboardStandardSection = "mcp_usage"
	DashboardSectionLanguageBurn      DashboardStandardSection = "language_burn"
	DashboardSectionCodeStats         DashboardStandardSection = "code_stats"
	DashboardSectionDailyUsage        DashboardStandardSection = "daily_usage"
	DashboardSectionProviderBurn      DashboardStandardSection = "provider_burn"
	DashboardSectionUpstreamProviders DashboardStandardSection = "upstream_providers"
	DashboardSectionOtherData         DashboardStandardSection = "other_data"
)

func DashboardStandardSections added in v0.6.5

func DashboardStandardSections() []DashboardStandardSection

DashboardStandardSections returns the canonical dashboard section list in the default render order.

func NormalizeDashboardStandardSection added in v0.6.6

func NormalizeDashboardStandardSection(section DashboardStandardSection) DashboardStandardSection

NormalizeDashboardStandardSection maps legacy aliases to canonical section IDs.

type DashboardWidget added in v0.2.0

type DashboardWidget struct {
	DisplayStyle DashboardDisplayStyle
	ResetStyle   DashboardResetStyle
	ColorRole    DashboardColorRole
	// Opt-in client composition panel (client share + trend) in tile view.
	ShowClientComposition bool
	// Override the default heading for the client composition section.
	ClientCompositionHeading string
	// When true, fold interface_ metrics into the client composition as separate entries.
	ClientCompositionIncludeInterfaces bool
	// Opt-in tool composition panel (tool share) in tile view.
	ShowToolComposition bool
	// Override the default "Tool Usage (calls)" heading for the tool composition section.
	ToolCompositionHeading string
	// Opt-in language composition panel (by-language request share) in tile view.
	ShowLanguageComposition bool
	// Opt-in graphical code statistics panel (lines added/removed, commits, AI %).
	ShowCodeStatsComposition bool
	// Metric keys for the code stats section (added, removed, files, commits, ai%).
	CodeStatsMetrics CodeStatsConfig
	// Opt-in actual tool usage panel (tool calls from agent bubbles).
	ShowActualToolUsage bool
	// Opt-in MCP server usage panel (MCP tool calls per server).
	ShowMCPUsage bool

	// API key provider metadata. APIKeyEnv marks a provider as configurable in API Keys tab.
	APIKeyEnv        string
	DefaultAccountID string

	// When ResetStyle is DashboardResetStyleCompactModelResets and the number of active
	// reset entries meets/exceeds this value, reset pills are grouped.
	ResetCompactThreshold int

	GaugePriority               []string
	StackedGaugeKeys            map[string]StackedGaugeConfig
	GaugeMaxLines               int
	CompactRows                 []DashboardCompactRow
	RawGroups                   []DashboardRawGroup
	MetricLabelOverrides        map[string]string
	MetricGroupOverrides        map[string]DashboardMetricGroupOverride
	CompactMetricLabelOverrides map[string]string

	HideMetricKeys     []string
	HideMetricPrefixes []string
	// Hide key-level "credits" row when richer account-level balance metric is present.
	HideCreditsWhenBalancePresent bool

	// Hide noisy metrics that are often zero-value for this provider.
	SuppressZeroMetricKeys []string
	// Hide all zero-valued non-quota metrics.
	SuppressZeroNonUsageMetrics bool

	// StandardSectionOrder controls normalized tile section ordering and visibility.
	// Unknown values are ignored; omitted sections are hidden.
	StandardSectionOrder []DashboardStandardSection

	DataSpec WidgetDataSpec
}

func DefaultDashboardWidget added in v0.2.0

func DefaultDashboardWidget() DashboardWidget

func (DashboardWidget) EffectiveStandardSectionOrder added in v0.4.0

func (w DashboardWidget) EffectiveStandardSectionOrder() []DashboardStandardSection

func (DashboardWidget) IsZero added in v0.6.7

func (w DashboardWidget) IsZero() bool

IsZero returns true when no fields have been set on the widget.

func (DashboardWidget) MissingMetrics added in v0.4.0

func (w DashboardWidget) MissingMetrics(snap UsageSnapshot) []string

type DetailSection added in v0.3.0

type DetailSection struct {
	Name  string
	Order int
	Style DetailSectionStyle
}

type DetailSectionStyle added in v0.3.0

type DetailSectionStyle string
const (
	DetailSectionStyleUsage     DetailSectionStyle = "usage"
	DetailSectionStyleSpending  DetailSectionStyle = "spending"
	DetailSectionStyleTokens    DetailSectionStyle = "tokens"
	DetailSectionStyleActivity  DetailSectionStyle = "activity"
	DetailSectionStyleList      DetailSectionStyle = "list"
	DetailSectionStyleModels    DetailSectionStyle = "models"
	DetailSectionStyleTrends    DetailSectionStyle = "trends"
	DetailSectionStyleLanguages DetailSectionStyle = "languages"
	DetailSectionStyleMCP       DetailSectionStyle = "mcp"
)

type DetailStandardSection added in v0.8.0

type DetailStandardSection string

DetailStandardSection identifies a normalized detail view section.

const (
	DetailSectionUsage           DetailStandardSection = "usage"
	DetailSectionSpending        DetailStandardSection = "spending"
	DetailSectionModels          DetailStandardSection = "models"
	DetailSectionClients         DetailStandardSection = "clients"
	DetailSectionProjects        DetailStandardSection = "projects"
	DetailSectionTools           DetailStandardSection = "tools"
	DetailSectionMCP             DetailStandardSection = "mcp"
	DetailSectionLanguages       DetailStandardSection = "languages"
	DetailSectionCodeStats       DetailStandardSection = "code_stats"
	DetailSectionTrends          DetailStandardSection = "trends"
	DetailSectionActivityHeatmap DetailStandardSection = "activity_heatmap"
	DetailSectionCostRequests    DetailStandardSection = "cost_requests"
	DetailSectionForecast        DetailStandardSection = "forecast"
	DetailSectionUpstream        DetailStandardSection = "upstream"
	DetailSectionProviderBurn    DetailStandardSection = "provider_burn"
	DetailSectionOtherData       DetailStandardSection = "other_data"
	DetailSectionTimers          DetailStandardSection = "timers"
	DetailSectionInfo            DetailStandardSection = "info"
)

func DefaultDetailSectionOrder added in v0.8.0

func DefaultDetailSectionOrder() []DetailStandardSection

DefaultDetailSectionOrder returns the canonical detail section list in the default render order.

type DetailWidget added in v0.3.0

type DetailWidget struct {
	Sections []DetailSection
}

func CodingToolDetailWidget added in v0.6.12

func CodingToolDetailWidget(includeMCP bool) DetailWidget

func DefaultDetailWidget added in v0.3.0

func DefaultDetailWidget() DetailWidget

func (DetailWidget) SectionOrder added in v0.3.0

func (w DetailWidget) SectionOrder(name string) int

func (DetailWidget) SectionStyle added in v0.3.0

func (w DetailWidget) SectionStyle(name string) DetailSectionStyle

type LanguageUsageEntry added in v0.6.12

type LanguageUsageEntry struct {
	Name     string
	Requests float64
}

func ExtractLanguageUsage added in v0.6.12

func ExtractLanguageUsage(s UsageSnapshot) ([]LanguageUsageEntry, map[string]bool)

type LogThrottle added in v0.6.12

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

func NewLogThrottle added in v0.6.12

func NewLogThrottle(maxKeys int, maxAge time.Duration) *LogThrottle

func (*LogThrottle) Allow added in v0.6.12

func (t *LogThrottle) Allow(key string, interval time.Duration, now time.Time) bool

type MCPFunctionUsageEntry added in v0.6.12

type MCPFunctionUsageEntry struct {
	RawName string
	Calls   float64
}

type MCPServerUsageEntry added in v0.6.12

type MCPServerUsageEntry struct {
	RawName   string
	Calls     float64
	Functions []MCPFunctionUsageEntry
	Series    []TimePoint
}

func ExtractMCPBreakdown added in v0.9.0

func ExtractMCPBreakdown(s UsageSnapshot) ([]MCPServerUsageEntry, map[string]bool)

func ExtractMCPUsage added in v0.6.12

func ExtractMCPUsage(s UsageSnapshot) ([]MCPServerUsageEntry, map[string]bool)

type Metric

type Metric struct {
	Limit     *float64 `json:"limit,omitempty"`
	Remaining *float64 `json:"remaining,omitempty"`
	Used      *float64 `json:"used,omitempty"`
	Unit      string   `json:"unit"`   // "requests", "tokens", "USD", "credits"
	Window    string   `json:"window"` // "1m", "1d", "month", "rolling-5h", etc.
}

func (Metric) Percent

func (m Metric) Percent() float64

Percent returns the remaining percentage (0–100) or -1 if unknown. For used percentage, use MetricUsedPercent which is context-aware.

type ModelBreakdownEntry added in v0.6.12

type ModelBreakdownEntry struct {
	Name       string
	Cost       float64
	Input      float64
	Output     float64
	CacheRead  float64
	CacheWrite float64
	Reasoning  float64
	Requests   float64
	Requests1d float64
	Series     []TimePoint
}

func ExtractModelBreakdown added in v0.6.12

func ExtractModelBreakdown(s UsageSnapshot) ([]ModelBreakdownEntry, map[string]bool)

func (ModelBreakdownEntry) TotalTokens added in v0.9.2

func (e ModelBreakdownEntry) TotalTokens() float64

TotalTokens returns the billable token volume: input + output + cache writes + reasoning. Cache reads are deliberately excluded because they're discounted 90% by Anthropic and represent repeated reads of the same cached bytes across turns — counting them linearly inflates "usage" by orders of magnitude.

type ModelNormalizationConfig added in v0.4.0

type ModelNormalizationConfig struct {
	Enabled       bool                         `json:"enabled"`
	GroupBy       string                       `json:"group_by,omitempty"`       // lineage | release
	MinConfidence float64                      `json:"min_confidence,omitempty"` // 0..1
	Overrides     []ModelNormalizationOverride `json:"overrides,omitempty"`
}

func DefaultModelNormalizationConfig added in v0.4.0

func DefaultModelNormalizationConfig() ModelNormalizationConfig

func NormalizeModelNormalizationConfig added in v0.4.0

func NormalizeModelNormalizationConfig(cfg ModelNormalizationConfig) ModelNormalizationConfig

type ModelNormalizationOverride added in v0.4.0

type ModelNormalizationOverride struct {
	Provider         string `json:"provider,omitempty"`
	RawModelID       string `json:"raw_model_id"`
	CanonicalLineage string `json:"canonical_lineage_id"`
	CanonicalRelease string `json:"canonical_release_id,omitempty"`
	CanonicalModel   string `json:"canonical_model,omitempty"`
}

type ModelUsageRecord added in v0.4.0

type ModelUsageRecord struct {
	RawModelID string `json:"raw_model_id"`
	RawSource  string `json:"raw_source,omitempty"` // api | jsonl | sqlite | metrics_fallback

	CanonicalLineageID string `json:"canonical_lineage_id,omitempty"`
	CanonicalReleaseID string `json:"canonical_release_id,omitempty"`
	CanonicalVendor    string `json:"canonical_vendor,omitempty"`
	CanonicalFamily    string `json:"canonical_family,omitempty"`
	CanonicalVariant   string `json:"canonical_variant,omitempty"`
	Canonical          string `json:"canonical,omitempty"` // Canonical model name for consistent identification

	Confidence float64 `json:"confidence,omitempty"` // 0..1
	Reason     string  `json:"reason,omitempty"`

	Window     string            `json:"window,omitempty"`
	Dimensions map[string]string `json:"dimensions,omitempty"` // provider/account/client/endpoint

	InputTokens     *float64 `json:"input_tokens,omitempty"`
	OutputTokens    *float64 `json:"output_tokens,omitempty"`
	CachedTokens    *float64 `json:"cached_tokens,omitempty"`
	ReasoningTokens *float64 `json:"reasoning_tokens,omitempty"`
	TotalTokens     *float64 `json:"total_tokens,omitempty"`
	CostUSD         *float64 `json:"cost_usd,omitempty"`
	Requests        *float64 `json:"requests,omitempty"`
}

func BuildModelUsageFromSnapshotMetrics added in v0.4.0

func BuildModelUsageFromSnapshotMetrics(s UsageSnapshot) []ModelUsageRecord

func (*ModelUsageRecord) EnsureDimensions added in v0.4.0

func (r *ModelUsageRecord) EnsureDimensions()

func (*ModelUsageRecord) SetDimension added in v0.4.0

func (r *ModelUsageRecord) SetDimension(key, value string)

type NamedSeries added in v0.6.12

type NamedSeries struct {
	Name   string
	Points []TimePoint
}

func ExtractAnalyticsModelSeries added in v0.6.12

func ExtractAnalyticsModelSeries(series map[string][]TimePoint) []NamedSeries

type ProjectUsageEntry added in v0.6.12

type ProjectUsageEntry struct {
	Name       string
	Requests   float64
	Requests1d float64
	Series     []TimePoint
}

func ExtractProjectUsage added in v0.6.12

func ExtractProjectUsage(s UsageSnapshot) ([]ProjectUsageEntry, map[string]bool)

type ProviderAuthSpec added in v0.4.0

type ProviderAuthSpec struct {
	Type             ProviderAuthType
	APIKeyEnv        string
	DefaultAccountID string
}

ProviderAuthSpec defines how a provider authenticates and how users configure it.

type ProviderAuthType added in v0.4.0

type ProviderAuthType string
const (
	ProviderAuthTypeUnknown ProviderAuthType = ""
	ProviderAuthTypeAPIKey  ProviderAuthType = "api_key"
	ProviderAuthTypeOAuth   ProviderAuthType = "oauth"
	ProviderAuthTypeCLI     ProviderAuthType = "cli"
	ProviderAuthTypeLocal   ProviderAuthType = "local"
	ProviderAuthTypeToken   ProviderAuthType = "token"
)

type ProviderBreakdownEntry added in v0.6.12

type ProviderBreakdownEntry struct {
	Name     string
	Cost     float64
	Input    float64
	Output   float64
	Requests float64
}

func ExtractProviderBreakdown added in v0.6.12

func ExtractProviderBreakdown(s UsageSnapshot) ([]ProviderBreakdownEntry, map[string]bool)

func ExtractUpstreamProviderBreakdown added in v0.6.12

func ExtractUpstreamProviderBreakdown(s UsageSnapshot) ([]ProviderBreakdownEntry, map[string]bool)

type ProviderInfo

type ProviderInfo struct {
	Name         string   // e.g. "OpenAI", "Anthropic"
	Capabilities []string // "headers", "cli_stats", "usage_endpoint", "credits_endpoint"
	DocURL       string   // link to vendor's rate-limit documentation
}

type ProviderSetupSpec added in v0.4.0

type ProviderSetupSpec struct {
	DocsURL    string
	Quickstart []string
}

ProviderSetupSpec describes setup entry points and quickstart instructions.

type ProviderSpec added in v0.4.0

type ProviderSpec struct {
	ID        string
	Info      ProviderInfo
	Auth      ProviderAuthSpec
	Setup     ProviderSetupSpec
	Dashboard DashboardWidget
	Detail    DetailWidget
}

ProviderSpec is the canonical provider definition used for registration and UI metadata.

type RateLimitDisplayMetric added in v0.6.12

type RateLimitDisplayMetric struct {
	Key                  string
	LabelKey             string
	UsedPercent          float64
	UsesRemainingPercent bool
	RemainingPercent     float64
}

func ExtractRateLimitDisplayMetrics added in v0.6.12

func ExtractRateLimitDisplayMetrics(metrics map[string]Metric) []RateLimitDisplayMetric

type StackedGaugeConfig added in v0.5.5

type StackedGaugeConfig struct {
	SegmentMetricKeys []string // Metric keys — segment value = metric.Used
	SegmentLabels     []string // Display labels for each segment
	SegmentColors     []string // Theme color names: "teal", "peach", "green", etc.
}

StackedGaugeConfig describes how a metric renders as a stacked gauge bar. Each segment references another metric key whose Used value provides the segment's absolute amount. Percentages are computed against the parent metric's Limit at render time.

type Status

type Status string
const (
	StatusOK          Status = "OK"
	StatusNearLimit   Status = "NEAR_LIMIT"
	StatusLimited     Status = "LIMITED"
	StatusAuth        Status = "AUTH_REQUIRED"
	StatusUnsupported Status = "UNSUPPORTED"
	StatusError       Status = "ERROR"
	StatusUnknown     Status = "UNKNOWN"
)

type SystemClock added in v0.6.12

type SystemClock struct{}

func (SystemClock) Now added in v0.6.12

func (SystemClock) Now() time.Time

type TimePoint

type TimePoint struct {
	Date  string  `json:"date"`  // "2025-01-15"
	Value float64 `json:"value"` // metric value at that date
}

func SelectAnalyticsWeightSeries added in v0.6.12

func SelectAnalyticsWeightSeries(series map[string][]TimePoint) []TimePoint

func SortedTimePoints added in v0.6.12

func SortedTimePoints(values map[string]float64) []TimePoint

type TimeWindow added in v0.5.2

type TimeWindow string

TimeWindow represents a configurable time window for filtering usage data.

const (
	TimeWindow1d  TimeWindow = "1d"
	TimeWindow3d  TimeWindow = "3d"
	TimeWindow7d  TimeWindow = "7d"
	TimeWindow30d TimeWindow = "30d"
	TimeWindowAll TimeWindow = "all"
)

func LargestWindowFitting added in v0.5.2

func LargestWindowFitting(maxDays int) TimeWindow

LargestWindowFitting returns the largest valid TimeWindow whose Days() <= maxDays. Falls back to the smallest window if none fit. Skips TimeWindowAll.

func NextTimeWindow added in v0.5.2

func NextTimeWindow(current TimeWindow) TimeWindow

NextTimeWindow returns the next time window in the cycle.

func ParseTimeWindow added in v0.5.2

func ParseTimeWindow(s string) TimeWindow

func (TimeWindow) Days added in v0.5.2

func (tw TimeWindow) Days() int

Days returns the window size in days.

func (TimeWindow) Hours added in v0.5.2

func (tw TimeWindow) Hours() int

Hours returns the window size in hours. Returns 0 for TimeWindowAll (no filter).

func (TimeWindow) Label added in v0.5.2

func (tw TimeWindow) Label() string

func (TimeWindow) SQLiteOffset added in v0.5.2

func (tw TimeWindow) SQLiteOffset() string

SQLiteOffset returns the SQLite datetime offset string for this window (e.g., "-7 day"). Returns empty string for TimeWindowAll (no filter).

func (TimeWindow) Since added in v0.8.0

func (tw TimeWindow) Since() time.Time

Since returns the cutoff time for this window. For "1d" (Today): local midnight (calendar day boundary). For "3d", "7d", "30d": rolling N*24 hours from now. For "all": zero time (no filter).

type TokenUsage added in v0.6.9

type TokenUsage struct {
	InputTokens      *int64   `json:"input_tokens,omitempty"`
	OutputTokens     *int64   `json:"output_tokens,omitempty"`
	ReasoningTokens  *int64   `json:"reasoning_tokens,omitempty"`
	CacheReadTokens  *int64   `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens *int64   `json:"cache_write_tokens,omitempty"`
	TotalTokens      *int64   `json:"total_tokens,omitempty"`
	CostUSD          *float64 `json:"cost_usd,omitempty"`
	Requests         *int64   `json:"requests,omitempty"`
}

TokenUsage holds the canonical token and cost counters shared across telemetry events, hook payloads, and ingest requests. Centralizing these fields eliminates the triple-duplication that previously existed between shared.TelemetryEvent, telemetry.IngestRequest, and telemetry.CanonicalEvent.

func (TokenUsage) HasTokenData added in v0.6.9

func (u TokenUsage) HasTokenData() bool

HasTokenData reports whether the usage contains any non-zero token or cost data.

func (*TokenUsage) SumTotalTokens added in v0.6.9

func (u *TokenUsage) SumTotalTokens()

SumTotalTokens computes TotalTokens from parts if it is nil.

type UsageProvider added in v0.4.0

type UsageProvider interface {
	ID() string

	Describe() ProviderInfo

	// Spec defines provider-level auth/setup metadata and presentation defaults.
	Spec() ProviderSpec

	// DashboardWidget defines how provider metrics should be presented in dashboard tiles.
	DashboardWidget() DashboardWidget
	// DetailWidget defines how sections should be rendered in the details panel.
	DetailWidget() DetailWidget

	Fetch(ctx context.Context, acct AccountConfig) (UsageSnapshot, error)
}

type UsageSnapshot added in v0.4.0

type UsageSnapshot struct {
	ProviderID  string                 `json:"provider_id"`
	AccountID   string                 `json:"account_id"`
	Timestamp   time.Time              `json:"timestamp"`
	Status      Status                 `json:"status"`
	Metrics     map[string]Metric      `json:"metrics"`                // keys like "rpm", "tpm", "rpd"
	Resets      map[string]time.Time   `json:"resets,omitempty"`       // e.g. "rpm_reset"
	Attributes  map[string]string      `json:"attributes,omitempty"`   // normalized provider/account metadata
	Diagnostics map[string]string      `json:"diagnostics,omitempty"`  // non-fatal errors, warnings, probe/debug notes
	Raw         map[string]string      `json:"raw,omitempty"`          // provider metadata/debug bag (not for primary quota analytics)
	ModelUsage  []ModelUsageRecord     `json:"model_usage,omitempty"`  // per-model usage rows with canonical IDs
	DailySeries map[string][]TimePoint `json:"daily_series,omitempty"` // time-indexed data (e.g. "messages", "cost", "tokens_<model>")
	Message     string                 `json:"message,omitempty"`      // human-readable summary
}

func NewAuthSnapshot added in v0.5.0

func NewAuthSnapshot(providerID, accountID, message string) UsageSnapshot

func NewUsageSnapshot added in v0.5.0

func NewUsageSnapshot(providerID, accountID string) UsageSnapshot

func NormalizeUsageSnapshotWithConfig added in v0.4.0

func NormalizeUsageSnapshotWithConfig(s UsageSnapshot, modelCfg ModelNormalizationConfig) UsageSnapshot

func (*UsageSnapshot) AppendModelUsage added in v0.4.0

func (s *UsageSnapshot) AppendModelUsage(rec ModelUsageRecord)

func (UsageSnapshot) DeepClone added in v0.6.1

func (s UsageSnapshot) DeepClone() UsageSnapshot

DeepClone returns a deep copy of the snapshot with all map and pointer fields fully independent from the original.

func (*UsageSnapshot) EnsureMaps added in v0.4.0

func (s *UsageSnapshot) EnsureMaps()

func (UsageSnapshot) MetaValue added in v0.4.0

func (s UsageSnapshot) MetaValue(key string) (string, bool)

func (*UsageSnapshot) SetAttribute added in v0.4.0

func (s *UsageSnapshot) SetAttribute(key, value string)

func (*UsageSnapshot) SetDiagnostic added in v0.4.0

func (s *UsageSnapshot) SetDiagnostic(key, value string)

func (UsageSnapshot) WorstPercent added in v0.4.0

func (s UsageSnapshot) WorstPercent() float64

type WidgetDataSpec added in v0.4.0

type WidgetDataSpec struct {
	RequiredMetricKeys []string
	OptionalMetricKeys []string
	MetricPrefixes     []string
}

WidgetDataSpec describes the expected metric payload for a dashboard widget. RequiredMetricKeys provide a strict contract; MetricPrefixes provide extensibility.

Jump to

Keyboard shortcuts

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