accounts

package
v0.7.44 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 13 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	DefaultCheckinTime            = "09:00"
	CheckinDisabledAccountsSecret = "checkin_disabled_accounts"
)
View Source
const (
	KindQuota             = "quota"
	KindRateLimit         = "rate_limit"
	KindAuth              = "auth"
	KindNotReady          = "not_ready"
	KindUnavailable       = "unavailable"
	KindInvalidRequest    = "invalid_request"
	KindModelNotAvailable = "model_not_available"
	KindCanceled          = "canceled"
)
View Source
const (
	RoutingStrategyRoundRobin         = "round-robin"
	RoutingStrategyWeightedRoundRobin = "weighted-round-robin"
	RoutingStrategyFillFirst          = "fill-first"
	// RoutingStrategyFEFO is the opt-in earliest-expiry-first strategy. It
	// ranks accounts inside one provider family by the nearest credit-package
	// expiry and leaves cross-provider rotation untouched.
	RoutingStrategyFEFO = "fefo"
)
View Source
const (
	DefaultMaxInFlight = 4
	DefaultPriority    = 50
	// MaxAPIKeyInFlight is the largest concurrency cap a client key may store.
	// Zero means unlimited, matching keys created before the cap existed.
	MaxAPIKeyInFlight = 256
)
View Source
const (
	RequestStatusStarted    = "started"
	RequestStatusStreaming  = "streaming"
	RequestStatusOK         = "ok"
	RequestStatusIncomplete = "incomplete"
	RequestStatusError      = "error"
	RequestStatusCanceled   = "canceled"

	AttemptStatusStarted  = "started"
	AttemptStatusOK       = "ok"
	AttemptStatusError    = "error"
	AttemptStatusFailover = "failover"
)
View Source
const (
	RequestStatsDimModel    = "model"
	RequestStatsDimAccount  = "account"
	RequestStatsDimProvider = "provider"

	// RequestStatsDefaultLimit is the per-dimension row cap when no limit is
	// given (the overview rankings); RequestStatsMaxLimit bounds any request.
	RequestStatsDefaultLimit = 6
	RequestStatsMaxLimit     = 500
)

Stats grouping dimensions accepted by RequestStatsOptions.Dims.

View Source
const (
	DefaultWorkBuddyCheckinTime = "09:00"
	WorkBuddyCheckinTimeSecret  = "workbuddy_checkin_time"
)
View Source
const BackoffMaxLevel = 8

BackoffMaxLevel caps the exponential backoff ladder applied to repeated failures of the same kind. The classifier owns the duration math; this bound is shared with persist/restore so a restart cannot resume past it.

View Source
const QuotaPackageScopeAccountFEFO = "account-fefo"

QuotaPackageScopeAccountFEFO marks credit packages that the provider has confirmed are spendable by this account and carry a real package expiry. An empty or unknown scope never participates in FEFO ranking.

Variables

View Source
var ErrAPIKeyNotFound = errors.New("api key not found")
View Source
var ErrAccountNotFound = errors.New("account not found")
View Source
var ErrRequestLogNotFound = errors.New("request log not found")
View Source
var ErrSecretNotFound = errors.New("secret not found")

Functions

func APIKeyPrefix added in v0.2.21

func APIKeyPrefix(secret string) string

func CanonicalModelID added in v0.2.13

func CanonicalModelID(model string) string

func CheckinTimeDefault added in v0.6.1

func CheckinTimeDefault(ctx context.Context, store CheckinSettingsReader, providerID string) (string, error)

func CheckinTimeSecret added in v0.6.1

func CheckinTimeSecret(providerID string) string

func ClampBackoffLevel added in v0.6.0

func ClampBackoffLevel(level int) int

ClampBackoffLevel bounds a persisted or restored backoff ladder value.

func ConstantTimeEqual added in v0.2.21

func ConstantTimeEqual(left, right string) bool

func DefaultDropSystemPrompt added in v0.6.0

func DefaultDropSystemPrompt(provider string, value *bool) bool

DefaultDropSystemPrompt is the create-time default. WorkBuddy strips caller system prompts because upstream content screening rejects third-party identity. Trae, Kimi, and CodeArts keep them: clients such as MiMo Code put JSON instructions in the system prompt, and those families have no equivalent screening. An explicit value always wins.

func DefaultMaxInFlightValue added in v0.6.0

func DefaultMaxInFlightValue(value int) int

func DefaultPriorityValue added in v0.6.0

func DefaultPriorityValue(value int) int

func DefaultWorkBuddyAutoCheckin added in v0.6.0

func DefaultWorkBuddyAutoCheckin(value *bool) bool

func GenerateAPIKeySecret added in v0.2.21

func GenerateAPIKeySecret() (string, error)

func GrantedRegions added in v0.5.1

func GrantedRegions(provider string, allowed []string) (regions []string, allRegions bool)

GrantedRegions returns the set of regions of the given family the allowlist grants, with a boolean telling whether every region is allowed (bare entry or empty allowlist). Unknown regions in stored entries are still returned so callers can reason about explicit grants; validation happens at write time.

func GrantsAllowed added in v0.5.1

func GrantsAllowed(provider, region string, allowed []string) bool

GrantsAllowed reports whether provider+region is covered by the allowlist entries. An empty allowlist allows everything. A bare family entry ("workbuddy") covers every region of that family; a region-scoped entry only covers accounts whose region matches. Malformed entries never match.

func HashAPIKey added in v0.2.21

func HashAPIKey(secret string) string

func IsInvalidRequestText added in v0.2.12

func IsInvalidRequestText(text string) bool

IsInvalidRequestText reports whether an error body looks like an upstream content-screening rejection: the request itself is the problem, so no account should fail over or cool down. Quota and prompt-limit shapes are matched earlier in Classify and never reach this check.

func IsPromptLimitText added in v0.2.42

func IsPromptLimitText(text string) bool

func NewAttemptID added in v0.2.6

