accounts

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: MIT Imports: 31 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 store.AccountKey) (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 AccountKeyFor added in v0.1.10

func AccountKeyFor(provider Provider, email string) store.AccountKey

AccountKeyFor names a subscription account by its provider and email, such as "chatgpt:you@example.com". One email can hold both a ChatGPT and a Claude subscription, so the provider is part of the key.

func AllowancePeriodLabel

func AllowancePeriodLabel(seconds int64) string

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

func AutomaticResetsOn added in v0.1.11

func AutomaticResetsOn(directory string) (bool, error)

AutomaticResetsOn reports whether this installation's proxy spends reset credits by itself. They are off unless turned on.

func ClaudeAvailableAgain added in v0.1.7

func ClaudeAvailableAgain(fact AccountRoutingFact, model string, now time.Time) (availableAt time.Time, limitClaim string, found bool)

ClaudeAvailableAgain is when the account's reserve and Claude limits next allow model work, and Anthropic's name for the limit that ends then. found is false when no known reset frees the account.

func ClaudeModelFamily

func ClaudeModelFamily(model string) string

func ClaudeRejectionNamesUsageLimit added in v0.1.7

func ClaudeRejectionNamesUsageLimit(headers http.Header) bool

ClaudeRejectionNamesUsageLimit is whether a 429 names a usage limit, by the rule restrictClaudeAccountAfterRejection applies: a representative claim for a window, or a window Anthropic reports at its limit.

func ClaudeUnavailableReason

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

func IncludedAllowanceLeft added in v0.1.11

func IncludedAllowanceLeft(sample AllowanceSample, now time.Time) bool

IncludedAllowanceLeft reports whether a Codex account can work on the allowance its plan includes: OpenAI allows it, and no window shared by all models is used up. While an account holds usage credits, OpenAI still reports it allowed once that allowance is used up, and draws the credits.

func RecordAccountKeys added in v0.1.10

func RecordAccountKeys(dataDirectory string, database *store.StoreDatabase) (int64, error)

RecordAccountKeys records which folder holds which account, gives accounts recorded by earlier builds their key, and sets each record's key to the key of its folder: earlier builds write records with only a folder name, and move a task's pin to another folder without changing its key. It returns how many records it changed. The proxy runs it whenever it reads the pool: an earlier build may write while an update switches proxies, or after a rollback.

func ReserveStatus

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

func ReserveUnavailableReason

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

ReserveUnavailableReason applies to the account's overall allowance windows (5-hour and weekly), not model-specific sub-limits such as Fable. Expired windows no longer hold the account back.

func SetAutomaticResets added in v0.1.11

func SetAutomaticResets(directory string, on bool) error

SetAutomaticResets turns automatic resets on or off for this installation. The running proxy follows within one account read.

func SoftReserveReached

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

func StoredResetLabel added in v0.1.11

func StoredResetLabel(kind ResetKind, count uint32) string

StoredResetLabel names resets the way status, the proxy log and the menu do: "1 weekly reset", "3 Fable resets", or "2 resets" for a kind the provider names in no way this build knows.

Types

type AccountReserve

type AccountReserve struct {
	SoftPercent int
	HardPercent int
}

type AccountRoutingFact

type AccountRoutingFact struct {
	Provider                  Provider
	ClaudeRestrictions        map[string]ClaudeRestriction
	AccountKey                store.AccountKey
	DisplayName               string
	Reserve                   AccountReserve
	Credentials               Credentials
	AccountState              AccountState
	AccountStateCause         error
	AllowanceSample           AllowanceSample
	CreditBalanceBlockedUntil time.Time
	ResetCredits              []ResetCredit
	ResetCreditsReadAt        time.Time
	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
	// StoredResets are the resets Anthropic listed for a Claude account at
	// StoredResetsReadAt, which is zero until it has answered. A Codex
	// account's are its reset credits, on AccountRoutingFact.
	StoredResets       []StoredReset
	StoredResetsReadAt time.Time
	// NoResetsReason is Anthropic's reason for listing a Claude account no
	// resets, such as no_grant, or cli_version when it lists them only for a
	// newer Claude Code than the proxy read as. It is empty when Anthropic
	// lists the account's resets.
	NoResetsReason string
	// CreditBalance is the account's usage credit balance; nil when OpenAI
	// reports none.
	CreditBalance *float64
	Windows       []ReportedWindow
}

type AllowanceWindow

type AllowanceWindow struct {
	FreePercent float64
	ResetsAt    time.Time
	// NotStarted means OpenAI has not started the window: it starts at the
	// account's first request after a reset, and until then OpenAI reports
	// nothing used and a reset one full window from the reading.
	NotStarted bool
}

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.

func ClaudeWeeklyAllowance added in v0.1.8

func ClaudeWeeklyAllowance(fact AccountRoutingFact, model string, now time.Time) (AllowanceWindow, bool)

ClaudeWeeklyAllowance is the free share of the tightest weekly window that applies to model, and the earliest reset among those windows. Anthropic's weekly windows reset at fixed times, so they always count as started.

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
	// Claim is Anthropic's representative claim on the 429, such as five_hour.
	Claim string `json:",omitempty"`
	// Throttle is a 429 that named no usage limit.
	Throttle bool `json:",omitempty"`
}

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(accountKey store.AccountKey, 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) ObserveClaudeClient added in v0.1.11

func (monitor *Monitor) ObserveClaudeClient(userAgent string)

ObserveClaudeClient notes the client that sent a Claude request. The proxy reads usage as the newest Claude Code it has served, so a Claude Code upgrade keeps the reads current without a Codex Switch release.

func (*Monitor) ObserveClaudeResponse

