accounts

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: AGPL-3.0 Imports: 17 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

Overview

Package accounts keeps the live pool of upstream accounts: selection, token refresh, cooldowns, quota polling and banked-reset redemption.

Index

Constants

View Source
const (
	ActionStop  = "stop"  // return the error to the client
	ActionRetry = "retry" // try another account
)

Error actions decide what happens to a request after an upstream error.

View Source
const (
	CooldownNone    = "none"
	CooldownAccount = "account"
	CooldownModel   = "model" // only this model on this account
	CooldownAuto    = ""      // built-in judgement (rate-limit headers etc.)
)

Cooldown scopes decide what gets benched after an error.

View Source
const (
	StatusOK       = "ok"
	StatusCooldown = "cooldown"
	StatusError    = "error"
	StatusReauth   = "reauth"
)

Variables

View Source
var DefaultPrimerModels = map[string]string{"claude": "haiku", "codex": "gpt-5.6-luna(low)"}

DefaultPrimerModels are the cheapest models each provider's subscription accepts. "haiku" resolves to the newest Haiku the account can use.

View Source
var ErrNoAccounts = errors.New("no accounts configured for this provider")

Functions

func ValidZone

func ValidZone(name string) bool

ValidZone reports whether name is an IANA time zone this build knows.

func ZoneName

func ZoneName(loc *time.Location) string

ZoneName names loc for people. The server's own zone is often just "Local" (always on Windows), so it falls back to $TZ and then to the current UTC offset.

Types

type AccountPrimer

type AccountPrimer struct {
	Enabled bool `json:"enabled"`
	// Model replaces the provider's ping model when set.
	Model string `json:"model,omitempty"`
	// Schedule replaces the pool schedule when set.
	Schedule *PrimerPolicy `json:"schedule,omitempty"`
}

AccountPrimer is one account's primer setup. Accounts are only primed once turned on.

func ParseAccountPrimer

func ParseAccountPrimer(raw string) AccountPrimer

type ErrAllCooling

type ErrAllCooling struct{ Until time.Time }

ErrAllCooling means every account is rate limited; Until is the soonest recovery.

func (*ErrAllCooling) Error

func (e *ErrAllCooling) Error() string

type ErrorRule

type ErrorRule struct {
	ID       string `json:"id"`
	Enabled  bool   `json:"enabled"`
	Provider string `json:"provider"` // "" any, "claude", "codex"
	Status   int    `json:"status"`   // 0 any
	// Match is a case-insensitive substring of the error body, or a regular expression when
	// written as /pattern/.
	Match           string `json:"match"`
	Action          string `json:"action"`
	Cooldown        string `json:"cooldown"`
	CooldownSeconds int    `json:"cooldownSeconds"`
	Note            string `json:"note"`
}

ErrorRule overrides how an upstream error is handled. Rules are checked in order; the first match wins, and unmatched errors fall back to the built-in classification.

func DefaultErrorRules

func DefaultErrorRules() []ErrorRule

