diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 9d192cfbc..a90757f5e 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -277,6 +277,7 @@ the key's leaves the call as asked, with a log line (`compactRefused`). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. - A group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "/" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. On a provider the user added by its address (`OwnFast`, a GPT or o-series model on an OpenAI API) the member's button goes on to Ultrafast when OpenAI offers the tier on the model: one of Codex's accounts lists it, or Codex's own `models_cache.json` entry for the slug does (`codexcat.OwnOffers`, the entry `ownTiers` already offers Codex), and the tier is only asked for, as its Fast is: a provider that turns the field away is asked again without it (KoiLx0 on X). A fast member never goes slower than the provider's extraBody asks: its `service_tier` `ultrafast` (forced or not) makes a Fast member go Ultrafast (`extraUltra`), a slower one (`flex`) gives way to the member's Fast, and a forced `!service_tier` still goes as written over all of them (`TestFastMemberOwnProviderExtraTier`, `TestCanUltraOwnProvider`, `group-member-fast.test.cjs`). `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`. - Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`. +- A client's `service_tier: "fast"`, Codex's own name for its Fast mode, is read as `priority` on Chat and Responses as the main handler takes the body (`fastTier` in [`codex_tier.go`](../../internal/gateway/codex_tier.go), before the Codex and key tiers above and before `tier_asked` is noted), and `codexBody` sends it as `priority` too. Codex itself never sends `fast`: its `ServiceTier::from_request_value` reads `fast` and `priority` alike as Fast and `request_value` sends `priority` (openai/codex `codex-rs/protocol/src/config_types.rs`). Before, `fast` was dropped on the way to a ChatGPT account (`codexBody` kept only `priority` and `ultrafast`) and never set the IR's Fast (Archivemylife on X). Claude's equivalent is `speed: "fast"` (Anthropic's own `service_tier`, `auto`/`standard_only`, is about capacity, not speed), already read as Fast. The ChatGPT backend's reply says `auto` and then `default` whether priority ran or not (`servedTierAt`): on gpt-6.1-sol a `fast` ask decoded at about 29 tok/s against about 22 without, both answered `default`. `TestFastTierWordReachesCodex`, `TestCodexBodyServiceTier`. - The Codex client magpie presents to the ChatGPT backend (`settings.CodexClient`, a row in Codex's settings, ouhthuo on X) is Codex CLI by default (`originator: codex_cli_rs`, `User-Agent: codex_cli_rs/ (; ) `) or `desktop`: `originator: Codex Desktop` and `Codex Desktop/ (; ) unknown (Codex Desktop; )`, as codex-rs `default_client.rs` builds it from the originator the app sets. Only these two values are accepted. `codexClientHeaders` in `internal/provider/codex_request.go` is the one place both headers are set, so a model request (`codexSign`), the account calls (`/wham`, resets, token refresh, device sign-in) and a test asked as Codex all follow it; the sign-in's authorize URL keeps `codex_cli_rs`. A real Codex client's own originator never reaches the backend on a signed-in account: `codexSign` replaces it, which this setting now chooses. - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`, Moonshot's top-level `cached_tokens`, Mistral's older top-level `num_cached_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic `cache_read_input_tokens` and `cache_creation_input_tokens`, DeepSeek's `prompt_cache_hit_tokens`, Mistral's `num_cached_tokens` or Moonshot's top-level `cached_tokens` beside a 0 in `prompt_tokens_details`) is told in OpenAI's too, streamed (`chatTidy`) and whole (`chatWhole`), by `openAIUsage` in [`chattidy.go`](../../internal/gateway/chattidy.go): `prompt_tokens_details.cached_tokens` (and `cache_write_tokens`), with `prompt_tokens` and `total_tokens` made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (`mayMendUsage`). pi-ai, which DeepSeek Harness and Pi use, reads `prompt_tokens_details.cached_tokens` first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. `TestAgentReadsCacheTokensOnEveryRoute`, `TestPluginAgentReadsCacheTokens`, `TestOpenAIUsageLeavesOpenAIsAlone`, `TestMayMendUsageOnlyOtherNames` in [`usage_cache_agent_test.go`](../../internal/gateway/usage_cache_agent_test.go). diff --git a/internal/gateway/codex_fast_word_test.go b/internal/gateway/codex_fast_word_test.go new file mode 100644 index 000000000..cce8d09ca --- /dev/null +++ b/internal/gateway/codex_fast_word_test.go @@ -0,0 +1,72 @@ +package gateway + +import ( + "net/http" + "net/url" + "testing" + + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/provider" +) + +// Archivemylife on X: a Responses request for a Codex account's model with +// service_tier "fast", Codex's own name for its Fast mode, reached the +// ChatGPT backend with no tier at all. Codex sends Fast as "priority" +// (ServiceTier::request_value in openai/codex), so "fast" goes as +// "priority" on every OpenAI API it can arrive on, and the route says the +// tier was asked; Claude's speed "fast" already did. Another tier, and a +// request with none, goes as before. +func TestFastTierWordReachesCodex(t *testing.T) { + codexSignedIn(t) + d := daybreak(t) + to, _ := url.Parse(provider.CodexBase) + provider.CodexBase = "https://chatgpt.com/backend-api/codex" + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + return http.DefaultTransport.RoundTrip(r) + })} + const m = `"model":"codex/gpt-daybreak-blue-latest"` + const msgs = `"messages":[{"role":"user","content":"Respond with OK."}]` + for _, c := range []struct{ name, path, body, want string }{ + {"Responses, fast", "/v1/responses", `{` + m + `,"input":"Respond with OK.","stream":true,"service_tier":"fast"}`, "priority"}, + {"Responses, whole, fast", "/v1/responses", `{` + m + `,"input":"Respond with OK.","service_tier":"fast"}`, "priority"}, + {"Responses, priority", "/v1/responses", `{` + m + `,"input":"Respond with OK.","stream":true,"service_tier":"priority"}`, "priority"}, + {"Chat, fast", "/v1/chat/completions", `{` + m + `,"stream":true,` + msgs + `,"service_tier":"fast"}`, "priority"}, + {"Chat, whole, fast", "/v1/chat/completions", `{` + m + `,` + msgs + `,"service_tier":"fast"}`, "priority"}, + {"Messages, speed fast", "/v1/messages", `{` + m + `,"max_tokens":64,"stream":true,` + msgs + `,"speed":"fast"}`, "priority"}, + {"Responses, flex", "/v1/responses", `{` + m + `,"input":"Respond with OK.","stream":true,"service_tier":"flex"}`, ""}, + {"Responses, none", "/v1/responses", `{` + m + `,"input":"Respond with OK.","stream":true}`, ""}, + {"Chat, none", "/v1/chat/completions", `{` + m + `,"stream":true,` + msgs + `}`, ""}, + } { + r := postFrom(t, s, "opencode", c.path, c.body) + b := d.last(t) + if got := gjson.GetBytes(b, "service_tier").String(); got != c.want { + t.Errorf("%s: the backend got service_tier %q, want %q: %s", c.name, got, c.want, b) + } + if c.want != "" && r.Tier != "priority" && r.Tier != "fast" { + t.Errorf("%s: the route says tier %q was asked", c.name, r.Tier) + } + } +} + +// fastTier changes "fast" alone, and only as a top-level string; every +// other body comes back byte for byte. +func TestFastTier(t *testing.T) { + if got := gjson.GetBytes(fastTier([]byte(`{"model":"m","service_tier":"fast","input":"hi"}`)), "service_tier").String(); got != "priority" { + t.Errorf("fast went as %q", got) + } + for _, in := range []string{ + `{"model":"m","service_tier":"priority"}`, + `{"model":"m","service_tier":"flex"}`, + `{"model":"m","service_tier":"Fast"}`, + `{"model":"m","metadata":{"service_tier":"fast"}}`, + `{"model":"m","service_tier":["fast"]}`, + `{"model":"m"}`, + `not json`, + } { + if got := string(fastTier([]byte(in))); got != in { + t.Errorf("fastTier(%s) = %s", in, got) + } + } +} diff --git a/internal/gateway/codex_tier.go b/internal/gateway/codex_tier.go index e9a0593b7..6f212c5f1 100644 --- a/internal/gateway/codex_tier.go +++ b/internal/gateway/codex_tier.go @@ -5,6 +5,8 @@ import ( "net/http" "strings" + "github.com/tidwall/gjson" + "github.com/yetone/magpie/internal/access" "github.com/yetone/magpie/internal/provider" "github.com/yetone/magpie/internal/settings" @@ -55,6 +57,22 @@ func keyTiered(r *http.Request, body []byte, model string) []byte { return withServiceTier(body, set) } +// fastTier is body with a service_tier of "fast" as "priority", every +// other byte as it came. "fast" is Codex's own name for its Fast mode, +// which Codex sends as "priority" and nothing else +// (ServiceTier::from_request_value in openai/codex's config_types.rs, +// which reads "fast" and "priority" alike as Fast): a client that writes +// Codex's word (Archivemylife on X, gpt-6.1-sol on a Codex account) had +// it dropped by the ChatGPT backend's filter (codexBody) and by every +// check of the IR's Fast, which go by "priority". Any other tier, and a +// body with none, goes as it came. +func fastTier(body []byte) []byte { + if t := topValue(body, tierField); t.Type != gjson.String || t.Str != "fast" { + return body + } + return withServiceTier(body, "priority") +} + // withServiceTier is body with its top-level service_tier set to tier, or // without one for "", every other byte as it came. A body that isn't a // JSON object goes as it came. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index dbaf06c92..7ef4c1622 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -2324,6 +2324,11 @@ func (s *Server) handle(from provider.Protocol) http.HandlerFunc { return } noteAsked(r.Context(), model) + // service_tier "fast", Codex's older word for its Fast, in the + // word Codex sends it in (fastTier, Archivemylife on X) + if from == provider.Responses || from == provider.Chat { + body = fastTier(body) + } // Qoder 1.1.82 and later name no session: the one of its own // session files the request holds the prompts of (qoder_session.go) r = qoderSession(r, from, body) diff --git a/internal/provider/codex_request.go b/internal/provider/codex_request.go index e52f7c52e..226ebc2b3 100644 --- a/internal/provider/codex_request.go +++ b/internal/provider/codex_request.go @@ -305,7 +305,7 @@ func codexInstructions(model string) string { // streams only, keeps nothing (so its items carry no ids), carries Codex's // instructions — the client's own riding first in the input — and rejects // the sampling knobs, explicit cache options and any service tier but -// Fast's and Ultrafast's. +// Fast's ("fast" sent as "priority") and Ultrafast's. func codexBody(body []byte) []byte { dec := json.NewDecoder(bytes.NewReader(body)) dec.UseNumber() @@ -321,8 +321,12 @@ func codexBody(body []byte) []byte { for _, k := range []string{"max_output_tokens", "max_completion_tokens", "temperature", "top_p", "previous_response_id", "user", "safety_identifier", "prompt_cache_options"} { delete(m, k) } - // Codex's Fast mode sends "priority", its Ultrafast "ultrafast"; any - // other tier stays out + // Codex's Fast mode sends "priority", its Ultrafast "ultrafast"; its + // older word for Fast, "fast", goes as Codex sends it (Archivemylife + // on X); any other tier stays out + if m["service_tier"] == "fast" { + m["service_tier"] = "priority" + } if t := m["service_tier"]; t != "priority" && t != "ultrafast" { delete(m, "service_tier") } diff --git a/internal/provider/codex_request_test.go b/internal/provider/codex_request_test.go index e96e1413f..105c921c3 100644 --- a/internal/provider/codex_request_test.go +++ b/internal/provider/codex_request_test.go @@ -279,7 +279,8 @@ func TestCodexPromptsSameMtime(t *testing.T) { } // Codex's Fast mode reaches the ChatGPT backend as service_tier "priority", -// its Ultrafast as "ultrafast"; any other tier is dropped as before. +// whether asked as "priority" or "fast", its Ultrafast as "ultrafast"; any +// other tier is dropped as before. func TestCodexBodyServiceTier(t *testing.T) { t.Setenv("CODEX_HOME", t.TempDir()) t.Setenv("XDG_CACHE_HOME", t.TempDir()) @@ -295,7 +296,12 @@ func TestCodexBodyServiceTier(t *testing.T) { if v, _ := tier(`{"model":"gpt-6-sol","service_tier":"ultrafast","input":"hi"}`); v != "ultrafast" { t.Errorf("ultrafast: %v", v) } - for _, s := range []string{`"flex"`, `"auto"`, `"default"`, `"fast"`, `null`} { + // "fast", Codex's older word for Fast, as Codex sends it (Archivemylife + // on X) + if v, _ := tier(`{"model":"gpt-6-sol","service_tier":"fast","input":"hi"}`); v != "priority" { + t.Errorf("fast: %v", v) + } + for _, s := range []string{`"flex"`, `"auto"`, `"default"`, `"Fast"`, `null`} { if v, ok := tier(`{"model":"gpt-6-sol","service_tier":` + s + `,"input":"hi"}`); ok { t.Errorf("%s kept as %v", s, v) }