b3c9575fde
- A stage refused for a Claude usage limit no longer fails its run: the runner tries the chats' Claude account auto-switch (per-home setting) and reruns the visit, else parks the run in the new waiting_quota status (persisted, with reset/resume time in run summaries, details and events) and resumes the same visit at reset + 1 min, also after a restart. resume_run / `pipelines resume` resumes now; cancel works on parked runs. The rerun visit gets a "# Previous attempt" interruption note. Subscription limits no longer say "top up the provider account". - run/retry into an account known to be limited are deferred (quota_policy defer/refuse/now; CLI refuses under --json/--yes unless --defer or --now). - failure_class on runs (quota, loop_exhausted, timeout, permission_denied, harness_error, blocked, environment, canceled, interrupted, budget, check_failed, other) in RunSummary/RunDetail/events, CLI inspect/runs/wait/ stats and the app failure line. - Claude permission denials (permission_denials / refused tool results) fail a blocked visit with permission_denied naming the tool use. - Harness failures are classified transient vs deterministic; deterministic ones (and a repeated empty readback) skip error self-loops; transient self-loops back off 15 s, 1 min, 4 min. - Whole-run USD budget: run --budget, server default (run-budget / get/set_run_settings); 80% warning notification, stop with class budget. - App: waiting_quota status/filter with resume time, Resume now and Cancel, failure class wording. Docs and skill references updated. Merges main (check stage, delivery gate, Claude stage restart survival, schedule changes). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
240 lines
7.7 KiB
Go
240 lines
7.7 KiB
Go
package claude
|
||
|
||
import (
|
||
"regexp"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// A turn Claude Code refuses for a usage limit ends with a synthetic
|
||
// assistant message carrying the API error ("rate_limit") and the CLI's own
|
||
// text, "You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of
|
||
// usage credits" (older CLIs: "Claude AI usage limit reached|<epoch>"), and a
|
||
// result line marked is_error that repeats it. The app recognises the same
|
||
// text (app domain/chat_usage_limit.dart).
|
||
var usageLimitText = regexp.MustCompile(`(?m)^\s*You['’]ve hit your [^·\n]*limit|usage limit reached\|\d{9,11}\b`)
|
||
|
||
// UsageRefusal is one live turn Claude Code refused because the account ran
|
||
// out of usage.
|
||
type UsageRefusal struct {
|
||
SessionID string
|
||
// Directory is the chat's working directory, which selects its Claude
|
||
// home (CLAUDE_CONFIG_DIR).
|
||
Directory string
|
||
TurnID string
|
||
// MessageID is the refusal message's id, as transcripts name it ("" when
|
||
// only the result reported it).
|
||
MessageID string
|
||
// Email is the account the refused turn started on ("" when unknown).
|
||
Email string
|
||
// ResetsAt is when the limit resets: the time the refusal's own text
|
||
// names, else the reset of the turn's rejected rate_limit_event; zero
|
||
// when neither said.
|
||
ResetsAt time.Time
|
||
// Prompt is the operator's message the refusal answered when the
|
||
// refused turn was started by it and did no work before the refusal;
|
||
// "" for a turn that worked, or one Claude Code started itself (a
|
||
// background-task notification).
|
||
Prompt string
|
||
}
|
||
|
||
// OnUsageRefused registers the receiver of usage-limit refusals; each is
|
||
// delivered once, on its own goroutine, after the turn's end was published.
|
||
func (c *Chat) OnUsageRefused(handler func(UsageRefusal)) {
|
||
c.refusalMu.Lock()
|
||
c.onRefusal = handler
|
||
c.refusalMu.Unlock()
|
||
}
|
||
|
||
func (c *Chat) reportUsageRefusal(refusal UsageRefusal) {
|
||
c.refusalMu.Lock()
|
||
handler := c.onRefusal
|
||
c.refusalMu.Unlock()
|
||
if handler != nil {
|
||
go handler(refusal)
|
||
}
|
||
}
|
||
|
||
// beginTurnLocked records the account a new turn starts on and forgets any
|
||
// refusal of the previous turn. The caller holds s.mu.
|
||
func (s *session) beginTurnLocked() {
|
||
s.turnEmail = s.account.email
|
||
s.clearRefusalLocked()
|
||
}
|
||
|
||
// clearRefusalLocked forgets the running turn's refusal record and prompt.
|
||
// The caller holds s.mu.
|
||
func (s *session) clearRefusalLocked() {
|
||
s.limitMessageID = ""
|
||
s.limitByError = false
|
||
s.limitText = ""
|
||
s.limitAt = time.Time{}
|
||
s.limitReset = time.Time{}
|
||
s.turnPrompt = ""
|
||
s.turnWorked = false
|
||
}
|
||
|
||
// noteUsageRefusalLocked remembers an assistant message that is a
|
||
// usage-limit refusal. The caller holds s.mu.
|
||
func (s *session) noteUsageRefusalLocked(envelope lineEnvelope, body messageBody, blocks []contentBlock, messageID string) {
|
||
byError := envelope.Error == "rate_limit" || body.Error == "rate_limit"
|
||
byText := false
|
||
for _, block := range blocks {
|
||
if block.Type == "text" && usageLimitText.MatchString(block.Text) {
|
||
byText = true
|
||
break
|
||
}
|
||
}
|
||
if !byError && !byText {
|
||
if messageID != s.limitMessageID {
|
||
s.turnWorked = true
|
||
}
|
||
return
|
||
}
|
||
s.limitMessageID = messageID
|
||
s.limitByError = s.limitByError || byError
|
||
s.limitText = ""
|
||
for _, block := range blocks {
|
||
if block.Type == "text" {
|
||
s.limitText += block.Text + "\n"
|
||
}
|
||
}
|
||
s.limitAt = time.Now()
|
||
if at, err := time.Parse(time.RFC3339Nano, envelope.Timestamp); err == nil {
|
||
s.limitAt = at
|
||
}
|
||
}
|
||
|
||
// takeUsageRefusalLocked reports whether the turn a result line ends was
|
||
// refused for a usage limit, and clears the record. The caller holds s.mu.
|
||
func (s *session) takeUsageRefusalLocked(envelope lineEnvelope) (UsageRefusal, bool) {
|
||
refused := (s.limitMessageID != "" && (s.limitByError || envelope.IsError)) ||
|
||
(envelope.IsError && usageLimitText.MatchString(envelope.Result))
|
||
email := s.turnEmail
|
||
if email == "" {
|
||
email = s.account.email
|
||
}
|
||
refusal := UsageRefusal{SessionID: s.id, Directory: s.directory, TurnID: s.turnID, MessageID: s.limitMessageID, Email: email}
|
||
if refusal.TurnID == "" {
|
||
refusal.TurnID = "result-" + strings.TrimSpace(envelope.UUID)
|
||
}
|
||
at := s.limitAt
|
||
if at.IsZero() {
|
||
at = time.Now()
|
||
}
|
||
if reset, ok := usageLimitReset(s.limitText+envelope.Result, at); ok {
|
||
refusal.ResetsAt = reset
|
||
} else if !s.limitReset.IsZero() {
|
||
refusal.ResetsAt = s.limitReset
|
||
}
|
||
if !s.turnWorked {
|
||
refusal.Prompt = s.turnPrompt
|
||
}
|
||
s.clearRefusalLocked()
|
||
return refusal, refused
|
||
}
|
||
|
||
// noteRejectedResetLocked records when a rejected rate_limit_event the
|
||
// running turn received says the limit resets. The caller holds s.mu.
|
||
func (s *session) noteRejectedResetLocked(until time.Time) {
|
||
if until.After(s.limitReset) {
|
||
s.limitReset = until
|
||
}
|
||
}
|
||
|
||
var (
|
||
// usageLimitEpoch is the older CLI's "usage limit reached|<epoch>".
|
||
usageLimitEpoch = regexp.MustCompile(`usage limit reached\|(\d{9,11})\b`)
|
||
// usageLimitResets is the current CLI's "resets 5:20pm (Europe/London)",
|
||
// or with a date for a longer window, "resets Dec 9, 5pm (Europe/London)".
|
||
usageLimitResets = regexp.MustCompile(`(?i)\bresets\s+(?:([a-z]{3})[a-z]*\.?\s+(\d{1,2})(?:,|\s+at)?\s+)?(\d{1,2})(?::(\d{2}))?\s*([ap]m)\s*\(([^)\s]+)\)`)
|
||
)
|
||
|
||
// usageLimitReset is the reset a refusal's text names, the first such time
|
||
// after at (when the refusal was written).
|
||
func usageLimitReset(text string, at time.Time) (time.Time, bool) {
|
||
if match := usageLimitEpoch.FindStringSubmatch(text); match != nil {
|
||
seconds, err := strconv.ParseInt(match[1], 10, 64)
|
||
if err != nil || seconds <= 0 {
|
||
return time.Time{}, false
|
||
}
|
||
return time.Unix(seconds, 0), true
|
||
}
|
||
match := usageLimitResets.FindStringSubmatch(text)
|
||
if match == nil {
|
||
return time.Time{}, false
|
||
}
|
||
location, err := time.LoadLocation(match[6])
|
||
if err != nil {
|
||
return time.Time{}, false
|
||
}
|
||
hour, _ := strconv.Atoi(match[3])
|
||
minute := 0
|
||
if match[4] != "" {
|
||
minute, _ = strconv.Atoi(match[4])
|
||
}
|
||
if hour < 1 || hour > 12 || minute > 59 {
|
||
return time.Time{}, false
|
||
}
|
||
hour %= 12
|
||
if strings.EqualFold(match[5], "pm") {
|
||
hour += 12
|
||
}
|
||
local := at.In(location)
|
||
if match[1] != "" {
|
||
month, ok := monthOf(match[1])
|
||
day, _ := strconv.Atoi(match[2])
|
||
if !ok || day < 1 || day > 31 {
|
||
return time.Time{}, false
|
||
}
|
||
reset := time.Date(local.Year(), month, day, hour, minute, 0, 0, location)
|
||
if reset.Before(at.Add(-time.Minute)) {
|
||
reset = time.Date(local.Year()+1, month, day, hour, minute, 0, 0, location)
|
||
}
|
||
return reset, true
|
||
}
|
||
reset := time.Date(local.Year(), local.Month(), local.Day(), hour, minute, 0, 0, location)
|
||
if reset.Before(at.Add(-time.Minute)) {
|
||
reset = time.Date(local.Year(), local.Month(), local.Day()+1, hour, minute, 0, 0, location)
|
||
}
|
||
return reset, true
|
||
}
|
||
|
||
func monthOf(name string) (time.Month, bool) {
|
||
for month := time.January; month <= time.December; month++ {
|
||
if strings.EqualFold(month.String()[:3], name) {
|
||
return month, true
|
||
}
|
||
}
|
||
return 0, false
|
||
}
|
||
|
||
// noteRejectedLocked records when a rejected account's limit ends. The
|
||
// caller holds c.quotaMu.
|
||
func (c *Chat) noteRejectedLocked(email string, until time.Time) {
|
||
email = strings.ToLower(strings.TrimSpace(email))
|
||
if email == "" || until.IsZero() {
|
||
return
|
||
}
|
||
if c.rejectedUntil == nil {
|
||
c.rejectedUntil = map[string]time.Time{}
|
||
}
|
||
if until.After(c.rejectedUntil[email]) {
|
||
c.rejectedUntil[email] = until
|
||
}
|
||
}
|
||
|
||
// IsUsageLimitText reports whether text is Claude Code's usage-limit refusal.
|
||
func IsUsageLimitText(text string) bool { return usageLimitText.MatchString(text) }
|
||
|
||
// UsageLimitResetIn reads the reset time a usage-limit refusal's text names
|
||
// (as of at); ok is false when the text is not a usage-limit refusal or names
|
||
// no reset. Pipeline stages use it when no rate_limit_event said.
|
||
func UsageLimitResetIn(text string, at time.Time) (time.Time, bool) {
|
||
if !usageLimitText.MatchString(text) {
|
||
return time.Time{}, false
|
||
}
|
||
return usageLimitReset(text, at)
|
||
}
|