diff --git a/internal/agent/codex.go b/internal/agent/codex.go index 01c9fa573..0ce407259 100644 --- a/internal/agent/codex.go +++ b/internal/agent/codex.go @@ -21,8 +21,8 @@ import ( "github.com/yetone/magpie/internal/provider" ) -// Codex talks the OpenAI Responses API. Signed in (ChatGPT or an API key), -// it is routed through magpie with `openai_base_url` alone: Codex keeps its +// Codex talks the OpenAI Responses API. Signed in to ChatGPT, it is +// routed through magpie with `openai_base_url` alone: Codex keeps its // built-in OpenAI provider and sign-in, so its own models, its threads // (listed per provider) and the Codex app's model picker stay as they are, // and magpie's gateway passes its own models through to OpenAI while it @@ -30,9 +30,14 @@ import ( // OpenAI's in /model. Not signed in, the built-in provider can't run, and // magpie is a provider of its own: a [model_providers.magpie] table, // `model_provider = "magpie"`, and a model catalog file for /model. So it -// is too for a ChatGPT account that has used its allowance up, which the -// Codex app won't send anything for, whoever serves the model, and when -// the user asks for it (the sign-in field's api): the Codex app is then in +// is too for Codex signed in with an API key, often one a relay issued: +// Codex then never asks for the model list (its models manager skips the +// fetch for an API key), so its picker was the models it was built with +// and the one set, magpie's others missing, and the built-in ones went to +// OpenAI with that key (#322). So it is too for a ChatGPT account that +// has used its allowance up, which the Codex app won't send anything for, +// whoever serves the model, and when the user asks for it (the sign-in +// field's api): the Codex app is then in // its API state rather than signed in to ChatGPT. The base URL is set then // too: a thread started on the built-in provider is opened on it again, and // a magpie model picked in it would otherwise go to the ChatGPT backend. @@ -270,7 +275,7 @@ func codexIn(at place) *Agent { // a ChatGPT account out of allowance keeps the Codex app from // sending at all, a magpie model's request too; as a provider // of Codex's own, magpie is past that - if !api() && codexSignedIn(dir) && !codexUsedUp() { + if !api() && codexChatGPT(dir) && !codexUsedUp() { if err := dropProvider(); err != nil { return err } @@ -367,6 +372,12 @@ func codexIn(at place) *Agent { if err := failover(); err != nil { return err } + // on a magpie model by the base URL alone with no ChatGPT + // sign-in, as an older magpie left a Codex signed in with an + // API key: its picker never had magpie's models (#322) + if m := get("model"); isMagpie(m) && viaBase() && get("model_provider") == "" && !codexChatGPT(dir) { + return set(m) + } // a table taken away before (by an older magpie) comes back // while magpie is wired, for the threads that name it if isMagpie(get("model")) && viaBase() && !hasProvider() { @@ -716,11 +727,11 @@ func codexFailover() bool { 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 { +// codexChatGPT reports whether Codex is signed in to a ChatGPT account: +// its built-in provider then runs and asks for the model list at +// openai_base_url. Signed in with an API key alone, it asks for none. +func codexChatGPT(dir string) bool { var a struct { - Key string `json:"OPENAI_API_KEY"` Tokens struct { Access string `json:"access_token"` } `json:"tokens"` @@ -729,7 +740,7 @@ func codexSignedIn(dir string) bool { if err != nil || json.Unmarshal(b, &a) != nil { return false } - return a.Key != "" || a.Tokens.Access != "" + return a.Tokens.Access != "" } // codexReached reads Codex's newest model request since a time — the diff --git a/internal/agent/codex_apikey_test.go b/internal/agent/codex_apikey_test.go new file mode 100644 index 000000000..d57f6fec8 --- /dev/null +++ b/internal/agent/codex_apikey_test.go @@ -0,0 +1,64 @@ +package agent + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// Signed in with an API key — a relay's, with the relay's own provider +// table — Codex never asks for the model list, so a base URL alone left its +// picker with the models it was built with and the one set. magpie is its +// provider instead, with every magpie model in the catalog, and stepping +// back to Codex's own model brings the relay's table back (#322). +func TestCodexAPIKeyUsesProvider(t *testing.T) { + home, read := codexHome(t, `{"OPENAI_API_KEY":"sk-relay"}`, + "model = \"gpt-5.5\"\nmodel_provider = \"relay\"\n\n[model_providers.relay]\nname = \"relay\"\nbase_url = \"https://relay.example/v1\"\nwire_api = \"responses\"\nrequires_openai_auth = true\n") + if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "k", Chat: "http://127.0.0.1:1/v1", Models: []string{"m1", "m2"}}); err != nil { + t.Fatal(err) + } + cx := codex(home) + if err := cx.Fields[0].Set("fake/m1"); err != nil { + t.Fatal(err) + } + cfg := read() + if !strings.Contains(cfg, `model_provider = "magpie"`) || !strings.Contains(cfg, "model_catalog_json") || + !strings.Contains(cfg, `openai_base_url = "`+codexGatewayURL()+`"`) || !strings.Contains(cfg, "[model_providers.relay]") { + t.Fatalf("\n%s", cfg) + } + b, err := os.ReadFile(filepath.Join(home, ".codex", "magpie-models.json")) + if err != nil || !strings.Contains(string(b), `"fake/m1"`) || !strings.Contains(string(b), `"fake/m2"`) { + t.Fatalf("catalog: %v %s", err, b) + } + if c := cx.Check(); c != "" { + t.Fatal(c) + } + if err := cx.Fields[0].Set("gpt-5.4"); err != nil { + t.Fatal(err) + } + if cfg = read(); !strings.Contains(cfg, `model_provider = "relay"`) || strings.Contains(cfg, "model_catalog_json") || + strings.Contains(cfg, "openai_base_url") || !strings.Contains(cfg, `model = "gpt-5.4"`) { + t.Fatalf("back:\n%s", cfg) + } +} + +// A Codex an older magpie routed by the base URL alone while it was signed +// in with an API key moves to magpie as its provider on the next sync. +func TestCodexAPIKeyBaseURLMoved(t *testing.T) { + home, read := codexHome(t, `{"OPENAI_API_KEY":"sk-relay"}`, + "model = \"fake/m1\"\nopenai_base_url = \""+codexGatewayURL()+"\"\n") + cx := codex(home) + if err := cx.Sync(); err != nil { + t.Fatal(err) + } + if cfg := read(); !strings.Contains(cfg, `model_provider = "magpie"`) || !strings.Contains(cfg, "model_catalog_json") || + !strings.Contains(cfg, `model = "fake/m1"`) { + t.Fatalf("\n%s", cfg) + } + if c := cx.Check(); c != "" { + t.Fatal(c) + } +} diff --git a/internal/agent/codex_route_test.go b/internal/agent/codex_route_test.go index 99cb462ca..9f28ac0e6 100644 --- a/internal/agent/codex_route_test.go +++ b/internal/agent/codex_route_test.go @@ -73,7 +73,7 @@ func TestCodexSignedInRoutesByBaseURL(t *testing.T) { // URL the next time a magpie model is picked, and its table stays: threads // started on it name it, and without it Codex can't open them (#129). func TestCodexSignedInLeavesProviderTable(t *testing.T) { - home, read := codexHome(t, `{"OPENAI_API_KEY":"sk-x"}`, + home, read := codexHome(t, `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`, "model = \"fake/m1\"\nmodel_provider = \"magpie\"\nmodel_catalog_json = \"/x/magpie-models.json\"\n\n[model_providers.magpie]\nname = \"magpie\"\nbase_url = \"http://127.0.0.1:3425/v1\"\nwire_api = \"responses\"\n") if err := codex(home).Fields[0].Set("fake/m1"); err != nil { t.Fatal(err) diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go index 0a7af0252..1a50ef55b 100644 --- a/internal/agent/sync_test.go +++ b/internal/agent/sync_test.go @@ -151,6 +151,7 @@ func TestSyncCatalogRewritesAgentLists(t *testing.T) { func TestSyncCatalogAgesCodexCache(t *testing.T) { home := syncHome(t) dir := filepath.Join(home, ".codex") + writeFile(t, filepath.Join(dir, "auth.json"), `{"tokens":{"access_token":"x","id_token":"x.e30.x"}}`) writeFile(t, filepath.Join(dir, "config.toml"), "model = \"relay/glm-4.6\"\nopenai_base_url = \""+codexGatewayURL()+"\"\n") cache := filepath.Join(dir, "models_cache.json") writeFile(t, cache, `{"fetched_at":"2026-09-25T10:00:00Z","etag":"W/\"v1\"","client_version":"0.155.1","models":[{"slug":"gpt-5.5"}]}`) diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 67f30c9a5..0dfaf0b96 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -258,8 +258,12 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri // 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 { - writeError(w, provider.Responses, 502, "OpenAI: "+err.Error()) - end(502, "OpenAI: "+err.Error(), 0, 0) + msg := "OpenAI: " + err.Error() + if rest == "/responses" { + msg = codexUnreached(modelOf(body), err) + } + writeError(w, provider.Responses, 502, msg) + end(502, msg, 0, 0) return } if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) { @@ -396,8 +400,6 @@ func withoutItem(body []byte, id string) ([]byte, bool) { return b, err == nil } -// apiKey reports whether Codex signed in with an API key rather than a -// ChatGPT account. // codexKeyRefused says why a model of Codex's own failed with 401: what // OpenAI said, and what to do about it. func codexKeyRefused(msg []byte) string { @@ -416,6 +418,18 @@ func codexKeyRefused(msg []byte) string { "or sign Codex in with ChatGPT, or with an OpenAI API key" } +// codexUnreached says why a model of Codex's own failed with 502: OpenAI, +// where it goes with Codex's own sign-in, couldn't be reached — often from +// a Codex whose only sign-in is a relay's key, whose own models it still +// lists (#322) — and what to do about it. +func codexUnreached(model string, err error) string { + return "OpenAI can't be reached (" + err.Error() + "). " + model + " is one of Codex's own models, " + + "which goes to OpenAI with Codex's own sign-in: pick one of magpie's models in Codex " + + "(provider/model, or set it in magpie's Agents view), or let Codex reach OpenAI" +} + +// apiKey reports whether Codex signed in with an API key rather than a +// ChatGPT account. func apiKey(h http.Header) bool { return strings.HasPrefix(strings.TrimPrefix(h.Get("Authorization"), "Bearer "), "sk-") } diff --git a/internal/gateway/codex_unreached_test.go b/internal/gateway/codex_unreached_test.go new file mode 100644 index 000000000..f0b181f2d --- /dev/null +++ b/internal/gateway/codex_unreached_test.go @@ -0,0 +1,30 @@ +package gateway + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// One of Codex's own models, when OpenAI can't be reached, fails saying so +// and what to do, not with the dial error alone (#322). +func TestCodexOwnModelUnreached(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + up := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + up.Close() + was := codexAPIBase + codexAPIBase = up.URL + t.Cleanup(func() { codexAPIBase = was }) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"gpt-5.5","input":"hi","stream":true}`)) + req.Header.Set("Authorization", "Bearer sk-relay-key") + New().Handler().ServeHTTP(rec, req) + body := rec.Body.String() + if rec.Code != 502 || !strings.Contains(body, "OpenAI can't be reached") || !strings.Contains(body, "gpt-5.5 is one of Codex's own models") || + !strings.Contains(body, "pick one of magpie's models") { + t.Fatalf("%d %s", rec.Code, body) + } +}