func NewAttemptID() string

func NewRequestID added in v0.2.6

func NewRequestID() string

func NormalizeAPIKeyMaxInFlight added in v0.7.34

func NormalizeAPIKeyMaxInFlight(value int) int

NormalizeAPIKeyMaxInFlight clamps a client-key concurrency cap. Zero and negatives mean unlimited. Values above MaxAPIKeyInFlight are not guessed down; the caller must reject them.

func NormalizeAPIKeyProviders added in v0.2.21

func NormalizeAPIKeyProviders(ids []string) ([]string, error)

func NormalizeAccountRouting added in v0.6.22

func NormalizeAccountRouting(aliases map[string]string, enabled []string) (map[string]string, []string, error)

NormalizeAccountRouting canonicalizes one account's alias map and enabled model list. An alias points at exactly one real model on that account. The enabled list is the catalog models the account may serve; empty means the operator saved a list with nothing selected.

func NormalizeCheckinTime added in v0.6.1

func NormalizeCheckinTime(value string) (string, error)

func NormalizeModelName added in v0.5.0

func NormalizeModelName(model string) string

NormalizeModelName converts display-name formats sent by external clients into the canonical model ID used for routing. It currently strips a leading "Provider: " segment (single-word provider, no spaces) before lowercasing and folding separators so names like "DeepSeek: DeepSeek V4.1 Flash" become "deepseek-v4.1-flash".

func NormalizeProviderFamily added in v0.3.1

func NormalizeProviderFamily(provider string) string

NormalizeProviderFamily maps a stored or requested provider ID onto the canonical family name. An empty value is Qoder, matching the historical default account family.

func NormalizeRegion added in v0.3.1

func NormalizeRegion(region string) string

NormalizeRegion maps a stored or requested region onto the canonical routing region. An empty value or the shorthand "gl" is global.

func NormalizeRoutingStrategy added in v0.2.45

func NormalizeRoutingStrategy(strategy string) string

func NormalizeWeight added in v0.2.29

func NormalizeWeight(priority int) int

NormalizeWeight maps a stored priority onto a scheduling weight. The console exposes 1..100 with 50 as the default; anything outside the range falls back to the default so a bad row cannot distort rotation.

func NormalizeWorkBuddyCheckinTime added in v0.5.0

func NormalizeWorkBuddyCheckinTime(value string) (string, error)

func PricedModelIDs added in v0.7.9

func PricedModelIDs() []string

PricedModelIDs returns the bare model ids that have a price row. The store uses this to filter request_logs without re-spelling the catalog.

func ProviderAllowed added in v0.3.1

func ProviderAllowed(provider string, allowed []string) bool

ProviderAllowed reports whether an account family may be used under an API key allowlist — i.e. whether any entry (bare or region-scoped) grants some region of the family. An empty allowlist means every family. An empty provider is treated as Qoder, the same default PickRoute uses. Region-level narrowing happens per candidate account via ProviderRegionAllowed.

func ProviderRegionAllowed added in v0.5.1

func ProviderRegionAllowed(provider, region string, allowed []string) bool

ProviderRegionAllowed reports whether a specific account (provider family plus region) is covered by an API key allowlist. This is the fail-closed gate every routed candidate must pass; ProviderAllowed alone answers only the family-level question and must not be used to admit an account.

func ResolveCheckinTime added in v0.6.1

func ResolveCheckinTime(ctx context.Context, store CheckinSettingsReader, account Account) (string, error)

func ResolveWorkBuddyCheckinTime added in v0.6.0

func ResolveWorkBuddyCheckinTime(value, defaultTime string) (string, error)

ResolveWorkBuddyCheckinTime inherits defaultTime when value is empty.

func ValidateAPIKeyMaxInFlight added in v0.7.34

func ValidateAPIKeyMaxInFlight(value int) error

func ValidateAccountProxy added in v0.6.0

func ValidateAccountProxy(providerID, region, raw string) error

ValidateAccountProxy enforces the per-provider proxy boundary. Child-process providers (Qoder) can only forward every cloud request through an http(s) proxy, so SOCKS is rejected for them; in-process providers (WorkBuddy, Trae) may use any scheme Parse accepts.

func ValidateCheckinSettings added in v0.6.1

func ValidateCheckinSettings(providerID, regionID string, enabled bool, override string) error

func ValidateModelContextLength added in v0.6.0

func ValidateModelContextLength(contextLength int) error

Types

type APIKey added in v0.2.21

type APIKey struct {
	ID          string     `json:"id"`
	Name        string     `json:"name"`
	Prefix      string     `json:"prefix"`
	Providers   []string   `json:"providers"`
	Enabled     bool       `json:"enabled"`
	MaxInFlight int        `json:"max_inflight"`
	LastUsedAt  *time.Time `json:"last_used_at,omitempty"`
	CreatedAt   time.Time  `json:"created_at"`
	UpdatedAt   time.Time  `json:"updated_at"`
	Secret      string     `json:"secret,omitempty"`
	SecretOnce  bool       `json:"secret_once,omitempty"`
}

func ApplyAPIKeyUpdate added in v0.6.0

func ApplyAPIKeyUpdate(current APIKey, input UpdateAPIKey) (APIKey, error)

type Account added in v0.2.0

