accounts

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2026 License: MIT Imports: 26 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 owns subscription sign-in, pool membership, credentials, and the account information reported by OpenAI and Anthropic. The relay forwards client work; this package makes the proxy's own account reads.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccountDisplayName

func AccountDisplayName(pool []PoolAccount, key string) (string, int)

AccountDisplayName derives a name and provider-local number from pool order. A key outside the current pool belongs to a removed account.

func AllowancePeriodLabel

func AllowancePeriodLabel(seconds int64) string

AllowancePeriodLabel names an allowance window the way the proxy log and the status command show it.

func ClaudeModelFamily

func ClaudeModelFamily(model string) string

func ClaudeUnavailableReason

func ClaudeUnavailableReason(fact AccountRoutingFact, model string, now time.Time) (string, time.Time)

func ClaudeWeeklyAllowanceLeft

func ClaudeWeeklyAllowanceLeft(fact AccountRoutingFact, model string, now time.Time) (float64, bool)

func ReserveStatus

func ReserveStatus(fact AccountRoutingFact, now time.Time) string

func ReserveUnavailableReason

func ReserveUnavailableReason(fact AccountRoutingFact, now time.Time) string

ReserveUnavailableReason applies to the whole account, including windows specific to another model. Expired windows no longer hold the account back.

func SoftReserveReached

func SoftReserveReached(fact AccountRoutingFact, now time.Time) bool

Types

type AccountReserve

type AccountReserve struct {
	SoftPercent int
	HardPercent int
}

type AccountRoutingFact

type AccountRoutingFact struct {
	Provider           Provider
	ClaudeRestrictions map[string]ClaudeRestriction
	AccountName        store.AccountName
	DisplayName        string
	Reserve            AccountReserve
	Credentials        Credentials
	AccountState       AccountState
	AccountStateCause  error
	AllowanceSample    AllowanceSample
	RefreshedAt        time.Time
	// Nil means the catalogue has not been observed; an empty slice means no models.
	SupportedModelSlugs []string
	// ModelListCause is why the latest model-list read failed; nil after a successful read.
	ModelListCause error
}

AccountRoutingFact keeps provider eligibility and its matching credentials in one selection unit.

type AccountState

type AccountState string
const (
	AccountReady                  AccountState = "ready"
	AccountUsageCheckPending      AccountState = "usage-check-pending"
	AccountSignInRequired         AccountState = "sign-in-required"
	AccountCredentialsUnavailable AccountState = "credentials-unavailable"
	AccountLimited                AccountState = "limited"
	AccountUsageCheckFailed       AccountState = "usage-check-failed"
)

func (AccountState) Eligible

func (s AccountState) Eligible() bool

type AllowanceSample

type AllowanceSample struct {
	AccountID             string
	Plan                  string
	Allowed               bool
	LimitReached          bool
	ObservedAt            time.Time
	AvailableResetCredits *uint32
	Windows               []ReportedWindow
}

type AllowanceWindow

type AllowanceWindow struct {
	FreePercent float64
	ResetsAt    time.Time
}

AllowanceWindow is one provider-reported allowance window that is current at the time it was analysed.

func AnalyseAllowance

func AnalyseAllowance(sample AllowanceSample, state AccountState, asOf time.Time, kind AllowanceWindowKind) (AllowanceWindow, bool)

AnalyseAllowance returns the current window of one kind from a provider sample, without inferring any future usage. It reports false when the account state, the sample or the window gives no trustworthy reading.

type AllowanceWindowKind

type AllowanceWindowKind string

AllowanceWindowKind identifies an OpenAI allowance by its provider-reported duration. The primary and secondary positions are not stable product identities.

const (
	FiveHours AllowanceWindowKind = "5-hour"
	Weekly    AllowanceWindowKind = "weekly"
)

func (AllowanceWindowKind) Duration

func (k AllowanceWindowKind) Duration() time.Duration

type ClaudeRestriction

type ClaudeRestriction struct {
	ResetsAt   time.Time
	ObservedAt time.Time
}

type Credentials

type Credentials struct {
	AccessToken string
	AccountID   string
}

type Monitor

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

Monitor watches every account in the pool: its credentials, provider-reported allowances and model availability. Routing reads the latest facts without waiting on the network.

func NewMonitor

func NewMonitor(dataDirectory string, upstreamOrigin *url.URL, codexExecutable string, httpClient *http.Client, storeDatabase *store.StoreDatabase) *Monitor

NewMonitor reads accounts from upstreamOrigin, asking for the model catalogue that codexExecutable's version of Codex would see.

func (*Monitor) CheckProviderAccess

func (monitor *Monitor) CheckProviderAccess(ctx context.Context) error

CheckProviderAccess reads each signed-in account's allowance from the provider. Deployment calls this before listening; cached allowances cannot admit a new generation.

func (*Monitor) ExcludeUnsupportedAccountModel

func (monitor *Monitor) ExcludeUnsupportedAccountModel(accountName store.AccountName, modelSlug string)

ExcludeUnsupportedAccountModel records that OpenAI rejected modelSlug for the account before admitting work. An in-flight catalogue read cannot overwrite this newer observation.

func (*Monitor) ObserveClaudeResponse

func (monitor *Monitor) ObserveClaudeResponse(name store.AccountName, model string, headers http.Header, status int)

ObserveClaudeResponse retains all reported windows, including a model bucket absent from the next side request. Account state uses shared windows only.

func (*Monitor) ReadAccountRoutingFacts

