gateway: a broken tool exchange a Chat or Zed client left is mended for a Messages upstream, as the Chat and Responses paths mend theirs

What changed: buildAnthropic (every request built for a Messages
upstream: a Chat or Responses client's conversation translated, Zed's
bridge) now runs its messages through pairToolBlocks, as buildChat's
pairToolMessages (#554) and the relayed Responses path's pairToolItems
(#1341) mend theirs. Anthropic refuses a tool_use the next message's
tool_results don't answer ("`tool_use` ids were found without
`tool_result` blocks immediately after") and a tool_result naming a call
it never saw ("unexpected `tool_use_id` found in `tool_result` blocks");
an interrupted turn leaves the first behind, a client that dropped a
call the second. A call left unanswered gets the synthetic result the
other paths make; an answer to no call becomes a text block keeping
what it said. A well-formed exchange is built exactly as it was (ids in
their places, results in the order the client sent, text after them).

TestZedToolResultSaysIsError's fixture carried a result for a call the
request never made; it asserted the orphan went through as a
tool_result, which the cloud refuses. It now goes out as the text it
said, and the test says so.

Run:
- /tmp/sbx.sh test -tags nogui -count=1 -run 'TestMessages' ./internal/gateway/
  with the pairing call taken out: 6 FAIL (trace "user assistant(A)",
  and the end-to-end one 400 "unexpected `tool_use_id` found in
  `tool_result` blocks"); with it back in, all pass
- /tmp/sbx.sh test -tags nogui -count=1 ./internal/gateway/ — ok
- gofmt -l (nothing), go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... (the trayimage_darwin.go -Wenum-conversion
  warning as on main), go build, GOOS=linux go build -tags nogui,
  GOOS=windows go build

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
ggbdpq
2026-10-13 06:43:00 +08:00
committed by yetone
co-authored by factory-droid[bot]
parent 44b5b2b96b
commit e21b1dbc16
3 changed files with 452 additions and 7 deletions
+111 -6
View File
@@ -747,6 +747,16 @@ func imageBlock(p Part) aBlock {
return b
}
// aMessage is one message of a request built for a Messages upstream.
type aMessage struct {
Role string `json:"role"`
Content []aBlock `json:"content"`
}
// interruptedTool is what an unanswered call gets, as pairToolMessages and
// pairToolItems make for the Chat and Responses paths.
const interruptedTool = "[The result of this tool call is unavailable: the turn was interrupted.]"
// buildAnthropic renders a request for an Anthropic-style upstream.
func buildAnthropic(r *Request, model string) []byte {
return anthropicBody(r, model, false)
@@ -761,11 +771,7 @@ func anthropicBody(r *Request, model string, replay bool) []byte {
// asked for in words
r = r.inSystem()
}
type msg struct {
Role string `json:"role"`
Content []aBlock `json:"content"`
}
var msgs []msg
var msgs []aMessage
push := func(role string, blocks []aBlock) {
if len(blocks) == 0 {
return
@@ -774,7 +780,7 @@ func anthropicBody(r *Request, model string, replay bool) []byte {
msgs[n-1].Content = append(msgs[n-1].Content, blocks...)
return
}
msgs = append(msgs, msg{Role: role, Content: blocks})
msgs = append(msgs, aMessage{Role: role, Content: blocks})
}
for _, m := range r.Messages {
var results, rest []aBlock
@@ -823,6 +829,10 @@ func anthropicBody(r *Request, model string, replay bool) []byte {
}
push(role, append(results, rest...))
}
// a conversation a client left with its exchange broken — a call whose
// turn was interrupted, a result whose call it dropped — is mended, as
// the Chat and Responses paths mend theirs, where Anthropic refuses it
msgs = pairToolBlocks(msgs)
// Anthropic caches a prompt only up to a block marked for it, which a
// request from another API (Codex's, a Chat client's) never has: the
// conversation so far is marked at its last block, so the next turn,
@@ -950,6 +960,101 @@ func anthropicBody(r *Request, model string, replay bool) []byte {
return b
}
// pairToolBlocks mends the tool exchange of a request built for a Messages
// upstream, as pairToolMessages does for a Chat one (#554) and
// pairToolItems for a relayed Responses request (#1341): Anthropic refuses
// a tool_use the next message's tool_results don't answer ("`tool_use` ids
// were found without `tool_result` blocks immediately after") and a
// tool_result naming a call it never saw ("unexpected `tool_use_id` found
// in `tool_result` blocks") — an interrupted turn or a client that dropped
// its calls leaves both behind, and a relay serving Claude over Messages
// passes the refusal on. A call left unanswered gets a synthetic result in
// the user message that follows, or one of its own where none does; an
// answer to no call becomes a text block, keeping what it said. A
// well-formed exchange is built exactly as it was.
func pairToolBlocks(msgs []aMessage) []aMessage {
out := make([]aMessage, 0, len(msgs))
var pending []string // the calls of the assistant message in hand
open := map[string]bool{} // which of them stand
answered := map[string]bool{} // pending calls a result answered
// synthetic is a call's missing result
synthetic := func(id string) aBlock {
c, _ := json.Marshal(interruptedTool)
return aBlock{Type: "tool_result", ToolUseID: id, Content: c, IsError: true}
}
// closeExchange answers the calls still open and ends the exchange
closeExchange := func() {
var blocks []aBlock
for _, id := range pending {
if !answered[id] {
blocks = append(blocks, synthetic(id))
}
}
if len(blocks) > 0 {
out = append(out, aMessage{Role: "user", Content: blocks})
}
pending, open, answered = nil, map[string]bool{}, map[string]bool{}
}
for _, m := range msgs {
if m.Role == "assistant" {
closeExchange()
for _, b := range m.Content {
if b.Type == "tool_use" {
pending = append(pending, b.ID)
open[b.ID] = true
}
}
out = append(out, m)
continue
}
var kept, rest []aBlock
for _, b := range m.Content {
if b.Type != "tool_result" {
rest = append(rest, b)
continue
}
if !open[b.ToolUseID] {
// answers no call of the exchange in hand — one another
// request carried, that closed already, or never there
rest = append(rest, resultSaid(b)...)
continue
}
if answered[b.ToolUseID] {
continue // a second answer: the first stands
}
answered[b.ToolUseID] = true
kept = append(kept, b)
}
for _, id := range pending {
if !answered[id] {
kept = append(kept, synthetic(id))
}
}
out = append(out, aMessage{Role: "user", Content: append(kept, rest...)})
pending, open, answered = nil, map[string]bool{}, map[string]bool{}
}
closeExchange()
return out
}
// resultSaid is what a tool_result that answers no call keeps: its text as
// a text block, its images beside it as they came.
func resultSaid(b aBlock) []aBlock {
var s string
if len(b.Content) > 0 && json.Unmarshal(b.Content, &s) == nil {
if strings.TrimSpace(s) == "" {
s = "Tool result received."
}
return []aBlock{{Type: "text", Text: s}}
}
var blocks []aBlock
if len(b.Content) > 0 && json.Unmarshal(b.Content, &blocks) == nil && len(blocks) > 0 {
return blocks
}
return []aBlock{{Type: "text", Text: "Tool result received."}}
}
// anthropicDecoder leaves out the blocks of Anthropic's own server tools —
// a web search it ran — whose input is no call of the client's. A
// tool_use block whose start carries its whole input, as a relay in front
@@ -0,0 +1,327 @@
package gateway
import (
"encoding/json"
"strconv"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// wantInterrupted is the synthetic result the other paths make for a call
// whose turn was interrupted (pairToolMessages, pairToolItems).
const wantInterrupted = "[The result of this tool call is unavailable: the turn was interrupted.]"
// aBlockProbe is one content block of a request built for a Messages
// upstream, as the tests read it back.
type aBlockProbe struct {
Type string `json:"type"`
ID string `json:"id"`
ToolUseID string `json:"tool_use_id"`
Text string `json:"text"`
Content json.RawMessage `json:"content"`
}
// aMessageProbe is one message of it.
type aMessageProbe struct {
Role string `json:"role"`
Content []aBlockProbe `json:"content"`
}
// messagesTrace renders the message sequence of a request built for a
// Messages upstream: roles with the calls made and the results answered,
// e.g. "user assistant(A) user[A] user".
func messagesTrace(t *testing.T, r *Request) (string, []aMessageProbe) {
t.Helper()
body := buildAnthropic(r, "claude-sonnet-4-5")
var q struct {
Messages []aMessageProbe `json:"messages"`
}
if err := json.Unmarshal(body, &q); err != nil {
t.Fatalf("built request does not parse: %v", err)
}
var b strings.Builder
for _, m := range q.Messages {
b.WriteString(" " + m.Role)
var calls, results []string
for _, c := range m.Content {
switch c.Type {
case "tool_use":
calls = append(calls, c.ID)
case "tool_result":
results = append(results, c.ToolUseID)
}
}
if len(calls) > 0 {
b.WriteString("(" + strings.Join(calls, ",") + ")")
}
if len(results) > 0 {
b.WriteString("[" + strings.Join(results, ",") + "]")
}
}
return strings.TrimSpace(b.String()), q.Messages
}
// anthropicValid reports whether a built message sequence passes what
// Anthropic's Messages API validates: every tool_result names a call of the
// assistant message it follows, and every call is answered by the results
// of that message.
func anthropicValid(msgs []aMessageProbe) bool {
pending := map[string]bool{}
for _, m := range msgs {
if m.Role == "assistant" {
pending = map[string]bool{}
for _, c := range m.Content {
if c.Type == "tool_use" {
pending[c.ID] = true
}
}
continue
}
for _, c := range m.Content {
if c.Type != "tool_result" {
continue
}
if !pending[c.ToolUseID] {
return false // unexpected tool_use_id found in tool_result blocks
}
delete(pending, c.ToolUseID)
}
if len(pending) > 0 {
return false // tool_use ids were found without tool_result blocks
}
}
return true
}
// messagesRefused is Anthropic's refusal of a broken tool exchange, as its
// API answers it and a relay serving Claude over Messages passes it on.
func messagesRefused(at int, msg string) string {
b, _ := json.Marshal(map[string]any{"type": "error", "error": map[string]any{
"type": "invalid_request_error", "message": "messages." + strconv.Itoa(at) + ": " + msg}})
return string(b)
}
// validateExchange refuses a Messages request the way Anthropic's own does
// over a broken tool exchange, with its documented 400s.
func validateExchange(body []byte) (int, string) {
var q struct {
Messages []aMessageProbe `json:"messages"`
}
if err := json.Unmarshal(body, &q); err != nil {
return 400, messagesRefused(0, "could not parse the request")
}
pending := map[string]bool{}
for i, m := range q.Messages {
if m.Role == "assistant" {
for _, c := range m.Content {
if c.Type == "tool_use" {
pending[c.ID] = true
}
}
continue
}
for _, c := range m.Content {
if c.Type != "tool_result" {
continue
}
if !pending[c.ToolUseID] {
return 400, messagesRefused(i, "unexpected `tool_use_id` found in `tool_result` blocks: "+c.ToolUseID+". Each `tool_result` block must have a corresponding `tool_use` block in the previous message.")
}
delete(pending, c.ToolUseID)
}
for id := range pending {
return 400, messagesRefused(i, "`tool_use` ids were found without `tool_result` blocks immediately after: "+id+". Each `tool_use` block must have a corresponding `tool_result` block in the next message.")
}
}
for id := range pending {
return 400, messagesRefused(len(q.Messages), "`tool_use` ids were found without `tool_result` blocks immediately after: "+id+". Each `tool_use` block must have a corresponding `tool_result` block in the next message.")
}
return 0, ""
}
// An interrupted turn leaves its call without a result: the synthetic one
// goes into the user message that follows, before what the user said, as
// pairToolMessages and pairToolItems make for the Chat and Responses paths
// (#554, #1341). Anthropic refuses the call as it was — "messages.2:
// `tool_use` ids were found without `tool_result` blocks immediately
// after" — and a relay serving Claude over Messages passes it on.
func TestMessagesUnansweredCallGetsSyntheticResult(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "run it"}}},
{Role: "assistant", Parts: []Part{call("A")}},
{Role: "user", Parts: []Part{{Kind: Text, Text: "go on"}}},
}}
trace, msgs := messagesTrace(t, r)
want := "user assistant(A) user[A]"
if trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if !anthropicValid(msgs) {
t.Fatal("sequence fails Anthropic's tool exchange validation")
}
if got := msgs[2].Content[0]; got.Type != "tool_result" || got.ToolUseID != "A" || string(got.Content) != `"`+wantInterrupted+`"` {
t.Fatalf("the synthetic result is not what the other paths make: %+v %s", got, got.Content)
}
if got := msgs[2].Content[1]; got.Type != "text" || got.Text != "go on" {
t.Fatalf("what the user said is not kept after it: %+v", got)
}
}
// A result answering no call the request carries — its call went with an
// earlier request, was closed already, or was never there — becomes a text
// block, as a Chat upstream's becomes a user message. Anthropic refuses it
// as it is: "unexpected `tool_use_id` found in `tool_result` blocks".
func TestMessagesOrphanToolResultBecomesText(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "run it"}}},
{Role: "assistant", Parts: []Part{call("A")}},
{Role: "user", Parts: []Part{result("A", "ok"), result("gone", "late")}},
}}
trace, msgs := messagesTrace(t, r)
want := "user assistant(A) user[A]"
if trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if !anthropicValid(msgs) {
t.Fatal("sequence fails Anthropic's tool exchange validation")
}
var texts []string
for _, c := range msgs[2].Content {
if c.Type == "tool_result" && c.ToolUseID == "gone" {
t.Fatalf("the orphan result is still a tool_result: %+v", c)
}
if c.Type == "text" {
texts = append(texts, c.Text)
}
}
if len(texts) == 0 || texts[0] != "late" {
t.Fatalf("what the orphan said is not kept: %v in %+v", texts, msgs[2].Content)
}
}
// A result with no call anywhere in the request keeps what it said as text,
// beside what the user said, in the one message they build.
func TestMessagesOrphanToolResultWithoutACallBecomesText(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{result("gone", "late"), {Kind: Text, Text: "go on"}}},
}}
trace, msgs := messagesTrace(t, r)
want := "user"
if trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
last := msgs[len(msgs)-1].Content
if last[0].Type != "text" || last[0].Text != "late" {
t.Fatalf("the orphan is not text: %+v", last[0])
}
if last[1].Type != "text" || last[1].Text != "go on" {
t.Fatalf("what the user said moved: %+v", last[1])
}
}
// A conversation that ends on its calls — the client asks the turn to go on
// — ends on their synthetic results, as a Chat request ends on theirs.
func TestMessagesUnansweredCallAtTheEnd(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "run it"}}},
{Role: "assistant", Parts: []Part{call("A")}},
}}
trace, msgs := messagesTrace(t, r)
want := "user assistant(A) user[A]"
if trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if !anthropicValid(msgs) {
t.Fatal("sequence fails Anthropic's tool exchange validation")
}
}
// A well-formed exchange is built exactly as before: parallel results out
// of order keep their order, a result keeps its place before the text
// beside it, and every id goes where it did.
func TestMessagesCleanExchangeUntouched(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "run them"}}},
{Role: "assistant", Parts: []Part{call("A"), call("B")}},
{Role: "user", Parts: []Part{result("B", "second"), result("A", "first"), {Kind: Text, Text: "done"}}},
}}
trace, msgs := messagesTrace(t, r)
want := "user assistant(A,B) user[B,A]"
if trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if !anthropicValid(msgs) {
t.Fatal("sequence fails Anthropic's tool exchange validation")
}
third := msgs[2].Content
if third[0].Type != "tool_result" || third[0].ToolUseID != "B" || third[1].ToolUseID != "A" || third[2].Text != "done" {
t.Fatalf("results or text moved: %+v", third)
}
}
// Another vendor's call id ("Bash:0#…", 6c099edd) still goes out through
// anthropicOutID when the exchange is mended, and the call and its
// synthetic result keep matching.
func TestMessagesMendedExchangeKeepsForeignIDsEncoded(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "run it"}}},
{Role: "assistant", Parts: []Part{call("Bash:0#a65b6a5e")}},
{Role: "user", Parts: []Part{result("gone", "late")}},
}}
_, msgs := messagesTrace(t, r)
id := anthropicOutID("Bash:0#a65b6a5e")
if msgs[1].Content[0].ID != id {
t.Fatalf("the call's id is not encoded as the Messages path does: %+v", msgs[1].Content[0])
}
for _, m := range msgs {
for _, c := range m.Content {
if c.Type == "tool_result" && c.ToolUseID == "gone" {
t.Fatalf("the orphan result survived as a result: %+v", c)
}
if c.Type == "tool_result" && c.ToolUseID != id {
t.Fatalf("the synthetic result names another id: %+v", c)
}
}
}
if !anthropicValid(msgs) {
t.Fatal("sequence fails Anthropic's tool exchange validation")
}
}
// An interrupted turn and a late result, sent by an agent that speaks Chat
// to a provider that serves the model over Messages alone: the upstream is
// asked a mended exchange and answers, where the broken one was refused 400
// and the turn failed.
func TestMessagesUpstreamAnswersABrokenToolExchange(t *testing.T) {
f := &fake{t: t, refuse: validateExchange, reply: sse(
`data: {"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"x","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`,
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"ok"}}`,
`data: {"type":"content_block_stop","index":0}`,
`data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`,
`data: {"type":"message_stop"}`,
)}
setup(t, provider.Anthropic, f)
body := `{"model":"fake/m1","stream":true,"messages":[` +
`{"role":"user","content":"run it"},` +
`{"role":"assistant","content":null,"tool_calls":[{"id":"call_1","type":"function","function":{"name":"run","arguments":"{}"}}]},` +
`{"role":"tool","tool_call_id":"call_gone","content":"late"},` +
`{"role":"user","content":"go on"}]}`
if code, out := post(t, "/v1/chat/completions", body); code != 200 {
t.Fatalf("status %d: %s", code, out)
}
if f.path != "/v1/messages" {
t.Fatalf("not translated to Messages: %s", f.path)
}
if code, msg := validateExchange(f.got); code != 0 {
t.Fatalf("the upstream was asked a broken exchange: %s", msg)
}
if !strings.Contains(string(f.got), `"tool_use_id":"call_1"`) {
t.Fatalf("no result for the interrupted call reached the upstream: %s", f.got)
}
if strings.Contains(string(f.got), `"tool_use_id":"call_gone"`) {
t.Fatalf("the orphan result reached the upstream as one: %s", f.got)
}
}
+14 -1
View File
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/http/httptest"
"slices"
"strings"
"sync/atomic"
"testing"
@@ -233,6 +234,7 @@ func TestZedToolResultSaysIsError(t *testing.T) {
t.Fatal(err)
}
var errs []any
var texts []string
for _, m := range got.Messages {
for _, b := range m.Content {
if b["type"] == "tool_result" {
@@ -242,12 +244,23 @@ func TestZedToolResultSaysIsError(t *testing.T) {
}
errs = append(errs, v)
}
if b["type"] == "text" {
if s, ok := b["text"].(string); ok {
texts = append(texts, s)
}
}
}
}
if !bytes.Contains(raw, []byte(`12345678901234567890`)) {
t.Errorf("a tool input number changed: %s", raw)
}
if len(errs) != 2 || errs[0] != false || errs[1] != true {
// toolu_2's result answers no call in the request, so it goes out as
// the text it said (pairToolBlocks), where the cloud refuses a result
// with no call as Anthropic does; the one real result keeps is_error
if len(errs) != 1 || errs[0] != false {
t.Errorf("is_error: %v in %s", errs, raw)
}
if !slices.Contains(texts, "no") {
t.Errorf("what the lost result said is not kept: %v in %s", texts, raw)
}
}