limits

package
v2.6.2 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 16 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 limits makes Lectern usage-limit aware: it recognises when an agent CLI has been stopped by its provider's usage limit, records a hold with the reset time, and applies the session's or project's policy — notify, wait and resume at the reset, or hand the work to another agent. See docs/rate-limits.md.

Index

Constants

View Source
const (
	// ModeNotify pushes a notification with one-tap choices and does nothing
	// else. It is the default: typing into someone's session unasked, or
	// starting a different agent, is an opt-in.
	ModeNotify = "notify"
	// ModeWait resumes the same agent once its limit resets (a task is
	// requeued for then).
	ModeWait = "wait"
	// ModeHandoff hands the work to the configured fallback agent now.
	ModeHandoff = "handoff"
	// ModeSwap moves the same conversation to another signed-in account of
	// the same CLI (docs/accounts.md). When every account is limited, Then
	// applies instead.
	ModeSwap = "swap"
)

What to do when a limit is hit.

View Source
const (
	ScopeGlobal  = "global"
	ScopeProject = "project"
	ScopeSession = "session"
)

Scopes, narrowest last. The narrowest one with a stored policy wins.

View Source
const (
	StateSwapping = "swapping"
	StateSwapped  = "swapped"
)

StateSwapping is an open hold whose agent is being restarted under another account. StateSwapped resolves a task hold whose continuation was queued under another account.

View Source
const (
	StateWaiting    = "waiting"
	StateResuming   = "resuming"
	StateHandingOff = "handing_off"

	StateResumed      = "resumed"
	StateCleared      = "cleared"
	StateHandedOff    = "handed_off"
	StateRequeued     = "requeued"
	StateRedispatched = "redispatched"
	StateGaveUp       = "gave_up"
	StateDismissed    = "dismissed"
)

Hold states. waiting, resuming and handing_off are open; the rest are written together with resolved_at.

View Source
const (
	NudgeText   = "Your usage limit has reset. Please continue where you left off."
	NudgeMarker = "continue where you left off"
)

NudgeText is what Lectern types into a session once its limit has reset. NudgeMarker, a distinctive part of it that fits on one terminal row, is how the verifier finds the nudge in the pane and reads only what came after it.

View Source
const (
	ActionWait      = "wait"
	ActionResumeNow = "resume_now"
	ActionHandoff   = "handoff"
	ActionNotify    = "notify"
	ActionDismiss   = "dismiss"
)

Actions an operator can take on a hold from the card or the push.

View Source
const ActionSwap = "swap"

ActionSwap moves the work to another account now.

View Source
const TailLines = 15

TailLines is how much of the bottom of a pane counts as "what the agent is showing now".

Variables

View Source
var DefaultTiming = Timing{
	Grace: 45 * time.Second, Jitter: 90 * time.Second,
	Backoff: 10 * time.Minute, MaxBackoff: 2 * time.Hour,
	Settle: 90 * time.Second, MaxTries: 4, Stale: 10 * time.Minute,
}

DefaultTiming is the production schedule.

View Source
var ErrAgentExited = errors.New("the agent exited")

ErrAgentExited is a swap whose agent quit right after restarting under the new account (it could not find the conversation, or was not signed in).

View Source
var ErrConflict = errors.New("this limit is already being handled")

ErrConflict means the hold is no longer in a state the action applies to.

View Source
var ErrNoAccount = errors.New("no other account is available")

ErrNoAccount means every other account of the CLI is limited, or there is no other account.

