gateway: a turn's parallel tool calls split over two assistant messages keep their results on Chat, Cursor and Devin (#1275)

An Anthropic request may send one turn's tool_use blocks in consecutive
assistant messages, answered by one user message. buildChat's
pairToolMessages, cursorMessages and buildDevin each closed the first
message's calls at the second one: the calls were answered "interrupted"
and the real results went out as a stray user message (Chat) or were
dropped (Cursor, Devin). joinSplitCalls now joins an assistant message
onto an assistant message before it that made tool calls, as Anthropic
reads them, so the calls are pending together. Responses, Messages,
Kiro and Gemini/Code Assist already kept the results.

Tests (split_calls_test.go): Chat, Cursor and Devin split cases fail on
main and pass now; a truly unanswered call of a split turn still gets
the synthetic result; text after a call in its own message; two text-only
assistant messages unchanged; Responses guard.
This commit is contained in:
yetone
2026-10-08 16:47:52 +08:00
parent 7d8cda18aa
commit 7067fce5ec
5 changed files with 189 additions and 5 deletions
+6 -3
View File
@@ -254,7 +254,8 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
seen = nil
}
}
for i, m := range r.Messages {
turns := joinSplitCalls(r.Messages)
for i, m := range turns {
if m.Role == "assistant" {
showSeen()
am := map[string]any{"role": "assistant"}
@@ -303,7 +304,7 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
// to go on) — and its reasoning goes with it where the upstream
// reads reasoning_content back, so the going on picks the thought
// up where it was cut
if r.Resume && i == len(r.Messages)-1 {
if r.Resume && i == len(turns)-1 {
mode := chatPrefill(host, model)
switch mode {
case "prefix":
@@ -471,7 +472,9 @@ func buildChat(r *Request, model, host string, rejectTemp bool) []byte {
// id used twice, the way the Responses path's orphanedToolOutputs
// turns an output without a call into a user message;
// - a call left unanswered gets a synthetic error result, so the turn
// can go on (an interrupted turn leaves its call pending);
// can go on (an interrupted turn leaves its call pending); a turn's
// calls split over consecutive assistant messages were joined into
// one by joinSplitCalls before, so they are pending together (#1275);
// - an assistant message with nothing in it — no text, no calls, no
// reasoning, what a thinking-only turn becomes — is dropped inside a
// pending exchange, where it would sit between calls and their
+1 -1
View File
@@ -476,7 +476,7 @@ func cursorMessages(r *Request, tools []bridgeTool) [][]byte {
add(map[string]any{"role": "tool", "content": results})
}
}
for _, m := range r.Messages {
for _, m := range joinSplitCalls(r.Messages) {
if m.Role == "assistant" {
answer(nil)
var content []any
+1 -1
View File
@@ -319,7 +319,7 @@ func buildDevin(r *Request, uid, key string) []byte {
}
pending = nil
}
for _, m := range r.Messages {
for _, m := range joinSplitCalls(r.Messages) {
if m.Role == "assistant" {
a := devinMsg{role: devinAssistant}
var texts []string
+29
View File
@@ -78,6 +78,35 @@ type Message struct {
Parts []Part
}
// joinSplitCalls joins an assistant message onto the assistant message
// before it when that one made tool calls: Anthropic's Messages takes
// consecutive assistant messages as one turn, and an agent can send a
// turn's parallel tool_use blocks split over two of them, answered by one
// user message (#1275). A builder that closes a turn's calls at the next
// assistant message would otherwise answer the first calls as interrupted
// and lose their real results. ms is left as it is.
func joinSplitCalls(ms []Message) []Message {
out := make([]Message, 0, len(ms))
for _, m := range ms {
if n := len(out); n > 0 && m.Role == "assistant" && out[n-1].Role == "assistant" && hasCalls(out[n-1].Parts) {
out[n-1].Parts = append(out[n-1].Parts, m.Parts...)
continue
}
out = append(out, Message{Role: m.Role, Parts: append([]Part(nil), m.Parts...)})
}
return out
}
// hasCalls reports whether parts hold a tool call.
func hasCalls(parts []Part) bool {
for _, p := range parts {
if p.Kind == ToolCall {
return true
}
}
return false
}
// Tool is a function the model may call.
type Tool struct {
Name string
+152
View File
@@ -0,0 +1,152 @@
package gateway
import (
"bytes"
"encoding/json"
"strings"
"testing"
)
// splitCalls is #1275's request as an agent sent it: one turn's parallel
// tool_use blocks split over two consecutive assistant messages, answered
// by one user message carrying both results.
const splitCalls = `{"model":"m","max_tokens":1024,"messages":[
{"role":"user","content":"read a and b"},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_a","name":"read","input":{"path":"a"}}]},
{"role":"assistant","content":[{"type":"tool_use","id":"toolu_b","name":"read","input":{"path":"b"}}]},
{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_a","content":"A!"},
{"type":"tool_result","tool_use_id":"toolu_b","content":"B!"}]}]}`
func parseSplit(t *testing.T, body string) *Request {
t.Helper()
r, err := parseAnthropic([]byte(body))
if err != nil {
t.Fatal(err)
}
return r
}
// The two calls are one exchange on Chat: both answered by their real
// results, none marked interrupted, nothing left as a stray user message.
func TestChatSplitParallelCallsKeepTheirResults(t *testing.T) {
r := parseSplit(t, splitCalls)
trace, msgs := chatTrace(t, r)
if want := "user assistant(toolu_a,toolu_b) tool(toolu_a) tool(toolu_b)"; trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if a, b := msgs[2]["content"], msgs[3]["content"]; a != "A!" || b != "B!" {
t.Fatalf("results = %q, %q, want the real ones", a, b)
}
if !kimiValid(msgs) || !idsUsedOnce(msgs) {
t.Fatal("sequence fails Kimi's tool exchange validation")
}
if len(r.Messages) != 4 {
t.Fatalf("the request's own messages changed: %d", len(r.Messages))
}
}
// A call of the split turn that really went unanswered still gets the
// synthetic result, after the real ones as in a turn sent whole, and the
// answered one keeps its own.
func TestChatSplitCallsUnansweredStillSynthetic(t *testing.T) {
r := parseSplit(t, strings.Replace(splitCalls,
`{"type":"tool_result","tool_use_id":"toolu_a","content":"A!"},`, "", 1))
trace, msgs := chatTrace(t, r)
if want := "user assistant(toolu_a,toolu_b) tool(toolu_b) tool(toolu_a)"; trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if a, _ := msgs[3]["content"].(string); !strings.Contains(a, "unavailable") {
t.Fatalf("unanswered toolu_a = %q, want the synthetic result", a)
}
if b := msgs[2]["content"]; b != "B!" {
t.Fatalf("toolu_b = %q, want B!", b)
}
}
// Text the turn said after its call, in a message of its own, joins the
// turn too, so the call is still answered by its result.
func TestChatSplitTextAfterCallKeepsResult(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "read a"}}},
{Role: "assistant", Parts: []Part{call("A")}},
{Role: "assistant", Parts: []Part{{Kind: Text, Text: "reading"}}},
{Role: "user", Parts: []Part{result("A", "1")}},
}}
trace, msgs := chatTrace(t, r)
if want := "user assistant(A) tool(A)"; trace != want {
t.Fatalf("trace = %q, want %q", trace, want)
}
if msgs[1]["content"] != "reading" || msgs[2]["content"] != "1" {
t.Fatalf("assistant %q, answer %q", msgs[1]["content"], msgs[2]["content"])
}
}
// Two assistant messages with no calls are left as they were.
func TestChatConsecutiveTextAssistantsUnchanged(t *testing.T) {
r := &Request{Messages: []Message{
{Role: "user", Parts: []Part{{Kind: Text, Text: "hi"}}},
{Role: "assistant", Parts: []Part{{Kind: Text, Text: "one"}}},
{Role: "assistant", Parts: []Part{{Kind: Text, Text: "two"}}},
}}
if trace, _ := chatTrace(t, r); trace != "user assistant assistant" {
t.Fatalf("trace = %q", trace)
}
}
// Responses carries calls as items of their own, so the split turn's
// results follow their calls there already.
func TestResponsesSplitParallelCallsKeepTheirResults(t *testing.T) {
var q struct {
Input []map[string]any `json:"input"`
}
if err := json.Unmarshal(buildResponses(parseSplit(t, splitCalls), "gpt-5.4", "api.openai.com", false), &q); err != nil {
t.Fatal(err)
}
var got []string
for _, it := range q.Input {
s, _ := it["type"].(string)
if id, ok := it["call_id"].(string); ok {
s += "(" + id
if out, ok := it["output"].(string); ok {
s += "=" + out
}
s += ")"
}
got = append(got, s)
}
want := "message function_call(toolu_a) function_call(toolu_b) function_call_output(toolu_a=A!) function_call_output(toolu_b=B!)"
if strings.Join(got, " ") != want {
t.Fatalf("input = %s\nwant %s", strings.Join(got, " "), want)
}
}
// Cursor's built-in answers a reply's calls at the next assistant message,
// as Chat did.
func TestCursorSplitParallelCallsKeepTheirResults(t *testing.T) {
r := parseSplit(t, splitCalls)
b := bytes.Join(cursorMessages(r, bridgeTools(r)), []byte("\n"))
if bytes.Contains(b, []byte(devinNoResult)) {
t.Fatalf("a call answered as interrupted:\n%s", b)
}
if !bytes.Contains(b, []byte(`"result":"A!"`)) || !bytes.Contains(b, []byte(`"result":"B!"`)) {
t.Fatalf("results lost:\n%s", b)
}
}
// So did Devin's.
func TestDevinSplitParallelCallsKeepTheirResults(t *testing.T) {
d := decodeDevinRequest(t, buildDevin(parseSplit(t, splitCalls), "swe-2-high", "k"))
var got []string
for _, m := range d.msgs {
got = append(got, devinSummary(m))
}
want := []string{
"1:read a and b",
`2: call toolu_a/read {"path":"a"} call toolu_b/read {"path":"b"}`,
"4:A! for toolu_a",
"4:B! for toolu_b",
}
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Fatalf("got\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}