type Account struct {
	ID             string `json:"id"`
	Name           string `json:"name"`
	RemoteUID      string `json:"remote_uid,omitempty"`
	Provider       string `json:"provider"`
	ProviderRegion string `json:"region"`
	AuthType       string `json:"auth_type"`
	Enabled        bool   `json:"enabled"`
	MaxInFlight    int    `json:"max_inflight"`
	Priority       int    `json:"priority"`
	// CreditFloor is the per-account credit floor override. Nil means "not
	// set" and defers to the global CLI2API_CREDIT_FLOOR; a non-nil value
	// (including 0, which disables the floor for this account) overrides it.
	// No omitempty: an explicit 0 must survive API responses so a caller can
	// distinguish "disable this account's floor" from "inherit the global floor".
	CreditFloor *float64 `json:"credit_floor"`
	// PercentFloor is the per-account floor for percent-denominated quota.
	// Nil defers to the global CLI2API_PERCENT_FLOOR; a non-nil value (including
	// 0, which disables the percent floor for this account) overrides it.
	PercentFloor *float64 `json:"percent_floor"`
	// DropSystemPrompt drops caller system prompts before provider-native chat.
	DropSystemPrompt bool `json:"drop_system_prompt"`
	// ModelAliases maps a client-facing name to this account's real catalog
	// model. Routing matches the alias; the request is rewritten to the real
	// model only after this account is picked.
	ModelAliases map[string]string `json:"model_aliases,omitempty"`
	// EnabledModels limits which catalog models this account may serve.
	// ModelsRestricted reports whether the operator saved a list; an empty
	// list then serves nothing, while an unset list serves the catalog.
	EnabledModels    []string `json:"enabled_models,omitempty"`
	ModelsRestricted bool     `json:"models_restricted,omitempty"`
	// WorkBuddyAutoCheckin opts into scheduled daily check-in (default off).
	WorkBuddyAutoCheckin bool `json:"workbuddy_auto_checkin"`
	// WorkBuddyCheckinTime is the process-local daily check-in time.
	WorkBuddyCheckinTime string `json:"workbuddy_checkin_time"`
	AutoCheckin          bool   `json:"auto_checkin"`
	CheckinTime          string `json:"checkin_time"`
	ProxyURL             string `json:"-"`
	// LastCheckin* are display-only WorkBuddy ops results.
	LastCheckinAt     string         `json:"last_checkin_at,omitempty"`
	LastCheckinMsg    string         `json:"last_checkin_msg,omitempty"`
	LastCheckinStatus string         `json:"last_checkin_status,omitempty"`
	Status            string         `json:"status"`
	LastError         string         `json:"last_error,omitempty"`
	LastErrorKind     string         `json:"last_error_kind,omitempty"`
	CooldownUntil     *time.Time     `json:"cooldown_until,omitempty"`
	Quota             *QuotaSnapshot `json:"-"`
	CreatedAt         time.Time      `json:"created_at"`
	UpdatedAt         time.Time      `json:"updated_at"`
}

type AccountStore added in v0.6.0

type AccountStore interface {
	PoolStateStore
	Close() error
	Backup(ctx context.Context, directory string, keep int) (Backup, error)
	Create(ctx context.Context, input CreateAccount) (Account, error)
	Get(ctx context.Context, id string) (Account, error)
	List(ctx context.Context) ([]Account, error)
	Update(ctx context.Context, id string, input UpdateAccount) error
	Delete(ctx context.Context, id string) error
	SaveCredential(ctx context.Context, accountID, authType string, credential NativeCredential) error
	LoadCredential(ctx context.Context, accountID string) (NativeCredential, error)
	SaveCredentialPayload(ctx context.Context, accountID, format string, payload []byte) error
	// SetCredentialAuthType records the credential kind ("pat"/"oauth") on the
	// account without rewriting the blob, so a PAT login shows the right type.
	SetCredentialAuthType(ctx context.Context, accountID, authType string) error
	LoadCredentialPayload(ctx context.Context, accountID string) (string, []byte, error)
	Observe(ctx context.Context, id, remoteUID, status, lastError, lastKind string) error
	// ObserveHealth updates the probe-derived fields (remote_uid, last_error,
	// last_error_kind) without touching the account status. It is used for
	// disabled accounts that have no pool item, where a probe must not promote
	// the account out of disabled.
	ObserveHealth(ctx context.Context, id, remoteUID, lastError, lastKind string) error
	SaveQuota(ctx context.Context, id string, quota *QuotaSnapshot) error
	RecordCheckin(ctx context.Context, id, status, msg string, at time.Time) error
	ListCheckinRecords(ctx context.Context, accountID string, limit int) ([]CheckinRecord, error)
	GetSecret(ctx context.Context, name string) (string, bool, error)
	SetSecret(ctx context.Context, name, value string) error
	SetSecretOrEmpty(ctx context.Context, name, value string) error
	WorkBuddyCheckinTimeDefault(ctx context.Context) string
	GetModelContext(ctx context.Context, modelID string) (int, bool, error)
	SetModelContext(ctx context.Context, modelID string, contextLength int) error
	ListModelContexts(ctx context.Context) (map[string]int, error)
	GetProviderModelSetting(ctx context.Context, provider, modelID string) (ProviderModelSetting, error)
	SetProviderModelSetting(ctx context.Context, provider, modelID string, setting ProviderModelSetting) error
	InsertAPIKey(ctx context.Context, key StoredAPIKey) (APIKey, error)
	SaveAPIKey(ctx context.Context, key StoredAPIKey) (APIKey, error)
	ListAPIKeys(ctx context.Context) ([]APIKey, error)
	GetAPIKey(ctx context.Context, id string) (APIKey, error)
	LookupAPIKey(ctx context.Context, secret string) (APIKey, bool, error)
	DeleteAPIKey(ctx context.Context, id string) error
	TouchAPIKey(ctx context.Context, id string) error
}

AccountStore is the persistence surface Manager and console HTTP use. The SQLite implementation lives in internal/store; this package must not import it.

type AccountView added in v0.2.0

type AccountView struct {
	Account
	Ready    bool `json:"ready"`
	Hot      bool `json:"hot"`
	InFlight int  `json:"in_flight"`
	// InFlightSince is RFC3339 when the pool slot went busy (0→1); empty when idle.
	InFlightSince       string            `json:"in_flight_since,omitempty"`
	Restarts            int               `json:"restarts"`
	RuntimeState        string            `json:"runtime_state,omitempty"`
	NextRestartAt       string            `json:"next_restart_at,omitempty"`
	RestartBackoffLevel int               `json:"restart_backoff_level,omitempty"`
	DownUntil           string            `json:"down_until,omitempty"`
	ModelCooldowns      map[string]string `json:"model_cooldowns,omitempty"`
	Quota               *QuotaSnapshot    `json:"quota,omitempty"`
	ProxyURL            string            `json:"proxy_url,omitempty"`
}