func (monitor *Monitor) ReadAccountRoutingFacts() ([]AccountRoutingFact, error)

ReadAccountRoutingFacts joins the latest facts to current pool membership. Removed or replaced accounts cannot admit new work before their next read.

func (*Monitor) RefreshAccountCredentialsAfterUnauthorized

func (monitor *Monitor) RefreshAccountCredentialsAfterUnauthorized(accountName store.AccountName, rejected Credentials) error

RefreshAccountCredentialsAfterUnauthorized prepares the account for the next routed request.

func (*Monitor) RequestAccountRoutingFactsRefresh

func (monitor *Monitor) RequestAccountRoutingFactsRefresh()

RequestAccountRoutingFactsRefresh asks for every account to be read again soon, because work is waiting for capacity.

func (*Monitor) Run

func (monitor *Monitor) Run(ctx context.Context)

Run discovers accounts and reads them until ctx ends. Each account is read independently, so a slow account never delays another, and discovery goes on while the first reads finish.

func (*Monitor) SetClaudeUpstreamOrigin

func (monitor *Monitor) SetClaudeUpstreamOrigin(origin *url.URL)

SetClaudeUpstreamOrigin changes the Claude origin before Run starts.

func (*Monitor) WaitForFirstRead

func (monitor *Monitor) WaitForFirstRead()

WaitForFirstRead returns once every account has been read once, successfully or not.

type OpenAIDailyTokenBucket

type OpenAIDailyTokenBucket struct {
	StartDate string
	Tokens    int64
}

type OpenAIDailyTokenHistory

type OpenAIDailyTokenHistory struct {
	AccountID      string
	ReadStartedAt  time.Time
	ReportingDate  time.Time
	GeneratedAt    time.Time
	LifetimeTokens int64
	Buckets        []OpenAIDailyTokenBucket
}

OpenAIDailyTokenHistory is an account-scoped OpenAI profile snapshot. OpenAI supplies the reporting date independently of the local read time.

type OpenAIDailyTokenSource

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

func NewOpenAIDailyTokenSource

func NewOpenAIDailyTokenSource(home string, client *http.Client) *OpenAIDailyTokenSource

func (*OpenAIDailyTokenSource) Read

func (*OpenAIDailyTokenSource) ReadDailyModelCredits

func (s *OpenAIDailyTokenSource) ReadDailyModelCredits(ctx context.Context, firstDate, lastDate time.Time) (string, []OpenAIModelDayCredits, error)

ReadDailyModelCredits reads the per-model, per-speed credits for the UTC dates firstDate through lastDate. OpenAI fills in a day one to two days after it ends; until then the day is empty.

type OpenAIModelDayCredits

type OpenAIModelDayCredits struct {
	Date                string
	Model               string
	Fast                bool
	PercentOfBusiestDay float64
}

OpenAIModelDayCredits is the Codex credits one model at one speed used on one UTC day, as a percentage of the busiest day in the same read. OpenAI counts every client and machine, ChatGPT Work on the web included. The unit holds only within one read: OpenAI scales each response so that its busiest day totals 100, so a read starting on 1 September and one starting on 12 September give the same day different values.

type PoolAccount

type PoolAccount struct {
	Provider       Provider
	OrganizationID string
	Plan           string
	// Name is the directory name, such as account-3, and Index its number.
	Name           string
	Index          int
	DisplayName    string
	ProviderNumber int
	Reserve        AccountReserve
	// ID identifies the subscription user within its provider.
	ID string
	// AccountID is the immutable subscription identity. For ChatGPT it is sent
	// as ChatGPT-Account-ID; for Claude it joins the account and organization IDs.
	AccountID string
	Email     string
}

PoolAccount is one signed-in subscription account. Pool accounts live in account-N directories in the data directory, each holding an auth.json.

func ReadPool

func ReadPool(dataDirectory string) ([]PoolAccount, error)

ReadPool returns every signed-in account in dataDirectory, ordered by account number. A missing data directory is an empty pool.

func ReadPoolAccount

func ReadPoolAccount(accountDirectory, name string, index int) (PoolAccount, error)

ReadPoolAccount reads the provider identity from the auth.json in accountDirectory.

func RemoveAccount

func RemoveAccount(dataDirectory, accountName string) (PoolAccount, int64, error)

RemoveAccount takes the account out of the pool, forgets its task pins and moves its saved login to the Trash. It returns the removed account and how many task pins it had.

func SetAccountReserve

func SetAccountReserve(dataDirectory, accountName string, reserve AccountReserve) (PoolAccount, error)

SetAccountReserve changes placement and cutover thresholds without a restart.

func SignIn

func SignIn(dataDirectory, codexExecutable, accountName string) (PoolAccount, error)

SignIn runs Codex's browser login into a staging directory, then adds the signed-in account to the pool. With accountName set, it replaces that account's login instead, and only if the browser signed in to the same user.

func SignInClaude

func SignInClaude(dataDirectory, accountName string) (PoolAccount, error)

SignInClaude obtains an independent rotating login; it never borrows another client's refresh token.

type Provider

type Provider string
const (
	ProviderCodex   Provider = ""
	ProviderChatGPT Provider = ProviderCodex
	ProviderClaude  Provider = "claude"
)

type ReportedWindow

type ReportedWindow struct {
	ObservedAt      time.Time
	LimitReached    bool
	ModelID         string
	ModelName       string
	UsedPercent     float64
	DurationSeconds int64
	ResetsAt        time.Time
}

Jump to

Keyboard shortcuts

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