core

package
v0.6.6 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

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

Variables

Functions

func AppendModelUsageRecord added in v0.4.0

func AppendModelUsageRecord(snap *UsageSnapshot, rec ModelUsageRecord)

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 Float64Ptr added in v0.4.0

func Float64Ptr(v float64) *float64

func IsKnownDashboardStandardSection added in v0.6.5

func IsKnownDashboardStandardSection(section DashboardStandardSection) bool

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

func IsModelCostMetricKey added in v0.4.0

func IsModelCostMetricKey(key string) bool

func IsPerModelTokenMetricKey added in v0.4.0

func IsPerModelTokenMetricKey(key string) bool

func MetricUsedPercent added in v0.4.0

func MetricUsedPercent(key string, m Metric) float64

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     string            `json:"binary,omitempty"`      // path to CLI binary
	BaseURL    string            `json:"base_url,omitempty"`    // custom API base URL (e.g. for OpenRouter)
	Token      string            `json:"-"`                     // runtime-only: access token (never persisted)
	ExtraData  map[string]string `json:"-"`                     // runtime-only: extra detection data
}

func MergeAccounts added in v0.5.0

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

func (AccountConfig) ResolveAPIKey

func (c AccountConfig) ResolveAPIKey() string

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"
	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) 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 DetailWidget added in v0.3.0

type DetailWidget struct {
	Sections []DetailSection
}

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

type MetricGroup added in v0.4.0

type MetricGroup string
const (
	MetricGroupUsage    MetricGroup = "Usage"
	MetricGroupSpending MetricGroup = "Spending"
	MetricGroupTokens   MetricGroup = "Tokens"
	MetricGroupActivity MetricGroup = "Activity"
	MetricGroupMCP      MetricGroup = "MCP Usage"
)

func InferMetricGroup added in v0.4.0

func InferMetricGroup(key string, m Metric) MetricGroup

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 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 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 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 TimePoint

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

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

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