type Backup added in v0.2.2

type Backup struct {
	Name      string    `json:"name"`
	Path      string    `json:"-"`
	CreatedAt time.Time `json:"created_at"`
}

type CheckinAllResult added in v0.7.40

type CheckinAllResult struct {
	AccountID string `json:"account_id"`
	Provider  string `json:"provider"`
	Region    string `json:"region"`
	Status    string `json:"status"`
	Message   string `json:"message,omitempty"`
}

type CheckinRecord added in v0.2.40

type CheckinRecord struct {
	ID        string    `json:"id"`
	AccountID string    `json:"account_id"`
	Status    string    `json:"status"`
	Message   string    `json:"message"`
	CreatedAt time.Time `json:"created_at"`
}

type CheckinSettingsReader added in v0.6.1

type CheckinSettingsReader interface {
	GetSecret(context.Context, string) (string, bool, error)
}

type CooldownRow added in v0.2.29

type CooldownRow struct {
	AccountID    string
	Model        string
	DownUntil    time.Time
	BackoffLevel int
	Kind         string
	Message      string
	ModelKind    string
}

CooldownRow is one persisted cooldown: account-wide when Model is empty, scoped to a single canonical model otherwise. ModelKind holds the per-model previous failure kind (empty for the account-wide row) so the backoff ladder can resume after a restart without cross-model confusion.

type CostBreakdown added in v0.7.9

type CostBreakdown struct {
	Window   RequestStatsWindow `json:"window"`
	Currency string             `json:"currency"`
	Models   []ModelCost        `json:"models"`
	Totals   ModelCost          `json:"totals"`
	Series   []CostSeriesPoint  `json:"series"`
	Unpriced []string           `json:"unpriced,omitempty"`
}

CostBreakdown is the Usage Cost tab payload: quota and tokens for every model, plus an optional DeepSeek list-price CNY estimate for priced rows.

func BuildCostBreakdown added in v0.7.9

func BuildCostBreakdown(rows []CostUsageRow, from, to time.Time, daily bool) CostBreakdown

BuildCostBreakdown prices pre-aggregated usage rows into the console payload. When daily is true the series is bucketed by UTC day, otherwise by hour.

type CostSeriesPoint added in v0.7.9

type CostSeriesPoint struct {
	At              time.Time          `json:"at"`
	PerModel        map[string]float64 `json:"per_model"`
	PerModelCredits map[string]float64 `json:"per_model_credits"`
	PerModelTokens  map[string]float64 `json:"per_model_tokens"`
	Tokens          int64              `json:"tokens"`
	Credits         float64            `json:"credits"`
}

CostSeriesPoint is one time bucket for the stacked chart. PerModelCredits and PerModelTokens cover every model; PerModel holds DeepSeek list-price CNY for priced models only (optional estimate UI).

type CostUsageRow added in v0.7.9

type CostUsageRow struct {
	Model     string
	HourStart time.Time // UTC, truncated to the hour
	Requests  int64
	Usage     TokenUsage
	// Credits is the quota consumed in this bucket; it is provider-agnostic and
	// survives models that have no official list price.
	Credits float64
}

CostUsageRow is one pre-aggregated slice the store hands back: token usage for one model in one whole-hour UTC bucket. Bucketing by hour keeps every row on one side of DeepSeek's peak boundary (which is set on Beijing whole hours), so the peak/off-peak split stays exact even when callers ask for a daily view.

type CreateAPIKey added in v0.2.21

type CreateAPIKey struct {
	Name        string
	Providers   []string
	Enabled     bool
	MaxInFlight int
}

func PrepareCreateAPIKey added in v0.6.0

func PrepareCreateAPIKey(input CreateAPIKey) (CreateAPIKey, error)

type CreateAccount added in v0.2.0

type CreateAccount struct {
	AutoCheckin          *bool
	CheckinTime          string
	Name                 string
	Provider             string
	Region               string
	Enabled              bool
	MaxInFlight          int
	Priority             int
	CreditFloor          *float64
	PercentFloor         *float64
	DropSystemPrompt     *bool
	WorkBuddyAutoCheckin *bool
	WorkBuddyCheckinTime string
	ProxyURL             string
	ModelAliases         map[string]string
	EnabledModels        []string
	SetModelRouting      bool
}

type ImportAccount added in v0.2.0

type ImportAccount struct {
	AutoCheckin          *bool
	CheckinTime          string
	Name                 string
	Provider             string
	Region               string
	Enabled              bool
	MaxInFlight          int
	Priority             int
	CreditFloor          *float64
	PercentFloor         *float64
	DropSystemPrompt     *bool
	WorkBuddyAutoCheckin *bool
	WorkBuddyCheckinTime string
	ProxyURL             string
	Credential           NativeCredential
}

type ModelCost added in v0.7.9

type ModelCost struct {
	ID           string  `json:"id"`
	Label        string  `json:"label"`
	Vendor       string  `json:"vendor"`
	Currency     string  `json:"currency"`
	Requests     int64   `json:"requests"`
	CacheHit     int64   `json:"cache_hit"`
	CacheMiss    int64   `json:"cache_miss"`
	Output       int64   `json:"output"`
	TotalTokens  int64   `json:"total_tokens"`
	Cost         float64 `json:"cost"`
	CostOffPeak  float64 `json:"cost_off_peak"`
	CostPeak     float64 `json:"cost_peak"`
	PeakRequests int64   `json:"peak_requests"`
	// Credits is the subscription quota this model consumed, as recorded by the
	// provider. It applies to every provider, priced or not, and is the honest
	// cost unit for subscription accounts where no list price exists.
	Credits float64 `json:"credits"`
	// Priced reports whether an official list price backs the Cost fields.
	// Unpriced models still contribute tokens and Credits.
	Priced bool `json:"priced"`
}

