gateway: a thinking block Claude says is another conversation's is left out and asked again (ferock)

ferock (Discord, 10-30): Command Code requests sometimes fail with 400
"messages.3.content.20: Invalid signature in thinking block. The block
is bound to a different conversation ...". The client's history carries
thinking blocks signed for another conversation or account (a switch,
a fork, another provider), and the plugin passes the Messages body
through as written, so this is fixed in magpie, not the plugin.

forward(), which every Anthropic-protocol route goes through (relayed,
translated, plugin fetch, count_tokens), now reads that refusal
(thinking_bound.go). It remembers the block it names and every thinking
block after it, for that provider and account only, then asks again
without them. An assistant message left empty is dropped. The next turn
leaves them out at once. Other 400s, and other providers, keep every
block byte for byte. The drop_block beta isn't sent: Claude Code sends
it only behind a flag, and magpie doesn't mimic Claude Code.

Run (mote, at this head rebased on cae785a37):
- go test -run 'TestBoundRefusalRead|TestBoundThinkingLeftOut|
  TestOtherRefusalKeepsThinking|TestWithoutThinkingBlocks|
  TestPluginBoundThinkingLeftOut|TestPluginThinkingOff|TokenField|Beta'
  ./internal/gateway: ok
- go test -count=1 -timeout 45m ./internal/gateway (before the rebase):
  every test ok except five Antigravity/Grok tests. They are red the
  same way on origin/main e8d42c02d, and #4362 covers them.
- gofmt -l clean; go vet ./internal/gateway for darwin, linux, windows: ok

Broken by hand:
- the retry turned off: TestBoundThinkingLeftOut and
  TestPluginBoundThinkingLeftOut go red with ferock's exact 400
- only the named block dropped, not the ones after it: red, because the
  fake refuses message 5's block next

