From 2b44088413840b3d149ae2032a10709e66fb2e95 Mon Sep 17 00:00:00 2001 From: chengyongru <2755839590@qq.com> Date: Fri, 30 Oct 2026 02:21:34 +0800 Subject: [PATCH] refactor(commands): own trusted Shell completion outside agent loop --- nanobot/agent/loop.py | 45 ------------ nanobot/command/builtin.py | 27 +------ nanobot/command/user_shell.py | 58 +++++++++++++++ tests/command/test_user_shell_command.py | 93 ++++++++++++++++++++---- 4 files changed, 140 insertions(+), 83 deletions(-) create mode 100644 nanobot/command/user_shell.py diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 6b54fa601..46461687f 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -34,7 +34,6 @@ from nanobot.agent.tools.file_state import FileStateStore, bind_file_states, res from nanobot.agent.tools.message import capture_message_deliveries from nanobot.agent.tools.registry import ToolRegistry from nanobot.agent.tools.runtime_control import AgentRuntimeControl -from nanobot.agent.tools.shell import ExecTool from nanobot.agent.turn_delivery import ( TurnDelivery, TurnDeliveryFactory, @@ -896,50 +895,6 @@ class AgentLoop: return await dispatch_and_publish() - async def execute_user_shell_command(self, ctx: CommandContext) -> OutboundMessage: - """Execute one trusted user command with the active workspace policy.""" - metadata = dict(ctx.msg.metadata or {}) - tool = self.tools.get("exec") - if not isinstance(tool, ExecTool): - content = "Shell execution is disabled in this nanobot configuration." - else: - session = ctx.session or await self.sessions.state.get(ctx.key) - scope = self.workspace_scopes.for_turn( - channel=ctx.msg.channel, - message_metadata=metadata, - session_metadata=session.metadata, - ) - request_token = bind_request_context(RequestContext( - channel=ctx.msg.channel, - chat_id=ctx.msg.chat_id, - message_id=metadata.get("message_id"), - session_key=ctx.key, - session_generation=session.generation, - original_user_text=f"!{ctx.args.strip()}", - runtime=ctx.runtime, - metadata=metadata, - sender_id=ctx.msg.sender_id, - turn_id=metadata.get("webui_turn_id"), - workspace=scope.project_path, - log_content=session.policy.log_content, - )) - workspace_token = bind_workspace_scope(scope) - try: - result = await tool.execute_to_completion( - command=ctx.args.strip(), - working_dir=str(scope.project_path), - ) - content = str(result) - finally: - reset_workspace_scope(workspace_token) - reset_request_context(request_token) - return OutboundMessage( - channel=ctx.msg.channel, - chat_id=ctx.msg.chat_id, - content=content, - metadata={**metadata, "render_as": "text"}, - ) - def _track_active_task(self, key: str, task: asyncio.Task[Any]) -> None: tasks = self._active_tasks.setdefault(key, set()) tasks.add(task) diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py index 8ea6deb2a..bb2c04f3d 100644 --- a/nanobot/command/builtin.py +++ b/nanobot/command/builtin.py @@ -11,10 +11,11 @@ from typing import TYPE_CHECKING, Any, cast from loguru import logger from nanobot import __version__ -from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage +from nanobot.bus.events import OutboundMessage from nanobot.command.router import CommandContext, CommandRouter from nanobot.command.spec import BuiltinCommandSpec from nanobot.command.spec import CommandLifecycle as CommandLifecycle +from nanobot.command.user_shell import cmd_user_shell from nanobot.providers.base import LLMUsage from nanobot.utils.cancellation import shield_and_drain from nanobot.utils.helpers import build_status_content @@ -924,30 +925,6 @@ async def cmd_help(ctx: CommandContext) -> OutboundMessage: ) -async def cmd_user_shell(ctx: CommandContext) -> OutboundMessage: - """Run a trusted local ``!command`` through nanobot's exec policy.""" - metadata = dict(ctx.msg.metadata or {}) - if ( - ctx.msg.channel != "websocket" - or metadata.get("webui") is not True - or metadata.get(INBOUND_META_USER_SHELL) is not True - ): - return OutboundMessage( - channel=ctx.msg.channel, - chat_id=ctx.msg.chat_id, - content="Shell commands are only available from a trusted local client.", - metadata={**metadata, "render_as": "text"}, - ) - if not ctx.args.strip(): - return OutboundMessage( - channel=ctx.msg.channel, - chat_id=ctx.msg.chat_id, - content="Type a command after `!`, for example `!pwd`.", - metadata={**metadata, "render_as": "text"}, - ) - return await ctx.loop.execute_user_shell_command(ctx) - - def build_help_text(specs: tuple[BuiltinCommandSpec, ...] = CORE_COMMAND_SPECS) -> str: """Build help text for the commands registered in one application.""" lines = ["🐈 nanobot commands:"] diff --git a/nanobot/command/user_shell.py b/nanobot/command/user_shell.py new file mode 100644 index 000000000..b7fc4fb25 --- /dev/null +++ b/nanobot/command/user_shell.py @@ -0,0 +1,58 @@ +"""Trusted user Shell commands, outside model-turn execution policy.""" + +from nanobot.agent.tools.context import RequestContext, bind_request_context, reset_request_context +from nanobot.agent.tools.shell import ExecTool +from nanobot.bus.events import INBOUND_META_USER_SHELL, OutboundMessage +from nanobot.command.router import CommandContext +from nanobot.security.workspace_access import bind_workspace_scope, reset_workspace_scope + + +async def cmd_user_shell(ctx: CommandContext) -> OutboundMessage: + """Run a trusted local command to completion under its admitted policy.""" + metadata = dict(ctx.msg.metadata or {}) + command = ctx.args.strip() + if ( + ctx.msg.channel != "websocket" + or metadata.get("webui") is not True + or metadata.get(INBOUND_META_USER_SHELL) is not True + ): + content = "Shell commands are only available from a trusted local client." + elif not command: + content = "Type a command after `!`, for example `!pwd`." + elif not isinstance(tool := ctx.loop.tools.get("exec"), ExecTool): + content = "Shell execution is disabled in this nanobot configuration." + else: + session = ctx.session or await ctx.loop.sessions.state.get(ctx.key) + scope = ctx.loop.workspace_scopes.for_turn( + channel=ctx.msg.channel, + message_metadata=metadata, + session_metadata=session.metadata, + ) + request_token = bind_request_context(RequestContext( + channel=ctx.msg.channel, + chat_id=ctx.msg.chat_id, + message_id=metadata.get("message_id"), + session_key=ctx.key, + session_generation=session.generation, + original_user_text=f"!{command}", + runtime=ctx.runtime, + metadata=metadata, + sender_id=ctx.msg.sender_id, + turn_id=metadata.get("webui_turn_id"), + workspace=scope.project_path, + log_content=session.policy.log_content, + )) + workspace_token = bind_workspace_scope(scope) + try: + # A trusted user command owns the complete result. The model's + # bounded observation/exec_session behavior remains in its tool. + content = str(await tool.execute_to_completion( + command=command, working_dir=str(scope.project_path), + )) + finally: + reset_workspace_scope(workspace_token) + reset_request_context(request_token) + return OutboundMessage( + channel=ctx.msg.channel, chat_id=ctx.msg.chat_id, content=content, + metadata={**metadata, "render_as": "text"}, + ) diff --git a/tests/command/test_user_shell_command.py b/tests/command/test_user_shell_command.py index b928a207b..8c81fd286 100644 --- a/tests/command/test_user_shell_command.py +++ b/tests/command/test_user_shell_command.py @@ -4,12 +4,11 @@ from unittest.mock import AsyncMock, MagicMock import pytest -from nanobot.agent.loop import AgentLoop from nanobot.agent.tools.context import current_request_context from nanobot.agent.tools.shell import ExecTool -from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage, OutboundMessage -from nanobot.command.builtin import cmd_user_shell +from nanobot.bus.events import INBOUND_META_USER_SHELL, InboundMessage from nanobot.command.router import CommandContext +from nanobot.command.user_shell import cmd_user_shell from nanobot.session.manager import Session, SessionPolicy @@ -38,12 +37,11 @@ def _context(loop: MagicMock, *, trusted: bool, command: str = "pwd") -> Command @pytest.mark.asyncio async def test_user_shell_rejects_untrusted_transport_metadata() -> None: loop = MagicMock() - loop.execute_user_shell_command = AsyncMock() response = await cmd_user_shell(_context(loop, trusted=False)) assert "trusted local client" in response.content - loop.execute_user_shell_command.assert_not_awaited() + loop.tools.get.assert_not_called() @pytest.mark.asyncio @@ -71,7 +69,7 @@ async def test_user_shell_uses_exec_tool_with_workspace_scope( if context_session: ctx.session = session - response = await AgentLoop.execute_user_shell_command(loop, ctx) + response = await cmd_user_shell(ctx) tool.execute_to_completion.assert_awaited_once_with(command="pwd", working_dir=str(tmp_path)) assert response.content.endswith("Exit code: 0") @@ -80,13 +78,82 @@ async def test_user_shell_uses_exec_tool_with_workspace_scope( @pytest.mark.asyncio -async def test_user_shell_delegates_trusted_request_to_agent_loop() -> None: +@pytest.mark.parametrize("command, disabled", [("", False), ("pwd", True)]) +async def test_user_shell_reports_missing_command_or_disabled_execution(command, disabled) -> None: loop = MagicMock() - expected = OutboundMessage(channel="websocket", chat_id="chat", content="ok") - loop.execute_user_shell_command = AsyncMock(return_value=expected) - ctx = _context(loop, trusted=True, command="printf ok") + loop.tools.get.return_value = None + response = await cmd_user_shell(_context(loop, trusted=True, command=command)) + assert ("disabled" if disabled else "Type a command") in response.content + loop.sessions.state.get.assert_not_called() - response = await cmd_user_shell(ctx) - assert response is expected - loop.execute_user_shell_command.assert_awaited_once_with(ctx) +@pytest.mark.asyncio +async def test_user_command_keeps_waiting_for_full_result_while_model_observation_is_bounded(tmp_path): + import shlex + import sys + + from nanobot.agent.loop import AgentLoop + from nanobot.agent.tools.exec_session import ExecSessionManager + from nanobot.bus.queue import MessageBus + from nanobot.security.workspace_access import default_workspace_scope + + manager = ExecSessionManager() + tool = ExecTool(working_dir=str(tmp_path), session_manager=manager) + snippet = 'import time; print("first", flush=True); time.sleep(.15); print("last")' + command = f"{shlex.quote(sys.executable)} -I -c {shlex.quote(snippet)}" + provider = MagicMock(aclose=AsyncMock()) + provider.get_default_model.return_value = "unused-model" + loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path) + loop.tools.register(tool) + ctx = _context(loop, trusted=True, command=command) + scope = default_workspace_scope(tmp_path, False, source_channel="websocket") + ctx.session = Session(key=ctx.key, metadata={"workspace_scope": scope.metadata()}) + try: + bounded = await tool.execute(command=command, yield_time_ms=0) + assert "Process running" in bounded + response = await cmd_user_shell(ctx) + assert "first" in response.content and "last" in response.content + assert "Exit code: 0" in response.content and response.metadata["render_as"] == "text" + assert current_request_context() is None + finally: + await manager.close_all() + await loop.aclose() + + +@pytest.mark.asyncio +async def test_shell_cancellation_unwinds_workspace_and_request_context(tmp_path): + import asyncio + + from nanobot.security.workspace_access import current_workspace_scope, default_workspace_scope + + entered, release = asyncio.Event(), asyncio.Event() + scope = default_workspace_scope(tmp_path, False, source_channel="websocket") + after_cancel = [] + + async def execute(**kwargs): + entered.set() + assert current_request_context().session_key == "websocket:chat" + assert current_workspace_scope() is scope + await release.wait() + return "not reached" + + tool = MagicMock(spec=ExecTool) + tool.execute_to_completion = AsyncMock(side_effect=execute) + loop = MagicMock() + loop.tools.get.return_value = tool + loop.workspace_scopes.for_turn.return_value = scope + ctx = _context(loop, trusted=True) + ctx.session = Session(key=ctx.key) + + async def run_command(): + try: + await cmd_user_shell(ctx) + finally: + after_cancel.append((current_request_context(), current_workspace_scope())) + + task = asyncio.create_task(run_command()) + await entered.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + assert after_cancel == [(None, None)]