ModelCost is the monetary breakdown for one model over one window.

type ModelPrice added in v0.7.9

type ModelPrice struct {
	ID               string         `json:"id"`
	Label            string         `json:"label"`
	Vendor           string         `json:"vendor"`
	Currency         string         `json:"currency"`
	OffPeak          ModelPriceBand `json:"off_peak"`
	Peak             ModelPriceBand `json:"peak"`
	PeakStartHour    int            `json:"peak_start_hour"`
	PeakEndHour      int            `json:"peak_end_hour"`
	PeakWeekdaysOnly bool           `json:"peak_weekdays_only"`
	PeakNote         string         `json:"peak_note,omitempty"`
	Source           string         `json:"source,omitempty"`
	// Alias marks an id that shares another row's price (legacy rename). The
	// console hides alias rows from the price table but still matches them in
	// logs so old request rows price correctly.
	Alias bool `json:"alias,omitempty"`
	// CanonicalID, when set, folds this alias onto the canonical priced model so
	// cost totals and the breakdown do not split one model across two rows.
	CanonicalID string `json:"canonical_id,omitempty"`
}

ModelPrice carries the official list price for one model. Peak hours are the vendor's published peak window in China Standard Time (UTC+8); a zero window (empty PeakStart/PeakEnd) means the model has a flat price. When flat, both bands hold the same numbers and PeakWeekdaysOnly is irrelevant.

func LookupModelPrice added in v0.7.9

func LookupModelPrice(modelID string) (ModelPrice, bool)

LookupModelPrice matches an upstream model id to a price row. Matching is case-insensitive, tolerates a provider prefix (workbuddy/...), and strips a trailing "-sg" / "_sg" regional suffix so WorkBuddy's Singapore aliases fold onto the same official price.

func ModelPriceCatalog added in v0.7.9

func ModelPriceCatalog() []ModelPrice

ModelPriceCatalog is the full set of priced models, sorted by vendor then id.

func (ModelPrice) Cost added in v0.7.9

func (p ModelPrice) Cost(u TokenUsage, peak bool) float64

Cost prices one request's usage; when peak is true it bills the whole split at the peak band. (Per-request granularity is the caller's; a request that straddles the boundary is billed by its start time, which matches how the provider stamps usage.)

type ModelPriceBand added in v0.7.9

type ModelPriceBand struct {
	CacheHit  float64 `json:"cache_hit"`
	CacheMiss float64 `json:"cache_miss"`
	Output    float64 `json:"output"`
}

TimeBand splits a price list into the off-peak and peak rows DeepSeek (and most CN vendors) bill at. Prices are CNY per 1M tokens.

type NativeCredential added in v0.2.0

type NativeCredential struct {
	UserBlob  []byte `json:"-"`
	MachineID string `json:"machine_id"`
}

type PoolState added in v0.6.0

type PoolState struct {
	ID            string
	DownUntil     time.Time
	LastError     string
	LastErrorKind string
}

PoolState is the persistable account-wide slice of a live pool item. Store and AccountStore stay free of executor types; runtime maps Item onto this DTO before writing.

type PoolStateStore added in v0.6.0

type PoolStateStore interface {
	RecordPoolState(ctx context.Context, state PoolState) error
	SaveCooldowns(ctx context.Context, accountID string, rows []CooldownRow) error
	LoadCooldowns(ctx context.Context) ([]CooldownRow, error)
}

PoolStateStore is the cooldown persistence surface used by the pool observer drainer. Pool and executor never see the SQLite type; they emit snapshots, and Manager writes through this interface.

type ProviderGrant added in v0.5.1

type ProviderGrant struct {
	Provider string
	Region   string
}

ProviderGrant is a single entry of an API key allowlist. Region is empty for a bare family grant ("workbuddy") that covers every region of the family, and set for a region-scoped grant ("workbuddy:cn").

Grants stay in accounts: ParseProviderGrant uses the providers catalog, and ProviderAllowed / ProviderRegionAllowed plus NormalizeAPIKeyProviders own the runtime/write paths. Moving this file to auth would create accounts → auth while auth already imports accounts.

func ParseProviderGrant added in v0.5.1

func ParseProviderGrant(entry string) (ProviderGrant, error)

ParseProviderGrant strictly parses one allowlist entry. Accepted forms:

workbuddy            bare family grant, any region
workbuddy:cn         family + region grant

Rejected: empty strings, unknown families, unknown regions, missing sides ("workbuddy:", ":cn"), more than one colon ("workbuddy:cn:x"), and any whitespace inside the entry.

func (ProviderGrant) String added in v0.5.1

func (g ProviderGrant) String() string

String renders the canonical storage form: "workbuddy:cn" or "workbuddy".

type ProviderModelSetting added in v0.2.21

type ProviderModelSetting struct {
	MaxMode         bool
	ReasoningEffort string
}

type QuotaPackage added in v0.6.6

type QuotaPackage struct {
	Remain  float64 `json:"remain"`
	Used    float64 `json:"used"`
	Size    float64 `json:"size"`
	Unit    string  `json:"unit,omitempty"`
	Scope   string  `json:"scope,omitempty"`
	EndsAt  int64   `json:"ends_at,omitempty"`
	EndTime string  `json:"end_time,omitempty"`
}

QuotaPackage is one upstream credit/resource pack that carries its own expiry. EndsAt is a Unix second; EndTime is the provider-native wall-clock string for display.

type QuotaSnapshot added in v0.2.7

