gateway: a Claude subscription's reply goes on when Anthropic's stream is cut short and Claude Code asks again, instead of ending in an empty end_turn (#726, EZN7L2C3 on Claude Code 2.1.288 at effort max: a 601 s turn ended with only 74,427 chars of thinking, output_tokens 5, end_turn, and Claude Code appended "Your previous response had no visible output"; the next turns each wrote ~467k tokens to the cache again, five of them 2.2M, and the 5h window went from 84% to 0) — when Anthropic's stream drops or stalls, Claude Code 2.1.28x closes the open block and writes its own message_stop with no message_delta before it, emits a system api_retry and asks again, streamed (a new message_start); cut short again, it asks once more without a stream and tells that answer only as assistant envelopes, one per content block, each carrying the whole message's id, model, stop_reason and usage (checked against a fake Anthropic API under a sandbox HOME, with the bridge's own flags: one cut, two cuts, two cuts then tool_use blocks, every stream cut). readOutput took that message_stop for the reply's end: relay ended with no stop, which anthropicEncoder.finish writes as end_turn, with the usage message_start had told (output 5, cache write 467,708), and ended() aborts a run whose stop isn't "stop", killing Claude Code's retry and the run kept for the next turn, so the next turn started a new run with the whole conversation in one message, written to the cache again (the 38,623 read at 05:10 is Claude Code's own prefix). Now a message_stop with no message_delta before it marks the attempt cut short and ends nothing: the next message_start goes on in the same reply, its usage added to the attempt's as after Claude Code's own tool call, and an assistant envelope under an id other than the streamed message's (not Claude Code's <synthetic> error message) is that unstreamed answer: its thinking (with signature), text and tool calls are passed on, client calls handed over as from a stream, and the reply ends with its stop on the next line of anything else, the result, or once nothing has come for unstreamedQuiet (300 ms), as Claude Code writes all the blocks at once and then calls the client's tools and waits. A cut short after words or a client call were shown fails the reply (502, "Claude Code's stream from Anthropic was cut short after the reply had begun") rather than repeating the answer after half of it; one with nothing to go on in (the output or the turn ends) fails too, never a false end_turn. readOutput's loop body moved into a closure run under a mutex, which the quiet timer takes as well; toolStart, text, begin, end and failed are shared by the stream and the unstreamed paths. Output accounting itself was right: message_delta's output_tokens reach the client (TestClaudeStreamOutputCounted, which passes on the old code too); the 5 was the cut attempt's message_start count. TestClaudeCutStreamGoesOnInRetry (answer, end_turn, output 12005, run kept), TestClaudeCutStreamAnsweredUnstreamed, TestClaudeCutStreamUnstreamedToolCalls, TestClaudeCutStreamWithNoAnswer and TestClaudeCutStreamAfterWords fail on the old code and pass; the real Claude Code 2.1.289 output captured against the fake API (retry, unstreamed answer, unstreamed tool calls, every stream cut) gives the answer, its stop and a kept run through readOutput and relay. go vet, builds (darwin, GOOS=linux, GOOS=windows), go test -race on the gateway's Claude tests and go test -tags nogui -count=1 ./... under a temp HOME pass. Not tried with the reporter's account or a real Anthropic cut. What this doesn't change: a hot switch to another account starts a new run, and Anthropic's cache is per organisation, so the whole conversation is written once on the new account; sonnet and opus caches are separate too, and the sonnet served at 04:56 came from inside Claude Code (its own fallbacks; magpie passes no --fallback-model and maps no opus to sonnet). PR #626 (one work dir, the caller's system prompt cached on its own) would help a new run read more of its prefix; it isn't part of this.
This commit is contained in:
@@ -0,0 +1,217 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// cutStart is the start of the reporter's first attempt (#726): the whole
|
||||
// conversation written to the cache, 5 tokens out so far.
|
||||
const cutStart = `{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_cut","model":"claude-opus-5-5","usage":{"input_tokens":2,"cache_creation_input_tokens":467708,"cache_read_input_tokens":0,"output_tokens":5}}}}`
|
||||
|
||||
// cutAttempt is an attempt Anthropic's stream cut short in its thinking,
|
||||
// as Claude Code 2.1.28x tells it: its own content_block_stop and
|
||||
// message_stop, no message_delta, then an api_retry.
|
||||
var cutAttempt = []string{
|
||||
cutStart,
|
||||
`{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"thinking so far. "}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`,
|
||||
`{"type":"stream_event","event":{"type":"message_stop"}}`,
|
||||
`{"type":"assistant","message":{"id":"msg_cut","model":"claude-opus-5-5","role":"assistant","content":[{"type":"thinking","thinking":"thinking so far. ","signature":""}],"stop_reason":null,"usage":{"input_tokens":2,"cache_creation_input_tokens":467708,"cache_read_input_tokens":0,"output_tokens":5}}}`,
|
||||
`{"type":"system","subtype":"api_retry","attempt":1,"max_retries":10,"retry_delay_ms":500,"error_status":null,"error":"unknown"}`,
|
||||
}
|
||||
|
||||
// claudeReply runs lines through readOutput and relay as an Anthropic
|
||||
// Messages stream, and says what the client was told and how the run was
|
||||
// left.
|
||||
func claudeReply(t *testing.T, run *subscriptionRun, lines []string, hold bool) (text, stop string, out, write int, raw string, ended string, ok bool) {
|
||||
t.Helper()
|
||||
segment := run.attach()
|
||||
pr, pw := io.Pipe()
|
||||
go run.readOutput(pr)
|
||||
go func() {
|
||||
for _, l := range lines {
|
||||
pw.Write([]byte(l + "\n"))
|
||||
}
|
||||
if !hold { // Claude Code waits on its next input, its output open
|
||||
pw.Close()
|
||||
}
|
||||
}()
|
||||
t.Cleanup(func() { pw.Close() })
|
||||
rec := httptest.NewRecorder()
|
||||
req := &Request{Model: "claude-opus-5-5", Stream: true}
|
||||
var usage Usage
|
||||
relay(rec, httptest.NewRequest("POST", "/v1/messages", nil), provider.Anthropic, "Claude Code", req, segment, &usage,
|
||||
func() {}, func(said, s string, k bool) { ended, ok = s, k })
|
||||
raw = rec.Body.String()
|
||||
var tools []string
|
||||
for _, l := range strings.Split(raw, "\n") {
|
||||
data, found := strings.CutPrefix(l, "data: ")
|
||||
if !found {
|
||||
continue
|
||||
}
|
||||
var ev struct {
|
||||
Type string `json:"type"`
|
||||
ContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
} `json:"content_block"`
|
||||
Delta struct {
|
||||
Text string `json:"text"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
} `json:"delta"`
|
||||
Usage struct {
|
||||
Output int `json:"output_tokens"`
|
||||
CacheWrite int `json:"cache_creation_input_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if json.Unmarshal([]byte(data), &ev) != nil {
|
||||
continue
|
||||
}
|
||||
switch ev.Type {
|
||||
case "content_block_start":
|
||||
if ev.ContentBlock.Type == "tool_use" {
|
||||
tools = append(tools, ev.ContentBlock.Name)
|
||||
}
|
||||
case "content_block_delta":
|
||||
text += ev.Delta.Text
|
||||
case "message_delta":
|
||||
stop, out, write = ev.Delta.StopReason, ev.Usage.Output, ev.Usage.CacheWrite
|
||||
}
|
||||
}
|
||||
if len(tools) > 0 {
|
||||
text += "[" + strings.Join(tools, ",") + "]"
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Anthropic's stream is cut short and Claude Code asks again, streamed: the
|
||||
// client hears the answer of the attempt that gave one, with its usage and
|
||||
// stop, and the run is kept for the next turn (#726). The old code took
|
||||
// Claude Code's own message_stop for the reply's end: end_turn, 5 tokens
|
||||
// out, no answer, and the run ended.
|
||||
func TestClaudeCutStreamGoesOnInRetry(t *testing.T) {
|
||||
lines := append(append([]string{}, cutAttempt...),
|
||||
`{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg_retry","model":"claude-opus-5-5","usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":467708,"output_tokens":5}}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"the answer"}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`,
|
||||
`{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":12000}}}`,
|
||||
`{"type":"stream_event","event":{"type":"message_stop"}}`,
|
||||
`{"type":"result","subtype":"success","is_error":false,"result":"the answer"}`,
|
||||
)
|
||||
text, stop, out, write, raw, ended, ok := claudeReply(t, &subscriptionRun{}, lines, true)
|
||||
if text != "the answer" || stop != "end_turn" || ended != "stop" || !ok {
|
||||
t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw)
|
||||
}
|
||||
// both attempts were made, and are counted
|
||||
if out != 12005 || write != 467708 {
|
||||
t.Fatalf("usage: %d out, %d written:\n%s", out, write, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// Cut short twice, Claude Code asks without a stream and tells the answer
|
||||
// in whole messages only: the client hears it.
|
||||
func TestClaudeCutStreamAnsweredUnstreamed(t *testing.T) {
|
||||
lines := append(append(append([]string{}, cutAttempt...), cutAttempt...),
|
||||
`{"type":"assistant","message":{"id":"msg_whole","model":"claude-opus-5-5","role":"assistant","content":[{"type":"thinking","thinking":"NS thinking","signature":"sig"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"cache_read_input_tokens":467708,"output_tokens":777}}}`,
|
||||
`{"type":"assistant","message":{"id":"msg_whole","model":"claude-opus-5-5","role":"assistant","content":[{"type":"text","text":"NONSTREAM ANSWER"}],"stop_reason":"end_turn","usage":{"input_tokens":2,"cache_read_input_tokens":467708,"output_tokens":777}}}`,
|
||||
`{"type":"result","subtype":"success","is_error":false,"result":"NONSTREAM ANSWER"}`,
|
||||
)
|
||||
text, stop, out, _, raw, ended, ok := claudeReply(t, &subscriptionRun{}, lines, true)
|
||||
if text != "NONSTREAM ANSWER" || stop != "end_turn" || ended != "stop" || !ok {
|
||||
t.Fatalf("reply %q stop %q, run ended %q %v:\n%s", text, stop, ended, ok, raw)
|
||||
}
|
||||
if out != 787 {
|
||||
t.Fatalf("usage: %d out:\n%s", out, raw)
|
||||
}
|
||||
if !strings.Contains(raw, "NS thinking") {
|
||||
t.Fatalf("thinking lost:\n%s", raw)
|
||||
}
|
||||
}
|
||||
|
||||
// An unstreamed answer calling the client's tools: Claude Code then calls
|
||||
// them and waits, writing nothing more, so the reply ends once its blocks
|
||||
// stop coming.
|
||||
func TestClaudeCutStreamUnstreamedToolCalls(t *testing.T) {
|
||||
was := unstreamedQuiet
|
||||
unstreamedQuiet = 50 * time.Millisecond
|
||||
t.Cleanup(func() { unstreamedQuiet = was })
|
||||
lines := append(append(append([]string{}, cutAttempt...), cutAttempt...),
|
||||
`{"type":"assistant","message":{"id":"msg_whole","model":"claude-opus-5-5","content":[{"type":"text","text":"calling"}],"stop_reason":"tool_use","usage":{"output_tokens":777}}}`,
|
||||
`{"type":"assistant","message":{"id":"msg_whole","model":"claude-opus-5-5","content":[{"type":"tool_use","id":"toolu_a","name":"mcp__magpie__Read","input":{"p":1}}],"stop_reason":"tool_use","usage":{"output_tokens":777}}}`,
|
||||
`{"type":"assistant","message":{"id":"msg_whole","model":"claude-opus-5-5","content":[{"type":"tool_use","id":"toolu_b","name":"mcp__magpie__Read","input":{"p":2}}],"stop_reason":"tool_use","usage":{"output_tokens":777}}}`,
|
||||
)
|
||||
run := &subscriptionRun{}
|
||||
text, stop, _, _, raw, ended, _ := claudeReply(t, run, lines, true)
|
||||
if text != "calling[Read,Read]" || stop != "tool_use" || ended != "tool" {
|
||||
t.Fatalf("reply %q stop %q, run ended %q:\n%s", text, stop, ended, raw)
|
||||
}
|
||||
if !strings.Contains(raw, `"partial_json":"{\"p\":2}"`) {
|
||||
t.Fatalf("arguments lost:\n%s", raw)
|
||||
}
|
||||
if len(run.asked) != 2 {
|
||||
t.Fatalf("asked: %v", run.asked)
|
||||
}
|
||||
}
|
||||
|
||||
// Cut short with nothing to go on in — Claude Code's output ends, or its
|
||||
// turn ends without an answer — the client is told of an error, not an
|
||||
// empty end_turn.
|
||||
func TestClaudeCutStreamWithNoAnswer(t *testing.T) {
|
||||
for name, lines := range map[string][]string{
|
||||
"output ends": cutAttempt,
|
||||
"turn ends": append(append([]string{}, cutAttempt...), `{"type":"result","subtype":"success","is_error":false,"result":""}`),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
_, stop, _, _, raw, _, ok := claudeReply(t, &subscriptionRun{}, lines, name == "turn ends")
|
||||
if stop == "end_turn" || ok || !strings.Contains(raw, "cut short") {
|
||||
t.Fatalf("stop %q, ok %v:\n%s", stop, ok, raw)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A stream cut short after words were shown can't go on in the next
|
||||
// attempt, which writes its answer again: the reply fails instead, for the
|
||||
// client to ask again.
|
||||
func TestClaudeCutStreamAfterWords(t *testing.T) {
|
||||
lines := []string{
|
||||
cutStart,
|
||||
`{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"half an ans"}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_stop","index":0}}`,
|
||||
`{"type":"stream_event","event":{"type":"message_stop"}}`,
|
||||
}
|
||||
_, stop, _, _, raw, _, ok := claudeReply(t, &subscriptionRun{}, lines, true)
|
||||
if stop == "end_turn" || ok || !strings.Contains(raw, "cut short") {
|
||||
t.Fatalf("stop %q, ok %v:\n%s", stop, ok, raw)
|
||||
}
|
||||
}
|
||||
|
||||
// A whole stream's output count is its message_delta's, which the client
|
||||
// is told: no usage is lost on the way (#726's first question).
|
||||
func TestClaudeStreamOutputCounted(t *testing.T) {
|
||||
lines := []string{
|
||||
cutStart,
|
||||
`{"type":"stream_event","event":{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"hmm"}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"sig"}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}}`,
|
||||
`{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"hello"}}}`,
|
||||
`{"type":"stream_event","event":{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":12000}}}`,
|
||||
`{"type":"stream_event","event":{"type":"message_stop"}}`,
|
||||
`{"type":"assistant","message":{"id":"msg_cut","model":"claude-opus-5-5","content":[{"type":"text","text":"hello"}],"stop_reason":"end_turn","usage":{"output_tokens":12000}}}`,
|
||||
}
|
||||
text, stop, out, write, raw, ended, ok := claudeReply(t, &subscriptionRun{}, lines, true)
|
||||
if text != "hello" || stop != "end_turn" || out != 12000 || write != 467708 || ended != "stop" || !ok {
|
||||
t.Fatalf("reply %q stop %q out %d write %d ended %q %v:\n%s", text, stop, out, write, ended, ok, raw)
|
||||
}
|
||||
}
|
||||
@@ -786,7 +786,102 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
this.add(v)
|
||||
return v.plus(before, true)
|
||||
}
|
||||
for s.Scan() {
|
||||
// A stream Anthropic cut short (a dropped connection, a stall) Claude
|
||||
// Code ends with a message_stop of its own and no message_delta, and
|
||||
// asks again: streamed, then once more without a stream, whose answer
|
||||
// it tells only in whole messages, a block each (#726). That
|
||||
// message_stop ends nothing: the reply goes on in the attempt that
|
||||
// answers. Taken for the reply's end, it told the client end_turn with
|
||||
// the first attempt's usage (5 tokens out, the thinking so far, no
|
||||
// answer) and ended the run, its next turn writing the whole
|
||||
// conversation to the cache again.
|
||||
stopped := false // this message's message_delta said why it stopped
|
||||
cut := false // an attempt was cut short, and Claude Code asks again
|
||||
shown := false // this message has shown the client words or a call
|
||||
streamed := "" // the message whose stream the events are
|
||||
// a message told in whole messages: its id, its stop, and its blocks
|
||||
// so far; it is whole when anything else comes, or nothing does for
|
||||
// unstreamedQuiet, as when Claude Code goes on to call the client's
|
||||
// tools and waits on them
|
||||
unstreamed, unstreamedStop, blocks := "", "", 0
|
||||
var pmu sync.Mutex // held for each line, and by quiet's settle
|
||||
var quiet *time.Timer
|
||||
// what each message's end does, once its stop is known
|
||||
end := func(why string) {
|
||||
if goesOn := why != "" && r.schema && !theirs || why == "tool_use" && len(own) > 0 && !theirs; goesOn {
|
||||
inside = true // the answer is the next message's, or the result's
|
||||
} else if why != "" {
|
||||
r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(why)})
|
||||
}
|
||||
}
|
||||
settle := func() { // pmu held
|
||||
if quiet != nil {
|
||||
quiet.Stop()
|
||||
}
|
||||
if unstreamed == "" {
|
||||
return
|
||||
}
|
||||
unstreamed = ""
|
||||
end(unstreamedStop)
|
||||
if !inside {
|
||||
r.endSegment()
|
||||
}
|
||||
}
|
||||
// toolStart says whether a tool_use block, index of this message, is a
|
||||
// call of the client's, to be handed over as name: Claude Code's own
|
||||
// calls (WebSearch, magpie's web search, a schema's StructuredOutput)
|
||||
// are its own to answer
|
||||
toolStart := func(index int, name string) (string, bool) {
|
||||
if r.schema && name == "StructuredOutput" {
|
||||
own[index] = true
|
||||
return "", false
|
||||
}
|
||||
name, ok := strings.CutPrefix(name, "mcp__magpie__")
|
||||
r.mu.Lock()
|
||||
search := r.search != nil && name == r.searchName
|
||||
r.mu.Unlock()
|
||||
// magpie answers its own web search, as Claude Code does
|
||||
// its WebSearch
|
||||
if !ok || search {
|
||||
own[index] = true
|
||||
return "", false
|
||||
}
|
||||
theirs, shown = true, true
|
||||
r.mu.Lock()
|
||||
r.asked = append(r.asked, name)
|
||||
r.mu.Unlock()
|
||||
return name, true
|
||||
}
|
||||
text := func(s string) {
|
||||
if s != "" && !r.schema {
|
||||
shown = true
|
||||
r.emit(Event{Kind: KText, Text: s})
|
||||
}
|
||||
}
|
||||
// begin starts a message: the reply's first, or one it goes on in,
|
||||
// after Claude Code's own call or an attempt cut short
|
||||
begin := func(id, model string, u cliUsage) {
|
||||
own, theirs, stopped, shown = map[int]bool{}, false, false, false
|
||||
if inside || cut {
|
||||
inside, cut = false, false
|
||||
before, this = before.plus(this, false), Usage{}
|
||||
r.emit(Event{Kind: KUsage, Usage: usage(u)})
|
||||
return
|
||||
}
|
||||
before, this = Usage{}, Usage{}
|
||||
r.mu.Lock()
|
||||
r.asked = nil
|
||||
r.mu.Unlock()
|
||||
r.emit(Event{Kind: KStart, MsgID: id, Model: model, Usage: usage(u)})
|
||||
}
|
||||
// failed ends the reply with an error where it was cut short with
|
||||
// nothing to go on in
|
||||
failed := func(why string) {
|
||||
cut = false
|
||||
r.emit(Event{Kind: KError, Text: "Claude Code's stream from Anthropic was cut short " + why, Status: http.StatusBadGateway, RequestID: reqID})
|
||||
r.endSegment()
|
||||
}
|
||||
line := func(b []byte) {
|
||||
var envelope struct {
|
||||
Type string `json:"type"`
|
||||
Subtype string `json:"subtype"`
|
||||
@@ -807,7 +902,10 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
ToolUseResult json.RawMessage `json:"tool_use_result"`
|
||||
// what the account has left, as Anthropic told Claude Code
|
||||
RateLimitInfo json.RawMessage `json:"rate_limit_info"`
|
||||
Event struct {
|
||||
// an assistant message, one of its blocks at a time; raw, as
|
||||
// a user message's content may be a string
|
||||
Message json.RawMessage `json:"message"`
|
||||
Event struct {
|
||||
Type string `json:"type"`
|
||||
Index int `json:"index"`
|
||||
Message struct {
|
||||
@@ -832,8 +930,34 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
Usage cliUsage `json:"usage"`
|
||||
} `json:"event"`
|
||||
}
|
||||
if json.Unmarshal(s.Bytes(), &envelope) != nil {
|
||||
continue
|
||||
if json.Unmarshal(b, &envelope) != nil {
|
||||
return
|
||||
}
|
||||
var whole struct {
|
||||
ID string `json:"id"`
|
||||
Model string `json:"model"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage cliUsage `json:"usage"`
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
} `json:"content"`
|
||||
}
|
||||
if envelope.Type == "assistant" {
|
||||
_ = json.Unmarshal(envelope.Message, &whole)
|
||||
}
|
||||
// a message not streamed is told by its id: a streamed one's
|
||||
// whole messages come after its stream's events, under its id;
|
||||
// Claude Code's own (an error it tells as a message) is
|
||||
// <synthetic>
|
||||
next := envelope.Type == "assistant" && whole.ID != "" && whole.ID != streamed && whole.Model != "<synthetic>"
|
||||
if unstreamed != "" && !(next && whole.ID == unstreamed) {
|
||||
settle()
|
||||
}
|
||||
if envelope.Type == "rate_limit_event" {
|
||||
// a run in Claude Code's own home is on whatever account
|
||||
@@ -842,7 +966,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
if user, own := ownerAccount(r.owner); user != "" && !(own && provider.ClaudeCodeMovedOff(user)) {
|
||||
provider.NoteClaudeLimits(user, claudeLimits(envelope.RateLimitInfo))
|
||||
}
|
||||
continue
|
||||
return
|
||||
}
|
||||
if envelope.Type == "result" {
|
||||
// a turn that failed — out of quota, rate limited — ends with
|
||||
@@ -852,6 +976,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
inside = false
|
||||
switch {
|
||||
case envelope.IsError:
|
||||
cut = false
|
||||
text := envelope.Result
|
||||
if text == "" && waiting {
|
||||
text = "Claude Code gave no answer fitting the schema (" + envelope.Subtype + ")"
|
||||
@@ -869,6 +994,8 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
}
|
||||
r.emit(Event{Kind: KError, Text: text, Status: envelope.APIErrorStatus, Code: errKind, RequestID: reqID})
|
||||
r.endSegment()
|
||||
case cut:
|
||||
failed("and Claude Code ended the turn without asking again")
|
||||
case waiting && len(envelope.StructuredOutput) > 0 && string(envelope.StructuredOutput) != "null":
|
||||
r.emit(Event{Kind: KText, Text: string(envelope.StructuredOutput)})
|
||||
r.emit(Event{Kind: KStop, Stop: "stop"})
|
||||
@@ -877,18 +1004,60 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
r.emit(Event{Kind: KError, Text: "Claude Code ended the turn with no answer fitting the schema", RequestID: reqID})
|
||||
r.endSegment()
|
||||
}
|
||||
continue
|
||||
return
|
||||
}
|
||||
if envelope.Type == "assistant" {
|
||||
// the whole message, whose id its stream's later events go
|
||||
// out under; a failure says how it failed here, before its result
|
||||
// a failure says how it failed here, before its result
|
||||
if envelope.RequestID != "" {
|
||||
reqID = envelope.RequestID
|
||||
}
|
||||
var kind string
|
||||
_ = json.Unmarshal(envelope.ErrorKind, &kind)
|
||||
errKind = kind
|
||||
continue
|
||||
if !next {
|
||||
return
|
||||
}
|
||||
// asked again without a stream, after attempts cut short:
|
||||
// the answer is told here only
|
||||
if whole.ID != unstreamed {
|
||||
begin(whole.ID, whole.Model, whole.Usage)
|
||||
unstreamed, blocks = whole.ID, 0
|
||||
}
|
||||
unstreamedStop = whole.StopReason
|
||||
for _, c := range whole.Content {
|
||||
index := blocks
|
||||
blocks++
|
||||
switch c.Type {
|
||||
case "thinking":
|
||||
if c.Thinking != "" {
|
||||
r.emit(Event{Kind: KThink, Text: c.Thinking})
|
||||
}
|
||||
if c.Signature != "" {
|
||||
r.emit(Event{Kind: KSig, Text: c.Signature})
|
||||
}
|
||||
case "text":
|
||||
text(c.Text)
|
||||
case "tool_use":
|
||||
name, theirs := toolStart(index, c.Name)
|
||||
if !theirs {
|
||||
continue
|
||||
}
|
||||
r.emit(Event{Kind: KToolStart, ID: c.ID, Name: name})
|
||||
if len(c.Input) > 0 {
|
||||
r.emit(Event{Kind: KToolArgs, Text: string(c.Input)})
|
||||
}
|
||||
}
|
||||
}
|
||||
r.emit(Event{Kind: KUsage, Usage: usage(whole.Usage), RequestID: reqID})
|
||||
if quiet != nil {
|
||||
quiet.Stop()
|
||||
}
|
||||
quiet = time.AfterFunc(unstreamedQuiet, func() {
|
||||
pmu.Lock()
|
||||
defer pmu.Unlock()
|
||||
settle()
|
||||
})
|
||||
return
|
||||
}
|
||||
var searched struct {
|
||||
Query string `json:"query"`
|
||||
@@ -905,59 +1074,29 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
}
|
||||
}
|
||||
r.emit(Event{Kind: KSearch, Text: searched.Query, Hits: hits})
|
||||
continue
|
||||
return
|
||||
}
|
||||
if envelope.Type != "stream_event" {
|
||||
continue
|
||||
return
|
||||
}
|
||||
e := envelope.Event
|
||||
switch e.Type {
|
||||
case "message_start":
|
||||
own, theirs = map[int]bool{}, false
|
||||
if inside {
|
||||
inside = false
|
||||
before, this = before.plus(this, false), Usage{}
|
||||
r.emit(Event{Kind: KUsage, Usage: usage(e.Message.Usage)})
|
||||
continue
|
||||
}
|
||||
before, this = Usage{}, Usage{}
|
||||
r.mu.Lock()
|
||||
r.asked = nil
|
||||
r.mu.Unlock()
|
||||
r.emit(Event{Kind: KStart, MsgID: e.Message.ID, Model: e.Message.Model, Usage: usage(e.Message.Usage)})
|
||||
streamed = e.Message.ID
|
||||
begin(e.Message.ID, e.Message.Model, e.Message.Usage)
|
||||
case "content_block_start":
|
||||
switch e.ContentBlock.Type {
|
||||
case "tool_use":
|
||||
if r.schema && e.ContentBlock.Name == "StructuredOutput" {
|
||||
own[e.Index] = true
|
||||
continue
|
||||
if name, theirs := toolStart(e.Index, e.ContentBlock.Name); theirs {
|
||||
r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name})
|
||||
}
|
||||
name, ok := strings.CutPrefix(e.ContentBlock.Name, "mcp__magpie__")
|
||||
r.mu.Lock()
|
||||
search := r.search != nil && name == r.searchName
|
||||
r.mu.Unlock()
|
||||
// magpie answers its own web search, as Claude Code does
|
||||
// its WebSearch
|
||||
if !ok || search {
|
||||
own[e.Index] = true
|
||||
continue
|
||||
}
|
||||
theirs = true
|
||||
r.mu.Lock()
|
||||
r.asked = append(r.asked, name)
|
||||
r.mu.Unlock()
|
||||
r.emit(Event{Kind: KToolStart, ID: e.ContentBlock.ID, Name: name})
|
||||
case "text":
|
||||
if e.ContentBlock.Text != "" && !r.schema {
|
||||
r.emit(Event{Kind: KText, Text: e.ContentBlock.Text})
|
||||
}
|
||||
text(e.ContentBlock.Text)
|
||||
}
|
||||
case "content_block_delta":
|
||||
switch e.Delta.Type {
|
||||
case "text_delta":
|
||||
if !r.schema {
|
||||
r.emit(Event{Kind: KText, Text: e.Delta.Text})
|
||||
}
|
||||
text(e.Delta.Text)
|
||||
case "thinking_delta":
|
||||
r.emit(Event{Kind: KThink, Text: e.Delta.Thinking})
|
||||
case "signature_delta":
|
||||
@@ -969,24 +1108,45 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
|
||||
}
|
||||
case "message_delta":
|
||||
r.emit(Event{Kind: KUsage, Usage: usage(e.Usage), RequestID: reqID})
|
||||
if e.Delta.StopReason != "" && r.schema && !theirs {
|
||||
inside = true // the answer is the result's
|
||||
} else if e.Delta.StopReason == "tool_use" && len(own) > 0 && !theirs {
|
||||
inside = true
|
||||
} else if e.Delta.StopReason != "" {
|
||||
r.emit(Event{Kind: KStop, Stop: stopFromAnthropic(e.Delta.StopReason)})
|
||||
if e.Delta.StopReason != "" {
|
||||
stopped = true
|
||||
}
|
||||
end(e.Delta.StopReason)
|
||||
case "message_stop":
|
||||
if !inside {
|
||||
switch {
|
||||
case inside:
|
||||
case !stopped && shown:
|
||||
// what the client was shown can't be taken back, nor
|
||||
// the attempt's answer added to it: Claude Code's own
|
||||
// request is the client's to make again
|
||||
failed("after the reply had begun")
|
||||
case !stopped:
|
||||
cut = true
|
||||
default:
|
||||
r.endSegment()
|
||||
}
|
||||
}
|
||||
}
|
||||
for s.Scan() {
|
||||
pmu.Lock()
|
||||
line(s.Bytes())
|
||||
pmu.Unlock()
|
||||
}
|
||||
pmu.Lock()
|
||||
defer pmu.Unlock()
|
||||
settle()
|
||||
if err := s.Err(); err != nil {
|
||||
r.emit(Event{Kind: KError, Text: err.Error()})
|
||||
} else if cut {
|
||||
failed("and Claude Code stopped")
|
||||
}
|
||||
}
|
||||
|
||||
// unstreamedQuiet is how long a message told in whole messages is taken
|
||||
// as whole once none of its blocks come: Claude Code writes them all at
|
||||
// once.
|
||||
var unstreamedQuiet = 300 * time.Millisecond
|
||||
|
||||
type cliUsage struct {
|
||||
Input int `json:"input_tokens"`
|
||||
Output int `json:"output_tokens"`
|
||||
|
||||
Reference in New Issue
Block a user