Skip to content
Merged
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
5 changes: 3 additions & 2 deletions internal/agent/loop.go
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,8 @@ func Run(ctx context.Context, prompt string, provider Provider, options Options)
// collected and a non-nil stop error when the run must end now.
recoverStreamError := func(collected zeroruntime.CollectedStream) (zeroruntime.CollectedStream, error) {
if isImageRejectionError(errors.New(collected.Error)) {
return collected, fmt.Errorf("model %s rejected the image: %s. The model may not support image input — try switching to a vision-capable model (claude, gpt-4o, gemini)", options.Model, collected.Error)
cause := &zeroruntime.StreamError{Message: collected.Error, StatusCode: collected.ErrorStatusCode, Cause: collected.ErrorCause}
return collected, fmt.Errorf("model %s rejected the image: %w. The model may not support image input — try switching to a vision-capable model (claude, gpt-4o, gemini)", options.Model, cause)
}
// REACTIVE compaction: the streamed error may also be a context limit
// (some providers surface it mid-stream). Compact and retry once.
Expand Down Expand Up @@ -542,7 +543,7 @@ func Run(ctx context.Context, prompt string, provider Provider, options Options)
}
if collected.Error != "" {
result.Messages = copyMessages(messages)
return result, errors.New(collected.Error)
return result, &zeroruntime.StreamError{Message: collected.Error, StatusCode: collected.ErrorStatusCode, Cause: collected.ErrorCause}
}
}

Expand Down
80 changes: 80 additions & 0 deletions internal/agent/loop_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4205,6 +4205,86 @@ func TestRunNilTraceForwardsUsage(t *testing.T) {
}
}

// TestRunReturnsStreamErrorWithStatusCodeAndCause covers the collector-to-agent
// propagation boundary: a provider stream that terminates with a StreamEventError
// carrying StatusCode/Cause must have Run return an error that errors.As can
// still recover those fields from — the detail a session's "error" event needs
// to actually diagnose why a provider call failed (#674).
func TestRunReturnsStreamErrorWithStatusCodeAndCause(t *testing.T) {
provider := &mockProvider{turns: [][]zeroruntime.StreamEvent{{
{
Type: zeroruntime.StreamEventError,
Error: "provider error: provider returned error",
StatusCode: 500,
Cause: "upstream returned an empty completion",
},
}}}

_, err := Run(context.Background(), "hi", provider, Options{
SessionID: "stream-error-session",
Cwd: t.TempDir(),
ProviderName: "test-provider",
Model: "test-model",
})
if err == nil {
t.Fatal("Run: expected an error, got nil")
}

var streamErr *zeroruntime.StreamError
if !errors.As(err, &streamErr) {
t.Fatalf("Run error %v (%T) does not unwrap to *zeroruntime.StreamError", err, err)
}
if streamErr.StatusCode != 500 {
t.Fatalf("StatusCode = %d, want 500", streamErr.StatusCode)
}
if streamErr.Cause != "upstream returned an empty completion" {
t.Fatalf("Cause = %q, want %q", streamErr.Cause, "upstream returned an empty completion")
}
if err.Error() != "provider error: provider returned error" {
t.Fatalf("Error() = %q, want the flattened message unchanged", err.Error())
}
}

// TestRunImageRejectionKeepsStreamErrorStatusCodeAndCause covers the 400
// image-rejection recovery path: the friendly message is kept, but the returned
// error must still unwrap to the *StreamError so StatusCode and Cause reach the
// session's "error" event (#674).
func TestRunImageRejectionKeepsStreamErrorStatusCodeAndCause(t *testing.T) {
provider := &mockProvider{turns: [][]zeroruntime.StreamEvent{{
{
Type: zeroruntime.StreamEventError,
Error: "provider error 400: image input is not supported",
StatusCode: 400,
Cause: "this model does not support image input",
},
}}}

_, err := Run(context.Background(), "hi", provider, Options{
SessionID: "image-rejection-session",
Cwd: t.TempDir(),
ProviderName: "test-provider",
Model: "test-model",
})
if err == nil {
t.Fatal("Run: expected an error, got nil")
}

want := "model test-model rejected the image: provider error 400: image input is not supported. The model may not support image input — try switching to a vision-capable model (claude, gpt-4o, gemini)"
if err.Error() != want {
t.Fatalf("Error() = %q, want the friendly message unchanged: %q", err.Error(), want)
}
var streamErr *zeroruntime.StreamError
if !errors.As(err, &streamErr) {
t.Fatalf("Run error %v (%T) does not unwrap to *zeroruntime.StreamError", err, err)
}
if streamErr.StatusCode != 400 {
t.Fatalf("StatusCode = %d, want 400", streamErr.StatusCode)
}
if streamErr.Cause != "this model does not support image input" {
t.Fatalf("Cause = %q, want the upstream cause", streamErr.Cause)
}
}