type QuotaSnapshot struct {
	Used       float64       `json:"used"`
	Total      float64       `json:"total"`
	Remaining  float64       `json:"remaining"`
	Percentage float64       `json:"percentage"`
	Unit       string        `json:"unit"`
	Exceeded   bool          `json:"exceeded"`
	Windows    []QuotaWindow `json:"windows,omitempty"`
	// ExpiresAt is the soonest package expiry (Unix seconds); 0 means the
	// provider did not report one. ExpiringRemain is the remaining amount that
	// expires at that time.
	ExpiresAt                int64          `json:"expires_at,omitempty"`
	ExpiringRemain           float64        `json:"expiring_remain,omitempty"`
	Packages                 []QuotaPackage `json:"packages,omitempty"`
	HasAddOn                 bool           `json:"has_add_on"`
	AddOnUsed                float64        `json:"add_on_used"`
	AddOnTotal               float64        `json:"add_on_total"`
	AddOnRemaining           float64        `json:"add_on_remaining"`
	AddOnUnit                string         `json:"add_on_unit"`
	AddOnAvailable           *bool          `json:"add_on_available,omitempty"`
	HasResourcePackage       bool           `json:"has_resource_package"`
	ResourcePackageUsed      float64        `json:"resource_package_used"`
	ResourcePackageTotal     float64        `json:"resource_package_total"`
	ResourcePackageRemaining float64        `json:"resource_package_remaining"`
	ResourcePackageUnit      string         `json:"resource_package_unit"`
	ResourcePackageAvailable *bool          `json:"resource_package_available,omitempty"`
	FetchedAt                string         `json:"fetched_at"`
	// Plan is the upstream subscription tier. Empty means not reported.
	Plan string `json:"plan,omitempty"`
}

QuotaSnapshot is the quota state for one account. A zero value means "unknown". Exceeded gates quota routing; explicitly scoped package expiry may additionally guide opt-in FEFO scheduling.

type QuotaWindow added in v0.6.3

type QuotaWindow struct {
	ID         string  `json:"id"`
	Label      string  `json:"label,omitempty"`
	Used       float64 `json:"used"`
	Total      float64 `json:"total"`
	Remaining  float64 `json:"remaining"`
	Percentage float64 `json:"percentage"`
	Unit       string  `json:"unit,omitempty"`
	ResetAt    string  `json:"reset_at,omitempty"`
	Exceeded   bool    `json:"exceeded,omitempty"`
}

QuotaWindow is one provider-native usage period, such as Devin daily and weekly included quota. The top-level QuotaSnapshot fields stay the tighter of these windows for routing.

type RequestAttempt added in v0.2.6

type RequestAttempt struct {
	ID               string     `json:"id"`
	RequestID        string     `json:"request_id"`
	AttemptIndex     int        `json:"attempt_index"`
	AccountID        string     `json:"account_id,omitempty"`
	StartedAt        time.Time  `json:"started_at"`
	FinishedAt       *time.Time `json:"finished_at,omitempty"`
	Status           string     `json:"status"`
	HTTPStatus       *int       `json:"http_status,omitempty"`
	ErrorKind        string     `json:"error_kind,omitempty"`
	ErrorMessage     string     `json:"error_message,omitempty"`
	LatencyMs        *int       `json:"latency_ms,omitempty"`
	PromptTokens     *int       `json:"prompt_tokens,omitempty"`
	CompletionTokens *int       `json:"completion_tokens,omitempty"`
	UsageSource      string     `json:"usage_source,omitempty"`
}

type RequestLog added in v0.2.6

type RequestLog struct {
	ID                 string     `json:"id"`
	CreatedAt          time.Time  `json:"created_at"`
	FinishedAt         *time.Time `json:"finished_at,omitempty"`
	Stream             bool       `json:"stream"`
	Status             string     `json:"status"`
	RequestedModel     string     `json:"requested_model"`
	MappedModel        string     `json:"mapped_model,omitempty"`
	RequestedReasoning string     `json:"requested_reasoning,omitempty"`
	ResolvedReasoning  string     `json:"resolved_reasoning,omitempty"`
	AccountID          string     `json:"account_id,omitempty"`
	APIKeyID           string     `json:"api_key_id,omitempty"` // console API key id; "" for console-key traffic and legacy rows
	Provider           string     `json:"provider,omitempty"`
	Routing            string     `json:"routing,omitempty"`
	PromptTokens       *int       `json:"prompt_tokens,omitempty"`
	CompletionTokens   *int       `json:"completion_tokens,omitempty"`
	CacheReadTokens    *int       `json:"cache_read_tokens,omitempty"`
	CacheWriteTokens   *int       `json:"cache_write_tokens,omitempty"`
	UsageSource        string     `json:"usage_source,omitempty"`
	Credits            *float64   `json:"credits,omitempty"`
	LatencyMs          *int       `json:"latency_ms,omitempty"`
	TTFBMs             *int       `json:"ttfb_ms,omitempty"`
	ErrorKind          string     `json:"error_kind,omitempty"`
	ErrorCode          string     `json:"error_code,omitempty"`
	ErrorMessage       string     `json:"error_message,omitempty"`
	AttemptCount       int        `json:"attempt_count"`
	// DetailExpired marks a log whose detail rows and detail-only columns were
	// cleared by retention. The aggregate columns (tokens, credits, latency,
	// status, model) are still present, so usage totals stay exact; only the
	// per-request drill-down is gone.
	DetailExpired       bool                     `json:"detail_expired,omitempty"`
	MessageCount        int                      `json:"message_count,omitempty"`
	EmptyMessageIndexes []int                    `json:"empty_message_indexes,omitempty"`
	MessageRoles        []string                 `json:"message_roles,omitempty"`
	Attempts            []RequestAttempt         `json:"attempts,omitempty"`
	StreamDiagnostic    *RequestStreamDiagnostic `json:"stream_diagnostic,omitempty"`
	UsageDetail         *RequestUsageDetail      `json:"usage_detail,omitempty"`
}

type RequestLogFilter added in v0.2.6

