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
- Variables
- func FormatReset(reset, now time.Time) string
- func ParseReset(text string, now time.Time) time.Time
- func RecordAttemptHit(db *store.DB, att *store.Attempt, task *store.Task, agent string, hit Hit, ...) (*store.LimitHold, bool)
- type Hit
- type Pattern
- type Policy
- type SessionDriver
- type TaskActor
- type Timing
- type Tracker
- func (t *Tracker) Choose(ctx context.Context, id int64, action string, override *Policy) (*store.LimitHold, error)
- func (t *Tracker) HandleHookEvent(s *store.Session, event string, body []byte, _ string, _ bool)
- func (t *Tracker) ObservePane(s *store.Session, pane string, busy bool)
- func (t *Tracker) Tick(ctx context.Context)
Constants ¶
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" )
What to do when a limit is hit.
const ( ScopeGlobal = "global" ScopeProject = "project" ScopeSession = "session" )
Scopes, narrowest last. The narrowest one with a stored policy wins.
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.
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.
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.
const TailLines = 15
TailLines is how much of the bottom of a pane counts as "what the agent is showing now".
Variables ¶
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.
var ErrConflict = errors.New("this limit is already being handled")
ErrConflict means the hold is no longer in a state the action applies to.
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.", }, }, }
Table is every recognised limit message, most specific first.
Functions ¶
func FormatReset ¶
FormatReset renders a reset for a notification: a clock time today, a date otherwise, in the server's zone.
func ParseReset ¶
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).
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 ¶
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 ¶
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.
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.
Samples []string
}
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"`
FallbackAgent string `json:"fallback_agent,omitempty"`
FallbackModel string `json:"fallback_model,omitempty"`
FallbackProfileID int64 `json:"fallback_profile_id,omitempty"`
}
Policy is one scope's limit policy, stored as JSON in limit_policies.
func Effective ¶
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 ¶
ParsePolicy decodes a stored policy; an empty or unreadable value is the default notify policy.
func (Policy) HasFallback ¶
HasFallback reports whether a handoff has somewhere 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
}
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.
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 (*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 ¶
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 ¶
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.