diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a7e5a145e..3500e2469 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -255,7 +255,7 @@ recorded as a prediction failure (`noPrediction`). - A translated Chat stream's tool calls are read by `index`, not as one after another (`chatDecoder.toolCall` in [`chat.go`](../../internal/gateway/chat.go)). An upstream may send several calls' fragments by turns (index 0, 1, 0, 1…), the first of each with its id and name; read as a new call at each change of index, two calls reached Codex as six `function_call` items, the first two with `{}` and four with no name (mysterious_dove on Discord). The open call streams as it comes; a call that starts while the open one's arguments aren't yet whole JSON is held by its index and given whole, in index order, at `finish_reason` or `[DONE]`. Every translation from Chat (Responses, Messages, Gemini, a whole reply) reads the stream through it. `TestInterleavedToolCallsToResponses`, `TestInterleavedToolCallsToAnthropic`, `TestInterleavedToolCallsWhole`, `TestToolCallsNamedFirstThenArgued` in [`translate_stream_test.go`](../../internal/gateway/translate_stream_test.go). - A relayed Chat reply whose choice made calls and ended `stop` ends `tool_calls`, streamed (`chatTidy`) and whole (`chatWhole`), as the translations' collector already ends it (`collector.finish`): told it stopped, a client that reads `finish_reason` ends its turn with the calls not run (喜欢一个人 on Discord, a relay in front of deepseek-v4.1-flash). Any other reason stays as it came. `TestChatCallsEndToolCalls` in [`chattidy_finish_test.go`](../../internal/gateway/chattidy_finish_test.go). - A Chat reply's call whose function names nothing in a JSON string — no name, null, another kind — is dropped, its later fragments with it, and a finish of `tool_calls` with no call left after the drop ends `stop` (a reply that came with no calls keeps its finish), and a whole reply given as a stream numbers the calls it keeps with no gap: streamed (`chatTidy`), whole (`chatWhole`) and a whole reply given to the agent as the stream it asked for (`chatWholeEvents`), since a client that checks the shape of every frame refuses the whole reply for one — the turn not retryable, the call already in the history, the session dead, while the gateway's own log says the reply went (AricRedemption, #1475). A nameless call runs nowhere, so it is no call, as a written block naming no offered tool is; a name the client reads as a string, empty included, goes as it came. `TestNamelessCallStreamDropped`, `TestNameAbsentStreamDropped`, `TestNamelessCallBesideAGoodOne`, `TestNamelessCallWholeDropped`, `TestNamelessCallWholeAsStreamDropped`, `TestNamelessCallWithoutAnIDStaysDropped`, `TestNamelessCallBesideAGoodOneWholeAsStream`, `TestToolCallsFinishWithNoCallsStaysWhole` in [`chat_call_name_test.go`](../../internal/gateway/chat_call_name_test.go). -- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models stay in it when they are kept out of other agents' lists for routing groups, by the codex provider "Only through routing groups" (`Provider.Unlisted`) or a group that unlists its members (`Group.Unlists`): Codex's own catalog (`catalogOf("codex")`, behind `ListedFor`/`CatalogFor`) keeps `CodexOwn` entries, so the Agents page shows its Codex section, its picker offers them as magpie's, and the desk file and `spawnChoices` list them. #1602 dropped them here, and the picker then still offered them through the own-models switch while the Codex app had none (士奇 on Discord, 10-28). They are hidden from Codex through Codex's list (`provider.CodexNativeHidden`, `TestCodexModelListKeepsOwnForGroups`, `TestCodexOwnModelsListedOnlyThroughGroups`). Every other agent, and every client of `/v1/models` (one that names no agent is `other` or its User-Agent's name, never `""`), is given `Catalog()`: a group listing alone keeps a signed-in subscription's models out of its list too. 88e6fb9cf had kept them for every agent (`SubscriptionKept`), so for a group of subscription models the option changed no list fetched over HTTP (shaoyang. on Discord, 11-03; `TestGroupAloneKeepsSubscriptionModelsOutOfEveryAgentsList`, `TestGroupAloneKeepsSubscriptionModelsOffAgentsModelList`). A backend answer that says the sign-in itself is revoked (`provider.SignInRevoked`, a 401 `token_revoked`; jjt on Discord, #4308) isn't passed through: the list is Codex's cached one (`codexcat.CacheEntries`) and magpie's, so the picker keeps magpie's models; any other refusal, a 401 `token_expired` among them, still is. The desk file does the same while the live list says revoked (`provider.CodexListRevoked`, `codexDesk.revoked`) (`TestCodexModelListRevokedSignIn`, `TestCodexDesktopCatalogRevokedSignIn`). +- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListedBeside`): every model but a ChatGPT account's own the sign-in's list has already, so a model only another account on in magpie has (a Team or Pro one beside a Free sign-in) is listed by magpie's id, `codex/`, and routed to that account (bigfisheatsmall on X: Codex kept signed in to a Free account, the Team account's models in dsh and not in Codex; `TestCodexListHasAnotherAccountsModels`, `TestCodexListOneAccountNoneTwice`). Its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models stay in it when they are kept out of other agents' lists for routing groups, by the codex provider "Only through routing groups" (`Provider.Unlisted`) or a group that unlists its members (`Group.Unlists`): Codex's own catalog (`catalogOf("codex")`, behind `ListedFor`/`CatalogFor`) keeps `CodexOwn` entries, so the Agents page shows its Codex section, its picker offers them as magpie's, and the desk file and `spawnChoices` list them. #1602 dropped them here, and the picker then still offered them through the own-models switch while the Codex app had none (士奇 on Discord, 10-28). They are hidden from Codex through Codex's list (`provider.CodexNativeHidden`, `TestCodexModelListKeepsOwnForGroups`, `TestCodexOwnModelsListedOnlyThroughGroups`). Every other agent, and every client of `/v1/models` (one that names no agent is `other` or its User-Agent's name, never `""`), is given `Catalog()`: a group listing alone keeps a signed-in subscription's models out of its list too. 88e6fb9cf had kept them for every agent (`SubscriptionKept`), so for a group of subscription models the option changed no list fetched over HTTP (shaoyang. on Discord, 11-03; `TestGroupAloneKeepsSubscriptionModelsOutOfEveryAgentsList`, `TestGroupAloneKeepsSubscriptionModelsOffAgentsModelList`). A backend answer that says the sign-in itself is revoked (`provider.SignInRevoked`, a 401 `token_revoked`; jjt on Discord, #4308) isn't passed through: the list is Codex's cached one (`codexcat.CacheEntries`) and magpie's, so the picker keeps magpie's models; any other refusal, a 401 `token_expired` among them, still is. The desk file does the same while the live list says revoked (`provider.CodexListRevoked`, `codexDesk.revoked`) (`TestCodexModelListRevokedSignIn`, `TestCodexDesktopCatalogRevokedSignIn`). - The Codex app and its VS Code extension read only the first 100 of that list by priority, hidden entries counted: each asks its app-server for `model/list` with `limit: 100` and never for the next page (ChatGPT.app 26.1013, openai.chatgpt 26.51021; the CLI's `/model` lists every one). So `codexcat.FitOwn` ranks the list last of all: hidden entries after every listed one, and, with more than 100 listed (`codexcat.AppList`), Codex's own listed models (the backend's entries in `codexMerged`; a ChatGPT account's `codex/…` ones, `codexcat.ChatGPTOwn`, on the other two routes) and then the models Codex used in the last 30 days (`usage.CodexUsed`, most recent first, at most 100) brought into the first 100 in the order they stood, the rest kept in theirs. The user's own order (`codexcat.Order`, #855) goes first, so an order that names only magpie's models (set while Codex's list had no Codex section, or before OpenAI added a model) no longer puts every GPT model past the 100th (maiya on Discord); the user takes one out of the app by hiding it in Codex's list. The same holds for `/v1/codex/models` (with the models that key's Codex used alone, `usage.CodexUsedBy`, before the 1 MiB cut) and the `model_catalog_json` magpie writes (`codexcat.CatalogUsed`). `codexListTag` carries a tag of the used set (`codexcat.UsedTag`), so the ETag and `X-Models-Etag` change when Codex uses a model it hadn't; `usage.CodexUsed` is read again a minute on, or at once when `Append` writes a Codex call to a model it doesn't hold (`codexUsedNew`). `TestCodexModelListKeepsUsedModelsInTheAppsHundred`, `TestCodexCatalogKeepsTheKeysUsedModelsFirst`, `TestFitKeepsUsedModelsWhereTheCodexAppReads`, `TestCodexUsed`, `TestCodexModelListKeepsOwnModelsInTheAppsHundred`, `TestFitOwnKeepsCodexsOwnInTheAppsHundred` and `TestCatalogUsedKeepsChatGPTOwn` cover it (@ZhenLuoTTAWDTT on X). - Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. The signature itself is kept in magpie's folder, `gemini-signatures/`, named by its hash (`keepSignature` in [`gemini_sigstore.go`](../../internal/gateway/gemini_sigstore.go)), and the id carries only the key (`__tsk16__`), so an id stays under 64 characters however long the step's signature (#2411: LobeHub's PostgreSQL index turned away a 3KB id). A key magpie no longer has, or whose file doesn't hash to it, reads as no signature; one not read for 90 days is removed. Where the folder can't be written, the id carries the signature as before. Across APIs, only Claude's reasoning is carried to a Responses client, below. - A Responses upstream reads only the reasoning it sealed itself (`encrypted_content`). When one answers that it can't read the sealed reasoning or compaction it was sent (`foreignReasoning` in [`affinity.go`](../../internal/gateway/affinity.go): OpenAI's and Codex's "could not be verified", xAI's "Could not decrypt", Azure's "invalid encrypted summary", a relay's compaction-blob refusal), `serve` asks once more without it and remembers its hashes for that conversation (`stickKey`) and key or account (`candidate.vendor`, `refusedSeals`), so the conversation's later turns there go without it the first time; the try is `fail: foreign`. A Responses client's own items go first (`withoutReasoning`, `withoutRefused`), then OpenAI's compaction (`withoutCompaction`). A Chat, Messages or Gemini client holds a Responses upstream's sealed reasoning in its calls' ids instead (`__rk__`, `carryReasoning` and `unreasonCalls` in [`reasoning_carry.go`](../../internal/gateway/reasoning_carry.go), 9da9bfabd), and every later turn of its history sends it again, so a conversation that moved to another Responses upstream or account (Grok to Codex after a 402, and back) was refused on that turn and every one after it (#4798, zane668, ZanderH-code). Such a refusal is asked again once too: `refuseCarried` remembers what the request's calls carried as refused by that key or account, and `translate` leaves those items out of this and every later request to it (`withoutRefusedCarry`, scoped to the try's provider through `withSealScope`). The calls, their arguments and results and the text go as the client wrote them, under the calls' own ids; the one that sealed an item, and every other key or account, is still given it. As for a Responses client, all the reasoning the request carried goes, the upstream's own earlier items among them; what it seals next goes along. `TestForeignSealAcrossGroupMembers`, `TestForeignCarriedReasoningAskedAgainWithout`. diff --git a/internal/agent/sync_test.go b/internal/agent/sync_test.go index 407a594e9..4155aa1d6 100644 --- a/internal/agent/sync_test.go +++ b/internal/agent/sync_test.go @@ -292,7 +292,7 @@ func TestSyncCatalogAgesCodexCache(t *testing.T) { t.Errorf("stale cache: %+v", c) } - fresh := `{"fetched_at":"2026-09-25T10:00:00Z","etag":` + string(must(json.Marshal(codexcat.WithTag(`W/"v1"`, codexcat.Tag(provider.CodexListed()))))) + `,"models":[]}` + fresh := `{"fetched_at":"2026-09-25T10:00:00Z","etag":` + string(must(json.Marshal(codexcat.WithTag(`W/"v1"`, provider.CodexListTag())))) + `,"models":[]}` writeFile(t, cache, fresh) SyncCatalog() if got := readFile(cache); got != fresh { diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 84236eb94..46ad1b257 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -2281,6 +2281,17 @@ func (s *Server) codexModels(w http.ResponseWriter, r *http.Request) { // provider, with magpie's models after them. The entries are written into. func codexMerged(own []any, cached bool) []any { defer provider.Hold()() + // the slugs the sign-in's list has, before the user's narrowing: a + // ChatGPT account's model it lacks is listed by magpie's id after it + // (provider.CodexListedBeside) + backend := make(map[string]bool, len(own)) + for _, m := range own { + if o, ok := m.(map[string]any); ok { + if slug, _ := o["slug"].(string); slug != "" { + backend[slug] = true + } + } + } // the windows the user set on the codex provider, as /v1/models says // them (#674); a cached entry, which keeps what magpie handed Codex // last, takes the account's own list's back when none is set @@ -2363,9 +2374,10 @@ func codexMerged(own []any, cached bool) []any { // keeps to its own models (#1385: 62 of magpie's were in its list) var ms []catalog.Model if !codexOwnOnly() { - ms = provider.CodexListed() + ms = provider.CodexListedBeside(backend) } - // Codex's own, as the user left them in its list + // Codex's own, as the user left them in its list, and a ChatGPT + // account's that the sign-in's list lacks mine := make(map[string]bool, len(own)) for _, m := range own { if o, ok := m.(map[string]any); ok { @@ -2374,6 +2386,11 @@ func codexMerged(own []any, cached bool) []any { } } } + for _, m := range ms { + if codexcat.ChatGPTOwn(m.ID) { + mine[m.ID] = true + } + } all := append(own, codexcat.Entries(ms, len(own)+100)...) if at, ok := provider.CodexOrder(); ok { codexcat.Order(all, at) diff --git a/internal/gateway/codex_pool_models_test.go b/internal/gateway/codex_pool_models_test.go index 1a16d0d4e..522fe9a6f 100644 --- a/internal/gateway/codex_pool_models_test.go +++ b/internal/gateway/codex_pool_models_test.go @@ -56,13 +56,13 @@ func codexPlanList(free bool) string { return string(b) } -// Raven on Discord: Codex signed in to a Free ChatGPT account, a Pro 5x -// ("prolite") one saved beside it and used first. The codex provider listed -// only the Free plan's three models, fetched with the sign-in Codex has, so -// GPT-6.1-Sol and the rest of the Pro plan's were nowhere to pick. Its list -// is now what the accounts together have, in the Pro plan's order, and a -// model only the Pro account has goes to it alone. -func TestCodexProviderListsEveryAccountsModels(t *testing.T) { +// codexFreeBesidePro signs Codex in to a Free ChatGPT account, saves a +// Pro 5x one on beside it, and points the backend at a fake that lists +// each plan's models and refuses the Free account the others. tried takes +// the account:model of each turn the backend was sent since it was last +// called. +func codexFreeBesidePro(t *testing.T) (tried func() string) { + t.Helper() home := t.TempDir() t.Setenv("HOME", home) t.Setenv("USERPROFILE", home) @@ -90,7 +90,7 @@ func TestCodexProviderListsEveryAccountsModels(t *testing.T) { }), 0o600) var mu sync.Mutex - var tried []string + var sent []string up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { acct := r.Header.Get("chatgpt-account-id") if strings.HasSuffix(r.URL.Path, "/models") { @@ -103,7 +103,7 @@ func TestCodexProviderListsEveryAccountsModels(t *testing.T) { b, _ := io.ReadAll(r.Body) json.Unmarshal(b, &q) mu.Lock() - tried = append(tried, acct+":"+q.Model) + sent = append(sent, acct+":"+q.Model) mu.Unlock() if acct == "acct-free" && !slices.Contains([]string{"gpt-6-luna", "gpt-5.6-terra", "gpt-5.6-luna"}, q.Model) { w.WriteHeader(400) @@ -120,6 +120,23 @@ func TestCodexProviderListsEveryAccountsModels(t *testing.T) { provider.CodexBase = up.URL + "/backend-api/codex" t.Cleanup(func() { provider.CodexBase = old }) + return func() string { + mu.Lock() + defer mu.Unlock() + got := strings.Join(sent, ",") + sent = nil + return got + } +} + +// Raven on Discord: Codex signed in to a Free ChatGPT account, a Pro 5x +// ("prolite") one saved beside it and used first. The codex provider listed +// only the Free plan's three models, fetched with the sign-in Codex has, so +// GPT-6.1-Sol and the rest of the Pro plan's were nowhere to pick. Its list +// is now what the accounts together have, in the Pro plan's order, and a +// model only the Pro account has goes to it alone. +func TestCodexProviderListsEveryAccountsModels(t *testing.T) { + tried := codexFreeBesidePro(t) p, err := provider.Find("codex") if err != nil { t.Fatal(err) @@ -152,11 +169,124 @@ func TestCodexProviderListsEveryAccountsModels(t *testing.T) { } code, body := post(t, "/v1/responses", `{"model":"codex/gpt-6.1-sol","input":"ping"}`) - mu.Lock() - got := strings.Join(tried, ",") - tried = nil - mu.Unlock() + got := tried() if code != 200 || !strings.Contains(body, "pong") || got != "acct-prolite:gpt-6.1-sol" { t.Fatalf("gpt-6.1-sol: status %d, tried %s: %s", code, got, body) } } + +// bigfisheatsmall on X: Codex kept signed in to a Free ChatGPT account, a +// Team one the only account on in magpie. dsh listed the Team plan's +// models; Codex, joined to magpie beside its sign-in, was handed the +// backend's list for the Free sign-in and magpie's models without any +// ChatGPT account's (CodexListed), so a model only the Team account has +// was in no picker of Codex's. Codex's list now has those by magpie's id, +// and a turn on one goes to the account that has it. +func TestCodexListHasAnotherAccountsModels(t *testing.T) { + tried := codexFreeBesidePro(t) + if err := provider.SetLoginOn("codex", "free@example.com", false); err != nil { + t.Fatal(err) + } + if err := provider.SetKeepLogin("codex", true); err != nil { + t.Fatal(err) + } + p, err := provider.Find("codex") + if err != nil { + t.Fatal(err) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + // as Codex asks: its own sign-in, the Free account's + free := func(req *http.Request) { + req.Header.Set("Authorization", "Bearer free-token") + req.Header.Set("chatgpt-account-id", "acct-free") + } + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", CodexPath+"/models", nil) + free(req) + New().Handler().ServeHTTP(rec, req) + var list struct { + Models []map[string]any `json:"models"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil { + t.Fatalf("status %d: %v: %s", rec.Code, err, rec.Body) + } + var slugs []string + for _, m := range list.Models { + slug, _ := m["slug"].(string) + slugs = append(slugs, slug) + if v, _ := m["visibility"].(string); slug == "codex/gpt-6.1-sol" && v != "list" { + t.Errorf("codex/gpt-6.1-sol is %q in Codex's picker, want list", v) + } + } + for _, want := range []string{"gpt-6-luna", "gpt-5.6-terra", "gpt-5.6-luna", "codex/gpt-6.1-sol", "codex/gpt-6-astra", "codex/gpt-5.5"} { + if !slices.Contains(slugs, want) { + t.Errorf("Codex's list lacks %s: %v", want, slugs) + } + } + // the Free plan's own stay as the backend lists them, never twice + for _, dup := range []string{"codex/gpt-6-luna", "codex/gpt-5.6-terra", "codex/gpt-5.6-luna"} { + if slices.Contains(slugs, dup) { + t.Errorf("Codex's list has %s beside the backend's own entry: %v", dup, slugs) + } + } + + rec = httptest.NewRecorder() + req = httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(`{"model":"codex/gpt-6.1-sol","input":"ping","stream":true}`)) + free(req) + New().Handler().ServeHTTP(rec, req) + if got := tried(); rec.Code != 200 || !strings.Contains(rec.Body.String(), "pong") || got != "acct-prolite:gpt-6.1-sol" { + t.Fatalf("codex/gpt-6.1-sol from Codex: status %d, tried %s: %s", rec.Code, got, rec.Body) + } + + // spawn_agent's models for a lead on another of magpie's models: the + // Free sign-in's (Codex's models_cache.json) and the Team plan's + // beyond them, by magpie's id + if err := os.WriteFile(catalog.CodexModelsCache(), []byte(codexPlanList(true)), 0o600); err != nil { + t.Fatal(err) + } + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Responses: "http://127.0.0.1:1/v1", Models: []string{"m1"}}); err != nil { + t.Fatal(err) + } + var spawn []string + for _, c := range spawnChoices(req, "relay/m1", true) { + spawn = append(spawn, c.slug) + } + for _, want := range []string{"gpt-6-luna", "codex/gpt-6.1-sol", "relay/m1"} { + if !slices.Contains(spawn, want) { + t.Errorf("spawn_agent's models lack %s: %v", want, spawn) + } + } + if slices.Contains(spawn, "codex/gpt-6-luna") { + t.Errorf("spawn_agent's models have codex/gpt-6-luna beside gpt-6-luna: %v", spawn) + } +} + +// One account, Codex's own sign-in: the backend lists every model it has, +// and Codex's list has none of them again by magpie's id. +func TestCodexListOneAccountNoneTwice(t *testing.T) { + codexFreeBesidePro(t) + ls := filepath.Join(filepath.Dir(provider.Path()), "logins.json") + if err := os.WriteFile(ls, []byte("[]"), 0o600); err != nil { + t.Fatal(err) + } + p, err := provider.Find("codex") + if err != nil { + t.Fatal(err) + } + if _, err := p.Fetch(context.Background()); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + req := httptest.NewRequest("GET", CodexPath+"/models", nil) + req.Header.Set("Authorization", "Bearer free-token") + req.Header.Set("chatgpt-account-id", "acct-free") + New().Handler().ServeHTTP(rec, req) + if strings.Contains(rec.Body.String(), `"codex/`) { + t.Fatalf("Codex's list has a codex/ model beside its own sign-in's: %s", rec.Body) + } + if !strings.Contains(rec.Body.String(), `"gpt-6-luna"`) { + t.Fatalf("Codex's list lacks its own gpt-6-luna: %s", rec.Body) + } +} diff --git a/internal/gateway/codex_spawn_models.go b/internal/gateway/codex_spawn_models.go index e8ecc1da5..d5b13ee1c 100644 --- a/internal/gateway/codex_spawn_models.go +++ b/internal/gateway/codex_spawn_models.go @@ -269,7 +269,8 @@ func spawnChoices(r *http.Request, lead string, codexPath bool) []spawnChoice { at int } var owns []own - for slug, e := range codexcat.CacheEntries() { + cached := codexcat.CacheEntries() + for slug, e := range cached { if v, _ := e["visibility"].(string); v != "list" || hidden[slug] || narrowed && !keep[slug] { continue } @@ -284,7 +285,13 @@ func spawnChoices(r *http.Request, lead string, codexPath bool) []spawnChoice { if sealed || codexOwnOnly() { return out } - for _, m := range provider.CodexListed() { + // and a ChatGPT account's own the sign-in's list lacks, by + // magpie's id, as codexMerged lists them + backend := make(map[string]bool, len(cached)) + for slug := range cached { + backend[slug] = true + } + for _, m := range provider.CodexListedBeside(backend) { out = append(out, spawnChoice{m.ID, m.Name}) } return out diff --git a/internal/provider/codex_models.go b/internal/provider/codex_models.go index 25add6ab2..2c2ef624e 100644 --- a/internal/provider/codex_models.go +++ b/internal/provider/codex_models.go @@ -522,6 +522,23 @@ func CodexListed() []catalog.Model { }, false) } +// CodexListedBeside is CodexListed for a Codex whose sign-in's list, from +// the backend, has the slugs in backend: with a ChatGPT account's own +// models that list lacks among them, by magpie's id (codex/), which +// reaches them through magpie on the account that has them. Codex signed +// in to a Free account, a Team one on in magpie beside it, was handed the +// Free plan's list alone, and the Team plan's models were in every agent +// but Codex (bigfisheatsmall on X), though the codex provider lists them +// (codexPoolModels) and routing sends them to that account. +func CodexListedBeside(backend map[string]bool) []catalog.Model { + shown, _ := CatalogFor("codex") + find := GroupFinder() + return codexListedIf(shown, func(id string) []Member { + _, ms, _ := find(id) + return ms + }, func(e Entry) bool { return !CodexOwn(e) || !backend[e.Model] }) +} + // CodexCatalog is shown as a Codex that names magpie its model_provider is // handed it from GET /v1/codex/models (#1281): every model, a ChatGPT // account's own among them, since that Codex reaches them through magpie's @@ -600,6 +617,17 @@ func CodexOwnListTag() string { return codexListTag("own") } // buildCodexListTag is codexListTag built afresh from the catalog. func buildCodexListTag(kind string) string { ms := CodexListed() + // and a ChatGPT account's own models, listed by magpie's id where the + // sign-in's list lacks them (CodexListedBeside): another account on + // gaining or losing one has Codex ask for the list again + if kind != "own" { + shown, _ := CatalogFor("codex") + for _, e := range shown { + if CodexOwn(e) { + ms = append(ms, catalog.Model{ID: "+" + e.ID}) + } + } + } off := slices.Sorted(maps.Keys(CodexNativeHidden())) for _, slug := range off { ms = append(ms, catalog.Model{ID: "-" + slug}) @@ -759,6 +787,11 @@ func codexWindowsTag() []catalog.Model { // account (buildResponses). own keeps a ChatGPT account's own models in, // which a signed-in Codex has from the backend already. func codexListed(shown []Entry, members func(id string) []Member, own bool) []catalog.Model { + return codexListedIf(shown, members, func(e Entry) bool { return own || !CodexOwn(e) }) +} + +// codexListedIf is codexListed for the entries of shown listed says. +func codexListedIf(shown []Entry, members func(id string) []Member, listed func(Entry) bool) []catalog.Model { var ms []catalog.Model // named among all shown: the account's own, which the backend lists, // are in Codex's picker beside these @@ -766,7 +799,6 @@ func codexListed(shown []Entry, members func(id string) []Member, own bool) []ca seen := described() s := settings.Load().ForAgent("codex") find := func(id string) (Group, []Member, bool) { return Group{}, members(id), true } - listed := func(e Entry) bool { return own || !CodexOwn(e) } apart := codexApart(shown, labels, listed) for i, e := range shown { if !listed(e) {