Documentation
¶
Index ¶
- Constants
- Variables
- func DeepCloneSnapshots(m map[string]UsageSnapshot) map[string]UsageSnapshot
- func FirstNonEmpty(values ...string) string
- func Float64Ptr(v float64) *float64
- func Int64Ptr(v int64) *int64
- func IsKnownDashboardStandardSection(section DashboardStandardSection) bool
- func IsModelCostMetricKey(key string) bool
- func IsPerModelTokenMetricKey(key string) bool
- func MetricUsedPercent(key string, m Metric) float64
- func Tracef(format string, args ...any)
- type AccountConfig
- type CodeStatsConfig
- type DashboardColorRole
- type DashboardCompactRow
- type DashboardDisplayStyle
- type DashboardMetricGroupOverride
- type DashboardMetricMatcher
- type DashboardRawGroup
- type DashboardResetStyle
- type DashboardStandardSection
- type DashboardWidget
- type DetailSection
- type DetailSectionStyle
- type DetailWidget
- type Metric
- type MetricGroup
- type ModelNormalizationConfig
- type ModelNormalizationOverride
- type ModelUsageRecord
- type ProviderAuthSpec
- type ProviderAuthType
- type ProviderInfo
- type ProviderSetupSpec
- type ProviderSpec
- type StackedGaugeConfig
- type Status
- type TimePoint
- type TimeWindow
- type TokenUsage
- type UsageProvider
- type UsageSnapshot
- func (s *UsageSnapshot) AppendModelUsage(rec ModelUsageRecord)
- func (s UsageSnapshot) DeepClone() UsageSnapshot
- func (s *UsageSnapshot) EnsureMaps()
- func (s UsageSnapshot) MetaValue(key string) (string, bool)
- func (s *UsageSnapshot) SetAttribute(key, value string)
- func (s *UsageSnapshot) SetDiagnostic(key, value string)
- func (s UsageSnapshot) WorstPercent() float64
- type WidgetDataSpec
Constants ¶
const ( ModelNormalizationGroupLineage = "lineage" ModelNormalizationGroupRelease = "release" )
Variables ¶
var ValidTimeWindows = []TimeWindow{ TimeWindow1d, TimeWindow3d, TimeWindow7d, TimeWindow30d, TimeWindowAll, }
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 FirstNonEmpty ¶ added in v0.6.7
FirstNonEmpty returns the first non-blank string from values (trimmed).
func Float64Ptr ¶ added in v0.4.0
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 IsPerModelTokenMetricKey ¶ added in v0.4.0
func MetricUsedPercent ¶ added in v0.4.0
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 (copilot, gemini_cli) or a primary data
// file path (cursor tracking DB, claude_code stats-cache.json).
// Prefer using Paths for new providers.
Binary string `json:"binary,omitempty"`
// BaseURL stores an API base URL (openrouter, codex, ollama) or a secondary
// data file path (cursor state.vscdb, claude_code .claude.json).
// Prefer using Paths for new providers.
BaseURL string `json:"base_url,omitempty"`
// Paths holds named provider-specific paths/URLs, replacing the overloaded
// Binary and BaseURL fields. Keys are provider-defined (e.g. "tracking_db",
// "state_db", "stats_cache", "account_config").
Paths map[string]string `json:"paths,omitempty"`
Token string `json:"-"` // runtime-only: access token (never persisted)
ExtraData map[string]string `json:"-"` // runtime-only: extra detection data (never persisted)
}
func MergeAccounts ¶ added in v0.5.0
func MergeAccounts(manual, autoDetected []AccountConfig) []AccountConfig
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 Paths first, then ExtraData (for backward compat with detect), then the given fallback.
func (AccountConfig) ResolveAPIKey ¶
func (c AccountConfig) ResolveAPIKey() string
func (*AccountConfig) SetPath ¶ added in v0.6.9
func (c *AccountConfig) SetPath(key, value string)
SetPath stores a named provider-specific path.
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 DashboardMetricMatcher ¶ added in v0.2.0
type DashboardRawGroup ¶ added in v0.2.0
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 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 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 ProviderSetupSpec ¶ added in v0.4.0
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 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 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.