Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion internal/providers/claude_cli_chat.go
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,14 @@ func (p *ClaudeCLIProvider) Chat(ctx context.Context, req ChatRequest) (*ChatRes
}
continue
}
return nil, fmt.Errorf("claude-cli: %w (stderr: %s)", err, stderr.String())
stderrStr := stderr.String()
if strings.TrimSpace(stderrStr) == "" {
// claude-cli reports API errors in the result on stdout, not stderr.
if msg := cliResultError(output); msg != "" {
stderrStr = "result: " + msg
}
}
return nil, fmt.Errorf("claude-cli: %w (stderr: %s)", err, stderrStr)
}

return parseJSONResponse(output)
Expand Down
80 changes: 80 additions & 0 deletions internal/providers/claude_cli_error_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package providers

import (
"context"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
)

func TestParseJSONResponse_IsErrorResult(t *testing.T) {
const result = `{"type":"result","subtype":"success","is_error":true,"result":"API Error: 529 overloaded"}`
for name, out := range map[string]string{"object": result, "array": "[" + result + "]"} {
t.Run(name, func(t *testing.T) {
resp, err := parseJSONResponse([]byte(out))
if err != nil {
t.Fatalf("parseJSONResponse: %v", err)
}
if resp.FinishReason != "error" {
t.Errorf("FinishReason = %q, want error", resp.FinishReason)
}
})
}
}

func TestClaudeCLIChat_ExitErrorKeepsAPIMessage(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a shell script as the fake CLI")
}
for name, out := range map[string]string{
"result field": `{"type":"result","subtype":"success","is_error":true,"result":"API Error: 529 overloaded"}`,
"error field": `[{"type":"result","subtype":"error","is_error":true,"error":"API Error: 529 overloaded"}]`,
} {
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
cli := filepath.Join(dir, "claude")
script := "#!/bin/sh\necho '" + out + "'\nexit 1\n"
if err := os.WriteFile(cli, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
p := NewClaudeCLIProvider(cli, WithClaudeCLIWorkDir(dir))
_, err := p.Chat(context.Background(), ChatRequest{
Messages: []Message{{Role: "user", Content: "hi"}},
})
if err == nil || !strings.Contains(err.Error(), "API Error: 529 overloaded") {
t.Fatalf("err = %v, want it to carry the API error", err)
}
})
}
}

