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): respect temporary chat privacy in tool execution
Xubin Ren264025107635
diff --git a/docs/webui.md b/docs/webui.mdindex a4a55d5c8..b475d3a4a 100644--- a/docs/webui.md+++ b/docs/webui.md@@ -165,9 +165,16 @@ You can keep more than one temporary chat open and switch between them underopen. Reloading or closing the page, restarting the gateway, or losing theWebSocket connection ends all of them. They cannot be recovered afterward.+Temporary chats do not create saved files for oversized text tool results; these+stay in memory and are truncated to the configured tool-result limit. Tool-call+arguments and execution-error details are hidden from the built-in tool logs,+while tool activity remains visible in the current chat.+Temporary does not mean consequence-free. Requests still go to the configuredmodel provider, and tools can still change files, run commands, or affect-external services. Temporary chats always use the default workspace in+external services. Files and image artifacts created or exported by tools+(including images returned by MCP tools) are not erased when the chat closes.+Temporary chats always use the default workspace inRestricted mode; the project picker and Full Access are unavailable. Commandsand tools that create durable goals, automations, or subagent work are alsounavailable. Use a regular topic when you need reusable context, scheduled work,diff --git a/nanobot/agent/hook.py b/nanobot/agent/hook.pyindex 136e57db2..2cab7686e 100644--- a/nanobot/agent/hook.py+++ b/nanobot/agent/hook.py@@ -9,6 +9,7 @@ from typing import Anyfrom loguru import logger+from nanobot.agent.tools.context import tool_log_content_allowedfrom nanobot.events import NO_EVENTS, EventSinkfrom nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest@@ -180,7 +181,9 @@ class CompositeHook(AgentHook):try:await getattr(h, method_name)(*args, **kwargs)except Exception:- logger.exception("AgentHook.{} error in {}", method_name, type(h).__name__)+ logger.opt(exception=tool_log_content_allowed()).error(+ "AgentHook.{} error in {}", method_name, type(h).__name__,+ )async def before_iteration(self, context: AgentHookContext) -> None:await self._for_each_hook_safe("before_iteration", context)diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pyindex c405c738d..55fceff86 100644--- a/nanobot/agent/loop.py+++ b/nanobot/agent/loop.py@@ -732,6 +732,7 @@ class AgentLoop:sender_id=ctx.msg.sender_id,turn_id=ctx.turn_id,workspace=scope.project_path,+ log_content=ctx.session.policy.log_content and not ctx.ephemeral,)async def _resolve_runtime_context_for_turn(@@ -814,6 +815,7 @@ class AgentLoop: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)turn_scope_stack = ExitStack()@@ -983,6 +985,8 @@ class AgentLoop:"""self._sync_subagent_runtime_limits()+ ephemeral = ephemeral or (session is not None and not session.policy.persist)+async def _checkpoint(payload: dict[str, Any]) -> None:if session is None:return@@ -1058,6 +1062,7 @@ class AgentLoop:sender_id=pending_msg.sender_id,turn_id=request_ctx.turn_id,workspace=scope.project_path,+ log_content=request_ctx.log_content,)blocks = await self._resolve_runtime_context_for_request(pending_request,@@ -1165,6 +1170,13 @@ class AgentLoop:request_ctx,workspace=effective_scope.project_path,)+ request_ctx = dataclasses.replace(+ request_ctx,+ log_content=(+ request_ctx.log_content and not ephemeral+ and (session is None or session.policy.log_content)+ ),+ )effective_tools = tools or self.toolsfile_state_token = bind_file_states(self._file_state_store.for_session(active_session_key))request_token = bind_request_context(request_ctx)@@ -1203,6 +1215,7 @@ class AgentLoop:turn_hooks=list(hooks or []),ephemeral=ephemeral,run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral,+ log_content=request_ctx.log_content,))result = await self.runner.run(AgentRunSpec(initial_messages=None,@@ -1214,7 +1227,9 @@ class AgentLoop:transcript_builder=transcript_builder,hook=hook,concurrent_tools=True,- workspace=effective_scope.project_path,+ # Temporary turns use the governor's bounded in-memory results;+ # never create durable spill files, even before discard/cancellation.+ workspace=None if ephemeral else effective_scope.project_path,session_key=session.key if session else None,provider_retry_mode=self.provider_retry_mode,checkpoint_callback=_checkpoint,@@ -1274,7 +1289,10 @@ class AgentLoop:await events.publish(StreamDeltaEvent(content=stream_content))await events.publish(StreamEndEvent())elif result.stop_reason == "error":- logger.error("LLM returned error: {}", (result.final_content or "")[:200])+ logger.error(+ "LLM returned error: {}",+ (result.final_content or "")[:200] if request_ctx.log_content else "[content hidden]",+ )return resultdef _check_expired_sessions_if_due(self) -> None:diff --git a/nanobot/agent/progress_hook.py b/nanobot/agent/progress_hook.pyindex 515cb2048..83242758f 100644--- a/nanobot/agent/progress_hook.py+++ b/nanobot/agent/progress_hook.py@@ -29,12 +29,14 @@ class AgentProgressHook(AgentHook):streaming: bool = False,session_key: str | None = None,tool_hint_max_length: int = 40,+ log_content: bool = True,) -> None:super().__init__(reraise=True)self._publish = events.publishself._streaming = streamingself._session_key = session_keyself._tool_hint_max_length = tool_hint_max_length+ self._log_content = log_contentself._stream_buf = ""self._think_extractor = IncrementalThinkExtractor()self._reasoning_open = False@@ -124,7 +126,8 @@ class AgentProgressHook(AgentHook):logger.info("Provider-hosted tool call: {}({})",name,- json.dumps(arguments, ensure_ascii=False)[:200],+ json.dumps(arguments, ensure_ascii=False)[:200]+ if self._log_content else "[content hidden]",)returnawait self._publish(ProgressEvent(tool_events=[payload]))@@ -141,8 +144,11 @@ class AgentProgressHook(AgentHook):content=tool_hint or "", tool_hint=True, tool_events=tool_events,))for tc in context.tool_calls:- args_str = json.dumps(tc.arguments, ensure_ascii=False)- logger.info("Tool call: {}({})", tc.name, args_str[:200])+ args_str = (+ json.dumps(tc.arguments, ensure_ascii=False)[:200]+ if self._log_content else "[content hidden]"+ )+ logger.info("Tool call: {}({})", tc.name, args_str)async def emit_reasoning(self, reasoning_content: str | None) -> None:"""Publish a reasoning chunk; channel plugins decide whether to render."""diff --git a/nanobot/agent/tools/context.py b/nanobot/agent/tools/context.pyindex 5124f7798..40288a6ca 100644--- a/nanobot/agent/tools/context.py+++ b/nanobot/agent/tools/context.py@@ -40,6 +40,7 @@ class RequestContext:turn_id: str | None = Noneworkspace: Path | None = Noneattributes: dict[str, Any] = field(default_factory=dict)+ log_content: bool = True@runtime_checkable@@ -70,6 +71,12 @@ def current_request_context() -> RequestContext | None:return _CURRENT_REQUEST_CONTEXT.get()+def tool_log_content_allowed() -> bool:+ """Whether diagnostics may include content from the current tool request."""+ ctx = current_request_context()+ return ctx is None or ctx.log_content++def current_request_session_key() -> str | None:ctx = current_request_context()return ctx.session_key if ctx else Nonediff --git a/nanobot/agent/tools/execution.py b/nanobot/agent/tools/execution.pyindex 7ec3b71dc..e81f45c4d 100644--- a/nanobot/agent/tools/execution.py+++ b/nanobot/agent/tools/execution.py@@ -11,6 +11,7 @@ from typing import Any, castfrom loguru import loggerfrom nanobot.agent.hook import AgentHook, AgentHookContext+from nanobot.agent.tools.context import tool_log_content_allowedfrom nanobot.agent.tools.file_state import file_read_contextfrom nanobot.agent.tools.registry import ToolRegistry, is_tool_error_resultfrom nanobot.providers.base import ToolCallRequest@@ -253,7 +254,8 @@ def _classify_violation(logger.warning("Tool {} blocked by SSRF guard; returning non-retryable tool error: {}",tool_call.name,- raw_text.replace("\n", " ").strip()[:200],+ raw_text.replace("\n", " ").strip()[:200]+ if tool_log_content_allowed() else "[content hidden]",)event["detail"] = _event_detail("ssrf_violation: ", raw_text)return _ssrf_soft_payload(raw_text), eventdiff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.pyindex f0b8bbe5c..9f328d78d 100644--- a/nanobot/agent/tools/mcp.py+++ b/nanobot/agent/tools/mcp.py@@ -17,6 +17,7 @@ import httpxfrom loguru import loggerfrom nanobot.agent.tools.base import Tool, ToolResult+from nanobot.agent.tools.context import tool_log_content_allowedfrom nanobot.agent.tools.registry import ToolRegistryfrom nanobot.security.network import (PinnedDNSAsyncTransport,@@ -666,7 +667,7 @@ class MCPToolWrapper(_MCPWrapperBase):await asyncio.sleep(1) # Brief backoff before retrycontinue# Second transient failure — give up with retry-specific message- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP tool '{}' failed after retry: {}",self._name,type(exc).__name__,@@ -674,11 +675,11 @@ class MCPToolWrapper(_MCPWrapperBase):return ToolResult.error(f"(MCP tool call failed after retry: {type(exc).__name__})")- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP tool '{}' failed: {}: {}",self._name,type(exc).__name__,- exc,+ exc if tool_log_content_allowed() else "[content hidden]",)return ToolResult.error(f"(MCP tool call failed: {type(exc).__name__})"@@ -691,11 +692,11 @@ class MCPToolWrapper(_MCPWrapperBase):return ToolResult.error(rendered)return renderedexcept Exception as exc:- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP tool '{}' failed while rendering result: {}: {}",self._name,type(exc).__name__,- exc,+ exc if tool_log_content_allowed() else "[content hidden]",)return ToolResult.error(f"(MCP tool returned malformed content: {type(exc).__name__})"@@ -749,7 +750,7 @@ class MCPToolWrapper(_MCPWrapperBase):logger.warning("MCP tool '{}' returned an image that could not be stored: {}",self._name,- exc,+ exc if tool_log_content_allowed() else type(exc).__name__,)return None@@ -833,17 +834,17 @@ class MCPResourceWrapper(_MCPWrapperBase):)await asyncio.sleep(1)continue- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP resource '{}' failed after retry: {}",self._name,type(exc).__name__,)return f"(MCP resource read failed after retry: {type(exc).__name__})"- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP resource '{}' failed: {}: {}",self._name,type(exc).__name__,- exc,+ exc if tool_log_content_allowed() else "[content hidden]",)return f"(MCP resource read failed: {type(exc).__name__})"else:@@ -942,11 +943,11 @@ class MCPPromptWrapper(_MCPWrapperBase):):refreshed_session = Truecontinue- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP prompt '{}' failed: code={} message={}",self._name,exc.error.code,- exc.error.message,+ exc.error.message if tool_log_content_allowed() else "[content hidden]",)return f"(MCP prompt call failed: {exc.error.message} [code {exc.error.code}])"except Exception as exc:@@ -967,17 +968,17 @@ class MCPPromptWrapper(_MCPWrapperBase):)await asyncio.sleep(1)continue- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP prompt '{}' failed after retry: {}",self._name,type(exc).__name__,)return f"(MCP prompt call failed after retry: {type(exc).__name__})"- logger.exception(+ logger.opt(exception=tool_log_content_allowed()).error("MCP prompt '{}' failed: {}: {}",self._name,type(exc).__name__,- exc,+ exc if tool_log_content_allowed() else "[content hidden]",)return f"(MCP prompt call failed: {type(exc).__name__})"else:diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.pyindex d01147c98..087acf04c 100644--- a/nanobot/agent/tools/web.py+++ b/nanobot/agent/tools/web.py@@ -18,7 +18,7 @@ from loguru import loggerfrom pydantic import Fieldfrom nanobot.agent.tools.base import Tool, ToolResult, tool_parameters-from nanobot.agent.tools.context import ToolContext+from nanobot.agent.tools.context import ToolContext, tool_log_content_allowedfrom nanobot.agent.tools.schema import (BooleanSchema,IntegerSchema,@@ -186,6 +186,8 @@ def _url_carries_credentials(url: str) -> bool:def _redact_url_for_log(url: str) -> str:"""Return only a URL's origin, excluding userinfo, path, query, and fragment."""+ if not tool_log_content_allowed():+ return "[content hidden]"try:parsed = urlparse(url)hostname = parsed.hostname@@ -415,7 +417,7 @@ class WebSearchTool(Tool):try:self.config = self._config_loader()except Exception:- logger.exception("Failed to refresh web search config")+ logger.opt(exception=tool_log_content_allowed()).error("Failed to refresh web search config")def _effective_provider(self) -> str:"""Resolve the backend that execute() will actually use."""@@ -732,7 +734,10 @@ class WebSearchTool(Tool):]return _format_results(query, items, n)except Exception as e:- logger.warning("Jina search failed ({}), falling back to DuckDuckGo", e)+ logger.warning(+ "Jina search failed ({}), falling back to DuckDuckGo",+ e if tool_log_content_allowed() else type(e).__name__,+ )return await self._search_duckduckgo(query, n)async def _search_kagi(self, query: str, n: int) -> str:@@ -1037,7 +1042,10 @@ class WebSearchTool(Tool):]return _format_results(query, items, n)except Exception as e:- logger.warning("DuckDuckGo search failed: {}", e)+ logger.warning(+ "DuckDuckGo search failed: {}",+ e if tool_log_content_allowed() else type(e).__name__,+ )return ToolResult.error(f"Error: DuckDuckGo search failed ({e})")async def _search_bocha(self, query: str, n: int, freshness: str = "noLimit") -> str:diff --git a/nanobot/agent/turn_hooks.py b/nanobot/agent/turn_hooks.pyindex 6720f69cf..3b4cb423e 100644--- a/nanobot/agent/turn_hooks.py+++ b/nanobot/agent/turn_hooks.py@@ -38,15 +38,18 @@ class AgentTurnHookSpec:ephemeral: bool = Falserun_extra_hooks_for_ephemeral: bool = Falseattributes: dict[str, Any] | None = None+ log_content: bool = Truedef build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:"""Build the hook chain used by ``AgentRunner`` for one turn."""+ log_content = spec.log_content and not spec.ephemeralprogress_hook = AgentProgressHook(events=spec.events,streaming=spec.streaming,session_key=spec.session_key,tool_hint_max_length=spec.tool_hint_max_length,+ log_content=log_content,)if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral:return progress_hook@@ -68,7 +71,10 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:try:created_hook = factory(turn_context)except Exception:- logger.exception("Agent turn hook factory failed: {}", factory)+ logger.opt(exception=log_content).error(+ "Agent turn hook factory failed: {}",+ factory if log_content else type(factory).__name__,+ )continueif created_hook is not None:hook_chain.append(created_hook)@@ -79,7 +85,10 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:try:created_hook = factory(turn_context)except Exception:- logger.exception("Agent turn hook factory failed: {}", factory)+ logger.opt(exception=log_content).error(+ "Agent turn hook factory failed: {}",+ factory if log_content else type(factory).__name__,+ )continueif created_hook is not None:hook_chain.append(created_hook)diff --git a/tests/agent/test_loop_session_policy.py b/tests/agent/test_loop_session_policy.pyindex 8ba2f4144..e37f107fb 100644--- a/tests/agent/test_loop_session_policy.py+++ b/tests/agent/test_loop_session_policy.py@@ -2,17 +2,21 @@ import asynciofrom unittest.mock import AsyncMock, MagicMockimport pytest+from loguru import loggerfrom agent.session_helpers import run_session+from nanobot.agent.context import TranscriptInputfrom nanobot.agent.loop import AgentLoop+from nanobot.agent.tools.context import current_request_contextfrom 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, ToolCallRequestfrom nanobot.session.keys import UNIFIED_SESSION_KEY+from nanobot.session.manager import SessionPolicydef _message(key: str, content: str) -> InboundMessage:@@ -73,6 +77,99 @@ async def test_transient_session_keeps_history_without_persisting_or_durable_tooassert loop.sessions.read_session_file(key) is None[email protected]("privacy", ["temporary", "quiet", "ordinary"])[email protected]("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.asyncioasync def test_transient_session_stays_outside_unified_session(tmp_path) -> None:loop = _loop(tmp_path, ["private answer"], unified_session=True)diff --git a/tests/agent/test_turn_hooks.py b/tests/agent/test_turn_hooks.pyindex 56d8347f8..700224912 100644--- a/tests/agent/test_turn_hooks.py+++ b/tests/agent/test_turn_hooks.py@@ -1,7 +1,10 @@import pytest+from loguru import loggerfrom nanobot.agent.hook import AgentHook, AgentHookContext, AgentTurnHookContextfrom nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook+from nanobot.providers.base import ToolCallRequest+from nanobot.utils.progress_events import output_eventsclass RecordingHook(AgentHook):@@ -14,6 +17,39 @@ class RecordingHook(AgentHook):self._events.append(f"{self._label}:{context.iteration}")[email protected]("ephemeral", [True, False])[email protected]("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,diff --git a/tests/tools/test_private_tool_logging.py b/tests/tools/test_private_tool_logging.pynew file mode 100644index 000000000..3cac4934e--- /dev/null+++ b/tests/tools/test_private_tool_logging.py@@ -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"+++def diagnostic_records():+ records = []+ sink = logger.add(lambda message: records.append(message.record), format="{message}")+ try:+ yield records+ finally:+ logger.remove(sink)++[email protected]("log_content", [True, False])[email protected]("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])++[email protected]("log_content", [True, False])[email protected]("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()++[email protected]("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++[email protected]("log_content", [True, False])[email protected]("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