fix(agent): respect temporary chat privacy in tool execution

This commit is contained in:
Xubin Ren committed 2026-09-21 15:24:38 +08:00
1 parent 804e4c4ea6
commit 2640251076
12 files changed
+410 -29

No files matched your search

+98 -1
View File
@@ -2,17 +2,21 @@ import asyncio
from unittest.mock import AsyncMock, MagicMock
import pytest
from loguru import logger
from agent.session_helpers import run_session
from nanobot.agent.context import TranscriptInput
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
from nanobot.bus.events import (
INBOUND_META_RUNTIME_CONTROL,
RUNTIME_CONTROL_SESSION_DISCARD,
InboundMessage,
)
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import GenerationSettings, LLMResponse
from nanobot.providers.base import GenerationSettings, LLMResponse, ToolCallRequest
from nanobot.session.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionPolicy
def _message(key: str, content: str) -> InboundMessage:
@@ -73,6 +77,99 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_too
assert loop.sessions.read_session_file(key) is None
@pytest.mark.parametrize("privacy", ["temporary", "quiet", "ordinary"])
@pytest.mark.parametrize("structured", [True, False])
async def test_session_policy_controls_tool_logs_and_result_offload(
tmp_path, privacy, structured,
) -> None:
loop = _loop(tmp_path, [])
loop.max_tool_result_chars = 2048
key = "websocket:privacy-regression"
if privacy == "temporary":
loop.sessions.get_or_create_transient(key)
else:
session = loop.sessions.get_or_create(key)
session.policy = SessionPolicy(log_content=privacy != "quiet")
secret = "synthetic-private-query-测试"
text = "synthetic-private-result-" * 1000
image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,c3ludGhldGlj"}}
result = [{"type": "text", "text": text}, image] if structured else text
loop.tools.prepare_call = MagicMock(return_value=(None, {"query": secret}, None))
loop.tools.execute = AsyncMock(return_value=result)
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=[
LLMResponse(content="", tool_calls=[
ToolCallRequest(id="private_result", name="web_search", arguments={"query": secret}),
]),
LLMResponse(content="done"),
])
logs: list[str] = []
sink = logger.add(lambda message: logs.append(str(message)), format="{message}")
try:
await loop._process_message(_message(key, "synthetic question"))
finally:
logger.remove(sink)
assert loop.tools.execute.await_count == 1
messages = loop.provider.chat_stream_with_retry.await_args.kwargs["messages"]
content = next(m["content"] for m in messages if m["role"] == "tool")
preview = content[0]["text"] if structured else content
offload_root = tmp_path / ".nanobot" / "tool-results"
assert (secret in "\n".join(logs)) is (privacy == "ordinary")
if structured:
assert content[1] == image
if privacy == "temporary":
assert not offload_root.exists()
assert preview.endswith("... (truncated)")
assert len(preview) < len(text)
await loop.discard_session(key)
assert loop.sessions.get_cached(key) is None
assert loop.sessions.read_session_file(key) is None
assert not offload_root.exists()
else:
assert "[tool output persisted]" in preview
assert [p.read_text() for p in offload_root.rglob("*.txt")] == [text]
async def test_direct_transient_run_never_spills_before_cancellation(tmp_path) -> None:
loop = _loop(tmp_path, [])
session = loop.sessions.get_or_create_transient("websocket:cancel-private")
loop.max_tool_result_chars = 100
loop.tools.prepare_call = MagicMock(return_value=(None, {}, None))
loop.tools.execute = AsyncMock(return_value="synthetic large result" * 1000)
second_call = asyncio.Event()
count = 0
async def respond(**kwargs):
nonlocal count
count += 1
request = current_request_context()
assert request is not None and request.workspace == tmp_path
assert request.log_content is False
if count == 1:
return LLMResponse(content="", tool_calls=[
ToolCallRequest(id="cancel-result", name="web_search", arguments={}),
])
second_call.set()
await asyncio.Event().wait()
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=respond)
# The session policy must suffice even without passing ephemeral=True.
task = asyncio.create_task(loop._run_agent_loop(
TranscriptInput(history=[], current_message="synthetic question"),
runtime=loop.llm_runtime(), session=session,
))
try:
await asyncio.wait_for(second_call.wait(), timeout=2)
assert not (tmp_path / ".nanobot" / "tool-results").exists()
finally:
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
await loop.discard_session(session.key)
assert not (tmp_path / ".nanobot" / "tool-results").exists()
assert current_request_context() is None
@pytest.mark.asyncio
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
loop = _loop(tmp_path, ["private answer"], unified_session=True)
+36
View File
@@ -1,7 +1,10 @@
import pytest
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentTurnHookContext
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.providers.base import ToolCallRequest
from nanobot.utils.progress_events import output_events
class RecordingHook(AgentHook):
@@ -14,6 +17,39 @@ class RecordingHook(AgentHook):
self._events.append(f"{self._label}:{context.iteration}")
@pytest.mark.parametrize("ephemeral", [True, False])
@pytest.mark.parametrize("hosted", [True, False])
async def test_tool_log_privacy_preserves_user_visible_progress(ephemeral, hosted) -> None:
secret = "synthetic-private-argument-测试"
events: list[dict] = []
async def on_progress(content, **kwargs):
events.extend(kwargs.get("tool_events") or [])
hook = build_agent_turn_hook(AgentTurnHookSpec(
ephemeral=ephemeral, events=output_events(on_progress=on_progress),
))
context = AgentHookContext(iteration=1, messages=[], tool_calls=[
ToolCallRequest(id="private-call", name="web_search", arguments={"query": secret}),
])
logs: list[str] = []
sink = logger.add(lambda message: logs.append(str(message)), format="{message}")
try:
if hosted:
await hook.on_provider_tool_event(context, {
"phase": "start", "name": "web_search", "call_id": "private-call",
"arguments": {"query": secret},
})
else:
await hook.before_execute_tools(context)
finally:
logger.remove(sink)
assert events[0]["arguments"] == {"query": secret}
assert "web_search" in "\n".join(logs)
assert (secret in "\n".join(logs)) is not ephemeral
def test_turn_hook_context_preserves_legacy_positional_arguments(tmp_path) -> None:
context = AgentTurnHookContext(
None,
+187
View File
@@ -0,0 +1,187 @@
"""Synthetic privacy regressions for tool diagnostics, without external requests."""
import asyncio
import sys
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
from loguru import logger
from mcp import types
from mcp.shared.exceptions import McpError
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.tools.context import (
RequestContext,
request_context,
tool_log_content_allowed,
)
from nanobot.agent.tools.execution import _classify_violation, execute_tool_calls
from nanobot.agent.tools.mcp import MCPPromptWrapper, MCPResourceWrapper, MCPToolWrapper
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.agent.tools.web import WebFetchTool, WebSearchTool, _redact_url_for_log
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook
from nanobot.config.schema import WebSearchConfig
from nanobot.providers.base import ToolCallRequest
_SECRET = "synthetic-private-detail"
@pytest.fixture
def diagnostic_records():
records = []
sink = logger.add(lambda message: records.append(message.record), format="{message}")
try:
yield records
finally:
logger.remove(sink)
@pytest.mark.parametrize("log_content", [True, False])
@pytest.mark.parametrize("kind", ["tool", "resource", "prompt", "prompt_error", "render", "retry"])
async def test_mcp_private_errors_exclude_exception_payloads(
log_content, kind, monkeypatch, diagnostic_records,
):
session = MagicMock()
definition = SimpleNamespace(name="sample", description="sample", inputSchema={})
error = ValueError(_SECRET)
if kind in {"tool", "render", "retry"}:
tool = MCPToolWrapper(session, "test", definition)
if kind == "render":
session.call_tool = AsyncMock(return_value=SimpleNamespace(content=[]))
monkeypatch.setattr(tool, "_render_call_result", MagicMock(side_effect=error))
else:
if kind == "retry":
error = ConnectionResetError(_SECRET)
monkeypatch.setattr("nanobot.agent.tools.mcp.asyncio.sleep", AsyncMock())
session.call_tool = AsyncMock(side_effect=error)
elif kind == "resource":
tool = MCPResourceWrapper(session, "test", types.Resource(
name="sample", uri="https://example.test/resource",
))
session.read_resource = AsyncMock(side_effect=error)
else:
tool = MCPPromptWrapper(session, "test", types.Prompt(name="sample"))
if kind == "prompt_error":
error = McpError(types.ErrorData(code=-32602, message=_SECRET))
session.get_prompt = AsyncMock(side_effect=error)
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
result = await tool.execute()
assert "failed" in result or "malformed" in result
errors = [r for r in diagnostic_records if r["level"].name == "ERROR"]
assert errors
if log_content:
assert errors[-1]["exception"] is not None
else:
assert all(r["exception"] is None for r in diagnostic_records)
assert _SECRET not in str([r["message"] for r in diagnostic_records])
@pytest.mark.parametrize("log_content", [True, False])
@pytest.mark.parametrize("kind", ["fetch", "jina", "duckduckgo", "ssrf"])
async def test_web_private_diagnostics_keep_error_category_not_content(
log_content, kind, monkeypatch, diagnostic_records,
):
url = f"https://{_SECRET}.example/path?query={_SECRET}"
error = RuntimeError(url)
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
if kind == "fetch":
monkeypatch.setattr("nanobot.agent.tools.web.httpx.AsyncClient", MagicMock(side_effect=error))
result = await WebFetchTool()._fetch_readability(url, "text", 100)
assert url in result
elif kind == "jina":
tool = WebSearchTool(config=WebSearchConfig(provider="jina", api_key="synthetic"))
monkeypatch.setattr("nanobot.agent.tools.web.httpx.AsyncClient", MagicMock(side_effect=error))
monkeypatch.setattr(tool, "_search_duckduckgo", AsyncMock(return_value="fallback"))
assert await tool._search_jina(_SECRET, 1) == "fallback"
elif kind == "duckduckgo":
monkeypatch.setitem(sys.modules, "ddgs", SimpleNamespace(DDGS=MagicMock(side_effect=error)))
result = await WebSearchTool()._search_duckduckgo(_SECRET, 1)
assert _SECRET in result
else:
raw = f"Error: private/internal address {url}"
result = _classify_violation(
raw_text=raw, soft_payload=raw, event={},
tool_call=ToolCallRequest(id="test", name="web_fetch", arguments={"url": url}),
workspace_violation_counts={},
)
assert result is not None and url in result[0]
assert diagnostic_records
assert (_SECRET in str([r["message"] for r in diagnostic_records])) is log_content
async def test_private_logging_policy_is_task_local_and_restored():
private_started = asyncio.Event()
ordinary_started = asyncio.Event()
async def private():
with request_context(RequestContext(channel="websocket", chat_id="private", log_content=False)):
private_started.set()
await ordinary_started.wait()
assert not tool_log_content_allowed()
assert _redact_url_for_log("https://example.test/private") == "[content hidden]"
async def ordinary():
await private_started.wait()
with request_context(RequestContext(channel="websocket", chat_id="ordinary")):
ordinary_started.set()
await asyncio.sleep(0)
assert tool_log_content_allowed()
assert _redact_url_for_log("https://example.test/private") == "https://example.test"
await asyncio.gather(private(), ordinary())
assert tool_log_content_allowed()
@pytest.mark.parametrize("log_content", [True, False])
async def test_search_refresh_traceback_cannot_capture_private_call_arguments(
log_content, monkeypatch,
):
tool = WebSearchTool(config_loader=MagicMock(side_effect=ValueError("config unavailable")))
monkeypatch.setattr(tool, "_search_duckduckgo", AsyncMock(return_value="synthetic result"))
tools = ToolRegistry()
tools.register(tool)
rendered: list[str] = []
sink = logger.add(
lambda message: rendered.append(str(message)), format="{message}",
diagnose=True, backtrace=True,
)
try:
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
results, _ = await execute_tool_calls(
tools, [ToolCallRequest(id="test", name="web_search", arguments={"query": _SECRET})],
concurrent=False, external_lookup_counts={}, workspace_violation_counts={},
hook=AgentHook(), context=AgentHookContext(iteration=1, messages=[]),
)
finally:
logger.remove(sink)
assert results == ["synthetic result"]
assert "Failed to refresh web search config" in "\n".join(rendered)
assert (_SECRET in "\n".join(rendered)) is log_content
@pytest.mark.parametrize("log_content", [True, False])
@pytest.mark.parametrize("factory", [True, False])
async def test_optional_hook_failures_obey_private_log_policy(
log_content, factory, diagnostic_records,
):
class BrokenHook(AgentHook):
async def before_execute_tool(self, *args):
raise ValueError("synthetic hook failure")
broken_factory = MagicMock(side_effect=ValueError("synthetic factory failure"))
with request_context(RequestContext(channel="websocket", chat_id="test", log_content=log_content)):
hook = build_agent_turn_hook(AgentTurnHookSpec(
ephemeral=not log_content, run_extra_hooks_for_ephemeral=True,
registered_hooks=[] if factory else [BrokenHook()],
turn_hook_factories=[broken_factory] if factory else [],
))
await hook.before_execute_tool(
AgentHookContext(iteration=1, messages=[]),
ToolCallRequest(id="test", name="web_search", arguments={"query": _SECRET}),
None, {"query": _SECRET},
)
errors = [r for r in diagnostic_records if r["level"].name == "ERROR"]
assert errors
assert (errors[0]["exception"] is not None) is log_content