| 755 | break |
| 756 | } |
| 757 | if ctx.Err() != nil || e.isAborted() { |
| 758 | e.restoreInFlightCacheEdits() |
| 759 | e.LastState = state |
| 760 | sendStream(ctx, out, NewStreamEvent("done", "Aborted by user.", nil)) |
| 761 | return |
| 762 | } |
| 763 | action := e.HandleStreamEvent(result.Event, turn, executor, state, consecutiveAPIErrors) |
| 764 | consecutiveAPIErrors = action.ConsecutiveAPIErrors |
| 765 | if action.Event != nil { |
| 766 | sendStream(ctx, out, *action.Event) |
| 767 | } |
| 768 | if action.Return { |
| 769 | e.restoreInFlightCacheEdits() |
| 770 | sendStream(ctx, out, NewStreamEvent("done", "", nil)) |
| 771 | return |
| 772 | } |
| 773 | if action.Break { |
| 774 | break |
| 775 | } |
| 776 | } |
| 777 | |
| 778 | if turn.StreamHadError || turn.PTLDetected { |
| 779 | e.restoreInFlightCacheEdits() |
| 780 | } else { |
| 781 | e.pinConsumedCacheEdits() |
| 782 | } |
| 783 | |
| 784 | if ShouldCommitFinalTextAfterStreamError(turn) { |
| 785 | turn.StreamHadError = false |
| 786 | consecutiveAPIErrors = 0 |
| 787 | } |
| 788 | if !turn.StreamHadError { |
| 789 | consecutiveAPIErrors = 0 |
| 790 | } |
| 791 | if turn.StreamHadError && len(turn.ToolCalls) == 0 && consecutiveAPIErrors < MaxAPIErrorRetries { |
| 792 | continue |
| 793 | } |
| 794 | if turn.PTLDetected { |
| 795 | action, event := ptlRecovery.Recover(state, turn.PTLErrorMsg) |
| 796 | if action == "retry" { |
| 797 | e.clearRuntimeCompressionStateAfterHistoryReplace(state) |
| 798 | outputRecovery.ResetAfterHistoryReplace(e.Config.APIMaxTokens) |
| 799 | continue |
| 800 | } |
| 801 | if event != nil { |
| 802 | sendStream(ctx, out, *event) |
| 803 | } |
| 804 | e.LastState = state |
| 805 | sendStream(ctx, out, NewStreamEvent("done", "", nil)) |
| 806 | return |
| 807 | } |
| 808 | if turn.OutputTruncated { |
| 809 | recovery := HandleOutputTruncation(state, &outputRecovery, turn.ToolCalls, turn.ThinkingContent, turn.FullText, turn.MessageID, turn.InputTokens, turn.OutputTokens) |
| 810 | if recovery.ShouldContinue() { |
| 811 | continue |
| 812 | } |
| 813 | if recovery.ShouldReturn() { |
| 814 | if recovery.Event != nil { |