View Source
var Table = []Pattern{
	{
		Name: "claude-auto-continue", Agent: "claude", SelfResume: true,
		Re:     regexp.MustCompile(`^Usage limit reached\s*[·•∙]\s*continuing (automatically|shortly)`),
		Source: "Claude Code 2.1.283 bundle: the rate-limit wait banner (\"Usage limit reached · continuing automatically at …\")",
		Samples: []string{
			"Usage limit reached · continuing automatically at 3:40pm · esc to cancel",
			"Usage limit reached · continuing automatically when it resets · esc to cancel",
			"Usage limit reached · continuing shortly · esc to cancel",
		},
	},
	{
		Name: "claude-limit", Agent: "claude",

		Re:     regexp.MustCompile(`^You(?:'|’)ve hit your ((?:session|weekly|Opus|Sonnet|Fable|org's monthly (?:spend|usage)|monthly spend|usage credit|usage) )?limit(?:\s*[·•∙]|$)`),
		Source: "Claude Code 2.1.283 bundle: rate-limit error text (\"You've hit your ${limit} · resets ${time}\"; reset time rendered as 3pm, 3:40pm or Oct 3, 9am, with the IANA zone in parentheses)",
		Samples: []string{
			"You've hit your session limit · resets 3:40pm (America/Chicago)",
			"You've hit your weekly limit · resets Oct 3, 9am (America/Chicago)",
			"You've hit your limit · resets 11pm (UTC)",
			"You've hit your Opus limit · resets Oct 3, 9:30am (Europe/Berlin)",
			"You've hit your session limit · resets 3pm (UTC) · progress saved",
		},
	},
	{
		Name: "claude-out-of-credits", Agent: "claude",
		Re:      regexp.MustCompile(`^You(?:'|’)re out of usage credits(?:\s*[·•∙]|$)`),
		Source:  "Claude Code 2.1.283 bundle: overage-rejected error text",
		Samples: []string{"You're out of usage credits · resets Oct 3, 9am (UTC)"},
	},
	{
		Name: "claude-legacy", Agent: "claude",
		Re:      regexp.MustCompile(`^Claude AI usage limit reached\|(\d{9,11})`),
		Source:  "Claude Code 1.x print-mode result text (\"Claude AI usage limit reached|<unix reset>\")",
		Samples: []string{"Claude AI usage limit reached|1790200800"},
	},
	{
		Name: "codex-usage-limit", Agent: "codex",
		Re:     regexp.MustCompile(`^You(?:'|’)ve hit your usage limit(?: for [^.]+)?\.`),
		Source: "codex 0.157.0 binary / codex-rs core error.rs UsageLimitReachedError (\" Try again at %-I:%M %p\" today, \"%b %-d<suffix>, %Y %-I:%M %p\" otherwise)",
		Samples: []string{
			"You've hit your usage limit. Try again at 3:40 PM.",
			"You've hit your usage limit. Upgrade to Plus to continue using Codex (https://chatgpt.com/explore/plus), or try again at Oct 3rd, 2026 9:05 AM.",
			"You've hit your usage limit. Visit https://chatgpt.com/codex/settings/usage to purchase more credits or try again at 11:15 AM.",
			"You've hit your usage limit. Try again in 2 days 3 hours 4 minutes.",
			"You've hit your usage limit. Try again later.",
		},
	},
	{
		Name: "gemini-usage-limit", Agent: "gemini",
		Re:     regexp.MustCompile(`^Usage limit reached for [\w.\-]+\.`),
		Source: "gemini-cli 0.61.0 interactiveCli bundle: TerminalQuotaError message (\"Usage limit reached for ${model}.\" then \"Access resets at ${h:mm AM zone}.\")",
		Samples: []string{
			"Usage limit reached for gemini-2.5-pro.\nAccess resets at 3:40 PM PST.\n/stats model for usage details",
			"Usage limit reached for gemini-2.5-flash.",
		},
	},
	{
		Name: "gemini-quota-exhausted", Agent: "gemini",
		Re:     regexp.MustCompile(`^You have exhausted your (capacity|daily quota) on this model\.`),
		Source: "gemini-cli-core 0.61.0 googleQuotaErrors.js and its tests (the Code Assist API's own message)",
		Samples: []string{
			"You have exhausted your capacity on this model. Your quota will reset after 19h14m47s.",
			"You have exhausted your capacity on this model. Your quota will reset after 10m.",
			"You have exhausted your daily quota on this model.",
		},
	},

	{
		Name: "grok-usage-limit", Agent: "grok",
		Re:      regexp.MustCompile(`^You hit your (?:free usage|weekly) limit\.`),
		Source:  "grok 1.0.41 binary: status-402 upsell strings",
		Samples: []string{"You hit your free usage limit.", "You hit your weekly limit."},
	},
	{
		Name: "grok-plan-limit", Agent: "grok",
		Re:     regexp.MustCompile(`^You(?:'|’)ve (?:hit the (?:rate|credit) limit for your plan|hit your spending cap|reached your free Grok Build usage limit for now)\.`),
		Source: "grok 1.0.41 binary: plan limit strings (the credit, spending-cap and free-usage ones use a typographic apostrophe)",
		Samples: []string{
			"You've hit the rate limit for your plan.",
			"You’ve hit the credit limit for your plan.",
			"You’ve hit your spending cap.",
			"You’ve reached your free Grok Build usage limit for now. Get SuperGrok for much higher limits, or try again later: https://grok.com/supergrok?referrer=grok-build",
		},
	},
	{
		Name: "devin-quota-exhausted", Agent: "devin",
		Re:      regexp.MustCompile(`^Purchase on-demand usage or turn on auto-reload, or wait for your quota to reset\.`),
		Source:  "devin 3000.11.3 binary: the \"Quota exhausted\" notice body",
		Samples: []string{"Purchase on-demand usage or turn on auto-reload, or wait for your quota to reset."},
	},
	{
		Name: "droid-standard-limit", Agent: "droid",
		Re:     regexp.MustCompile(`^Standard Usage limit reached\. Select an option below to continue using Droid\.`),
		Source: "droid 0.228.0 binary: limit picker text (\"Standard resets <date>.\" follows when the reset date is known)",
		Samples: []string{
			"Standard Usage limit reached. Select an option below to continue using Droid.",
			"Standard Usage limit reached. Select an option below to continue using Droid. Standard resets Oct 3.",
		},
	},
	{
		Name: "droid-provider-quota", Agent: "droid",
		Re:     regexp.MustCompile(`^Your model provider(?:'|’)s usage quota is exhausted\.`),
		Source: "droid 0.228.0 binary: BYOK quota error (resetAt filled by droid)",
		Samples: []string{
			"Your model provider's usage quota is exhausted. Wait for the reset, raise the limit with your provider, or switch to another model with `/model`.",
			"Your model provider's usage quota is exhausted. Limits reset at 3:40 PM. Wait for the reset, raise the limit with your provider, or switch to another model with `/model`.",
		},
	},
	{
		Name: "droid-org-limit", Agent: "droid",
		Re:      regexp.MustCompile(`^Your organization(?:'|’)s usage limit was reached\. Runs resume automatically once the limit resets\.`),
		Source:  "droid 0.228.0 binary",
		Samples: []string{"Your organization's usage limit was reached. Runs resume automatically once the limit resets."},
	},
	{
		Name: "kiro-monthly-limit", Agent: "kiro",
		Re:      regexp.MustCompile(`^The monthly usage limit has been reached`),
		Source:  "kiro-cli-chat 2.24.1 binary: error message table",
		Samples: []string{"The monthly usage limit has been reached"},
	},
	{
		Name: "qwen-quota-exhausted", Agent: "qwen",
		Re:      regexp.MustCompile(`^Please retry after the reset time, or switch to another API key / auth method\.`),
		Source:  "qwen 0.24.6 formatQuotaExhaustedMessage: \"Quota exhausted: <provider message>\" then this fixed line; the provider message in the sample is illustrative",
		Samples: []string{"Quota exhausted: free tier quota exceeded, will reset at 00:00 UTC\n\nPlease retry after the reset time, or switch to another API key / auth method."},
	},
	{
		Name: "opencode-quota-exceeded", Agent: "opencode",
		Re:      regexp.MustCompile(`^Quota exceeded\. Check your plan and billing details\.`),
		Source:  "opencode 1.18.32, kilo 7.8.1 and mimo 0.1.15 binaries (shared OpenCode error text)",
		Samples: []string{"Quota exceeded. Check your plan and billing details."},
	},
	{
		Name: "codebuff-out-of-credits", Agent: "codebuff",
		Re:      regexp.MustCompile(`^Out of credits\. Please add credits at \S+/usage`),
		Source:  "codebuff 1.0.688 binary (~/.config/manicode/codebuff): `Out of credits. Please add credits at ${appUrl}/usage`, appUrl defaulting to https://codebuff.com",
		Samples: []string{"Out of credits. Please add credits at https://codebuff.com/usage"},
	},
	{
		Name: "autohand-plan-limit", Agent: "autohand",
		Re:     regexp.MustCompile(`^You(?:'|’)ve reached your (?:\S+ )?plan limit\. Run /upgrade`),
		Source: "autohand-cli 0.9.8 dist: \"You've reached your {{plan}} plan limit. Run /upgrade to move to {{next}}.\" (placeholders filled)",
		Samples: []string{
			"You've reached your plan limit. Run /upgrade to review your plan.",
			"You've reached your Pro plan limit. Run /upgrade to move to Max.",
		},
	},
	{
		Name: "goose-out-of-credits", Agent: "goose",
		Re:     regexp.MustCompile(`^Please (?:add credits to your account|check your account with your provider to add more credits), then resend your message to continue\.`),
		Source: "goose 1.52.0 binary: credits_exhausted error text",
		Samples: []string{
			"Please add credits to your account, then resend your message to continue.",
			"Please check your account with your provider to add more credits, then resend your message to continue.",
		},
	},
	{
		Name: "hermes-credits-exhausted", Agent: "hermes",
		Re:     regexp.MustCompile(`^(?:❌ )?Billing or credits exhausted(?: —|:) `),
		Unless: regexp.MustCompile(`switching to fallback provider`),
		Source: "hermes 0.21.5 agent/turn_recovery.py and conversation_loop.py (the \"switching to fallback provider\" variant continues on its own and is not a stop); the summary after the dash in the samples is illustrative",
		Samples: []string{
			"❌ Billing or credits exhausted — Nous Portal: insufficient credits",
			"Billing or credits exhausted: Nous Portal: insufficient credits",
		},
	},
}

