gateway: a Claude account Anthropic turned off moves on and rests as restricted

When Anthropic turns a Claude subscription account off, the request now
goes on to the routing group's next member and the provider's other
accounts, and the account rests as restricted (2h) instead of a short
failure rest. Before, a disabled organization's 400 ended the group at
that account and its next members were never asked (Ramon317317 on X),
and Claude Code's "account is on hold" came back from the bridge as a
502 that rested the account a minute and asked it again.

The words (claudeOffWords, routing.go): "This organization has been
disabled." (400 invalid_request_error or 403), "account is on hold and
can't use Claude Code" (the bridge now answers it as a 403),
"organization has disabled Claude subscription access", "OAuth
authentication is currently not allowed for this organization", and
"account can't receive replies from Claude" (either apostrophe, or
"cannot"). claudeAccountOff scopes them to a Claude subscription account
or a key on api.anthropic.com. A relay's same words are about the
relay's own account behind it, so they stay ordinary failures there, as
on Codex. The extra-usage and Usage Policy refusals are not account
faults and are unchanged. riskRefused keeps the provider's other
accounts in, as for Google's suspension.

Docs: claude-subscription-bridge.md and gateway-routing.md updated.

Run at f357a5e25 (this commit on origin/main f7e0f68ca), on mote:
- new tests (TestClaudeAccountOffMovesToNextAccount,
  TestClaudeOrgDisabledGroupMovesOn, TestClaudeAccountOffScoped):
  51 PASS lines, 0 FAIL.
- Broken by hand: routing.go, fallback.go and claude_subscription.go put
  back to the parent's, with a claudeAccountOff stub returning false so
  the test compiles: all 3 tests fail, 35 FAIL lines (32 subtests), 16
  pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./...: ok.
- go test ./... -timeout 45m: every package ok (103 ok lines), rc 0.

Then rebased on origin/main a2d402afe (six commits, internal/gui, site/
and docs/ only) and run again at the pushed head, on mote: gofmt -l
nothing; go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows
go vet ./... ok; go test -count=1 ./internal/gateway ./internal/gui ok.
Rebased again on 1318864d1 (internal/agent, internal/provider,
internal/sessions; none touched here) and run at this head: gofmt and
the three vets as above ok; go test -count=1 ./internal/gateway
./internal/provider ok.
main moved once more (3e66d25d8, 03314b25a: internal/agent, catalog,
gui import links, provider's CC Switch import; none touched here), and
this pushed head was run with gofmt, the three vets ok and the new tests
(51 PASS, 0 FAIL); the gateway package as a whole last ran at 1318864d1.

Not counted: an earlier full run on mica at an older base was voided
because mica's disk filled mid-run (253 "no space left on device"
failures). Its three internal/dirent reds (TestWatchesFromOneMarkProbeOnce,
TestWatchedFolderReadOnlyWhenChanged, TestFileHeldOpenStillSeen) did not
come back in the mote run above. mote's 1-minute load was ~39 on 18 cores
during the run, with no other full suite there.

