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
Merge origin/main into feat/session-replay-file-cap-invariants
Xubin Ren29ebc2d3552e
diff --cc nanobot/agent/loop.pyindex 06e0a3ad8,f2ec1e252..3c936a85f--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@@ -892,11 -863,11 +924,15 @@@ class AgentLoopis_subagent = msg.sender_id == "subagent"if is_subagent and self._persist_subagent_followup(session, msg):self.sessions.save(session)- self._set_tool_context(channel, chat_id, msg.metadata.get("message_id"))+ self._set_tool_context(+ channel, chat_id, msg.metadata.get("message_id"),+ msg.metadata, session_key=key,+ )- history = session.get_history(max_messages=0, include_timestamps=True)+ history = session.get_history(+ max_messages=self.session_history_max_messages,+ max_tokens=self._history_token_budget(),++ include_timestamps=True,+ )current_role = "assistant" if is_subagent else "user"# Subagent content is already in `history` above; passing it again@@@ -966,10 -950,7 +1016,11 @@@if isinstance(message_tool, MessageTool):message_tool.start_turn()- history = session.get_history(max_messages=0, include_timestamps=True)+ history = session.get_history(+ max_messages=self.session_history_max_messages,+ max_tokens=self._history_token_budget(),++ include_timestamps=True,+ )pending_ask_id = pending_ask_user_id(history)if pending_ask_id:diff --cc nanobot/session/manager.pyindex 8d98bf8e6,d04798944..93d96c607--- a/nanobot/session/manager.py+++ b/nanobot/session/manager.py@@@ -46,13 -71,9 +72,14 @@@ class Sessionself,max_messages: int = 500,*,+ max_tokens: int = 0,+ include_timestamps: bool = False,) -> list[dict[str, Any]]:- """Return unconsolidated messages for LLM input, aligned to a legal tool-call boundary."""+ """Return unconsolidated messages for LLM input.++ History is sliced by message count first (``max_messages``), then by+ token budget from the tail (``max_tokens``) when provided.+ """unconsolidated = self.messages[self.last_consolidated:]sliced = unconsolidated[-max_messages:]diff --cc tests/agent/test_auto_compact.pyindex 91ca09e6c,1f6886ed0..b3b5a07db--- a/tests/agent/test_auto_compact.py+++ b/tests/agent/test_auto_compact.py@@@ -123,109 -86,6 +123,113 @@@ class TestAgentLoopTTLParamloop = _make_loop(tmp_path, session_ttl_minutes=0)assert loop.auto_compact._ttl == 0+ def test_loop_stores_history_window(self, tmp_path):+ """AgentLoop should store configured session history max_messages."""+ loop = _make_loop(tmp_path, session_history_max_messages=42)+ assert loop.session_history_max_messages == 42++ def test_loop_stores_history_token_budget(self, tmp_path):+ loop = _make_loop(tmp_path, session_history_max_tokens=2048)+ assert loop.session_history_max_tokens == 2048++ def test_loop_stores_session_file_cap(self, tmp_path):+ loop = _make_loop(tmp_path, session_file_max_messages=512)+ assert loop.session_file_max_messages == 512++ @pytest.mark.asyncio+ async def test_process_message_reads_history_with_configured_cap(self, tmp_path):+ """_process_message should use session_history_max_messages, not unlimited history."""+ loop = _make_loop(tmp_path, session_history_max_messages=7)+ session = loop.sessions.get_or_create("cli:direct")+ session.get_history = MagicMock(return_value=[])+ loop.context.build_messages = MagicMock(return_value=[])+ loop._run_agent_loop = AsyncMock(return_value=("ok", [], [], "stop", False))+ loop._save_turn = MagicMock()++ msg = InboundMessage(+ channel="cli",+ sender_id="u1",+ chat_id="direct",+ content="hello",+ )+ await loop._process_message(msg)+ session.get_history.assert_called_once()+ kwargs = session.get_history.call_args.kwargs+ assert kwargs["max_messages"] == 7+ assert isinstance(kwargs.get("max_tokens"), int)++ @pytest.mark.asyncio+ async def test_process_message_reads_history_with_token_budget(self, tmp_path):+ loop = _make_loop(+ tmp_path,+ session_history_max_messages=7,+ session_history_max_tokens=333,+ )+ session = loop.sessions.get_or_create("cli:direct")+ session.get_history = MagicMock(return_value=[])+ loop.context.build_messages = MagicMock(return_value=[])+ loop._run_agent_loop = AsyncMock(return_value=("ok", [], [], "stop", False))+ loop._save_turn = MagicMock()++ msg = InboundMessage(+ channel="cli",+ sender_id="u1",+ chat_id="direct",+ content="hello",+ )+ await loop._process_message(msg)- session.get_history.assert_called_once_with(max_messages=7, max_tokens=333)++ session.get_history.assert_called_once_with(++ max_messages=7,++ max_tokens=333,++ include_timestamps=True,++ )++ @pytest.mark.asyncio+ async def test_session_file_cap_archives_and_trims_old_messages(self, tmp_path):+ loop = _make_loop(tmp_path, session_file_max_messages=6)+ loop.context.memory.raw_archive = MagicMock()++ for i in range(4):+ msg = InboundMessage(+ channel="cli",+ sender_id="u1",+ chat_id="direct",+ content=f"hello {i}",+ )+ await loop._process_message(msg)++ session = loop.sessions.get_or_create("cli:direct")+ assert len(session.messages) <= 6+ assert loop.context.memory.raw_archive.called++ def test_session_file_cap_skips_raw_archive_when_dropped_prefix_is_already_consolidated(self, tmp_path):+ loop = _make_loop(tmp_path, session_file_max_messages=4)+ loop.context.memory.raw_archive = MagicMock()+ session = loop.sessions.get_or_create("cli:direct")+ for i in range(8):+ session.add_message("user", f"u{i}")+ session.last_consolidated = 6++ loop._enforce_session_file_cap(session)++ assert len(session.messages) <= 4+ loop.context.memory.raw_archive.assert_not_called()++ def test_session_file_cap_archives_only_unconsolidated_part_of_dropped_prefix(self, tmp_path):+ loop = _make_loop(tmp_path, session_file_max_messages=4)+ loop.context.memory.raw_archive = MagicMock()+ session = loop.sessions.get_or_create("cli:direct")+ for i in range(8):+ session.add_message("user", f"u{i}")+ session.last_consolidated = 2++ loop._enforce_session_file_cap(session)++ assert len(session.messages) <= 4+ loop.context.memory.raw_archive.assert_called_once()+ archived = loop.context.memory.raw_archive.call_args.args[0]+ assert [m["content"] for m in archived] == ["u2", "u3"]+class TestAutoCompact:"""Test the _archive method."""