Table is every recognised limit message, most specific first.

Functions

func Account added in v2.6.0

func Account(db *store.DB, targetID int64, agent string, accountID *int64) *store.Account

Account is where a session or attempt runs: its registered account, the registered default login when it has none, or nil for an unregistered default login.

func AccountLabel added in v2.6.0

func AccountLabel(a *store.Account) string

AccountLabel names an account for a push; nil is the default login.

func AccountRef added in v2.6.0

func AccountRef(a *store.Account) int64

AccountRef is an account's id, 0 for an unregistered default login.

func Candidates added in v2.6.0

func Candidates(db *store.DB, targetID int64, agent string) []accounts.Candidate

Candidates is every account of one CLI on one target as the selection sees it: its recorded limit plus the fullest usage window the CLI last reported.

func FormatReset

func FormatReset(reset, now time.Time) string

FormatReset renders a reset for a notification: a clock time today, a date otherwise, in the server's zone.

func MarkLimited added in v2.6.0

func MarkLimited(db *store.DB, a *store.Account, h *store.LimitHold, now time.Time)

MarkLimited records the limit against the account the hold happened on.

func NextAccount added in v2.6.0

func NextAccount(db *store.DB, targetID int64, agent string, current *store.Account, chosen int64, now time.Time) (*store.Account, time.Time, error)

