diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 79cffa5da..4c2c2ad86 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -286,7 +286,7 @@ recorded as a prediction failure (`noPrediction`). - A Messages or Chat upstream whose host and model don't say DeepSeek but whose model answers 400 "The `content[].thinking` (or `reasoning_content`) in the thinking mode must be passed back to the API" (`thinkingBackRefusal` in [`thinking_back.go`](../../internal/gateway/thinking_back.go)) is asked once more with its tool turns filled as above (`withThinkingOnToolTurns`, `withReasoningOnToolTurns`), and that provider's model is sent them at once from then on (`thinkingBackNeeded` in `unfit`, filled in `forwardOnce`), on every route to it. A relay serving DeepSeek under another name, or a provider the user named "My Claude", got a routing group's fall from a rate-limited Codex subscription mid tool loop refused, Codex's sealed reasoning having no text to give (qisishiqi on Discord, 2026-11-02). Checked against api.deepseek.com on 2026-11-02: only the tool loop being continued needs it; finished turns and plain replies are taken without. A provider that never asked is sent the turns as before. `TestThinkingBackLearnedBehindAnotherName`, `TestReasoningBackLearnedBehindAnotherName`. - 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 model writes a whole number in a call's arguments with a fraction of zeros (`2500.0`, `17277.0`, tool_search's `limit: 8.0`): Grok's on every turn, whoever serves it (#1431), and muse-spark through the gateway (#3152). Codex reads the integer fields it parses as u64, usize or i32 even though their schemas say `number`, so serde turns away the whole call ("invalid number" for tool_search's arguments). In every reply, 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 and one that took `2500.0` takes `2500`. 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; a whole reply with no call in it is said as it came, undecoded. A glm-5.3-flash* route's stitched CR (`crTidy`, #4256) is dropped before `intTidy` sees the reply, since `intTidy` holds a whole one to its flush (`TestStitchedCRAndWholeFloatsBothGo`). Translated replies are rewritten at the encoder (`wholeEncoder`, outside `usageEncoder`) and at `render` (`wholeResult`). Grok's schema quirks stay `grokModel`'s ([`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' `{…}`, 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 `` form (#917), GLM's ``/`` (#906), and the plain `…` of Claude's and MiniMax's calls, bare or in `` or `` (packinggoodsllc_07668 on Discord: Claude Code through a routing group was shown the invokes as text), read by `parseTextCalls`. Text after a call read out, other than tags, ends the calls, and it and all after it go: the model went on as if its call had run ("*Result: Tool loaded.*", then the next call, then "done"), and the agent runs the call and gives it the real result. 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 (``) 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`), a relayed Messages reply, streamed or whole (`anthropicTextCalls`: the held text's block start and stop are held with it, the calls become `tool_use` blocks after it, or in its place when none of its text went), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses reply, streamed or whole, is read too (`responsesTextCalls` in [`textcalls_relay.go`](../../internal/gateway/textcalls_relay.go), #4743, from v0.1.2652): the held text's `output_text.done`, `content_part.done` and `output_item.done` wait with it, and the calls become `function_call` items after it, in the events and in `response.completed`'s output. Before it, Alma (whose provider of type openai speaks Responses) through a group to DeepSeek, whose preset speaks Responses too, had the reply relayed as it came and got DeepSeek's `<||DSML|| calls>` as text with nothing run (wishSeikouudoku on X). A relayed Gemini reply the same (`geminiTextCalls`). Covered by `TestTextWritten*`, `TestInvokeReported*`, `TestDSMLAlma*` (a group of Responses members and a plugin's DeepSeek, from a Responses client, one character to a delta), `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`. +- 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' `{…}`, 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 `` form (#917), GLM's ``/`` (#906), and the plain `…` of Claude's and MiniMax's calls, bare or in `` or `` (packinggoodsllc_07668 on Discord: Claude Code through a routing group was shown the invokes as text), read by `parseTextCalls`. Text after a call read out, other than tags, ends the calls, and it and all after it go: the model went on as if its call had run ("*Result: Tool loaded.*", then the next call, then "done"), and the agent runs the call and gives it the real result. 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 (``) 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`), a relayed Messages reply, streamed or whole (`anthropicTextCalls`: the held text's block start and stop are held with it, the calls become `tool_use` blocks after it, or in its place when none of its text went), and every translation, which magpie always asks streamed, a plugin's included, whatever the client asked (`textCallSee`). A relayed Responses reply, streamed or whole, is read too (`responsesTextCalls` in [`textcalls_relay.go`](../../internal/gateway/textcalls_relay.go), #4743, from v0.1.2652): the held text's `output_text.done`, `content_part.done` and `output_item.done` wait with it, and the calls become `function_call` items after it, in the events and in `response.completed`'s output. Before it, Alma (whose provider of type openai speaks Responses) through a group to DeepSeek, whose preset speaks Responses too, had the reply relayed as it came and got DeepSeek's `<||DSML|| calls>` as text with nothing run (wishSeikouudoku on X). A relayed Gemini reply the same (`geminiTextCalls`). Covered by `TestTextWritten*`, `TestInvokeReported*`, `TestDSMLAlma*` (a group of Responses members and a plugin's DeepSeek, from a Responses client, one character to a delta), `TestDSMLClose*`, `TestDSMLBlockClosedWithCalls`, `TestGLMTextCall*`, `TestPluginTextWrittenCall` and `TestQuietWholeReplyStreamed`. Relayed Messages streams buffer complete SSE events with `tidyEvents` ([`phase.go`](../../internal/gateway/phase.go)), so splitting an event header, data and blank delimiter across reads cannot detach headers or join distinct JSON payloads (#4868). Held text-block starts and stops own their bytes so buffer reuse cannot overwrite them. `TestAnthropicTextCallsSSEChunksKeepFraming` and `TestAnthropicMessagesSSEChunksKeepFraming` cover native and text-written calls, held text, whole/event/line/byte reads, and CRLF. - 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. - A tool's images reach the model on every translation (`toolOutput` in [`ir.go`](../../internal/gateway/ir.go) reads them from Anthropic's `tool_result`, Responses' `function_call_output`, such as Codex's `view_image` output `[{"type":"input_image","image_url":"data:…"}]`, and a Chat tool message). Anthropic's Messages keeps them in the `tool_result`. Chat puts them in a user message right after the results, and the result says they follow; Gemini and Code Assist after the function's response. Kiro's results hold text alone, so Kiro's plugin (from 0.1.9 on) sends them with the message that answers the call, and only the latest images go again (#369, #1861). `TestCodexToolImageReachesAnthropicPlugin` and the Kiro plugin's `tool-images.test.mjs`. - An image's `detail` (`Part.Detail`, read from a Responses `input_image` and a Chat `image_url`, in a message or a tool's output) is carried on a translation to Chat and Responses (`chatImage`, `chatDetail`, `responsesDetail` in [`chat.go`](../../internal/gateway/chat.go)). Chat takes `low`, `high` and `auto` as they came, and Responses' `original`, which Chat lacks, as `high`; an image without one goes without. Responses takes the four as they came, and anything else, none included, as `auto` (#1474). Messages and Gemini have no such field, so it isn't sent there (mysterious_dove on Discord, Codex: `high` and `original` were dropped on the way to Chat; `TestResponsesImageDetailReachesChat`, `TestChatImageDetailReachesResponses`). diff --git a/internal/gateway/textcalls_anthropic.go b/internal/gateway/textcalls_anthropic.go index 132d915e1..de352c63b 100644 --- a/internal/gateway/textcalls_anthropic.go +++ b/internal/gateway/textcalls_anthropic.go @@ -1,7 +1,6 @@ package gateway import ( - "bytes" "encoding/json" "strings" ) @@ -27,7 +26,6 @@ type anthropicTextCalls struct { names map[string]bool sse bool buf []byte - ev []byte // the lines of the event being read idx int // the open text block's index text bool // a text block is being read @@ -45,47 +43,24 @@ func (t *anthropicTextCalls) write(b []byte) []byte { if !t.sse { return nil } - i := bytes.LastIndexByte(t.buf, '\n') - if i < 0 { - return nil - } - var out []byte - for _, line := range bytes.SplitAfter(t.buf[:i+1], []byte("\n")) { - out = append(out, t.line(line)...) - } - t.buf = append(t.buf[:0], t.buf[i+1:]...) + out, rest := tidyEvents(t.buf, t.event) + t.buf = rest return out } func (t *anthropicTextCalls) flush() []byte { + b := t.buf + t.buf = nil if !t.sse { - b := t.buf - t.buf = nil return t.whole(b) } var out []byte - if len(t.buf) > 0 { - out = t.line(t.buf) - t.buf = nil - } - if len(t.ev) > 0 { - out = append(out, t.event(t.ev)...) - t.ev = nil + if len(b) > 0 { + out = t.event(b) } return append(out, t.release()...) } -// line gathers an event's lines; a blank one ends it. -func (t *anthropicTextCalls) line(line []byte) []byte { - t.ev = append(t.ev, line...) - if len(bytes.TrimSpace(line)) > 0 { - return nil - } - ev := t.ev - t.ev = nil - return t.event(ev) -} - // messagesEvent is a Messages stream event of v. func messagesEvent(typ string, v any) []byte { b, _ := marshalPlain(v) @@ -99,12 +74,7 @@ func (t *anthropicTextCalls) textDelta(s string) []byte { // event is one whole event, given on, held or made into others. func (t *anthropicTextCalls) event(ev []byte) []byte { - var data []byte - for _, l := range bytes.Split(ev, []byte("\n")) { - if d, ok := bytes.CutPrefix(bytes.TrimRight(l, "\r"), []byte("data:")); ok { - data = bytes.TrimSpace(d) - } - } + data := eventData(ev) var m map[string]json.RawMessage if len(data) == 0 || decodeJSON(data, &m) != nil || m == nil { return ev @@ -126,7 +96,7 @@ func (t *anthropicTextCalls) event(ev []byte) []byte { t.native = true } if cb.Type == "text" && cb.Text == "" { - t.idx, t.text, t.startHeld = index, true, ev + t.idx, t.text, t.startHeld = index, true, append([]byte(nil), ev...) return pre } t.text = false @@ -163,7 +133,7 @@ func (t *anthropicTextCalls) event(ev []byte) []byte { return ev } if t.holding || t.pending != "" { - t.stopHeld = ev + t.stopHeld = append([]byte(nil), ev...) return nil } out := t.startHeld diff --git a/internal/gateway/textcalls_anthropic_chunks_test.go b/internal/gateway/textcalls_anthropic_chunks_test.go new file mode 100644 index 000000000..24b0e4614 --- /dev/null +++ b/internal/gateway/textcalls_anthropic_chunks_test.go @@ -0,0 +1,527 @@ +package gateway + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// nativeAnthropicToolStream is a Messages reply whose text block is followed +// by a tool_use the model made itself. Its events, data lines and blank +// delimiters are the shape a Messages upstream streams. +const nativeAnthropicToolStream = `event: message_start +data: {"type":"message_start","message":{"id":"msg_relay_native","type":"message","role":"assistant","model":"relay-model","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":21,"output_tokens":1}}} + +event: content_block_start +data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Checking: "}} + +event: content_block_stop +data: {"type":"content_block_stop","index":0} + +event: content_block_start +data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"toolu_native_01","name":"Bash","input":{}}} + +event: content_block_delta +data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"command\":\"echo hi\"}"}} + +event: content_block_stop +data: {"type":"content_block_stop","index":1} + +event: message_delta +data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":12}} + +event: message_stop +data: {"type":"message_stop"} + +` + +// writtenAnthropicToolStream is a Messages reply whose text holds a call +// written the way Claude's own calls look. The relay turns it into a +// tool_use block after the words before it. +const writtenAnthropicToolStream = `event: message_start +data: {"type":"message_start","message":{"id":"msg_relay_written","type":"message","role":"assistant","model":"relay-model","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":18,"output_tokens":1}}} + +event: content_block_start +data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"I'll check: echo hi"}} + +event: content_block_stop +data: {"type":"content_block_stop","index":0} + +event: message_delta +data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":9}} + +event: message_stop +data: {"type":"message_stop"} + +` + +// writtenAtStartAnthropicToolStream is writtenAnthropicToolStream with no +// words before the written call, so the text block's held start is replaced +// by the call's block. +const writtenAtStartAnthropicToolStream = `event: message_start +data: {"type":"message_start","message":{"id":"msg_relay_start","type":"message","role":"assistant","model":"relay-model","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":17,"output_tokens":1}}} + +event: content_block_start +data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"echo hi"}} + +event: content_block_stop +data: {"type":"content_block_stop","index":0} + +event: message_delta +data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":8}} + +event: message_stop +data: {"type":"message_stop"} + +` + +// heldTextAnthropicStream is a Messages reply whose text starts with a call +// of a tool the request didn't offer. The relay holds the whole text block, +// then has to release its held start and stop as text when the reply ends. +const heldTextAnthropicStream = `event: message_start +data: {"type":"message_start","message":{"id":"msg_relay_held","type":"message","role":"assistant","model":"relay-model","content":[],"stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":16,"output_tokens":1}}} + +event: content_block_start +data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}} + +event: content_block_delta +data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"y"}} + +event: content_block_stop +data: {"type":"content_block_stop","index":0} + +event: message_delta +data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":7}} + +event: message_stop +data: {"type":"message_stop"} + +` + +type anthropicSSEChunk struct { + Type string `json:"type"` + Index int `json:"index"` + ContentBlock struct { + Type string `json:"type"` + ID string `json:"id"` + Name string `json:"name"` + } `json:"content_block"` + Delta struct { + Type string `json:"type"` + Text string `json:"text"` + PartialJSON string `json:"partial_json"` + StopReason string `json:"stop_reason"` + } `json:"delta"` +} + +type anthropicSSEFrame struct { + event string + chunk anthropicSSEChunk +} + +// readAnthropicSSE reads a Messages stream strictly: every frame must name +// its event and carry exactly one data line whose JSON parses. A frame that +// lost its event header, or whose data lines were joined, fails here rather +// than being skipped by a lenient parser. +func readAnthropicSSE(t *testing.T, body string) []anthropicSSEFrame { + t.Helper() + // CRLF and LF both delimit SSE lines; the relay may pass an upstream's + // CRLF frames through while making its own with LF. + body = strings.ReplaceAll(body, "\r\n", "\n") + var out []anthropicSSEFrame + for _, frame := range strings.Split(body, "\n\n") { + if strings.TrimSpace(frame) == "" { + continue + } + var event string + var data []string + for _, line := range strings.Split(frame, "\n") { + switch { + case line == "": + case strings.HasPrefix(line, "event:"): + if event != "" { + t.Fatalf("SSE frame names two events:\n%s", frame) + } + event = strings.TrimSpace(strings.TrimPrefix(line, "event:")) + if event == "" { + t.Fatalf("SSE frame has an empty event name:\n%s", frame) + } + case strings.HasPrefix(line, "data:"): + data = append(data, strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " ")) + default: + t.Fatalf("SSE frame has a line that is neither event nor data: %q\n%s", line, frame) + } + } + if event == "" { + t.Fatalf("SSE frame reached the client without an event line:\n%s", frame) + } + if len(data) != 1 { + t.Fatalf("SSE frame %q has %d data lines, want one:\n%s", event, len(data), frame) + } + var chunk anthropicSSEChunk + if err := json.Unmarshal([]byte(data[0]), &chunk); err != nil { + t.Fatalf("SSE frame %q has unreadable data %q: %v", event, data[0], err) + } + out = append(out, anthropicSSEFrame{event: event, chunk: chunk}) + } + if len(out) == 0 { + t.Fatal("the reply carried no SSE events") + } + return out +} + +type wantAnthropicCall struct { + name string + id string // "" when the relay made the call and its id is its own + args string +} + +// checkAnthropicStream asserts what a Messages client sees: events whose +// names match their data, blocks opened and closed one at a time in index +// order, the text, calls and stop reason expected. +func checkAnthropicStream(t *testing.T, frames []anthropicSSEFrame, wantBlocks []string, wantText, wantStop string, wantCalls []wantAnthropicCall) { + t.Helper() + if frames[0].event != "message_start" { + t.Fatalf("the reply begins with %q, not message_start", frames[0].event) + } + open, next := -1, 0 + var blocks []string + var text strings.Builder + type toolBlock struct{ id, name, input string } + var tools []*toolBlock + ended := false + for i, f := range frames { + if f.event != f.chunk.Type { + t.Fatalf("frame %d says event %q but data type %q", i, f.event, f.chunk.Type) + } + switch f.event { + case "message_start": + if i != 0 { + t.Fatalf("message_start is frame %d", i) + } + case "content_block_start": + if open >= 0 { + t.Fatalf("block %d opened while block %d was open", f.chunk.Index, open) + } + if f.chunk.Index != next { + t.Fatalf("block %d opened, want %d", f.chunk.Index, next) + } + open, next = f.chunk.Index, next+1 + blocks = append(blocks, f.chunk.ContentBlock.Type) + if f.chunk.ContentBlock.Type == "tool_use" { + tools = append(tools, &toolBlock{id: f.chunk.ContentBlock.ID, name: f.chunk.ContentBlock.Name}) + } + case "content_block_delta": + if f.chunk.Index != open { + t.Fatalf("block %d got a delta while block %d was open", f.chunk.Index, open) + } + switch f.chunk.Delta.Type { + case "text_delta": + text.WriteString(f.chunk.Delta.Text) + case "input_json_delta": + if len(tools) == 0 || f.chunk.Index != next-1 { + t.Fatalf("input for block %d reached the client without its start", f.chunk.Index) + } + tools[len(tools)-1].input += f.chunk.Delta.PartialJSON + default: + t.Fatalf("block %d has an unexpected delta type %q", f.chunk.Index, f.chunk.Delta.Type) + } + case "content_block_stop": + if f.chunk.Index != open { + t.Fatalf("block %d stopped while block %d was open", f.chunk.Index, open) + } + open = -1 + case "message_delta": + if open >= 0 { + t.Fatalf("the reply ended while block %d was open", open) + } + if f.chunk.Delta.StopReason != wantStop { + t.Fatalf("the reply stopped for %q, want %q", f.chunk.Delta.StopReason, wantStop) + } + case "message_stop": + if open >= 0 { + t.Fatalf("the reply stopped while block %d was open", open) + } + ended = true + default: + t.Fatalf("unexpected event %q", f.event) + } + } + if open >= 0 { + t.Fatalf("the reply ended with block %d open", open) + } + if !ended { + t.Fatal("the reply carried no message_stop") + } + if got := strings.Join(blocks, ","); got != strings.Join(wantBlocks, ",") { + t.Fatalf("blocks %v, want %v", blocks, wantBlocks) + } + if text.String() != wantText { + t.Fatalf("text %q, want %q", text.String(), wantText) + } + if len(tools) != len(wantCalls) { + t.Fatalf("%d tool calls reached the client, want %d", len(tools), len(wantCalls)) + } + for i, want := range wantCalls { + got := tools[i] + if got.name != want.name || got.id == "" || want.id != "" && got.id != want.id { + t.Fatalf("call %d is id %q name %q, want id %q name %q", i, got.id, got.name, want.id, want.name) + } + var a, b any + if json.Unmarshal([]byte(got.input), &a) != nil || json.Unmarshal([]byte(want.args), &b) != nil || !jsonSame(a, b) { + t.Fatalf("call %d args %q, want %q", i, got.input, want.args) + } + } +} + +func jsonSame(a, b any) bool { + ab, _ := json.Marshal(a) + bb, _ := json.Marshal(b) + return string(ab) == string(bb) +} + +// chunkAnthropicSSE cuts a stream at the boundaries a provider's writes may +// land on: whole, one event, one line, one byte, and one CRLF line. +func chunkAnthropicSSE(stream, how string) []string { + if how == "crlf lines" { + stream = strings.ReplaceAll(stream, "\n", "\r\n") + } + sep := "\n" + switch how { + case "whole": + return []string{stream} + case "events": + sep = "\n\n" + case "bytes": + out := make([]string, 0, len(stream)) + for i := range len(stream) { + out = append(out, stream[i:i+1]) + } + return out + } + out := strings.SplitAfter(stream, sep) + if n := len(out); n > 0 && out[n-1] == "" { + out = out[:n-1] + } + return out +} + +// The relayed Messages reply is read from whole events, whatever write +// boundaries the upstream used: an event line, its data line and the blank +// line may each arrive alone. Every event reaches the client with its name +// and one parseable data value, blocks open and close in order, and the +// native tool_use stays the call it was. +func TestAnthropicTextCallsSSEChunksKeepFraming(t *testing.T) { + cases := []struct { + name string + stream string + blocks []string + text string + stop string + calls []wantAnthropicCall + }{ + { + name: "native text then tool use", stream: nativeAnthropicToolStream, + blocks: []string{"text", "tool_use"}, text: "Checking: ", stop: "tool_use", + calls: []wantAnthropicCall{{name: "Bash", id: "toolu_native_01", args: `{"command":"echo hi"}`}}, + }, + { + name: "written call after text", stream: writtenAnthropicToolStream, + blocks: []string{"text", "tool_use"}, text: "I'll check: ", stop: "tool_use", + calls: []wantAnthropicCall{{name: "Bash", args: `{"command":"echo hi"}`}}, + }, + { + name: "written call at the start", stream: writtenAtStartAnthropicToolStream, + blocks: []string{"tool_use"}, text: "", stop: "tool_use", + calls: []wantAnthropicCall{{name: "Bash", args: `{"command":"echo hi"}`}}, + }, + { + name: "held text released whole", stream: heldTextAnthropicStream, + blocks: []string{"text"}, text: `y`, stop: "end_turn", + }, + } + chunkings := []string{"whole", "events", "lines", "bytes", "crlf lines"} + for _, c := range cases { + for _, how := range chunkings { + t.Run(c.name+"/"+how, func(t *testing.T) { + tc := &anthropicTextCalls{names: map[string]bool{"Bash": true}, sse: true} + var out strings.Builder + for _, part := range chunkAnthropicSSE(c.stream, how) { + out.Write(tc.write([]byte(part))) + } + out.Write(tc.flush()) + checkAnthropicStream(t, readAnthropicSSE(t, out.String()), c.blocks, c.text, c.stop, c.calls) + }) + } + // two reads, cut at every byte: every place one line ends and + // the next begins among them, LF and CRLF + for _, crlf := range []bool{false, true} { + stream := c.stream + if crlf { + stream = strings.ReplaceAll(stream, "\n", "\r\n") + } + t.Run(fmt.Sprintf("%s/every cut crlf=%v", c.name, crlf), func(t *testing.T) { + for at := 1; at < len(stream); at++ { + tc := &anthropicTextCalls{names: map[string]bool{"Bash": true}, sse: true} + out := append(tc.write([]byte(stream[:at])), tc.write([]byte(stream[at:]))...) + out = append(out, tc.flush()...) + ok := t.Run(fmt.Sprintf("at %d", at), func(t *testing.T) { + checkAnthropicStream(t, readAnthropicSSE(t, string(out)), c.blocks, c.text, c.stop, c.calls) + }) + if !ok { + return // one cut's failure says it; the rest would say it again + } + } + }) + } + } +} + +// lineCuts is the stream in two reads, cut after each of its lines. +func lineCuts(stream string) [][]string { + var out [][]string + for at := 0; at < len(stream)-1; at++ { + if stream[at] == '\n' { + out = append(out, []string{stream[:at+1], stream[at+1:]}) + } + } + return out +} + +// sseChunkBody hands the relay the upstream's writes one at a time, so a +// test controls the read boundaries without a socket or a sleep. +type sseChunkBody struct { + chunks []string +} + +func (b *sseChunkBody) Read(p []byte) (int, error) { + if len(b.chunks) == 0 { + return 0, io.EOF + } + part := b.chunks[0] + b.chunks = b.chunks[1:] + if len(part) > len(p) { + b.chunks = append([]string{part[len(p):]}, b.chunks...) + part = part[:len(p)] + } + return copy(p, part), nil +} + +func (b *sseChunkBody) Close() error { return nil } + +// The same chunk boundaries through magpie's Messages relay: the reply the +// agent reads is the stream the upstream sent, with each event complete and +// one data value each, not an event whose header went in an earlier write or +// whose data values were joined. +func TestAnthropicMessagesSSEChunksKeepFraming(t *testing.T) { + setup(t, provider.Anthropic, &fake{t: t}) + var chunks []string + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Status: "200 OK", + Header: http.Header{"Content-Type": {"text/event-stream"}}, + Body: &sseChunkBody{chunks: append([]string(nil), chunks...)}, + Request: r, + }, nil + })} + const ask = `{"model":"fake/m1","max_tokens":256,"stream":true,` + + `"tools":[{"name":"Bash","description":"Run a shell command","input_schema":{"type":"object","properties":{"command":{"type":"string"}},"required":["command"]}}],` + + `"messages":[{"role":"user","content":"run echo hi"}]}` + cases := []struct { + name string + stream string + blocks []string + text string + stop string + calls []wantAnthropicCall + }{ + { + name: "native text then tool use", stream: nativeAnthropicToolStream, + blocks: []string{"text", "tool_use"}, text: "Checking: ", stop: "tool_use", + calls: []wantAnthropicCall{{name: "Bash", id: "toolu_native_01", args: `{"command":"echo hi"}`}}, + }, + { + name: "written call after text", stream: writtenAnthropicToolStream, + blocks: []string{"text", "tool_use"}, text: "I'll check: ", stop: "tool_use", + calls: []wantAnthropicCall{{name: "Bash", args: `{"command":"echo hi"}`}}, + }, + { + name: "written call at the start", stream: writtenAtStartAnthropicToolStream, + blocks: []string{"tool_use"}, text: "", stop: "tool_use", + calls: []wantAnthropicCall{{name: "Bash", args: `{"command":"echo hi"}`}}, + }, + { + name: "held text released whole", stream: heldTextAnthropicStream, + blocks: []string{"text"}, text: `y`, stop: "end_turn", + }, + } + for _, c := range cases { + for _, how := range []string{"whole", "events", "lines", "bytes", "crlf lines"} { + t.Run(c.name+"/"+how, func(t *testing.T) { + chunks = chunkAnthropicSSE(c.stream, how) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(ask)) + req.Header.Set("anthropic-version", "2023-06-01") + req.Header.Set("User-Agent", "claude-cli/2.1.316 (external, cli)") + s.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + checkAnthropicStream(t, readAnthropicSSE(t, rec.Body.String()), c.blocks, c.text, c.stop, c.calls) + }) + } + t.Run(c.name+"/each line cut", func(t *testing.T) { + for i, cut := range lineCuts(c.stream) { + chunks = cut + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(ask)) + req.Header.Set("anthropic-version", "2023-06-01") + req.Header.Set("User-Agent", "claude-cli/2.1.316 (external, cli)") + s.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("cut %d: %d %s", i, rec.Code, rec.Body) + } + if !t.Run(fmt.Sprintf("cut %d", i), func(t *testing.T) { + checkAnthropicStream(t, readAnthropicSSE(t, rec.Body.String()), c.blocks, c.text, c.stop, c.calls) + }) { + return + } + } + }) + } + // a request that offers no tools: nothing reads the reply for calls, + // and it reaches the client as the upstream cut it, whole events each + const plain = `{"model":"fake/m1","max_tokens":256,"stream":true,"messages":[{"role":"user","content":"run echo hi"}]}` + for _, how := range []string{"lines", "bytes", "crlf lines"} { + t.Run("no tools/"+how, func(t *testing.T) { + chunks = chunkAnthropicSSE(nativeAnthropicToolStream, how) + rec := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/v1/messages?beta=true", strings.NewReader(plain)) + req.Header.Set("anthropic-version", "2023-06-01") + req.Header.Set("User-Agent", "claude-cli/2.1.316 (external, cli)") + s.Handler().ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + checkAnthropicStream(t, readAnthropicSSE(t, rec.Body.String()), []string{"text", "tool_use"}, "Checking: ", "tool_use", + []wantAnthropicCall{{name: "Bash", id: "toolu_native_01", args: `{"command":"echo hi"}`}}) + }) + } +}