providerusage

package
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 37 Imported by: 0

Documentation

Overview

Package providerusage owns profile-scoped, in-memory usage snapshots and collection lifetimes. Collectors read only resolved-route credentials; background intent never accesses the Keychain. Publication fences route and credential ownership, and stale retention never crosses accounts. The daemon supplies DefaultRegistry to NewService and owns Start, consent invalidation, and Shutdown.

Index

Constants

View Source
const MaxResponseBytes = 1 << 20

Variables

This section is empty.

Functions

func KeychainSupported

func KeychainSupported() bool

KeychainSupported reports whether the daemon host has the Claude Keychain source.

func ParseRetryAfter

func ParseRetryAfter(value string, now time.Time) time.Time

Types

type Account

type Account struct {
	Label string // email or org display name; display-only
	Plan  string // provider plan string, verbatim ("max_20x", "pro", "team")
}

type Action

type Action string
const (
	ActionSignIn        Action = "sign_in"
	ActionAllowKeychain Action = "allow_keychain"
	ActionRefresh       Action = "refresh"
	ActionRetry         Action = "retry"
	ActionConfigure     Action = "configure"
	ActionNone          Action = ""
)

type Amount

type Amount struct {
	Value string // decimal string, no float rounding
	Unit  string // "USD", "CNY", "credits", "requests", "tokens"
}

type Balance

type Balance struct {
	ID        string // "credits", "prepaid", "promo"
	Label     string
	Remaining Amount
	ExpiresAt *time.Time
}

type ClaudeCollector

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

func NewClaudeCollector

func NewClaudeCollector(options ...ClaudeOption) *ClaudeCollector

func (*ClaudeCollector) ClearCredentials

func (c *ClaudeCollector) ClearCredentials(profileID string)

func (*ClaudeCollector) Close

func (c *ClaudeCollector) Close() error

func (*ClaudeCollector) Collect

func (c *ClaudeCollector) Collect(
	ctx context.Context,
	target Target,
	_ Intent,
	identity CredentialIdentity,
) (Snapshot, error)

func (*ClaudeCollector) Identity

func (c *ClaudeCollector) Identity(ctx context.Context, target Target, intent Intent) (CredentialIdentity, error)

func (*ClaudeCollector) ProviderID

func (*ClaudeCollector) ProviderID() string

func (*ClaudeCollector) ValidateIdentity

func (c *ClaudeCollector) ValidateIdentity(_ context.Context, target Target, identity CredentialIdentity) error

ValidateIdentity never reads the Keychain, including for an explicit one-shot collection.

type ClaudeOption

type ClaudeOption func(*ClaudeCollector)

func WithClaudeClock

func WithClaudeClock(now func() time.Time) ClaudeOption

func WithClaudeHTTP

func WithClaudeHTTP(baseURL string, transport http.RoundTripper) ClaudeOption

func WithClaudeKeychain

func WithClaudeKeychain(reader KeychainReader) ClaudeOption

func WithClaudePlatform

func WithClaudePlatform(platform string) ClaudeOption

WithClaudePlatform overrides the host platform for collectors with an injected Keychain reader.

type CodexCollector

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

func NewCodexCollector

func NewCodexCollector(options CodexOptions) *CodexCollector

func (*CodexCollector) Collect

func (c *CodexCollector) Collect(
	ctx context.Context,
	t Target,
	intent Intent,
	cred CredentialIdentity,
) (Snapshot, error)

func (*CodexCollector) Identity

func (*CodexCollector) ProviderID

func (*CodexCollector) ProviderID() string

type CodexOptions

type CodexOptions struct {
	BaseURL   string
	Transport http.RoundTripper
	Now       func() time.Time
}

type Collector

type Collector interface {
	ProviderID() string
	CredentialProbe
	// Errors may carry fenced partial data without MeasuredAt; same-owner last-good data takes precedence.
	Collect(ctx context.Context, t Target, intent Intent, cred CredentialIdentity) (Snapshot, error) // *UsageError
}

Collector produces one snapshot for a target using the credential the probe identified.

type CollectorOption

type CollectorOption func(*collectorHTTP)

func WithCollectorBaseURL

func WithCollectorBaseURL(baseURL string) CollectorOption

func WithCollectorClock

func WithCollectorClock(now func() time.Time) CollectorOption

func WithCollectorTransport

func WithCollectorTransport(transport http.RoundTripper) CollectorOption

type Confidence

type Confidence string
const (
	ConfidenceExact       Confidence = "exact"
	ConfidencePercentOnly Confidence = "percent_only"
	ConfidenceEstimated   Confidence = "estimated"
)

type CredentialCache

type CredentialCache interface {
	// An empty profile ID clears every cached profile.
	ClearCredentials(profileID string)
}

type CredentialIdentity