NextAccount picks where a limited session or attempt should move: the operator's choice when one is given (if it is usable), otherwise the next free account in rotation order.

func ParseReset

func ParseReset(text string, now time.Time) time.Time

ParseReset reads a reset time out of a limit message, relative to now (when the message was seen). It returns the zero time when the message names none or names one it cannot place.

func RecordAttemptHit

func RecordAttemptHit(db *store.DB, att *store.Attempt, task *store.Task, agent string, hit Hit, source string, now time.Time) (*store.LimitHold, bool)

RecordAttemptHit opens a hold for a headless task attempt. The scheduler decides what to do with it once the attempt exits (ApplyTaskLimit).

func SwapTo added in v2.6.0

func SwapTo(db *store.DB, h *store.LimitHold, targetID int64, accountID *int64) *store.Account

SwapTo is the account a swap on this hold would move to right now, for the card's "Swap to …" button; nil when there is none.

Types

type Hit

type Hit struct {
	Pattern    string
	Agent      string
	Message    string
	ResetAt    time.Time // zero when the message did not say
	SelfResume bool
	// Line is the index of the matched line in the text it was found in.
	Line int
}

Hit is one detected limit message.

func DetectEvent

func DetectEvent(typ string, payload map[string]any, now time.Time) (Hit, bool)

