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): bound per-session file state
yu-xin-c42afebb0cb3e
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex 253247168..67b7c7f04 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -76,6 +76,7 @@ from nanobot.session.goal_state import (from nanobot.session.history_visibility import HIDDEN_HISTORY_METAfrom nanobot.session.keys import UNIFIED_SESSION_KEY, remember_last_channelfrom nanobot.session.manager import (+ SESSION_CACHE_MAX_SIZE,Session,SessionManager,replay_max_messages_for_context,@@ -380,7 +381,7 @@ class AgentLoop:self.tools = tool_registry if tool_registry is not None else ToolRegistry()# One file-read/write tracker per logical session. The tool registry is# shared by this loop, so tools resolve the active state via contextvars.- self._file_state_store = FileStateStore()+ self._file_state_store = FileStateStore(max_sessions=SESSION_CACHE_MAX_SIZE)self._exec_session_manager = ExecSessionManager()self.runner = AgentRunner()self.subagents = SubagentManager(@@ -818,8 +819,13 @@ class AgentLoop:self.sessions.invalidate(key)await self._cancel_active_tasks(key)finally:+ self.discard_session_file_state(key)self._discarding_sessions.discard(key)+ def discard_session_file_state(self, key: str) -> None:+ """Forget ephemeral file-read state for a reset or removed session."""+ self._file_state_store.discard(key)+def _effective_session_key(self, msg: InboundMessage) -> str:"""Return the session key used for task routing and mid-turn injections."""if self._unified_session and not msg.session_key_override:diff --git a/nanobot/agent/tools/file_state.py b/nanobot/agent/tools/file_state.pyindex 3dd4667d5..811981913 100644--- a/nanobot/agent/tools/file_state.py+++ b/nanobot/agent/tools/file_state.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport hashlibimport os+from collections import OrderedDictfrom contextvars import ContextVar, Tokenfrom dataclasses import dataclassfrom pathlib import Path@@ -135,21 +136,30 @@ class FileStates:class FileStateStore:- """Lookup table for per-session file read/write state."""+ """Bounded lookup table for per-session file read/write state."""- __slots__ = ("_states_by_key",)+ __slots__ = ("_max_sessions", "_states_by_key")- def __init__(self) -> None:- self._states_by_key: dict[str, FileStates] = {}+ def __init__(self, *, max_sessions: int = 128) -> None:+ if max_sessions <= 0:+ raise ValueError("max_sessions must be positive")+ self._max_sessions = max_sessions+ self._states_by_key: OrderedDict[str, FileStates] = OrderedDict()def for_session(self, session_key: str | None) -> FileStates:key = session_key or "__default__"- states = self._states_by_key.get(key)+ states = self._states_by_key.pop(key, None)if states is None:states = FileStates()- self._states_by_key[key] = states+ self._states_by_key[key] = states+ while len(self._states_by_key) > self._max_sessions:+ self._states_by_key.popitem(last=False)return states+ def discard(self, session_key: str | None) -> None:+ """Forget file state when a session is reset or removed."""+ self._states_by_key.pop(session_key or "__default__", None)+def clear(self) -> None:self._states_by_key.clear()diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.pyindex 7ef7c6368..c5fe59105 100644--- a/nanobot/command/builtin.py+++ b/nanobot/command/builtin.py@@ -302,6 +302,7 @@ async def cmd_new(ctx: CommandContext) -> OutboundMessage:"""Stop active task and start a fresh session."""loop = ctx.loopawait loop._cancel_active_tasks(ctx.key) # pyright: ignore[reportPrivateUsage]+ loop.discard_session_file_state(ctx.key)session = ctx.session or loop.sessions.get_or_create(ctx.key)snapshot = session.messages[session.last_consolidated:]runtime = Nonediff --git a/nanobot/sdk/clients.py b/nanobot/sdk/clients.pyindex a1d189af3..52fb22ce8 100644--- a/nanobot/sdk/clients.py+++ b/nanobot/sdk/clients.py@@ -138,6 +138,7 @@ class SessionClient:def clear(self, session_key: str) -> SessionSnapshot:"""Clear one session and persist the empty session."""+ self._loop.discard_session_file_state(session_key)session = self._loop.sessions.get_or_create(session_key)session.clear()self._loop.sessions.save(session)@@ -145,6 +146,7 @@ class SessionClient:def delete(self, session_key: str) -> bool:"""Delete one session from disk and cache."""+ self._loop.discard_session_file_state(session_key)return self._loop.sessions.delete_session(session_key)def flush(self) -> int:diff --git a/tests/agent/test_loop_session_policy.py b/tests/agent/test_loop_session_policy.pyindex 3a2a065f5..adee6817b 100644--- a/tests/agent/test_loop_session_policy.py+++ b/tests/agent/test_loop_session_policy.py@@ -131,6 +131,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatchterminate_exec_sessions,)key = "websocket:transient-cancelled"+ previous_file_state = loop._file_state_store.for_session(key)loop.sessions.get_or_create_transient(key,disabled_tools={"create_goal", "update_goal", "spawn", "cron"},@@ -157,6 +158,7 @@ async def test_session_discard_control_cancels_active_turn(tmp_path, monkeypatchawait asyncio.wait_for(active_task, timeout=2)await asyncio.wait_for(wait_for_discard(key), timeout=2)assert loop.sessions.get_cached(key) is None+ assert loop._file_state_store.for_session(key) is not previous_file_stateterminate_exec_sessions.assert_awaited_once_with(key)loop.stop()diff --git a/tests/agent/test_unified_session.py b/tests/agent/test_unified_session.pyindex 7c0656ec2..1acede1c6 100644--- a/tests/agent/test_unified_session.py+++ b/tests/agent/test_unified_session.py@@ -20,6 +20,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom nanobot.agent.loop import AgentLoop+from nanobot.agent.tools.file_state import FileStateStorefrom nanobot.bus.events import InboundMessagefrom nanobot.bus.queue import MessageBusfrom nanobot.command.builtin import cmd_new, register_builtin_commands@@ -250,10 +251,16 @@ class TestCmdNewUnifiedSession:# asyncio.create_task(). Mirror that exactly so the coroutine is consumed# and no RuntimeWarning is emitted.admitted_runtime = MagicMock(name="admitted_runtime")+ file_state_store = FileStateStore()+ previous_file_state = file_state_store.for_session("unified:default")+ tracked_file = tmp_path / "tracked.txt"+ tracked_file.write_text("tracked", encoding="utf-8")+ previous_file_state.record_read(tracked_file)loop = SimpleNamespace(sessions=sessions,consolidator=SimpleNamespace(archive=AsyncMock(return_value=True)),_cancel_active_tasks=AsyncMock(return_value=0),+ discard_session_file_state=file_state_store.discard,llm_runtime=MagicMock(return_value=MagicMock()),schedule_background=lambda coro: asyncio.ensure_future(coro),)@@ -278,6 +285,9 @@ class TestCmdNewUnifiedSession:sessions.invalidate("unified:default")reloaded = sessions.get_or_create("unified:default")assert reloaded.messages == []+ reset_file_state = file_state_store.for_session("unified:default")+ assert reset_file_state is not previous_file_state+ assert reset_file_state.is_unchanged(tracked_file) is Falseloop.consolidator.archive.assert_called_once_with(expected_snapshot,runtime=admitted_runtime,@@ -302,6 +312,7 @@ class TestCmdNewUnifiedSession:sessions=sessions,consolidator=SimpleNamespace(archive=AsyncMock(return_value=True)),_cancel_active_tasks=AsyncMock(return_value=0),+ discard_session_file_state=MagicMock(),runtime_for_session=MagicMock(return_value=MagicMock()),schedule_background=lambda coro: asyncio.ensure_future(coro),)diff --git a/tests/test_nanobot_facade.py b/tests/test_nanobot_facade.pyindex dfddf7150..d3ef4d233 100644--- a/tests/test_nanobot_facade.py+++ b/tests/test_nanobot_facade.py@@ -1500,10 +1500,15 @@ async def test_session_helpers_get_list_export_clear_delete_flush(tmp_path):exported.messages[0]["content"] = "mutated copy"assert bot.sessions.get("sdk:first").messages[0]["content"] == "hello"+ state_before_clear = bot._loop._file_state_store.for_session("sdk:first")cleared = bot.sessions.clear("sdk:first")assert cleared.messages == []+ state_after_clear = bot._loop._file_state_store.for_session("sdk:first")+ assert state_after_clear is not state_before_clearassert bot.sessions.flush() >= 1+ state_before_delete = state_after_clearassert bot.sessions.delete("sdk:first") is True+ assert bot._loop._file_state_store.for_session("sdk:first") is not state_before_deleteassert bot.sessions.get("sdk:first") is Nonediff --git a/tests/tools/test_file_state_store.py b/tests/tools/test_file_state_store.pynew file mode 100644index 000000000..2d241ef51--- /dev/null+++ b/tests/tools/test_file_state_store.py@@ -0,0 +1,29 @@+import pytest++from nanobot.agent.tools.file_state import FileStateStore+++def test_file_state_store_evicts_least_recently_used_session() -> None:+ store = FileStateStore(max_sessions=2)+ first = store.for_session("first")+ second = store.for_session("second")++ assert store.for_session("first") is first+ store.for_session("third")++ assert store.for_session("first") is first+ assert store.for_session("second") is not second+++def test_file_state_store_discards_reset_session() -> None:+ store = FileStateStore()+ previous = store.for_session("websocket:chat")++ store.discard("websocket:chat")++ assert store.for_session("websocket:chat") is not previous+++def test_file_state_store_requires_positive_capacity() -> None:+ with pytest.raises(ValueError, match="max_sessions must be positive"):+ FileStateStore(max_sessions=0)