fix(my): report current workspace access in self-inspection
This commit is contained in:
1 parent
9261e731ce
commit
e79a0099f6
4 files changed
+177
-5
No files matched your search
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
from unittest.mock import AsyncMock, MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -20,20 +20,31 @@ from nanobot.agent.tools.runtime_control import (
|
||||
from nanobot.agent.tools.self import MyTool, MyToolConfig
|
||||
from nanobot.bus.queue import MessageBus
|
||||
from 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 = sandbox
|
||||
return 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_path
|
||||
assert loop.workspace_scopes.default_workspace == tmp_path
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize(("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)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@pytest.mark.parametrize("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
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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())
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
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.fixture
|
||||
def runtime() -> LLMRuntime:
|
||||
return LLMRuntime(MagicMock(), "test", GenerationSettings(), 128_000)
|
||||
|
||||
Reference in new issue
Block a user