diff --git a/docs/architecture.md b/docs/architecture.md index 97afb09f7..cb372afcc 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -55,6 +55,8 @@ MCP connections are application-owned infrastructure. Composition roots create a Keep this split in mind when debugging. If a problem is about channel routing, session keys, workspace selection, or outbound delivery, start in `agent/loop.py`. If it is about provider calls, tool calls, streaming, or iteration limits, start in `agent/runner.py`. +After a terminal tool-iteration limit, the next ordinary turn receives a short runtime-context note to follow the current request and resume unfinished work only when asked. `session/turn_continuation.py` owns this budget-stop context; a queued Goal continuation is not a terminal stop. The note is stored with that input for stable model-history replay but is hidden from display history. Tool calls and results remain intact. New or forked histories do not inherit the pending note. This is model guidance, not a tool-execution ban or a fix for sudo authentication. + ## Providers Provider metadata is centralized in `nanobot/providers/registry.py`. Configuration fields live in `nanobot/config/schema.py`. diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index b2a7734d9..57661e120 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -660,6 +660,9 @@ class AgentLoop: runtime_control = AgentRuntimeControl(self) self.register_runtime_context_provider(runtime_control.workspace_context) + self.register_runtime_context_provider( + partial(turn_continuation.iteration_limit_context, self.sessions.state), + ) ctx = ToolContext( config=self.tools_config, network=self.network_config, @@ -2379,6 +2382,11 @@ class AgentLoop: turn_continuation.prepare_save_boundary(ctx) if ctx.usage is not None and not ctx.ephemeral: session.metadata["_last_usage"] = ctx.usage.to_dict() + if ctx.kind is TurnKind.USER and not ctx.ephemeral: + turn_continuation.record_iteration_limit( + session.metadata, ctx.stop_reason, + continuation_pending=ctx.delivery.continuation_pending, + ) self._save_turn( session, ctx.all_messages, ctx.save_skip, turn_latency_ms=ctx.turn_latency_ms, diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 28ddd182f..00724f05d 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -43,6 +43,7 @@ _SESSION_PREVIEW_MAX_CHARS = 120 _SESSION_LIST_PREVIEW_MAX_RECORDS = 200 _SESSION_LIST_PREVIEW_MAX_CHARS = 1_000_000 _FORK_VOLATILE_METADATA_KEYS = { + "_stopped_at_iteration_limit", PARENT_SESSION_KEY, SESSION_TYPE_KEY, "goal_state", @@ -353,6 +354,7 @@ class Session: self.provider_state = None self.updated_at = datetime.now() self.metadata.pop("_last_summary", None) + self.metadata.pop("_stopped_at_iteration_limit", None) class SessionPayload(TypedDict): key: str diff --git a/nanobot/session/state.py b/nanobot/session/state.py index 7d5c33ac0..31cd7e3f1 100644 --- a/nanobot/session/state.py +++ b/nanobot/session/state.py @@ -1119,7 +1119,7 @@ class SessionState: if old is not None: session.policy = old.policy session.metadata = deepcopy(old.metadata) - for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary"): + for name in (*_RESERVED_KEYS, "webui_recovery", "_last_summary", "_stopped_at_iteration_limit"): session.metadata.pop(name, None) if session.policy.persist: self._store.delete(key) diff --git a/nanobot/session/turn_continuation.py b/nanobot/session/turn_continuation.py index 5806f6ec2..1a6cf6f92 100644 --- a/nanobot/session/turn_continuation.py +++ b/nanobot/session/turn_continuation.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, Mapping, MutableMapping from loguru import logger +from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines from nanobot.session.goal_state import ( goal_state_runtime_lines, sustained_goal_active, @@ -21,11 +22,14 @@ from nanobot.session.recovery import REQUEST_ORIGIN_METADATA_KEY if TYPE_CHECKING: from nanobot.agent.loop import TurnContext + from nanobot.agent.tools.context import RequestContext + from nanobot.session.state import SessionState INTERNAL_CONTINUATION_META = "_internal_continuation" INTERNAL_CONTINUATION_KIND_META = "_internal_continuation_kind" INTERNAL_CONTINUATION_RUN_STARTED_AT_META = "_internal_continuation_run_started_at" SKIP_USER_PERSIST_META = "_skip_user_persist" +_ITERATION_LIMIT_META = "_stopped_at_iteration_limit" _GOAL_CONTINUATION_KIND = "sustained_goal" _GOAL_CONTINUATION_SENDER = "system:continuation" @@ -37,6 +41,37 @@ _STRIPPED_INBOUND_META_KEYS = { } +def record_iteration_limit( + metadata: MutableMapping[str, Any], stop_reason: str, *, continuation_pending: bool, +) -> None: + """Remember a terminal budget stop, not an internal continuation handoff.""" + if stop_reason == "max_iterations" and not continuation_pending: + metadata[_ITERATION_LIMIT_META] = True + else: + metadata.pop(_ITERATION_LIMIT_META, None) + + +async def iteration_limit_context( + state: SessionState, request: RequestContext, +) -> RuntimeContextBlock | None: + """Attach the previous terminal budget outcome to the new input suffix.""" + if not request.session_key or not request.persist_session: + return None + if internal_continuation_inbound(request.metadata): + return None + payload = await state.read_metadata(request.session_key) + if payload is None or not payload["metadata"].get(_ITERATION_LIMIT_META): + return None + return RuntimeContextBlock( + source="iteration_limit", + content=wrap_runtime_context_lines([ + "The previous turn stopped at the tool-iteration limit without finishing its work.", + "Follow the current request. Resume unfinished work only if the user asks for it.", + "Completed tool calls and their results remain in the history; do not repeat them blindly.", + ]), + ) + + def internal_continuation_inbound(metadata: Mapping[str, Any] | None) -> bool: """True for an inbound message created by an internal continuation policy.""" return bool(metadata and metadata.get(INTERNAL_CONTINUATION_META) is True) diff --git a/tests/agent/test_loop_iteration_limit.py b/tests/agent/test_loop_iteration_limit.py new file mode 100644 index 000000000..f41dc4489 --- /dev/null +++ b/tests/agent/test_loop_iteration_limit.py @@ -0,0 +1,179 @@ +"""Regression tests for turns that stop at the tool-iteration limit (#5924).""" + +from __future__ import annotations + +import asyncio +import json +from copy import deepcopy +from typing import Any +from unittest.mock import AsyncMock + +import pytest + +from nanobot.agent.loop import AgentLoop +from nanobot.bus.events import InboundMessage +from nanobot.bus.queue import MessageBus +from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest +from nanobot.runtime_context import public_history_messages +from nanobot.session.goal_state import GOAL_STATE_KEY + +_STOP_MARKER = "previous turn stopped at the tool-iteration limit" + + +class BudgetProvider(LLMProvider): + def __init__(self, requests): + super().__init__(provider_name="offline-budget-test") + self.requests = requests + self.schemas = [] + + def get_default_model(self): + return "test-model" + + async def chat(self, messages, tools=None, **kwargs): + self.requests.append(deepcopy(self._sanitize_empty_content(messages))) + self.schemas.append(deepcopy(tools)) + last_user = next(m for m in reversed(messages) if m.get("role") == "user") + if str(last_user.get("content")).startswith("run the tests") and tools is not None: + return LLMResponse( + content="running", + tool_calls=[ + ToolCallRequest( + id=f"call_{len(self.requests)}", + name="exec", + arguments={"command": "make test"}, + ) + ], + ) + return LLMResponse(content="done", tool_calls=[]) + + +def _make_loop(tmp_path, requests: list[list[dict[str, Any]]]) -> AgentLoop: + loop = AgentLoop( + bus=MessageBus(), + provider=BudgetProvider(requests), + workspace=tmp_path, + model="test-model", + context_window_tokens=128_000, + max_iterations=2, + ) + exec_tool = loop.tools.get("exec") + assert exec_tool is not None + exec_tool.execute = AsyncMock(return_value="Error: make test failed") + return loop + + +def _last_user_content(messages: list[dict[str, Any]]) -> str: + return str(next(m for m in reversed(messages) if m.get("role") == "user")["content"]) + + +async def test_next_turn_is_told_not_to_resume_after_iteration_limit(tmp_path): + requests: list[list[dict[str, Any]]] = [] + loop = _make_loop(tmp_path, requests) + try: + await loop.process_direct("run the tests", session_key="cli:limit") + assert _STOP_MARKER not in _last_user_content(requests[0]) + + await loop.process_direct("what is 2 + 2?", session_key="cli:limit") + assert _STOP_MARKER in _last_user_content(requests[-1]) + + # Later inputs get no new marker; the earlier marked input stays in history. + await loop.process_direct("thanks", session_key="cli:limit") + assert _STOP_MARKER not in _last_user_content(requests[-1]) + assert _STOP_MARKER in json.dumps(requests[-1]) + finally: + await loop.aclose() + + +async def test_stop_survives_restart_and_keeps_history_prefix(tmp_path): + previous: list[list[dict[str, Any]]] = [] + loop = _make_loop(tmp_path, previous) + try: + await loop.process_direct("hello", session_key="cli:limit") + await loop.process_direct("run the tests", session_key="cli:limit") + schemas = loop.provider.schemas + finally: + await loop.aclose() + + current: list[list[dict[str, Any]]] = [] + loop = _make_loop(tmp_path, current) + try: + await loop.process_direct("what is 2 + 2?", session_key="cli:limit") + assert _STOP_MARKER in _last_user_content(current[0]) + # Ordinary prefix and tool schemas are unchanged. Structured failed calls remain. + assert json.dumps(previous[0]) == json.dumps(current[0][:len(previous[0])]) + assert schemas[0] == loop.provider.schemas[0] + assert [m for m in previous[-1] if m["role"] == "tool"] == [ + m for m in current[0] if m["role"] == "tool" + ] + await loop.process_direct("thanks", session_key="cli:limit") + assert json.dumps(current[0]) == json.dumps(current[1][:len(current[0])]) + assert _STOP_MARKER not in _last_user_content(current[1]) + session = await loop.sessions.state.get("cli:limit") + assert _STOP_MARKER not in json.dumps(public_history_messages(session.messages)) + + # Another session must not inherit this stopped turn. + await loop.process_direct("hello", session_key="cli:other") + assert _STOP_MARKER not in json.dumps(current[-1]) + finally: + await loop.aclose() + + +async def test_goal_budget_handoff_is_not_an_abandoned_turn(tmp_path): + requests: list[list[dict[str, Any]]] = [] + loop = _make_loop(tmp_path, requests) + pending: asyncio.Queue[InboundMessage] = asyncio.Queue() + try: + await loop.sessions.state.get("cli:goal") + await loop.sessions.state.update_metadata("cli:goal", { + GOAL_STATE_KEY: {"status": "active", "objective": "run the tests"}, + }) + await loop._process_message( + InboundMessage(channel="cli", sender_id="user", chat_id="goal", content="run the tests"), + pending_queue=pending, + ) + continuation = pending.get_nowait() + assert continuation.sender_id == "system:continuation" + + # A new user input can run before the already queued goal continuation. + next_request = len(requests) + await loop.process_direct("give me a progress update", session_key="cli:goal") + assert _STOP_MARKER not in _last_user_content(requests[next_request]) + next_request = len(requests) + await loop._process_message(continuation, pending_queue=pending) + assert _STOP_MARKER not in _last_user_content(requests[next_request]) + finally: + await loop.aclose() + + +@pytest.mark.parametrize("operation", ["reset", "fork"]) +async def test_new_history_does_not_inherit_abandoned_turn(tmp_path, operation): + requests: list[list[dict[str, Any]]] = [] + loop = _make_loop(tmp_path, requests) + try: + await loop.process_direct("run the tests", session_key="cli:limit") + target = "cli:limit" + if operation == "reset": + await loop.process_direct("/new", session_key=target) + else: + target = "cli:fork" + await loop.sessions.state.fork("cli:limit", target, before_user_index=0) + await loop.process_direct("hello", session_key=target) + assert _STOP_MARKER not in _last_user_content(requests[-1]) + finally: + await loop.aclose() + + +async def test_temporary_turn_skips_hint_and_explicit_retry_can_use_tools(tmp_path): + requests: list[list[dict[str, Any]]] = [] + loop = _make_loop(tmp_path, requests) + try: + await loop.process_direct("run the tests", session_key="cli:limit") + await loop.process_direct("hello", session_key="cli:limit", ephemeral=True) + assert _STOP_MARKER not in _last_user_content(requests[-1]) + next_request = len(requests) + await loop.process_direct("run the tests again", session_key="cli:limit") + assert _STOP_MARKER in _last_user_content(requests[next_request]) + assert "only if the user asks" in _last_user_content(requests[next_request]) + assert loop.tools.get("exec").execute.await_count == 4 + finally: + await loop.aclose()