docs: refresh stale runtime comments and docstrings (#6129)
* docs: refresh stale runtime comments and docstrings * docs: correct remaining delivery and recovery descriptions
This commit is contained in:
1 parent
e5a69544e8
commit
98f89c6a43
14 files changed
+34
-38
No files matched your search
@@ -2039,7 +2039,7 @@ class AgentLoop:
|
|||||||
if result is not None:
|
if result is not None:
|
||||||
ctx.outbound = result
|
ctx.outbound = result
|
||||||
# Shortcut commands skip BUILD and SAVE, so we must persist the
|
# 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
|
# message. Mark messages with _command so get_history can filter
|
||||||
# them out of LLM context. /new is excluded because it
|
# them out of LLM context. /new is excluded because it
|
||||||
# intentionally clears the session.
|
# intentionally clears the session.
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
"""Sandbox backends for shell command execution.
|
"""Sandbox backends for shell command execution.
|
||||||
|
|
||||||
To add a new backend, implement a function with the signature:
|
To add a backend, match the callable signature of _bwrap and _seatbelt,
|
||||||
_wrap_<name>(command: str, workspace: str, cwd: str) -> str
|
including keyword-only sandbox_ro_binds and sandbox_rw_binds, and register
|
||||||
and register it in _BACKENDS below.
|
it in _BACKENDS below.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -55,9 +55,10 @@ def _bwrap(
|
|||||||
) -> str:
|
) -> str:
|
||||||
"""Wrap command in a bubblewrap sandbox (requires bwrap in container).
|
"""Wrap command in a bubblewrap sandbox (requires bwrap in container).
|
||||||
|
|
||||||
Only the workspace is bind-mounted read-write; its parent dir (which holds
|
The workspace is bind-mounted read-write; its parent directory is hidden
|
||||||
config.json) is hidden behind a fresh tmpfs. The media directory is
|
behind a fresh tmpfs. Media is mounted read-only for uploaded attachments.
|
||||||
bind-mounted read-only so exec commands can read uploaded attachments.
|
Explicit sandbox_ro_binds and sandbox_rw_binds add read-only and read-write
|
||||||
|
roots, respectively.
|
||||||
"""
|
"""
|
||||||
ws = Path(workspace).resolve()
|
ws = Path(workspace).resolve()
|
||||||
media = get_media_dir().resolve()
|
media = get_media_dir().resolve()
|
||||||
|
|||||||
@@ -1023,8 +1023,7 @@ class WebSearchTool(Tool):
|
|||||||
|
|
||||||
async def _search_duckduckgo(self, query: str, n: int) -> str:
|
async def _search_duckduckgo(self, query: str, n: int) -> str:
|
||||||
try:
|
try:
|
||||||
# Note: duckduckgo_search is synchronous and does its own requests
|
# DDGS.text performs synchronous requests; run it in a thread to avoid blocking the loop.
|
||||||
# We run it in a thread to avoid blocking the loop
|
|
||||||
from ddgs import DDGS # pyright: ignore[reportUnknownVariableType]
|
from ddgs import DDGS # pyright: ignore[reportUnknownVariableType]
|
||||||
|
|
||||||
ddgs_type = cast(Any, DDGS)
|
ddgs_type = cast(Any, DDGS)
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ class InboundMessage:
|
|||||||
chat_id: str # Chat/channel identifier
|
chat_id: str # Chat/channel identifier
|
||||||
content: str # Message text
|
content: str # Message text
|
||||||
timestamp: datetime = field(default_factory=datetime.now)
|
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
|
metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data
|
||||||
session_key_override: str | None = None # Optional override for thread-scoped sessions
|
session_key_override: str | None = None # Optional override for thread-scoped sessions
|
||||||
require_existing_session: bool = False
|
require_existing_session: bool = False
|
||||||
|
|||||||
@@ -359,7 +359,7 @@ def _markdown_to_telegram_html(text: str) -> str:
|
|||||||
escaped = _escape_telegram_html(code)
|
escaped = _escape_telegram_html(code)
|
||||||
text = text.replace(f"\x00CB{i}\x00", f"<pre><code>{escaped}</code></pre>")
|
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>')
|
text = text.replace('⟪B⟫', '<b>').replace('⟪/B⟫', '</b>')
|
||||||
|
|
||||||
return text
|
return text
|
||||||
|
|||||||
@@ -216,11 +216,9 @@ class WeixinConfig(Base):
|
|||||||
reply_progress_messages: bool = False
|
reply_progress_messages: bool = False
|
||||||
reply_progress_max_messages: int = Field(default=2, ge=0, le=4)
|
reply_progress_max_messages: int = Field(default=2, ge=0, le=4)
|
||||||
context_message_budget: int = Field(default=8, ge=1, le=10)
|
context_message_budget: int = Field(default=8, ge=1, le=10)
|
||||||
# Default on: WeChat iLink has no native incremental delivery (send_delta is
|
# Default on: use the LLM streaming API even when block_streaming is off
|
||||||
# buffered and the final answer is still sent in one shot), so streaming has
|
# and visible delivery waits for stream end. This avoids upstream Anthropic
|
||||||
# zero user-facing effect here — it only switches the LLM call to the
|
# relays that drop tool_use id/name/input on the non-streaming Messages path (a common third-party
|
||||||
# streaming API. That 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.
|
# relay bug). Set to false only if a relay's streaming/SSE path is broken.
|
||||||
streaming: bool = True
|
streaming: bool = True
|
||||||
# Optional user-visible block streaming. Disabled by default because every
|
# 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._context_token_at: dict[str, float] = {}
|
||||||
self._pending_tool_hints: dict[str, list[str]] = {}
|
self._pending_tool_hints: dict[str, list[str]] = {}
|
||||||
# Buffers streamed content deltas per chat. WeChat iLink has no native
|
# Buffers streamed content deltas per chat. WeChat iLink has no native
|
||||||
# incremental delivery, so when streaming is enabled we accumulate the
|
# incremental delivery. Optional block streaming sends bounded messages
|
||||||
# deltas and flush the full reply in one shot at _stream_end.
|
# while deltas arrive; stream end flushes the remaining buffered reply.
|
||||||
self._stream_buffers: dict[str, list[str]] = {}
|
self._stream_buffers: dict[str, list[str]] = {}
|
||||||
self._stream_sent_counts: dict[str, int] = {}
|
self._stream_sent_counts: dict[str, int] = {}
|
||||||
self._stream_live_disabled: set[str] = set()
|
self._stream_live_disabled: set[str] = set()
|
||||||
@@ -2126,10 +2124,10 @@ class WeixinChannel(BaseChannel):
|
|||||||
) -> None:
|
) -> None:
|
||||||
"""Deliver a streamed reply to WeChat.
|
"""Deliver a streamed reply to WeChat.
|
||||||
|
|
||||||
WeChat iLink has no native incremental delivery, and the manager
|
WeChat iLink has no native incremental delivery. Optional block streaming
|
||||||
bypasses :meth:`send` for the ``_streamed`` final answer. So we
|
sends bounded messages while deltas arrive; stream end flushes the
|
||||||
accumulate content deltas and flush the full reply as a single message
|
remaining reply. The manager skips the final ``StreamedResponseEvent``
|
||||||
at stream end. Reasoning deltas are invisible in WeChat and are dropped.
|
to avoid duplicate delivery. Reasoning deltas are dropped.
|
||||||
"""
|
"""
|
||||||
meta = metadata or {}
|
meta = metadata or {}
|
||||||
if meta.get("_reasoning_delta") or meta.get("_reasoning"):
|
if meta.get("_reasoning_delta") or meta.get("_reasoning"):
|
||||||
|
|||||||
@@ -279,7 +279,7 @@ async def cmd_status(ctx: CommandContext) -> OutboundMessage:
|
|||||||
if ctx_est <= 0:
|
if ctx_est <= 0:
|
||||||
ctx_est = last_usage.input_tokens if last_usage is not None else 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
|
search_usage_text: str | None = None
|
||||||
# Never let usage fetch break /status
|
# Never let usage fetch break /status
|
||||||
with suppress(Exception):
|
with suppress(Exception):
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ def get_logs_dir() -> Path:
|
|||||||
|
|
||||||
|
|
||||||
def get_webui_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")
|
return get_runtime_subdir("webui")
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
# pyright: reportPrivateImportUsage=false
|
||||||
|
|
||||||
@@ -478,7 +478,7 @@ def _merge_responses_extra_body(
|
|||||||
|
|
||||||
|
|
||||||
class OpenAICompatProvider(LLMProvider):
|
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
|
Receives a resolved ``ProviderSpec`` from the caller — no internal
|
||||||
registry lookups needed.
|
registry lookups needed.
|
||||||
@@ -552,9 +552,8 @@ class OpenAICompatProvider(LLMProvider):
|
|||||||
elif self._is_local:
|
elif self._is_local:
|
||||||
# Local model servers (Ollama, llama.cpp, vLLM) often close idle
|
# Local model servers (Ollama, llama.cpp, vLLM) often close idle
|
||||||
# HTTP connections before the client-side keepalive expires. When
|
# HTTP connections before the client-side keepalive expires. When
|
||||||
# two LLM calls happen seconds apart (e.g. heartbeat _decide then
|
# two LLM calls happen seconds apart, the second may grab a dead
|
||||||
# process_direct), the second call may grab a now-dead pooled
|
# pooled connection, causing a transient APIConnectionError on every first
|
||||||
# connection, causing a transient APIConnectionError on every first
|
|
||||||
# attempt. Disabling keepalive for local endpoints avoids this by
|
# attempt. Disabling keepalive for local endpoints avoids this by
|
||||||
# opening a fresh connection for each request, which is cheap on a
|
# opening a fresh connection for each request, which is cheap on a
|
||||||
# LAN. Cloud providers benefit from keepalive, so we leave the
|
# LAN. Cloud providers benefit from keepalive, so we leave the
|
||||||
|
|||||||
@@ -1593,7 +1593,7 @@ class SessionManager:
|
|||||||
return JsonlSessionStore.session_key_from_path(path)
|
return JsonlSessionStore.session_key_from_path(path)
|
||||||
|
|
||||||
def _get_session_path(self, key: str) -> 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)
|
return self._jsonl_store.get_session_path(key)
|
||||||
|
|
||||||
def _get_runtime_checkpoint_path(self, key: str) -> Path:
|
def _get_runtime_checkpoint_path(self, key: str) -> Path:
|
||||||
|
|||||||
@@ -1155,7 +1155,7 @@ class TestSummaryPersistence:
|
|||||||
loop.sessions.invalidate("cli:test")
|
loop.sessions.invalidate("cli:test")
|
||||||
reloaded = loop.sessions.get_or_create("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")
|
_, summary = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||||
assert summary is not None
|
assert summary is not None
|
||||||
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
_, summary2 = loop.auto_compact.prepare_session(reloaded, "cli:test")
|
||||||
@@ -1167,7 +1167,7 @@ class TestSummaryPersistence:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_metadata_cleanup_on_inmemory_path(self, tmp_path):
|
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)
|
loop = _make_loop(tmp_path, session_ttl_minutes=15)
|
||||||
session = loop.sessions.get_or_create("cli:test")
|
session = loop.sessions.get_or_create("cli:test")
|
||||||
_add_turns(session, 6, prefix="hello")
|
_add_turns(session, 6, prefix="hello")
|
||||||
|
|||||||
@@ -365,7 +365,7 @@ class TestConsolidatorSummarize:
|
|||||||
async def test_summarize_raw_dumps_on_llm_failure(
|
async def test_summarize_raw_dumps_on_llm_failure(
|
||||||
self, consolidator, mock_provider, store, runtime
|
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")
|
mock_provider.chat_stream_with_retry.side_effect = Exception("API error")
|
||||||
messages = [{"role": "user", "content": "hello"}]
|
messages = [{"role": "user", "content": "hello"}]
|
||||||
result = await _archive(consolidator, messages, runtime)
|
result = await _archive(consolidator, messages, runtime)
|
||||||
@@ -1605,7 +1605,7 @@ class TestRawArchiveTruncation:
|
|||||||
assert "PUBLIC_TAIL" in joined
|
assert "PUBLIC_TAIL" in joined
|
||||||
|
|
||||||
def test_raw_archive_truncates_large_content(self, store):
|
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
|
big = "x" * 50_000
|
||||||
messages = [{"role": "user", "content": big}]
|
messages = [{"role": "user", "content": big}]
|
||||||
store.raw_archive(messages)
|
store.raw_archive(messages)
|
||||||
|
|||||||
@@ -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
|
import asyncio
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -277,7 +277,7 @@ class TestToolEventProgress:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_bus_progress_forwards_tool_events_to_outbound_metadata(self, tmp_path: Path) -> None:
|
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()
|
bus = MessageBus()
|
||||||
provider = MagicMock()
|
provider = MagicMock()
|
||||||
provider.get_default_model.return_value = "test-model"
|
provider.get_default_model.return_value = "test-model"
|
||||||
|
|||||||
@@ -507,8 +507,7 @@ async def test_loop_retries_think_only_final_response(tmp_path):
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_streamed_flag_not_set_on_llm_error(tmp_path):
|
async def test_streamed_flag_not_set_on_llm_error(tmp_path):
|
||||||
"""When LLM errors during a streaming-capable channel interaction,
|
"""LLM errors must not produce StreamedResponseEvent, so channels deliver the error."""
|
||||||
_streamed must NOT be set so ChannelManager delivers the error."""
|
|
||||||
from nanobot.agent.loop import AgentLoop
|
from nanobot.agent.loop import AgentLoop
|
||||||
from nanobot.bus.events import InboundMessage
|
from nanobot.bus.events import InboundMessage
|
||||||
from nanobot.bus.queue import MessageBus
|
from nanobot.bus.queue import MessageBus
|
||||||
|
|||||||
Reference in new issue
Block a user