DetectEvent reads one normalised task event (internal/agents) for a usage limit. Claude's stream reports it structurally (a rate_limit_event whose status is "rejected", normalised to a "rate_limit" event); every other agent is read from the text it printed — the result, an error record, or a plain output line — with the same table as a pane.

func DetectLines

func DetectLines(text string, now time.Time) (Hit, bool)

DetectLines scans text line by line and returns the LAST limit message in it. Only the matched line and the one after it (a narrow terminal wraps the reset time onto the next row) are read for the reset time.

func DetectTail

func DetectTail(pane string, n int, now time.Time) (Hit, bool)

DetectTail looks only at the bottom of a terminal: the last n non-blank lines. A limit message the agent has since scrolled past is not a limit.

type Pattern

type Pattern struct {
	Name string
	// Agent is the CLI whose message this is. Detection does not filter by
	// it: custom and catalog agents often wrap one of these CLIs or print a
	// provider's message verbatim, and every phrase here is specific enough to
	// mean the same thing wherever it appears.
	Agent string
	// Re must match at the start of a line, after terminal decoration
	// (bullets, box edges, prompts) is stripped — an agent quoting the phrase
	// mid-sentence, or source code containing it, is not a limit.
	Re *regexp.Regexp
	// SelfResume marks the CLI's own "I will continue when it resets" banner.
	// Lectern then waits for the CLI instead of typing into it.
	SelfResume bool
	// Source is where the message text was read from.
	Source string
	// Samples are verbatim messages; patterns_test.go matches every one.
	// Where a CLI fills a placeholder, the sample fills it the way that CLI
	// would and Source says so.
	Samples []string
	// Unless excludes a matching line that is not a stop: a CLI that prints
	// the same opening when it is about to switch to a fallback on its own.
	Unless *regexp.Regexp
}

Pattern is one CLI limit message Lectern recognises. Every entry carries the real text it was taken from, so the table doubles as its own test fixture (patterns_test.go) and a changed CLI message fails a test rather than silently disabling detection.

type Policy

type Policy struct {
	Mode string `json:"mode"`
	// Then is what a swap policy does when no other account is free:
	// notify, wait or handoff (notify when empty).
	Then              string `json:"then,omitempty"`
	FallbackAgent     string `json:"fallback_agent,omitempty"`
	FallbackModel     string `json:"fallback_model,omitempty"`
	FallbackProfileID int64  `json:"fallback_profile_id,omitempty"`
	// AccountID is an operator's choice of account for one swap; never stored.
	AccountID int64 `json:"-"`
}

Policy is one scope's limit policy, stored as JSON in limit_policies.

func Effective

func Effective(db *store.DB, sessionID int64, projectID *int64) (Policy, string)

Effective resolves the policy for a session (sessionID 0 for a task) in a project (nil for none): session, then project, then global, then notify. The scope that supplied it is returned so the UI can say where to change it.

func ParsePolicy

func ParsePolicy(raw string) (Policy, bool)

ParsePolicy decodes a stored policy; an empty or unreadable value is the default notify policy.

func (Policy) Fallback

func (p Policy) Fallback() string

Fallback names the handoff destination for a card or a push.

func (Policy) HasFallback

func (p Policy) HasFallback() bool

HasFallback reports whether a handoff has somewhere to go.

func (Policy) Secondary added in v2.6.0

func (p Policy) Secondary() string

Secondary is the mode to use when a swap has nowhere to go: the policy's Then for a swap policy, otherwise the mode itself.

func (*Policy) Validate

func (p *Policy) Validate() error

Validate normalises the mode and rejects a handoff with nowhere to go.

type SessionDriver