type CredentialIdentity struct {
	Digest    [32]byte `json:"-"` // HMAC-SHA256(process-random key, source kind || credential bytes)
	AccountID string   `json:"-"` // upstream account ID when readable without network; "" otherwise
}

CredentialIdentity fences publication and keys cooldowns. Never serialized, logged, or exposed.

func NewCredentialIdentity

func NewCredentialIdentity(source SourceKind, credential []byte, accountID string) CredentialIdentity

func (CredentialIdentity) Format

func (CredentialIdentity) Format(s fmt.State, _ rune)

func (CredentialIdentity) LogValue

func (CredentialIdentity) LogValue() slog.Value

func (CredentialIdentity) Same

type CredentialProbe

type CredentialProbe interface {
	Identity(ctx context.Context, t Target, intent Intent) (CredentialIdentity, error) // *UsageError
}

CredentialProbe reads the route's credential without network access.

type CursorCollector

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

func NewCursorCollector

func NewCursorCollector(options ...CollectorOption) *CursorCollector

func (*CursorCollector) Collect

func (*CursorCollector) Identity

func (*CursorCollector) ProviderID

func (*CursorCollector) ProviderID() string

type Envelope

type Envelope struct {
	KeychainSupported bool
	ProfileID         string
	Revision          uint64 // monotonic per profile within one daemon process
	GeneratedAt       time.Time
	Enabled           bool
	Tray              *TraySignal // nil when no known window
	Targets           []Snapshot  // resolver order; daemon catalog uses canonical provider IDs
}

type ErrorCode

type ErrorCode string
const (
	ErrorCodeProfileNotFound         ErrorCode = "profile_not_found"
	ErrorCodeProfileSessionConflict  ErrorCode = "profile_session_conflict"
	ErrorCodeInvalidRequest          ErrorCode = "invalid_request"
	ErrorCodeAppTokenRouteForbidden  ErrorCode = "app_token_route_forbidden" //nolint:gosec // Public error code.
	ErrorCodeProviderNotFound        ErrorCode = "provider_not_found"
	ErrorCodeProviderUsageDisabled   ErrorCode = "provider_usage_disabled"
	ErrorCodeAuthMissing             ErrorCode = "auth_missing"
	ErrorCodeAuthExpired             ErrorCode = "auth_expired"
	ErrorCodeAuthScope               ErrorCode = "auth_scope"
	ErrorCodeKeychainConsentRequired ErrorCode = "keychain_consent_required"
	ErrorCodeKeychainDenied          ErrorCode = "keychain_denied"
	ErrorCodeKeychainTokenExpired    ErrorCode = "keychain_token_expired"
	ErrorCodeProviderRateLimited     ErrorCode = "provider_rate_limited"
	ErrorCodeProviderUnavailable     ErrorCode = "provider_unavailable"
	ErrorCodeNetworkError            ErrorCode = "network_error"
	ErrorCodeParseError              ErrorCode = "parse_error"
	ErrorCodeNoCollector             ErrorCode = "no_collector"
	ErrorCodeNoPlan                  ErrorCode = "no_plan"
	ErrorCodeAuthStoreUnsupported    ErrorCode = "auth_store_unsupported"
	ErrorCodeDisabled                ErrorCode = "disabled"
)

type GeminiCollector

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

func NewGeminiCollector

func NewGeminiCollector(options ...CollectorOption) *GeminiCollector

func (*GeminiCollector) Collect

func (*GeminiCollector) Identity

func (*GeminiCollector) ProviderID

func (*GeminiCollector) ProviderID() string

type HTTPClient

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

HTTPClient confines authenticated requests to their original origin.

func NewHTTPClient

func NewHTTPClient(baseURL string, transport http.RoundTripper, now func() time.Time) *HTTPClient

func (*HTTPClient) Do

func (c *HTTPClient) Do(
	ctx context.Context,
	method, path string,
	headers http.Header,
	body io.Reader,
	provider string,
) ([]byte, error)

type Intent

type Intent string
const (
	IntentBackground Intent = "background" // No Keychain reads; honors cooldowns.
	IntentExplicit   Intent = "explicit"   // Local operator action; may read Keychain.
)

type KeychainReader

type KeychainReader interface {
	// Read must never prompt when interactive is false.
	Read(ctx context.Context, service, account string, interactive bool) ([]byte, error)
}

type KimiCollector

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

func NewKimiCLICollector

func NewKimiCLICollector(options ...CollectorOption) *KimiCollector

func NewKimiCollector

func NewKimiCollector(options ...CollectorOption) *KimiCollector

func (*KimiCollector) Collect

func (c *KimiCollector) Collect(ctx context.Context, t Target, _ Intent, cred CredentialIdentity) (Snapshot, error)

func (*KimiCollector) Identity

func (*KimiCollector) ProviderID

func (c *KimiCollector) ProviderID() string

