Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

fix(cli): align stream error handling after output-mode merge

wizardchen1109e85a5752
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index e14c06316..32467e0a6 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -89,10 +89,10 @@ text` renders the same projection live.
```
{"type":"init","session_id":"...","kb_id":"...","profile":"...","agent_id":"..."}
-{"type":"thinking","content":"..."}
-{"type":"answer","content":"Hello"}
-{"type":"tool_call","name":"...","input":{}}
-{"type":"complete","done":true}
+{"response_type":"thinking","content":"..."}
+{"response_type":"answer","content":"Hello"}
+{"response_type":"tool_call","tool_calls":[...]}
+{"response_type":"complete","done":true}
```
MCP `chat` / `session_ask` return the same `events` shape and accept
@@ -223,7 +223,7 @@ Key packages:
- `internal/iostreams/` — global IO singleton + TTY detection + `SetForTest` swap
- `internal/secrets/` — `Store` interface; `KeyringStore` primary, `FileStore` 0600 fallback, `MemStore` for tests
- `internal/prompt/` — `TTYPrompter` (password no-echo) + `AgentPrompter` (non-TTY no-prompt sentinel)
-- `internal/sse/` — `Accumulator` for chat / session ask SSE streams
+- `internal/sse/` — `Projector` for chat / session ask bounded output; `Accumulator` remains for legacy/tests
- `internal/mcp/` — curated 10-tool stdio MCP server (wired by `cmd/mcp/serve.go`); see [MCP tool surface](#mcp-tool-surface) for the curation rationale and inventory
- `client/` (parent module) — generated SDK
diff --git a/cli/CHANGELOG.md b/cli/CHANGELOG.md
index a47ab017c..997346053 100644
--- a/cli/CHANGELOG.md
+++ b/cli/CHANGELOG.md
@@ -45,6 +45,9 @@ CLI history before v0.3 is recorded in the project root
per-event `done:true` markers as completion of the whole run.
- Reference `knowledge_base_id`, `parent_chunk_id`, and `sub_chunk_id` fields
now survive SDK unmarshal.
+- E2E chat step parses the bounded JSON envelope; MCP stream errors include
+ `session_id` in `error.detail`; terminal SSE errors classify as
+ `server.error` instead of `network.error` or `local.sse_stream_aborted`.
## [0.9.0] - 2026-06-10
diff --git a/cli/acceptance/e2e/e2e_test.go b/cli/acceptance/e2e/e2e_test.go
index 5fe0dbbf1..069c75a33 100644
--- a/cli/acceptance/e2e/e2e_test.go
+++ b/cli/acceptance/e2e/e2e_test.go
@@ -91,20 +91,40 @@ func TestRAGFullLoop(t *testing.T) {
}
t.Logf("search returned %d results", len(results))
- // 5. chat --format json → bare {answer, references, ...} object
- var chat struct {
- Answer string `json:"answer"`
- References []map[string]any `json:"references"`
+ // 5. chat --format json → bounded answer-event envelope (--reference for citations)
+ var chatEnv struct {
+ OK bool `json:"ok"`
+ Data struct {
+ Events []struct {
+ ResponseType string `json:"response_type"`
+ Content string `json:"content"`
+ KnowledgeReferences []struct {
+ ChunkID string `json:"chunk_id"`
+ } `json:"knowledge_references"`
+ } `json:"events"`
+ SessionID string `json:"session_id"`
+ } `json:"data"`
}
- runJSONInto(t, bin, env, &chat, "chat", "summarize the document briefly", "--kb", created.ID, "--format", "json")
- if strings.TrimSpace(chat.Answer) == "" {
+ runJSONInto(t, bin, env, &chatEnv, "chat", "summarize the document briefly", "--kb", created.ID, "--format", "json", "--reference")
+ if !chatEnv.OK {
+ t.Fatal("chat ok=false")
+ }
+ var answer strings.Builder
+ refCount := 0
+ for _, ev := range chatEnv.Data.Events {
+ if ev.ResponseType == "answer" {
+ answer.WriteString(ev.Content)
+ }
+ refCount += len(ev.KnowledgeReferences)
+ }
+ if strings.TrimSpace(answer.String()) == "" {
t.Fatalf("chat returned empty answer")
}
- t.Logf("chat answer (%d chars), %d references", len(chat.Answer), len(chat.References))
- if len(chat.References) == 0 {
+ t.Logf("chat answer (%d chars), %d reference indexes", len(answer.String()), refCount)
+ if refCount == 0 {
// Soft warning - some servers may not surface references for every
// question, but the demo flow is supposed to.
- t.Logf("warning: chat returned 0 references (server may have a different config)")
+ t.Logf("warning: chat returned 0 reference indexes (server may have a different config)")
}
}
diff --git a/cli/cmd/chat/chat.go b/cli/cmd/chat/chat.go
index b90780815..cdac84523 100644
--- a/cli/cmd/chat/chat.go
+++ b/cli/cmd/chat/chat.go
@@ -218,7 +218,7 @@ func runChatNDJSON(ctx context.Context, opts *Options, sessionID string, svc Cha
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled")
}
- return cmdutil.WrapHTTP(err, "knowledge qa stream")
+ return cmdutil.WrapStream(err, "knowledge qa stream")
}
return nil
}
@@ -265,7 +265,7 @@ func runChatText(ctx context.Context, opts *Options, sessionID string, autoCreat
}
// Pre-stream HTTP / transport failure: route through the canonical
// classifier so 401 / 404 / 5xx still surface their specific codes.
- return cmdutil.WrapHTTP(streamErr, "knowledge qa stream")
+ return cmdutil.WrapStream(streamErr, "knowledge qa stream")
}
// SDK returned nil but we never saw a Done event - server closed the
@@ -304,7 +304,7 @@ func runChatJSON(ctx context.Context, opts *Options, fopts *cmdutil.FormatOption
if cmdutil.IsCancelled(ctx, err) {
return chatStreamError(cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "chat cancelled"), sessionID, projector.AssistantMessageID())
}
- return chatStreamError(cmdutil.WrapHTTP(err, "knowledge qa stream"), sessionID, projector.AssistantMessageID())
+ return chatStreamError(cmdutil.WrapStream(err, "knowledge qa stream"), sessionID, projector.AssistantMessageID())
}
if !projector.Done() {
return chatStreamError(
diff --git a/cli/cmd/chat/chat_test.go b/cli/cmd/chat/chat_test.go
index b5495c3ce..b85cb5f14 100644
--- a/cli/cmd/chat/chat_test.go
+++ b/cli/cmd/chat/chat_test.go
@@ -318,6 +318,29 @@ func TestChat_SDKError_MidStream_AbortsAsSSE(t *testing.T) {
}
}
+func TestChat_TerminalSSEError_ClassifiesAsServerError(t *testing.T) {
+ _, _ = iostreams.SetForTest(t)
+ svc := &fakeChatService{
+ streamEvents: []*sdk.StreamResponse{
+ {ResponseType: sdk.ResponseTypeAnswer, Content: "partial"},
+ {ResponseType: sdk.ResponseTypeError, Content: "boom", Done: true},
+ },
+ streamErr: sdk.NewSSEStreamError("boom"),
+ }
+ opts := &Options{Query: "q", KBID: "kb"}
+ err := runChat(context.Background(), opts, textOpts(), svc)
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ var typed *cmdutil.Error
+ if !errors.As(err, &typed) {
+ t.Fatalf("expected *cmdutil.Error, got %T", err)
+ }
+ if typed.Code != cmdutil.CodeServerError {
+ t.Errorf("code: got %q want %q", typed.Code, cmdutil.CodeServerError)
+ }
+}
+
func TestChat_ContextCancelled(t *testing.T) {
_, _ = iostreams.SetForTest(t)
ctx, cancel := context.WithCancel(context.Background())
diff --git a/cli/cmd/session/ask.go b/cli/cmd/session/ask.go
index 0b6f3d48c..adb4ba889 100644
--- a/cli/cmd/session/ask.go
+++ b/cli/cmd/session/ask.go
@@ -190,7 +190,7 @@ func runAskNDJSON(ctx context.Context, opts *AskOptions, sessionID string, svc A
if cmdutil.IsCancelled(ctx, err) {
return cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session ask cancelled")
}
- return cmdutil.WrapHTTP(err, "agent-chat stream")
+ return cmdutil.WrapStream(err, "agent-chat stream")
}
return nil
}
@@ -226,7 +226,7 @@ func runAskText(ctx context.Context, opts *AskOptions, sessionID string, autoCre
if projector.Seen() && !projector.Done() {
return cmdutil.Wrapf(cmdutil.CodeSSEStreamAborted, streamErr, "stream aborted before completion")
}
- return cmdutil.WrapHTTP(streamErr, "agent-chat stream")
+ return cmdutil.WrapStream(streamErr, "agent-chat stream")
}
// Server closed cleanly but never sent a complete event — treat as aborted
@@ -260,7 +260,7 @@ func runAskJSON(ctx context.Context, opts *AskOptions, fopts *cmdutil.FormatOpti
if cmdutil.IsCancelled(ctx, err) {
return askStreamError(cmdutil.Wrapf(cmdutil.CodeOperationCancelled, err, "session ask cancelled"), sessionID)
}
- return askStreamError(cmdutil.WrapHTTP(err, "agent-chat stream"), sessionID)
+ return askStreamError(cmdutil.WrapStream(err, "agent-chat stream"), sessionID)
}
if !projector.Done() {
return askStreamError(
diff --git a/cli/internal/cmdutil/errors.go b/cli/internal/cmdutil/errors.go
index 8384132e3..1c35a6db8 100644
--- a/cli/internal/cmdutil/errors.go
+++ b/cli/internal/cmdutil/errors.go
@@ -11,6 +11,7 @@ import (
"strings"
"github.com/Tencent/WeKnora/cli/internal/output"
+ sdk "github.com/Tencent/WeKnora/client"
)
// ErrorCode is a namespaced stable identifier emitted on stderr in the
@@ -268,6 +269,21 @@ func WrapHTTP(cause error, format string, args ...any) *Error {
return Wrapf(ClassifyHTTPError(cause), cause, format, args...)
}
+// ClassifySDKError maps SDK transport, HTTP, and terminal SSE stream errors to
+// the canonical ErrorCode. SSE terminal frames classify as server.error rather
+// than network.error.
+func ClassifySDKError(err error) ErrorCode {
+ if sdk.IsSSEStreamError(err) {
+ return CodeServerError
+ }
+ return ClassifyHTTPError(err)
+}
+
+// WrapStream wraps an SDK streaming error with ClassifySDKError.
+func WrapStream(cause error, format string, args ...any) *Error {
+ return Wrapf(ClassifySDKError(cause), cause, format, args...)
+}
+
// FlagError signals user-visible flag/argument problems; the root command
// prints help on top of the message and exits 2.
type FlagError struct{ err error }
diff --git a/cli/internal/cmdutil/errors_test.go b/cli/internal/cmdutil/errors_test.go
index 3c02a096a..f758fdb31 100644
--- a/cli/internal/cmdutil/errors_test.go
+++ b/cli/internal/cmdutil/errors_test.go
@@ -5,6 +5,7 @@ import (
"fmt"
"testing"
+ sdk "github.com/Tencent/WeKnora/client"
"github.com/stretchr/testify/assert"
)
@@ -35,6 +36,12 @@ func TestClassifyHTTPError(t *testing.T) {
}
}
+func TestClassifySDKError_SSEStreamTerminal(t *testing.T) {
+ err := sdk.NewSSEStreamError("boom")
+ assert.Equal(t, CodeServerError, ClassifySDKError(err))
+ assert.Equal(t, CodeNetworkError, ClassifyHTTPError(err))
+}
+
func TestClassifyHTTPError_500NotFoundRescue(t *testing.T) {
// Server's 1003 = ErrNotFound is the only typed "not found" code we
// rescue. 1007 = ErrInternalServer is the catch-all bucket — its
diff --git a/cli/internal/mcp/tools.go b/cli/internal/mcp/tools.go
index f2e91c11a..b194edad8 100644
--- a/cli/internal/mcp/tools.go
+++ b/cli/internal/mcp/tools.go
@@ -45,6 +45,18 @@ func toolErrorResult(err error) *mcpsdk.CallToolResult {
}
}
+func streamErrorDetail(sessionID, assistantMessageID string) map[string]any {
+ detail := map[string]any{"session_id": sessionID}
+ if assistantMessageID != "" {
+ detail["assistant_message_id"] = assistantMessageID
+ }
+ return detail
+}
+
+func toolStreamError(err *cmdutil.Error, sessionID, assistantMessageID string) *mcpsdk.CallToolResult {
+ return toolErrorResult(err.WithDetail(streamErrorDetail(sessionID, assistantMessageID)))
+}
+
// successResult builds a CallToolResult with StructuredContent = payload.
// Using Out=any in all handlers disables the SDK auto-marshal path (which
// would overwrite our StructuredContent with a zero-struct when the handler
@@ -484,10 +496,10 @@ func addChat(server *mcpsdk.Server, svc chatService) {
return nil
})
if streamErr != nil {
- return toolErrorResult(cmdutil.WrapHTTP(streamErr, "knowledge qa stream")), nil, nil
+ return toolStreamError(cmdutil.WrapStream(streamErr, "knowledge qa stream"), sessionID, projector.AssistantMessageID()), nil, nil
}
if !projector.Done() {
- return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil
+ return toolStreamError(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event"), sessionID, projector.AssistantMessageID()), nil, nil
}
sid := projector.SessionID()
if sid == "" {
@@ -594,10 +606,10 @@ func addSessionAsk(server *mcpsdk.Server, svc sessionAskService) {
return nil
})
if streamErr != nil {
- return toolErrorResult(cmdutil.WrapHTTP(streamErr, "agent-chat stream")), nil, nil
+ return toolStreamError(cmdutil.WrapStream(streamErr, "agent-chat stream"), sessionID, ""), nil, nil
}
if !projector.Done() {
- return toolErrorResult(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event")), nil, nil
+ return toolStreamError(cmdutil.NewError(cmdutil.CodeSSEStreamAborted, "stream ended without a terminal event"), sessionID, ""), nil, nil
}
return successResult(sessionAskOutput{
Events: events,
diff --git a/cli/internal/mcp/tools_test.go b/cli/internal/mcp/tools_test.go
index a386b8623..53aa2fa2f 100644
--- a/cli/internal/mcp/tools_test.go
+++ b/cli/internal/mcp/tools_test.go
@@ -576,6 +576,43 @@ func TestTool_SessionAsk_StreamAbort(t *testing.T) {
}
}
+func TestTool_Chat_StreamErrorIncludesSessionDetail(t *testing.T) {
+ svc := &fakeSvc{
+ kbStreamEvents: []*sdk.StreamResponse{
+ {ResponseType: sdk.ResponseTypeAnswer, Content: "partial"},
+ {ResponseType: sdk.ResponseTypeError, Content: "boom", Done: true},
+ },
+ kbStreamErr: sdk.NewSSEStreamError("boom"),
+ }
+ c, _ := newTestServer(t, svc)
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
+ defer cancel()
+ res, err := c.CallTool(ctx, &mcpsdk.CallToolParams{Name: "chat", Arguments: map[string]any{"kb_id": "kb_x", "query": "q"}})
+ if err != nil {
+ t.Fatalf("unexpected transport error: %v", err)
+ }
+ if !res.IsError {
+ t.Fatal("expected IsError=true on terminal stream error")
+ }
+ b, err := json.Marshal(res.StructuredContent)
+ if err != nil {
+ t.Fatalf("marshal structured content: %v", err)
+ }
+ var detail struct {
+ Type string `json:"type"`
+ Detail map[string]any `json:"detail"`
+ }
+ if err := json.Unmarshal(b, &detail); err != nil {
+ t.Fatalf("unmarshal error detail: %v", err)
+ }
+ if detail.Type != "server.error" {
+ t.Errorf("type=%q, want server.error", detail.Type)
+ }
+ if detail.Detail["session_id"] != "sess_auto" {
+ t.Errorf("detail=%v, want session_id sess_auto", detail.Detail)
+ }
+}
+
func TestTool_ChunkList_Happy(t *testing.T) {
svc := &fakeSvc{
chunks: []sdk.Chunk{{ID: "c1", ChunkIndex: 0, Content: "hello"}},
diff --git a/cli/internal/sse/accumulator.go b/cli/internal/sse/accumulator.go
index 28e24b954..26546402b 100644
--- a/cli/internal/sse/accumulator.go
+++ b/cli/internal/sse/accumulator.go
@@ -65,12 +65,7 @@ func (a *Accumulator) Append(r *sdk.StreamResponse) {
a.AssistantMessageID = r.AssistantMessageID
}
// Capture references whenever they arrive - they may land on a
- // dedicated `references` event before the terminal `complete`. Strip the
- // bulky per-chunk Content so the buffered envelope stays small: agents
- // consume the index (id / parent_chunk_id / title / score / snippet) and
- // fetch full passages on demand via `chunk view`. This runs after SSE
- // parsing, so it governs outgoing envelope size — the incoming line-size
- // limit is the scanner buffer's job, not this one.
+ // dedicated `references` event before the terminal `complete`.
if r.KnowledgeReferences != nil {
a.References = r.KnowledgeReferences
}
diff --git a/cli/internal/sse/projector.go b/cli/internal/sse/projector.go
index b2d301108..941f533b3 100644
--- a/cli/internal/sse/projector.go
+++ b/cli/internal/sse/projector.go
@@ -64,6 +64,9 @@ func (p *Projector) Chat(r *sdk.StreamResponse) (ProjectedEvent, bool) {
if r.ResponseType == sdk.ResponseTypeComplete {
p.done = true
}
+ if r.ResponseType == sdk.ResponseTypeError && r.Done {
+ p.done = true
+ }
responseType := string(r.ResponseType)
isAnswer := r.ResponseType == sdk.ResponseTypeAnswer || (r.ResponseType == "" && r.Content != "")
@@ -103,6 +106,9 @@ func (p *Projector) Agent(r *sdk.AgentStreamResponse) (ProjectedEvent, bool) {
if r.ResponseType == sdk.AgentResponseTypeComplete {
p.done = true
}
+ if r.ResponseType == sdk.AgentResponseTypeError && r.Done {
+ p.done = true
+ }
isAnswer := r.ResponseType == sdk.AgentResponseTypeAnswer
isReference := r.ResponseType == sdk.AgentResponseTypeReferences
diff --git a/cli/internal/sse/projector_test.go b/cli/internal/sse/projector_test.go
index b52a5e0c0..1d55cd219 100644
--- a/cli/internal/sse/projector_test.go
+++ b/cli/internal/sse/projector_test.go
@@ -111,6 +111,28 @@ func TestProjector_VerboseDoesNotImplicitlyAddReferences(t *testing.T) {
}
}
+func TestProjector_TerminalErrorMarksDone(t *testing.T) {
+ p := sse.NewProjector(false, false, "kb")
+ _, include := p.Chat(&sdk.StreamResponse{
+ ResponseType: sdk.ResponseTypeAnswer,
+ Content: "partial",
+ })
+ if !include || p.Done() {
+ t.Fatalf("answer frame: include=%v done=%v", include, p.Done())
+ }
+ _, include = p.Chat(&sdk.StreamResponse{
+ ResponseType: sdk.ResponseTypeError,
+ Content: "boom",
+ Done: true,
+ })
+ if include {
+ t.Fatal("default projection should not include terminal error event")
+ }
+ if !p.Done() {
+ t.Fatal("terminal error did not mark projector done")
+ }
+}
+
func TestTextRenderer_StreamsSelectedEvents(t *testing.T) {
var out bytes.Buffer
r := sse.NewTextRenderer(&out, true)
diff --git a/cli/skills/weknora-rag-search/SKILL.md b/cli/skills/weknora-rag-search/SKILL.md
index 54a5662c0..25e166f42 100644
--- a/cli/skills/weknora-rag-search/SKILL.md
+++ b/cli/skills/weknora-rag-search/SKILL.md
@@ -2,7 +2,7 @@
name: weknora-rag-search
description: Use when retrieving from or asking questions against a WeKnora knowledge base via the `weknora` CLI — and especially when unsure whether to use `chat`, `session ask`, or `search chunks` for a given goal.
metadata:
- tested_against: v0.9
+ tested_against: v0.10
---
# WeKnora — retrieval & RAG queries
diff --git a/cli/skills/weknora-shared/SKILL.md b/cli/skills/weknora-shared/SKILL.md
index 82f1139be..85d796fe8 100644
--- a/cli/skills/weknora-shared/SKILL.md
+++ b/cli/skills/weknora-shared/SKILL.md
@@ -2,7 +2,7 @@
name: weknora-shared
description: Use when driving a WeKnora RAG server through the `weknora` CLI as an agent — authenticating, managing knowledge bases / documents / sessions / agents, running search or chat, or interpreting the CLI's JSON envelopes and exit codes. Read this before any other weknora-* skill.
metadata:
- tested_against: v0.9
+ tested_against: v0.10
---
# WeKnora CLI — shared base
diff --git a/client/agent.go b/client/agent.go
index b3dbc449f..3f6697354 100644
--- a/client/agent.go
+++ b/client/agent.go
@@ -130,7 +130,7 @@ func (c *Client) processAgentSSEStream(reader io.Reader, callback AgentEventCall
// follows it with `complete` or EOF. Deliver it to the callback
// first, then terminate the SDK call with an error.
if streamResponse.ResponseType == AgentResponseTypeError && streamResponse.Done {
- return fmt.Errorf("SSE stream error: %s", streamResponse.Content)
+ return NewSSEStreamError(streamResponse.Content)
}
dataBuffer = ""
}
diff --git a/client/session.go b/client/session.go
index 317b5b252..b7cf9c756 100644
--- a/client/session.go
+++ b/client/session.go
@@ -321,7 +321,7 @@ func (c *Client) KnowledgeQAStream(
return err
}
if streamResponse.ResponseType == ResponseTypeError && streamResponse.Done {
- return fmt.Errorf("SSE stream error: %s", streamResponse.Content)
+ return NewSSEStreamError(streamResponse.Content)
}
dataBuffer = ""
eventType = ""
@@ -396,7 +396,7 @@ func (c *Client) ContinueStream(
return err
}
if streamResponse.ResponseType == ResponseTypeError && streamResponse.Done {
- return fmt.Errorf("SSE stream error: %s", streamResponse.Content)
+ return NewSSEStreamError(streamResponse.Content)
}
dataBuffer = ""
eventType = ""
diff --git a/client/stream_errors.go b/client/stream_errors.go
new file mode 100644
index 000000000..0890aea52
--- /dev/null
+++ b/client/stream_errors.go
@@ -0,0 +1,49 @@
+package client
+
+import (
+ "errors"
+ "fmt"
+ "strings"
+)
+
+// ErrSSEStreamTerminal marks a terminal response_type=error, done=true frame
+// from an SSE stream. The stream delivered the frame to the callback before
+// returning the error.
+var ErrSSEStreamTerminal = errors.New("SSE stream terminal error")
+
+// SSEStreamError is returned when the server emits a terminal error frame on
+// an SSE stream.
+type SSEStreamError struct {
+ Content string
+}
+
+func (e *SSEStreamError) Error() string {
+ return fmt.Sprintf("SSE stream error: %s", e.Content)
+}
+
+func (e *SSEStreamError) Unwrap() error {
+ return ErrSSEStreamTerminal
+}
+
+// NewSSEStreamError builds the terminal SSE stream error returned by the
+// streaming readers after delivering the error frame to the callback.
+func NewSSEStreamError(content string) error {
+ return &SSEStreamError{Content: content}
+}
+
+// IsSSEStreamError reports whether err is a terminal SSE stream error from the
+// SDK readers, including wrapped *SSEStreamError values and legacy
+// fmt.Errorf("SSE stream error: ...") chains.
+func IsSSEStreamError(err error) bool {
+ var sse *SSEStreamError
+ if errors.As(err, &sse) {
+ return true
+ }
+ for err != nil {
+ if strings.HasPrefix(err.Error(), "SSE stream error: ") {
+ return true
+ }
+ err = errors.Unwrap(err)
+ }
+ return false
+}
diff --git a/client/stream_errors_test.go b/client/stream_errors_test.go
new file mode 100644
index 000000000..4ae514502
--- /dev/null
+++ b/client/stream_errors_test.go
@@ -0,0 +1,35 @@
+package client
+
+import (
+ "errors"
+ "fmt"
+ "testing"
+)
+
+func TestIsSSEStreamError(t *testing.T) {
+ cases := []struct {
+ name string
+ err error
+ want bool
+ }{
+ {"typed", NewSSEStreamError("boom"), true},
+ {"wrapped", fmt.Errorf("request failed: %w", NewSSEStreamError("boom")), true},
+ {"legacy_string", fmt.Errorf("SSE stream error: boom"), true},
+ {"http", fmt.Errorf("HTTP error 500: internal"), false},
+ {"nil", nil, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := IsSSEStreamError(tc.err); got != tc.want {
+ t.Errorf("IsSSEStreamError(%v) = %v, want %v", tc.err, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestSSEStreamError_Unwrap(t *testing.T) {
+ err := NewSSEStreamError("boom")
+ if !errors.Is(err, ErrSSEStreamTerminal) {
+ t.Fatal("expected ErrSSEStreamTerminal in chain")
+ }
+}