type SessionDriver interface {
	// SendNudge types text into the session without Lectern's automatic
	// memory context, so the pane shows exactly the nudge.
	SendNudge(ctx context.Context, id int64, text string) error
	// StartLimitHandoff starts a successor on the fallback agent in the same
	// workspace, primed from what Lectern captured (the limited agent cannot
	// write a handoff of its own), and resolves the hold once it is running.
	StartLimitHandoff(id int64, agent, model string, profileID int64) error
	InFlight(id int64) bool
	HandoffError(id int64) string
	// SwapAccount restarts the session's agent under another account of the
	// same CLI, resuming the same conversation (docs/accounts.md), and waits
	// for its prompt. committed reports whether the agent now runs under the
	// new account, even when err says it never reached a prompt.
	SwapAccount(ctx context.Context, id, accountID int64) (committed bool, err error)
}

SessionDriver is the slice of the session manager the tracker drives.

type TaskActor

type TaskActor interface {
	ApplyTaskLimit(ctx context.Context, h *store.LimitHold, mode string, p Policy) error
}

TaskActor requeues or re-dispatches a limited task attempt (the scheduler).

type Timing

type Timing struct {
	// Grace is added to a stated reset time before anything is retried:
	// provider clocks and the CLI's rounded display are not exact.
	Grace time.Duration
	// Jitter is a random extra delay on top of Grace, so a fleet of sessions
	// limited by the same account does not all resume in the same second.
	Jitter time.Duration
	// Backoff is the first retry delay when no reset time is known or a
	// resume attempt hit the limit again. It doubles per try up to MaxBackoff.
	Backoff    time.Duration
	MaxBackoff time.Duration
	// Settle is how long a nudge has to show a result before Lectern decides
	// whether the agent resumed.
	Settle time.Duration
	// MaxTries bounds automatic resume attempts for one hold.
	MaxTries int
	// Stale is how long a handoff or requeue may sit mid-flight before it is
	// treated as interrupted (a restart in the middle of one).
	Stale time.Duration
}

Timing is every delay the resume loop uses. Tests shrink it; production uses DefaultTiming.

func (Timing) DueAt

func (t Timing) DueAt(reset time.Time, tries int, now time.Time, rnd func() float64) time.Time

DueAt is when a waiting hold should next be retried: just after the reset when one is known and still ahead, otherwise an exponential backoff from now (tries is how many resumes have already failed).

type Tracker

type Tracker struct {
	DB       *store.DB
	Bus      *bus.Bus
	Notifier *sinks.Notifier
	Log      *slog.Logger
	Sessions SessionDriver
	Tasks    TaskActor
	Timing   Timing
	// Clock and Rand are test seams; nil means time.Now and math/rand.
	Clock func() time.Time
	Rand  func() float64
	// contains filtered or unexported fields
}

Tracker owns every limit hold's lifecycle. All state lives in limit_holds; the only memory it keeps is the most recent pane of each session, which the next poll refreshes.

func New

func New(db *store.DB, b *bus.Bus, n *sinks.Notifier, log *slog.Logger) *Tracker

New builds a tracker with the production timing.

func (*Tracker) Choose

func (t *Tracker) Choose(ctx context.Context, id int64, action string, override *Policy) (*store.LimitHold, error)

Choose applies an operator's choice. override, when non-nil, names the handoff destination; otherwise the effective policy's fallback is used.

func (*Tracker) HandleHookEvent

func (t *Tracker) HandleHookEvent(s *store.Session, event string, body []byte, _ string, _ bool)

HandleHookEvent is chained onto agentevents.Ingester.OnHookEvent. Claude's StopFailure hook carries the API error ("rate_limit") and the message it showed; tool and Stop hooks after a nudge prove the agent really resumed.

func (*Tracker) ObservePane

func (t *Tracker) ObservePane(s *store.Session, pane string, busy bool)

ObservePane is called by the session poll with every capture. busy is the poll's own "the agent is working" reading of the same pane. It only reads and writes the database; anything that types into a session happens in Tick.

func (*Tracker) Tick

func (t *Tracker) Tick(ctx context.Context)

Tick advances every open hold whose next step is due. It is wired onto the scheduler's tick, after the session poll.

func (*Tracker) Wait added in v2.6.0

func (t *Tracker) Wait()

Wait blocks until every swap this tracker started has finished. Tests use it.

Jump to

Keyboard shortcuts

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