// TestRunSuppressesAdvisoryHooksInPlanMode: plan mode promises a read-only
// turn for advisory hooks (sessionStart/sessionEnd/afterTool), which execute
// configured host commands outside the advertised-tool and sandbox gates.
Expand Down
2 changes: 1 addition & 1 deletion internal/cli/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -799,7 +799,7 @@ func runExec(args []string, stdout io.Writer, stderr io.Writer, deps appDeps) in
}
return exitInterrupted
}
sessionRecorder.append(sessions.EventError, map[string]any{"message": err.Error()})
sessionRecorder.append(sessions.EventError, sessions.ErrorEventPayload(err))
if options.outputFormat == execOutputStreamJSON {
writer.errorEvent("provider_error", err.Error(), false)
writer.runEnd("error", exitProvider)
Expand Down
135 changes: 135 additions & 0 deletions internal/cli/exec_error_payload_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
package cli

import (
"bytes"
"context"
"encoding/json"
"testing"

"github.com/Twigpine/zero/internal/config"
"github.com/Twigpine/zero/internal/sandbox"
"github.com/Twigpine/zero/internal/sessions"
"github.com/Twigpine/zero/internal/zeroruntime"
)

// streamErrorExecProvider fails every request with one provider error event.
type streamErrorExecProvider struct {
event zeroruntime.StreamEvent
}

func (provider streamErrorExecProvider) StreamCompletion(ctx context.Context, _ zeroruntime.CompletionRequest) (<-chan zeroruntime.StreamEvent, error) {
ch := make(chan zeroruntime.StreamEvent, 1)
ch <- provider.event
close(ch)
return ch, nil
}

func providerErrorExecDeps(t *testing.T, store *sessions.Store, workspaceRoot string) appDeps {
t.Helper()
return appDeps{
getwd: func() (string, error) { return workspaceRoot, nil },
resolveConfig: func(_ string, _ config.Overrides) (config.ResolvedConfig, error) {
return config.ResolvedConfig{
ActiveProvider: "test",
Provider: config.ProviderProfile{
Name: "test",
ProviderKind: config.ProviderKindOpenAICompatible,
BaseURL: "http://127.0.0.1/v1",
Model: "test-model",
},
MaxTurns: 3,
}, nil
},
resolveMCPConfig: func(string, bool) (config.MCPConfig, error) { return config.MCPConfig{}, nil },
newProvider: func(config.ProviderProfile) (zeroruntime.Provider, error) {
return streamErrorExecProvider{event: zeroruntime.StreamEvent{
Type: zeroruntime.StreamEventError,
Error: "provider request error: model not found",
StatusCode: 404,
Cause: "upstream said: no such model",
}}, nil
},
newSessionStore: func() *sessions.Store { return store },
newSandboxStore: func() (*sandbox.GrantStore, error) {
return sandbox.NewGrantStore(sandbox.StoreOptions{FilePath: t.TempDir() + "/grants.json"})
},
}
}

// recordedProviderError returns the payload of the one error event the run
// recorded, failing unless there is exactly one session with exactly one.
func recordedProviderError(t *testing.T, store *sessions.Store) map[string]any {
t.Helper()
items, err := store.List()
if err != nil || len(items) != 1 {
t.Fatalf("sessions = %d, %v; want one", len(items), err)
}
events, err := store.ReadEvents(items[0].SessionID)
if err != nil {
t.Fatalf("ReadEvents returned error: %v", err)
}
var found []map[string]any
for _, event := range events {
if event.Type != sessions.EventError {
continue
}
var payload map[string]any
if err := json.Unmarshal(event.Payload, &payload); err != nil {
t.Fatalf("unmarshal error payload: %v", err)
}
found = append(found, payload)
}
if len(found) != 1 {
t.Fatalf("recorded %d error events, want 1: %#v", len(found), found)
}
return found[0]
}

func assertProviderErrorDetail(t *testing.T, payload map[string]any) {
t.Helper()
if got, want := payload["message"], "provider request error: model not found"; got != want {
t.Errorf("message = %#v, want %q", got, want)
}
if got, want := payload["statusCode"], float64(404); got != want {
t.Errorf("statusCode = %#v, want %v: the run recorded only the flattened message", got, want)
}
if got, want := payload["cause"], "upstream said: no such model"; got != want {
t.Errorf("cause = %#v, want %q: the run recorded only the flattened message", got, want)
}
}

// A provider error reaches the exec session log with its HTTP status and the
// upstream cause, not only the flattened message (#674).
func TestRunExecRecordsTheProviderErrorStatusAndCause(t *testing.T) {
isolateCLIUserState(t)
workspaceRoot := t.TempDir()
// exec records through the default store, which isolateCLIUserState has
// moved under the test's temp root; this opens the same one.
store := sessions.NewStore(sessions.StoreOptions{})
var stdout, stderr bytes.Buffer

exitCode := runWithDeps([]string{"exec", "--cwd", workspaceRoot, "--init-session-id", "provider_error_run", "hello"}, &stdout, &stderr,
providerErrorExecDeps(t, store, workspaceRoot))

if exitCode != exitProvider {
t.Fatalf("exit = %d, want %d; stderr=%s", exitCode, exitProvider, stderr.String())
}
assertProviderErrorDetail(t, recordedProviderError(t, store))
}

// The spec draft run records its provider error through its own call site, so
// it is checked on its own.
func TestRunExecUseSpecRecordsTheProviderErrorStatusAndCause(t *testing.T) {
isolateCLIUserState(t)
workspaceRoot := t.TempDir()
store := sessions.NewStore(sessions.StoreOptions{RootDir: t.TempDir()})
var stdout, stderr bytes.Buffer

exitCode := runWithDeps([]string{"exec", "--cwd", workspaceRoot, "--use-spec", "-o", "json", "plan the review flow"}, &stdout, &stderr,
providerErrorExecDeps(t, store, workspaceRoot))

if exitCode != exitProvider {
t.Fatalf("exit = %d, want %d; stderr=%s stdout=%s", exitCode, exitProvider, stderr.String(), stdout.String())
}
assertProviderErrorDetail(t, recordedProviderError(t, store))
}
2 changes: 1 addition & 1 deletion internal/cli/exec_spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ func runExecSpecDraft(run execSpecDraftRun) int {
}
return exitInterrupted
}
sessionRecorder.append(sessions.EventError, map[string]any{"message": err.Error()})
sessionRecorder.append(sessions.EventError, sessions.ErrorEventPayload(err))
return writeExecSpecDraftProviderError(&writer, run.options.outputFormat, err.Error())
}
if result.StopReason != agent.StopReasonSpecReviewRequired || draftInfo.SpecID == "" || draftInfo.SpecFilePath == "" {
Expand Down
29 changes: 21 additions & 8 deletions internal/providers/openai/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -298,26 +298,32 @@ func (provider *Provider) emitPayload(ctx context.Context, data string, state *t
if chunk.Error != nil {
state.flushContent(ctx, events)
state.closeOpen(ctx, events)
// statusCode buckets the error for classification only. The HTTP response
// was 200, so observedStatus stays 0 unless the payload's code maps to a
// known status; a bucket default must not be persisted as a real status.
statusCode := http.StatusInternalServerError
observedStatus := 0
if chunk.Error.Code != nil {
switch c := chunk.Error.Code.(type) {
case string:
if code, ok := openAIStreamErrorStatusByCode[c]; ok {
statusCode = code
statusCode, observedStatus = code, code
}
case float64:
if code, ok := openAIStreamErrorStatusByCode[strconv.Itoa(int(c))]; ok {
statusCode = code
statusCode, observedStatus = code, code
}
case int:
if code, ok := openAIStreamErrorStatusByCode[strconv.Itoa(c)]; ok {
statusCode = code
statusCode, observedStatus = code, code
}
}
}
sendEvent(ctx, events, zeroruntime.StreamEvent{
Type: zeroruntime.StreamEventError,
Error: provider.classifiedError(statusCode, chunk.Error.Message),
Type: zeroruntime.StreamEventError,
Error: provider.classifiedError(statusCode, chunk.Error.Message),
StatusCode: observedStatus,
Cause: provider.redact(chunk.Error.Message),
})
state.done = true
return false
Expand Down Expand Up @@ -404,12 +410,19 @@ func (provider *Provider) emitHTTPError(ctx context.Context, response *http.Resp
// localhost but returns a gateway error when it cannot reach its own backend.
// Surface that as a clear connectivity message instead of the raw proxied body.
if humanized, ok := providerio.UpstreamUnreachable(message); ok {
sendEvent(ctx, events, zeroruntime.StreamEvent{Type: zeroruntime.StreamEventError, Error: provider.redact(humanized)})
sendEvent(ctx, events, zeroruntime.StreamEvent{
Type: zeroruntime.StreamEventError,
Error: provider.redact(humanized),
StatusCode: response.StatusCode,
Cause: provider.redact(message),
})
return
}
sendEvent(ctx, events, zeroruntime.StreamEvent{
Type: zeroruntime.StreamEventError,
Error: provider.classifiedError(response.StatusCode, message),
Type: zeroruntime.StreamEventError,
Error: provider.classifiedError(response.StatusCode, message),
StatusCode: response.StatusCode,
Cause: provider.redact(message),
})
}

Expand Down
Loading
Loading