type RequestLogFilter struct {
	AccountID string
	// APIKeyID narrows the window to requests issued by one console API key.
	APIKeyID  string
	Status    string
	Stream    *bool
	ErrorKind string
	Model     string
	// Provider matches the logged provider, falling back to the account's
	// provider for rows written before provider was recorded.
	Provider string
	ID       string
	Query    string
	From     *time.Time
	To       *time.Time
	Limit    int
	Offset   int
}

type RequestLogList added in v0.2.6

type RequestLogList struct {
	Items  []RequestLog `json:"items"`
	Total  int          `json:"total"`
	Limit  int          `json:"limit"`
	Offset int          `json:"offset"`
}

type RequestStats added in v0.2.14

type RequestStats struct {
	Window    RequestStatsWindow   `json:"window"`
	Totals    RequestStatsTotals   `json:"totals"`
	Latency   RequestStatsLatency  `json:"latency"`
	Tokens    RequestStatsTokens   `json:"tokens"`
	Status    []RequestStatsBucket `json:"status"`
	Errors    []RequestStatsBucket `json:"errors"`
	Models    []RequestStatsNamed  `json:"models"`
	Accounts  []RequestStatsNamed  `json:"accounts"`
	Providers []RequestStatsNamed  `json:"providers"`
	Series    []RequestStatsPoint  `json:"series"`
}

type RequestStatsBucket added in v0.2.14

type RequestStatsBucket struct {
	Key   string `json:"key"`
	Count int    `json:"count"`
}

type RequestStatsLatency added in v0.2.14

type RequestStatsLatency struct {
	AvgMs     *int `json:"avg_ms,omitempty"`
	P50Ms     *int `json:"p50_ms,omitempty"`
	P95Ms     *int `json:"p95_ms,omitempty"`
	TTFBAvgMs *int `json:"ttfb_avg_ms,omitempty"`
}

type RequestStatsNamed added in v0.2.14

type RequestStatsNamed struct {
	Key          string `json:"key"`
	Count        int    `json:"count"`
	OK           int    `json:"ok"`
	Error        int    `json:"error"`
	LatencyAvgMs *int   `json:"latency_avg_ms,omitempty"`
	LatencyP95Ms *int   `json:"latency_p95_ms,omitempty"`
	// Usage totals for the group.
	PromptTokens     int64   `json:"prompt_tokens"`
	CompletionTokens int64   `json:"completion_tokens"`
	CacheReadTokens  int64   `json:"cache_read_tokens"`
	CacheWriteTokens int64   `json:"cache_write_tokens"`
	Credits          float64 `json:"credits"`
}

type RequestStatsOptions added in v0.7.2

type RequestStatsOptions struct {
	From     time.Time
	To       time.Time
	Dims     []string
	Limit    int
	APIKeyID string
}

RequestStatsOptions selects the window, which grouped lists to compute and how many rows each may return. Empty Dims means all three dimensions. APIKeyID narrows every aggregate to one console API key, so the usage view can report a single key's traffic; empty means all keys.

func (RequestStatsOptions) EffectiveLimit added in v0.7.2

func (o RequestStatsOptions) EffectiveLimit() int

EffectiveLimit clamps Limit to [1, RequestStatsMaxLimit], defaulting to RequestStatsDefaultLimit.

func (RequestStatsOptions) WantsDim added in v0.7.2

func (o RequestStatsOptions) WantsDim(dim string) bool

WantsDim reports whether dim's grouped list should be computed.

type RequestStatsPoint added in v0.2.14

type RequestStatsPoint struct {
	At       time.Time `json:"at"`
	Requests int       `json:"requests"`
	OK       int       `json:"ok"`
	Error    int       `json:"error"`
	// Per-bucket usage and latency for the traffic chart's metric switch.
	PromptTokens     int64 `json:"prompt_tokens"`
	CompletionTokens int64 `json:"completion_tokens"`
	CacheReadTokens  int64 `json:"cache_read_tokens"`
	LatencyP50Ms     *int  `json:"latency_p50_ms,omitempty"`
	LatencyP95Ms     *int  `json:"latency_p95_ms,omitempty"`
}

type RequestStatsTokens added in v0.2.14

type RequestStatsTokens struct {
	Prompt     int64 `json:"prompt"`
	Completion int64 `json:"completion"`
	CacheRead  int64 `json:"cache_read"`
	CacheWrite int64 `json:"cache_write"`
	Total      int64 `json:"total"`
}

type RequestStatsTotals added in v0.2.14

type RequestStatsTotals struct {
	Requests    int     `json:"requests"`
	OK          int     `json:"ok"`
	Incomplete  int     `json:"incomplete"`
	Error       int     `json:"error"`
	Canceled    int     `json:"canceled"`
	Streaming   int     `json:"streaming"`
	SuccessRate float64 `json:"success_rate"`
	Credits     float64 `json:"credits"`
}

type RequestStatsWindow added in v0.2.14

type RequestStatsWindow struct {
	From  time.Time `json:"from"`
	To    time.Time `json:"to"`
	Hours int       `json:"hours"`
}

type RequestStreamDiagnostic added in v0.3.7

type RequestStreamDiagnostic struct {
	RequestID          string     `json:"request_id"`
	CreatedAt          time.Time  `json:"created_at"`
	FinishedAt         *time.Time `json:"finished_at,omitempty"`
	UpstreamStatus     *int       `json:"upstream_status,omitempty"`
	UpstreamRequestID  string     `json:"upstream_request_id,omitempty"`
	ContextErr         string     `json:"context_err,omitempty"`
	CancellationSource string     `json:"cancellation_source,omitempty"`
	RelayError         string     `json:"relay_error,omitempty"`
	SSEEventCount      int        `json:"sse_event_count"`
	BytesRead          int64      `json:"bytes_read"`
	ContentLength      int        `json:"content_length"`
	LastEvent          string     `json:"last_event,omitempty"`
	SawDone            bool       `json:"saw_done"`
}

type RequestUsage added in v0.7.4

