diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ebe48c103..cb270dd60 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -191,6 +191,7 @@ recorded as a prediction failure (`noPrediction`). - 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 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 doesn't begin as JSON. 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. - An error status whose body holds no message of its own says what it was (`provider.Unsaid`, through `APIError` and the plan-quota and drawing readers): a web page by its title as plain words, a firewall's block page (`EdgeBlocked`: Alibaba Cloud's, Cloudflare's "you have been blocked", "used Cloudflare to restrict access" and `error code: 1005`–`1020`) with `BlockedHint` after it, and an empty body under an HTTP status as refused with no details, often a firewall or proxy in front of the API (`NoDetails`; an empty `response.failed` event, whose fallback is no status, still reads "upstream stream failed"). A bare "403 Forbidden" told a relay's user nothing (maralica on Discord). A JSON error still reads as its message. `TestAPIErrorUnsaid`, `TestRelayRefusalSaysWhatItWas`. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A 400 that is no error at all, from OpenCode's gateway (`openCodeBareRefusal` in `forwardOnce`, #3740), is the 502 it stands for: OpenCode Go answered s-leeq's requests `400 {"model":"deepseek-v4.1-flash"}`, the model's name and nothing else, with nothing in or out, and the same request was answered some seconds later (13s to 25s in their timelines). A body any error field names goes on as it came (the missing `x-opencode-session` refusal among it), and so does a body that isn't a JSON object, or one over 64KB; a body is never cut. Read as the 502, a group's next member is asked, and a lone provider is asked again within its patience, which outlasts that window, where the 400 ended the turn at once. The failure is tied to the request (30 of 214 requests with ~246K tokens of tools, none of 420 with under 1K), so nobody rests for it (`restAfterMarked`, `openCodeBare`): the key goes on serving the requests it serves. Only OpenCode's hosts are read this way; every other vendor's bare 400 stays as it came. (`TestOpenCodeGoBare400AskedAgain`, `TestOpenCodeGoBare400ToldAs502`, `TestOpenCodeGoBare400RestsNobody`, `TestOpenCodeGoError400Untouched`) diff --git a/internal/gateway/betas.go b/internal/gateway/betas.go index e48eea5fa..223e18e88 100644 --- a/internal/gateway/betas.go +++ b/internal/gateway/betas.go @@ -147,16 +147,27 @@ var unexpectedBetas = regexp.MustCompile("(?i)unexpected values?(?:\\(s\\))?\\s+ var backquoted = regexp.MustCompile("`([^`]+)`") +// unsupportedBetas is Copilot's word for the same: 400 "unsupported beta +// header(s): tool-search-tool-2025-10-19", the name Claude Code asks tool +// search by in Claude Desktop's Code tab once its toolSearchEnabled policy +// is on. Copilot answers the same request without it, defer_loading tools +// and all (and with advanced-tool-use-2025-11-20). +var unsupportedBetas = regexp.MustCompile(`(?i)unsupported beta headers?(?:\(s\))?:\s*([a-z0-9][a-z0-9._-]*(?:\s*,\s*[a-z0-9][a-z0-9._-]*)*)`) + // refuseBetas reads the betas an error from p names as unknown, remembers // them so p isn't asked them again, and returns those it hadn't already. func (s *Server) refuseBetas(p provider.Provider, errBody []byte) []string { - m := unexpectedBetas.FindSubmatch(errBody) - if m == nil { - return nil + var named []string + if m := unexpectedBetas.FindSubmatch(errBody); m != nil { + for _, q := range backquoted.FindAllSubmatch(m[1], -1) { + named = append(named, string(q[1])) + } + } else if m := unsupportedBetas.FindSubmatch(errBody); m != nil { + named = strings.Split(string(m[1]), ",") } var fresh []string - for _, q := range backquoted.FindAllSubmatch(m[1], -1) { - b := strings.TrimSpace(string(q[1])) + for _, b := range named { + b = strings.TrimSpace(b) if b != "" && s.fits(p.ID, betaKey(b), provider.Anthropic) { s.markUnfit(p.ID, betaKey(b), provider.Anthropic) fresh = append(fresh, b) diff --git a/internal/gateway/user_betas_test.go b/internal/gateway/user_betas_test.go index ae501bde8..242201830 100644 --- a/internal/gateway/user_betas_test.go +++ b/internal/gateway/user_betas_test.go @@ -18,6 +18,8 @@ type betaRelay struct { mu sync.Mutex refuses []string seen [][]string + // copilot words the refusal as Copilot's Messages API does + copilot bool } func (b *betaRelay) ServeHTTP(w http.ResponseWriter, r *http.Request) { @@ -33,6 +35,12 @@ func (b *betaRelay) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } } + if len(bad) > 0 && b.copilot { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"error":{"message":"unsupported beta header(s): `+strings.ReplaceAll(strings.Join(bad, ", "), "`", "")+`","code":"invalid_request_body"}}`) + return + } if len(bad) > 0 { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusBadRequest) @@ -97,6 +105,45 @@ func TestUserBetasMergeWithTheAgents(t *testing.T) { } } +// bigcat1800 on Discord: Claude Desktop's Code tab, its tool search on, +// asks tool-search-tool-2025-10-19, and Copilot turns the name away: 400 +// "Copilot: unsupported beta header(s): tool-search-tool-2025-10-19" +// reached Claude Code. The gateway reads Copilot's wording as it reads +// Bedrock's: asked again at once without the betas named, and not asked +// them again. +func TestCopilotUnsupportedBetasLeftOut(t *testing.T) { + fresh(t) + up := &betaRelay{copilot: true, refuses: []string{"tool-search-tool-2025-10-19", "effort-2025-11-24"}} + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL, + Models: []string{"claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + s := New() + ask := func() { + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader( + `{"model":"relay/claude-opus-5-5","max_tokens":20,"messages":[{"role":"user","content":"ping"}],"tools":[{"name":"mcp__big__tool_7","input_schema":{"type":"object"},"defer_loading":true}]}`)) + req.Header.Set("User-Agent", "claude-cli/2.1.309 (external, claude-desktop-3p, agent-sdk/0.3.309)") + req.Header.Set("anthropic-beta", "claude-code-20250219,interleaved-thinking-2025-05-14,tool-search-tool-2025-10-19,effort-2025-11-24") + s.Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("status %d: %s", rec.Code, rec.Body) + } + } + ask() + want := []string{"claude-code-20250219,interleaved-thinking-2025-05-14"} + if got := up.last(); !slices.Equal(got, want) { + t.Fatalf("betas sent %q, want %q", got, want) + } + n := len(up.seen) + ask() + if got := up.last(); len(up.seen) != n+1 || !slices.Equal(got, want) { + t.Fatalf("again: %d calls, betas %q", len(up.seen)-n, got) + } +} + // A request with no betas of its own sends the user's alone. func TestUserBetasAlone(t *testing.T) { fresh(t)