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

+8 -1
View File
@@ -165,9 +165,16 @@ You can keep more than one temporary chat open and switch between them under
open. Reloading or closing the page, restarting the gateway, or losing the open. Reloading or closing the page, restarting the gateway, or losing the
WebSocket connection ends all of them. They cannot be recovered afterward. WebSocket 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 configured Temporary does not mean consequence-free. Requests still go to the configured
model provider, and tools can still change files, run commands, or affect model 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 in
Restricted mode; the project picker and Full Access are unavailable. Commands Restricted mode; the project picker and Full Access are unavailable. Commands
and tools that create durable goals, automations, or subagent work are also and tools that create durable goals, automations, or subagent work are also
unavailable. Use a regular topic when you need reusable context, scheduled work, unavailable. Use a regular topic when you need reusable context, scheduled work,
+4 -1
View File
@@ -9,6 +9,7 @@ from typing import Any
from loguru import logger from loguru import logger
from nanobot.agent.tools.context import tool_log_content_allowed
from nanobot.events import NO_EVENTS, EventSink from nanobot.events import NO_EVENTS, EventSink
from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest
@@ -180,7 +181,9 @@ class CompositeHook(AgentHook):
try: try:
await getattr(h, method_name)(*args, **kwargs) await getattr(h, method_name)(*args, **kwargs)
except Exception: 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: async def before_iteration(self, context: AgentHookContext) -> None:
await self._for_each_hook_safe("before_iteration", context) await self._for_each_hook_safe("before_iteration", context)
+20 -2
View File
@@ -732,6 +732,7 @@ class AgentLoop:
sender_id=ctx.msg.sender_id, sender_id=ctx.msg.sender_id,
turn_id=ctx.turn_id, turn_id=ctx.turn_id,
workspace=scope.project_path, workspace=scope.project_path,
log_content=ctx.session.policy.log_content and not ctx.ephemeral,
) )
async def _resolve_runtime_context_for_turn( async def _resolve_runtime_context_for_turn(
@@ -814,6 +815,7 @@ class AgentLoop:
sender_id=ctx.msg.sender_id, sender_id=ctx.msg.sender_id,
turn_id=metadata.get("webui_turn_id"), turn_id=metadata.get("webui_turn_id"),
workspace=scope.project_path, workspace=scope.project_path,
log_content=session.policy.log_content,
)) ))
workspace_token = bind_workspace_scope(scope) workspace_token = bind_workspace_scope(scope)
turn_scope_stack = ExitStack() turn_scope_stack = ExitStack()
@@ -983,6 +985,8 @@ class AgentLoop:
""" """
self._sync_subagent_runtime_limits() 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: async def _checkpoint(payload: dict[str, Any]) -> None:
if session is None: if session is None:
return return
@@ -1058,6 +1062,7 @@ class AgentLoop:
sender_id=pending_msg.sender_id, sender_id=pending_msg.sender_id,
turn_id=request_ctx.turn_id, turn_id=request_ctx.turn_id,
workspace=scope.project_path, workspace=scope.project_path,
log_content=request_ctx.log_content,
) )
blocks = await self._resolve_runtime_context_for_request( blocks = await self._resolve_runtime_context_for_request(
pending_request, pending_request,
@@ -1165,6 +1170,13 @@ class AgentLoop:
request_ctx, request_ctx,
workspace=effective_scope.project_path, 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.tools effective_tools = tools or self.tools
file_state_token = bind_file_states(self._file_state_store.for_session(active_session_key)) file_state_token = bind_file_states(self._file_state_store.for_session(active_session_key))
request_token = bind_request_context(request_ctx) request_token = bind_request_context(request_ctx)
@@ -1203,6 +1215,7 @@ class AgentLoop:
turn_hooks=list(hooks or []), turn_hooks=list(hooks or []),
ephemeral=ephemeral, ephemeral=ephemeral,
run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral, run_extra_hooks_for_ephemeral=run_extra_hooks_for_ephemeral,
log_content=request_ctx.log_content,
)) ))
result = await self.runner.run(AgentRunSpec( result = await self.runner.run(AgentRunSpec(
initial_messages=None, initial_messages=None,
@@ -1214,7 +1227,9 @@ class AgentLoop:
transcript_builder=transcript_builder, transcript_builder=transcript_builder,
hook=hook, hook=hook,
concurrent_tools=True, 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, session_key=session.key if session else None,
provider_retry_mode=self.provider_retry_mode, provider_retry_mode=self.provider_retry_mode,
checkpoint_callback=_checkpoint, checkpoint_callback=_checkpoint,
@@ -1274,7 +1289,10 @@ class AgentLoop:
await events.publish(StreamDeltaEvent(content=stream_content)) await events.publish(StreamDeltaEvent(content=stream_content))
await events.publish(StreamEndEvent()) await events.publish(StreamEndEvent())
elif result.stop_reason == "error": 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 result return result
def _check_expired_sessions_if_due(self) -> None: def _check_expired_sessions_if_due(self) -> None:
+9 -3
View File
@@ -29,12 +29,14 @@ class AgentProgressHook(AgentHook):
streaming: bool = False, streaming: bool = False,
session_key: str | None = None, session_key: str | None = None,
tool_hint_max_length: int = 40, tool_hint_max_length: int = 40,
log_content: bool = True,
) -> None: ) -> None:
super().__init__(reraise=True) super().__init__(reraise=True)
self._publish = events.publish self._publish = events.publish
self._streaming = streaming self._streaming = streaming
self._session_key = session_key self._session_key = session_key
self._tool_hint_max_length = tool_hint_max_length self._tool_hint_max_length = tool_hint_max_length
self._log_content = log_content
self._stream_buf = "" self._stream_buf = ""
self._think_extractor = IncrementalThinkExtractor() self._think_extractor = IncrementalThinkExtractor()
self._reasoning_open = False self._reasoning_open = False
@@ -124,7 +126,8 @@ class AgentProgressHook(AgentHook):
logger.info( logger.info(
"Provider-hosted tool call: {}({})", "Provider-hosted tool call: {}({})",
name, name,
json.dumps(arguments, ensure_ascii=False)[:200], json.dumps(arguments, ensure_ascii=False)[:200]
if self._log_content else "[content hidden]",
) )
return return
await self._publish(ProgressEvent(tool_events=[payload])) await self._publish(ProgressEvent(tool_events=[payload]))
@@ -141,8 +144,11 @@ class AgentProgressHook(AgentHook):
content=tool_hint or "", tool_hint=True, tool_events=tool_events, content=tool_hint or "", tool_hint=True, tool_events=tool_events,
)) ))
for tc in context.tool_calls: for tc in context.tool_calls:
args_str = json.dumps(tc.arguments, ensure_ascii=False) args_str = (
logger.info("Tool call: {}({})", tc.name, args_str[:200]) 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: async def emit_reasoning(self, reasoning_content: str | None) -> None:
"""Publish a reasoning chunk; channel plugins decide whether to render.""" """Publish a reasoning chunk; channel plugins decide whether to render."""
+7
View File
@@ -40,6 +40,7 @@ class RequestContext:
turn_id: str | None = None turn_id: str | None = None
workspace: Path | None = None workspace: Path | None = None
attributes: dict[str, Any] = field(default_factory=dict) attributes: dict[str, Any] = field(default_factory=dict)
log_content: bool = True
@runtime_checkable @runtime_checkable
@@ -70,6 +71,12 @@ def current_request_context() -> RequestContext | None:
return _CURRENT_REQUEST_CONTEXT.get() 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: def current_request_session_key() -> str | None:
ctx = current_request_context() ctx = current_request_context()
return ctx.session_key if ctx else None return ctx.session_key if ctx else None
+3 -1
View File
@@ -11,6 +11,7 @@ from typing import Any, cast
from loguru import logger from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.tools.context import tool_log_content_allowed
from nanobot.agent.tools.file_state import file_read_context from nanobot.agent.tools.file_state import file_read_context
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
from nanobot.providers.base import ToolCallRequest from nanobot.providers.base import ToolCallRequest
@@ -253,7 +254,8 @@ def _classify_violation(
logger.warning( logger.warning(
"Tool {} blocked by SSRF guard; returning non-retryable tool error: {}", "Tool {} blocked by SSRF guard; returning non-retryable tool error: {}",
tool_call.name, 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) event["detail"] = _event_detail("ssrf_violation: ", raw_text)
return _ssrf_soft_payload(raw_text), event return _ssrf_soft_payload(raw_text), event
+15 -14
View File
@@ -17,6 +17,7 @@ import httpx
from loguru import logger from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.context import tool_log_content_allowed
from nanobot.agent.tools.registry import ToolRegistry from nanobot.agent.tools.registry import ToolRegistry
from nanobot.security.network import ( from nanobot.security.network import (
PinnedDNSAsyncTransport, PinnedDNSAsyncTransport,
@@ -666,7 +667,7 @@ class MCPToolWrapper(_MCPWrapperBase):
await asyncio.sleep(1) # Brief backoff before retry await asyncio.sleep(1) # Brief backoff before retry
continue continue
# Second transient failure — give up with retry-specific message # Second transient failure — give up with retry-specific message
logger.exception( logger.opt(exception=tool_log_content_allowed()).error(
"MCP tool '{}' failed after retry: {}", "MCP tool '{}' failed after retry: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
@@ -674,11 +675,11 @@ class MCPToolWrapper(_MCPWrapperBase):
return ToolResult.error( return ToolResult.error(
f"(MCP tool call failed after retry: {type(exc).__name__})" f"(MCP tool call failed after retry: {type(exc).__name__})"
) )
logger.exception( logger.opt(exception=tool_log_content_allowed()).error(
"MCP tool '{}' failed: {}: {}", "MCP tool '{}' failed: {}: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
exc, exc if tool_log_content_allowed() else "[content hidden]",
) )
return ToolResult.error( return ToolResult.error(
f"(MCP tool call failed: {type(exc).__name__})" f"(MCP tool call failed: {type(exc).__name__})"
@@ -691,11 +692,11 @@ class MCPToolWrapper(_MCPWrapperBase):
return ToolResult.error(rendered) return ToolResult.error(rendered)
return rendered return rendered
except Exception as exc: except Exception as exc:
logger.exception( logger.opt(exception=tool_log_content_allowed()).error(
"MCP tool '{}' failed while rendering result: {}: {}", "MCP tool '{}' failed while rendering result: {}: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
exc, exc if tool_log_content_allowed() else "[content hidden]",
) )
return ToolResult.error( return ToolResult.error(
f"(MCP tool returned malformed content: {type(exc).__name__})" f"(MCP tool returned malformed content: {type(exc).__name__})"
@@ -749,7 +750,7 @@ class MCPToolWrapper(_MCPWrapperBase):
logger.warning( logger.warning(
"MCP tool '{}' returned an image that could not be stored: {}", "MCP tool '{}' returned an image that could not be stored: {}",
self._name, self._name,
exc, exc if tool_log_content_allowed() else type(exc).__name__,
) )
return None return None
@@ -833,17 +834,17 @@ class MCPResourceWrapper(_MCPWrapperBase):
) )
await asyncio.sleep(1) await asyncio.sleep(1)
continue continue
logger.exception( logger.opt(exception=tool_log_content_allowed()).error(
"MCP resource '{}' failed after retry: {}", "MCP resource '{}' failed after retry: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
) )
return f"(MCP resource read failed after retry: {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: {}: {}", "MCP resource '{}' failed: {}: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
exc, exc if tool_log_content_allowed() else "[content hidden]",
) )
return f"(MCP resource read failed: {type(exc).__name__})" return f"(MCP resource read failed: {type(exc).__name__})"
else: else:
@@ -942,11 +943,11 @@ class MCPPromptWrapper(_MCPWrapperBase):
): ):
refreshed_session = True refreshed_session = True
continue continue
logger.exception( logger.opt(exception=tool_log_content_allowed()).error(
"MCP prompt '{}' failed: code={} message={}", "MCP prompt '{}' failed: code={} message={}",
self._name, self._name,
exc.error.code, 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}])" return f"(MCP prompt call failed: {exc.error.message} [code {exc.error.code}])"
except Exception as exc: except Exception as exc:
@@ -967,17 +968,17 @@ class MCPPromptWrapper(_MCPWrapperBase):
) )
await asyncio.sleep(1) await asyncio.sleep(1)
continue continue
logger.exception( logger.opt(exception=tool_log_content_allowed()).error(
"MCP prompt '{}' failed after retry: {}", "MCP prompt '{}' failed after retry: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
) )
return f"(MCP prompt call failed after retry: {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: {}: {}", "MCP prompt '{}' failed: {}: {}",
self._name, self._name,
type(exc).__name__, type(exc).__name__,
exc, exc if tool_log_content_allowed() else "[content hidden]",
) )
return f"(MCP prompt call failed: {type(exc).__name__})" return f"(MCP prompt call failed: {type(exc).__name__})"
else: else:
+12 -4
View File
@@ -18,7 +18,7 @@ from loguru import logger
from pydantic import Field from pydantic import Field
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters from 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_allowed
from nanobot.agent.tools.schema import ( from nanobot.agent.tools.schema import (
BooleanSchema, BooleanSchema,
IntegerSchema, IntegerSchema,
@@ -186,6 +186,8 @@ def _url_carries_credentials(url: str) -> bool:
def _redact_url_for_log(url: str) -> str: def _redact_url_for_log(url: str) -> str:
"""Return only a URL's origin, excluding userinfo, path, query, and fragment.""" """Return only a URL's origin, excluding userinfo, path, query, and fragment."""
if not tool_log_content_allowed():
return "[content hidden]"
try: try:
parsed = urlparse(url) parsed = urlparse(url)
hostname = parsed.hostname hostname = parsed.hostname
@@ -415,7 +417,7 @@ class WebSearchTool(Tool):
try: try:
self.config = self._config_loader() self.config = self._config_loader()
except Exception: 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: def _effective_provider(self) -> str:
"""Resolve the backend that execute() will actually use.""" """Resolve the backend that execute() will actually use."""
@@ -732,7 +734,10 @@ class WebSearchTool(Tool):
] ]
return _format_results(query, items, n) return _format_results(query, items, n)
except Exception as e: 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) return await self._search_duckduckgo(query, n)
async def _search_kagi(self, query: str, n: int) -> str: async def _search_kagi(self, query: str, n: int) -> str:
@@ -1037,7 +1042,10 @@ class WebSearchTool(Tool):
] ]
return _format_results(query, items, n) return _format_results(query, items, n)
except Exception as e: 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})") return ToolResult.error(f"Error: DuckDuckGo search failed ({e})")
async def _search_bocha(self, query: str, n: int, freshness: str = "noLimit") -> str: async def _search_bocha(self, query: str, n: int, freshness: str = "noLimit") -> str:
+11 -2
View File
@@ -38,15 +38,18 @@ class AgentTurnHookSpec:
ephemeral: bool = False ephemeral: bool = False
run_extra_hooks_for_ephemeral: bool = False run_extra_hooks_for_ephemeral: bool = False
attributes: dict[str, Any] | None = None attributes: dict[str, Any] | None = None
log_content: bool = True
def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook: def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:
"""Build the hook chain used by ``AgentRunner`` for one turn.""" """Build the hook chain used by ``AgentRunner`` for one turn."""
log_content = spec.log_content and not spec.ephemeral
progress_hook = AgentProgressHook( progress_hook = AgentProgressHook(
events=spec.events, events=spec.events,
streaming=spec.streaming, streaming=spec.streaming,
session_key=spec.session_key, session_key=spec.session_key,
tool_hint_max_length=spec.tool_hint_max_length, tool_hint_max_length=spec.tool_hint_max_length,
log_content=log_content,
) )
if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral: if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral:
return progress_hook return progress_hook
@@ -68,7 +71,10 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:
try: try:
created_hook = factory(turn_context) created_hook = factory(turn_context)
except Exception: 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__,
)
continue continue
if created_hook is not None: if created_hook is not None:
hook_chain.append(created_hook) hook_chain.append(created_hook)
@@ -79,7 +85,10 @@ def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:
try: try:
created_hook = factory(turn_context) created_hook = factory(turn_context)
except Exception: 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__,
)
continue continue
if created_hook is not None: if created_hook is not None:
hook_chain.append(created_hook) hook_chain.append(created_hook)
+98 -1
View File
@@ -2,17 +2,21 @@ import asyncio
from unittest.mock import AsyncMock, MagicMock from unittest.mock import AsyncMock, MagicMock
import pytest import pytest
from loguru import logger
from agent.session_helpers import run_session from agent.session_helpers import run_session
from nanobot.agent.context import TranscriptInput
from nanobot.agent.loop import AgentLoop from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
from nanobot.bus.events import ( from nanobot.bus.events import (
INBOUND_META_RUNTIME_CONTROL, INBOUND_META_RUNTIME_CONTROL,
RUNTIME_CONTROL_SESSION_DISCARD, RUNTIME_CONTROL_SESSION_DISCARD,
InboundMessage, InboundMessage,
) )
from nanobot.bus.queue import MessageBus 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.keys import UNIFIED_SESSION_KEY
from nanobot.session.manager import SessionPolicy
def _message(key: str, content: str) -> InboundMessage: 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 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 @pytest.mark.asyncio
async def test_transient_session_stays_outside_unified_session(tmp_path) -> None: async def test_transient_session_stays_outside_unified_session(tmp_path) -> None:
loop = _loop(tmp_path, ["private answer"], unified_session=True) loop = _loop(tmp_path, ["private answer"], unified_session=True)
+36
View File
@@ -1,7 +1,10 @@
import pytest import pytest
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentTurnHookContext from nanobot.agent.hook import AgentHook, AgentHookContext, AgentTurnHookContext
from nanobot.agent.turn_hooks import AgentTurnHookSpec, build_agent_turn_hook 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): class RecordingHook(AgentHook):
@@ -14,6 +17,39 @@ class RecordingHook(AgentHook):
self._events.append(f"{self._label}:{context.iteration}") 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: def test_turn_hook_context_preserves_legacy_positional_arguments(tmp_path) -> None:
context = AgentTurnHookContext( context = AgentTurnHookContext(
None, 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