Skip to content

Your lightweight open-source personal agent.

docs: refresh stale runtime comments and docstrings (#6129)

chengyongru98f89c6a43ce
diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py
index f7fcca0d1..a8dbe9131 100644
--- a/nanobot/agent/loop.py
+++ b/nanobot/agent/loop.py
@@ -2039,7 +2039,7 @@ class AgentLoop:
if result is not None:
ctx.outbound = result
# Shortcut commands skip BUILD and SAVE, so we must persist the
- # turn here so WebUI history hydration after _turn_end sees the
+ # turn here so WebUI history hydration after turn_end sees the
# message. Mark messages with _command so get_history can filter
# them out of LLM context. /new is excluded because it
# intentionally clears the session.
diff --git a/nanobot/agent/tools/sandbox.py b/nanobot/agent/tools/sandbox.py
index e3fa90451..6ef1e6ca0 100644
--- a/nanobot/agent/tools/sandbox.py
+++ b/nanobot/agent/tools/sandbox.py
@@ -1,8 +1,8 @@
"""Sandbox backends for shell command execution.
-To add a new backend, implement a function with the signature:
- _wrap_<name>(command: str, workspace: str, cwd: str) -> str
-and register it in _BACKENDS below.
+To add a backend, match the callable signature of _bwrap and _seatbelt,
+including keyword-only sandbox_ro_binds and sandbox_rw_binds, and register
+it in _BACKENDS below.
"""
import os
@@ -55,9 +55,10 @@ def _bwrap(
) -> str:
"""Wrap command in a bubblewrap sandbox (requires bwrap in container).
- Only the workspace is bind-mounted read-write; its parent dir (which holds
- config.json) is hidden behind a fresh tmpfs. The media directory is
- bind-mounted read-only so exec commands can read uploaded attachments.
+ The workspace is bind-mounted read-write; its parent directory is hidden
+ behind a fresh tmpfs. Media is mounted read-only for uploaded attachments.
+ Explicit sandbox_ro_binds and sandbox_rw_binds add read-only and read-write
+ roots, respectively.
"""
ws = Path(workspace).resolve()
media = get_media_dir().resolve()
diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.py
index 0fc75297b..f7bea1f19 100644
--- a/nanobot/agent/tools/web.py
+++ b/nanobot/agent/tools/web.py
@@ -1023,8 +1023,7 @@ class WebSearchTool(Tool):
async def _search_duckduckgo(self, query: str, n: int) -> str:
try:
- # Note: duckduckgo_search is synchronous and does its own requests
- # We run it in a thread to avoid blocking the loop
+ # DDGS.text performs synchronous requests; run it in a thread to avoid blocking the loop.
from ddgs import DDGS # pyright: ignore[reportUnknownVariableType]
ddgs_type = cast(Any, DDGS)
diff --git a/nanobot/bus/events.py b/nanobot/bus/events.py
index 7d0f24728..7de154af5 100644
--- a/nanobot/bus/events.py
+++ b/nanobot/bus/events.py
@@ -30,7 +30,7 @@ class InboundMessage:
chat_id: str # Chat/channel identifier
content: str # Message text
timestamp: datetime = field(default_factory=datetime.now)
- media: list[str] = field(default_factory=list) # Media URLs
+ media: list[str] = field(default_factory=list) # Media paths or URLs
metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data
session_key_override: str | None = None # Optional override for thread-scoped sessions
require_existing_session: bool = False
diff --git a/nanobot/channels/telegram/runtime.py b/nanobot/channels/telegram/runtime.py
index a12e808c5..1824930fc 100644
--- a/nanobot/channels/telegram/runtime.py
+++ b/nanobot/channels/telegram/runtime.py
@@ -359,7 +359,7 @@ def _markdown_to_telegram_html(text: str) -> str:
escaped = _escape_telegram_html(code)
text = text.replace(f"\x00CB{i}\x00", f"<pre><code>{escaped}</code></pre>")
- # 13. Restore header bold markers (inserted in step 3, after HTML escaping)
+ # 13. Restore header bold markers inserted in step 3 before HTML escaping.
text = text.replace('⟪B⟫', '<b>').replace('⟪/B⟫', '</b>')
return text
diff --git a/nanobot/channels/weixin/runtime.py b/nanobot/channels/weixin/runtime.py
index dacd9fe18..616738ff7 100644
--- a/nanobot/channels/weixin/runtime.py
+++ b/nanobot/channels/weixin/runtime.py
@@ -216,11 +216,9 @@ class WeixinConfig(Base):
reply_progress_messages: bool = False
reply_progress_max_messages: int = Field(default=2, ge=0, le=4)
context_message_budget: int = Field(default=8, ge=1, le=10)
- # Default on: WeChat iLink has no native incremental delivery (send_delta is
- # buffered and the final answer is still sent in one shot), so streaming has
- # zero user-facing effect here — it only switches the LLM call to the
- # streaming API. That avoids upstream Anthropic relays that drop tool_use
- # id/name/input on the non-streaming Messages path (a common third-party
+ # Default on: use the LLM streaming API even when block_streaming is off
+ # and visible delivery waits for stream end. This avoids upstream Anthropic
+ # relays that drop tool_use id/name/input on the non-streaming Messages path (a common third-party
# relay bug). Set to false only if a relay's streaming/SSE path is broken.
streaming: bool = True
# Optional user-visible block streaming. Disabled by default because every
@@ -330,8 +328,8 @@ class WeixinChannel(BaseChannel):
self._context_token_at: dict[str, float] = {}
self._pending_tool_hints: dict[str, list[str]] = {}
# Buffers streamed content deltas per chat. WeChat iLink has no native
- # incremental delivery, so when streaming is enabled we accumulate the
- # deltas and flush the full reply in one shot at _stream_end.
+ # incremental delivery. Optional block streaming sends bounded messages
+ # while deltas arrive; stream end flushes the remaining buffered reply.
self._stream_buffers: dict[str, list[str]] = {}
self._stream_sent_counts: dict[str, int] = {}
self._stream_live_disabled: set[str] = set()
@@ -2126,10 +2124,10 @@ class WeixinChannel(BaseChannel):
) -> None:
"""Deliver a streamed reply to WeChat.
- WeChat iLink has no native incremental delivery, and the manager
- bypasses :meth:`send` for the ``_streamed`` final answer. So we
- accumulate content deltas and flush the full reply as a single message
- at stream end. Reasoning deltas are invisible in WeChat and are dropped.
+ WeChat iLink has no native incremental delivery. Optional block streaming
+ sends bounded messages while deltas arrive; stream end flushes the
+ remaining reply. The manager skips the final ``StreamedResponseEvent``
+ to avoid duplicate delivery. Reasoning deltas are dropped.
"""
meta = metadata or {}
if meta.get("_reasoning_delta") or meta.get("_reasoning"):
diff --git a/nanobot/command/builtin.py b/nanobot/command/builtin.py
index 98a014ffc..43df46e2f 100644
--- a/nanobot/command/builtin.py
+++ b/nanobot/command/builtin.py
@@ -279,7 +279,7 @@ async def cmd_status(ctx: CommandContext) -> OutboundMessage:
if ctx_est <= 0:
ctx_est = last_usage.input_tokens if last_usage is not None else 0
- # Fetch web search provider usage (best-effort, never blocks the response)
+ # Await web search provider usage; network requests have a bounded timeout.
search_usage_text: str | None = None
# Never let usage fetch break /status
with suppress(Exception):
diff --git a/nanobot/config/paths.py b/nanobot/config/paths.py
index bed717b1f..23cafa28d 100644
--- a/nanobot/config/paths.py
+++ b/nanobot/config/paths.py
@@ -44,7 +44,7 @@ def get_logs_dir() -> Path:
def get_webui_dir() -> Path:
- """Return the directory for WebUI-only persisted display threads (JSON)."""
+ """Return the directory for WebUI JSONL transcripts and legacy JSON snapshots."""
return get_runtime_subdir("webui")
diff --git a/nanobot/providers/openai_compat_provider.py b/nanobot/providers/openai_compat_provider.py
index 0eebcb8e8..f5e406cd0 100644
--- a/nanobot/providers/openai_compat_provider.py
+++ b/nanobot/providers/openai_compat_provider.py
@@ -1,4 +1,4 @@
-"""OpenAI-compatible provider for all non-Anthropic LLM APIs."""
+"""Shared provider for OpenAI-compatible Chat Completions and Responses APIs."""
# pyright: reportPrivateImportUsage=false
@@ -478,7 +478,7 @@ def _merge_responses_extra_body(
class OpenAICompatProvider(LLMProvider):
- """Unified provider for all OpenAI-compatible APIs.
+ """Provider for OpenAI-compatible Chat Completions and Responses endpoints.
Receives a resolved ``ProviderSpec`` from the caller — no internal
registry lookups needed.
@@ -552,9 +552,8 @@ class OpenAICompatProvider(LLMProvider):
elif self._is_local:
# Local model servers (Ollama, llama.cpp, vLLM) often close idle
# HTTP connections before the client-side keepalive expires. When
- # two LLM calls happen seconds apart (e.g. heartbeat _decide then
- # process_direct), the second call may grab a now-dead pooled
- # connection, causing a transient APIConnectionError on every first
+ # two LLM calls happen seconds apart, the second may grab a dead
+ # pooled connection, causing a transient APIConnectionError on every first
# attempt. Disabling keepalive for local endpoints avoids this by
# opening a fresh connection for each request, which is cheap on a
# LAN. Cloud providers benefit from keepalive, so we leave the
diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py
index d0a54323f..af7ad5eb7 100644
--- a/nanobot/session/manager.py
+++ b/nanobot/session/manager.py
@@ -1593,7 +1593,7 @@ class SessionManager:
return JsonlSessionStore.session_key_from_path(path)
def _get_session_path(self, key: str) -> Path:
- """Get the collision-resistant workspace path for a session."""
+ """Get the canonical session path in the workspace's external storage namespace."""
return self._jsonl_store.get_session_path(key)
def _get_runtime_checkpoint_path(self, key: str) -> Path:
diff --git a/tests/agent/test_auto_compact.py b/tests/agent/test_auto_compact.py
index 9604a09cc..56df53245 100644
--- a/tests/agent/test_auto_compact.py
+++ b/tests/agent/test_auto_compact.py
@@ -1155,7 +1155,7 @@ class TestSummaryPersistence:
loop.sessions.invalidate("cli:test")
reloaded = loop.sessions.get_or_create("cli:test")
- # Every call returns the summary from metadata (no _consumed_keys gate)
+ # Every call returns the persisted summary.
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
assert summary is not None
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
@@ -1167,7 +1167,7 @@ class TestSummaryPersistence:
@pytest.mark.asyncio
async def test_metadata_cleanup_on_inmemory_path(self, tmp_path):
- """In-memory _summaries path should also clean up _last_summary from metadata."""
+ """The in-memory summary path preserves _last_summary for restart recovery."""
loop = _make_loop(tmp_path, session_ttl_minutes=15)
session = loop.sessions.get_or_create("cli:test")
_add_turns(session, 6, prefix="hello")
diff --git a/tests/agent/test_consolidator.py b/tests/agent/test_consolidator.py
index 2eb641bf4..6ddc26156 100644
--- a/tests/agent/test_consolidator.py
+++ b/tests/agent/test_consolidator.py
@@ -365,7 +365,7 @@ class TestConsolidatorSummarize:
async def test_summarize_raw_dumps_on_llm_failure(
self, consolidator, mock_provider, store, runtime
):
- """On LLM failure, raw-dump messages to HISTORY.md."""
+ """On LLM failure, append raw messages to memory/history.jsonl."""
mock_provider.chat_stream_with_retry.side_effect = Exception("API error")
messages = [{"role": "user", "content": "hello"}]
result = await _archive(consolidator, messages, runtime)
@@ -1605,7 +1605,7 @@ class TestRawArchiveTruncation:
assert "PUBLIC_TAIL" in joined
def test_raw_archive_truncates_large_content(self, store):
- """Large messages should be truncated to _RAW_ARCHIVE_MAX_CHARS."""
+ """Large messages are split across bounded journal entries."""
big = "x" * 50_000
messages = [{"role": "user", "content": big}]
store.raw_archive(messages)
diff --git a/tests/agent/test_loop_progress.py b/tests/agent/test_loop_progress.py
index 7f227841d..b609c041f 100644
--- a/tests/agent/test_loop_progress.py
+++ b/tests/agent/test_loop_progress.py
@@ -1,4 +1,4 @@
-"""Tests for structured tool-event progress metadata emitted by AgentLoop."""
+"""Tests for structured tool activity emitted through AgentLoop progress events."""
import asyncio
from pathlib import Path
@@ -277,7 +277,7 @@ class TestToolEventProgress:
@pytest.mark.asyncio
async def test_bus_progress_forwards_tool_events_to_outbound_metadata(self, tmp_path: Path) -> None:
- """When run() handles a bus message, _tool_events lands in OutboundMessage metadata."""
+ """Bus-dispatched turns deliver tool activity through ProgressEvent.tool_events."""
bus = MessageBus()
provider = MagicMock()
provider.get_default_model.return_value = "test-model"
diff --git a/tests/agent/test_loop_runner_integration.py b/tests/agent/test_loop_runner_integration.py
index b215c5805..65481b267 100644
--- a/tests/agent/test_loop_runner_integration.py
+++ b/tests/agent/test_loop_runner_integration.py
@@ -507,8 +507,7 @@ async def test_loop_retries_think_only_final_response(tmp_path):
@pytest.mark.asyncio
async def test_streamed_flag_not_set_on_llm_error(tmp_path):
- """When LLM errors during a streaming-capable channel interaction,
- _streamed must NOT be set so ChannelManager delivers the error."""
+ """LLM errors must not produce StreamedResponseEvent, so channels deliver the error."""
from nanobot.agent.loop import AgentLoop
from nanobot.bus.events import InboundMessage
from nanobot.bus.queue import MessageBus