gateway: every ChatGPT account used up reaches Codex as the backend's usage_limit_reached
bitssly on X (11-06): with Codex's quota used up, the Codex app on Windows flickered and errored, and only a restart fixed it. With two or more ChatGPT accounts on, Codex's turn is routed through serve. When every account refused with the backend's 429 usage_limit_reached (or 403 usage_not_included), passthrough wrote it through writeVendorError. That re-typed it as rate_limit_error and dropped the x-codex-* headers. codex-rs's api_bridge maps only usage_limit_reached to UsageLimitReached (plan, reset, windows from the x-codex-* headers). Any other 429 is a retryable status ending in "exceeded retry limit, last status 429", so the app had no limit or reset to show. On one account the refusal was already relayed as sent. codexOutRefusal/writeCodexOut (codex_out_reply.go) now relay a ChatGPT account's usage_limit_reached/usage_not_included on Responses as the backend wrote it: its status, its error object (plan_type, resets_at kept as written, through json.Number) with magpie's message, and its x-codex-* headers. A rate_limit_exceeded 429, a key's 429 and other protocols keep magpie's shape. Turns held before any account is asked (a cap the user set, credits not to be spent) keep rate_limit_error and magpie's advice: Codex shows no message on a usage_limit_reached, and TestCodexNoCreditsEveryAccount guards that advice. The full-window "hit a snag" page itself is the #4550 class: magpie ends the app-server at the used-up takeover or a switch off a spent account, and the ChatGPT app's identity check throws. v0.1.3045 and later reopen the app when it logged fatal_error_broadcasted. That still needs bitssly's version and logs to confirm. Run at origin/main8f69ca29cplus this, on mote: - gofmt -l internal/gateway: nothing - go vet ./..., GOOS=linux go vet -tags nogui ./..., GOOS=windows go vet ./..., go build, GOOS=linux go build -tags nogui, GOOS=windows go build: ok - go test -tags nogui -count=1 -timeout 45m ./internal/gateway: ok (1154s) On xiaomi-gpu (win-run): TestCodexEveryAccountOutToldAsTheBackend, TestCodexRateLimitNotToldAsUsedUp and TestCodexOneAccountSpent*: ok. Rebased on303a31dd6(37c1bc043touched provider and a gateway test), then at the pushed head on mote: go build, go vet ./internal/gateway ./internal/provider, go test -tags nogui -run "Codex|Group" ./internal/gateway: ok. Broken by hand: with the codexOutRefusal call disabled, TestCodexEveryAccountOutToldAsTheBackend/usage_limit_reached is red (type rate_limit_error, plan_type/resets_at missing, no x-codex-* headers on either turn). Not tried: the full go test ./... (mote at load 428 with two full suites queued on suite.lock; this changes only internal/gateway); a real Codex app against a used-up account; a usage_limit_reached that arrives in-stream after a 200 (response.failed), which this doesn't change.
This commit is contained in:
@@ -0,0 +1,80 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A turn on one of magpie's ChatGPT accounts that the ChatGPT backend
|
||||
// refuses as the account's usage limit (429 usage_limit_reached) or as a
|
||||
// plan without Codex (usage_not_included) reaches the agent in the
|
||||
// backend's own shape: the error's type, plan_type, resets_at and
|
||||
// resets_in_seconds as the backend said them, and its x-codex-* headers
|
||||
// (the windows' used percents and resets). Codex reads the limit from
|
||||
// exactly those (codex-rs codex-api api_bridge.rs: a 429 whose error type
|
||||
// is usage_limit_reached is UsageLimitReached, with its plan, its reset
|
||||
// and the rate limits parsed from the x-codex-* headers). Re-typed as
|
||||
// magpie's rate_limit_error, with the headers left behind, Codex read the
|
||||
// same 429 as a retryable one: it asked again, then stopped on "exceeded
|
||||
// retry limit, last status: 429" with no reset time and no limit for the
|
||||
// app to show (bitssly on X, the ChatGPT app on Windows with every Codex
|
||||
// account out). Only the message is magpie's (the provider named), as
|
||||
// every other vendor error's is.
|
||||
//
|
||||
// A turn magpie holds before asking any account (each at a usage cap the
|
||||
// user set, or used up and set not to spend its credits) keeps magpie's
|
||||
// words and type: those say which setting to change, and Codex shows a
|
||||
// usage_limit_reached in its own words alone.
|
||||
|
||||
// codexOutTypes are the ChatGPT backend's error types for an account
|
||||
// that has nothing left for Codex.
|
||||
var codexOutTypes = []string{"usage_limit_reached", "usage_not_included"}
|
||||
|
||||
// codexOutRefusal is whether b, a refusal of a turn on p, is the ChatGPT
|
||||
// backend saying p's account has nothing left for Codex, answered on the
|
||||
// Responses API it came on.
|
||||
func codexOutRefusal(p provider.Provider, proto provider.Protocol, status int, b []byte) bool {
|
||||
if proto != provider.Responses || p.Account == nil || p.Account.Agent != "codex" || status != http.StatusTooManyRequests && status != http.StatusForbidden {
|
||||
return false
|
||||
}
|
||||
t := gjson.GetBytes(b, "error.type").String()
|
||||
for _, o := range codexOutTypes {
|
||||
if t == o {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// writeCodexOut answers a codexOutRefusal as the backend did: its error
|
||||
// object, its message magpie's msg, and the x-codex-* headers of h.
|
||||
func writeCodexOut(w http.ResponseWriter, h http.Header, status int, msg string, b []byte) int {
|
||||
var e struct {
|
||||
Error map[string]any `json:"error"`
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(b))
|
||||
d.UseNumber() // resets_at as written, never through a float
|
||||
if d.Decode(&e) != nil || e.Error == nil {
|
||||
return writeVendorError(w, provider.Responses, status, msg, b)
|
||||
}
|
||||
e.Error["message"] = msg
|
||||
out, err := json.Marshal(e)
|
||||
if err != nil {
|
||||
return writeVendorError(w, provider.Responses, status, msg, b)
|
||||
}
|
||||
for k, vs := range h {
|
||||
if strings.HasPrefix(strings.ToLower(k), "x-codex-") {
|
||||
w.Header()[k] = vs
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
w.Write(out)
|
||||
return status
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Every one of magpie's ChatGPT accounts used up, Codex's turn routed
|
||||
// through them: Codex gets the 429 the backend gave, typed
|
||||
// usage_limit_reached with its plan and reset and the x-codex-* windows
|
||||
// beside it, as it gets it on its own sign-in, so it shows its usage
|
||||
// limit and when it ends. Re-typed rate_limit_error with the headers
|
||||
// dropped, Codex took it for a retryable 429 and stopped on "exceeded
|
||||
// retry limit" (bitssly on X). Asked again with both resting, the same.
|
||||
func TestCodexEveryAccountOutToldAsTheBackend(t *testing.T) {
|
||||
for _, x := range []struct {
|
||||
name, body string
|
||||
status int
|
||||
}{
|
||||
{"usage_limit_reached", `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_at":4102444800,"resets_in_seconds":7200}}`, 429},
|
||||
{"usage_not_included", `{"error":{"type":"usage_not_included","message":"To use Codex with your ChatGPT plan, upgrade to Plus."}}`, 403},
|
||||
} {
|
||||
t.Run(x.name, func(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
var asked []string
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
asked = append(asked, r.Header.Get("chatgpt-account-id"))
|
||||
w.Header()["Content-Type"] = nil
|
||||
w.Header().Set("x-codex-primary-used-percent", "100")
|
||||
w.Header().Set("x-codex-primary-window-minutes", "300")
|
||||
w.Header().Set("x-codex-primary-reset-at", "4102444800")
|
||||
w.WriteHeader(x.status)
|
||||
io.WriteString(w, x.body)
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
if _, routed := codexAccounts(httptest.NewRequest("POST", CodexPath+"/responses", nil), "gpt-5.5"); !routed {
|
||||
t.Fatal("two accounts on: Codex's turn isn't routed")
|
||||
}
|
||||
var want map[string]any
|
||||
json.Unmarshal([]byte(x.body), &want)
|
||||
for i := range 2 {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","stream":true,"input":"ping"}`))
|
||||
req.Header.Set("Authorization", "Bearer chatgpt-token")
|
||||
req.Header.Set("chatgpt-account-id", "acct-1")
|
||||
New().Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != x.status {
|
||||
t.Fatalf("turn %d: %d %s", i, rec.Code, rec.Body)
|
||||
}
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("turn %d: %v: %s", i, err, rec.Body)
|
||||
}
|
||||
e, w := got["error"].(map[string]any), want["error"].(map[string]any)
|
||||
for k, v := range w {
|
||||
if k == "message" {
|
||||
continue
|
||||
}
|
||||
if e[k] != v {
|
||||
t.Errorf("turn %d: error.%s = %v, the backend said %v: %s", i, k, e[k], v, rec.Body)
|
||||
}
|
||||
}
|
||||
if m, _ := e["message"].(string); !strings.Contains(m, w["message"].(string)) {
|
||||
t.Errorf("turn %d: message %q", i, m)
|
||||
}
|
||||
if rec.Header().Get("x-codex-primary-used-percent") != "100" || rec.Header().Get("x-codex-primary-reset-at") != "4102444800" {
|
||||
t.Errorf("turn %d: the windows left behind: %v", i, rec.Header())
|
||||
}
|
||||
if !strings.HasPrefix(rec.Header().Get("Content-Type"), "application/json") {
|
||||
t.Errorf("turn %d: Content-Type %q", i, rec.Header().Get("Content-Type"))
|
||||
}
|
||||
}
|
||||
if len(asked) < 2 || asked[0] == asked[1] {
|
||||
t.Fatalf("asked %v: both accounts are to be tried", asked)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A ChatGPT account's 429 that isn't its usage limit (a rate limit per
|
||||
// minute) keeps magpie's shape: Codex retries it, as it should.
|
||||
func TestCodexRateLimitNotToldAsUsedUp(t *testing.T) {
|
||||
p := provider.Provider{ID: "codex", Account: &provider.Account{Agent: "codex"}}
|
||||
if codexOutRefusal(p, provider.Responses, 429, []byte(`{"error":{"type":"rate_limit_exceeded","message":"slow down"}}`)) {
|
||||
t.Fatal("a rate limit told as used up")
|
||||
}
|
||||
if codexOutRefusal(provider.Provider{ID: "k"}, provider.Responses, 429, []byte(`{"error":{"type":"usage_limit_reached"}}`)) {
|
||||
t.Fatal("a key's 429 told as a ChatGPT account's")
|
||||
}
|
||||
if codexOutRefusal(p, provider.Chat, 429, []byte(`{"error":{"type":"usage_limit_reached"}}`)) {
|
||||
t.Fatal("Chat Completions told in the ChatGPT backend's shape")
|
||||
}
|
||||
if !codexOutRefusal(p, provider.Responses, 429, []byte(`{"error":{"type":"usage_limit_reached"}}`)) {
|
||||
t.Fatal("a used-up ChatGPT account not told as the backend")
|
||||
}
|
||||
}
|
||||
@@ -6640,6 +6640,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
}
|
||||
keepRetry(w.Header(), res.Header, b)
|
||||
u.ErrType = provider.ErrorType(b)
|
||||
if codexOutRefusal(p, proto, res.StatusCode, b) {
|
||||
return writeCodexOut(w, res.Header, res.StatusCode, msg, b), msg, true
|
||||
}
|
||||
return writeVendorError(w, proto, res.StatusCode, msg, b), msg, true
|
||||
}
|
||||
if remote != nil && res.Header.Get(KeptTurnHeader) != "" {
|
||||
|
||||
Reference in New Issue
Block a user