From 3e9bbdaae9d5f29e93b93a6edecf0bf9cb9d4488 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 9 Oct 2026 10:38:35 +0800 Subject: [PATCH] gateway: a paused Codex sign-in isn't spent by native compaction either (JasonLeeForOnly on Discord: a ChatGPT account turned off in magpie still had its quota used) The account Codex is signed in to can be paused in magpie while another of its accounts is on (#263: the user's own ChatGPT account kept for Codex's remote control and Computer Use, another doing the work). Turns on Codex's own models already passed over it (codexAccounts, routing and OwnPaused), but /responses/compact for one of those models still relayed as it came, on the paused account's own token, and on history the others had sealed. compactOn now picks, for that case only, the first of the other accounts on that isn't resting, and codexUpstreamOn relays the compaction signed as that account (its token and chatgpt-account-id, through its proxy), keeping the Accept Codex sent. A gateway key held to some accounts (#905) is asked of the account it goes to, not the paused sign-in. Not paused, nothing else on, an API-key Codex, or a request naming an account: the relay is as before. Not changed: a Codex provider switched off (Off) still relays Codex's own model requests (the Codex app's gpt-5.6-luna/terra side generations, memories, codex-auto-review, native compaction) on the sign-in as they came; that is a design question, reported separately. Tested: TestCodexPausedOwnAccountNotCompactedOn (in use: on the sign-in; paused: acct-2 with its own token; key held to the paused sign-in: 403 with nothing asked; held to the spare: acct-2; the spare off: the sign-in again) fails on origin/main at the paused step (tried [acct-1]) and passes. gofmt; go vet -tags nogui ./internal/gateway on darwin, linux, windows; go test -tags nogui ./internal/gateway ./internal/provider ./internal/agent under a temp HOME pass. Not tried with real accounts. --- docs/subsystems/providers-accounts.md | 1 + internal/gateway/codex_accounts_test.go | 70 ++++++++++++++++++++++++ internal/gateway/codex_backend.go | 71 +++++++++++++++++++++++-- 3 files changed, 139 insertions(+), 3 deletions(-) diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 859b4d89f..4156055ef 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -50,6 +50,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi - The Copilot account the editors and CLI keep is read by `copilotLogin` ([account.go](../../internal/provider/account.go)): an editor's github.com sign-in in `~/.config/github-copilot/apps.json` or `hosts.json` first, then the Copilot CLI's, then an editor's on GHE.com. When GitHub refuses the editor token's trade for a session token (401 or 403, `copilotRefusals`, retried after an hour), the CLI's sign-in of the same login on the same host takes its place, sent as the CLI sends it, from that request on and on the Usage card (`copilotStandIn`); a CLI signed in to another account is never used for it, and the error names the editors' file (#1238). A sign-in from magpie of the account whose editor token is refused is kept and stands for it (`copilotProbeEditor`, `addCopilotLogin`); while the editor token works, it is let go as the agent's own, as before. - An unreadable `providers.json` is an error, never an empty list. Saving over an empty list would lose every provider. - When `logins.json` cannot be decoded as saved accounts, reads keep the accounts read before. Before saving a change, `keepUnreadLogins` copies the original file aside, including valid JSON with invalid account field types, so its credentials can be recovered. If the existing file cannot be read or the backup fails, saving returns the error and leaves the original file unchanged. A missing file can be created normally. +- The account Codex or Claude Code is signed in to can be paused (`SetLoginOn` off, #263) only while another of its accounts is on. The gateway then sends it nothing: Codex's own-model turns go through routing, which passes over it (`OwnPaused`), and a native compaction (`/responses/compact`) goes to the first account on that isn't resting, signed as that account (`compactOn` in [codex_backend.go](../../internal/gateway/codex_backend.go)). The last other account off, the paused one is used again. A switched-off Codex provider is not a pause: Codex's own-model requests still relay on its sign-in as they came. - A switched-off provider (`Off`, #163) stays saved. The gateway says it is off instead of saying the model is unknown. - A provider removed or switched off takes its models out of the catalog. [Agent wiring](agent-wiring.md)'s `Reseat` moves agents off them. - A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests. diff --git a/internal/gateway/codex_accounts_test.go b/internal/gateway/codex_accounts_test.go index 9fe317f74..455564f6f 100644 --- a/internal/gateway/codex_accounts_test.go +++ b/internal/gateway/codex_accounts_test.go @@ -190,6 +190,76 @@ func TestCodexPausedOwnAccountPassedOver(t *testing.T) { } } +// Native compaction of one of Codex's own models, with the account Codex +// is signed in to paused in magpie while another is on (#263, the free +// ChatGPT account kept for Codex's remote control and Computer Use): +// it goes to the account that is on, signed as that account, not relayed +// on the paused one's sign-in as it came. With nothing else on, or not +// paused, it relays on the sign-in as before. +func TestCodexPausedOwnAccountNotCompactedOn(t *testing.T) { + codexSignedIn(t, "spare@example.com") + var tried, auths, paths []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + tried = append(tried, r.Header.Get("chatgpt-account-id")) + auths = append(auths, r.Header.Get("Authorization")) + paths = append(paths, r.URL.Path) + io.WriteString(w, `{"output":[{"type":"compaction","encrypted_content":"gAAAAAx"}]}`) + })) + t.Cleanup(up.Close) + was := provider.CodexBase + provider.CodexBase = up.URL + "/backend-api/codex" + t.Cleanup(func() { provider.CodexBase = was }) + compact := func() int { + t.Helper() + tried, auths, paths = nil, nil, nil + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses/compact", strings.NewReader(`{"model":"gpt-5.5","input":[{"type":"message","role":"user","content":"ping"}]}`)) + req.Header.Set("Authorization", "Bearer chatgpt-token") + req.Header.Set("chatgpt-account-id", "acct-1") + New().Handler().ServeHTTP(rec, req) + return rec.Code + } + + if code := compact(); code != 200 || strings.Join(tried, ",") != "acct-1" || auths[0] != "Bearer chatgpt-token" { + t.Fatalf("in use: %d tried %v auth %v", code, tried, auths) + } + if err := provider.SetLoginOn("codex", "me@example.com", false); err != nil { + t.Fatal(err) + } + if code := compact(); code != 200 || strings.Join(tried, ",") != "acct-2" || auths[0] == "Bearer chatgpt-token" || paths[0] != "/backend-api/codex/responses/compact" { + t.Fatalf("paused: %d tried %v auth %v path %v", code, tried, auths, paths) + } + // a key held to some accounts (#905) is asked of the account it goes + // to: held to the paused sign-in alone, refused with nothing asked; + // held to the one on, compacted there + keys, secrets := newCaller(t, "Held") + keyed := func(as string) int { + t.Helper() + if _, err := access.Update("accounts-key", access.Change{Key: keys[0].ID, Accounts: []string{as}}); err != nil { + t.Fatal(err) + } + tried = nil + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses/compact", strings.NewReader(`{"model":"gpt-5.5","input":[]}`)) + req.Header.Set("Authorization", "Bearer "+secrets[0]) + New().Handler().ServeHTTP(rec, req) + return rec.Code + } + if code := keyed("codex/me@example.com"); code != 403 || len(tried) != 0 { + t.Fatalf("held to the paused sign-in: %d tried %v", code, tried) + } + if code := keyed("codex/spare@example.com"); code != 200 || strings.Join(tried, ",") != "acct-2" { + t.Fatalf("held to the one on: %d tried %v", code, tried) + } + // the other off: the paused one is all there is, and is used + if err := provider.SetLoginOn("codex", "spare@example.com", false); err != nil { + t.Fatal(err) + } + if code := compact(); code != 200 || strings.Join(tried, ",") != "acct-1" || auths[0] != "Bearer chatgpt-token" { + t.Fatalf("with the other off: %d tried %v auth %v", code, tried, auths) + } +} + // A gateway key held to some accounts (#905) holds Codex's own models // too: asked for by its bare native name — the request Codex would relay // to its own sign-in when that one account is all that is on — the turn diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 9a23e9d48..9d113f858 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -114,10 +114,15 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) { // compaction still relays on: refused as its turns are (#967), // with nothing asked of OpenAI — and refused when the sign-in // can't be shown to be the key's, switched off or gone - if who, held := compactSigninHeld(r, model); held { + on := compactOn(r, model) + if who, held := compactSigninHeld(r, model, on); held { writeError(w, provider.Responses, 403, compactHeldError(who, model)) return } + if on != nil { + s.codexUpstreamOn(w, r, rest, body, on) + return + } break // preserve native compaction's existing passthrough } body, _ = codexInput(body, false) @@ -366,11 +371,16 @@ func hasSealedAgentMessage(body []byte) bool { // auth_mode) spends no account the key's list governs, and is the one // allowance. A key held to some models alone (#882) still compacts as // it always did, its holds asked on /responses where its turns go. -func compactSigninHeld(r *http.Request, model string) (access.Identity, bool) { +func compactSigninHeld(r *http.Request, model string, on *provider.Provider) (access.Identity, bool) { who, held := accountHolds(r) if !held || provider.CodexAPIKeySignedIn() { return who, false } + if on != nil { + // compacted on another of Codex's accounts (compactOn): the key + // holds that one, not the sign-in + return who, !who.AllowsAccount(on.ID, on.AccountID()) + } p, _, ok := provider.Resolve("codex/" + model) if !ok || p.Account == nil || p.Account.Agent != "codex" || !who.AllowsAccount(p.ID, p.AccountID()) { return who, true @@ -388,6 +398,36 @@ func compactHeldError(who access.Identity, model string) string { model, who.KeyName, keyAccountNames(who)) } +// compactOn is the account a native compaction of one of Codex's own +// models goes to in place of the ChatGPT sign-in it would relay on: one of +// Codex's other accounts on in magpie while the sign-in is paused there +// (#263, the user's own account kept for Codex's remote control, Computer +// Use and the like, another doing the work). Its turns already go to the +// others (codexAccounts, routing passing the paused one over); relayed as +// it came, compaction alone still spent the paused account — and on +// history the others sealed. The first not resting is taken, else the +// first. nil keeps the relay to the sign-in: not paused, or nothing else +// on, or Codex on an API key. +func compactOn(r *http.Request, model string) *provider.Provider { + if model == "" || strings.Contains(model, "/") || apiKey(r.Header) || r.Header.Get(AccountHeader) != "" { + return nil + } + p, _, ok := provider.Resolve("codex/" + model) + if !ok || p.Account == nil || p.Account.Agent != "codex" || !p.OwnPaused() { + return nil + } + others := p.AlsoOn() + for i, o := range others { + if !resting(candidate{p: o, model: model, rest: o.ID}) { + return &others[i] + } + } + if len(others) > 0 { + return &others[0] + } + return nil +} + // 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 @@ -446,6 +486,12 @@ func withModel(body []byte, model string) []byte { // 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) { + s.codexUpstreamOn(w, r, rest, body, nil) +} + +// codexUpstreamOn is codexUpstream signed by the account on instead of +// Codex's own sign-in, when on isn't nil (compactOn). +func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest string, body []byte, on *provider.Provider) { start := time.Now() usage.Saw(agentOf(r)) if r.Method == http.MethodPost { @@ -523,13 +569,32 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri autoReset := false // a Codex reset looked at, once resetNote := "" // what spending it did, for the request log for tries := 0; ; tries++ { - req, err := http.NewRequestWithContext(provider.ViaSignedIn(r.Context(), "codex"), r.Method, u, bytes.NewReader(body)) + ctx := provider.ViaSignedIn(r.Context(), "codex") + if on != nil { + ctx = on.Via(r.Context()) + } + req, err := http.NewRequestWithContext(ctx, r.Method, u, bytes.NewReader(body)) if err != nil { writeError(w, provider.Responses, 502, err.Error()) end(502, err.Error(), 0, 0) return } copyHeaders(req.Header, r.Header) + if on != nil { + // the account's own token and id in place of the sign-in's; + // what Codex said it takes back stays as it said it + accept := req.Header.Values("Accept") + if err := on.Sign(ctx, req, provider.Responses, body); err != nil { + msg := "OpenAI (" + on.Account.User + "): " + err.Error() + writeError(w, provider.Responses, 502, msg) + end(502, msg, 0, 0) + return + } + req.Header.Del("Accept") + for _, v := range accept { + req.Header.Add("Accept", v) + } + } // left to the transport, the reply comes back plain for the usage in it req.Header.Del("Accept-Encoding") if res, err = s.client.Do(req); err != nil {