fix(gateway): an account Antigravity turned away doesn't rest (#873)
* fix(gateway): an account Antigravity turned away doesn't rest
A 429 that is Antigravity refusing Claude Code's or its Agent SDK's
system instruction — "Resource has been exhausted (e.g. check quota)"
whatever quota the account has left (#666) — carries the word "quota",
so it was classified failQuota: the account rested 15 minutes and had
its usage asked of Google again, while it answers titles, background
requests and Codex normally.
Carry the fact the error path already works out from —
antigravityTurnsAway(request.System) and the CodeAssist agent, what the
8c652a83 hint is computed from — into the routing decision, the way
sharedPool and refused already carry an upstream routing fact through
error translation. The held attempt is marked on either failure path,
not only on a 429: the refusal also arrives as an in-stream error event,
which skips the 4xx branch and returns 200 while still failing the
attempt, and usedUpWords doesn't look at the status either. Where the
attempt then fails on that mark, the next member is asked first and
restAfterMarked is never called, as for a refusal — nobody rests and
nobody's usage is re-queried.
A 429 that really is the plan used up, with no such system prompt
asking, still rests the account and re-queries its usage, as it did
(#147, #530).
* fix(gateway): only the refusal leaves an Antigravity account alone
The mark was wider than the refusal it describes (yetone's review of
#873): it was set for any status >= 400, and for any failed stream,
whenever the system prompt was Claude Code's. A 500, 503 or 403 on such
a turn was therefore told as a refusal and never set the account aside,
and the account's 4xx handling below it was skipped for those requests.
The mark now goes on the refusal itself: a 429, or an in-stream error
event saying "Resource has been exhausted". The latter needs its own
predicate, since the Code Assist decoder keeps only the error's message
and leaves its status and code out of the event.
Two more of the review:
- the refused attempt now writes a usage.Record, as the hw.refused
branch it is modelled on does, so these 429s stay in the ledger;
- the member's other Antigravity accounts are asked last rather than
first, by matesLast, the inverse of matesFirst: they carry the same
system prompt, so each is turned away just the same, and asking them
first spent a round-trip apiece before the group reached a member
that answers.
TestAntigravityTurnedAwayIsOnlyTheRefusal, ...StillLandsInTheLedger
and ...LeavesItsMatesForLast fail on the previous revision of this
branch for each of these reasons.
* fix(gateway): the refusal said inside a reply that isn't streamed
The mark was inside translate's `if stream` block, so a client that
doesn't ask for a stream — and a stream that isn't held — never set it:
the same "Resource has been exhausted" said as an in-stream error event
still rested the account 15 minutes on those requests.
A test for that path first: TestAntigravityTurnedAwaySaidInsideTheReply
drives a 200 that opens with the error event, and pairs it with an error
event of another kind, which still rests the account. The first half
failed on the previous commit for exactly this reason.
Both error paths now go through markAntigravityRefused, which decides
from what the failure said rather than repeating the four conditions at
each return: the Code Assist decoder keeps only the error's message, so
an in-stream refusal is recognised by its text, while a 429 is
recognised by its status as before.
This commit is contained in:
@@ -0,0 +1,316 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/usage"
|
||||
)
|
||||
|
||||
// turnedAway is Antigravity's answer to Claude Code's and the Agent SDK's
|
||||
// system prompt: a 429 that reads as a used-up plan whatever the quota
|
||||
// left, on every model (#666: Claude Desktop's chats always 429 while its
|
||||
// titles and Codex on the same account answer). magpie says why, and now
|
||||
// also leaves the account alone, since nothing is wrong with it.
|
||||
const turnedAway = `{"error":{"code":429,"message":"Resource has been exhausted (e.g. check quota).","status":"RESOURCE_EXHAUSTED"}}`
|
||||
|
||||
// claudeCodeSystem is Claude Code's, as 2.1.288 sends it: its billing line
|
||||
// or the SDK's identity line anywhere in the system instruction.
|
||||
const claudeCodeSystem = "x-anthropic-billing-header: cc_version=2.1.288.e3f; cc_entrypoint=sdk-cli;\nYou are Claude Code, Anthropic's official CLI for Claude."
|
||||
|
||||
// antigravityTurnedAwayGroup is a routing group whose first member holds the
|
||||
// Antigravity accounts signed in at users, and whose second — "other", another
|
||||
// provider altogether, not a mate of Antigravity's — answers anything, so the
|
||||
// first has someone else to fail over to. say is what those accounts' upstream
|
||||
// answers. The second value counts how often an account's usage was asked of
|
||||
// the vendor again.
|
||||
func antigravityTurnedAwayGroup(t *testing.T, users []string, say func(w http.ResponseWriter, r *http.Request)) (*Server, *int) {
|
||||
t.Helper()
|
||||
fresh(t)
|
||||
var logins []map[string]any
|
||||
for _, user := range users {
|
||||
logins = append(logins, map[string]any{
|
||||
"agent": "antigravity", "user": user, "on": true,
|
||||
"auth": map[string]any{"access_token": user, "refresh_token": "ref-" + user, "project": "p1",
|
||||
"expiry_date": time.Now().Add(time.Hour).UnixMilli()},
|
||||
})
|
||||
}
|
||||
dir := filepath.Dir(provider.Path())
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "logins.json"), mustJSON(logins), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
old := http.DefaultClient
|
||||
http.DefaultClient = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {
|
||||
var body string
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "latest-arm64-mac.yml"):
|
||||
body = "version: 2.9.1\n"
|
||||
case strings.Contains(r.URL.Path, ":loadCodeAssist"):
|
||||
body = `{"currentTier":{"id":"standard-tier"},"cloudaicompanionProject":"p1"}`
|
||||
case strings.Contains(r.URL.Path, ":fetchAvailableModels"):
|
||||
body = `{"models":{"m":{}}}`
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected request to %s", r.URL)
|
||||
}
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body))}, nil
|
||||
})}
|
||||
t.Cleanup(func() { http.DefaultClient = old })
|
||||
p, err := provider.Find("antigravity")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := p.Fetch(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"m1","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`,
|
||||
`event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
|
||||
`event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from the other"}}`,
|
||||
`event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
|
||||
`event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":3}}`,
|
||||
`event: message_stop`+"\n"+`data: {"type":"message_stop"}`))
|
||||
}))
|
||||
t.Cleanup(other.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "other", Name: "Other", Key: "k", Models: []string{"m"}, Anthropic: other.URL}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{Name: "G", Members: []string{"antigravity/m", "other/m"}, Routing: provider.Ordered}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
askedUsage := new(int)
|
||||
oldAsk := staleAllowance
|
||||
staleAllowance = func(agent, user string) { *askedUsage++ }
|
||||
t.Cleanup(func() { staleAllowance = oldAsk })
|
||||
s := New()
|
||||
// the Antigravity accounts' own upstream, which only the gateway asks;
|
||||
// any other member is answered by its own test server
|
||||
s.client = &http.Client{Transport: countTransport(func(r *http.Request) (*http.Response, error) {
|
||||
if !strings.Contains(r.URL.Host, "googleapis.com") {
|
||||
return http.DefaultTransport.RoundTrip(r)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
say(rec, r)
|
||||
return rec.Result(), nil
|
||||
})}
|
||||
return s, askedUsage
|
||||
}
|
||||
|
||||
// claudeTurn is a turn as Claude Code sends it on the group, with system
|
||||
// as the system instruction the client asked for.
|
||||
func claudeTurn(system string) string {
|
||||
return `{"model":"group/g","max_tokens":100,"system":` + quote(system) + `,"messages":[{"role":"user","content":"hi"}]}`
|
||||
}
|
||||
|
||||
// turnOn posts a turn to this gateway and says what came back.
|
||||
func turnOn(t *testing.T, s *Server, body string) (int, string) {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
|
||||
return rec.Code, rec.Body.String()
|
||||
}
|
||||
|
||||
// the account Antigravity turned away is healthy: it rests no quarter of
|
||||
// an hour for a request it refused, its usage isn't asked again, and the
|
||||
// next turn asks it first again — as the refusal it is, not a spent quota.
|
||||
func TestAntigravityTurnedAwayRestsNobody(t *testing.T) {
|
||||
s, askedUsage := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, turnedAway)
|
||||
})
|
||||
code, out := turnOn(t, s, claudeTurn(claudeCodeSystem))
|
||||
if code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the turn: %d %s", code, out)
|
||||
}
|
||||
r := lastRoute(s)
|
||||
if len(r.Tries) != 2 || r.Tries[0].Status != 429 || r.Tries[0].Fail != failRefused || r.Tries[0].Rest != nil {
|
||||
t.Fatalf("the turned-away try: %+v", r.Tries)
|
||||
}
|
||||
if !strings.Contains(r.Tries[0].Error, antigravityTurnedAwayHint) {
|
||||
t.Fatalf("the attempt isn't told why: %s", r.Tries[0].Error)
|
||||
}
|
||||
if *askedUsage != 0 {
|
||||
t.Fatalf("the account's usage was asked again %d times for a request it refused", *askedUsage)
|
||||
}
|
||||
if _, ok := restOf("antigravity@u@example.com"); ok {
|
||||
t.Fatalf("antigravity@u@example.com rests for a request it answered with a refusal: %v", rests())
|
||||
}
|
||||
// the same account is asked first again on the next turn
|
||||
code, out = turnOn(t, s, claudeTurn(claudeCodeSystem))
|
||||
if code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the next turn: %d %s", code, out)
|
||||
}
|
||||
if r := lastRoute(s); len(r.Tries) != 2 || r.Tries[0].ID != "antigravity" || r.Tries[0].Status != 429 {
|
||||
t.Fatalf("the next turn asked %+v first", r.Tries)
|
||||
}
|
||||
}
|
||||
|
||||
// A 429 that really is the plan used up — no such system prompt asking —
|
||||
// still rests the account, as it did (#147, #530).
|
||||
func TestAntigravityQuotaStillRests(t *testing.T) {
|
||||
s, askedUsage := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, turnedAway)
|
||||
})
|
||||
code, out := turnOn(t, s, claudeTurn("You are a helpful assistant."))
|
||||
if code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the turn: %d %s", code, out)
|
||||
}
|
||||
r := lastRoute(s)
|
||||
if len(r.Tries) != 2 || r.Tries[0].Status != 429 || r.Tries[0].Fail != failQuota || r.Tries[0].Rest == nil {
|
||||
t.Fatalf("the used-up try: %+v", r.Tries)
|
||||
}
|
||||
if d := time.Until(r.Tries[0].Rest.Until); d < 14*time.Minute || d > 15*time.Minute {
|
||||
t.Fatalf("rests %v, not the 15 minutes a used-up plan takes", d)
|
||||
}
|
||||
if *askedUsage != 1 {
|
||||
t.Fatalf("the account's usage was asked again %d times, once as it was", *askedUsage)
|
||||
}
|
||||
if _, ok := restOf("antigravity@u@example.com"); !ok {
|
||||
t.Fatal("antigravity@u@example.com doesn't rest for a plan used up")
|
||||
}
|
||||
}
|
||||
|
||||
// Only the refusal itself leaves the account alone. A Claude Code turn is
|
||||
// no excuse for an account that really is broken, overloaded or denied: it
|
||||
// rests as it would on any other request (the maintenance review of #873).
|
||||
func TestAntigravityTurnedAwayIsOnlyTheRefusal(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
fail string
|
||||
}{
|
||||
{"500 INTERNAL", http.StatusInternalServerError, `{"error":{"code":500,"message":"internal error","status":"INTERNAL"}}`, failOther},
|
||||
{"503 UNAVAILABLE", http.StatusServiceUnavailable, `{"error":{"code":503,"message":"unavailable","status":"UNAVAILABLE"}}`, failOther},
|
||||
{"403 PERMISSION_DENIED", http.StatusForbidden, `{"error":{"code":403,"message":"denied","status":"PERMISSION_DENIED"}}`, failOther},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, _ := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tc.status)
|
||||
io.WriteString(w, tc.body)
|
||||
})
|
||||
code, out := turnOn(t, s, claudeTurn(claudeCodeSystem))
|
||||
if code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the turn: %d %s", code, out)
|
||||
}
|
||||
r := lastRoute(s)
|
||||
if len(r.Tries) != 2 || r.Tries[0].Status != tc.status || r.Tries[0].Fail != tc.fail || r.Tries[0].Rest == nil {
|
||||
t.Fatalf("a %d on a Claude Code turn isn't the refusal: %+v", tc.status, r.Tries)
|
||||
}
|
||||
if _, ok := restOf("antigravity@u@example.com"); !ok {
|
||||
t.Fatalf("antigravity@u@example.com doesn't rest for a %d, as it wouldn't on any other request", tc.status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The refusal costs the account nothing, but it still happened, and the
|
||||
// ledger keeps it: a Claude Code turn's 429 is as visible as any other
|
||||
// failed call (the maintenance review of #873).
|
||||
func TestAntigravityTurnedAwayStillLandsInTheLedger(t *testing.T) {
|
||||
s, _ := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, turnedAway)
|
||||
})
|
||||
if code, out := turnOn(t, s, claudeTurn(claudeCodeSystem)); code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the turn: %d %s", code, out)
|
||||
}
|
||||
rows, _, _ := usage.Ledger(usage.All, usage.Filter{Provider: "antigravity"})
|
||||
if len(rows) == 0 {
|
||||
t.Fatal("the refusal is in no usage row")
|
||||
}
|
||||
for _, row := range rows {
|
||||
if row.Status == http.StatusTooManyRequests && row.Failed() {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("no 429 row of the refusal among %d: %+v", len(rows), rows)
|
||||
}
|
||||
|
||||
// Its mates are asked last, not first: they carry the same system prompt,
|
||||
// so each of them is turned away just the same, and asking them first costs
|
||||
// a round-trip apiece before the group reaches the member that answers
|
||||
// (the maintenance review of #873).
|
||||
func TestAntigravityTurnedAwayLeavesItsMatesForLast(t *testing.T) {
|
||||
s, _ := antigravityTurnedAwayGroup(t, []string{"u@example.com", "v@example.com"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
io.WriteString(w, turnedAway)
|
||||
})
|
||||
if code, out := turnOn(t, s, claudeTurn(claudeCodeSystem)); code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the turn: %d %s", code, out)
|
||||
}
|
||||
r := lastRoute(s)
|
||||
if len(r.Tries) != 2 {
|
||||
t.Fatalf("asked %d times: the second account of the member was asked before the one that answers: %+v", len(r.Tries), r.Tries)
|
||||
}
|
||||
if r.Tries[0].ID != "antigravity" || r.Tries[0].Status != 429 || r.Tries[1].ID != "other" {
|
||||
t.Fatalf("asked: %+v", r.Tries)
|
||||
}
|
||||
for _, user := range []string{"u@example.com", "v@example.com"} {
|
||||
if _, ok := restOf("antigravity@" + user); ok {
|
||||
t.Fatalf("antigravity@%s rests for a request it was turned away from", user)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The refusal also comes said inside the reply: a 200 that opens with the
|
||||
// same error event, where the Code Assist decoder keeps only its message.
|
||||
// It leaves the account alone as the 429 does, and an error event of any
|
||||
// other kind still rests it.
|
||||
func TestAntigravityTurnedAwaySaidInsideTheReply(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body string
|
||||
rest bool
|
||||
}{
|
||||
{"the refusal", `data: {"error":{"message":"Resource has been exhausted (e.g. check quota)."}}`, false},
|
||||
{"another error", `data: {"error":{"message":"api key not valid"}}`, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, _ := antigravityTurnedAwayGroup(t, []string{"u@example.com"}, func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(tc.body))
|
||||
})
|
||||
if code, out := turnOn(t, s, claudeTurn(claudeCodeSystem)); code != 200 || !strings.Contains(out, "from the other") {
|
||||
t.Fatalf("the turn: %d %s", code, out)
|
||||
}
|
||||
r := lastRoute(s)
|
||||
if len(r.Tries) != 2 || r.Tries[1].Status != 200 {
|
||||
t.Fatalf("the turn: %+v", r.Tries)
|
||||
}
|
||||
_, resting := restOf("antigravity@u@example.com")
|
||||
if resting != tc.rest {
|
||||
t.Fatalf("rests %v, want %v: %+v", resting, tc.rest, r.Tries)
|
||||
}
|
||||
if want := failRefused; !tc.rest && r.Tries[0].Fail != want {
|
||||
t.Fatalf("the refusal said inside the reply: Fail=%q: %+v", r.Tries[0].Fail, r.Tries)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// rests is what rests now, to say it when nothing should.
|
||||
func rests() map[string]time.Time {
|
||||
restingUntil.Lock()
|
||||
defer restingUntil.Unlock()
|
||||
out := map[string]time.Time{}
|
||||
for k, v := range restingUntil.m {
|
||||
if v.After(time.Now()) {
|
||||
out[k] = v
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -52,6 +52,14 @@ func antigravityTurnsAway(system string) bool {
|
||||
strings.Contains(system, "built on Anthropic's Claude Agent SDK")
|
||||
}
|
||||
|
||||
// antigravityRefuses is what Antigravity says when it turns such a request
|
||||
// away, on either shape the refusal arrives in: a 429's body, or the reply's
|
||||
// own error event, where the Code Assist decoder keeps the message and leaves
|
||||
// the status and its code out of the event.
|
||||
func antigravityRefuses(said string) bool {
|
||||
return strings.Contains(strings.ToLower(said), "resource has been exhausted")
|
||||
}
|
||||
|
||||
const antigravityTurnedAwayHint = "not a quota: Antigravity turns away Claude Code's and the Claude Agent SDK's system prompt (Claude Code, Claude Desktop's chats) with this 429; use another provider for them"
|
||||
|
||||
// codeAssistID is the id a request on the account's app goes out under: on
|
||||
|
||||
@@ -820,6 +820,30 @@ func matesFirst(left []candidate, c candidate) {
|
||||
copy(left, append(mates, others...))
|
||||
}
|
||||
|
||||
// matesLast puts last, of the candidates left, the other keys or accounts
|
||||
// of the member c is of: what turns one of them away is in the request, so
|
||||
// it turns them all away the same, and the group is better spent on a
|
||||
// member that answers (#666). Antigravity refuses Claude Code's and its
|
||||
// Agent SDK's system prompt whichever account is asked.
|
||||
func matesLast(left []candidate, c candidate) {
|
||||
mate := func(x candidate) bool {
|
||||
if x.p.ID != c.p.ID || x.model != c.model || x.effort != c.effort || x.who() == c.who() {
|
||||
return false
|
||||
}
|
||||
_, resting := restOf(x.restKey())
|
||||
return !resting
|
||||
}
|
||||
var mates, others []candidate
|
||||
for _, x := range left {
|
||||
if mate(x) {
|
||||
mates = append(mates, x)
|
||||
} else {
|
||||
others = append(others, x)
|
||||
}
|
||||
}
|
||||
copy(left, append(others, mates...))
|
||||
}
|
||||
|
||||
// holdWriter keeps an error reply back while another provider may still
|
||||
// answer: headers and body wait until release, or are dropped for the next
|
||||
// try. Anything else goes straight through — but for a stream, only once
|
||||
@@ -842,6 +866,11 @@ type holdWriter struct {
|
||||
failMsg string
|
||||
sharedPool bool // an OpenRouter upstream pool rejected this attempt
|
||||
|
||||
// turnedAway: the account is asked with the system prompt Antigravity
|
||||
// answers with a 429 whatever quota it has left — Claude Code's, its
|
||||
// Agent SDK's — so the account isn't at fault and doesn't rest (#666)
|
||||
turnedAway bool
|
||||
|
||||
// refused: the vendor's safety filter ended the reply before any of it
|
||||
// was said — Anthropic's stop_reason "refusal", OpenAI's content_filter
|
||||
// — which another account or model may answer (#248)
|
||||
|
||||
@@ -1767,6 +1767,43 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !last && hw.failed() && hw.turnedAway {
|
||||
// another member may answer what this account was turned away
|
||||
// from, and this one isn't set aside: Antigravity refused the
|
||||
// request, whatever quota the account has left, so nothing is
|
||||
// wrong with it and no usage is asked again (#666). Its own
|
||||
// mates are asked last, not first: they carry the same system
|
||||
// prompt, so each is turned away just the same before the group
|
||||
// reaches a member that answers
|
||||
try.Fail = failRefused
|
||||
s.trace.update(tr, func(t *Route) {
|
||||
t.Tries[len(t.Tries)-1] = try
|
||||
if call.To != "" {
|
||||
t.Usage = append(t.Usage, routeUsage(call.Provider, c.model, call.Usage)...)
|
||||
}
|
||||
})
|
||||
skipped = append(skipped, c.label()+": "+call.Error)
|
||||
matesLast(cands[i+1:], c)
|
||||
if call.To != "" {
|
||||
rec := usage.Record{RouteID: tr.ID, Time: began, Agent: call.Agent, Via: call.Via, Provider: call.Provider, Host: where, Model: c.model,
|
||||
ProviderKeyID: providerKeyID, ProviderKeyName: providerKeyName, ProviderAccount: providerAccount,
|
||||
Requested: call.Model, Served: call.Usage.Served,
|
||||
Input: call.Usage.Input, Output: call.Usage.Output, CacheRead: call.Usage.CacheRead,
|
||||
CacheWrite: call.Usage.CacheWrite, Reasoning: call.Usage.Reasoning, Effort: sent, Millis: time.Since(began).Milliseconds(), Status: call.Status,
|
||||
TTFT: try.TTFT, FirstText: try.FirstText, Session: sessionOf(r.Header), NativeSession: nativeSessionOf(r.Header), Kind: call.Kind,
|
||||
RequestID: call.Usage.RequestID, Endpoint: endpointOf(r, from, call.To), Archive: call.archiveName()}
|
||||
failedWith(&rec, call.Status, call.Error, call.Usage.ErrType)
|
||||
// what this account answered is its refusal, the reply
|
||||
// captured so far being no one's yet
|
||||
refusal := &Call{RequestBody: call.RequestBody, RequestTruncated: call.RequestTruncated, ResponseBody: string(hw.errBody())}
|
||||
if call.otelIn != nil {
|
||||
refusal.otelIn, refusal.otelOut = call.otelIn, hw.errBody()
|
||||
}
|
||||
withBodies(&rec, refusal)
|
||||
appendUsage(r, rec)
|
||||
}
|
||||
continue
|
||||
}
|
||||
if c.p.Account != nil && !hw.passing && hw.code() >= 400 && hw.code() < 500 && modelTakes(c, sent) {
|
||||
if takes, ok := effortRefused(hw.errBody(), sent); ok {
|
||||
// the account's plan doesn't take the level, which the
|
||||
@@ -2198,6 +2235,29 @@ func markOpenRouterSharedPool(w http.ResponseWriter) {
|
||||
}
|
||||
}
|
||||
|
||||
// markAntigravityTurnsAway keeps in the held attempt that the account was
|
||||
// asked with the system prompt Antigravity turns away, so a failure on it
|
||||
// isn't held against the account.
|
||||
func markAntigravityTurnsAway(w http.ResponseWriter) {
|
||||
if h, ok := w.(*holdWriter); ok {
|
||||
h.turnedAway = true
|
||||
}
|
||||
}
|
||||
|
||||
// markAntigravityRefused marks the attempt when what the account said is the
|
||||
// refusal Antigravity answers such a system prompt with. said is what the
|
||||
// failure said once the status is gone: the 429's body arrives with its 429,
|
||||
// and the reply's own error event arrives with 200 from translate and only
|
||||
// its message, the Code Assist decoder keeping neither its code nor its
|
||||
// status. An error event of any other kind says something else and marks
|
||||
// nothing.
|
||||
func markAntigravityRefused(w http.ResponseWriter, p provider.Provider, system, said string) {
|
||||
if said == "" || !antigravityRefuses(said) || accountAgent(p) != "antigravity" || !antigravityTurnsAway(system) {
|
||||
return
|
||||
}
|
||||
markAntigravityTurnsAway(w)
|
||||
}
|
||||
|
||||
// forward sends a request to the provider. On Anthropic's messages, a
|
||||
// provider that turns away betas it doesn't know by name (Bedrock's: 400
|
||||
// Unexpected value(s) `x` for the `anthropic-beta` header) is asked again
|
||||
@@ -3276,6 +3336,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
msg := p.Explain(p.Name+": "+provider.APIError(b, res.Status), res.StatusCode, b)
|
||||
if res.StatusCode == http.StatusTooManyRequests && accountAgent(p) == "antigravity" && antigravityTurnsAway(request.System) {
|
||||
msg += " — " + antigravityTurnedAwayHint
|
||||
markAntigravityTurnsAway(w)
|
||||
}
|
||||
if p.Preset == "openrouter" && openRouterSharedPool(b) {
|
||||
markOpenRouterSharedPool(w)
|
||||
@@ -3356,6 +3417,10 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
failed = p.Name + ": " + emptyReply
|
||||
enc.event(Event{Kind: KError, Text: failed})
|
||||
}
|
||||
if failed != "" {
|
||||
// the same refusal as the 429's, said inside the reply
|
||||
markAntigravityRefused(w, p, request.System, failed)
|
||||
}
|
||||
if failed == "" {
|
||||
for _, ev := range kept {
|
||||
enc.event(ev)
|
||||
@@ -3380,6 +3445,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
return writeError(w, from, 502, msg), msg
|
||||
}
|
||||
if col.err != "" && !saidAnything(col.res.Parts) {
|
||||
markAntigravityRefused(w, p, request.System, col.err)
|
||||
return writeError(w, from, 502, p.Name+": "+col.err), col.err
|
||||
}
|
||||
if empty && !saidAnything(col.res.Parts) && answersNothing(col.res.Stop) {
|
||||
|
||||
Reference in New Issue
Block a user