func (monitor *Monitor) ObserveClaudeResponse(key store.AccountKey, 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(accountKey store.AccountKey, rejected Credentials) error

RefreshAccountCredentialsAfterUnauthorized prepares the account for the next routed request.

func (*Monitor) ReportCodexWorkWaiting added in v0.1.11

func (monitor *Monitor) ReportCodexWorkWaiting()

ReportCodexWorkWaiting tells the monitor that Codex model work is waiting because routing found no account for it.

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) ResetCreditComesFirst added in v0.1.11

func (monitor *Monitor) ResetCreditComesFirst() bool

ResetCreditComesFirst reports whether a reset credit is about to be spent, so no account may draw its usage credits yet: reset credits expire sooner. That is when a spend from this installation awaits its outcome or OpenAI's reading of it, or when automatic resets are on here and the latest readings show the pool out with a credit to spend; see choosePoolOutCredit. It reads no network, so routing can ask it.

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) RunAutomaticResets added in v0.1.11

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

RunAutomaticResets spends a reset credit by the rule in chooseResetCredit until ctx ends, while automatic resets are on. It looks once per account read, and at once when work starts waiting. It asks OpenAI only when the latest readings show a need: work waiting for an account, or a credit in its last hour. The decision itself is made from a fresh read of every account.

func (*Monitor) SetAccountReadInterval added in v0.1.7

func (monitor *Monitor) SetAccountReadInterval(interval time.Duration)

SetAccountReadInterval changes how often each account is read, before Run starts.

func (*Monitor) SetClaudeTokenOrigin added in v0.1.11

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

SetClaudeTokenOrigin changes where Claude logins are refreshed, before Run starts.

func (*Monitor) SetClaudeUpstreamOrigin

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

SetClaudeUpstreamOrigin changes the Claude origin before Run starts.

func (*Monitor) SetClaudeUsageReadInterval added in v0.1.11

func (monitor *Monitor) SetClaudeUsageReadInterval(interval time.Duration)

SetClaudeUsageReadInterval changes how often each Claude account's usage is read, 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, origin *url.URL, client *http.Client) *OpenAIDailyTokenSource

NewOpenAIDailyTokenSource reads from origin, which is chatgpt.com except in the system test.

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
	// Key identifies the account on every Mac; see AccountKeyFor.
	Key store.AccountKey
	// Folder is where its login is saved, such as account-3, and Index its
	// number. Folders are numbered in sign-in order on each Mac.
	Folder         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
	// SignInEndsAt is when a Claude sign-in ends and the account must sign in
	// again; zero when Anthropic has not said.
	SignInEndsAt time.Time
}

PoolAccount is one signed-in subscription account. Pool accounts live in account-N folders 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 folder number. A missing data directory is an empty pool.

func ReadPoolAccount

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

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

func RemoveAccount

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

RemoveAccount takes the account named by its display name or key 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, target string, reserve AccountReserve) (PoolAccount, error)

SetAccountReserve changes placement and cutover thresholds without a restart.

func SignIn

func SignIn(dataDirectory, codexExecutable string, replacing store.AccountKey) (PoolAccount, error)

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

func SignInClaude

func SignInClaude(dataDirectory string, replacing store.AccountKey) (PoolAccount, error)

SignInClaude obtains an independent rotating login; it never borrows another client's refresh token. With replacing set, it replaces that account's login.

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
}

type ResetCredit added in v0.1.8

type ResetCredit struct {
	ID        string    `json:"id"`
	Status    string    `json:"status"`
	ResetType string    `json:"reset_type"`
	ExpiresAt time.Time `json:"expires_at"`
}

ResetCredit is a credit as OpenAI lists it. OpenAI may list a credit without an expiry, which never expires: its ExpiresAt is zero.

type ResetDecision added in v0.1.8

type ResetDecision struct {
	Message string
	Spent   bool
}

ResetDecision is what a reset request did, in words for the person or the proxy log. Spent is true when OpenAI confirmed that a credit this installation asked for was spent.

func ResetCodexPool added in v0.1.8

func ResetCodexPool(ctx context.Context, directory string, origin *url.URL, client *http.Client) (ResetDecision, error)

ResetCodexPool spends one credit when the Codex pool is out; see chooseResetCredit.

type ResetKind added in v0.1.11

type ResetKind string

ResetKind is what a stored reset gives back when it is spent.

const (
	// ResetWeekly gives back the weekly allowance for every model.
	ResetWeekly ResetKind = "weekly"
	// ResetFiveHour gives back the five-hour allowance.
	ResetFiveHour ResetKind = "five-hour"
	// ResetFull gives back the five-hour and weekly allowances.
	ResetFull ResetKind = "full"
	// ResetFable gives back what Fable models used of the week: the Fable
	// allowance is full again and the weekly allowance regains that share.
	// The week keeps its reset time.
	ResetFable ResetKind = "Fable"
)

type StoredReset added in v0.1.11

type StoredReset struct {
	Kind  ResetKind
	Count uint32
	// ExpiresAt is zero when the provider states no expiry.
	ExpiresAt time.Time
}

StoredReset is the resets of one kind that an account holds and that expire together.

func HeldResets added in v0.1.11

func HeldResets(fact AccountRoutingFact, now time.Time) (count *uint32, list []StoredReset)

HeldResets is the resets an account holds at now: how many, and the list of them, soonest expiry first, when the provider's list is known. The count is nil when the provider has not said.

Anthropic gives a Claude account's list and nothing else, so the count is the list's. OpenAI gives a Codex account's count with each usage reading, and its list of reset credits is read apart, every five minutes. While the two disagree the list is the older, and only the count is given.

Jump to

Keyboard shortcuts

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