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(my): report current workspace access in self-inspection
Xubin Rene79a0099f634
diff --git a/docs/configuration.md b/docs/configuration.mdindex 9793118e5..f8ee408ce 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -2083,6 +2083,15 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]| `tools.ssrfWhitelist` | `[]` | CIDR ranges exempted from the shared SSRF guard used by web fetches and HTTP/SSE MCP connections. Prefer exact host CIDRs such as `192.168.1.50/32`; broad ranges increase SSRF exposure. || `channels.*.allowFrom` | omitted | Access control per channel. Omit to use pairing-only mode; set `["*"]` to allow everyone; or list specific user IDs. See [Pairing](#pairing) for details. |+To diagnose a path error, the agent can call `my(action="check", key="workspace_sandbox")`.+This read-only result shows the current tool directory and workspace restriction, including+the restriction from `tools.exec.sandbox`. The older `workspace` value is an agent-directory+display; it does not select the current project or grant access.+Check `exec_config` for the configured shell sandbox and extra binds. Those binds do not grant+file-tool access or permit an external shell `working_dir`. OS file permissions still apply.+The `workspace_sandbox.enforced` field reports external sandbox markers, not whether a+configured shell sandbox has started successfully.+**Docker security**: The official Docker image runs as a non-root user (`nanobot`, UID 1000) with bubblewrap pre-installed. The default `docker-compose.yml` drops all Linux capabilities except the `CHOWN`, `SETGID`, and `SETUID` capabilities required by the root entrypoint to initialize bind-mount ownership and become UID 1000. It enables `no-new-privileges` so the final non-root process cannot regain those bootstrap capabilities, and keeps Docker's default AppArmor/seccomp profiles enabled. If you enable `"tools.exec.sandbox": "bwrap"` inside Docker, start Compose with `docker-compose.bwrap.yml` as an additional override so bubblewrap can create nested namespaces. The host must also allow unprivileged user namespaces; the override cannot bypass a host-level namespace restriction.diff --git a/nanobot/agent/tools/runtime_control.py b/nanobot/agent/tools/runtime_control.pyindex e031ba067..57a2e498f 100644--- a/nanobot/agent/tools/runtime_control.py+++ b/nanobot/agent/tools/runtime_control.py@@ -7,6 +7,8 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING, Protocol, TypeAlias, runtime_checkable+from nanobot.security.workspace_access import current_tool_workspace, workspace_sandbox_status+if TYPE_CHECKING:from nanobot.agent.tools.shell import ExecToolConfigfrom nanobot.agent.tools.web import WebToolsConfig@@ -25,6 +27,7 @@ RUNTIME_SNAPSHOT_KEYS = frozenset({"max_iterations","context_window_tokens","workspace",+ "workspace_sandbox","provider_retry_mode","max_tool_result_chars","tool_names",@@ -59,6 +62,7 @@ class RuntimeSnapshot:web_config: dict[str, object]exec_config: dict[str, object]scratchpad: dict[str, JsonValue]+ workspace_sandbox: dict[str, object]def as_mapping(self) -> Mapping[str, object]:"""Return the fixed public names understood by ``MyTool``."""@@ -69,6 +73,7 @@ class RuntimeSnapshot:"max_iterations": self.max_iterations,"context_window_tokens": self.context_window_tokens,"workspace": self.workspace,+ "workspace_sandbox": self.workspace_sandbox,"provider_retry_mode": self.provider_retry_mode,"max_tool_result_chars": self.max_tool_result_chars,"tool_names": self.tool_names,@@ -115,6 +120,7 @@ class _RuntimeControlTarget(Protocol):max_tool_result_chars: intweb_config: WebToolsConfigexec_config: ExecToolConfig+ restrict_to_workspace: bool@propertydef model(self) -> str: ...@@ -155,6 +161,12 @@ class AgentRuntimeControl:def snapshot(self) -> RuntimeSnapshot:target = self.__target+ workspace = current_tool_workspace(+ target.workspace,+ restrict_to_workspace=target.restrict_to_workspace,+ sandbox_restricts_workspace=bool(target.exec_config.sandbox),+ )+ assert workspace.project_path is not Nonereturn RuntimeSnapshot(model=target.model,model_preset=target.model_preset,@@ -172,6 +184,10 @@ class AgentRuntimeControl:web_config=_snapshot_web_config(target.web_config),exec_config=_snapshot_exec_config(target.exec_config),scratchpad=_snapshot_json_mapping(self.__scratchpad),+ workspace_sandbox=workspace_sandbox_status(+ workspace=workspace.project_path,+ restrict_to_workspace=workspace.restrict_to_workspace,+ ).as_dict(),)def set_model(self, model: str) -> LLMRuntime:diff --git a/nanobot/agent/tools/self.py b/nanobot/agent/tools/self.pyindex d7723f4e8..e7155cb55 100644--- a/nanobot/agent/tools/self.py+++ b/nanobot/agent/tools/self.py@@ -142,6 +142,10 @@ class MyTool(Tool):"Scratchpad keys persist across turns but not restarts.\n""Current routing metadata is available read-only via request.channel, ""request.chat_id, and request.sender_id.\n"+ "For path access, check workspace_sandbox for the current project and "+ "workspace restriction. Check exec_config for shell sandbox settings and extra binds. "+ "Shell binds do not grant file-tool access. OS permissions still apply.\n"+ "workspace is the legacy agent-directory display, not the current project or an access grant.\n""Use model_preset for session-scoped model or context changes; direct ""model/context_window_tokens writes are disabled during active sessions.\n""Note: web_config and exec_config are readable but read-only.\n"@@ -206,7 +210,7 @@ class MyTool(Tool):for part in parts:if part in self._DENIED_ATTRS or part.startswith("__"):return None, f"'{part}' is not accessible"- if part in self.BLOCKED:+ if part in self.BLOCKED and path != "workspace_sandbox.restrict_to_workspace":return None, f"'{part}' is not accessible"if part.lower() in self._SENSITIVE_NAMES:return None, f"'{part}' is not accessible"@@ -238,6 +242,8 @@ class MyTool(Tool):# Mapping — small: show content; large: show keys for dot-path navigationif isinstance(val, Mapping):value_mapping = cast(Mapping[object, object], val)+ if key == "workspace_sandbox":+ return f"{key}: {dict(value_mapping)!r}"ks = list(value_mapping.keys())if not ks:return f"{key}: {{}}" if key else "{}"@@ -344,6 +350,7 @@ class MyTool(Tool):))for k in ("workspace",+ "workspace_sandbox","provider_retry_mode","max_tool_result_chars","web_config",diff --git a/tests/agent/tools/test_runtime_control.py b/tests/agent/tools/test_runtime_control.pyindex bfb3be905..307cf4615 100644--- a/tests/agent/tools/test_runtime_control.py+++ b/tests/agent/tools/test_runtime_control.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonfrom pathlib import Path-from unittest.mock import MagicMock+from unittest.mock import AsyncMock, MagicMockimport pytest@@ -20,20 +20,31 @@ from nanobot.agent.tools.runtime_control import (from nanobot.agent.tools.self import MyTool, MyToolConfigfrom nanobot.bus.queue import MessageBusfrom nanobot.config.schema import ToolsConfig-from nanobot.providers.base import GenerationSettings+from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest+from nanobot.security.workspace_access import (+ bind_workspace_scope,+ build_workspace_scope,+ reset_workspace_scope,+)from nanobot.utils.llm_runtime import LLMRuntime-def _make_loop(tmp_path: Path, *, allow_set: bool = False) -> AgentLoop:+def _make_loop(+ tmp_path: Path, *, allow_set: bool = False, restricted: bool = False, sandbox: str = "",+) -> AgentLoop:provider = MagicMock()provider.get_default_model.return_value = "test-model"- tools_config = ToolsConfig(my=MyToolConfig(allow_set=allow_set))+ tools_config = ToolsConfig(+ my=MyToolConfig(allow_set=allow_set), restrict_to_workspace=restricted,+ )+ tools_config.exec.sandbox = sandboxreturn AgentLoop(bus=MessageBus(),provider=provider,workspace=tmp_path,model="test-model",tools_config=tools_config,+ restrict_to_workspace=restricted,)@@ -68,6 +79,7 @@ def test_runtime_snapshot_has_exact_allowlist_and_redacts_secrets(tmp_path: Path"max_iterations","context_window_tokens","workspace",+ "workspace_sandbox","provider_retry_mode","max_tool_result_chars","tool_names",@@ -243,6 +255,134 @@ async def test_workspace_display_command_cannot_change_path_enforcement(tmp_pathassert loop.workspace_scopes.default_workspace == tmp_path[email protected](("mode", "sandbox", "restricted"), [+ ("restricted", "", True),+ ("full", "", False),+ ("full", "seatbelt", True),+])+async def test_workspace_inspection_matches_registered_file_tool(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mode: str, sandbox: str, restricted: bool,+) -> None:+ # A configured shell backend is not proof that an external sandbox is running.+ monkeypatch.delenv("NANOBOT_WORKSPACE_SANDBOX_ENFORCED", raising=False)+ monkeypatch.delenv("NANOBOT_SANDBOX_ENFORCED", raising=False)+ agent = tmp_path / "agent"+ project = tmp_path / "project"+ project.mkdir()+ (project / "marker.txt").write_text("project marker", encoding="utf-8")+ outside = tmp_path / "outside.txt"+ outside.write_text("outside marker", encoding="utf-8")+ loop = _make_loop(agent, allow_set=True, restricted=True, sandbox=sandbox)+ tool = _my_tool(loop)+ definitions = json.dumps(loop.tools.get_definitions(), sort_keys=True)+ token = bind_workspace_scope(build_workspace_scope(project, mode))+ try:+ # Legacy display writes must not spoof the effective directory or permission.+ await tool.execute(action="set", key="workspace", value=str(outside.parent))+ status = tool._runtime_control.snapshot().workspace_sandbox+ assert status["workspace_root"] == str(project.resolve())+ assert status["restrict_to_workspace"] is restricted+ assert status["level"] == ("application" if restricted else "off")+ assert status["enforced"] is False+ assert str(project.resolve()) in await tool.execute(action="check", key="workspace_sandbox")+ assert str(project.resolve()) in await tool.execute(action="check")+ assert await tool.execute(action="check", key="workspace_sandbox.restrict_to_workspace") == (+ f"workspace_sandbox.restrict_to_workspace: {restricted!r}"+ )+ for key in ("workspace_sandbox", "workspace_sandbox.restrict_to_workspace"):+ assert "read-only" in await tool.execute(action="set", key=key, value=False)+ assert "not accessible" in await tool.execute(action="check", key="restrict_to_workspace")+ assert "project marker" in await loop.tools.execute("read_file", {"path": "marker.txt"})+ result = await loop.tools.execute("read_file", {"path": str(outside)})+ assert ("outside allowed directory" if restricted else "outside marker") in result+ # The directory and permission enter tool results, not the reusable tool schemas.+ assert json.dumps(loop.tools.get_definitions(), sort_keys=True) == definitions+ status["workspace_root"] = "changed snapshot"+ assert tool._runtime_control.snapshot().workspace_sandbox["workspace_root"] == str(project.resolve())+ finally:+ reset_workspace_scope(token)++[email protected]("restricted", [False, True])+async def test_workspace_inspection_uses_instance_default_without_turn(+ tmp_path: Path, restricted: bool,+) -> None:+ loop = _make_loop(tmp_path, restricted=restricted)+ status = _my_tool(loop)._runtime_control.snapshot().workspace_sandbox+ assert status["workspace_root"] == str(tmp_path.resolve())+ assert status["restrict_to_workspace"] is restricted+++async def test_workspace_inspection_is_isolated_between_concurrent_turns(tmp_path: Path) -> None:+ tool = _my_tool(_make_loop(tmp_path))+ ready = asyncio.Event()++ async def inspect(project: Path, mode: str, *, signal: bool) -> dict[str, object]:+ token = bind_workspace_scope(build_workspace_scope(project, mode))+ try:+ if signal:+ ready.set()+ await ready.wait()+ await asyncio.sleep(0)+ result = await tool.execute(action="check", key="workspace_sandbox.workspace_root")+ assert str(project.resolve()) in result+ return tool._runtime_control.snapshot().workspace_sandbox+ finally:+ reset_workspace_scope(token)++ first, second = await asyncio.gather(+ inspect(tmp_path / "first", "restricted", signal=False),+ inspect(tmp_path / "second", "full", signal=True),+ )+ assert first["restrict_to_workspace"] is True+ assert second["restrict_to_workspace"] is False+ assert tool._runtime_control.snapshot().workspace_sandbox["workspace_root"] == str(tmp_path.resolve())+++async def test_workspace_inspection_reaches_model_from_selected_chat(tmp_path: Path) -> None:+ project = tmp_path / "project"+ project.mkdir()+ (project / "marker.txt").write_text("selected project", encoding="utf-8")+ loop = _make_loop(tmp_path / "agent")+ provider = loop.provider+ provider.generation = GenerationSettings()+ provider.estimate_prompt_tokens.return_value = (100, "test")+ provider.chat_stream_with_retry = AsyncMock(side_effect=[+ LLMResponse(content=None, tool_calls=[+ ToolCallRequest(id="inspect", name="my", arguments={+ "action": "check", "key": "workspace_sandbox",+ }),+ ToolCallRequest(id="read", name="read_file", arguments={"path": "marker.txt"}),+ ]),+ LLMResponse(content="done", tool_calls=[]),+ ])+ session = loop.sessions.get_or_create("websocket:inspection")+ session.metadata["workspace_scope"] = {+ "project_path": str(project), "access_mode": "restricted",+ }++ response = await loop.process_direct(+ "Check the current directory and read marker.txt",+ channel="websocket", chat_id="inspection", session_key=session.key, ephemeral=True,+ )++ assert response is not None and response.content == "done"+ calls = provider.chat_stream_with_retry.await_args_list+ assert len(calls) == 2+ results = {+ msg["tool_call_id"]: msg["content"] for msg in calls[1].kwargs["messages"]+ if msg["role"] == "tool"+ }+ assert str(project.resolve()) in results["inspect"]+ assert "'restrict_to_workspace': True" in results["inspect"]+ assert "selected project" in results["read"]+ assert calls[0].kwargs["tools"] == calls[1].kwargs["tools"]++@pytest.fixturedef runtime() -> LLMRuntime:return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)