func TestClaudeCLIChat_EmptyFailedResult(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("uses a shell script as the fake CLI")
}
const result = `{"type":"result","subtype":"success","is_error":true,"result":"","error":""}`
const assistant = `{"type":"assistant","message":{"content":[{"type":"text","text":"partial answer"}]}}`
for name, out := range map[string]string{
"object": result,
"array": "[" + result + "]",
"array with assistant": "[" + assistant + "," + result + "]",
} {
t.Run(name, func(t *testing.T) {
dir := t.TempDir()
cli := filepath.Join(dir, "claude")
script := "#!/bin/sh\necho '" + out + "'\nexit 0\n"
if err := os.WriteFile(cli, []byte(script), 0o755); err != nil {
t.Fatal(err)
}
p := NewClaudeCLIProvider(cli, WithClaudeCLIWorkDir(dir))
resp, err := p.Chat(context.Background(), ChatRequest{
Messages: []Message{{Role: "user", Content: "hi"}},
})
if resp != nil || err == nil || err.Error() != "claude-cli: result error (no message)" {
t.Fatalf("Chat = (%+v, %v), want nil response and an explicit result error", resp, err)
}
})
}
}
71 changes: 55 additions & 16 deletions internal/providers/claude_cli_parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,29 @@ import (
// parseJSONResponse parses the CLI JSON output into a ChatResponse.
func parseJSONResponse(data []byte) (*ChatResponse, error) {
// Try parsing as JSON array first (CLI may output all events as a single array).
if resp := parseJSONArray(data); resp != nil {
return resp, nil
}
resp := parseJSONArray(data)

// Fallback: CLI may output one JSON object per line.
for line := range bytes.SplitSeq(data, []byte("\n")) {
line = bytes.TrimSpace(line)
if len(line) == 0 {
continue
if resp == nil {
for line := range bytes.SplitSeq(data, []byte("\n")) {
line = bytes.TrimSpace(line)
if len(line) == 0 {
continue
}
resp = parseSingleJSONResult(line)
if resp != nil {
break
}
}
if resp := parseSingleJSONResult(line); resp != nil {
return resp, nil
}
if resp != nil {
if resp.FinishReason == "error" && strings.TrimSpace(resp.Content) == "" {
if msg := strings.TrimSpace(cliResultError(data)); msg != "" {
return nil, fmt.Errorf("claude-cli: result error: %s", msg)
}
return nil, fmt.Errorf("claude-cli: result error (no message)")
}
return resp, nil
}

// Last resort: treat entire output as text response
Expand Down Expand Up @@ -61,6 +71,7 @@ func parseJSONArray(data []byte) *ChatResponse {
Result string `json:"result,omitempty"`
Message json.RawMessage `json:"message,omitempty"`
Usage *cliUsage `json:"usage,omitempty"`
IsError bool `json:"is_error,omitempty"`
}
if err := json.Unmarshal(raw, &ev); err != nil {
continue
Expand All @@ -69,7 +80,7 @@ func parseJSONArray(data []byte) *ChatResponse {
switch ev.Type {
case "result":
resultText = ev.Result
if ev.Subtype == "error" {
if ev.Subtype == "error" || ev.IsError {
finishReason = "error"
}
if ev.Usage != nil {
Expand All @@ -93,11 +104,13 @@ func parseJSONArray(data []byte) *ChatResponse {

// Prefer "result" text, fall back to concatenated assistant text blocks
content := resultText
if content == "" {
content = assistantText.String()
}
if content == "" {
return nil
if finishReason != "error" {
if content == "" {
content = assistantText.String()
}
if content == "" {
return nil
}
}

return &ChatResponse{
Expand All @@ -120,7 +133,7 @@ func parseSingleJSONResult(line []byte) *ChatResponse {
Content: resp.Result,
FinishReason: "stop",
}
if resp.Subtype == "error" {
if resp.Subtype == "error" || resp.IsError {
cr.FinishReason = "error"
}
if resp.Usage != nil {
Expand All @@ -129,6 +142,32 @@ func parseSingleJSONResult(line []byte) *ChatResponse {
return cr
}

// cliResultError returns the message of a failed "result" event in the CLI
// output (JSON array or one object per line), or "" if there is none.
func cliResultError(data []byte) string {
var events []json.RawMessage
if err := json.Unmarshal(bytes.TrimSpace(data), &events); err != nil {
for line := range bytes.SplitSeq(data, []byte("\n")) {
events = append(events, line)
}
}
for _, raw := range events {
var ev cliStreamEvent
if err := json.Unmarshal(raw, &ev); err != nil || ev.Type != "result" {
continue
}
if ev.Subtype != "error" && !ev.IsError {
continue
}
// Prefer ev.Error (result may be empty for usage/rate limit errors).
if ev.Error != "" {
return ev.Error
}
return ev.Result
}
return ""
}

// extractStreamContent extracts text and thinking from a stream message.
func extractStreamContent(msg *cliStreamMsg) (text, thinking string) {
var textBuf, thinkBuf strings.Builder
Expand Down
1 change: 1 addition & 0 deletions internal/providers/claude_cli_types.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ type cliJSONResponse struct {
Model string `json:"model"`
CostUSD float64 `json:"cost_usd"`
Usage *cliUsage `json:"usage"`
IsError bool `json:"is_error,omitempty"` // may be true with subtype="success" (API errors)
}

// cliUsage maps Claude CLI usage counters. input_tokens excludes cached
Expand Down
Loading