DefaultErrorRules cover errors the client caused (don't punish the account) and capacity errors (move on quickly).

type Lease

type Lease struct {
	ID       int64
	Provider string
	Label    string
	Plan     string
	Creds    provider.Credentials
}

Lease is an account handed out for one request.

type Manager

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

func New

func New(st *store.Store, settings func() Settings, providers ...provider.Provider) *Manager

func (*Manager) Add

func (m *Manager) Add(ctx context.Context, providerID string, creds provider.Credentials, id provider.Identity) (*store.Account, error)

Add stores a freshly logged-in or imported account and fetches its quota in the background.

func (*Manager) Credentials

func (m *Manager) Credentials(ctx context.Context, id int64, force bool) (provider.Credentials, error)

Credentials returns usable credentials, refreshing them when close to expiry or when forced.

func (*Manager) Delete

func (m *Manager) Delete(ctx context.Context, id int64) error

func (*Manager) Get

func (m *Manager) Get(id int64) (View, bool)

func (*Manager) List

func (m *Manager) List() []View

func (*Manager) Load

func (m *Manager) Load(ctx context.Context) error

func (*Manager) MarkCooldown

func (m *Manager) MarkCooldown(ctx context.Context, id int64, until time.Time, msg string)

MarkCooldown takes an account out of rotation until the given time.

func (*Manager) MarkError

func (m *Manager) MarkError(ctx context.Context, id int64, until time.Time, msg string)

func (*Manager) MarkModelCooldown

func (m *Manager) MarkModelCooldown(id int64, model string, until time.Time)

MarkModelCooldown benches one model on one account, leaving its other models usable.

func (*Manager) MarkSuccess

func (m *Manager) MarkSuccess(ctx context.Context, id int64)

MarkSuccess clears any error state after a successful upstream call.

func (*Manager) ObserveQuota

func (m *Manager) ObserveQuota(ctx context.Context, id int64, windows []quota.Window, plan string)

ObserveQuota merges windows learned from response headers into the account's snapshot.

func (*Manager) Pick

func (m *Manager) Pick(ctx context.Context, providerID string, exclude map[int64]bool, opts PickOptions) (*Lease, error)

Pick chooses an account among the highest available priority tier, using the strategy.

func (*Manager) PrimeNow

func (m *Manager) PrimeNow(ctx context.Context, id int64) (store.PrimerRun, error)

PrimeNow pings an account right away, whatever its schedule, and reports what happened.

func (*Manager) QuotaInfos

func (m *Manager) QuotaInfos() []quota.AccountInfo

QuotaInfos feeds the public quota page.

func (*Manager) Redeem

func (m *Manager) Redeem(ctx context.Context, id int64, creditID string) (*provider.RedeemResult, error)

Redeem spends one banked reset.

func (*Manager) RefreshQuota

func (m *Manager) RefreshQuota(ctx context.Context, id int64) error

RefreshQuota polls the provider's usage endpoint for one account.

func (*Manager) RefreshSubscription

func (m *Manager) RefreshSubscription(ctx context.Context, id int64) error

RefreshSubscription updates what's known about an account's plan period.

func (*Manager) Reload

func (m *Manager) Reload(ctx context.Context, id int64) error

Reload re-reads an account row changed outside the manager.

func (*Manager) Run

func (m *Manager) Run(ctx context.Context)

Run keeps tokens fresh, polls quotas and handles auto-redeem until ctx ends.

func (*Manager) RunPrimer

func (m *Manager) RunPrimer(ctx context.Context)

RunPrimer starts accounts' session windows on their schedules until ctx ends.

func (*Manager) Unstick

func (m *Manager) Unstick(stickyKey, providerID string)

Unstick drops any affinity binding for a key so the next request picks fresh.

func (*Manager) Update

func (m *Manager) Update(ctx context.Context, id int64, p store.AccountPatch) (*store.Account, error)

func (*Manager) WakePrimer

func (m *Manager) WakePrimer()

WakePrimer re-plans right away, after settings or an account's rules change.

type PickOptions

type PickOptions struct {
	// Strategy: "round_robin" (default), "fill", "most_remaining" or "random".
	Strategy string
	// Accounts restricts the pool to these IDs; empty means every account of the provider.
	Accounts []int64
	// StickyKey keeps requests with the same key on the same account for StickyFor.
	StickyKey string
	StickyFor time.Duration
	// Model skips accounts where this model is cooling down.
	Model string
}

PickOptions shape account selection for one request.

type PrimerEffective

type PrimerEffective struct {
	PrimerPolicy
	Enabled bool   `json:"enabled"`
	Model   string `json:"model"`
	// Source is whose schedule applies: "account", "provider" or "shared".
	Source string `json:"source"`
}

PrimerEffective is what the primer does for one account.

type PrimerPlan

type PrimerPlan struct {
	At time.Time `json:"at"`
	// ReadyAt is when the session it starts will reset.
	ReadyAt time.Time `json:"readyAt"`
}

PrimerPlan is an account's next planned ping.

type PrimerPolicy

type PrimerPolicy struct {
	Schedules []PrimerSchedule `json:"schedules"`
	// DelaySeconds waits this long after the previous session ends before a ping that had to
	// wait for it, in case the provider's clock runs a little behind.
	DelaySeconds int `json:"delaySeconds"`
	// Verify checks that the session started after each ping and only retries when it didn't.
	// Off, every follow-up ping is sent regardless.
	Verify        bool `json:"verify"`
	VerifySeconds int  `json:"verifySeconds"`
	// Retries is how many follow-up pings may be sent, RetrySeconds apart.
	Retries      int `json:"retries"`
	RetrySeconds int `json:"retrySeconds"`
	// GraceMinutes still pings a planned slot this late, e.g. after a restart or while the
	// previous session runs out.
	GraceMinutes int `json:"graceMinutes"`
}

PrimerPolicy decides when maitake starts an account's session window on its own, by sending a tiny request while the window is idle. The pool settings hold the schedule accounts share, which a provider or a single account can replace with its own.

func DefaultPrimerPolicy

func DefaultPrimerPolicy() PrimerPolicy

func (*PrimerPolicy) Normalize

func (p *PrimerPolicy) Normalize()

type PrimerSchedule

type PrimerSchedule struct {
	// Times are local "HH:MM".
	Times []string `json:"times"`
	// Days are weekdays (0 = Sunday) of the times; empty means every day.
	Days []int `json:"days"`
	// Timezone reads the times in this IANA zone instead of the server's.
	Timezone string `json:"timezone,omitempty"`
}

PrimerSchedule is a set of times a fresh session should be ready, on some days. Each ping goes out one session length before its time.

type PrimerSettings

type PrimerSettings struct {
	Schedule PrimerPolicy `json:"schedule"`
	// Providers replace Schedule for one provider's accounts.
	Providers map[string]PrimerPolicy `json:"providers"`
	// Models are the ping model per provider; missing ones use DefaultPrimerModels. Claude takes
	// a line name like "haiku" for its newest model; Codex models may carry an effort suffix,
	// e.g. "gpt-5.6-luna(low)".
	Models map[string]string `json:"models"`
	Prompt string            `json:"prompt"`
}

PrimerSettings are the primer's pool-wide settings.

func DefaultPrimerSettings

func DefaultPrimerSettings() PrimerSettings

func (PrimerSettings) Effective

func (s PrimerSettings) Effective(providerID string, a AccountPrimer) PrimerEffective

Effective is the account's own setup filled in from the pool settings.

func (*PrimerSettings) Normalize

func (s *PrimerSettings) Normalize()

type RedeemOverride

type RedeemOverride struct {
	Enabled                *bool   `json:"enabled,omitempty"`
	Trigger                *string `json:"trigger,omitempty"`
	MinWaitMinutes         *int    `json:"minWaitMinutes,omitempty"`
	Reserve                *int    `json:"reserve,omitempty"`
	Order                  *string `json:"order,omitempty"`
	GapMinutes             *int    `json:"gapMinutes,omitempty"`
	MaxPerDay              *int    `json:"maxPerDay,omitempty"`
	ExpiringHours          *int    `json:"expiringHours,omitempty"`
	ExpiringMinUsedPercent *int    `json:"expiringMinUsedPercent,omitempty"`
}

RedeemOverride is an account's own redeem rules; nil fields use the pool default.

func ParseRedeemOverride

func ParseRedeemOverride(raw string) RedeemOverride

func (RedeemOverride) Apply

Apply layers the override on top of base.

type RedeemPolicy

type RedeemPolicy struct {
	Enabled bool `json:"enabled"`
	// Trigger is which limit being hit spends a reset: "any" (5-hour or weekly), "weekly" or "session".
	Trigger string `json:"trigger"`
	// MinWaitMinutes skips limits that reset sooner than this anyway.
	MinWaitMinutes int `json:"minWaitMinutes"`
	// Reserve keeps this many banked resets unspent by limit triggers.
	Reserve int `json:"reserve"`
	// Order picks which reset to spend: "soonest_expiry" or "latest_expiry".
	Order string `json:"order"`
	// GapMinutes is the least time between two automatic uses on one account.
	GapMinutes int `json:"gapMinutes"`
	// MaxPerDay caps automatic uses per account in 24 hours; 0 is unlimited.
	MaxPerDay int `json:"maxPerDay"`
	// ExpiringHours spends a reset that expires within this many hours (0 = off), so it isn't
	// lost, once the account has used at least ExpiringMinUsedPercent of a limit.
	ExpiringHours          int `json:"expiringHours"`
	ExpiringMinUsedPercent int `json:"expiringMinUsedPercent"`
}

RedeemPolicy decides when a Codex account spends its banked resets on its own. The pool settings hold the default; each account can override any field.

func DefaultRedeemPolicy

func DefaultRedeemPolicy() RedeemPolicy

func (*RedeemPolicy) Normalize

func (p *RedeemPolicy) Normalize()

type Settings

type Settings struct {
	QuotaPollMinutes int `json:"quotaPollMinutes"`
	// AutoRedeemMinWaitMinutes is the pre-RedeemPolicy setting, read once into Redeem.
	AutoRedeemMinWaitMinutes int `json:"autoRedeemMinWaitMinutes,omitempty"`
	// Redeem is the default banked reset policy. Only Codex accounts spend resets automatically.
	Redeem     RedeemPolicy `json:"redeem"`
	MaxRetries int          `json:"maxRetries"`
	// BootstrapSeconds is how long to hold a stream's opening events, so an error that arrives
	// inside a 200 response can still move to another account before the client sees anything.
	BootstrapSeconds int `json:"bootstrapSeconds"`
	// KeepaliveSeconds sends an SSE comment when the upstream is quiet that long (0 = off).
	KeepaliveSeconds int         `json:"keepaliveSeconds"`
	ErrorRules       []ErrorRule `json:"errorRules"`
	// Primer starts session windows on a schedule.
	Primer PrimerSettings `json:"primer"`
}

Settings are the admin-tunable knobs for the pool.

func DefaultSettings

func DefaultSettings() Settings

func (Settings) MatchErrorRule

func (s Settings) MatchErrorRule(provider string, status int, body string) *ErrorRule

MatchErrorRule returns the first rule that applies to an error, if any.

func (*Settings) Normalize

func (s *Settings) Normalize()

type View

type View struct {
	store.Account
	Quota          *quota.Snapshot        `json:"quota"`
	Subscription   *provider.Subscription `json:"subscription"`
	ModelCooldowns map[string]time.Time   `json:"modelCooldowns,omitempty"`
	// Redeem is the account's own banked reset rules; RedeemEffective adds the pool defaults.
	Redeem          RedeemOverride `json:"redeem"`
	RedeemEffective RedeemPolicy   `json:"redeemEffective"`
	// Primer is the account's own session primer setup; PrimerEffective fills in the pool's.
	Primer          AccountPrimer    `json:"primer"`
	PrimerEffective PrimerEffective  `json:"primerEffective"`
	PrimerNext      *PrimerPlan      `json:"primerNext"`
	PrimerLast      *store.PrimerRun `json:"primerLast"`
	PrimerBusy      bool             `json:"primerBusy"`
	TokenExpiresAt  *time.Time       `json:"tokenExpiresAt"`
	LastRefresh     *time.Time       `json:"lastRefresh"`
}

View is an account as shown in the admin dashboard.

Jump to

Keyboard shortcuts

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