diff --git a/internal/agent/codex.go b/internal/agent/codex.go index b216d16ca..85feb7b4e 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -91,6 +91,25 @@ func codex(home string) *Agent { } return edit.DelTOMLKey(path, "agents", "default_subagent_model") } + // Codex on one of its own models goes through magpie too while more of + // its ChatGPT accounts are on there, so one out of its allowance hands + // the turn to the next; with none, it goes straight to OpenAI again + failover := func() error { + if isMagpie(get("model")) || asProvider() { + return nil + } + if p := get("model_provider"); p != "" && p != "openai" { + return nil + } + on := codexFailover() + switch { + case on && !viaBase(): + return edit.SetTOMLTop(path, edit.KV{Path: "openai_base_url", Value: codexGatewayURL()}) + case !on && viaBase(): + return dropBase() + } + return nil + } modelOptions := func(withMagpie bool) []Option { var own []Option if p := get("model_provider"); p != "" && p != magpieID { @@ -200,6 +219,9 @@ func codex(home string) *Agent { if err := edit.SetTOMLTop(path, edit.KV{Path: "model", Value: v}); err != nil { return err } + if err := failover(); err != nil { + return err + } return settle() } @@ -207,6 +229,9 @@ func codex(home string) *Agent { ID: "codex", Name: "Codex", Icon: "codex-color", Bin: "codex", Dir: dir, Path: path, UA: []string{"codex"}, Sync: func() error { + if err := failover(); err != nil { + return err + } switch { case asProvider() && get("model_catalog_json") == catalogPath: b := codexcat.Catalog(magpieModels("codex")) @@ -417,6 +442,17 @@ var codexUsedUp = func() bool { return provider.CodexUsedUp(ctx) } +// codexFailover reports whether Codex is signed in to a ChatGPT account +// with more of its accounts on in magpie, behind it. +func codexFailover() bool { + for _, p := range provider.Accounts() { + if p.Account != nil && p.Account.Agent == "codex" { + return len(p.AlsoOn()) > 0 + } + } + return false +} + // codexSignedIn reports whether Codex has a sign-in of its own, a ChatGPT // account or an API key, which its built-in OpenAI provider needs. func codexSignedIn(dir string) bool { diff --git a/internal/agent/codex_failover_test.go b/internal/agent/codex_failover_test.go new file mode 100644 index 000000000..dc5c23479 --- /dev/null +++ b/internal/agent/codex_failover_test.go @@ -0,0 +1,67 @@ +package agent + +import ( + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// Codex on one of its own models, signed in to ChatGPT, goes through +// magpie while another of its accounts is on there — so a turn the first +// has no allowance left for goes to the next — and straight to OpenAI +// once none is. +func TestCodexOwnModelThroughMagpieWhileAccountsOn(t *testing.T) { + claims := func(m map[string]any) string { + b, _ := json.Marshal(m) + return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s" + } + auth := func(email, acct string) map[string]any { + return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{ + "id_token": claims(map[string]any{"email": email}), + "access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix()}), + "refresh_token": "r-" + acct, "account_id": acct}} + } + me, _ := json.Marshal(auth("me@example.com", "acct-1")) + home, read := codexHome(t, string(me), "model = \"gpt-5.5\"\n") + cx := codex(home) + logins := func(on bool) { + b, _ := json.Marshal([]map[string]any{{"agent": "codex", "user": "spare@example.com", "on": on, + "seen": time.Now(), "auth": auth("spare@example.com", "acct-2")}}) + os.MkdirAll(filepath.Dir(provider.Path()), 0o755) + os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), b, 0o600) + } + logins(false) + if err := cx.Fields[0].Set("gpt-5.4"); err != nil { + t.Fatal(err) + } + if cfg := read(); strings.Contains(cfg, "openai_base_url") { + t.Fatalf("one account:\n%s", cfg) + } + logins(true) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `openai_base_url = "http://127.0.0.1:`) || !strings.Contains(cfg, `model = "gpt-5.4"`) { + t.Fatalf("second account on:\n%s", cfg) + } + // picked again, it stays so + if err := cx.Fields[0].Set("gpt-5.5"); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) { + t.Fatalf("picked with two accounts on:\n%s", cfg) + } + logins(false) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.5"`) { + t.Fatalf("second account off:\n%s", cfg) + } +} diff --git a/internal/gateway/codex_accounts_test.go b/internal/gateway/codex_accounts_test.go new file mode 100644 index 000000000..663adfb89 --- /dev/null +++ b/internal/gateway/codex_accounts_test.go @@ -0,0 +1,131 @@ +package gateway + +import ( + "encoding/base64" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/yetone/magpie/internal/provider" +) + +// codexSignedIn signs a test's Codex in to ChatGPT (acct-1), with the +// saved accounts spares (acct-2, …) on beside it in magpie. +func codexSignedIn(t *testing.T, spares ...string) { + t.Helper() + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache")) + restingUntil.Lock() + restingUntil.m = map[string]time.Time{} + restingUntil.Unlock() + claims := func(m map[string]any) string { + b, _ := json.Marshal(m) + return "h." + base64.RawURLEncoding.EncodeToString(b) + ".s" + } + auth := func(email, acct string) map[string]any { + return map[string]any{"auth_mode": "chatgpt", "tokens": map[string]any{ + "id_token": claims(map[string]any{"email": email}), + "access_token": claims(map[string]any{"exp": time.Now().Add(time.Hour).Unix(), "who": acct}), + "refresh_token": "r-" + acct, "account_id": acct}} + } + os.MkdirAll(filepath.Join(home, ".codex"), 0o755) + os.WriteFile(filepath.Join(home, ".codex", "auth.json"), mustJSON(auth("me@example.com", "acct-1")), 0o600) + var saved []map[string]any + for i, s := range spares { + saved = append(saved, map[string]any{"agent": "codex", "user": s, "on": true, "seen": time.Now(), + "auth": auth(s, "acct-"+string(rune('2'+i)))}) + } + os.MkdirAll(filepath.Dir(provider.Path()), 0o755) + os.WriteFile(filepath.Join(filepath.Dir(provider.Path()), "logins.json"), mustJSON(saved), 0o600) +} + +// usedUp stands in for the ChatGPT backend with acct-1 out of its +// allowance, as it says so; it notes the accounts asked and the models. +func usedUp(t *testing.T, tried, models *[]string) { + t.Helper() + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + *tried = append(*tried, r.Header.Get("chatgpt-account-id")) + *models = append(*models, modelOf(b)) + if r.Header.Get("chatgpt-account-id") == "acct-1" { + w.WriteHeader(429) + io.WriteString(w, `{"error":{"type":"usage_limit_reached","message":"The usage limit has been reached","plan_type":"plus","resets_in_seconds":7200}}`) + return + } + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","model":"gpt-5.5"}}`, + `data: {"type":"response.output_text.delta","delta":"pong"}`, + `data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":7,"output_tokens":1}}}`)) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) +} + +// Codex on one of its own models, signed in to a ChatGPT account that has +// used its allowance up, with another of its accounts on in magpie: the +// turn goes on to that one, asked for the model Codex asked for, and the +// first sits out as long as ChatGPT says, up to the longest wait. +func TestCodexOwnModelMovesToNextAccount(t *testing.T) { + codexSignedIn(t, "spare@example.com") + var tried, models []string + usedUp(t, &tried, &models) + + code, body := codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`) + if code != 200 || !strings.Contains(body, "pong") { + t.Fatalf("status %d: %s", code, body) + } + if strings.Join(tried, ",") != "acct-1,acct-2" || strings.Join(models, ",") != "gpt-5.5,gpt-5.5" { + t.Fatalf("tried %v models %v", tried, models) + } + restingUntil.Lock() + var rest time.Duration + for _, u := range restingUntil.m { + rest = max(rest, time.Until(u)) + } + restingUntil.Unlock() + if rest < longestWait-time.Minute || rest > longestWait { + t.Errorf("rests %v, not the %v ChatGPT's two hours come to", rest, longestWait) + } + tried, models = nil, nil + codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`) + if strings.Join(tried, ",") != "acct-2" { + t.Fatalf("second turn tried %v", tried) + } +} + +// With no other account on, Codex's own model goes as it came: its own +// sign-in, and the refusal back to Codex as ChatGPT said it. +func TestCodexOwnModelOneAccountRelayed(t *testing.T) { + codexSignedIn(t) + var tried, models []string + usedUp(t, &tried, &models) + code, body := codexPost(t, `{"model":"gpt-5.5","stream":true,"input":"ping"}`) + if code != 429 || !strings.Contains(body, "usage_limit_reached") || strings.Join(tried, ",") != "acct-1" { + t.Fatalf("%d %s tried %v", code, body, tried) + } +} + +func TestResetsIn(t *testing.T) { + now := time.Unix(1_000_000, 0) + for body, want := range map[string]time.Duration{ + `{"error":{"type":"usage_limit_reached","resets_at":1003600,"resets_in_seconds":5}}`: time.Hour, + `{"error":{"type":"usage_limit_reached","resets_in_seconds":90}}`: 90 * time.Second, + `{"error":{"resets_at":999000}}`: 0, + `{"error":{"message":"quota"}}`: 0, + `not json`: 0, + } { + if got := resetsIn([]byte(body), now); got != want { + t.Errorf("%s: %v, want %v", body, got, want) + } + } +} diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 2ace18c20..310f71cbc 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -76,6 +76,10 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { return } body, _ = codexInput(body, false) + if id, ok := codexAccounts(r.Header, modelOf(body)); ok { + s.serve(w, r, provider.Responses, withModel(body, id)) + return + } } s.codexUpstream(w, r, rest, body) } @@ -120,6 +124,37 @@ func isCatalogID(model string) bool { return false } +// codexAccounts is what a request for one of Codex's own models is served +// as when Codex is signed in to ChatGPT and more of its accounts are on in +// magpie: the codex subscription's model (codex/), which goes to the +// account Codex is signed in to and, when that one is out of its allowance +// or rate limited, on to the next — as it can't when relayed as it came. +func codexAccounts(h http.Header, model string) (string, bool) { + if model == "" || strings.Contains(model, "/") || apiKey(h) { + return "", false + } + id := "codex/" + model + p, _, ok := provider.Resolve(id) + if !ok || p.Account == nil || p.Account.Agent != "codex" || len(p.AlsoOn()) == 0 { + return "", false + } + return id, true +} + +// withModel is a request body asking for another model. +func withModel(body []byte, model string) []byte { + var q map[string]json.RawMessage + if json.Unmarshal(body, &q) != nil { + return body + } + q["model"], _ = json.Marshal(model) + b, err := json.Marshal(q) + if err != nil { + return body + } + return b +} + // codexUpstream relays a request as it came, the sign-in included, to where // Codex would have sent it. func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest string, body []byte) { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index b1d487566..6474e57f2 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -788,7 +788,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider. return res.StatusCode, msg, false } } - keepRetry(w.Header(), res.Header) + keepRetry(w.Header(), res.Header, b) return writeError(w, proto, res.StatusCode, msg), msg, true } rd, sse := eventStream(res) @@ -976,7 +976,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr if res.StatusCode >= 400 { b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) msg := p.Name + ": " + provider.APIError(b, res.Status) - keepRetry(w.Header(), res.Header) + keepRetry(w.Header(), res.Header, b) return writeError(w, from, res.StatusCode, msg), msg } dec := decoder(actual) diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index d29c5d360..8536d3d67 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -11,6 +11,7 @@ package gateway // again. import ( + "encoding/json" "math" "net/http" "regexp" @@ -119,6 +120,25 @@ type Rest struct { Failures int `json:"failures,omitempty"` // in a row, for a backoff } +// resetsIn is how long until a used-up ChatGPT account is back, as its +// refusal says: {"error":{"type":"usage_limit_reached","resets_at":, +// "resets_in_seconds":}}. Zero when it doesn't say. +func resetsIn(body []byte, now time.Time) time.Duration { + var e struct { + Error struct { + At int64 `json:"resets_at"` + In int64 `json:"resets_in_seconds"` + } `json:"error"` + } + if json.Unmarshal(body, &e) != nil { + return 0 + } + if t := time.Unix(e.Error.At, 0); e.Error.At > 0 && t.After(now) { + return t.Sub(now) + } + return time.Duration(max(e.Error.In, 0)) * time.Second +} + // restAfter sets a failed candidate aside for as long as its failure says. func (s *Server) restAfter(c candidate, status int, header http.Header, body []byte) Rest { now := time.Now() @@ -136,6 +156,8 @@ func (s *Server) restAfter(c candidate, status int, header http.Header, body []b if n, _ := strconv.ParseInt(string(m[1]), 10, 64); time.Unix(n, 0).After(now) { d, r.By = time.Unix(n, 0).Sub(now), "resets" } + } else if w := resetsIn(body, now); w > 0 { + d, r.By = w, "resets" } else if t := c.full(now); !t.IsZero() { d, r.By = t.Sub(now), "window" } @@ -177,14 +199,20 @@ func (c candidate) full(now time.Time) time.Time { // keepRetry passes on, with a vendor's error, what it said about when to // try again: restAfter reads it to rest the candidate that long, and an -// agent given the error reads it too. -func keepRetry(dst, src http.Header) { +// agent given the error reads it too. When it said so in the error itself +// (ChatGPT's resets_at), that goes on as Retry-After. +func keepRetry(dst, src http.Header, body []byte) { for k, vs := range src { l := strings.ToLower(k) if l == "retry-after" || strings.Contains(l, "ratelimit") && strings.Contains(l, "reset") { dst[k] = vs } } + if dst.Get("Retry-After") == "" { + if d := resetsIn(body, time.Now()); d > 0 { + dst.Set("Retry-After", strconv.Itoa(int(d.Seconds()))) + } + } } // retryAfter is when a vendor says to try again: Retry-After, in seconds diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 9035eed63..36cc2da5e 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -523,6 +523,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, err) return } + // an agent on its own models goes through magpie while more of + // its accounts are on, and straight to its vendor again once not + agent.SyncCatalog() writeJSON(rw, providersState()) }) // A provider's several keys: add one, put one in use, name or remove it. diff --git a/internal/tui/library.go b/internal/tui/library.go index ca6278905..93c81fa8a 100644 --- a/internal/tui/library.go +++ b/internal/tui/library.go @@ -8,7 +8,6 @@ package tui import ( "fmt" "os" - "os/exec" "runtime" "slices" "strings" @@ -18,6 +17,7 @@ import ( "github.com/yetone/magpie/internal/agent" "github.com/yetone/magpie/internal/library" + "github.com/yetone/magpie/internal/proc" ) // libRow is one line of the page. @@ -325,7 +325,7 @@ func editInstructions() tea.Cmd { } // the editor may come with flags: code -w words := strings.Fields(ed) - c := exec.Command(words[0], append(words[1:], f.Name())...) + c := proc.Command(words[0], append(words[1:], f.Name())...) return tea.ExecProcess(c, func(err error) tea.Msg { defer os.Remove(f.Name()) if err != nil {