Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: Codex's own model on a thread started on magpie goes on Codex's sign-in, not a 404

yetone4586307de574
diff --git a/docs/subsystems/agent-wiring.md b/docs/subsystems/agent-wiring.md
index 265733eb7..06977c247 100644
--- a/docs/subsystems/agent-wiring.md
+++ b/docs/subsystems/agent-wiring.md
@@ -36,7 +36,7 @@ something else shows up as drift.
2. **Pick.** `Pick` sets a field from the model picker. Picking one of magpie's models on an agent that isn't connected connects it first. Each row of a model picker that a provider served with a timed reply this week says how fast: tokens a second, or the first token's wait when only that was timed (`speedTag` in app.js, from `GET /api/model-speeds`, `modelSpeeds` in [`internal/gui/speeds.go`](../../internal/gui/speeds.go): the usage ledger's mean TTFT and decode speed by `provider/model`, the catalog ref an option carries). Under a search, rows that match equally go fastest first by about how long a 200-token reply takes (`speedRank`), the untimed last, so a model several providers serve lists the fastest one first (axuhere on X). Without a search the rows keep catalog order, grouped by provider. A routing group that always asks the fastest provider is the Speed first strategy ([gateway routing](gateway-routing.md)).
3. **Notice.** After a change the page shows `Notice` when the agent reads its config only at start-up and needs a restart. A field that is `Live` (`Field.Live`: magpie's own setting, which the gateway reads on each request, Claude Desktop's `subagent_model` and `subagent_effort`) needs no restart, so `POST /api/set` and `magpie <agent> <field> <value>` leave the Notice out after it, unless the pick connected the agent too (`Pick` on an agent not connected). A stopped WSL distro's copy of a field keeps the flag (`asleep`).
4. **Drift.** As the Agents page is drawn, `Drift` compares the config with `applied.json`. It runs `Check` first, then each field. An agent pointed at magpie through a reverse proxy is still on magpie (#1985, davisjiahao: a company's nginx at `https://ai.corp.example/magpie`). `wiringOff`, where most agents' `Check` compares a URL, and the checks of their own (Claude Code's managed settings, Reasonix's provider) take a URL that isn't magpie's when it ends with magpie's path, the rest is an http or https address on another machine (`onAnotherMachine`) or one on this machine's loopback with a path of its own (`loopbackWithPath`: the reporter's compliance proxy at `http://127.0.0.1:8788/claude-code-anthropic/<route>`; `proxyBase`), and `GET <rest>/` there answers as the gateway's own `GET /` does (`{"name":"magpie"}`, `magpieAt` in [`reach.go`](../../internal/agent/reach.go), tried in the background like `reachProbe`). Something else there (a relay CC Switch put in) is `unwired`, as is an address on this machine's loopback without a path, which is magpie's on an older port and is never tried. Until the answer is known it isn't drift, so Reconnect isn't offered and doesn't write the proxy away; port moves (`OnGateway`, `Rewire`) re-set only `unwired` agents, so they leave it too. Codex keeps such an address by magpie's key, as for #816 (`codexKeptGateway`: http or https, any port, a path before magpie's, loopback with a path). A model picked in Claude Code keeps it too once magpie has answered there (`surelyMagpie`; `routed` and `gwAt` in `claude.go`), so a proxy every request must go through isn't bypassed; before that, or at a relay, a pick points Claude Code at this magpie. Tests stub `magpieAt` in `TestMain` as known and not magpie. When the config is right and points at an address off loopback (a WSL twin under NAT, or this machine's Codex at an address the user kept, #816), it tries that address ([`reach.go`](../../internal/agent/reach.go)): in the background, at most every 20 s, never waited for. When nothing answers there while the gateway answers on loopback, the drift is `unreachable` (#1013), with what has to listen there: Share on local network, the user's portproxy, Windows' firewall. Then it checks whether the agent's latest use (`LastUsed`, `Reached`) reached the gateway: a request Codex's log says went to the host its config keeps magpie at, or one the gateway saw from it after (`lastSeen`), reached it.
-5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record. It also marks the agent disconnected (`<id>.disconnected` in the stash, `Disconnected`) until the user connects it again (`connect`, or an `Apply` that leaves it wired): nothing magpie does by itself puts magpie back in meanwhile, neither a start's `Sync` nor Codex's account failover nor #701's magpie API wiring (paynezhuang on Discord: Codex had `openai_base_url` back after every update).
+5. **Disconnect.** `Disconnect` puts back what the stash kept and forgets the record. It also marks the agent disconnected (`<id>.disconnected` in the stash, `Disconnected`) until the user connects it again (`connect`, or an `Apply` that leaves it wired): nothing magpie does by itself puts magpie back in meanwhile, neither a start's `Sync` nor Codex's account failover nor #701's magpie API wiring (paynezhuang on Discord: Codex had `openai_base_url` back after every update). A Codex thread keeps the provider it was started on, so one started while magpie was Codex's provider (its API, or the takeover of a used-up account) still sends to `/v1` after Disconnect or a switch back to ChatGPT. One of Codex's own models asked there that no account in magpie serves (an OpenAI model of Codex's models cache or the catalog), from Codex on this computer with no held gateway key, goes on Codex's own ChatGPT sign-in through `codexBackend`, magpie's key and `x-openai-actor-authorization` left behind (`codexOwnOffMagpie` in [`codex_own_v1.go`](../../internal/gateway/codex_own_v1.go)); it was answered 404 "magpie knows no model" (iuengei on Discord). With the sign-in out of reach (subscription accounts off, signed out, expired) the 404 says why and to start a new thread. `TestCodexOwnModelOnMagpieThreadGoesOnSignIn`, `TestCodexOwnModelOnMagpieThreadStaysHere`, `TestCodexOwnModelOnMagpieThreadSaysWhy`.
## Constraints and failure behavior
diff --git a/internal/gateway/codex_own_v1.go b/internal/gateway/codex_own_v1.go
new file mode 100644
index 000000000..7ad9d868a
--- /dev/null
+++ b/internal/gateway/codex_own_v1.go
@@ -0,0 +1,110 @@
+package gateway
+
+import (
+ "bytes"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "strings"
+
+ "github.com/yetone/magpie/internal/catalog"
+ "github.com/yetone/magpie/internal/codexcat"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// codexSignInToken is Codex's ChatGPT sign-in as Codex keeps it, which
+// tests set.
+var codexSignInToken = provider.CodexSignInAsKept
+
+// codexOwnOffMagpie is the request a Codex on this computer sent to /v1
+// for one of its own models that magpie serves nothing for, put on the
+// ChatGPT backend's route (CodexPath) and signed with Codex's own ChatGPT
+// sign-in, as Codex's built-in provider would have sent it. A thread
+// keeps the provider it was started on: one started while magpie was
+// Codex's provider (its API, or the takeover of a used-up account) goes
+// on sending to /v1 after Codex is disconnected or set back to ChatGPT,
+// and an official model picked in it (gpt-6.1-sol) met "magpie knows no
+// model" whenever no ChatGPT account in magpie serves it (iuengei on
+// Discord). nil when that isn't the case: a model magpie serves, switched
+// off, disabled or a group; a model not OpenAI's; a request from another
+// computer or held by its gateway key. Codex's sign-in not to be had
+// (subscription accounts off in magpie, signed out, expired), why is what
+// the request is answered instead of the bare 404: what sends it here and
+// what to do.
+func codexOwnOffMagpie(r *http.Request, body []byte, model string) (to *http.Request, why string) {
+ if model == "" || strings.Contains(model, "/") || !local(r) {
+ return nil, ""
+ }
+ if !fromCodex(r.Header) && agentOf(r) != "codex" {
+ return nil, ""
+ }
+ if _, _, ok := provider.Resolve(model); ok {
+ return nil, ""
+ }
+ if provider.IsGroupRef(model) {
+ return nil, ""
+ }
+ if _, ok := provider.GroupFor(model); ok {
+ return nil, ""
+ }
+ if _, ok := provider.AutoStandIn(model); ok {
+ return nil, ""
+ }
+ if _, off := idOff(model); off {
+ return nil, ""
+ }
+ if _, off := provider.SwitchedOff(model); off {
+ return nil, ""
+ }
+ if _, keyHeld := keyHolds(r); keyHeld {
+ return nil, ""
+ }
+ if _, accHeld := accountHolds(r); accHeld {
+ return nil, ""
+ }
+ if !codexOwnModel(model) {
+ return nil, ""
+ }
+ tok, acct, err := codexSignInToken()
+ if err != nil || tok == "" {
+ if err == nil {
+ err = errors.New("Codex is signed out")
+ }
+ return nil, fmt.Sprintf("%q is one of Codex's own models, and this Codex thread was started while magpie was Codex's model provider, so it is still sent to magpie whatever Codex is set to now. "+
+ "No ChatGPT account in magpie serves it, and magpie can't send it on Codex's own ChatGPT sign-in: %v. "+
+ "Start a new thread in Codex for its own models, or add Codex's ChatGPT account in magpie (Providers)", model, err)
+ }
+ r2 := r.Clone(r.Context())
+ r2.URL.Path = CodexPath + "/responses"
+ r2.URL.RawPath = ""
+ r2.RequestURI = ""
+ r2.Body = io.NopCloser(bytes.NewReader(body))
+ r2.ContentLength = int64(len(body))
+ r2.Header.Del("Content-Encoding")
+ r2.Header.Del("Content-Length")
+ // magpie's key and the header that names magpie Codex's provider are
+ // magpie's own, never sent on to OpenAI
+ r2.Header.Del("X-Api-Key")
+ r2.Header.Del("X-Openai-Actor-Authorization")
+ r2.Header.Set("Authorization", "Bearer "+tok)
+ if acct != "" {
+ r2.Header.Set("Chatgpt-Account-Id", acct)
+ }
+ return r2, ""
+}
+
+// codexOwnModel: model is one of Codex's own, as the ChatGPT backend last
+// listed it to Codex (models_cache.json, magpie's entries left out) or as
+// the catalog has it for OpenAI.
+func codexOwnModel(model string) bool {
+ if _, ok := codexcat.CacheEntries()[model]; ok {
+ return true
+ }
+ for _, m := range catalog.Provider("openai") {
+ if m.ID == model {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/gateway/codex_own_v1_test.go b/internal/gateway/codex_own_v1_test.go
new file mode 100644
index 000000000..d02bddad2
--- /dev/null
+++ b/internal/gateway/codex_own_v1_test.go
@@ -0,0 +1,142 @@
+package gateway
+
+import (
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/access"
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// codexOwnOffMagpieSetup: Codex signed in to ChatGPT, its models cache
+// listing gpt-6.1-sol, and no ChatGPT account in magpie serving it: the
+// sign-in removed from magpie's Providers (hidden), or with discoveryOff
+// subscription accounts turned off. The ChatGPT backend stands in and
+// notes what it was sent.
+func codexOwnOffMagpieSetup(t *testing.T, discoveryOff bool) (got *http.Header, models *[]string) {
+ t.Helper()
+ codexSignedIn(t)
+ if discoveryOff {
+ t.Setenv("MAGPIE_NO_ACCOUNTS", "1")
+ } else if err := provider.Delete("codex"); err != nil {
+ t.Fatal(err)
+ }
+ provider.ForgetAccounts()
+ home := os.Getenv("HOME")
+ os.WriteFile(filepath.Join(home, ".codex", "models_cache.json"),
+ []byte(`{"etag":"e1","models":[{"slug":"gpt-6.1-sol","display_name":"gpt-6.1-sol","priority":1}]}`), 0o600)
+ got, models = &http.Header{}, &[]string{}
+ up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ *got = r.Header.Clone()
+ *models = append(*models, modelOf(b))
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, sse(
+ `data: {"type":"response.created","response":{"id":"r1","model":"gpt-6.1-sol"}}`,
+ `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 })
+ return got, models
+}
+
+func codexOnMagpieRequest(from string) *http.Request {
+ req := httptest.NewRequest("POST", "/v1/responses",
+ strings.NewReader(`{"model":"gpt-6.1-sol","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"ping"}]}]}`))
+ req.RemoteAddr = from
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("User-Agent", "codex_cli_rs/0.164.0 (Mac OS 26.2.0; arm64) Terminal")
+ req.Header.Set("Originator", "codex_cli_rs")
+ req.Header.Set("Authorization", "Bearer "+Token)
+ req.Header.Set("X-Openai-Actor-Authorization", "magpie")
+ return req
+}
+
+// A thread Codex started while magpie was its provider keeps sending to
+// magpie's /v1 after Codex is disconnected or set back to ChatGPT; one of
+// Codex's own models picked in it, which no account in magpie serves,
+// goes to the ChatGPT backend on Codex's own sign-in, magpie's key and
+// header left behind, where it was answered 404 "magpie knows no model
+// \"gpt-6.1-sol\"" (iuengei on Discord).
+func TestCodexOwnModelOnMagpieThreadGoesOnSignIn(t *testing.T) {
+ got, models := codexOwnOffMagpieSetup(t, false)
+ rec := httptest.NewRecorder()
+ New().Handler().ServeHTTP(rec, codexOnMagpieRequest("127.0.0.1:51000"))
+ if rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") {
+ t.Fatalf("got %d %s", rec.Code, rec.Body.String())
+ }
+ if len(*models) != 1 || (*models)[0] != "gpt-6.1-sol" {
+ t.Fatalf("backend asked for %v", *models)
+ }
+ auth := got.Get("Authorization")
+ if auth == "" || strings.Contains(auth, Token) {
+ t.Fatalf("Authorization %q: want Codex's sign-in, not magpie's key", auth)
+ }
+ if got.Get("Chatgpt-Account-Id") != "acct-1" {
+ t.Fatalf("chatgpt-account-id %q, want acct-1", got.Get("Chatgpt-Account-Id"))
+ }
+ if v := got.Get("X-Openai-Actor-Authorization"); v != "" {
+ t.Fatalf("magpie's provider header went to OpenAI: %q", v)
+ }
+}
+
+// Not for a request from another computer, nor a gateway key held to some
+// models, nor a model that isn't OpenAI's: those are answered as before,
+// nothing sent on Codex's sign-in.
+func TestCodexOwnModelOnMagpieThreadStaysHere(t *testing.T) {
+ t.Run("another computer", func(t *testing.T) {
+ _, models := codexOwnOffMagpieSetup(t, false)
+ rec := httptest.NewRecorder()
+ New().Handler().ServeHTTP(rec, codexOnMagpieRequest("192.0.2.7:51000"))
+ if len(*models) != 0 {
+ t.Fatalf("a request from another computer went on Codex's sign-in: %d %s", rec.Code, rec.Body.String())
+ }
+ })
+ t.Run("held key", func(t *testing.T) {
+ _, models := codexOwnOffMagpieSetup(t, false)
+ req := codexOnMagpieRequest("127.0.0.1:51000")
+ req = req.WithContext(access.WithIdentity(req.Context(), access.Identity{KeyID: "k1", Models: []string{"fake/*"}}))
+ rec := httptest.NewRecorder()
+ New().handle(provider.Responses)(rec, req)
+ if len(*models) != 0 {
+ t.Fatalf("a held key went on Codex's sign-in: %d %s", rec.Code, rec.Body.String())
+ }
+ })
+ t.Run("not OpenAI's", func(t *testing.T) {
+ _, models := codexOwnOffMagpieSetup(t, false)
+ req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"no-such-model-xyz","input":"hi"}`))
+ req.RemoteAddr = "127.0.0.1:51000"
+ req.Header = codexOnMagpieRequest("127.0.0.1:51000").Header
+ rec := httptest.NewRecorder()
+ New().Handler().ServeHTTP(rec, req)
+ if len(*models) != 0 || rec.Code != 404 {
+ t.Fatalf("an unknown model: %d %s, sent %v", rec.Code, rec.Body.String(), *models)
+ }
+ })
+}
+
+// With subscription accounts off, magpie reads no sign-in, Codex's
+// neither: the request is answered why it can't be served and what to do,
+// not with the bare "magpie knows no model".
+func TestCodexOwnModelOnMagpieThreadSaysWhy(t *testing.T) {
+ _, models := codexOwnOffMagpieSetup(t, true)
+ rec := httptest.NewRecorder()
+ New().Handler().ServeHTTP(rec, codexOnMagpieRequest("127.0.0.1:51000"))
+ body := rec.Body.String()
+ if rec.Code != 404 || len(*models) != 0 {
+ t.Fatalf("got %d %s, sent %v", rec.Code, body, *models)
+ }
+ for _, want := range []string{"one of Codex's own models", "started while magpie was Codex's model provider", "subscription accounts are off", "Start a new thread"} {
+ if !strings.Contains(body, want) {
+ t.Errorf("answer lacks %q: %s", want, body)
+ }
+ }
+}
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index 410ad2292..c9bc09be0 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -1590,6 +1590,18 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc {
return
}
noteAsked(r.Context(), model)
+ // a thread Codex started on magpie, on one of Codex's own models
+ // magpie serves nothing for: on Codex's own sign-in, as the
+ // ChatGPT backend's route sends it (codexOwnOffMagpie)
+ if from == provider.Responses {
+ if r2, why := codexOwnOffMagpie(r, body, model); r2 != nil {
+ s.codexBackend(w, r2)
+ return
+ } else if why != "" {
+ writeError(w, from, 404, why)
+ return
+ }
+ }
// Codex with magpie as its provider: spawn_agent names every
// model a subagent may be put on, not only Codex's first five
// (Gearclickist on Discord)
diff --git a/internal/provider/account.go b/internal/provider/account.go
index 7d2e320e3..f26b9a44e 100644
--- a/internal/provider/account.go
+++ b/internal/provider/account.go
@@ -1080,6 +1080,13 @@ func codexTokenAsKept(dir string) (tok, accountID string, err error) {
return a.Tokens.AccessToken, codexAccountID(a), nil
}
+// CodexSignInAsKept is the access token and account id of the ChatGPT
+// sign-in Codex keeps, as it is (codexTokenAsKept): an expired one is an
+// error, left to Codex to renew.
+func CodexSignInAsKept() (tok, accountID string, err error) {
+ return codexTokenAsKept(codexHome())
+}
+
// codexTokenRenewing is codexToken, and with stale, the access token the
// backend just answered 401 "token expired" for while its exp was still
// ahead (willz on Discord, #2973: a Team account's), refreshes the