Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(agent): clear stale failure state when resuming runner iterations
Kail Tian5825e15a6fbf
diff --git a/nanobot/agent/runner.py b/nanobot/agent/runner.pyindex 4b62997c2..fc81d08a1 100644--- a/nanobot/agent/runner.py+++ b/nanobot/agent/runner.py@@ -430,6 +430,9 @@ class AgentRunner:await hook.on_stream_end(segment_context, resuming=True)for iteration in range(spec.max_iterations):+ # A resumed iteration must not inherit a previous iteration's failure.+ stop_reason = "completed"+ error = None# The session inbox cuts a finite snapshot before every model call.# This includes follow-ups that arrived before the first request and# messages received while the previous request or tools were running.diff --git a/tests/agent/test_runner_injections.py b/tests/agent/test_runner_injections.pyindex 96b56a59d..7ff09874c 100644--- a/tests/agent/test_runner_injections.py+++ b/tests/agent/test_runner_injections.py@@ -1833,6 +1833,86 @@ async def test_drain_injections_on_empty_final_response():assert len(injected) == 1[email protected]("failed_stop_reason", ["error", "empty_final_response"])+async def test_late_injection_recovery_completes_and_delivers_reply(failed_stop_reason):+ """Input arriving after failure bookkeeping must not poison a recovered turn."""+ from nanobot.agent.hook import AgentHook+ from nanobot.agent.runner import _MAX_EMPTY_RETRIES, AgentRunner+ from nanobot.agent.tools.registry import ToolRegistry+ from nanobot.agent.turn_delivery import TurnDeliveryFactory+ from nanobot.bus.events import InboundMessage, OutboundMessage+ from nanobot.bus.queue import MessageBus+ from nanobot.bus.runtime_events import TurnCompleted+ from nanobot.providers.base import LLMProvider++ failed_responses = (+ [LLMResponse(content="temporary failure", finish_reason="error")]+ if failed_stop_reason == "error"+ else [LLMResponse(content="") for _ in range(_MAX_EMPTY_RETRIES + 1)]+ )+ provider = MagicMock(spec=LLMProvider)+ provider.chat_stream_with_retry = AsyncMock(side_effect=[+ *failed_responses,+ LLMResponse(content="recovered answer"),+ ])+ injection_queue = asyncio.Queue()+ observed_failures = []++ class InjectAfterFailureHook(AgentHook):+ async def after_iteration(self, context) -> None:+ if context.stop_reason == failed_stop_reason and context.error is not None:+ observed_failures.append(context.error)+ # The earlier final-response drain has already run. Inject at+ # the late drain, after the runner has recorded the failure.+ await injection_queue.put(InboundMessage(+ channel="websocket",+ sender_id="user",+ chat_id="chat",+ content="Please retry now",+ ))++ hook = InjectAfterFailureHook()+ hook.on_error = AsyncMock()+ result = await AgentRunner().run(make_run_spec(provider,+ initial_messages=[{"role": "user", "content": "hello"}],+ tools=ToolRegistry(),+ model="test-model",+ max_iterations=_MAX_EMPTY_RETRIES + 2,+ max_tool_result_chars=_MAX_TOOL_RESULT_CHARS,+ injection_callback=_make_injection_callback(injection_queue),+ hook=hook,+ ))++ bus = MessageBus()+ completions: list[TurnCompleted] = []+ bus.subscribe(completions.append, TurnCompleted)+ msg = InboundMessage(+ channel="websocket", sender_id="user", chat_id="chat", content="hello",+ )+ delivery = TurnDeliveryFactory(bus).create(msg, msg.session_key)+ delivery.record_stop_reason(result.stop_reason, failure_error_kind=result.failure_error_kind)+ await delivery.complete(+ OutboundMessage(channel="websocket", chat_id="chat", content=result.final_content),+ publish_completion=True,+ )++ assert len(observed_failures) == 1+ assert provider.chat_stream_with_retry.await_count == len(failed_responses) + 1+ assert result.had_injections is True+ assert result.final_content == "recovered answer"+ assert bus.outbound_size == 1+ assert bus.outbound.get_nowait().content == "recovered answer"+ assert result.stop_reason == "completed"+ assert result.error is None+ assert result.failure_error_kind is None+ hook.on_error.assert_not_awaited()+ assert len(completions) == 1+ assert completions[0].outcome == "completed"+ assert completions[0].failure_kind is None+ assert completions[0].failure_error_kind is None++@pytest.mark.asyncioasync def test_max_iterations_without_finalization_keeps_late_injection_queued():"""Never consume a user message when no later model request can observe it."""