Not tried: a real disabled or on-hold Claude account; the bodies are
from Claude Code's errors page and users' reports.
This commit is contained in:
yetone
2026-11-18 17:09:18 +08:00
parent 03314b25a4
commit 54117164cd
6 changed files with 292 additions and 4 deletions
@@ -510,6 +510,13 @@ machine's turns with an image anywhere in their messages start as `-p`
then, and text alone is still the interactive mode's. When the redo can't
run (Off meanwhile, the client gone) the failure is a 400, not a 502
(`bridgeFailed`), so neither the client nor the fallback asks it again.
An account Anthropic turned off (its organization disabled, a 400 or
403; on hold, which Claude Code says with no status and `bridgeFailed`
gives a 403; subscription sign-in turned off for the organization; a
flagged account that "can't receive replies from Claude", a 403) is
read as restricted (`claudeAccountOff`, gateway-routing): it rests until
an appeal and the request goes on to the next account or member
(`TestClaudeAccountOffMovesToNextAccount`).
`claude_tui_unpasted_test.go` holds each case, and
`TestShimPaddedImageTakenWithoutMarks` the padded paste on a console that
drops the marks.
File diff suppressed because one or more lines are too long
+225
View File
@@ -0,0 +1,225 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// Anthropic's refusal of a request on a disabled organization, as Claude
// Code's errors page quotes it ("API Error: 400 ... This organization has
// been disabled.") in the API's own error body.
const orgDisabled = `{"type":"error","error":{"type":"invalid_request_error","message":"This organization has been disabled."},"request_id":"req_011CVs3dD7kFz8Rkq2a1bXyZ"}`
// A flagged account's refusal (RiverOnVenus on X got 403s; Claude's apps
// show 「您的账户暂时无法接收 Claude 的回复」).
const cantReceive = `{"type":"error","error":{"type":"permission_error","message":"Your account can't receive replies from Claude right now."}}`
// claudeOffResults are Claude Code's result lines for an account
// Anthropic turned off: its organization disabled (a 400), the claude.ai
// account put on hold (account_on_hold, no status of the API's), and an
// organization that turned off subscription sign-in for Claude Code
// (oauth_org_not_allowed, the API's 403), and a flagged account that
// "can’t receive replies from Claude" (RiverOnVenus on X: a plain 403,
// the apps' 「您的账户暂时无法接收 Claude 的回复」).
var claudeOffResults = map[string]string{
"disabled": ` echo '{"type":"assistant","message":{"id":"x","model":"<synthetic>","role":"assistant","content":[{"type":"text","text":"API Error: 400 {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"This organization has been disabled.\"}}"}]},"error":"invalid_request","request_id":"req_011CVs3dD7kFz8Rkq2a1bXyZ"}'
echo '{"type":"result","subtype":"success","is_error":true,"result":"API Error: 400 {\"type\":\"error\",\"error\":{\"type\":\"invalid_request_error\",\"message\":\"This organization has been disabled.\"},\"request_id\":\"req_011CVs3dD7kFz8Rkq2a1bXyZ\"}","api_error_status":400}'
`,
"on hold": ` echo '{"type":"result","subtype":"success","is_error":true,"result":"Your account is on hold and can'"'"'t use Claude Code. View details or appeal: https://claude.ai/restricted"}'
`,
"org off": ` echo '{"type":"result","subtype":"success","is_error":true,"result":"Your organization has disabled Claude subscription access for Claude Code · Use an Anthropic API key instead, or ask your admin to enable access","api_error_status":403}'
`,
"can't receive": ` echo '{"type":"result","subtype":"success","is_error":true,"result":"API Error: 403 {\"type\":\"error\",\"error\":{\"type\":\"permission_error\",\"message\":\"Your account can’t receive replies from Claude right now.\"}}","api_error_status":403}'
`,
}
// A Claude subscription account Anthropic turned off mid-use (Ramon317317
// on X: a Claude account flagged, and the group didn't move on): the
// request is answered by the spare account, on every route a client
// takes, streamed and not; the account rests as one its vendor
// restricted, and the requests after it go to the spare alone. Before, the
// disabled organization's 400 ended the request at the first account, and
// it was asked again by the next.
func TestClaudeAccountOffMovesToNextAccount(t *testing.T) {
asks := []struct{ path, body string }{
{"/v1/messages", `{"model":"claude/claude-sonnet-5","max_tokens":50,"stream":true,"messages":[{"role":"user","content":"ping"}]}`},
{"/v1/messages", `{"model":"claude/claude-sonnet-5","max_tokens":50,"messages":[{"role":"user","content":"ping"}]}`},
{"/v1/chat/completions", `{"model":"claude/claude-sonnet-5","stream":true,"messages":[{"role":"user","content":"ping"}]}`},
{"/v1/chat/completions", `{"model":"claude/claude-sonnet-5","messages":[{"role":"user","content":"ping"}]}`},
{"/v1/responses", `{"model":"claude/claude-sonnet-5","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`},
{"/v1/responses", `{"model":"claude/claude-sonnet-5","input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`},
}
for name, first := range claudeOffResults {
for i, ask := range asks {
t.Run(name+"/"+ask.path+map[bool]string{true: "/stream", false: "/whole"}[strings.Contains(ask.body, `"stream":true`)], func(t *testing.T) {
log := claudeSubscriptionFirstSays(t, first)
s := New()
code, body := sendTo(s, ask.path, ask.body)
b, _ := os.ReadFile(log)
if runs := strings.Join(strings.Fields(string(b)), ","); code != 200 || !strings.Contains(body, "pong") || runs != "own,tok-spare" {
t.Fatalf("ask %d: status %d: %.400s (runs %q)", i, code, body, runs)
}
r := lastRoute(s)
if len(r.Tries) != 2 || r.Tries[0].Fail != failRestricted || r.Tries[0].Rest == nil || r.Tries[1].Status != 200 {
t.Fatalf("tries: %+v", r.Tries)
}
os.Remove(log)
code, body = sendTo(s, ask.path, ask.body)
b, _ = os.ReadFile(log)
if runs := strings.Join(strings.Fields(string(b)), ","); code != 200 || runs != "tok-spare" {
t.Fatalf("the next request: status %d: %.300s (runs %q, want the spare's alone)", code, body, runs)
}
})
}
}
}
// A group whose first member, a key on Anthropic's API, answers that its
// organization is disabled, as a 400, a 403 or an error event before
// anything is said, has the request answered by the next member on every
// route, streamed and not. Before, the 400 and the event were the
// agent's, and the next member was never asked.
func TestClaudeOrgDisabledGroupMovesOn(t *testing.T) {
refusals := map[string]func(w http.ResponseWriter, stream bool){
"400": func(w http.ResponseWriter, _ bool) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, orgDisabled)
},
"403": func(w http.ResponseWriter, _ bool) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(403)
io.WriteString(w, `{"type":"error","error":{"type":"permission_error","message":"This organization has been disabled."}}`)
},
"403 can't receive": func(w http.ResponseWriter, _ bool) {
w.WriteHeader(403)
io.WriteString(w, cantReceive)
},
"event": func(w http.ResponseWriter, stream bool) {
if !stream {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, orgDisabled)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m1","role":"assistant","model":"m","content":[],"usage":{"input_tokens":3}}}`,
`event: error`+"\n"+`data: `+orgDisabled))
},
}
asks := []struct{ path, body string }{
{"/v1/messages", `{"model":"group/g","max_tokens":50,"stream":true,"messages":[{"role":"user","content":"ping"}]}`},
{"/v1/messages", `{"model":"group/g","max_tokens":50,"messages":[{"role":"user","content":"ping"}]}`},
{"/v1/chat/completions", `{"model":"group/g","stream":true,"messages":[{"role":"user","content":"ping"}]}`},
{"/v1/chat/completions", `{"model":"group/g","messages":[{"role":"user","content":"ping"}]}`},
{"/v1/responses", `{"model":"group/g","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`},
{"/v1/responses", `{"model":"group/g","input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`},
}
for name, refuse := range refusals {
for _, ask := range asks {
t.Run(name+ask.path+map[bool]string{true: "/stream", false: "/whole"}[strings.Contains(ask.body, `"stream":true`)], func(t *testing.T) {
fresh(t)
var asked []string
up := func(id string) string {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
asked = append(asked, id)
stream := gjson.GetBytes(b, "stream").Bool()
if id == "a" {
refuse(w, stream)
return
}
if stream {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, anthropicAnswer)
return
}
w.Header().Set("Content-Type", "application/json")
io.WriteString(w, `{"id":"m2","type":"message","role":"assistant","model":"m","content":[{"type":"text","text":"from b"}],"stop_reason":"end_turn","usage":{"input_tokens":3,"output_tokens":2}}`)
}))
t.Cleanup(srv.Close)
return srv.URL
}
for _, id := range []string{"a", "b"} {
if err := provider.Save(provider.Provider{ID: id, Name: strings.ToUpper(id), Key: "k-" + id, Models: []string{"m"}, Anthropic: up(id)}); err != nil {
t.Fatal(err)
}
}
if err := provider.SaveGroup(provider.Group{Name: "g", Members: []string{"a/m", "b/m"}, Routing: provider.Ordered}); err != nil {
t.Fatal(err)
}
s := New()
code, body := sendTo(s, ask.path, ask.body)
if code != 200 || !strings.Contains(body, "from b") || strings.Join(asked, ",") != "a,b" {
t.Fatalf("status %d: %.400s (asked %v)", code, body, asked)
}
// these members are relays (not api.anthropic.com): the
// refusal is about the relay's account behind it, so the
// member rests as any failure, not as restricted
if r := lastRoute(s); len(r.Tries) != 2 || r.Tries[0].Fail == failRestricted || r.Tries[0].Rest == nil {
t.Fatalf("the refusing relay member: %+v", r.Tries)
}
})
}
}
}
// Which accounts are read as turned off by Anthropic: a Claude
// subscription's and a key on Anthropic's own API, not a relay's in front
// of it, nor another subscription's; and not the refusals that are about
// what was asked, which every account gives alike.
func TestClaudeAccountOffScoped(t *testing.T) {
claude := provider.Provider{ID: "claude", Account: &provider.Account{Agent: "claude", User: "me@example.com"}}
direct := provider.Provider{ID: "k", Key: "sk", Anthropic: "https://api.anthropic.com"}
relay := provider.Provider{ID: "r", Key: "sk", Anthropic: "https://relay.example.com"}
codex := provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex", User: "me@example.com"}}
for _, c := range []struct {
p provider.Provider
status int
body string
want bool
}{
{claude, 400, orgDisabled, true},
{direct, 400, orgDisabled, true},
{direct, 403, `{"type":"error","error":{"type":"permission_error","message":"OAuth authentication is currently not allowed for this organization."}}`, true},
{claude, 502, `{"error":{"message":"Your account is on hold and can't use Claude Code. View details or appeal: https://claude.ai/restricted"}}`, false},
{claude, 400, `{"error":{"message":"Your account is on hold and can't use Claude Code. View details or appeal: https://claude.ai/restricted"}}`, true},
{claude, 403, cantReceive, true},
{direct, 403, cantReceive, true},
{claude, 403, strings.ReplaceAll(cantReceive, "can't", "can’t"), true},
{claude, 403, strings.ReplaceAll(cantReceive, "can't", "cannot"), true},
{relay, 403, cantReceive, false},
{relay, 400, orgDisabled, false},
{codex, 400, orgDisabled, false},
{claude, 400, `{"type":"error","error":{"type":"invalid_request_error","message":"Third-party apps now draw from your extra usage, not your plan limits."}}`, false},
{claude, 400, `{"type":"error","error":{"type":"invalid_request_error","message":"Claude Code is unable to respond to this request, which appears to violate our Usage Policy"}}`, false},
} {
if got := claudeAccountOff(c.p, c.status, []byte(c.body)); got != c.want {
t.Errorf("%s %d %.80s: %v, want %v", c.p.ID, c.status, c.body, got, c.want)
}
if got := failureOf(candidate{p: c.p}, c.status, []byte(c.body)) == failRestricted; got != c.want {
t.Errorf("%s %d %.80s: restricted %v, want %v", c.p.ID, c.status, c.body, got, c.want)
}
if c.want && riskRefused(candidate{p: c.p}, c.status, nil, []byte(c.body)) {
t.Errorf("%s %d: the provider's other accounts are left out", c.p.ID, c.status)
}
}
// the request isn't at fault: another member may serve it; the
// third-party refusal stays the agent's (#4503)
if !retryable(403, []byte(cantReceive)) {
t.Error("a flagged account's 403 isn't asked of the next member")
}
if !retryable(400, []byte(orgDisabled)) {
t.Error("a disabled organization's 400 isn't asked of the next member")
}
if retryable(400, []byte(`{"type":"error","error":{"type":"invalid_request_error","message":"Third-party apps now draw from your extra usage, not your plan limits."}}`)) {
t.Error("the third-party refusal is asked of the next member")
}
}
+6
View File
@@ -7724,6 +7724,12 @@ func bridgeFailed(name, msg string, status int) (int, string) {
return status, msg
case quotaSaid(msg):
return 429, msg
case name == "Claude Code" && claudeOffWords.MatchString(msg):
// the account on hold, as Claude Code says it with no status of
// the API's (account_on_hold): a 502 rested it a minute and asked
// it again; the account's own refusal, read as restricted
// (claudeAccountOff)
return http.StatusForbidden, msg
case unpastedSaid(name, msg):
// the same message fails the same way on every account and on
// every try: a 502 was asked again and again (ok123now on X)
+12 -2
View File
@@ -2010,9 +2010,14 @@ func elsewhere(left []candidate, c candidate) []candidate {
// Google's suspension of an account for its terms (googleSuspended): it
// says the service was disabled in this account before the request came,
// a ruling on the account, not on what was sent, so the provider's other
// accounts are asked (bestony on Discord).
// accounts are asked (bestony on Discord). Nor does Anthropic's disabling
// of a Claude account or organization (claudeAccountOff): the same.
func riskRefused(c candidate, status int, header http.Header, body []byte) bool {
return failureOf(c, status, body) == failRestricted && !remoteModelRest(c, failRestricted, header) && !googleSuspended(c.p, carriedStatus(status, body), body)
if failureOf(c, status, body) != failRestricted || remoteModelRest(c, failRestricted, header) {
return false
}
status = carriedStatus(status, body)
return !googleSuspended(c.p, status, body) && !claudeAccountOff(c.p, status, body)
}
// elsewhereWeighed is elsewhere on a list of candidates beside their
@@ -2066,6 +2071,11 @@ func retryable(status int, body []byte) bool {
// 6,467 points and the empty one was never rested (#4095,
// mycf_711)
return true
case status >= 400 && status < 500 && claudeOffWords.Match(body):
// the account turned off (its organization disabled, on hold):
// nothing about the request, which another member may serve. A
// 400, it ended the group at the disabled account (Ramon317317)
return true
case status >= 400 && status < 500 && refusedWords.Match(body):
// the vendor turning the agent's prompt away, at whatever 4xx it
// picks: the AutoClaw plugin's 406 (plugins#1094) as much as
+41 -1
View File
@@ -741,7 +741,47 @@ func restrictedRefused(p provider.Provider, status int, body []byte) bool {
if restrictedSaid(status, body) {
return true
}
return isWorkBuddy(p) && provider.WBRestricted(status, wordsOf(body)) || googleSuspended(p, status, body)
return isWorkBuddy(p) && provider.WBRestricted(status, wordsOf(body)) || googleSuspended(p, status, body) || claudeAccountOff(p, status, body)
}
// claudeOffWords are Anthropic's, and Claude Code's, words for an account
// that can serve nothing more: its organization disabled ("API Error: 400
// {"type":"error","error":{"type":"invalid_request_error","message":"This
// organization has been disabled."}}", Claude Code's errors page; the
// same as a 403 permission_error), the claude.ai account put on hold
// ("Your account is on hold and can't use Claude Code. View details or
// appeal: https://claude.ai/restricted", account_on_hold), and an
// organization that turned off Claude subscription sign-in for Claude
// Code (oauth_org_not_allowed; the API's "OAuth authentication is
// currently not allowed for this organization."), and a flagged account's
// "Your account can't receive replies from Claude right now" (Claude's
// apps show it as 「您的账户暂时无法接收 Claude 的回复」; RiverOnVenus on X
// got 403s in a group with it; the English words are from a user's report,
// not Anthropic's docs). Either apostrophe, or "cannot". None is about the
// model or what was asked: the same request is served by another account.
var claudeOffWords = lazyre.New(`(?i)this organization has been disabled|account is on hold and can(?:'|\x{2019}|no)t use Claude|organization has disabled Claude subscription access|OAuth authentication is currently not allowed for this organization|account can(?:'|\x{2019}|no)t receive (?:replies|responses) from Claude`)
// claudeAccountOff says Anthropic turned p, a Claude subscription account
// or a key on Anthropic's own API, off (claudeOffWords). Read as any
// failure, a disabled account answered 400 and its group stopped there,
// its next members never asked (Ramon317317 on X: a Claude account
// flagged mid-use, and the group didn't move on); now it rests as one its
// vendor restricted, until an appeal, and the request goes on to the
// next member and the provider's other accounts (riskRefused leaves them
// in). A relay's same words are about the relay's own account behind it,
// and its other keys may still answer: read as any failure there.
func claudeAccountOff(p provider.Provider, status int, body []byte) bool {
if status < 400 || status >= 500 {
return false
}
if a := p.Account; a != nil {
if a.Agent != "claude" {
return false
}
} else if provider.HostOf(p.Base(provider.Anthropic)) != "api.anthropic.com" {
return false
}
return claudeOffWords.Match(wordsOf(body))
}
// googleToS is Google's 403 PERMISSION_DENIED for a Code Assist account it