type Manager

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

func NewService

func NewService(options Options) *Manager

func (*Manager) BootID

func (s *Manager) BootID() string

func (*Manager) ClearCredentials

func (s *Manager) ClearCredentials(profileID, providerID string)

ClearCredentials invalidates a provider cache and its snapshots after consent changes.

func (*Manager) Envelope

func (s *Manager) Envelope(ctx context.Context, profile string) (Envelope, error)

func (*Manager) Refresh

func (s *Manager) Refresh(ctx context.Context, req RefreshRequest) (Envelope, error)

func (*Manager) SetEnabled

func (s *Manager) SetEnabled(ctx context.Context, enabled bool) error

SetEnabled drops all cached values and joins canceled flights before returning on disable.

func (*Manager) SetRefreshInterval

func (s *Manager) SetRefreshInterval(interval time.Duration)

SetRefreshInterval reschedules from now; intervals outside [1m, 1h] are ignored. Startup jitter, error outcomes, and active cooldown deadlines are preserved.

func (*Manager) Shutdown

func (s *Manager) Shutdown(ctx context.Context) error

func (*Manager) Start

func (s *Manager) Start(ctx context.Context, profileIDs []string) error

Start reconciles the complete live profile list and schedules startup within ten seconds.

func (*Manager) Subscribe

func (s *Manager) Subscribe(profile string) (<-chan Revision, func())

type Metrics

type Metrics interface {
	Collect(provider string, status Status, duration time.Duration)
}

type OpenRouterCollector

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

func NewOpenRouterCollector

func NewOpenRouterCollector(options ...CollectorOption) *OpenRouterCollector

func (*OpenRouterCollector) Collect

func (*OpenRouterCollector) Identity

func (*OpenRouterCollector) ProviderID

func (*OpenRouterCollector) ProviderID() string

type Options

type Options struct {
	Resolver        TargetResolver
	Collectors      Registry
	Clock           clockwork.Clock
	RefreshInterval time.Duration
	Logger          *slog.Logger
	Metrics         Metrics
	// Disabled defaults to false; Start owns scheduling for the supplied profiles.
	Disabled bool
}

type PublicationValidator

type PublicationValidator interface {
	ValidateIdentity(ctx context.Context, t Target, captured CredentialIdentity) error
}

PublicationValidator validates one-shot credentials without loading them again.

type RefreshRequest

type RefreshRequest struct {
	ProfileID   string
	ProviderIDs []string      // empty = all targets
	MaxAge      time.Duration // refresh only snapshots older than max(MaxAge, 30s floor)
	Wait        time.Duration // caller wait for results (zero returns immediately, max 30s); never bounds the flight
	Intent      Intent        // decided by the API boundary from principal + requested intent
}

type Registry

type Registry map[string]Collector

func DefaultRegistry

func DefaultRegistry(options RegistryOptions) Registry

DefaultRegistry constructs the supported collectors without probing credentials or providers.

type RegistryOptions

type RegistryOptions struct {
	BaseURLs  map[string]string
	Transport http.RoundTripper
	Now       func() time.Time
	Keychain  KeychainReader
}

type ResolvedRoute

type ResolvedRoute struct {
	Env            []string          // effective provider env (home/config dir), secrets excluded
	NativeCommand  string            // resolved native CLI path when the provider has one ("" if absent)
	BoundSecrets   map[string]string // slot -> value, only slots declared by the provider
	KeychainAccess bool              // operator consent recorded in config
}

ResolvedRoute is the read-only launch context a collector may use.

type Revision

type Revision struct {
	Revision uint64 `json:"revision"`
	BootID   string `json:"boot_id"`
}

type Service

type Service interface {
	Envelope(ctx context.Context, profileID string) (Envelope, error)
	Refresh(ctx context.Context, req RefreshRequest) (Envelope, error)
	Subscribe(profileID string) (<-chan Revision, func())
}

Service is the daemon-owned read model.

type Severity

type Severity string
const (
	SeverityNeutral   Severity = "neutral"
	SeverityWarning   Severity = "warning"
	SeverityExhausted Severity = "exhausted"
)

type Snapshot

type Snapshot struct {
	ProviderID    string
	ProviderName  string
	Status        Status
	Source        *Source // nil before first success
	Account       *Account
	Windows       []Window
	Balances      []Balance
	SpendCaps     []SpendCap
	Confidence    Confidence // exact | percent_only | estimated
	MeasuredAt    *time.Time // when the provider measured / we received accepted data
	CheckedAt     *time.Time // last attempt, success or failure
	NextRefreshAt *time.Time
	Refreshing    bool // a collection for this target is in flight
	Error         *UsageError
}

type Source

type Source struct {
	Kind  SourceKind // cli_rpc | oauth_http | api_key_http | acp_observed
	Label string     // "Codex app-server", "Claude Code OAuth", "OpenRouter API key"
}

