diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 14331834a..00391fb2e 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -257,8 +257,8 @@ recorded as a prediction failure (`noPrediction`). - 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. `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`. - 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`), 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` 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). +- 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). - A request whose key is a Claude sign-in (`claudeSignIn`: `Authorization: Bearer sk-ant-oat…`, Claude Code signed in to claude.ai with magpie as its base URL) is never told a 401, nor a 403 saying "OAuth token has been revoked". magpie never passes that sign-in on, so such an answer is a provider refusing magpie's credential, or one of magpie's own Claude accounts lapsing; told it, Claude Code renews its own sign-in before each of its retries (ten for one request) and then asks to `/login`. Any error whose message mentions x-api-key, whatever its status, Claude Code tells as "Not logged in · Please run /login" too. It is told as a 502 in magpie's words, an `api_error` saying " refused magpie's credential (HTTP 401): …" with x-api-key said as "API key", and any other error such a request is told keeps its status with x-api-key said as "API key", as does a stream's error after its 200 (`keepsSignIn`, `claude_signin.go`). Recent calls and the usage log keep the provider's status and message. Any other 403, and a request with magpie's key or an API key, is answered as before. The sign-in's beta (`oauth-…` in `anthropic-beta`) isn't passed on either (`askedBetas`), so a provider gets the request as Claude Code with magpie's key sends it; a provider's own `header.anthropic-beta` still goes. - A 400 that names betas a provider doesn't take, in Bedrock's words ("Unexpected value(s) `x` for the `anthropic-beta` header", `unexpectedBetas`) or Copilot's ("unsupported beta header(s): x, y", `unsupportedBetas`), is asked again at once without them, and they are left out for that provider from then on (`refuseBetas`, `markUnfit`). Copilot turns away `tool-search-tool-2025-10-19`, which Claude Code in Claude Desktop's Code tab asks with tool search on, and answers the same request without it (bigcat1800, `TestCopilotUnsupportedBetasLeftOut`). - A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that begins neither as JSON nor as an event stream. A reply whose first bytes are an event stream's (`event:`, `data:`, a `:` comment) is read as one under any Content-Type it names (`eventStream`, `eventsStart`): before, a stream under another type (`application/octet-stream`, say) was held whole and reached the agent only at its end, and one under `application/json` was a 502 (uk.jent on Discord: MiniMax Code to Grok Build showed each thinking block "Thought for 0.0s"; `TestPluginThinkingStreamsAsItComes`). Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 54427b71b..9befe082c 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -1107,10 +1107,14 @@ type cUsage struct { ReasoningTokens int `json:"reasoning_tokens"` } `json:"completion_tokens_details,omitempty"` // what others say was read from their cache, when prompt_tokens_details - // doesn't: DeepSeek's hits, Moonshot's cached_tokens, and Anthropic's - // own names from relays in front of Claude + // doesn't: DeepSeek's hits, Moonshot's cached_tokens, Mistral's + // num_cached_tokens (its older top-level count, which its API still + // sends beside or instead of prompt_tokens_details, counted in + // prompt_tokens as OpenAI's is), and Anthropic's own names from relays + // in front of Claude PromptCacheHitTokens int `json:"prompt_cache_hit_tokens"` CachedTokens int `json:"cached_tokens"` + NumCachedTokens int `json:"num_cached_tokens"` CacheReadInputTokens int `json:"cache_read_input_tokens"` CacheCreationInputTokens int `json:"cache_creation_input_tokens"` // Credit is what WorkBuddy says the request cost in its plan's credits @@ -1137,7 +1141,7 @@ func (u cUsage) usage() Usage { if d := u.PromptTokensDetails; d != nil { out.CacheRead, out.CacheWrite = d.CachedTokens, d.CacheWriteTokens } - for _, n := range []int{u.PromptCacheHitTokens, u.CachedTokens} { + for _, n := range []int{u.PromptCacheHitTokens, u.CachedTokens, u.NumCachedTokens} { if out.CacheRead == 0 { out.CacheRead = n } diff --git a/internal/gateway/chattidy.go b/internal/gateway/chattidy.go index 86276043b..4df9732c4 100644 --- a/internal/gateway/chattidy.go +++ b/internal/gateway/chattidy.go @@ -63,8 +63,8 @@ import ( // // And a usage that tells the cache only in another vendor's names // (Anthropic's cache_read_input_tokens from a relay in front of a model, -// DeepSeek's prompt_cache_hit_tokens or Moonshot's cached_tokens beside a -// 0 in prompt_tokens_details) is told in OpenAI's too (openAIUsage): the +// DeepSeek's prompt_cache_hit_tokens, Mistral's num_cached_tokens or +// Moonshot's cached_tokens beside a 0 in prompt_tokens_details) is told in OpenAI's too (openAIUsage): the // gateway counted the hit, but an agent on pi-ai (DeepSeek Harness), which // reads prompt_tokens_details.cached_tokens first, showed none. // @@ -175,13 +175,13 @@ var ( usageField = []byte(`"usage"`) cachedTokensField = []byte(`"cached_tokens"`) // the names other than OpenAI's that cUsage reads a cache in - otherCacheFields = [][]byte{[]byte(`"prompt_cache_hit_tokens"`), + otherCacheFields = [][]byte{[]byte(`"prompt_cache_hit_tokens"`), []byte(`"num_cached_tokens"`), []byte(`"cache_read_input_tokens"`), []byte(`"cache_creation_input_tokens"`)} ) // mayMendUsage reports whether b has a usage that may tell its cache in // names other than OpenAI's, which openAIUsage may have to tell again: -// DeepSeek's or Anthropic's, or Moonshot's top-level cached_tokens beside +// DeepSeek's, Mistral's or Anthropic's, or Moonshot's top-level cached_tokens beside // prompt_tokens_details' own. A usage in OpenAI's names alone, every // OpenAI reply, is left unread. func mayMendUsage(b []byte) bool { @@ -198,7 +198,7 @@ func mayMendUsage(b []byte) bool { // openAIUsage is a Chat usage whose cache cUsage reads in names other than // OpenAI's (Anthropic's from a relay, DeepSeek's prompt_cache_hit_tokens, -// Moonshot's cached_tokens), told in OpenAI's as well: what was read in +// Mistral's num_cached_tokens, Moonshot's cached_tokens), told in OpenAI's as well: what was read in // prompt_tokens_details.cached_tokens, what was written in its // cache_write_tokens (OpenRouter's), and prompt_tokens counting both, as // OpenAI's does. An agent reads prompt_tokens_details first, pi-ai (DeepSeek diff --git a/internal/gateway/usage_cache_agent_test.go b/internal/gateway/usage_cache_agent_test.go index fbc5b2d73..ad02c5020 100644 --- a/internal/gateway/usage_cache_agent_test.go +++ b/internal/gateway/usage_cache_agent_test.go @@ -101,6 +101,8 @@ func TestAgentReadsCacheTokensOnEveryRoute(t *testing.T) { {"chat-deepseek", provider.Chat, 0}, {"chat-zero-details", provider.Chat, 0}, {"chat-moonshot", provider.Chat, 0}, + {"chat-mistral", provider.Chat, 0}, + {"chat-mistral-zero-details", provider.Chat, 0}, {"responses", provider.Responses, 0}, {"gemini", provider.Gemini, 0}, } @@ -156,6 +158,7 @@ func TestOpenAIUsageLeavesOpenAIsAlone(t *testing.T) { `{"prompt_tokens":352,"completion_tokens":7,"total_tokens":359,"prompt_tokens_details":{"cached_tokens":300}}`, `{"prompt_tokens":52,"completion_tokens":7,"total_tokens":59}`, `{"prompt_tokens":52,"completion_tokens":7,"total_tokens":59,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":0}`, + `{"prompt_tokens":52,"completion_tokens":7,"total_tokens":59,"num_cached_tokens":0}`, `null`, `"x"`, } { @@ -183,6 +186,7 @@ func TestMayMendUsageOnlyOtherNames(t *testing.T) { `{"usage":{"prompt_tokens":352,"prompt_tokens_details":{"cached_tokens":300}}}`: false, `{"usage":{"prompt_tokens":352}}`: false, `{"usage":{"prompt_tokens":352,"prompt_cache_hit_tokens":300}}`: true, + `{"usage":{"prompt_tokens":352,"num_cached_tokens":300}}`: true, `{"usage":{"prompt_tokens":12,"cache_read_input_tokens":300}}`: true, `{"usage":{"prompt_tokens":352,"prompt_tokens_details":{"cached_tokens":0},"cached_tokens":300}}`: true, `{"choices":[],"prompt_cache_hit_tokens":300}`: false, diff --git a/internal/gateway/usage_cache_test.go b/internal/gateway/usage_cache_test.go index dc22bf985..c945ff7c4 100644 --- a/internal/gateway/usage_cache_test.go +++ b/internal/gateway/usage_cache_test.go @@ -49,7 +49,7 @@ func (v cachingVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { "event: message_delta\ndata: " + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":7}}`, "event: message_stop\ndata: " + `{"type":"message_stop"}`, } - case "chat", "chat-anthropic-names", "chat-deepseek", "chat-zero-details", "chat-moonshot": + case "chat", "chat-anthropic-names", "chat-deepseek", "chat-zero-details", "chat-moonshot", "chat-mistral", "chat-mistral-zero-details": u := map[string]string{ // OpenAI's: prompt_tokens counts the cached ones too "chat": `{"prompt_tokens":352,"completion_tokens":7,"total_tokens":359,"prompt_tokens_details":{"cached_tokens":300}}`, @@ -61,6 +61,10 @@ func (v cachingVendor) ServeHTTP(w http.ResponseWriter, r *http.Request) { "chat-zero-details": `{"prompt_tokens":352,"completion_tokens":7,"total_tokens":359,"prompt_tokens_details":{"cached_tokens":0},"prompt_cache_hit_tokens":300,"prompt_cache_miss_tokens":52}`, // Moonshot's top-level cached_tokens beside a 0 of OpenAI's "chat-moonshot": `{"prompt_tokens":352,"completion_tokens":7,"total_tokens":359,"prompt_tokens_details":{"cached_tokens":0},"cached_tokens":300}`, + // Mistral's older top-level num_cached_tokens, alone and beside + // a 0 of OpenAI's, counted in prompt_tokens (daoche_wuzui on X) + "chat-mistral": `{"prompt_tokens":352,"completion_tokens":7,"total_tokens":359,"num_cached_tokens":300}`, + "chat-mistral-zero-details": `{"prompt_tokens":352,"completion_tokens":7,"total_tokens":359,"prompt_tokens_details":{"cached_tokens":0},"num_cached_tokens":300}`, }[v.wire] whole = `{"id":"c1","object":"chat.completion","model":"m1","choices":[{"index":0,"message":{"role":"assistant","content":"hi"},"finish_reason":"stop"}],"usage":` + u + `}` events = []string{ @@ -117,6 +121,8 @@ func TestUsageRecordsCacheTokensOnEveryRoute(t *testing.T) { {"chat-deepseek", provider.Chat, want{52, 300, 0}}, {"chat-zero-details", provider.Chat, want{52, 300, 0}}, {"chat-moonshot", provider.Chat, want{52, 300, 0}}, + {"chat-mistral", provider.Chat, want{52, 300, 0}}, + {"chat-mistral-zero-details", provider.Chat, want{52, 300, 0}}, {"responses", provider.Responses, want{52, 300, 0}}, {"gemini", provider.Gemini, want{52, 300, 0}}, }