Not tried: a real Command Code account (the fake replays ferock's
literal error). The full ./... suite hasn't run yet. Claude
subscription accounts go through the bridge and are not covered here.
This commit is contained in:
yetone
2026-10-30 14:20:39 +08:00
parent 8d4c07ffed
commit 764a032f6f
4 changed files with 471 additions and 4 deletions
File diff suppressed because one or more lines are too long
+13 -4
View File
@@ -423,8 +423,11 @@ type Server struct {
calls uint64 // the last Call.ID given
// unfit remembers the endpoints each provider's models were turned away
// from, so every later turn goes straight to one that takes them.
unfit map[string]bool
subscription *subscriptionBridge
unfit map[string]bool
// refusedThinking is the thinking blocks each provider and account
// refused as signed for another conversation (thinking_bound.go)
refusedThinking map[string]bool
subscription *subscriptionBridge
// imageStore is the image MCP server's jobs and images (image_mcp.go)
imageStore imageMCPStore
debug bool
@@ -4379,7 +4382,8 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
}
// and what of Claude Code's newest asks it turns away (thinking.display
// "updates", a turn's output_config in messages: anthropic_shapes.go),
// each learned once
// each learned once, and the thinking blocks Claude says were signed
// for another conversation or account (thinking_bound.go)
for range 3 {
if err != nil || to != provider.Anthropic || res.StatusCode != http.StatusBadRequest && res.StatusCode != http.StatusUnprocessableEntity {
return res, err
@@ -4387,8 +4391,10 @@ func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.P
b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20))
res.Body.Close()
res.Body = io.NopCloser(bytes.NewReader(b))
sent := s.withoutRefusedShapes(p, body)
betas := len(s.refuseBetas(p, b)) > 0
if shapes := s.refuseShapes(p, b, body); !betas && !shapes {
shapes := s.refuseShapes(p, b, body)
if bound := s.refuseBoundThinking(p, b, sent); !betas && !shapes && !bound {
return res, nil
}
res, err = s.forwardOnce(ctx, p, to, path, body, in)
@@ -4437,6 +4443,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
body = adaptiveThinking(body)
}
body = s.withoutRefusedShapes(p, body)
// the thinking blocks it refused as another conversation's
// (thinking_bound.go), every route to it alike
body = s.withoutRefusedThinking(p, body)
if isKimi(p, to) || p.IsOpenCode() && strings.Contains(strings.ToLower(modelOf(body)), "deepseek") {
// Claude Code's deferred-tool blocks, for which Kimi's
// Anthropic endpoint turns the whole request away with a 400
+213
View File
@@ -0,0 +1,213 @@
package gateway
import (
"bytes"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"regexp"
"strconv"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// Claude's thinking block is signed for the conversation it was made in
// and the account that made it. A block an upstream doesn't take as its
// own is refused with the whole request (ferock on Discord, Command Code's
// plugin): 400 "messages.3.content.20: Invalid signature in thinking
// block. The block is bound to a different conversation. Remove the
// block, or set thinking.block_binding.prefix_mismatch_behavior to
// "drop_block"" (that setting needs a beta magpie doesn't send for an
// agent). Such a block comes from a conversation that moved between
// accounts or providers (a routing group's fallback, an account switch,
// a relay that serves Claude from more than one account of its own) or
// whose earlier turns changed since.
//
// forward does what the refusal asks: it leaves out the block it names
// and every thinking block after it (their signatures cover the turns
// before them, the left-out block among them), asks once more, and
// remembers those signatures for that provider and account
// (thinkingRefused), so the conversation's later turns go without them
// the first time and stay the conversation the model has gone on in.
// Other blocks, and every request to another provider or account, go as
// the agent wrote them. Only Claude's refusal text starts it, so no other
// vendor's request changes.
// boundRefusal is Claude's refusal of a thinking block it didn't sign for
// this conversation or account: the signature's wording, the newer
// binding's, and a redacted_thinking block's.
var boundRefusal = regexp.MustCompile("(?i)invalid `?signature`? in `?thinking`? block|bound to a different conversation|not created in this conversation|invalid data in `?redacted_thinking`? block")
// boundAt is where the refusal says the block is: messages.<m>.content.<b>.
var boundAt = regexp.MustCompile(`messages\.(\d+)\.content\.(\d+)`)
// thinkingRefusedMost bounds the signatures remembered; past it the
// memory starts again, and a conversation still going is mended by one
// more refusal.
const thinkingRefusedMost = 1 << 14
// thinkingOwner is who a refusal is remembered for: the provider, and the
// account signed in to it.
func thinkingOwner(p provider.Provider) string {
if p.Account != nil {
return p.ID + "\x00" + p.Account.User
}
return p.ID
}
// thinkingKey names a thinking or redacted_thinking block by its
// signature (a redacted block's data), or its text where it has neither.
func thinkingKey(b gjson.Result) string {
k := b.Get("signature").String()
if k == "" {
k = b.Get("data").String()
}
if k == "" {
k = b.Get("thinking").String()
}
h := sha256.Sum256([]byte(b.Get("type").String() + "\x00" + k))
return hex.EncodeToString(h[:16])
}
func isThinkingBlock(b gjson.Result) bool {
t := b.Get("type").String()
return t == "thinking" || t == "redacted_thinking"
}
// thinkingRefused tells whether p refused the block with key.
func (s *Server) thinkingRefused(owner, key string) bool {
s.mu.Lock()
defer s.mu.Unlock()
return s.refusedThinking[owner+"\x00"+key]
}
func (s *Server) refuseThinking(owner string, keys []string) {
s.mu.Lock()
defer s.mu.Unlock()
if s.refusedThinking == nil || len(s.refusedThinking)+len(keys) > thinkingRefusedMost {
s.refusedThinking = make(map[string]bool)
}
for _, k := range keys {
s.refusedThinking[owner+"\x00"+k] = true
}
}
// withoutRefusedThinking is a Messages body without the thinking blocks p
// refused before; an assistant message left with nothing goes too. A body
// with none of them goes byte for byte.
func (s *Server) withoutRefusedThinking(p provider.Provider, body []byte) []byte {
if !bytes.Contains(body, []byte(`thinking"`)) {
return body
}
owner := thinkingOwner(p)
s.mu.Lock()
none := len(s.refusedThinking) == 0
s.mu.Unlock()
if none {
return body
}
return withoutThinkingBlocks(body, func(_, _ int, b gjson.Result) bool {
return s.thinkingRefused(owner, thinkingKey(b))
})
}
// withoutThinkingBlocks leaves out of a Messages body each thinking or
// redacted_thinking block drop says to, at message m, block i, and an
// assistant message that had only those.
func withoutThinkingBlocks(body []byte, drop func(m, i int, b gjson.Result) bool) []byte {
var q map[string]json.RawMessage
var msgs []json.RawMessage
if decodeJSON(body, &q) != nil || decodeJSON(q["messages"], &msgs) != nil {
return body
}
out := make([]json.RawMessage, 0, len(msgs))
changed := false
for mi, raw := range msgs {
content := gjson.GetBytes(raw, "content")
if !content.IsArray() {
out = append(out, raw)
continue
}
var kept []json.RawMessage
gone := false
for bi, b := range content.Array() {
if isThinkingBlock(b) && drop(mi, bi, b) {
gone = true
continue
}
kept = append(kept, json.RawMessage(b.Raw))
}
if !gone {
out = append(out, raw)
continue
}
changed = true
if len(kept) == 0 {
continue
}
var m map[string]json.RawMessage
if decodeJSON(raw, &m) != nil {
out = append(out, raw)
continue
}
m["content"], _ = json.Marshal(kept)
nb, err := json.Marshal(m)
if err != nil {
return body
}
out = append(out, nb)
}
if !changed {
return body
}
q["messages"], _ = json.Marshal(out)
b, err := json.Marshal(q)
if err != nil {
return body
}
return b
}
// refuseBoundThinking reads a 400 from an Anthropic upstream: when it is
// Claude refusing a thinking block's signature, the block it names and
// every thinking block after it in body (as forwardOnce sends it, without
// those refused before) are remembered as refused by p. fresh is whether
// any was new, so asking again can go otherwise.
func (s *Server) refuseBoundThinking(p provider.Provider, errBody, body []byte) (fresh bool) {
if !boundRefusal.Match(errBody) {
return false
}
sent := s.withoutRefusedThinking(p, body)
msgs := gjson.GetBytes(sent, "messages").Array()
// from the block named, or from the start when it names none, or one
// that isn't a thinking block in what was sent
fromM, fromB := 0, 0
if at := boundAt.FindSubmatch(errBody); at != nil {
m, _ := strconv.Atoi(string(at[1]))
b, _ := strconv.Atoi(string(at[2]))
if m < len(msgs) {
if blocks := msgs[m].Get("content").Array(); b < len(blocks) && isThinkingBlock(blocks[b]) {
fromM, fromB = m, b
}
}
}
owner := thinkingOwner(p)
var keys []string
for mi := fromM; mi < len(msgs); mi++ {
for bi, b := range msgs[mi].Get("content").Array() {
if mi == fromM && bi < fromB || !isThinkingBlock(b) {
continue
}
if k := thinkingKey(b); !s.thinkingRefused(owner, k) {
keys = append(keys, k)
}
}
}
if len(keys) == 0 {
return false
}
s.refuseThinking(owner, keys)
return true
}
+244
View File
@@ -0,0 +1,244 @@
package gateway
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync"
"testing"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/provider"
)
// ferock's refusal, as Command Code's plugin passed it on (Discord,
// 2026-10-30), up to where the report was cut.
const boundRefusalText = `messages.3.content.20: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to "drop_block". That setting requires the thinking-binding-controls-2026-08-01 value in the anthropic-beta header. The system`
// boundClaude answers as Claude does a conversation it signed only part
// of: the first thinking block whose signature is in foreign is refused,
// named where it is, in Anthropic's error body (magpie's reply puts the
// provider's name before it: "Command Code: {...}"); any other request is
// answered. said is what Claude refuses with (%d %d: message, block).
type boundClaude struct {
mu sync.Mutex
bodies []string
foreign []string
said string
// stream: the reply is Anthropic's stream, as a plugin's account wants
stream bool
}
func (c *boundClaude) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
c.mu.Lock()
c.bodies = append(c.bodies, string(b))
c.mu.Unlock()
w.Header().Set("Content-Type", "application/json")
for mi, m := range gjson.GetBytes(b, "messages").Array() {
for bi, blk := range m.Get("content").Array() {
if blk.Get("type").String() == "thinking" && slices.Contains(c.foreign, blk.Get("signature").String()) {
w.WriteHeader(400)
msg := fmt.Sprintf(c.said, mi, bi)
e, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{"type": "invalid_request_error", "message": msg}})
w.Write(e)
return
}
}
}
if c.stream {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5","content":[],"stop_reason":null,"usage":{"input_tokens":1,"output_tokens":0}}}`,
`event: content_block_start`+"\n"+`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`event: content_block_delta`+"\n"+`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`,
`event: content_block_stop`+"\n"+`data: {"type":"content_block_stop","index":0}`,
`event: message_delta`+"\n"+`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
`event: message_stop`+"\n"+`data: {"type":"message_stop"}`))
return
}
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
}
func (c *boundClaude) sent() []string {
c.mu.Lock()
defer c.mu.Unlock()
return slices.Clone(c.bodies)
}
// boundConversation is a Claude Code conversation whose message 3 has
// the refused block at 20, as ferock's had: thinking signed ok-<i> before
// it, other-20 there, and a later turn's thinking after it.
func boundConversation(model string) string {
var blocks []string
for i := 0; i < 20; i += 2 {
blocks = append(blocks,
fmt.Sprintf(`{"type":"thinking","thinking":"step %d","signature":"ok-%d"}`, i, i),
fmt.Sprintf(`{"type":"text","text":"note %d"}`, i+1))
}
blocks = append(blocks,
`{"type":"thinking","thinking":"from elsewhere","signature":"other-20"}`,
`{"type":"tool_use","id":"t1","name":"Read","input":{"file_path":"a.go"}}`)
return `{"model":"` + model + `","max_tokens":4096,"thinking":{"type":"adaptive"},"messages":[` +
`{"role":"user","content":[{"type":"text","text":"hi"}]},` +
`{"role":"assistant","content":[{"type":"thinking","thinking":"first","signature":"ok-a"},{"type":"text","text":"hello"}]},` +
`{"role":"user","content":[{"type":"text","text":"read a.go"}]},` +
`{"role":"assistant","content":[` + strings.Join(blocks, ",") + `]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"t1","content":"package a"}]},` +
`{"role":"assistant","content":[{"type":"thinking","thinking":"later","signature":"later-5"},{"type":"tool_use","id":"t2","name":"Read","input":{"file_path":"b.go"}}]},` +
`{"role":"user","content":[{"type":"tool_result","tool_use_id":"t2","content":"package b"}]}]}`
}
// signatures lists a body's thinking signatures, in order.
func signatures(body string) []string {
var out []string
for _, m := range gjson.Get(body, "messages").Array() {
for _, b := range m.Get("content").Array() {
if b.Get("type").String() == "thinking" {
out = append(out, b.Get("signature").String())
}
}
}
return out
}
func TestBoundRefusalRead(t *testing.T) {
if !boundRefusal.MatchString(boundRefusalText) {
t.Error("ferock's refusal isn't read as a bound thinking block")
}
for _, s := range []string{
"messages.1.content.0: Invalid `signature` in `thinking` block",
"messages.1.content.0: thinking block was not created in this conversation",
"messages.1.content.0: Invalid data in redacted_thinking block",
} {
if !boundRefusal.MatchString(s) {
t.Errorf("%q not read as a bound thinking block", s)
}
}
for _, s := range []string{
// DeepSeek's (#1611) and a plain bad request: nothing to leave out
"The `content[].thinking` in the thinking mode must be passed back to the API",
"messages.1.content.0: Expected `thinking` or `redacted_thinking`, but found `tool_use`",
"prompt is too long",
} {
if boundRefusal.MatchString(s) {
t.Errorf("%q read as a bound thinking block", s)
}
}
if m := boundAt.FindStringSubmatch(boundRefusalText); m == nil || m[1] != "3" || m[2] != "20" {
t.Errorf("boundAt = %v, want message 3 block 20", m)
}
}
// ferock on Discord: Claude refused message 3's block 20 as bound to
// another conversation. magpie asks again without it and without the
// thinking after it, keeps the blocks before it, and sends the next turn
// so the first time.
func TestBoundThinkingLeftOut(t *testing.T) {
fresh(t)
up := &boundClaude{foreign: []string{"other-20"}, said: "messages.%d.content.%d: Invalid signature in thinking block. The block is bound to a different conversation. Remove the block, or set thinking.block_binding.prefix_mismatch_behavior to \"drop_block\"."}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
other := &boundClaude{}
srv2 := httptest.NewServer(other)
t.Cleanup(srv2.Close)
for _, p := range []provider.Provider{
{ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL, Models: []string{"claude-opus-5-5"}},
{ID: "relay2", Name: "Relay Two", Key: "k", Anthropic: srv2.URL, Models: []string{"claude-opus-5-5"}},
} {
if err := provider.Save(p); err != nil {
t.Fatal(err)
}
}
s := New()
postProto(t, s, "/v1/messages", boundConversation("relay/claude-opus-5-5"))
sent := up.sent()
if len(sent) != 2 {
t.Fatalf("asked %d times, want once more after the refusal", len(sent))
}
before := []string{"ok-a", "ok-0", "ok-2", "ok-4", "ok-6", "ok-8", "ok-10", "ok-12", "ok-14", "ok-16", "ok-18"}
if got := signatures(sent[1]); !slices.Equal(got, before) {
t.Errorf("asked again with %v, want the blocks before the refused one: %v", got, before)
}
// the rest of the conversation is as the agent wrote it
if n := len(gjson.Get(sent[1], "messages").Array()); n != 7 {
t.Errorf("%d messages, want 7", n)
}
if c := gjson.Get(sent[1], "messages.3.content"); len(c.Array()) != 21 || c.Get("20.type").String() != "tool_use" {
t.Errorf("message 3 = %s, want its blocks but the refused one", c.Raw)
}
if c := gjson.Get(sent[1], "messages.5.content"); len(c.Array()) != 1 || c.Get("0.id").String() != "t2" {
t.Errorf("message 5 = %s, want its tool call alone", c.Raw)
}
// the next turn: the provider gets it without them, at once
postProto(t, s, "/v1/messages", boundConversation("relay/claude-opus-5-5"))
if sent = up.sent(); len(sent) != 3 {
t.Fatalf("asked %d times more, want once", len(sent)-2)
}
if got := signatures(sent[2]); !slices.Equal(got, before) {
t.Errorf("next turn sent %v, want %v", got, before)
}
// another provider never refused them: it gets every block
postProto(t, s, "/v1/messages", boundConversation("relay2/claude-opus-5-5"))
if got := other.sent(); len(got) != 1 || len(signatures(got[0])) != 13 {
t.Errorf("another provider sent %d requests, signatures %v, want all 13 once", len(got), signatures(got[len(got)-1]))
}
}
// A refusal over something else, DeepSeek's wanting its thinking back
// among them, is passed on as it came: one request, every block kept.
func TestOtherRefusalKeepsThinking(t *testing.T) {
fresh(t)
up := &boundClaude{foreign: []string{"other-20"}, said: "messages.%d.content.%d: The `content[].thinking` in the thinking mode must be passed back to the API"}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "ds", Name: "DS", Key: "k", Anthropic: srv.URL, Models: []string{"claude-opus-5-5"}}); err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", "/v1/messages", strings.NewReader(boundConversation("ds/claude-opus-5-5")))
req.Header.Set("anthropic-version", "2023-06-01")
New().Handler().ServeHTTP(rec, req)
if rec.Code == 200 {
t.Fatalf("status 200, want the refusal")
}
if sent := up.sent(); len(sent) != 1 || len(signatures(sent[0])) != 13 {
t.Errorf("asked %d times, want once with every block", len(sent))
}
}
// withoutThinkingBlocks leaves a message that had only thinking out, and
// a body with nothing to leave out byte for byte.
func TestWithoutThinkingBlocks(t *testing.T) {
body := []byte(`{"model":"m","messages":[{"role":"user","content":"hi"},{"role":"assistant","content":[{"type":"redacted_thinking","data":"x"}]},{"role":"user","content":"go"}]}`)
got := withoutThinkingBlocks(body, func(int, int, gjson.Result) bool { return true })
if r := gjson.GetBytes(got, "messages.#.role").Raw; r != `["user","user"]` {
t.Errorf("roles %s, want the empty assistant message gone", r)
}
if got := withoutThinkingBlocks(body, func(int, int, gjson.Result) bool { return false }); string(got) != string(body) {
t.Errorf("changed with nothing to leave out: %s", got)
}
}
// The same through a plugin's fetch, as Command Code's plugin serves
// Claude: the refusal it passes on is read, and the plugin is asked again
// without the block.
func TestPluginBoundThinkingLeftOut(t *testing.T) {
up := &boundClaude{foreign: []string{"other-20"}, stream: true, said: "messages.%d.content.%d: Invalid signature in thinking block. The block is bound to a different conversation."}
pid := besideFake(t, "commandcode", up)
postProto(t, New(), "/v1/messages", boundConversation(pid+"/fake-claude"))
sent := up.sent()
if len(sent) != 2 {
t.Fatalf("plugin asked %d times, want once more after the refusal", len(sent))
}
if got := signatures(sent[1]); len(got) != 11 || slices.Contains(got, "other-20") || slices.Contains(got, "later-5") {
t.Errorf("asked again with %v, want the 11 blocks before the refused one", got)
}
}