diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 6a081cf26..b5530c791 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -192,7 +192,7 @@ recorded as a prediction failure (`noPrediction`). - 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. +- 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. - 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`) - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 7c6d16ca2..783ebcb4e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -6609,24 +6609,23 @@ func streamFailure(proto provider.Protocol, msg string) []byte { } // eventStream reports whether a reply is server-sent events. The header -// says so for most vendors; the ChatGPT backend sends none, so the body's -// first bytes decide, and the header is filled in for whoever reads it. +// says so for most vendors; where it doesn't, the body's first bytes +// decide, and the header is set right for whoever reads it. The ChatGPT +// backend sends no type at all, and a vendor's stream may come under +// another one (application/octet-stream, application/json): read as a +// whole reply, it reached the agent only at its end, its thinking all at +// once (uk.jent on Discord: MiniMax Code to Grok Build, "Thought for +// 0.0s"). A JSON or binary body never begins with a line of an event +// stream. func eventStream(res *http.Response) (io.Reader, bool) { - ct := res.Header.Get("Content-Type") - if strings.HasPrefix(ct, "text/event-stream") { + if strings.HasPrefix(res.Header.Get("Content-Type"), "text/event-stream") { return res.Body, true } - if ct != "" && !strings.HasPrefix(ct, "text/plain") { - return res.Body, false - } br := bufio.NewReaderSize(res.Body, 4<<10) head, _ := br.Peek(16) - head = bytes.TrimLeft(head, " \t\r\n") - for _, pfx := range []string{"event:", "data:", ":"} { - if bytes.HasPrefix(head, []byte(pfx)) { - res.Header.Set("Content-Type", "text/event-stream") - return br, true - } + if eventsStart(bytes.TrimLeft(head, " \t\r\n")) { + res.Header.Set("Content-Type", "text/event-stream") + return br, true } return br, false } diff --git a/internal/gateway/notapi.go b/internal/gateway/notapi.go index 6f0c73bc2..a8a9371aa 100644 --- a/internal/gateway/notapi.go +++ b/internal/gateway/notapi.go @@ -48,13 +48,24 @@ func notAnAPIReply(res *http.Response, name string) *http.Response { switch { case htmlStart.Match(head) && !strings.Contains(ct, "xml"): return asBadGateway(res, name, webPage(res, ct)) - case strings.Contains(ct, "json") && len(head) > 0 && head[0] != '{' && head[0] != '[': + case strings.Contains(ct, "json") && len(head) > 0 && head[0] != '{' && head[0] != '[' && !eventsStart(head): b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<10)) return asBadGateway(res, name, "answered "+res.Status+" with a reply that isn't JSON, not an API reply: "+clipRunes(string(bytes.TrimSpace(b)), 200)) } return res } +// eventsStart tells whether a body begins as server-sent events: a stream +// a vendor labels JSON is still its answer (eventStream reads it so). +func eventsStart(head []byte) bool { + for _, pfx := range []string{"event:", "data:", ":"} { + if bytes.HasPrefix(head, []byte(pfx)) { + return true + } + } + return false +} + // htmlStart is how a web page begins. var htmlStart = regexp.MustCompile(`(?i)^<(!doctype\s+html|html[\s>]|head[\s>]|body[\s>])`) diff --git a/internal/gateway/plugin_thinking_stream_test.go b/internal/gateway/plugin_thinking_stream_test.go new file mode 100644 index 000000000..00f234a56 --- /dev/null +++ b/internal/gateway/plugin_thinking_stream_test.go @@ -0,0 +1,109 @@ +package gateway + +import ( + "bufio" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +// heldThinker is an Anthropic vendor that says its first thought and then +// says nothing more until the agent has heard it (heard closed), or until +// giveUp passes. A gateway that holds the thinking until the reply ends +// lets the agent hear it only after giveUp, all at once. +type heldThinker struct { + ct []string // the reply's Content-Type: none when empty + heard chan struct{} + giveUp time.Duration + mu sync.Mutex + waited bool // the vendor gave up waiting: nothing reached the agent +} + +func (v *heldThinker) ServeHTTP(w http.ResponseWriter, r *http.Request) { + io.ReadAll(r.Body) + w.Header()["Content-Type"] = v.ct + f := w.(http.Flusher) + say := func(evs ...string) { + for _, ev := range evs { + io.WriteString(w, ev+"\n\n") + } + f.Flush() + } + say(glmThinksSlowly[0], glmThinksSlowly[1], glmThinksSlowly[2]) + select { + case <-v.heard: + case <-time.After(v.giveUp): + v.mu.Lock() + v.waited = true + v.mu.Unlock() + case <-r.Context().Done(): + return + } + say(glmThinksSlowly[3:]...) +} + +// uk.jent on Discord: MiniMax Code's plugin, served as Anthropic Messages +// to Grok Build, showed nothing for minutes and then the whole reply at +// once, each thinking block "Thought for 0.0s". A plugin's thinking reaches +// the agent while the vendor is still thinking, on every caller's shape. +func TestPluginThinkingStreamsAsItComes(t *testing.T) { + t.Setenv("FAKE_MINIMAX", "1") + tools := `,"tools":[{"name":"read_file","description":"Read a file","input_schema":{"type":"object","properties":{"path":{"type":"string"}}}}]` + for _, ct := range []string{"text/event-stream", "application/json", "text/plain; charset=utf-8", "", "application/octet-stream"} { + for _, ask := range []struct{ name, path, body, thought string }{ + {"messages", "/v1/messages", `{"model":"MODEL","max_tokens":32000,"stream":true,"thinking":{"type":"enabled","budget_tokens":10000},"messages":[{"role":"user","content":"hi"}]}`, `"thinking_delta"`}, + {"messages-tools", "/v1/messages", `{"model":"MODEL","max_tokens":32000,"stream":true,"thinking":{"type":"enabled","budget_tokens":10000},"messages":[{"role":"user","content":"hi"}]` + tools + `}`, `"thinking_delta"`}, + {"chat", "/v1/chat/completions", `{"model":"MODEL","stream":true,"reasoning_effort":"high","messages":[{"role":"user","content":"hi"}]}`, `first thought`}, + {"responses", "/v1/responses", `{"model":"MODEL","stream":true,"reasoning":{"effort":"high","summary":"auto"},"input":"hi"}`, `first thought`}, + } { + t.Run(ask.name+"/"+ct, func(t *testing.T) { + up := &heldThinker{heard: make(chan struct{}), giveUp: 10 * time.Second} + if ct != "" { + up.ct = []string{ct} + } + pid := besideFake(t, "minimax-code", up) + gw := httptest.NewServer(New().Handler()) + t.Cleanup(gw.Close) + req, _ := http.NewRequest("POST", gw.URL+ask.path, strings.NewReader(strings.Replace(ask.body, "MODEL", pid+"/MiniMax-M3.1-Flash", 1))) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("anthropic-version", "2023-06-01") + res, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.StatusCode != 200 { + b, _ := io.ReadAll(res.Body) + t.Fatalf("%d %s", res.StatusCode, b) + } + var all strings.Builder + rd := bufio.NewReader(res.Body) + heard := false + for { + ln, err := rd.ReadString('\n') + all.WriteString(ln) + if !heard && strings.Contains(ln, ask.thought) { + heard = true + close(up.heard) + } + if err != nil { + break + } + } + up.mu.Lock() + waited := up.waited + up.mu.Unlock() + if !heard { + t.Fatalf("the thought never reached the agent:\n%s", all.String()) + } + if waited { + t.Fatalf("the first thought reached the agent only once the vendor had finished:\n%s", all.String()) + } + }) + } + } +}