type RequestUsage struct {
	Window          RequestStatsWindow      `json:"window"`
	Totals          RequestUsageTotals      `json:"totals"`
	ByAccount       []RequestUsageRow       `json:"by_account"`
	ByModel         []RequestUsageRow       `json:"by_model"`
	ByRealm         []RequestUsageRow       `json:"by_realm"`
	CreditByAccount []RequestUsageCreditRow `json:"credit_by_account"`
	CreditByModel   []RequestUsageCreditRow `json:"credit_by_model"`
	// Series is retained for JSON compatibility but left empty; Overview
	// traffic uses /api/logs/stats series instead.
	Series []RequestStatsPoint `json:"series"`
}

RequestUsage is the token / credit breakdown behind the Overview usage panels. It aggregates request_logs (tokens, prefix-cache hits, latency, credits) into per-account / per-model / per-realm rows plus two credit ledgers. It is a superset of RequestStats aimed at the "usage detail" and "credit deduction history" views rather than the traffic chart.

type RequestUsageCreditRow added in v0.7.4

type RequestUsageCreditRow struct {
	Key                string   `json:"key"`
	Nickname           string   `json:"nickname,omitempty"`
	Realm              string   `json:"realm,omitempty"`
	Rate               *float64 `json:"rate,omitempty"`
	Requests           int      `json:"requests"`
	CreditSamples      int      `json:"credit_samples"`
	Credits            float64  `json:"credits"`
	CreditTokens       int64    `json:"credit_tokens"`
	CreditsPer1MTokens *float64 `json:"credits_per_1m_tokens,omitempty"`
	CacheHitTokens     int64    `json:"cache_hit_tokens"`
	CacheMissTokens    int64    `json:"cache_miss_tokens"`
}

type RequestUsageDetail added in v0.5.4

type RequestUsageDetail struct {
	RequestID string    `json:"request_id"`
	CreatedAt time.Time `json:"created_at"`
	Provider  string    `json:"provider,omitempty"`
	Credit    *float64  `json:"credit,omitempty"`
	Unit      string    `json:"unit,omitempty"`
}

type RequestUsageRow added in v0.7.4

type RequestUsageRow struct {
	Key                string   `json:"key"`
	Realm              string   `json:"realm,omitempty"`
	Extra              string   `json:"extra,omitempty"`
	TotalTokens        int64    `json:"total_tokens"`
	PromptTokens       int64    `json:"prompt_tokens"`
	CompletionTokens   int64    `json:"completion_tokens"`
	CacheHitTokens     int64    `json:"cache_hit_tokens"`
	CacheMissTokens    int64    `json:"cache_miss_tokens"`
	Requests           int      `json:"requests"`
	Errors             int      `json:"errors"`
	AvgLatencyMs       *int     `json:"avg_latency_ms,omitempty"`
	AvgTokensPerSecond *float64 `json:"avg_tokens_per_second,omitempty"`
}

type RequestUsageTotals added in v0.7.4

type RequestUsageTotals struct {
	TotalTokens        int64    `json:"total_tokens"`
	PromptTokens       int64    `json:"prompt_tokens"`
	CompletionTokens   int64    `json:"completion_tokens"`
	CacheHitTokens     int64    `json:"cache_hit_tokens"`
	CacheMissTokens    int64    `json:"cache_miss_tokens"`
	Requests           int      `json:"requests"`
	Errors             int      `json:"errors"`
	AvgLatencyMs       *int     `json:"avg_latency_ms,omitempty"`
	AvgTokensPerSecond *float64 `json:"avg_tokens_per_second,omitempty"`
	Credits            float64  `json:"credits"`
	CreditTokens       int64    `json:"credit_tokens"`
	CreditSamples      int      `json:"credit_samples"`
	CreditsPer1MTokens *float64 `json:"credits_per_1m_tokens,omitempty"`
	SuccessRate        float64  `json:"success_rate"`
}

type StoredAPIKey added in v0.6.0

type StoredAPIKey struct {
	ID          string
	Name        string
	Prefix      string
	KeyHash     string
	Providers   []string
	Enabled     bool
	MaxInFlight int
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

type TokenUsage added in v0.7.9

type TokenUsage struct {
	CacheHit  int64 `json:"cache_hit"`
	CacheMiss int64 `json:"cache_miss"`
	Output    int64 `json:"output"`
}

TokenUsage is the billable token split a request produced. CacheMiss is the portion of the prompt that was NOT served from cache (prompt - cache_read).

func (TokenUsage) Total added in v0.7.9

func (u TokenUsage) Total() int64

Total returns all billable tokens together.

type UpdateAPIKey added in v0.2.21

type UpdateAPIKey struct {
	Name        string
	Providers   []string
	Enabled     *bool
	MaxInFlight *int
}

type UpdateAccount added in v0.2.0

type UpdateAccount struct {
	AutoCheckin *bool
	CheckinTime *string
	Name        string
	Enabled     *bool
	MaxInFlight *int
	Priority    *int
	// CreditFloor overrides the global floor when non-nil. A nil pointer
	// leaves the stored value unchanged on PATCH; a non-nil value (including
	// 0, which disables the floor for this account) is stored as the override.
	CreditFloor  *float64
	PercentFloor *float64
	// SetCreditFloor/SetPercentFloor let a caller explicitly clear an override
	// (store NULL) while leaving PATCH fields absent untouched. Without these,
	// a JSON null would be indistinguishable from an omitted field in *float64.
	SetCreditFloor       bool
	SetPercentFloor      bool
	DropSystemPrompt     *bool
	WorkBuddyAutoCheckin *bool
	WorkBuddyCheckinTime *string
	ProxyURL             *string
	// ModelAliases and EnabledModels replace the stored routing when
	// SetModelRouting is true. Nil aliases clear the map; nil enabled models
	// mean the account can serve its whole catalog.
	ModelAliases    map[string]string
	EnabledModels   []string
	SetModelRouting bool
}

Jump to

Keyboard shortcuts

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