Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: every thinking block a Messages client gets says its signature (Grok Build on MiniMax)

yetone5d24bc6ccdfc
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index ba3bc7963..0d7b26303 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -254,6 +254,7 @@ recorded as a prediction failure (`noPrediction`).
- A tool Claude Code's ToolSearch loads, translated to a Responses API, used to join the top-level `tools` on the next request, which changed the prompt from its first bytes and missed the cache on every load (#2660). A deferred tool (`defer_loading`, `Tool.Deferred`) that a `tool_result`'s `tool_reference` names (`toolRefs`, `Part.Loads`) now goes, where `Request.LoadedInPlace` is set, in an `{"type":"additional_tools","role":"developer","tools":[…]}` item right after the run of tool outputs that loaded it, once, and not in `tools` (`buildResponses`): tools loaded by parallel results or one result naming several share one item, a tool named again isn't repeated, and the tool output's text is as before. OpenAI's tool search guide documents the item and that its tools load at the end of the context so the cache is kept. A compacted or edited history whose loading result is gone puts the tool back in `tools`, a new prefix, as is expected. `LoadedInPlace` is set (`loadsInPlace`, in `forwardTranslated`) for OpenAI's own API with a key (`api.openai.com`, `*.api.openai.com`) and for a provider set `additionalTools` (`magpie provider set <id> additional-tools=on`); nothing else, since xAI answers the item 422 (#350), the ChatGPT backend has been seen to take it only for Codex's Responses Lite, and no relay or plugin's vendor has been tried. An upstream that refuses a request holding the item with a 400 or 422 naming `additional_tools` is asked again with every tool in `tools`, logged ("turned away additional_tools … loaded tools go in tools from now on") and not sent the item again while magpie runs. Not handled: a tool a `tool_addition` block loads (an MCP server's late tool, the advisor) stays in `tools`. `TestLoadedToolsKeepThePrefix`, `TestLoadedToolsInOneItem`, `TestLoadedToolsWhereNotTaken`, `TestLoadsInPlaceScope`, `TestLoadedToolsThroughTheGateway`.
- A Responses upstream that wants a turn's reasoning back (`replaysReasoning` in [`responses.go`](../../internal/gateway/responses.go): a model with `deepseek` in its name, on any host but OpenAI's, xAI's, Copilot's and Azure's) gets every reasoning item with a `reasoning_text` and every tool call after one, relayed (`withReasoningText` in `passthrough`) or translated (`buildResponses`). DeepSeek's `/v1/responses` turns the whole request away ("The `reasoning_text` in the thinking mode must be passed back to the API") over a reasoning item without text, one with an empty text, and a `function_call` whose step (since the last user message or tool output) has no reasoning item. Codex sends all three in a routing group that falls to DeepSeek after ChatGPT: the backend's sealed items (`encrypted_content` only), magpie's summary-only items, and another member's calls with none (#1104, #1592). DeepSeek reads a step (a run of reasoning, assistant messages and calls) as one assistant message whose thinking is the item it starts with: in the current turn, a step with a call or after a tool output must lead with a reasoning item, so [message, reasoning, call] and [output, message] are refused while [reasoning, message, call] and [output, reasoning, message] are taken (checked against api.deepseek.com on 2026-10-12). Codex sends a step that said something before its call with no reasoning for another model's turn, which magpie used to send [message, reasoning " ", call] and DeepSeek refused intermittently, only while the turn lasted (#1822, through OpenCode Go). An item's own text is kept; one without gets its summary, else a space (`noReasoning`); each such step leads with its reasoning (`reasonFirst`): its own first reasoning item moved ahead, else one holding a space. A sealed item keeps its id and `encrypted_content`; a body already in that shape goes byte for byte.
- A Messages upstream that wants a turn's thinking back (`anthropicReplaysThinking` in [`anthropic.go`](../../internal/gateway/anthropic.go): a host or a model with `deepseek` in it, never `api.anthropic.com` or a Claude model) gets a thinking block on every assistant message with a `tool_use` or right after tool results alone (refused the same way, checked 2026-10-12, #1822), relayed (`withThinkingOnToolTurns` in `passthrough`) or translated (`build`, which also keeps unsigned thinking as its text there). DeepSeek's `/anthropic/v1/messages`, thinking (its default, or asked for), turns the whole request away with 400 "The `content[].thinking` in the thinking mode must be passed back to the API" when such a message has none, and answers any `redacted_thinking` with 422, a block it can't read. Claude Code sends both in a routing group that falls to DeepSeek after Claude (#1611). A message with no thinking gets one holding a space (`noReasoning`) first; Claude's `redacted_thinking` becomes that block, or is left out beside thinking of the message's own. Signed thinking, DeepSeek's own and every other message go as they came. Checked against the real endpoint on 2026-10-11: it takes Claude's signed thinking, unsigned thinking and a space, anywhere in the message. A thinking block magpie sends unsigned (the space, or a turn's reasoning kept as its text) says `"signature": ""`, as `aBlock` writes `thinking` even when empty: OpenRouter's `/api/v1/messages` holds a block's signature to a string and turns a DeepSeek request with none away, 400 "Invalid Anthropic Messages API request" (#2883, #3696), and DeepSeek's own endpoint takes the empty one (checked 2026-10-19). `TestOpenRouterDeepSeekThinkingHasASignature`.
+- Every thinking block a Messages client gets says a `signature`, a string, as Anthropic's own do (its stream starts each block with `"signature": ""`): Grok Build reads `ContentBlock::Thinking` as `{thinking, signature}`, both required, and turned a whole reply away, "missing field `signature`" (uk.jent on Discord, on the MiniMax Code plugin). The encoder starts a thinking block signed empty (`anthropicEncoder.thinking`), `renderAnthropic` and `whole_stream.go` write the field too, and a reply relayed from a Messages endpoint that wrote none, streamed or whole, gets an empty one (`sigFieldTidy` in [`thinking_signature.go`](../../internal/gateway/thinking_signature.go), in `passthrough`); a block already signed goes byte for byte, and `redacted_thinking` is untouched. magpie never makes a signature up: an empty one is none to every path that sends history on (`anthropicBody` leaves it out for Anthropic, keeps its text where reasoning is replayed), and a relay sends it back to the vendor that wrote the block. `TestMessagesThinkingIsSigned`, `TestSignedThinkingRelayedAsItCame`.
- A Grok model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`), whoever serves it: the Grok subscription or its plugin, xAI, OpenRouter or a relay. Codex reads its integer fields as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call (#1431). In a reply to a request whose model, as magpie names it or as it is sent upstream, has a last `/` segment beginning with `grok` (`grokModel`, `grokServed`), every number in a call's arguments written with a fraction of zeros and no exponent loses the fraction: `2500.0` becomes `2500`, `-3.00` becomes `-3`. Strings, keys, other fractions (`2.5`, `2.50`) and exponents (`1.0e3`) stay as written. No tool schema is consulted, since JSON has one number type. The rule runs over the arguments as a stream of text (`wholeNums`), holding back only a fraction of zeros until the next byte. This gives the same arguments whether they come whole or in deltas cut anywhere, so what a call's deltas add up to is what its done events say. Relayed replies are rewritten in `passthrough` by `intTidy`: Responses' function_call items, argument deltas and done events and the completed response; Chat's `tool_calls` deltas and messages; Messages' `tool_use` input and `input_json_delta`, streamed or whole. Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`) when `Request.Grok` is set. Any other model's reply is relayed byte for byte ([`grok_integral.go`](../../internal/gateway/grok_integral.go)).
- A tool call a model writes into its reply's text, when the request offered tools, is made the call it is ([`textcalls.go`](../../internal/gateway/textcalls.go), #823): Hermes' `<tool_call>{…}</tool_call>`, DeepSeek's DSML (`<|DSML|invoke name=…>` with its parameters; its mark found as the parse regexes read it, by `dsmlMark`, not from a list of spellings: any run of pipes, ASCII or full-width or mixed, spaces after `<` and around `/`, `<||DSML||` too, #2623), DeepSeek's half-Hermes `<parameter>` form (#917) and GLM's `<arg_key>`/`<arg_value>` (#906), read by `parseTextCalls`. Each block must name an offered tool and have arguments that can be read; else the text goes on as it came. The text before the first block is kept, what is left of the tags goes, and the reply ends as one that called tools (`finish_reason` `tool_calls`, `stop_reason` `tool_use`). A DSML close with no block before it (`</||DSML|| calls>`) is held as a block is, and dropped when it is tags and nothing else. A reply whose model made a call itself has no call read out of its text, but tags and nothing else left in it after the call go, with the spaces before them (喜欢一个人 on Discord: a relay made the calls of DeepSeek's invokes and left the wrapper's close as text). Every route reads it the same way: a relayed Chat stream (`textCallTidy`), a relayed Chat reply that came whole, JSON or under `text/plain` or no type (`chatWhole` with `wholeTextCalls`, #1845: a `stream:false` request kept the markup and `finish_reason` `stop`), which also covers a vendor that answered a streamed request whole (`wholeAsStream`), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses or Messages upstream's text is not read for calls. Covered by `TestTextWritten*`, `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`.
- Structured output is carried across every translation (`Format`, [`format.go`](../../internal/gateway/format.go)). It is read from Responses' `text.format`, Chat's `response_format`, Anthropic's `output_config.format` and Gemini's `responseMimeType` with `responseJsonSchema`/`responseSchema`: `json_schema` with its name, description, schema and strict, or `json_object`. Each upstream is asked in its own field: `text.format` on Responses, `response_format` on Chat, `output_config.format` on Messages, and `generationConfig.responseMimeType`/`responseJsonSchema` on Gemini and Code Assist. An API with no name for it gets `response`. Messages and the Claude subscription's `--json-schema` take a schema only, so `json_object` is told in the system prompt there (`inSystem`). A 400 or 422 that names the field (`refusesFormat`: DeepSeek's "This response_format type is unavailable now", a schema Anthropic can't hold) marks the provider and model (`formatRefused`), and the request is asked again with the format told in the system prompt, as are later requests to that provider and model. A relayed request keeps its format as sent. A Gemini client's format is also still told in its system prompt, as before. A model may still wrap its JSON answer in a Markdown code fence; a client that asked for structured output, in a field or told in the system prompt (`wantsJSON`), gets the JSON inside a single unlabelled or json-labelled fence when that content is a complete valid JSON value, streamed (`fenceEncoder`) or whole (`unfencedResult`), in [`format_fence.go`](../../internal/gateway/format_fence.go). Invalid or truncated JSON, other fence languages, text outside the fence, and answers to plain-text clients reach the client as they came. This normalization applies to translated replies; native protocol passthrough stays byte-preserving.
diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go
index a445f15ff..12e8e358b 100644
--- a/internal/gateway/anthropic.go
+++ b/internal/gateway/anthropic.go
@@ -1555,7 +1555,11 @@ func (e *anthropicEncoder) thinking() {
e.close()
e.fresh = false
}
- e.openBlock(Thinking, map[string]any{"thinking": ""})
+ // signed empty where it starts, as Anthropic's own stream starts one:
+ // its signature_delta, if any, comes before the block's stop, and a
+ // client that reads the field as required (Grok Build) turns a block
+ // without it away (thinking_signature.go)
+ e.openBlock(Thinking, map[string]any{"thinking": "", "signature": ""})
}
func (e *anthropicEncoder) delta(d map[string]any) {
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index e6d2565ff..3831890d8 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -5188,13 +5188,23 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if proto == provider.Responses && sse {
ids = &idTidy{}
}
- // out is what a filter let through, through ids and phases
+ // a thinking block with no signature, which a Messages client may read
+ // as required (Grok Build), gets an empty one, as Anthropic's own
+ // blocks start (thinking_signature.go)
+ var thinkSigs *sigFieldTidy
+ if proto == provider.Anthropic {
+ thinkSigs = &sigFieldTidy{sse: sse}
+ }
+ // out is what a filter let through, through ids, phases and thinkSigs
out := func(b []byte) []byte {
if ids != nil {
b = ids.write(b)
}
if phases != nil {
- return phases.write(b)
+ b = phases.write(b)
+ }
+ if thinkSigs != nil {
+ b = thinkSigs.write(b)
}
return b
}
@@ -5253,6 +5263,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if phases != nil {
out = phases.write(out)
}
+ if thinkSigs != nil {
+ out = thinkSigs.write(out)
+ }
if _, werr := write(out); werr != nil {
return res.StatusCode, "", true
}
@@ -5322,6 +5335,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if phases != nil {
write(phases.flush())
}
+ if thinkSigs != nil {
+ write(thinkSigs.flush())
+ }
if sse {
sniff.drain()
} else {
diff --git a/internal/gateway/thinking_signature.go b/internal/gateway/thinking_signature.go
new file mode 100644
index 000000000..96cb4bbaf
--- /dev/null
+++ b/internal/gateway/thinking_signature.go
@@ -0,0 +1,170 @@
+package gateway
+
+import (
+ "bytes"
+ "encoding/json"
+)
+
+// A Messages thinking block always says its signature. Anthropic's own API
+// writes one on every thinking block: `"signature": ""` where a stream's
+// block starts (its signature_delta comes before the block's stop), and
+// the whole signature in a reply that came whole. Clients read the field as
+// required: Grok Build's ContentBlock::Thinking has two fields, thinking
+// and signature, and serde turns the whole reply away without the second,
+// "Couldn't read the response: serialization error: missing field
+// `signature`" (uk.jent on Discord, minimax-code-global/MiniMax-M3.1-Flash).
+//
+// A thinking block magpie writes for a Messages client therefore carries
+// one: the encoder's (anthropicEncoder.thinking, renderAnthropic), the
+// whole-to-stream path's (whole_stream.go), and, through sigFieldTidy, a
+// block another vendor's Messages endpoint wrote without one, relayed as it
+// came. The signature magpie adds is always empty, never made up: an empty
+// signature is no signature to every path that sends history on.
+// anthropicBody leaves an unsigned thinking block out for Anthropic and
+// keeps its text only where the upstream wants reasoning back (DeepSeek,
+// which takes the empty field, as aBlock already writes it); a relay sends
+// it back to the vendor that wrote it, as the client keeps it.
+
+var thinkingType = []byte(`"thinking"`)
+
+// sigFieldTidy gives each thinking block of a Messages reply relayed as it
+// came an empty signature where it has none: a stream's content_block_start
+// lines, or a whole reply's content. A line that names no thinking, or that
+// has a signature already (Anthropic's), passes as it came; a reply that
+// isn't a stream is held whole and gone through at the end.
+type sigFieldTidy struct {
+ sse bool
+ buf []byte
+}
+
+func (t *sigFieldTidy) write(b []byte) []byte {
+ t.buf = append(t.buf, b...)
+ if !t.sse {
+ return nil
+ }
+ i := bytes.LastIndexByte(t.buf, '\n')
+ if i < 0 {
+ return nil
+ }
+ out := t.lines(t.buf[:i+1])
+ t.buf = append(t.buf[:0], t.buf[i+1:]...)
+ return out
+}
+
+func (t *sigFieldTidy) flush() []byte {
+ b := t.buf
+ t.buf = nil
+ if !t.sse {
+ if out, ok := signedContent(b); ok {
+ return out
+ }
+ return b
+ }
+ return t.lines(b)
+}
+
+func (t *sigFieldTidy) lines(b []byte) []byte {
+ if !bytes.Contains(b, thinkingType) {
+ return append([]byte(nil), b...)
+ }
+ var out []byte
+ for len(b) > 0 {
+ line := b
+ if i := bytes.IndexByte(b, '\n'); i >= 0 {
+ line, b = b[:i+1], b[i+1:]
+ } else {
+ b = nil
+ }
+ body := bytes.TrimRight(line, "\r\n")
+ data, ok := bytes.CutPrefix(body, []byte("data:"))
+ if !ok || !bytes.Contains(data, thinkingType) || !bytes.Contains(data, []byte("content_block_start")) {
+ out = append(out, line...)
+ continue
+ }
+ nb, ok := signedStart(bytes.TrimSpace(data))
+ if !ok {
+ out = append(out, line...)
+ continue
+ }
+ out = append(append(append(out, "data: "...), nb...), line[len(body):]...)
+ }
+ return out
+}
+
+// signedStart is a content_block_start event opening a thinking block with
+// no signature, given an empty one, and whether it was such an event.
+func signedStart(data []byte) ([]byte, bool) {
+ var ev map[string]json.RawMessage
+ if json.Unmarshal(data, &ev) != nil {
+ return nil, false
+ }
+ var typ string
+ if json.Unmarshal(ev["type"], &typ) != nil || typ != "content_block_start" {
+ return nil, false
+ }
+ block, ok := unsignedThinking(ev["content_block"])
+ if !ok {
+ return nil, false
+ }
+ ev["content_block"] = block
+ nb, err := marshalPlain(ev)
+ return nb, err == nil
+}
+
+// signedContent is a whole Messages reply whose thinking blocks without a
+// signature are given an empty one, and whether it had such a block.
+func signedContent(b []byte) ([]byte, bool) {
+ if !bytes.Contains(b, thinkingType) {
+ return nil, false
+ }
+ var reply map[string]json.RawMessage
+ if json.Unmarshal(b, &reply) != nil {
+ return nil, false
+ }
+ var content []json.RawMessage
+ if json.Unmarshal(reply["content"], &content) != nil {
+ return nil, false
+ }
+ changed := false
+ for i, c := range content {
+ if nb, ok := unsignedThinking(c); ok {
+ content[i], changed = nb, true
+ }
+ }
+ if !changed {
+ return nil, false
+ }
+ cb, err := marshalPlain(content)
+ if err != nil {
+ return nil, false
+ }
+ reply["content"] = cb
+ nb, err := marshalPlain(reply)
+ return nb, err == nil
+}
+
+// unsignedThinking is a thinking block that has no signature, given an
+// empty one, and whether it was one. A signature that isn't a string (a
+// null) is none too.
+func unsignedThinking(raw json.RawMessage) (json.RawMessage, bool) {
+ if !bytes.Contains(raw, thinkingType) {
+ return nil, false
+ }
+ var block map[string]json.RawMessage
+ if json.Unmarshal(raw, &block) != nil {
+ return nil, false
+ }
+ var typ string
+ if json.Unmarshal(block["type"], &typ) != nil || typ != "thinking" {
+ return nil, false
+ }
+ if s := bytes.TrimSpace(block["signature"]); len(s) > 0 && s[0] == '"' {
+ return nil, false
+ }
+ block["signature"] = json.RawMessage(`""`)
+ if _, ok := block["thinking"]; !ok {
+ block["thinking"] = json.RawMessage(`""`)
+ }
+ nb, err := marshalPlain(block)
+ return nb, err == nil
+}
diff --git a/internal/gateway/thinking_signature_test.go b/internal/gateway/thinking_signature_test.go
new file mode 100644
index 000000000..b1603ac68
--- /dev/null
+++ b/internal/gateway/thinking_signature_test.go
@@ -0,0 +1,177 @@
+package gateway
+
+import (
+ "encoding/json"
+ "strings"
+ "testing"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// Grok Build reads a Messages thinking block as ContentBlock::Thinking
+// {thinking, signature}, both required (its grok 1.0.67 binary), and
+// turned a reply from minimax-code-global/MiniMax-M3.1-Flash away with
+// "serialization error: missing field `signature`" (uk.jent on Discord).
+//
+// No bytes of MiniMax's reply were captured: there is no MiniMax Code
+// account here. The unsigned shapes below are what MiniMax's Anthropic API
+// docs read (`block.type == "thinking"`, `block.thinking`, thinking_delta;
+// no signature or signature_delta named anywhere), and what a translated
+// reply (Chat's reasoning_content) gave before.
+
+// minimaxUnsignedStream is a Messages stream whose thinking block starts
+// with no signature and gets none before its stop.
+var minimaxUnsignedStream = sse(
+ `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_mm1","type":"message","role":"assistant","model":"MiniMax-M3.1-Flash","content":[],"stop_reason":null,"usage":{"input_tokens":12,"output_tokens":0}}}`,
+ `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}`,
+ `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"The user says hi. <greet back>"}}`,
+ `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
+ `event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}`,
+ `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"Hello!"}}`,
+ `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":1}`,
+ `event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":9}}`,
+ `event: message_stop`+"\n"+`data: {"type":"message_stop"}`,
+)
+
+const minimaxUnsignedWhole = `{"id":"msg_mm2","type":"message","role":"assistant","model":"MiniMax-M3.1-Flash",` +
+ `"content":[{"type":"thinking","thinking":"The user says hi. <greet back>"},{"type":"text","text":"Hello!"}],` +
+ `"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":9}}`
+
+// thinkingBlocks are the thinking blocks a Messages reply gives its
+// client: each stream's content_block_start, or a whole reply's content.
+func thinkingBlocks(t *testing.T, body string) []map[string]any {
+ t.Helper()
+ var blocks []map[string]any
+ if strings.HasPrefix(strings.TrimSpace(body), "{") {
+ var reply struct {
+ Content []map[string]any `json:"content"`
+ }
+ if err := json.Unmarshal([]byte(body), &reply); err != nil {
+ t.Fatalf("reply isn't JSON: %v\n%s", err, body)
+ }
+ for _, b := range reply.Content {
+ if b["type"] == "thinking" {
+ blocks = append(blocks, b)
+ }
+ }
+ return blocks
+ }
+ for _, ev := range events(body) {
+ if ev["type"] != "content_block_start" {
+ continue
+ }
+ if b, _ := ev["content_block"].(map[string]any); b["type"] == "thinking" {
+ blocks = append(blocks, b)
+ }
+ }
+ return blocks
+}
+
+// TestMessagesThinkingIsSigned: every thinking block magpie gives a
+// Messages client says a signature, a string, whether the reply was
+// relayed from a vendor's Messages endpoint that wrote none (MiniMax's) or
+// translated from Chat's reasoning_content, streamed or whole. The
+// thinking itself is unchanged, and what magpie adds is empty, never a
+// made-up signature.
+func TestMessagesThinkingIsSigned(t *testing.T) {
+ for _, tt := range []struct {
+ name string
+ proto provider.Protocol
+ stream bool
+ f *fake
+ }{
+ {"relayed stream", provider.Anthropic, true, &fake{reply: minimaxUnsignedStream}},
+ {"relayed whole", provider.Anthropic, false, &fake{reply: minimaxUnsignedWhole, ctype: "application/json"}},
+ {"translated stream", provider.Chat, true, &fake{reply: sse(glmChatThinksSlowly...)}},
+ // the upstream is asked streamed; the client gets one body
+ {"translated whole", provider.Chat, false, &fake{reply: sse(glmChatThinksSlowly...)}},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ setup(t, tt.proto, tt.f)
+ stream := "false"
+ if tt.stream {
+ stream = "true"
+ }
+ code, body := post(t, "/v1/messages", `{"model":"fake/m1","max_tokens":64,"stream":`+stream+`,"messages":[{"role":"user","content":"hi"}]}`)
+ if code != 200 {
+ t.Fatalf("status %d: %s", code, body)
+ }
+ blocks := thinkingBlocks(t, body)
+ if len(blocks) != 1 {
+ t.Fatalf("thinking blocks = %d, want 1:\n%s", len(blocks), body)
+ }
+ sig, ok := blocks[0]["signature"].(string)
+ if !ok {
+ t.Fatalf("thinking block has no signature string, as Grok Build turns away: %v\n%s", blocks[0], body)
+ }
+ if sig != "" {
+ t.Errorf("signature = %q, want the empty one magpie adds", sig)
+ }
+ if _, ok := blocks[0]["thinking"].(string); !ok {
+ t.Errorf("thinking block has no thinking string: %v", blocks[0])
+ }
+ if tt.proto == provider.Anthropic && !strings.Contains(body, "<greet back>") && !strings.Contains(body, `\u003cgreet back\u003e`) {
+ t.Errorf("the thinking's text was lost:\n%s", body)
+ }
+ })
+ }
+}
+
+// TestSignedThinkingRelayedAsItCame: a reply whose thinking is signed
+// already (Anthropic's own) goes to the client byte for byte, its
+// signature as Anthropic wrote it.
+func TestSignedThinkingRelayedAsItCame(t *testing.T) {
+ signed := strings.NewReplacer(
+ `"content_block":{"type":"thinking","thinking":""}`, `"content_block":{"type":"thinking","thinking":"","signature":""}`,
+ `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
+ `event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"EqQBCkYIBxgCKkDreal"}}`+"\n\n"+
+ `event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
+ ).Replace(minimaxUnsignedStream)
+ whole := strings.Replace(minimaxUnsignedWhole, `"thinking":"The user says hi. <greet back>"}`, `"thinking":"The user says hi. <greet back>","signature":"EqQBCkYIBxgCKkDreal"}`, 1)
+ for _, tt := range []struct {
+ name, reply, ctype, stream string
+ }{
+ {"stream", signed, "", "true"},
+ {"whole", whole, "application/json", "false"},
+ } {
+ t.Run(tt.name, func(t *testing.T) {
+ setup(t, provider.Anthropic, &fake{reply: tt.reply, ctype: tt.ctype})
+ code, body := post(t, "/v1/messages", `{"model":"fake/m1","max_tokens":64,"stream":`+tt.stream+`,"messages":[{"role":"user","content":"hi"}]}`)
+ if code != 200 {
+ t.Fatalf("status %d: %s", code, body)
+ }
+ if body != tt.reply {
+ t.Errorf("signed reply changed on its way:\n got %s\nwant %s", body, tt.reply)
+ }
+ })
+ }
+}
+
+// TestSigFieldTidyCutAnywhere: a stream cut at any byte gives the same
+// lines as one read whole, and a thinking block's text that mentions
+// "thinking" in a delta is left alone.
+func TestSigFieldTidyCutAnywhere(t *testing.T) {
+ whole := (&sigFieldTidy{sse: true}).write([]byte(minimaxUnsignedStream))
+ for cut := 1; cut < len(minimaxUnsignedStream); cut += 7 {
+ tidy := &sigFieldTidy{sse: true}
+ got := append(tidy.write([]byte(minimaxUnsignedStream[:cut])), tidy.write([]byte(minimaxUnsignedStream[cut:]))...)
+ got = append(got, tidy.flush()...)
+ if string(got) != string(whole) {
+ t.Fatalf("cut at %d:\n got %s\nwant %s", cut, got, whole)
+ }
+ }
+ if !strings.Contains(string(whole), `"content_block":{"signature":"","thinking":"","type":"thinking"}`) {
+ t.Errorf("thinking start not signed:\n%s", whole)
+ }
+ if !strings.Contains(string(whole), `"thinking_delta","thinking":"The user says hi. <greet back>"}`) {
+ t.Errorf("a delta changed:\n%s", whole)
+ }
+ // a null signature is none too
+ if b, ok := unsignedThinking(json.RawMessage(`{"type":"thinking","thinking":"x","signature":null}`)); !ok || string(b) != `{"signature":"","thinking":"x","type":"thinking"}` {
+ t.Errorf("null signature: %s, %v", b, ok)
+ }
+ // redacted_thinking keeps its data, untouched
+ if _, ok := unsignedThinking(json.RawMessage(`{"type":"redacted_thinking","data":"abc"}`)); ok {
+ t.Error("redacted_thinking was changed")
+ }
+}