diff --git a/runtime/runtime.go b/runtime/runtime.go index d41b358..d7645e1 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -497,6 +497,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon streamSource := stream retriedNonStreaming := false + preTokenRetried := false retriedRefusal := false var refused bool var refusalCategory string @@ -556,6 +557,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon } case llm.EventError: + if !gotFirstToken && !preTokenRetried { + if newStream, ok := r.recoverFromPreTokenError(ctx, event.Error, &req, &msgs, spillCfg); ok { + preTokenRetried = true + drainKickoffs(kickoffs) + kickoffs = map[string]chan kickoffResult{} + textContent.Reset() + toolCalls = nil + kickoffStopped = false + streamSource = newStream + continue streamLoop + } + } if gotFirstToken && !retriedNonStreaming { if ns, ok := r.LLM.(llm.NonStreamingProvider); ok { slog.Warn("stream died mid-flight; retrying as non-streaming", @@ -743,6 +756,42 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon return r.events, nil } +// recoverFromPreTokenError attempts the same recovery the synchronous +// ChatStream-error path performs, for an error delivered via EventError +// before any token arrived (Anthropic/Gemini deliver HTTP errors this way). +// Returns a fresh stream to resume from and true if recovered; false if the +// error is not recoverable (caller should abort). May mutate *req (model +// swap) and the session (compaction), and reassigns *msgs on compaction. +func (r *Runtime) recoverFromPreTokenError(ctx context.Context, err error, req *llm.ChatRequest, msgs *[]llm.Message, spillCfg spillConfig) (<-chan llm.ChatEvent, bool) { + if compaction.IsContextOverflow(err) && r.Compaction != nil { + r.emit(AgentEvent{Type: EventCompactionStart}) + res, _ := r.Compaction.MaybeCompact(ctx, r.Session, compaction.ReasonReactive, "") + if res.Compacted { + r.emit(AgentEvent{Type: EventCompactionDone, Compaction: &res}) + history := r.Session.View() + newMsgs := assembleMessages(history) + pruneToolResults(newMsgs, r.maxToolResultLen(), spillCfg) + newMsgs = prependPostCompactRestore(newMsgs, r.snapshotTouchedFiles()) + *msgs = newMsgs + req.Messages = newMsgs + if s, e := r.LLM.ChatStream(ctx, *req); e == nil { + return s, true + } + } else { + r.emit(AgentEvent{Type: EventCompactionSkipped, Compaction: &res}) + } + } + if r.FallbackModel != "" && r.FallbackModel != req.Model && llm.IsRetryableModelError(err) { + slog.Info("llm fallback model engaged (stream error)", + "agent", r.AgentID, "primary", req.Model, "fallback", r.FallbackModel, "err", err.Error()) + req.Model = r.FallbackModel + if s, e := r.LLM.ChatStream(ctx, *req); e == nil { + return s, true + } + } + return nil, false +} + // RunSync is a convenience method that runs the agent and collects the // full text response. func (r *Runtime) RunSync(ctx context.Context, userMsg string, images []llm.ImageContent) (string, error) { diff --git a/runtime/streamrecover_test.go b/runtime/streamrecover_test.go new file mode 100644 index 0000000..ac3bdf7 --- /dev/null +++ b/runtime/streamrecover_test.go @@ -0,0 +1,79 @@ +package runtime + +import ( + "context" + "errors" + "sync/atomic" + "testing" + + "github.com/sausheong/harness/llm" + "github.com/sausheong/harness/llm/llmtest" + "github.com/sausheong/harness/session" + "github.com/sausheong/harness/tool" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// streamErrThenOKProvider emits EventError (no token) on the first stream +// call, then clean text on the second. +type streamErrThenOKProvider struct { + llmtest.Base + calls atomic.Int64 + streamErr error + finalText string +} + +func (p *streamErrThenOKProvider) ChatStream(_ context.Context, _ llm.ChatRequest) (<-chan llm.ChatEvent, error) { + n := p.calls.Add(1) + ch := make(chan llm.ChatEvent, 4) + if n == 1 { + ch <- llm.ChatEvent{Type: llm.EventError, Error: p.streamErr} + } else { + ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: p.finalText} + ch <- llm.ChatEvent{Type: llm.EventDone} + } + close(ch) + return ch, nil +} + +func TestStreamErrorRetryableEngagesFallback(t *testing.T) { + prov := &streamErrThenOKProvider{ + streamErr: errors.New("429 rate limit exceeded"), + finalText: "RECOVERED_VIA_FALLBACK", + } + rt := &Runtime{ + LLM: prov, + Tools: tool.NewRegistry(), + Session: session.NewSession("a", "k"), + AgentID: "a", + Model: "claude-opus-4-8", + FallbackModel: "claude-sonnet-4-5", + Provider: "anthropic", + MaxTurns: 2, + Workspace: t.TempDir(), + } + out, err := rt.RunSync(context.Background(), "do it", nil) + require.NoError(t, err) + assert.Contains(t, out, "RECOVERED_VIA_FALLBACK") + assert.EqualValues(t, 2, prov.calls.Load(), "must retry once after the pre-first-token 429") +} + +func TestStreamErrorNonRetryableStillAborts(t *testing.T) { + prov := &streamErrThenOKProvider{ + streamErr: errors.New("400 invalid input"), + finalText: "SHOULD_NOT_BE_REACHED", + } + rt := &Runtime{ + LLM: prov, + Tools: tool.NewRegistry(), + Session: session.NewSession("a", "k"), + AgentID: "a", + Model: "claude-opus-4-8", + Provider: "anthropic", + MaxTurns: 2, + Workspace: t.TempDir(), + } + _, err := rt.RunSync(context.Background(), "do it", nil) + require.Error(t, err) + assert.EqualValues(t, 1, prov.calls.Load(), "non-retryable pre-first-token error must abort, not retry") +}