type SourceKind

type SourceKind string
const (
	SourceKindCLIRPC      SourceKind = "cli_rpc"
	SourceKindOAuthHTTP   SourceKind = "oauth_http"
	SourceKindAPIKeyHTTP  SourceKind = "api_key_http" //nolint:gosec // Public source-kind identifier, not a credential.
	SourceKindACPObserved SourceKind = "acp_observed"
)

type SpendCap

type SpendCap struct {
	ID          string // "extra_usage", "key_limit", "monthly_budget"
	Label       string
	Used        Amount
	Limit       *Amount // nil = no cap reported (not "unlimited")
	UsedPercent *float64
	ResetsAt    *time.Time
	Enabled     *bool
}

type Status

type Status string
const (
	StatusOK           Status = "ok"
	StatusStale        Status = "stale"
	StatusRefreshing   Status = "refreshing"
	StatusSignedOut    Status = "signed_out"
	StatusNeedsConsent Status = "needs_consent"
	StatusRateLimited  Status = "rate_limited"
	StatusError        Status = "error"
	StatusUnsupported  Status = "unsupported"
	StatusDisabled     Status = "disabled"
)

type Target

type Target struct {
	ProfileID        string
	ProviderID       string // canonical Compozy provider ID
	ProviderName     string // catalog display name
	RouteFingerprint string // daemon-derived; never caller-supplied
	Status           Status // Empty means eligible for collection.
	Error            *UsageError
	Route            ResolvedRoute
}

Target is one profile-scoped provider route whose usage is collected.

type TargetCatalog

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

TargetCatalog provides atomic profile route replacement for configuration-driven composition.

func (*TargetCatalog) Replace

func (c *TargetCatalog) Replace(profile string, targets []Target)

func (*TargetCatalog) Targets

func (c *TargetCatalog) Targets(ctx context.Context, profile string) ([]Target, error)

type TargetResolver

type TargetResolver interface {
	Targets(ctx context.Context, profileID string) ([]Target, error)
}

TargetResolver lists the enabled targets for one profile.

type TraySignal

type TraySignal struct {
	ProviderID  string
	WindowID    string
	Label       string // "Codex · Weekly"
	UsedPercent float64
	ResetsAt    *time.Time
	Severity    Severity // neutral | warning | exhausted
	Stale       bool
}

func SelectTray

func SelectTray(targets []Snapshot) *TraySignal

type UsageError

type UsageError struct {
	Code       ErrorCode // see _dx.md Errors
	Message    string    // redacted, operator-readable
	Action     string    // "sign_in" | "allow_keychain" | "refresh" | "retry" | "configure" | ""
	RetryAfter *time.Time
}

func AsUsageError

func AsUsageError(err error, provider string) *UsageError

func NewUsageError

func NewUsageError(code ErrorCode, provider string) *UsageError

NewUsageError never includes upstream error text or response bodies.

func RateLimited

func RateLimited(provider string, until time.Time) *UsageError

func (*UsageError) Error

func (e *UsageError) Error() string

func (*UsageError) Status

func (e *UsageError) Status() Status

type VercelCollector

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

func NewVercelCollector

func NewVercelCollector(options ...CollectorOption) *VercelCollector

func (*VercelCollector) Collect

func (*VercelCollector) Identity

func (*VercelCollector) ProviderID

func (*VercelCollector) ProviderID() string

type Window

type Window struct {
	ID              string     // stable per provider: "session", "weekly", "weekly_opus", "model:<slug>:weekly", "monthly"
	Label           string     // "Session", "Weekly", "Weekly · Opus"
	Kind            WindowKind // session | daily | weekly | monthly | model | other
	DurationSeconds *int64
	UsedPercent     *float64 // nil = unknown
	Used            *Amount  // optional raw counts when the provider reports them
	Limit           *Amount
	ResetsAt        *time.Time
	ResetText       string // provider text when no timestamp exists
}

type WindowKind

type WindowKind string
const (
	WindowKindSession WindowKind = "session"
	WindowKindDaily   WindowKind = "daily"
	WindowKindWeekly  WindowKind = "weekly"
	WindowKindMonthly WindowKind = "monthly"
	WindowKindModel   WindowKind = "model"
	WindowKindOther   WindowKind = "other"
)

type ZaiCollector

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

func NewZaiCollector

func NewZaiCollector(options ...CollectorOption) *ZaiCollector

func (*ZaiCollector) Collect

func (c *ZaiCollector) Collect(ctx context.Context, t Target, _ Intent, cred CredentialIdentity) (Snapshot, error)

func (*ZaiCollector) Identity

func (*ZaiCollector) ProviderID

func (*ZaiCollector) ProviderID() string

Jump to

Keyboard shortcuts

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