Claude accounts: switch a chat refused for usage to another saved account and continue it

When Claude Code refuses an operator chat's turn for a usage limit, the
server marks the refused account until its reset and, if the chat's Claude
home allows it (claude_account_auto_switch / `pipelines claude-account auto
on|off`, on by default, kept in pipelines-accounts/settings.json), switches
the home to the saved account with the most usage left through the
claude_account_use path. Switches of one home are serialized, so chats
refused together switch once. Each refused chat gets one queued prompt,
marked as sent automatically, that asks the agent to check it is on track
before continuing; the app's auto-continue-at-reset prompt for the refusal is
removed (and refused if it arrives later), and the operator gets a
low-priority notification.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 00:23:43 +00:00
parent 1995382e8c
commit ed9072b79a
30 changed files with 1362 additions and 21 deletions
+23 -10
View File
@@ -71,21 +71,34 @@ func (c *Chat) ClaudeAccounts(ctx context.Context, sessionID, directory, operati
case protocol.ClaudeAccountRemove:
return store.Remove(name)
case protocol.ClaudeAccountUse:
list, err := store.Use(name)
if err != nil {
return list, err
return c.useAccount(ctx, configDir, store, name)
case protocol.ClaudeAccountAutoSwitch:
switch name {
case "on", "off":
return store.SetAutoSwitch(name == "on")
}
email, org, plan, ok := store.Identity()
if ok {
account := accountIdentity{key: accountKeyFor(email, org), plan: plan, email: strings.TrimSpace(email), organization: strings.TrimSpace(org)}
list.Usage = c.switchAccount(ctx, configDir, account)
log.Printf("claude account: %s switched to a saved account", configDir)
}
return list, nil
return protocol.ClaudeAccountList{}, errors.New(`automatic switching is "on" or "off"`)
}
return protocol.ClaudeAccountList{}, errors.New("unknown Claude account operation " + operation)
}
// useAccount makes the saved account name configDir's login and moves every
// open chat on that Claude home to it (claude_account_use and the automatic
// switch share it).
func (c *Chat) useAccount(ctx context.Context, configDir string, store claudeaccounts.Store, name string) (protocol.ClaudeAccountList, error) {
list, err := store.Use(name)
if err != nil {
return list, err
}
email, org, plan, ok := store.Identity()
if ok {
account := accountIdentity{key: accountKeyFor(email, org), plan: plan, email: strings.TrimSpace(email), organization: strings.TrimSpace(org)}
list.Usage = c.switchAccount(ctx, configDir, account)
log.Printf("claude account: %s switched to a saved account", configDir)
}
return list, nil
}
// switchAccount records that configDir now signs in as account: its quota
// report is marked switched (an empty one when nothing is known yet), and
// every open session on that Claude home takes the new account and
+220
View File
@@ -0,0 +1,220 @@
package claude
import (
"context"
"errors"
"sort"
"strings"
"sync"
"time"
"git.a-wan.net/alan/pipelines/internal/claudeaccounts"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// Automatic account switching: when a chat's turn is refused for a usage
// limit and its Claude home has another saved account with usage left, the
// home is switched to it (the claude_account_use path, under the same locks)
// so the server can continue the chat there. Switches of one home are
// serialized, so chats refused together switch once.
var (
// ErrAutoSwitchOff is returned when the Claude home's operator turned
// automatic switching off.
ErrAutoSwitchOff = errors.New("automatic Claude account switching is off for this Claude home")
// ErrNoAccountLeft is returned when no other saved account is known to
// have usage left.
ErrNoAccountLeft = errors.New("no other saved Claude account has usage left")
)
// refusalHold is how long a refused account is passed over when neither its
// quota nor the refusal said when its limit resets.
const refusalHold = time.Hour
// AutoSwitch is the outcome of AutoSwitchAccount.
type AutoSwitch struct {
// From is the account that was refused and To the one the home is
// signed in to now.
From, To string
// Switched is false when another refused chat on the same home had
// already switched it to To, which still has usage.
Switched bool
// Usage is To's latest known quota (marked switched when Switched).
Usage *protocol.ChatAccountUsage
}
// AutoSwitchAccount handles one usage-limit refusal: it marks the refused
// account as out of usage and, when the chat's Claude home allows automatic
// switching, signs the home in to the saved account with the lowest known
// usage that is not exhausted (an account with no known quota is still worth
// trying, after those known to have usage). It reports ErrAutoSwitchOff,
// ErrNoAccountLeft or ErrNoConfigDir when nothing is switched.
func (c *Chat) AutoSwitchAccount(ctx context.Context, refusal UsageRefusal) (AutoSwitch, error) {
directory := refusal.Directory
if strings.TrimSpace(directory) == "" {
if s := c.session(refusal.SessionID); s != nil {
s.mu.Lock()
directory = s.directory
s.mu.Unlock()
}
}
configDir, err := c.accountConfigDir(ctx, directory)
if err != nil {
return AutoSwitch{}, err
}
lock := c.autoLock(configDir)
lock.Lock()
defer lock.Unlock()
store := claudeaccounts.Store{ConfigDir: configDir}
if !store.AutoSwitch() {
return AutoSwitch{}, ErrAutoSwitchOff
}
list, err := store.List()
if err != nil {
return AutoSwitch{}, err
}
if list.Active == nil {
return AutoSwitch{}, ErrNoAccountLeft
}
now := time.Now()
from := strings.TrimSpace(refusal.Email)
if from == "" {
from = list.Active.Email
}
c.markRefused(from, organizationOf(list, from), now)
active := *list.Active
if !strings.EqualFold(active.Email, from) && c.usable(active, now) {
// Another chat's refusal already moved the home on.
identity := accountIdentity{key: accountKeyFor(active.Email, active.Organization), plan: active.Plan, email: active.Email, organization: active.Organization}
return AutoSwitch{From: from, To: active.Email, Usage: c.accountUsage(identity)}, nil
}
candidate, ok := c.pickAccount(list, from, now)
if !ok {
return AutoSwitch{}, ErrNoAccountLeft
}
switched, err := c.useAccount(ctx, configDir, store, candidate.Name)
if err != nil {
return AutoSwitch{}, err
}
to := candidate.Email
if switched.Active != nil {
to = switched.Active.Email
}
return AutoSwitch{From: from, To: to, Switched: true, Usage: switched.Usage}, nil
}
func (c *Chat) autoLock(configDir string) *sync.Mutex {
c.autoMu.Lock()
defer c.autoMu.Unlock()
if c.autoLocks == nil {
c.autoLocks = map[string]*sync.Mutex{}
}
lock := c.autoLocks[configDir]
if lock == nil {
lock = &sync.Mutex{}
c.autoLocks[configDir] = lock
}
return lock
}
func organizationOf(list protocol.ClaudeAccountList, email string) string {
if list.Active != nil && strings.EqualFold(list.Active.Email, email) {
return list.Active.Organization
}
for _, account := range list.Accounts {
if strings.EqualFold(account.Email, email) {
return account.Organization
}
}
return ""
}
// markRefused passes over email until its limit resets: the reset a
// rejected rate_limit_event named, else the latest reset of its exhausted
// windows, else refusalHold from now.
func (c *Chat) markRefused(email, organization string, now time.Time) {
if strings.TrimSpace(email) == "" {
return
}
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
if c.rejectedUntil[strings.ToLower(strings.TrimSpace(email))].After(now) {
return
}
until := now.Add(refusalHold)
if quota := c.quotas[accountKeyFor(email, organization)]; quota != nil {
latest := int64(0)
for _, w := range quota.Windows {
if w.UsedPercent >= 100 && w.ResetsAt > now.UnixMilli() && w.ResetsAt > latest {
latest = w.ResetsAt
}
}
if latest > 0 {
until = time.UnixMilli(latest)
}
}
c.noteRejectedLocked(email, until)
}
// usable reports whether account is neither marked refused nor known to be
// out of usage.
func (c *Chat) usable(account protocol.ClaudeAccount, now time.Time) bool {
_, _, ok := c.usageLeft(account, now)
return ok
}
// usageLeft is account's highest current window use (known false when no
// quota is known) and whether it can take a turn now.
func (c *Chat) usageLeft(account protocol.ClaudeAccount, now time.Time) (percent float64, known, ok bool) {
c.quotaMu.Lock()
defer c.quotaMu.Unlock()
if c.rejectedUntil[strings.ToLower(strings.TrimSpace(account.Email))].After(now) {
return 0, false, false
}
quota := c.quotas[accountKeyFor(account.Email, account.Organization)]
if quota == nil || len(quota.Windows) == 0 {
return 0, false, true
}
for _, w := range quota.Windows {
if w.ResetsAt != 0 && w.ResetsAt <= now.UnixMilli() {
continue // reset since it was reported
}
if w.UsedPercent >= 100 {
return w.UsedPercent, true, false
}
if w.UsedPercent > percent {
percent = w.UsedPercent
}
}
return percent, true, true
}
// pickAccount chooses the saved account to switch to after from was refused.
func (c *Chat) pickAccount(list protocol.ClaudeAccountList, from string, now time.Time) (protocol.ClaudeAccount, bool) {
type option struct {
account protocol.ClaudeAccount
percent float64
known bool
}
var options []option
for _, account := range list.Accounts {
if account.Active || !account.Saved || strings.EqualFold(account.Email, from) {
continue
}
percent, known, ok := c.usageLeft(account, now)
if ok {
options = append(options, option{account, percent, known})
}
}
if len(options) == 0 {
return protocol.ClaudeAccount{}, false
}
sort.SliceStable(options, func(i, j int) bool {
a, b := options[i], options[j]
if a.known != b.known {
return a.known
}
return a.percent < b.percent
})
return options[0].account, true
}
+173
View File
@@ -0,0 +1,173 @@
package claude
import (
"context"
"errors"
"path/filepath"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
func TestUsageLimitRefusalIsReportedOnceWithItsAccount(t *testing.T) {
chat := testChat(t)
refusals := make(chan UsageRefusal, 4)
chat.OnUsageRefused(func(refusal UsageRefusal) { refusals <- refusal })
created := newCreatedChat(t, chat)
frames := subscribe(t, chat, created.ID)
ended := func(what string) {
waitFrame(t, frames, what, func(frame protocol.ChatEventFrame) bool {
return frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded
})
}
if err := chat.Prompt(context.Background(), created.ID, "hello"); err != nil {
t.Fatal(err)
}
ended("an ordinary turn's end")
if err := chat.Prompt(context.Background(), created.ID, "usage-limit"); err != nil {
t.Fatal(err)
}
ended("the refused turn's end")
select {
case refusal := <-refusals:
if refusal.SessionID != created.ID || refusal.MessageID != "refusal-2" || refusal.Email != "fixture@example.invalid" ||
refusal.TurnID == "" || refusal.Directory != created.Directory {
t.Fatalf("refusal = %+v", refusal)
}
case <-time.After(5 * time.Second):
t.Fatal("the refusal was not reported")
}
select {
case extra := <-refusals:
t.Fatalf("a second refusal was reported: %+v", extra)
case <-time.After(200 * time.Millisecond):
}
// The rejected rate_limit_event says when the limit ends.
chat.quotaMu.Lock()
until := chat.rejectedUntil["fixture@example.invalid"]
chat.quotaMu.Unlock()
if !until.Equal(time.Unix(1900000000, 0)) {
t.Fatalf("rejected until %v", until)
}
}
func TestUsageRefusalNeedsTheLimitText(t *testing.T) {
s := &session{id: "s", turnID: "t1", account: accountIdentity{email: "a@example.invalid"}}
s.beginTurnLocked()
s.noteUsageRefusalLocked(lineEnvelope{}, messageBody{}, []contentBlock{{Type: "text", Text: "Done; nothing hit any limit."}}, "m1")
if _, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true, Result: "Done"}); refused {
t.Fatal("an ordinary error result was taken for a usage refusal")
}
// The older CLI's text on the result alone is enough.
s.turnID = "t2"
refusal, refused := s.takeUsageRefusalLocked(lineEnvelope{IsError: true, Result: "Claude AI usage limit reached|1900000000"})
if !refused || refusal.Email != "a@example.invalid" || refusal.TurnID != "t2" {
t.Fatalf("refusal = %+v %v", refusal, refused)
}
}
// accountsHome is a chat directory whose Claude home has saved accounts a-e,
// signed in as a.
func accountsHome(t *testing.T, chat *Chat) string {
t.Helper()
profile := t.TempDir()
directory := t.TempDir()
writeFile(t, filepath.Join(directory, ".envrc"), "export CLAUDE_CONFIG_DIR=...\n")
writeFile(t, filepath.Join(directory, ".envrc.allowed"), "")
writeFile(t, filepath.Join(directory, ".envrc.json"), `{"CLAUDE_CONFIG_DIR":"`+profile+`"}`)
for _, name := range []string{"e", "d", "c", "b", "a"} {
writeLogin(t, profile, name+"@example.invalid", "uuid-"+name, name+"1")
if _, err := chat.ClaudeAccounts(context.Background(), "s", directory, protocol.ClaudeAccountSave, ""); err != nil {
t.Fatal(err)
}
}
return directory
}
func setQuota(chat *Chat, email string, percent float64, resetsAt int64) {
chat.quotaMu.Lock()
defer chat.quotaMu.Unlock()
if chat.quotas == nil {
chat.quotas = map[string]*protocol.ChatAccountUsage{}
}
chat.quotas[accountKeyFor(email, "Org")] = &protocol.ChatAccountUsage{Harness: quotaHarness,
Windows: []protocol.ChatQuotaWindow{{ID: "five_hour", Label: "5-hour", UsedPercent: percent, ResetsAt: resetsAt}}}
}
func TestAutoSwitchMovesToTheSavedAccountWithTheMostUsageLeft(t *testing.T) {
chat := directoryChat(t)
directory := accountsHome(t, chat)
ctx := context.Background()
future := time.Now().Add(3 * time.Hour).UnixMilli()
setQuota(chat, "a@example.invalid", 100, future)
setQuota(chat, "b@example.invalid", 80, future)
setQuota(chat, "c@example.invalid", 20, future)
setQuota(chat, "d@example.invalid", 100, future) // exhausted
// e has no known quota.
// Two chats refused on a at once: the home switches once, to c.
var wg sync.WaitGroup
results := make([]AutoSwitch, 2)
errs := make([]error, 2)
for i := range results {
wg.Add(1)
go func(i int) {
defer wg.Done()
results[i], errs[i] = chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "a@example.invalid"})
}(i)
}
wg.Wait()
if errs[0] != nil || errs[1] != nil {
t.Fatalf("errs = %v", errs)
}
if results[0].Switched == results[1].Switched || results[0].To != "c@example.invalid" || results[1].To != "c@example.invalid" {
t.Fatalf("results = %+v", results)
}
for _, result := range results {
if result.From != "a@example.invalid" {
t.Fatalf("from = %+v", result)
}
if result.Switched && (result.Usage == nil || result.Usage.SwitchedAt == 0) {
t.Fatalf("the switch was not marked: %+v", result.Usage)
}
}
// c is refused too: the next best known account is b; then e, whose
// usage nobody knows; then nothing is left (a was refused, d is out).
for _, step := range []struct{ from, to string }{{"c@example.invalid", "b@example.invalid"}, {"b@example.invalid", "e@example.invalid"}} {
result, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: step.from})
if err != nil || !result.Switched || result.To != step.to {
t.Fatalf("after %s: %+v %v", step.from, result, err)
}
}
if _, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "e@example.invalid"}); !errors.Is(err, ErrNoAccountLeft) {
t.Fatalf("all exhausted: %v", err)
}
list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "")
if err != nil || list.Active == nil || list.Active.Email != "e@example.invalid" {
t.Fatalf("active = %+v %v", list.Active, err)
}
}
func TestAutoSwitchOffLeavesTheAccount(t *testing.T) {
chat := directoryChat(t)
directory := accountsHome(t, chat)
ctx := context.Background()
list, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountAutoSwitch, "off")
if err != nil || list.AutoSwitch {
t.Fatalf("auto off = %+v %v", list, err)
}
if _, err := chat.AutoSwitchAccount(ctx, UsageRefusal{SessionID: "s", Directory: directory, TurnID: "t", Email: "a@example.invalid"}); !errors.Is(err, ErrAutoSwitchOff) {
t.Fatalf("err = %v", err)
}
list, _ = chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccounts, "")
if list.Active == nil || list.Active.Email != "a@example.invalid" {
t.Fatalf("switched while off: %+v", list.Active)
}
if _, err := chat.ClaudeAccounts(ctx, "s", directory, protocol.ClaudeAccountAutoSwitch, "maybe"); err == nil {
t.Fatal("a bad choice was accepted")
}
}
+2
View File
@@ -188,6 +188,7 @@ func (c *Chat) PromptWithMessageIDModelFiles(ctx context.Context, id, text, mess
s.mu.Lock()
s.turnID = turn
s.running = true
s.beginTurnLocked()
s.steered = 0
s.awaitFollowUp = false
s.recordPromptLocked(messageID, text)
@@ -271,6 +272,7 @@ func (s *session) adoptFollowUpTurn() {
turn := fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.turnID = turn
s.running = true
s.beginTurnLocked()
s.mu.Unlock()
s.emit(protocol.ChatEventFrame{SessionID: s.id, NativeTurnID: turn, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepStarted, TurnID: turn}})
}
+19 -2
View File
@@ -116,6 +116,17 @@ type Chat struct {
// quotas is the latest rate_limit_event quota per account (see quota.go).
quotaMu sync.Mutex
quotas map[string]*protocol.ChatAccountUsage
// rejectedUntil is when an account's usage-limit refusal ends, from a
// rejected rate_limit_event or a refusal (by lower-case email); guarded
// by quotaMu (auto_switch.go).
rejectedUntil map[string]time.Time
// onRefusal receives every live usage-limit refusal (refusal.go);
// autoLocks serializes automatic switches per Claude home.
refusalMu sync.Mutex
onRefusal func(UsageRefusal)
autoMu sync.Mutex
autoLocks map[string]*sync.Mutex
// catalog is the latest initialize model list of any session (efforts.go),
// so a listed row names its levels without starting a CLI.
@@ -370,8 +381,14 @@ type session struct {
automationProcess *process
// account is the signed-in account the live process reported.
account accountIdentity
prompts []promptRecord
models []protocol.ChatModel
// turnEmail is the account the running turn started on; limitMessageID
// and limitByError record a usage-limit refusal the turn received
// (refusal.go).
turnEmail string
limitMessageID string
limitByError bool
prompts []promptRecord
models []protocol.ChatModel
// commands are the slash commands the live CLI's initialize listed;
// terminalCommands are those its init line marks terminal-only (commands.go).
commands []protocol.ChatCommand
+1
View File
@@ -379,6 +379,7 @@ func (p *process) readHost(conn *claudehost.Conn, plan replayPlan) {
turn = fmt.Sprintf("claude-%d", time.Now().UnixNano())
s.turnID = turn
s.running = true
s.beginTurnLocked()
s.steered = 0
} else if !plan.busyAtAcked {
// Output that starts a turn after the reconnect (a follow-up of
+19
View File
@@ -200,6 +200,9 @@ func (s *session) handleRateLimit(raw json.RawMessage) {
}
c := s.chat
c.quotaMu.Lock()
if until, ok := rejectedUntil(raw); ok {
c.noteRejectedLocked(account.email, until)
}
next := mergeRateLimit(c.quotas[key], raw, account.plan, time.Now())
if next == nil {
c.quotaMu.Unlock()
@@ -229,6 +232,22 @@ func (s *session) handleRateLimit(raw json.RawMessage) {
}
}
// rejectedUntil reports when a rejected rate_limit_event's limit resets: a
// refusal the account cannot draw extra usage past.
func rejectedUntil(raw json.RawMessage) (time.Time, bool) {
var info rateLimitInfo
if len(raw) == 0 || json.Unmarshal(raw, &info) != nil || info.Status != "rejected" {
return time.Time{}, false
}
if extra := info.extraUsage(); extra != nil && extra.InUse {
return time.Time{}, false
}
if info.ResetsAt == nil || *info.ResetsAt <= 0 || math.IsInf(*info.ResetsAt, 0) {
return time.Time{}, false
}
return time.UnixMilli(int64(*info.ResetsAt * 1000)), true
}
func containsSession(list []*session, s *session) bool {
for _, other := range list {
if other == s {
+105
View File
@@ -0,0 +1,105 @@
package claude
import (
"regexp"
"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
}
// 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.limitMessageID = ""
s.limitByError = 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 {
s.limitMessageID = messageID
s.limitByError = s.limitByError || byError
}
}
// 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)
}
s.limitMessageID = ""
s.limitByError = false
return refusal, refused
}
// 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
}
}
+22
View File
@@ -79,6 +79,9 @@ def user_message(text):
if "background" in text:
background(message_id)
return
if "usage-limit" in text:
refused(message_id)
return
if "notify" in text:
send({"type": "system", "subtype": "task_notification", "task_id": "b1",
"tool_use_id": "toolu_bg_fake", "status": "completed", "summary": "Background command completed (exit code 0)"})
@@ -175,6 +178,25 @@ def background(message_id):
finish(message_id)
def refused(message_id):
"""A turn refused for a usage limit, as Claude Code 2.1 ends one: a rejected
rate_limit_event, a synthetic assistant API-error message and an is_error
result repeating its text."""
text = "You've hit your 5-hour limit · resets 5:20pm (Europe/London) · out of usage credits"
send({"type": "rate_limit_event", "uuid": "rate-%d" % state["turn"], "session_id": state["session"],
"rate_limit_info": {"status": "rejected", "resetsAt": 1900000000, "rateLimitType": "five_hour",
"isUsingOverage": False, "overageStatus": "rejected",
"overageDisabledReason": "out_of_credits"}})
refusal_id = "refusal-%d" % state["turn"]
message = {"id": refusal_id, "role": "assistant", "model": "<synthetic>",
"content": [{"type": "text", "text": text}]}
append({"type": "assistant", "uuid": refusal_id, "timestamp": stamp(), "error": "rate_limit",
"isApiErrorMessage": True, "message": message})
send({"type": "assistant", "uuid": refusal_id, "error": "rate_limit", "message": message})
send({"type": "result", "subtype": "success", "is_error": True, "result": text,
"session_id": state["session"]})
def finish(message_id):
# Shape of SDKRateLimitEvent in Claude Code 2.1.316 (synthetic numbers).
if os.environ.get("FAKE_CLAUDE_RATE_LIMIT"):
+10
View File
@@ -42,6 +42,9 @@ type lineEnvelope struct {
IsMeta bool `json:"isMeta"`
// RateLimitInfo is the payload of a rate_limit_event line (see quota.go).
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
// Error names an API error an assistant line reports ("rate_limit" for a
// usage-limit refusal; see refusal.go).
Error string `json:"error"`
// TerminalSlashCommands, on a system init line, names the commands that
// only work in the interactive terminal (see commands.go).
TerminalSlashCommands []string `json:"terminal_slash_commands"`
@@ -65,6 +68,7 @@ type contentBlock struct {
}
type messageBody struct {
Error string `json:"error"`
ID string `json:"id"`
Role string `json:"role"`
Model string `json:"model"`
@@ -419,6 +423,7 @@ func (s *session) handleAssistant(envelope lineEnvelope) {
}
blocks := decodeBlocks(body.Content)
s.mu.Lock()
s.noteUsageRefusalLocked(envelope, body, blocks, messageID)
if messageID != s.streamID {
// A message that was not streamed (or a new one): nothing streamed can
// be aligned with it. Later events of the same message keep this state.
@@ -625,8 +630,10 @@ func (s *session) handleResult(envelope lineEnvelope) {
turn := s.turnID
running := s.running
proc := s.proc
refusal, refused := s.takeUsageRefusalLocked(envelope)
if s.silent {
proc = nil // replayed: the live usage query is made once caught up
refused = false
}
s.running = false
s.turnID = ""
@@ -662,6 +669,9 @@ func (s *session) handleResult(envelope lineEnvelope) {
if proc != nil {
go s.refreshUsage(proc)
}
if refused {
s.chat.reportUsageRefusal(refusal)
}
}
func (s *session) handleSystem(envelope lineEnvelope) {