From b523b277b05c6ed1c51c5ea44364787b71e3c592 Mon Sep 17 00:00:00 2001 From: Harry Zhou Date: Sat, 14 Feb 2026 23:44:03 +0800 Subject: [PATCH 001/154] fix(agent): handle non-string values in memory consolidation Fix TypeError when LLM returns JSON objects instead of strings for history_entry or memory_update. Changes: - Update prompt to explicitly require string values with example - Add type checking and conversion for non-string values - Use json.dumps() for consistent JSON formatting Fixes potential memory consolidation failures when LLM interprets the prompt loosely and returns structured objects instead of strings. --- nanobot/agent/loop.py | 14 +++ tests/test_memory_consolidation_types.py | 133 +++++++++++++++++++++++ 2 files changed, 147 insertions(+) create mode 100644 tests/test_memory_consolidation_types.py diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index c256a56..e28166f 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -384,6 +384,14 @@ class AgentLoop: ## Conversation to Process {conversation} +**IMPORTANT**: Both values MUST be strings, not objects or arrays. + +Example: +{{ + "history_entry": "[2026-02-14 22:50] User asked about...", + "memory_update": "- Host: HARRYBOOK-T14P\n- Name: Nado" +}} + Respond with ONLY valid JSON, no markdown fences.""" try: @@ -400,8 +408,14 @@ Respond with ONLY valid JSON, no markdown fences.""" result = json.loads(text) if entry := result.get("history_entry"): + # Defensive: ensure entry is a string (LLM may return dict) + if not isinstance(entry, str): + entry = json.dumps(entry, ensure_ascii=False) memory.append_history(entry) if update := result.get("memory_update"): + # Defensive: ensure update is a string + if not isinstance(update, str): + update = json.dumps(update, ensure_ascii=False) if update != current_memory: memory.write_long_term(update) diff --git a/tests/test_memory_consolidation_types.py b/tests/test_memory_consolidation_types.py new file mode 100644 index 0000000..3b76596 --- /dev/null +++ b/tests/test_memory_consolidation_types.py @@ -0,0 +1,133 @@ +"""Test memory consolidation handles non-string values from LLM. + +This test verifies the fix for the bug where memory consolidation fails +when LLM returns JSON objects instead of strings for history_entry or +memory_update fields. + +Related issue: Memory consolidation fails with TypeError when LLM returns dict +""" + +import json +import tempfile +from pathlib import Path + +import pytest + +from nanobot.agent.memory import MemoryStore + + +class TestMemoryConsolidationTypeHandling: + """Test that MemoryStore methods handle type conversion correctly.""" + + def test_append_history_accepts_string(self): + """MemoryStore.append_history should accept string values.""" + with tempfile.TemporaryDirectory() as tmpdir: + memory = MemoryStore(Path(tmpdir)) + + # Should not raise TypeError + memory.append_history("[2026-02-14] Test entry") + + # Verify content was written + history_content = memory.history_file.read_text() + assert "Test entry" in history_content + + def test_write_long_term_accepts_string(self): + """MemoryStore.write_long_term should accept string values.""" + with tempfile.TemporaryDirectory() as tmpdir: + memory = MemoryStore(Path(tmpdir)) + + # Should not raise TypeError + memory.write_long_term("- Fact 1\n- Fact 2") + + # Verify content was written + memory_content = memory.read_long_term() + assert "Fact 1" in memory_content + + def test_type_conversion_dict_to_str(self): + """Dict values should be converted to JSON strings.""" + input_val = {"timestamp": "2026-02-14", "summary": "test"} + expected = '{"timestamp": "2026-02-14", "summary": "test"}' + + # Simulate the fix logic + if not isinstance(input_val, str): + result = json.dumps(input_val, ensure_ascii=False) + else: + result = input_val + + assert result == expected + assert isinstance(result, str) + + def test_type_conversion_list_to_str(self): + """List values should be converted to JSON strings.""" + input_val = ["item1", "item2"] + expected = '["item1", "item2"]' + + # Simulate the fix logic + if not isinstance(input_val, str): + result = json.dumps(input_val, ensure_ascii=False) + else: + result = input_val + + assert result == expected + assert isinstance(result, str) + + def test_type_conversion_str_unchanged(self): + """String values should remain unchanged.""" + input_val = "already a string" + + # Simulate the fix logic + if not isinstance(input_val, str): + result = json.dumps(input_val, ensure_ascii=False) + else: + result = input_val + + assert result == input_val + assert isinstance(result, str) + + def test_memory_consolidation_simulation(self): + """Simulate full consolidation with dict values from LLM.""" + with tempfile.TemporaryDirectory() as tmpdir: + memory = MemoryStore(Path(tmpdir)) + + # Simulate LLM returning dict values (the bug scenario) + history_entry = {"timestamp": "2026-02-14", "summary": "User asked about..."} + memory_update = {"facts": ["Location: Beijing", "Skill: Python"]} + + # Apply the fix: convert to str + if not isinstance(history_entry, str): + history_entry = json.dumps(history_entry, ensure_ascii=False) + if not isinstance(memory_update, str): + memory_update = json.dumps(memory_update, ensure_ascii=False) + + # Should not raise TypeError after conversion + memory.append_history(history_entry) + memory.write_long_term(memory_update) + + # Verify content + assert memory.history_file.exists() + assert memory.memory_file.exists() + + history_content = memory.history_file.read_text() + memory_content = memory.read_long_term() + + assert "timestamp" in history_content + assert "facts" in memory_content + + +class TestPromptOptimization: + """Test that prompt optimization helps prevent the issue.""" + + def test_prompt_includes_string_requirement(self): + """The prompt should explicitly require string values.""" + # This is a documentation test - verify the fix is in place + # by checking the expected prompt content + expected_keywords = [ + "MUST be strings", + "not objects or arrays", + "Example:", + ] + + # The actual prompt content is in nanobot/agent/loop.py + # This test serves as documentation of the expected behavior + for keyword in expected_keywords: + assert keyword, f"Prompt should include: {keyword}" From fbbbdc727ddec942279a5d0ccc3c37b1bc08ab23 Mon Sep 17 00:00:00 2001 From: Oleg Medvedev Date: Sat, 14 Feb 2026 13:38:49 -0600 Subject: [PATCH 002/154] fix(tools): resolve relative file paths against workspace File tools now resolve relative paths (e.g., "test.txt") against the workspace directory instead of the current working directory. This fixes failures when models use simple filenames instead of full paths. - Add workspace parameter to _resolve_path() in filesystem.py - Update all file tools to accept workspace in constructor - Pass workspace when registering tools in AgentLoop --- nanobot/agent/loop.py | 10 +++--- nanobot/agent/tools/filesystem.py | 59 +++++++++++++++++-------------- 2 files changed, 38 insertions(+), 31 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index c256a56..3d9f77b 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -86,12 +86,12 @@ class AgentLoop: def _register_default_tools(self) -> None: """Register the default set of tools.""" - # File tools (restrict to workspace if configured) + # File tools (workspace for relative paths, restrict if configured) allowed_dir = self.workspace if self.restrict_to_workspace else None - self.tools.register(ReadFileTool(allowed_dir=allowed_dir)) - self.tools.register(WriteFileTool(allowed_dir=allowed_dir)) - self.tools.register(EditFileTool(allowed_dir=allowed_dir)) - self.tools.register(ListDirTool(allowed_dir=allowed_dir)) + self.tools.register(ReadFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) + self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) + self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) + self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) # Shell tool self.tools.register(ExecTool( diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index 6b3254a..419b088 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -6,9 +6,12 @@ from typing import Any from nanobot.agent.tools.base import Tool -def _resolve_path(path: str, allowed_dir: Path | None = None) -> Path: - """Resolve path and optionally enforce directory restriction.""" - resolved = Path(path).expanduser().resolve() +def _resolve_path(path: str, workspace: Path | None = None, allowed_dir: Path | None = None) -> Path: + """Resolve path against workspace (if relative) and enforce directory restriction.""" + p = Path(path).expanduser() + if not p.is_absolute() and workspace: + p = workspace / p + resolved = p.resolve() if allowed_dir and not str(resolved).startswith(str(allowed_dir.resolve())): raise PermissionError(f"Path {path} is outside allowed directory {allowed_dir}") return resolved @@ -16,8 +19,9 @@ def _resolve_path(path: str, allowed_dir: Path | None = None) -> Path: class ReadFileTool(Tool): """Tool to read file contents.""" - - def __init__(self, allowed_dir: Path | None = None): + + def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None): + self._workspace = workspace self._allowed_dir = allowed_dir @property @@ -43,12 +47,12 @@ class ReadFileTool(Tool): async def execute(self, path: str, **kwargs: Any) -> str: try: - file_path = _resolve_path(path, self._allowed_dir) + file_path = _resolve_path(path, self._workspace, self._allowed_dir) if not file_path.exists(): return f"Error: File not found: {path}" if not file_path.is_file(): return f"Error: Not a file: {path}" - + content = file_path.read_text(encoding="utf-8") return content except PermissionError as e: @@ -59,8 +63,9 @@ class ReadFileTool(Tool): class WriteFileTool(Tool): """Tool to write content to a file.""" - - def __init__(self, allowed_dir: Path | None = None): + + def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None): + self._workspace = workspace self._allowed_dir = allowed_dir @property @@ -90,10 +95,10 @@ class WriteFileTool(Tool): async def execute(self, path: str, content: str, **kwargs: Any) -> str: try: - file_path = _resolve_path(path, self._allowed_dir) + file_path = _resolve_path(path, self._workspace, self._allowed_dir) file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content, encoding="utf-8") - return f"Successfully wrote {len(content)} bytes to {path}" + return f"Successfully wrote {len(content)} bytes to {file_path}" except PermissionError as e: return f"Error: {e}" except Exception as e: @@ -102,8 +107,9 @@ class WriteFileTool(Tool): class EditFileTool(Tool): """Tool to edit a file by replacing text.""" - - def __init__(self, allowed_dir: Path | None = None): + + def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None): + self._workspace = workspace self._allowed_dir = allowed_dir @property @@ -137,24 +143,24 @@ class EditFileTool(Tool): async def execute(self, path: str, old_text: str, new_text: str, **kwargs: Any) -> str: try: - file_path = _resolve_path(path, self._allowed_dir) + file_path = _resolve_path(path, self._workspace, self._allowed_dir) if not file_path.exists(): return f"Error: File not found: {path}" - + content = file_path.read_text(encoding="utf-8") - + if old_text not in content: return f"Error: old_text not found in file. Make sure it matches exactly." - + # Count occurrences count = content.count(old_text) if count > 1: return f"Warning: old_text appears {count} times. Please provide more context to make it unique." - + new_content = content.replace(old_text, new_text, 1) file_path.write_text(new_content, encoding="utf-8") - - return f"Successfully edited {path}" + + return f"Successfully edited {file_path}" except PermissionError as e: return f"Error: {e}" except Exception as e: @@ -163,8 +169,9 @@ class EditFileTool(Tool): class ListDirTool(Tool): """Tool to list directory contents.""" - - def __init__(self, allowed_dir: Path | None = None): + + def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None): + self._workspace = workspace self._allowed_dir = allowed_dir @property @@ -190,20 +197,20 @@ class ListDirTool(Tool): async def execute(self, path: str, **kwargs: Any) -> str: try: - dir_path = _resolve_path(path, self._allowed_dir) + dir_path = _resolve_path(path, self._workspace, self._allowed_dir) if not dir_path.exists(): return f"Error: Directory not found: {path}" if not dir_path.is_dir(): return f"Error: Not a directory: {path}" - + items = [] for item in sorted(dir_path.iterdir()): prefix = "πŸ“ " if item.is_dir() else "πŸ“„ " items.append(f"{prefix}{item.name}") - + if not items: return f"Directory {path} is empty" - + return "\n".join(items) except PermissionError as e: return f"Error: {e}" From e44f14379a289f900556fa3d6f255f446aee634f Mon Sep 17 00:00:00 2001 From: Ivan Date: Wed, 18 Feb 2026 11:57:58 +0300 Subject: [PATCH 003/154] fix: sanitize messages and ensure 'content' for strict LLM providers - Strip non-standard keys like 'reasoning_content' before sending to LLM - Always include 'content' key in assistant messages (required by StepFun) - Add _sanitize_messages to LiteLLMProvider to prevent 400 BadRequest errors --- nanobot/agent/context.py | 6 +++--- nanobot/providers/litellm_provider.py | 26 +++++++++++++++++++++++++- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index cfd6318..458016e 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -227,9 +227,9 @@ To recall past events, grep {workspace_path}/memory/HISTORY.md""" """ msg: dict[str, Any] = {"role": "assistant"} - # Omit empty content β€” some backends reject empty text blocks - if content: - msg["content"] = content + # Always include content β€” some providers (e.g. StepFun) reject + # assistant messages that omit the key entirely. + msg["content"] = content if tool_calls: msg["tool_calls"] = tool_calls diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 8cc4e35..58acf95 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -12,6 +12,12 @@ from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest from nanobot.providers.registry import find_by_model, find_gateway +# Keys that are part of the OpenAI chat-completion message schema. +# Anything else (e.g. reasoning_content, timestamp) is stripped before sending +# to avoid "Unrecognized chat message" errors from strict providers like StepFun. +_ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name"}) + + class LiteLLMProvider(LLMProvider): """ LLM provider using LiteLLM for multi-provider support. @@ -103,6 +109,24 @@ class LiteLLMProvider(LLMProvider): kwargs.update(overrides) return + @staticmethod + def _sanitize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Strip non-standard keys from messages for strict providers. + + Some providers (e.g. StepFun via OpenRouter) reject messages that + contain extra keys like ``reasoning_content``. This method keeps + only the keys defined in the OpenAI chat-completion schema and + ensures every assistant message has a ``content`` key. + """ + sanitized = [] + for msg in messages: + clean = {k: v for k, v in msg.items() if k in _ALLOWED_MSG_KEYS} + # Strict providers require "content" even when assistant only has tool_calls + if clean.get("role") == "assistant" and "content" not in clean: + clean["content"] = None + sanitized.append(clean) + return sanitized + async def chat( self, messages: list[dict[str, Any]], @@ -132,7 +156,7 @@ class LiteLLMProvider(LLMProvider): kwargs: dict[str, Any] = { "model": model, - "messages": messages, + "messages": self._sanitize_messages(messages), "max_tokens": max_tokens, "temperature": temperature, } From c5b4331e692c09bb285a5c8e3d811dbfca52b273 Mon Sep 17 00:00:00 2001 From: dxtime Date: Thu, 19 Feb 2026 01:21:17 +0800 Subject: [PATCH 004/154] feature: Added custom headers for MCP Auth use. --- nanobot/agent/tools/mcp.py | 18 +++++++++++++++--- nanobot/config/schema.py | 1 + 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index 1c8eac4..4d5c053 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -59,9 +59,21 @@ async def connect_mcp_servers( read, write = await stack.enter_async_context(stdio_client(params)) elif cfg.url: from mcp.client.streamable_http import streamable_http_client - read, write, _ = await stack.enter_async_context( - streamable_http_client(cfg.url) - ) + import httpx + if cfg.headers: + http_client = await stack.enter_async_context( + httpx.AsyncClient( + headers=cfg.headers, + follow_redirects=True + ) + ) + read, write, _ = await stack.enter_async_context( + streamable_http_client(cfg.url, http_client=http_client) + ) + else: + read, write, _ = await stack.enter_async_context( + streamable_http_client(cfg.url) + ) else: logger.warning(f"MCP server '{name}': no command or url configured, skipping") continue diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index ce9634c..e404d3c 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -257,6 +257,7 @@ class MCPServerConfig(Base): args: list[str] = Field(default_factory=list) # Stdio: command arguments env: dict[str, str] = Field(default_factory=dict) # Stdio: extra env vars url: str = "" # HTTP: streamable HTTP endpoint URL + headers: dict[str, str] = Field(default_factory=dict) # HTTP: Custom HTTP Headers class ToolsConfig(Base): From 4a85cd9a1102871aa900b906ffb8ca4c89d206d0 Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Tue, 17 Feb 2026 13:18:43 +0100 Subject: [PATCH 005/154] fix(cron): add service-layer timezone validation Adds `_validate_schedule_for_add()` to `CronService.add_job` so that invalid or misplaced `tz` values are rejected before a job is persisted, regardless of which caller (CLI, tool, etc.) invoked the service. Surfaces the resulting `ValueError` in `nanobot cron add` via a `try/except` so the CLI exits cleanly with a readable error message. Co-Authored-By: Claude Sonnet 4.6 --- nanobot/cli/commands.py | 22 +++++++++++++--------- nanobot/cron/service.py | 15 +++++++++++++++ tests/test_cron_commands.py | 29 +++++++++++++++++++++++++++++ tests/test_cron_service.py | 30 ++++++++++++++++++++++++++++++ 4 files changed, 87 insertions(+), 9 deletions(-) create mode 100644 tests/test_cron_commands.py create mode 100644 tests/test_cron_service.py diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index b61d9aa..668fcb5 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -787,15 +787,19 @@ def cron_add( store_path = get_data_dir() / "cron" / "jobs.json" service = CronService(store_path) - job = service.add_job( - name=name, - schedule=schedule, - message=message, - deliver=deliver, - to=to, - channel=channel, - ) - + try: + job = service.add_job( + name=name, + schedule=schedule, + message=message, + deliver=deliver, + to=to, + channel=channel, + ) + except ValueError as e: + console.print(f"[red]Error: {e}[/red]") + raise typer.Exit(1) from e + console.print(f"[green]βœ“[/green] Added job '{job.name}' ({job.id})") diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index 14666e8..7ae1153 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -45,6 +45,20 @@ def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None: return None +def _validate_schedule_for_add(schedule: CronSchedule) -> None: + """Validate schedule fields that would otherwise create non-runnable jobs.""" + if schedule.tz and schedule.kind != "cron": + raise ValueError("tz can only be used with cron schedules") + + if schedule.kind == "cron" and schedule.tz: + try: + from zoneinfo import ZoneInfo + + ZoneInfo(schedule.tz) + except Exception: + raise ValueError(f"unknown timezone '{schedule.tz}'") from None + + class CronService: """Service for managing and executing scheduled jobs.""" @@ -272,6 +286,7 @@ class CronService: ) -> CronJob: """Add a new job.""" store = self._load_store() + _validate_schedule_for_add(schedule) now = _now_ms() job = CronJob( diff --git a/tests/test_cron_commands.py b/tests/test_cron_commands.py new file mode 100644 index 0000000..bce1ef5 --- /dev/null +++ b/tests/test_cron_commands.py @@ -0,0 +1,29 @@ +from typer.testing import CliRunner + +from nanobot.cli.commands import app + +runner = CliRunner() + + +def test_cron_add_rejects_invalid_timezone(monkeypatch, tmp_path) -> None: + monkeypatch.setattr("nanobot.config.loader.get_data_dir", lambda: tmp_path) + + result = runner.invoke( + app, + [ + "cron", + "add", + "--name", + "demo", + "--message", + "hello", + "--cron", + "0 9 * * *", + "--tz", + "America/Vancovuer", + ], + ) + + assert result.exit_code == 1 + assert "Error: unknown timezone 'America/Vancovuer'" in result.stdout + assert not (tmp_path / "cron" / "jobs.json").exists() diff --git a/tests/test_cron_service.py b/tests/test_cron_service.py new file mode 100644 index 0000000..07e990a --- /dev/null +++ b/tests/test_cron_service.py @@ -0,0 +1,30 @@ +import pytest + +from nanobot.cron.service import CronService +from nanobot.cron.types import CronSchedule + + +def test_add_job_rejects_unknown_timezone(tmp_path) -> None: + service = CronService(tmp_path / "cron" / "jobs.json") + + with pytest.raises(ValueError, match="unknown timezone 'America/Vancovuer'"): + service.add_job( + name="tz typo", + schedule=CronSchedule(kind="cron", expr="0 9 * * *", tz="America/Vancovuer"), + message="hello", + ) + + assert service.list_jobs(include_disabled=True) == [] + + +def test_add_job_accepts_valid_timezone(tmp_path) -> None: + service = CronService(tmp_path / "cron" / "jobs.json") + + job = service.add_job( + name="tz ok", + schedule=CronSchedule(kind="cron", expr="0 9 * * *", tz="America/Vancouver"), + message="hello", + ) + + assert job.schedule.tz == "America/Vancouver" + assert job.state.next_run_at_ms is not None From 166351799894d2159465ad7b3753ece78b977cec Mon Sep 17 00:00:00 2001 From: Your Name Date: Thu, 19 Feb 2026 03:00:44 +0800 Subject: [PATCH 006/154] feat: Add VolcEngine LLM provider support - Add VolcEngine ProviderSpec entry in registry.py - Add volcengine to ProvidersConfig class in schema.py - Update model providers table in README.md - Add description about VolcEngine coding plan endpoint --- README.md | 2 ++ nanobot/config/schema.py | 1 + nanobot/providers/registry.py | 18 ++++++++++++++++++ 3 files changed, 21 insertions(+) diff --git a/README.md b/README.md index a474367..94cdc88 100644 --- a/README.md +++ b/README.md @@ -578,6 +578,7 @@ Config file: `~/.nanobot/config.json` > - **Groq** provides free voice transcription via Whisper. If configured, Telegram voice messages will be automatically transcribed. > - **Zhipu Coding Plan**: If you're on Zhipu's coding plan, set `"apiBase": "https://open.bigmodel.cn/api/coding/paas/v4"` in your zhipu provider config. > - **MiniMax (Mainland China)**: If your API key is from MiniMax's mainland China platform (minimaxi.com), set `"apiBase": "https://api.minimaxi.com/v1"` in your minimax provider config. +> - **VolcEngine Coding Plan**: If you're on VolcEngine's coding plan, set `"apiBase": "https://ark.cn-beijing.volces.com/api/coding/v3"` in your volcengine provider config. | Provider | Purpose | Get API Key | |----------|---------|-------------| @@ -591,6 +592,7 @@ Config file: `~/.nanobot/config.json` | `minimax` | LLM (MiniMax direct) | [platform.minimax.io](https://platform.minimax.io) | | `aihubmix` | LLM (API gateway, access to all models) | [aihubmix.com](https://aihubmix.com) | | `siliconflow` | LLM (SiliconFlow/η‘…εŸΊζ΅εŠ¨, API gateway) | [siliconflow.cn](https://siliconflow.cn) | +| `volcengine` | LLM (VolcEngine/η«ε±±εΌ•ζ“Ž) | [volcengine.com](https://www.volcengine.com) | | `dashscope` | LLM (Qwen) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | | `moonshot` | LLM (Moonshot/Kimi) | [platform.moonshot.cn](https://platform.moonshot.cn) | | `zhipu` | LLM (Zhipu GLM) | [open.bigmodel.cn](https://open.bigmodel.cn) | diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index ce9634c..0d0c68f 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -220,6 +220,7 @@ class ProvidersConfig(Base): minimax: ProviderConfig = Field(default_factory=ProviderConfig) aihubmix: ProviderConfig = Field(default_factory=ProviderConfig) # AiHubMix API gateway siliconflow: ProviderConfig = Field(default_factory=ProviderConfig) # SiliconFlow (η‘…εŸΊζ΅εŠ¨) API gateway + volcengine: ProviderConfig = Field(default_factory=ProviderConfig) # VolcEngine (η«ε±±εΌ•ζ“Ž) API gateway openai_codex: ProviderConfig = Field(default_factory=ProviderConfig) # OpenAI Codex (OAuth) github_copilot: ProviderConfig = Field(default_factory=ProviderConfig) # Github Copilot (OAuth) diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py index 49b735c..e44720a 100644 --- a/nanobot/providers/registry.py +++ b/nanobot/providers/registry.py @@ -137,6 +137,24 @@ PROVIDERS: tuple[ProviderSpec, ...] = ( model_overrides=(), ), + # VolcEngine (η«ε±±εΌ•ζ“Ž): OpenAI-compatible gateway + ProviderSpec( + name="volcengine", + keywords=("volcengine", "volces", "ark"), + env_key="OPENAI_API_KEY", + display_name="VolcEngine", + litellm_prefix="openai", + skip_prefixes=(), + env_extras=(), + is_gateway=True, + is_local=False, + detect_by_key_prefix="", + detect_by_base_keyword="volces", + default_api_base="https://ark.cn-beijing.volces.com/api/v3", + strip_model_prefix=False, + model_overrides=(), + ), + # === Standard providers (matched by model-name keywords) =============== # Anthropic: LiteLLM recognizes "claude-*" natively, no prefix needed. From c865b293a9a772c000eed0cda63eecbd2efa472e Mon Sep 17 00:00:00 2001 From: Darye <54469750+DaryeDev@users.noreply.github.com> Date: Wed, 18 Feb 2026 20:18:27 +0100 Subject: [PATCH 007/154] feat: enhance message context handling by adding message_id parameter --- nanobot/agent/loop.py | 8 ++++---- nanobot/agent/tools/message.py | 14 +++++++++++--- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..7855297 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -133,11 +133,11 @@ class AgentLoop: await self._mcp_stack.__aenter__() await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) - def _set_tool_context(self, channel: str, chat_id: str) -> None: + def _set_tool_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None: """Update context for all tools that need routing info.""" if message_tool := self.tools.get("message"): if isinstance(message_tool, MessageTool): - message_tool.set_context(channel, chat_id) + message_tool.set_context(channel, chat_id, message_id) if spawn_tool := self.tools.get("spawn"): if isinstance(spawn_tool, SpawnTool): @@ -321,7 +321,7 @@ class AgentLoop: if len(session.messages) > self.memory_window: asyncio.create_task(self._consolidate_memory(session)) - self._set_tool_context(msg.channel, msg.chat_id) + self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id")) initial_messages = self.context.build_messages( history=session.get_history(max_messages=self.memory_window), current_message=msg.content, @@ -379,7 +379,7 @@ class AgentLoop: session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) - self._set_tool_context(origin_channel, origin_chat_id) + self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) initial_messages = self.context.build_messages( history=session.get_history(max_messages=self.memory_window), current_message=msg.content, diff --git a/nanobot/agent/tools/message.py b/nanobot/agent/tools/message.py index 3853725..10947c4 100644 --- a/nanobot/agent/tools/message.py +++ b/nanobot/agent/tools/message.py @@ -13,16 +13,19 @@ class MessageTool(Tool): self, send_callback: Callable[[OutboundMessage], Awaitable[None]] | None = None, default_channel: str = "", - default_chat_id: str = "" + default_chat_id: str = "", + default_message_id: str | None = None ): self._send_callback = send_callback self._default_channel = default_channel self._default_chat_id = default_chat_id + self._default_message_id = default_message_id - def set_context(self, channel: str, chat_id: str) -> None: + def set_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None: """Set the current message context.""" self._default_channel = channel self._default_chat_id = chat_id + self._default_message_id = message_id def set_send_callback(self, callback: Callable[[OutboundMessage], Awaitable[None]]) -> None: """Set the callback for sending messages.""" @@ -67,11 +70,13 @@ class MessageTool(Tool): content: str, channel: str | None = None, chat_id: str | None = None, + message_id: str | None = None, media: list[str] | None = None, **kwargs: Any ) -> str: channel = channel or self._default_channel chat_id = chat_id or self._default_chat_id + message_id = message_id or self._default_message_id if not channel or not chat_id: return "Error: No target channel/chat specified" @@ -83,7 +88,10 @@ class MessageTool(Tool): channel=channel, chat_id=chat_id, content=content, - media=media or [] + media=media or [], + metadata={ + "message_id": message_id, + } ) try: From 3ac55130042ad7b98a2416ef3802bc1a576df248 Mon Sep 17 00:00:00 2001 From: Darye <54469750+DaryeDev@users.noreply.github.com> Date: Wed, 18 Feb 2026 20:27:48 +0100 Subject: [PATCH 008/154] If given a message_id to telegram provider send, the bot will try to reply to that message --- nanobot/channels/telegram.py | 36 +++++++++++++++++++++++++++++++----- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.py index 39924b3..3a90d42 100644 --- a/nanobot/channels/telegram.py +++ b/nanobot/channels/telegram.py @@ -5,7 +5,7 @@ from __future__ import annotations import asyncio import re from loguru import logger -from telegram import BotCommand, Update +from telegram import BotCommand, Update, ReplyParameters from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes from telegram.request import HTTPXRequest @@ -224,6 +224,15 @@ class TelegramChannel(BaseChannel): logger.error(f"Invalid chat_id: {msg.chat_id}") return + # Build reply parameters (Will reply to the message if it exists) + reply_to_message_id = msg.metadata.get("message_id") + reply_params = None + if reply_to_message_id: + reply_params = ReplyParameters( + message_id=reply_to_message_id, + allow_sending_without_reply=True + ) + # Send media files for media_path in (msg.media or []): try: @@ -235,22 +244,39 @@ class TelegramChannel(BaseChannel): }.get(media_type, self._app.bot.send_document) param = "photo" if media_type == "photo" else media_type if media_type in ("voice", "audio") else "document" with open(media_path, 'rb') as f: - await sender(chat_id=chat_id, **{param: f}) + await sender( + chat_id=chat_id, + **{param: f}, + reply_parameters=reply_params + ) except Exception as e: filename = media_path.rsplit("/", 1)[-1] logger.error(f"Failed to send media {media_path}: {e}") - await self._app.bot.send_message(chat_id=chat_id, text=f"[Failed to send: {filename}]") + await self._app.bot.send_message( + chat_id=chat_id, + text=f"[Failed to send: {filename}]", + reply_parameters=reply_params + ) # Send text content if msg.content and msg.content != "[empty message]": for chunk in _split_message(msg.content): try: html = _markdown_to_telegram_html(chunk) - await self._app.bot.send_message(chat_id=chat_id, text=html, parse_mode="HTML") + await self._app.bot.send_message( + chat_id=chat_id, + text=html, + parse_mode="HTML", + reply_parameters=reply_params + ) except Exception as e: logger.warning(f"HTML parse failed, falling back to plain text: {e}") try: - await self._app.bot.send_message(chat_id=chat_id, text=chunk) + await self._app.bot.send_message( + chat_id=chat_id, + text=chunk, + reply_parameters=reply_params + ) except Exception as e2: logger.error(f"Error sending Telegram message: {e2}") From 4367038a95a8ae96e0fdfbb37b5488cd9a9fbe49 Mon Sep 17 00:00:00 2001 From: Clayton Wilson Date: Wed, 18 Feb 2026 13:32:06 -0600 Subject: [PATCH 009/154] fix: make cron run command actually execute the agent Wire up an AgentLoop with an on_job callback in the cron_run CLI command so the job's message is sent to the agent and the response is printed. Previously, CronService was created with no on_job callback, causing _execute_job to skip execution silently and always report success. Co-Authored-By: Claude Sonnet 4.6 --- nanobot/cli/commands.py | 44 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 39 insertions(+), 5 deletions(-) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 2f4ba7b..a45b4a7 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -860,17 +860,51 @@ def cron_run( force: bool = typer.Option(False, "--force", "-f", help="Run even if disabled"), ): """Manually run a job.""" - from nanobot.config.loader import get_data_dir + from nanobot.config.loader import load_config, get_data_dir from nanobot.cron.service import CronService - + from nanobot.bus.queue import MessageBus + from nanobot.agent.loop import AgentLoop + from loguru import logger + logger.disable("nanobot") + + config = load_config() + provider = _make_provider(config) + bus = MessageBus() + agent_loop = AgentLoop( + bus=bus, + provider=provider, + workspace=config.workspace_path, + model=config.agents.defaults.model, + max_iterations=config.agents.defaults.max_tool_iterations, + memory_window=config.agents.defaults.memory_window, + exec_config=config.tools.exec, + restrict_to_workspace=config.tools.restrict_to_workspace, + ) + store_path = get_data_dir() / "cron" / "jobs.json" service = CronService(store_path) - + + result_holder = [] + + async def on_job(job): + response = await agent_loop.process_direct( + job.payload.message, + session_key=f"cron:{job.id}", + channel=job.payload.channel or "cli", + chat_id=job.payload.to or "direct", + ) + result_holder.append(response) + return response + + service.on_job = on_job + async def run(): return await service.run_job(job_id, force=force) - + if asyncio.run(run()): - console.print(f"[green]βœ“[/green] Job executed") + console.print("[green]βœ“[/green] Job executed") + if result_holder: + _print_agent_response(result_holder[0], render_markdown=True) else: console.print(f"[red]Failed to run job {job_id}[/red]") From 107a380e61a57d72a23ea84c6ba8b68e0e2936cb Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Wed, 18 Feb 2026 21:22:22 -0300 Subject: [PATCH 010/154] fix: prevent duplicate memory consolidation tasks per session MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add a `_consolidating` set to track which sessions have an active consolidation task. Skip creating a new task if one is already in progress for the same session key, and clean up the flag when done. This prevents the excessive API calls reported when messages exceed the memory_window threshold β€” previously every single message after the threshold triggered a new background consolidation. Closes #751 --- nanobot/agent/loop.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..0e5d3b3 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -89,6 +89,7 @@ class AgentLoop: self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None self._mcp_connected = False + self._consolidating: set[str] = set() # Session keys with consolidation in progress self._register_default_tools() def _register_default_tools(self) -> None: @@ -318,8 +319,16 @@ class AgentLoop: return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") - if len(session.messages) > self.memory_window: - asyncio.create_task(self._consolidate_memory(session)) + if len(session.messages) > self.memory_window and session.key not in self._consolidating: + self._consolidating.add(session.key) + + async def _consolidate_and_unlock(): + try: + await self._consolidate_memory(session) + finally: + self._consolidating.discard(session.key) + + asyncio.create_task(_consolidate_and_unlock()) self._set_tool_context(msg.channel, msg.chat_id) initial_messages = self.context.build_messages( From 33d760d31213edf8af992026d3a7e3da33bca52f Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Wed, 18 Feb 2026 21:27:13 -0300 Subject: [PATCH 011/154] fix: handle /help command directly in Telegram, bypassing ACL check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The /help command was routed through _forward_command β†’ _handle_message β†’ is_allowed(), which denied access to users not in the allowFrom list. Since /help is purely informational, it should be accessible to all users β€” similar to how /start already works with its own handler. Add a dedicated _on_help handler that replies directly without going through the message bus access control. Closes #687 --- nanobot/channels/telegram.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.py index 39924b3..fa48fef 100644 --- a/nanobot/channels/telegram.py +++ b/nanobot/channels/telegram.py @@ -146,7 +146,7 @@ class TelegramChannel(BaseChannel): # Add command handlers self._app.add_handler(CommandHandler("start", self._on_start)) self._app.add_handler(CommandHandler("new", self._forward_command)) - self._app.add_handler(CommandHandler("help", self._forward_command)) + self._app.add_handler(CommandHandler("help", self._on_help)) # Add message handler for text, photos, voice, documents self._app.add_handler( @@ -258,14 +258,28 @@ class TelegramChannel(BaseChannel): """Handle /start command.""" if not update.message or not update.effective_user: return - + user = update.effective_user await update.message.reply_text( f"πŸ‘‹ Hi {user.first_name}! I'm nanobot.\n\n" "Send me a message and I'll respond!\n" "Type /help to see available commands." ) - + + async def _on_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: + """Handle /help command directly, bypassing access control. + + /help is informational and should be accessible to all users, + even those not in the allowFrom list. + """ + if not update.message: + return + await update.message.reply_text( + "🐈 nanobot commands:\n" + "/new β€” Start a new conversation\n" + "/help β€” Show available commands" + ) + @staticmethod def _sender_id(user) -> str: """Build sender_id with username for allowlist matching.""" From 464352c664c0c059457b8cceafbaa3844011a1d9 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Wed, 18 Feb 2026 21:29:10 -0300 Subject: [PATCH 012/154] fix: allow one retry for models that send interim text before tool calls Some LLM providers (MiniMax, Gemini Flash, GPT-4.1, etc.) send an initial text-only response like "Let me investigate..." before actually making tool calls. The agent loop previously broke immediately on any text response without tool calls, preventing these models from ever using tools. Now, when the model responds with text but hasn't used any tools yet, the loop forwards the text as progress to the user and gives the model one additional iteration to make tool calls. This is limited to a single retry to prevent infinite loops. Closes #705 --- nanobot/agent/loop.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..6acbb38 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -183,6 +183,7 @@ class AgentLoop: iteration = 0 final_content = None tools_used: list[str] = [] + text_only_retried = False while iteration < self.max_iterations: iteration += 1 @@ -226,6 +227,21 @@ class AgentLoop: ) else: final_content = self._strip_think(response.content) + # Some models (MiniMax, Gemini Flash, GPT-4.1, etc.) send an + # interim text response (e.g. "Let me investigate...") before + # making tool calls. If no tools have been used yet and we + # haven't already retried, forward the text as progress and + # give the model one more chance to use tools. + if not tools_used and not text_only_retried and final_content: + text_only_retried = True + logger.debug(f"Interim text response (no tools used yet), retrying: {final_content[:80]}") + if on_progress: + await on_progress(final_content) + messages = self.context.add_assistant_message( + messages, response.content, + reasoning_content=response.reasoning_content, + ) + continue break return final_content, tools_used From c7b5dd93502a829da18e2a7ef2253ae3298f2f28 Mon Sep 17 00:00:00 2001 From: chtangwin Date: Tue, 10 Feb 2026 17:31:45 +0800 Subject: [PATCH 013/154] Fix: Ensure UTF-8 encoding for all file operations --- nanobot/agent/loop.py | 3 ++- nanobot/agent/subagent.py | 4 ++-- nanobot/config/loader.py | 2 +- nanobot/cron/service.py | 4 ++-- nanobot/session/manager.py | 11 ++++++----- 5 files changed, 13 insertions(+), 11 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..1cd5730 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -206,7 +206,7 @@ class AgentLoop: "type": "function", "function": { "name": tc.name, - "arguments": json.dumps(tc.arguments) + "arguments": json.dumps(tc.arguments, ensure_ascii=False) } } for tc in response.tool_calls @@ -388,6 +388,7 @@ class AgentLoop: ) final_content, _ = await self._run_agent_loop(initial_messages) + if final_content is None: final_content = "Background task completed." diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 203836a..ffefc08 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -146,7 +146,7 @@ class SubagentManager: "type": "function", "function": { "name": tc.name, - "arguments": json.dumps(tc.arguments), + "arguments": json.dumps(tc.arguments, ensure_ascii=False), }, } for tc in response.tool_calls @@ -159,7 +159,7 @@ class SubagentManager: # Execute tools for tool_call in response.tool_calls: - args_str = json.dumps(tool_call.arguments) + args_str = json.dumps(tool_call.arguments, ensure_ascii=False) logger.debug(f"Subagent [{task_id}] executing: {tool_call.name} with arguments: {args_str}") result = await tools.execute(tool_call.name, tool_call.arguments) messages.append({ diff --git a/nanobot/config/loader.py b/nanobot/config/loader.py index 560c1f5..134e95f 100644 --- a/nanobot/config/loader.py +++ b/nanobot/config/loader.py @@ -31,7 +31,7 @@ def load_config(config_path: Path | None = None) -> Config: if path.exists(): try: - with open(path) as f: + with open(path, encoding="utf-8") as f: data = json.load(f) data = _migrate_config(data) return Config.model_validate(data) diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index 14666e8..3c77452 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -66,7 +66,7 @@ class CronService: if self.store_path.exists(): try: - data = json.loads(self.store_path.read_text()) + data = json.loads(self.store_path.read_text(encoding="utf-8")) jobs = [] for j in data.get("jobs", []): jobs.append(CronJob( @@ -148,7 +148,7 @@ class CronService: ] } - self.store_path.write_text(json.dumps(data, indent=2)) + self.store_path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8") async def start(self) -> None: """Start the cron service.""" diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 752fce4..42df1b1 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -121,7 +121,7 @@ class SessionManager: created_at = None last_consolidated = 0 - with open(path) as f: + with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if not line: @@ -151,7 +151,7 @@ class SessionManager: """Save a session to disk.""" path = self._get_session_path(session.key) - with open(path, "w") as f: + with open(path, "w", encoding="utf-8") as f: metadata_line = { "_type": "metadata", "created_at": session.created_at.isoformat(), @@ -159,9 +159,10 @@ class SessionManager: "metadata": session.metadata, "last_consolidated": session.last_consolidated } - f.write(json.dumps(metadata_line) + "\n") + f.write(json.dumps(metadata_line, ensure_ascii=False) + "\n") for msg in session.messages: - f.write(json.dumps(msg) + "\n") + f.write(json.dumps(msg, ensure_ascii=False) + "\n") + self._cache[session.key] = session @@ -181,7 +182,7 @@ class SessionManager: for path in self.sessions_dir.glob("*.jsonl"): try: # Read just the metadata line - with open(path) as f: + with open(path, encoding="utf-8") as f: first_line = f.readline().strip() if first_line: data = json.loads(first_line) From a2379a08ac5467e4b3e628a7264427be73759a9f Mon Sep 17 00:00:00 2001 From: chtangwin Date: Wed, 18 Feb 2026 18:37:17 -0800 Subject: [PATCH 014/154] Fix: Ensure UTF-8 encoding and ensure_ascii=False for remaining file/JSON operations --- nanobot/agent/tools/web.py | 8 ++++---- nanobot/channels/dingtalk.py | 2 +- nanobot/cli/commands.py | 6 +++--- nanobot/config/loader.py | 4 ++-- nanobot/heartbeat/service.py | 2 +- 5 files changed, 11 insertions(+), 11 deletions(-) diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.py index 9de1d3c..90cdda8 100644 --- a/nanobot/agent/tools/web.py +++ b/nanobot/agent/tools/web.py @@ -116,7 +116,7 @@ class WebFetchTool(Tool): # Validate URL before fetching is_valid, error_msg = _validate_url(url) if not is_valid: - return json.dumps({"error": f"URL validation failed: {error_msg}", "url": url}) + return json.dumps({"error": f"URL validation failed: {error_msg}", "url": url}, ensure_ascii=False) try: async with httpx.AsyncClient( @@ -131,7 +131,7 @@ class WebFetchTool(Tool): # JSON if "application/json" in ctype: - text, extractor = json.dumps(r.json(), indent=2), "json" + text, extractor = json.dumps(r.json(), indent=2, ensure_ascii=False), "json" # HTML elif "text/html" in ctype or r.text[:256].lower().startswith((" str: """Convert HTML to markdown.""" diff --git a/nanobot/channels/dingtalk.py b/nanobot/channels/dingtalk.py index 4a8cdd9..6b27af4 100644 --- a/nanobot/channels/dingtalk.py +++ b/nanobot/channels/dingtalk.py @@ -208,7 +208,7 @@ class DingTalkChannel(BaseChannel): "msgParam": json.dumps({ "text": msg.content, "title": "Nanobot Reply", - }), + }, ensure_ascii=False), } if not self._http: diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 2f4ba7b..d879d58 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -243,7 +243,7 @@ Information about the user goes here. for filename, content in templates.items(): file_path = workspace / filename if not file_path.exists(): - file_path.write_text(content) + file_path.write_text(content, encoding="utf-8") console.print(f" [dim]Created {filename}[/dim]") # Create memory directory and MEMORY.md @@ -266,12 +266,12 @@ This file stores important information that should persist across sessions. ## Important Notes (Things to remember) -""") +""", encoding="utf-8") console.print(" [dim]Created memory/MEMORY.md[/dim]") history_file = memory_dir / "HISTORY.md" if not history_file.exists(): - history_file.write_text("") + history_file.write_text("", encoding="utf-8") console.print(" [dim]Created memory/HISTORY.md[/dim]") # Create skills directory for custom user skills diff --git a/nanobot/config/loader.py b/nanobot/config/loader.py index 134e95f..c789efd 100644 --- a/nanobot/config/loader.py +++ b/nanobot/config/loader.py @@ -55,8 +55,8 @@ def save_config(config: Config, config_path: Path | None = None) -> None: data = config.model_dump(by_alias=True) - with open(path, "w") as f: - json.dump(data, f, indent=2) + with open(path, "w", encoding="utf-8") as f: + json.dump(data, f, indent=2, ensure_ascii=False) def _migrate_config(data: dict) -> dict: diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index 221ed27..a51e5a0 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -65,7 +65,7 @@ class HeartbeatService: """Read HEARTBEAT.md content.""" if self.heartbeat_file.exists(): try: - return self.heartbeat_file.read_text() + return self.heartbeat_file.read_text(encoding="utf-8") except Exception: return None return None From 124c611426eefe06aeb9a5b3d33338286228bb8a Mon Sep 17 00:00:00 2001 From: chtangwin Date: Wed, 18 Feb 2026 18:46:23 -0800 Subject: [PATCH 015/154] Fix: Add ensure_ascii=False to WhatsApp send payload The send() payload contains user message content (msg.content) which may include non-ASCII characters (e.g. CJK, German umlauts, emoji). The auth frame and Discord heartbeat/identify payloads are left unchanged as they only carry ASCII protocol fields. --- nanobot/channels/whatsapp.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nanobot/channels/whatsapp.py b/nanobot/channels/whatsapp.py index 0cf2dd7..f799347 100644 --- a/nanobot/channels/whatsapp.py +++ b/nanobot/channels/whatsapp.py @@ -87,7 +87,7 @@ class WhatsAppChannel(BaseChannel): "to": msg.chat_id, "text": msg.content } - await self._ws.send(json.dumps(payload)) + await self._ws.send(json.dumps(payload, ensure_ascii=False)) except Exception as e: logger.error(f"Error sending WhatsApp message: {e}") From 523b2982f4fb2c0dcf74e3a4bb01ebf2a77fd529 Mon Sep 17 00:00:00 2001 From: Darye <54469750+DaryeDev@users.noreply.github.com> Date: Thu, 19 Feb 2026 05:22:00 +0100 Subject: [PATCH 016/154] fix: fixed not logging tool uses if a think fragment had them attached. if a think fragment had a tool attached, the tool use would not log. now it does --- nanobot/agent/loop.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..6b45b28 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -198,7 +198,9 @@ class AgentLoop: if response.has_tool_calls: if on_progress: clean = self._strip_think(response.content) - await on_progress(clean or self._tool_hint(response.tool_calls)) + if clean: + await on_progress(clean) + await on_progress(self._tool_hint(response.tool_calls)) tool_call_dicts = [ { From 1b49bf96021eba1bfc95e3c0a1ab6cae36271973 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Thu, 19 Feb 2026 10:26:49 -0300 Subject: [PATCH 017/154] fix: avoid duplicate messages on retry and reset final_content Address review feedback: - Remove on_progress call for interim text to prevent duplicate messages when the model simply answers a direct question - Reset final_content to None before continue to avoid stale interim text leaking as the final response on empty retry Closes #705 --- nanobot/agent/loop.py | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 6acbb38..532488f 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -230,17 +230,18 @@ class AgentLoop: # Some models (MiniMax, Gemini Flash, GPT-4.1, etc.) send an # interim text response (e.g. "Let me investigate...") before # making tool calls. If no tools have been used yet and we - # haven't already retried, forward the text as progress and - # give the model one more chance to use tools. + # haven't already retried, add the text to the conversation + # and give the model one more chance to use tools. + # We do NOT forward the interim text as progress to avoid + # duplicate messages when the model simply answers directly. if not tools_used and not text_only_retried and final_content: text_only_retried = True logger.debug(f"Interim text response (no tools used yet), retrying: {final_content[:80]}") - if on_progress: - await on_progress(final_content) messages = self.context.add_assistant_message( messages, response.content, reasoning_content=response.reasoning_content, ) + final_content = None continue break From 3b4763b3f989c00da674933f459730717ea7385a Mon Sep 17 00:00:00 2001 From: tercerapersona Date: Thu, 19 Feb 2026 11:05:22 -0300 Subject: [PATCH 018/154] feat: add Anthropic prompt caching via cache_control Inject cache_control: {"type": "ephemeral"} on the system message and last tool definition for providers that support prompt caching. Adds supports_prompt_caching flag to ProviderSpec (enabled for Anthropic only) and skips caching when routing through a gateway. Co-Authored-By: Claude Sonnet 4.6 --- nanobot/providers/litellm_provider.py | 43 +++++++++++++++++++++++++-- nanobot/providers/registry.py | 4 +++ 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 8cc4e35..950a138 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -93,6 +93,41 @@ class LiteLLMProvider(LLMProvider): return model + def _supports_cache_control(self, model: str) -> bool: + """Return True when the provider supports cache_control on content blocks.""" + if self._gateway is not None: + return False + spec = find_by_model(model) + return spec is not None and spec.supports_prompt_caching + + def _apply_cache_control( + self, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]] | None, + ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]: + """Return copies of messages and tools with cache_control injected.""" + # Transform the system message + new_messages = [] + for msg in messages: + if msg.get("role") == "system": + content = msg["content"] + if isinstance(content, str): + new_content = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}] + else: + new_content = list(content) + new_content[-1] = {**new_content[-1], "cache_control": {"type": "ephemeral"}} + new_messages.append({**msg, "content": new_content}) + else: + new_messages.append(msg) + + # Add cache_control to the last tool definition + new_tools = tools + if tools: + new_tools = list(tools) + new_tools[-1] = {**new_tools[-1], "cache_control": {"type": "ephemeral"}} + + return new_messages, new_tools + def _apply_model_overrides(self, model: str, kwargs: dict[str, Any]) -> None: """Apply model-specific parameter overrides from the registry.""" model_lower = model.lower() @@ -124,8 +159,12 @@ class LiteLLMProvider(LLMProvider): Returns: LLMResponse with content and/or tool calls. """ - model = self._resolve_model(model or self.default_model) - + original_model = model or self.default_model + model = self._resolve_model(original_model) + + if self._supports_cache_control(original_model): + messages, tools = self._apply_cache_control(messages, tools) + # Clamp max_tokens to at least 1 β€” negative or zero values cause # LiteLLM to reject the request with "max_tokens must be at least 1". max_tokens = max(1, max_tokens) diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py index 49b735c..2584e0e 100644 --- a/nanobot/providers/registry.py +++ b/nanobot/providers/registry.py @@ -57,6 +57,9 @@ class ProviderSpec: # Direct providers bypass LiteLLM entirely (e.g., CustomProvider) is_direct: bool = False + # Provider supports cache_control on content blocks (e.g. Anthropic prompt caching) + supports_prompt_caching: bool = False + @property def label(self) -> str: return self.display_name or self.name.title() @@ -155,6 +158,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = ( default_api_base="", strip_model_prefix=False, model_overrides=(), + supports_prompt_caching=True, ), # OpenAI: LiteLLM recognizes "gpt-*" natively, no prefix needed. From 53b83a38e2dc44b91e7890594abb1bd2220a6b03 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Thu, 19 Feb 2026 17:19:36 -0300 Subject: [PATCH 019/154] fix: use loguru native formatting to prevent KeyError on messages containing curly braces Closes #857 --- nanobot/agent/loop.py | 12 ++++++------ nanobot/agent/subagent.py | 4 ++-- nanobot/agent/tools/mcp.py | 2 +- nanobot/bus/queue.py | 2 +- nanobot/channels/dingtalk.py | 18 +++++++++--------- nanobot/channels/discord.py | 10 +++++----- nanobot/channels/email.py | 4 ++-- nanobot/channels/feishu.py | 26 +++++++++++++------------- nanobot/channels/manager.py | 6 +++--- nanobot/channels/mochat.py | 24 ++++++++++++------------ nanobot/channels/qq.py | 6 +++--- nanobot/channels/slack.py | 8 ++++---- nanobot/channels/telegram.py | 16 ++++++++-------- nanobot/channels/whatsapp.py | 10 +++++----- nanobot/cron/service.py | 4 ++-- nanobot/heartbeat/service.py | 4 ++-- nanobot/providers/transcription.py | 2 +- nanobot/session/manager.py | 2 +- 18 files changed, 80 insertions(+), 80 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..cbab5aa 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -219,7 +219,7 @@ class AgentLoop: for tool_call in response.tool_calls: tools_used.append(tool_call.name) args_str = json.dumps(tool_call.arguments, ensure_ascii=False) - logger.info(f"Tool call: {tool_call.name}({args_str[:200]})") + logger.info("Tool call: {}({})", tool_call.name, args_str[:200]) result = await self.tools.execute(tool_call.name, tool_call.arguments) messages = self.context.add_tool_result( messages, tool_call.id, tool_call.name, result @@ -247,7 +247,7 @@ class AgentLoop: if response: await self.bus.publish_outbound(response) except Exception as e: - logger.error(f"Error processing message: {e}") + logger.error("Error processing message: {}", e) await self.bus.publish_outbound(OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, @@ -292,7 +292,7 @@ class AgentLoop: return await self._process_system_message(msg) preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content - logger.info(f"Processing message from {msg.channel}:{msg.sender_id}: {preview}") + logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) key = session_key or msg.session_key session = self.sessions.get_or_create(key) @@ -344,7 +344,7 @@ class AgentLoop: final_content = "I've completed processing but have no response to give." preview = final_content[:120] + "..." if len(final_content) > 120 else final_content - logger.info(f"Response to {msg.channel}:{msg.sender_id}: {preview}") + logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) session.add_message("user", msg.content) session.add_message("assistant", final_content, @@ -469,7 +469,7 @@ Respond with ONLY valid JSON, no markdown fences.""" text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip() result = json_repair.loads(text) if not isinstance(result, dict): - logger.warning(f"Memory consolidation: unexpected response type, skipping. Response: {text[:200]}") + logger.warning("Memory consolidation: unexpected response type, skipping. Response: {}", text[:200]) return if entry := result.get("history_entry"): @@ -484,7 +484,7 @@ Respond with ONLY valid JSON, no markdown fences.""" session.last_consolidated = len(session.messages) - keep_count logger.info(f"Memory consolidation done: {len(session.messages)} messages, last_consolidated={session.last_consolidated}") except Exception as e: - logger.error(f"Memory consolidation failed: {e}") + logger.error("Memory consolidation failed: {}", e) async def process_direct( self, diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 203836a..ae0e492 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -160,7 +160,7 @@ class SubagentManager: # Execute tools for tool_call in response.tool_calls: args_str = json.dumps(tool_call.arguments) - logger.debug(f"Subagent [{task_id}] executing: {tool_call.name} with arguments: {args_str}") + logger.debug("Subagent [{}] executing: {} with arguments: {}", task_id, tool_call.name, args_str) result = await tools.execute(tool_call.name, tool_call.arguments) messages.append({ "role": "tool", @@ -180,7 +180,7 @@ class SubagentManager: except Exception as e: error_msg = f"Error: {str(e)}" - logger.error(f"Subagent [{task_id}] failed: {e}") + logger.error("Subagent [{}] failed: {}", task_id, e) await self._announce_result(task_id, label, task, error_msg, origin, "error") async def _announce_result( diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index 1c8eac4..4e61923 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -77,4 +77,4 @@ async def connect_mcp_servers( logger.info(f"MCP server '{name}': connected, {len(tools.tools)} tools registered") except Exception as e: - logger.error(f"MCP server '{name}': failed to connect: {e}") + logger.error("MCP server '{}': failed to connect: {}", name, e) diff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.py index 4123d06..554c0ec 100644 --- a/nanobot/bus/queue.py +++ b/nanobot/bus/queue.py @@ -62,7 +62,7 @@ class MessageBus: try: await callback(msg) except Exception as e: - logger.error(f"Error dispatching to {msg.channel}: {e}") + logger.error("Error dispatching to {}: {}", msg.channel, e) except asyncio.TimeoutError: continue diff --git a/nanobot/channels/dingtalk.py b/nanobot/channels/dingtalk.py index 4a8cdd9..3ac233f 100644 --- a/nanobot/channels/dingtalk.py +++ b/nanobot/channels/dingtalk.py @@ -65,7 +65,7 @@ class NanobotDingTalkHandler(CallbackHandler): sender_id = chatbot_msg.sender_staff_id or chatbot_msg.sender_id sender_name = chatbot_msg.sender_nick or "Unknown" - logger.info(f"Received DingTalk message from {sender_name} ({sender_id}): {content}") + logger.info("Received DingTalk message from {} ({}): {}", sender_name, sender_id, content) # Forward to Nanobot via _on_message (non-blocking). # Store reference to prevent GC before task completes. @@ -78,7 +78,7 @@ class NanobotDingTalkHandler(CallbackHandler): return AckMessage.STATUS_OK, "OK" except Exception as e: - logger.error(f"Error processing DingTalk message: {e}") + logger.error("Error processing DingTalk message: {}", e) # Return OK to avoid retry loop from DingTalk server return AckMessage.STATUS_OK, "Error" @@ -142,13 +142,13 @@ class DingTalkChannel(BaseChannel): try: await self._client.start() except Exception as e: - logger.warning(f"DingTalk stream error: {e}") + logger.warning("DingTalk stream error: {}", e) if self._running: logger.info("Reconnecting DingTalk stream in 5 seconds...") await asyncio.sleep(5) except Exception as e: - logger.exception(f"Failed to start DingTalk channel: {e}") + logger.exception("Failed to start DingTalk channel: {}", e) async def stop(self) -> None: """Stop the DingTalk bot.""" @@ -186,7 +186,7 @@ class DingTalkChannel(BaseChannel): self._token_expiry = time.time() + int(res_data.get("expireIn", 7200)) - 60 return self._access_token except Exception as e: - logger.error(f"Failed to get DingTalk access token: {e}") + logger.error("Failed to get DingTalk access token: {}", e) return None async def send(self, msg: OutboundMessage) -> None: @@ -218,11 +218,11 @@ class DingTalkChannel(BaseChannel): try: resp = await self._http.post(url, json=data, headers=headers) if resp.status_code != 200: - logger.error(f"DingTalk send failed: {resp.text}") + logger.error("DingTalk send failed: {}", resp.text) else: logger.debug(f"DingTalk message sent to {msg.chat_id}") except Exception as e: - logger.error(f"Error sending DingTalk message: {e}") + logger.error("Error sending DingTalk message: {}", e) async def _on_message(self, content: str, sender_id: str, sender_name: str) -> None: """Handle incoming message (called by NanobotDingTalkHandler). @@ -231,7 +231,7 @@ class DingTalkChannel(BaseChannel): permission checks before publishing to the bus. """ try: - logger.info(f"DingTalk inbound: {content} from {sender_name}") + logger.info("DingTalk inbound: {} from {}", content, sender_name) await self._handle_message( sender_id=sender_id, chat_id=sender_id, # For private chat, chat_id == sender_id @@ -242,4 +242,4 @@ class DingTalkChannel(BaseChannel): }, ) except Exception as e: - logger.error(f"Error publishing DingTalk message: {e}") + logger.error("Error publishing DingTalk message: {}", e) diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.py index a76d6ac..ee54eed 100644 --- a/nanobot/channels/discord.py +++ b/nanobot/channels/discord.py @@ -51,7 +51,7 @@ class DiscordChannel(BaseChannel): except asyncio.CancelledError: break except Exception as e: - logger.warning(f"Discord gateway error: {e}") + logger.warning("Discord gateway error: {}", e) if self._running: logger.info("Reconnecting to Discord gateway in 5 seconds...") await asyncio.sleep(5) @@ -101,7 +101,7 @@ class DiscordChannel(BaseChannel): return except Exception as e: if attempt == 2: - logger.error(f"Error sending Discord message: {e}") + logger.error("Error sending Discord message: {}", e) else: await asyncio.sleep(1) finally: @@ -116,7 +116,7 @@ class DiscordChannel(BaseChannel): try: data = json.loads(raw) except json.JSONDecodeError: - logger.warning(f"Invalid JSON from Discord gateway: {raw[:100]}") + logger.warning("Invalid JSON from Discord gateway: {}", raw[:100]) continue op = data.get("op") @@ -175,7 +175,7 @@ class DiscordChannel(BaseChannel): try: await self._ws.send(json.dumps(payload)) except Exception as e: - logger.warning(f"Discord heartbeat failed: {e}") + logger.warning("Discord heartbeat failed: {}", e) break await asyncio.sleep(interval_s) @@ -219,7 +219,7 @@ class DiscordChannel(BaseChannel): media_paths.append(str(file_path)) content_parts.append(f"[attachment: {file_path}]") except Exception as e: - logger.warning(f"Failed to download Discord attachment: {e}") + logger.warning("Failed to download Discord attachment: {}", e) content_parts.append(f"[attachment: {filename} - download failed]") reply_to = (payload.get("referenced_message") or {}).get("id") diff --git a/nanobot/channels/email.py b/nanobot/channels/email.py index 0e47067..8a1ee79 100644 --- a/nanobot/channels/email.py +++ b/nanobot/channels/email.py @@ -94,7 +94,7 @@ class EmailChannel(BaseChannel): metadata=item.get("metadata", {}), ) except Exception as e: - logger.error(f"Email polling error: {e}") + logger.error("Email polling error: {}", e) await asyncio.sleep(poll_seconds) @@ -143,7 +143,7 @@ class EmailChannel(BaseChannel): try: await asyncio.to_thread(self._smtp_send, email_msg) except Exception as e: - logger.error(f"Error sending email to {to_addr}: {e}") + logger.error("Error sending email to {}: {}", to_addr, e) raise def _validate_config(self) -> bool: diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index 651d655..6f62202 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -156,7 +156,7 @@ class FeishuChannel(BaseChannel): try: self._ws_client.start() except Exception as e: - logger.warning(f"Feishu WebSocket error: {e}") + logger.warning("Feishu WebSocket error: {}", e) if self._running: import time; time.sleep(5) @@ -177,7 +177,7 @@ class FeishuChannel(BaseChannel): try: self._ws_client.stop() except Exception as e: - logger.warning(f"Error stopping WebSocket client: {e}") + logger.warning("Error stopping WebSocket client: {}", e) logger.info("Feishu bot stopped") def _add_reaction_sync(self, message_id: str, emoji_type: str) -> None: @@ -194,11 +194,11 @@ class FeishuChannel(BaseChannel): response = self._client.im.v1.message_reaction.create(request) if not response.success(): - logger.warning(f"Failed to add reaction: code={response.code}, msg={response.msg}") + logger.warning("Failed to add reaction: code={}, msg={}", response.code, response.msg) else: logger.debug(f"Added {emoji_type} reaction to message {message_id}") except Exception as e: - logger.warning(f"Error adding reaction: {e}") + logger.warning("Error adding reaction: {}", e) async def _add_reaction(self, message_id: str, emoji_type: str = "THUMBSUP") -> None: """ @@ -312,10 +312,10 @@ class FeishuChannel(BaseChannel): logger.debug(f"Uploaded image {os.path.basename(file_path)}: {image_key}") return image_key else: - logger.error(f"Failed to upload image: code={response.code}, msg={response.msg}") + logger.error("Failed to upload image: code={}, msg={}", response.code, response.msg) return None except Exception as e: - logger.error(f"Error uploading image {file_path}: {e}") + logger.error("Error uploading image {}: {}", file_path, e) return None def _upload_file_sync(self, file_path: str) -> str | None: @@ -339,10 +339,10 @@ class FeishuChannel(BaseChannel): logger.debug(f"Uploaded file {file_name}: {file_key}") return file_key else: - logger.error(f"Failed to upload file: code={response.code}, msg={response.msg}") + logger.error("Failed to upload file: code={}, msg={}", response.code, response.msg) return None except Exception as e: - logger.error(f"Error uploading file {file_path}: {e}") + logger.error("Error uploading file {}: {}", file_path, e) return None def _send_message_sync(self, receive_id_type: str, receive_id: str, msg_type: str, content: str) -> bool: @@ -360,14 +360,14 @@ class FeishuChannel(BaseChannel): response = self._client.im.v1.message.create(request) if not response.success(): logger.error( - f"Failed to send Feishu {msg_type} message: code={response.code}, " - f"msg={response.msg}, log_id={response.get_log_id()}" + "Failed to send Feishu {} message: code={}, msg={}, log_id={}", + msg_type, response.code, response.msg, response.get_log_id() ) return False logger.debug(f"Feishu {msg_type} message sent to {receive_id}") return True except Exception as e: - logger.error(f"Error sending Feishu {msg_type} message: {e}") + logger.error("Error sending Feishu {} message: {}", msg_type, e) return False async def send(self, msg: OutboundMessage) -> None: @@ -409,7 +409,7 @@ class FeishuChannel(BaseChannel): ) except Exception as e: - logger.error(f"Error sending Feishu message: {e}") + logger.error("Error sending Feishu message: {}", e) def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None: """ @@ -481,4 +481,4 @@ class FeishuChannel(BaseChannel): ) except Exception as e: - logger.error(f"Error processing Feishu message: {e}") + logger.error("Error processing Feishu message: {}", e) diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index e860d26..3e714c3 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -142,7 +142,7 @@ class ChannelManager: try: await channel.start() except Exception as e: - logger.error(f"Failed to start channel {name}: {e}") + logger.error("Failed to start channel {}: {}", name, e) async def start_all(self) -> None: """Start all channels and the outbound dispatcher.""" @@ -180,7 +180,7 @@ class ChannelManager: await channel.stop() logger.info(f"Stopped {name} channel") except Exception as e: - logger.error(f"Error stopping {name}: {e}") + logger.error("Error stopping {}: {}", name, e) async def _dispatch_outbound(self) -> None: """Dispatch outbound messages to the appropriate channel.""" @@ -198,7 +198,7 @@ class ChannelManager: try: await channel.send(msg) except Exception as e: - logger.error(f"Error sending to {msg.channel}: {e}") + logger.error("Error sending to {}: {}", msg.channel, e) else: logger.warning(f"Unknown channel: {msg.channel}") diff --git a/nanobot/channels/mochat.py b/nanobot/channels/mochat.py index 30c3dbf..e762dfd 100644 --- a/nanobot/channels/mochat.py +++ b/nanobot/channels/mochat.py @@ -322,7 +322,7 @@ class MochatChannel(BaseChannel): await self._api_send("/api/claw/sessions/send", "sessionId", target.id, content, msg.reply_to) except Exception as e: - logger.error(f"Failed to send Mochat message: {e}") + logger.error("Failed to send Mochat message: {}", e) # ---- config / init helpers --------------------------------------------- @@ -380,7 +380,7 @@ class MochatChannel(BaseChannel): @client.event async def connect_error(data: Any) -> None: - logger.error(f"Mochat websocket connect error: {data}") + logger.error("Mochat websocket connect error: {}", data) @client.on("claw.session.events") async def on_session_events(payload: dict[str, Any]) -> None: @@ -407,7 +407,7 @@ class MochatChannel(BaseChannel): ) return True except Exception as e: - logger.error(f"Failed to connect Mochat websocket: {e}") + logger.error("Failed to connect Mochat websocket: {}", e) try: await client.disconnect() except Exception: @@ -444,7 +444,7 @@ class MochatChannel(BaseChannel): "limit": self.config.watch_limit, }) if not ack.get("result"): - logger.error(f"Mochat subscribeSessions failed: {ack.get('message', 'unknown error')}") + logger.error("Mochat subscribeSessions failed: {}", ack.get('message', 'unknown error')) return False data = ack.get("data") @@ -466,7 +466,7 @@ class MochatChannel(BaseChannel): return True ack = await self._socket_call("com.claw.im.subscribePanels", {"panelIds": panel_ids}) if not ack.get("result"): - logger.error(f"Mochat subscribePanels failed: {ack.get('message', 'unknown error')}") + logger.error("Mochat subscribePanels failed: {}", ack.get('message', 'unknown error')) return False return True @@ -488,7 +488,7 @@ class MochatChannel(BaseChannel): try: await self._refresh_targets(subscribe_new=self._ws_ready) except Exception as e: - logger.warning(f"Mochat refresh failed: {e}") + logger.warning("Mochat refresh failed: {}", e) if self._fallback_mode: await self._ensure_fallback_workers() @@ -502,7 +502,7 @@ class MochatChannel(BaseChannel): try: response = await self._post_json("/api/claw/sessions/list", {}) except Exception as e: - logger.warning(f"Mochat listSessions failed: {e}") + logger.warning("Mochat listSessions failed: {}", e) return sessions = response.get("sessions") @@ -536,7 +536,7 @@ class MochatChannel(BaseChannel): try: response = await self._post_json("/api/claw/groups/get", {}) except Exception as e: - logger.warning(f"Mochat getWorkspaceGroup failed: {e}") + logger.warning("Mochat getWorkspaceGroup failed: {}", e) return raw_panels = response.get("panels") @@ -598,7 +598,7 @@ class MochatChannel(BaseChannel): except asyncio.CancelledError: break except Exception as e: - logger.warning(f"Mochat watch fallback error ({session_id}): {e}") + logger.warning("Mochat watch fallback error ({}): {}", session_id, e) await asyncio.sleep(max(0.1, self.config.retry_delay_ms / 1000.0)) async def _panel_poll_worker(self, panel_id: str) -> None: @@ -625,7 +625,7 @@ class MochatChannel(BaseChannel): except asyncio.CancelledError: break except Exception as e: - logger.warning(f"Mochat panel polling error ({panel_id}): {e}") + logger.warning("Mochat panel polling error ({}): {}", panel_id, e) await asyncio.sleep(sleep_s) # ---- inbound event processing ------------------------------------------ @@ -836,7 +836,7 @@ class MochatChannel(BaseChannel): try: data = json.loads(self._cursor_path.read_text("utf-8")) except Exception as e: - logger.warning(f"Failed to read Mochat cursor file: {e}") + logger.warning("Failed to read Mochat cursor file: {}", e) return cursors = data.get("cursors") if isinstance(data, dict) else None if isinstance(cursors, dict): @@ -852,7 +852,7 @@ class MochatChannel(BaseChannel): "cursors": self._session_cursor, }, ensure_ascii=False, indent=2) + "\n", "utf-8") except Exception as e: - logger.warning(f"Failed to save Mochat cursor file: {e}") + logger.warning("Failed to save Mochat cursor file: {}", e) # ---- HTTP helpers ------------------------------------------------------ diff --git a/nanobot/channels/qq.py b/nanobot/channels/qq.py index 0e8fe66..1d00bc7 100644 --- a/nanobot/channels/qq.py +++ b/nanobot/channels/qq.py @@ -80,7 +80,7 @@ class QQChannel(BaseChannel): try: await self._client.start(appid=self.config.app_id, secret=self.config.secret) except Exception as e: - logger.warning(f"QQ bot error: {e}") + logger.warning("QQ bot error: {}", e) if self._running: logger.info("Reconnecting QQ bot in 5 seconds...") await asyncio.sleep(5) @@ -108,7 +108,7 @@ class QQChannel(BaseChannel): content=msg.content, ) except Exception as e: - logger.error(f"Error sending QQ message: {e}") + logger.error("Error sending QQ message: {}", e) async def _on_message(self, data: "C2CMessage") -> None: """Handle incoming message from QQ.""" @@ -131,4 +131,4 @@ class QQChannel(BaseChannel): metadata={"message_id": data.id}, ) except Exception as e: - logger.error(f"Error handling QQ message: {e}") + logger.error("Error handling QQ message: {}", e) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index dca5055..7dd2971 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -55,7 +55,7 @@ class SlackChannel(BaseChannel): self._bot_user_id = auth.get("user_id") logger.info(f"Slack bot connected as {self._bot_user_id}") except Exception as e: - logger.warning(f"Slack auth_test failed: {e}") + logger.warning("Slack auth_test failed: {}", e) logger.info("Starting Slack Socket Mode client...") await self._socket_client.connect() @@ -70,7 +70,7 @@ class SlackChannel(BaseChannel): try: await self._socket_client.close() except Exception as e: - logger.warning(f"Slack socket close failed: {e}") + logger.warning("Slack socket close failed: {}", e) self._socket_client = None async def send(self, msg: OutboundMessage) -> None: @@ -90,7 +90,7 @@ class SlackChannel(BaseChannel): thread_ts=thread_ts if use_thread else None, ) except Exception as e: - logger.error(f"Error sending Slack message: {e}") + logger.error("Error sending Slack message: {}", e) async def _on_socket_request( self, @@ -164,7 +164,7 @@ class SlackChannel(BaseChannel): timestamp=event.get("ts"), ) except Exception as e: - logger.debug(f"Slack reactions_add failed: {e}") + logger.debug("Slack reactions_add failed: {}", e) await self._handle_message( sender_id=sender_id, diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.py index 39924b3..42db489 100644 --- a/nanobot/channels/telegram.py +++ b/nanobot/channels/telegram.py @@ -171,7 +171,7 @@ class TelegramChannel(BaseChannel): await self._app.bot.set_my_commands(self.BOT_COMMANDS) logger.debug("Telegram bot commands registered") except Exception as e: - logger.warning(f"Failed to register bot commands: {e}") + logger.warning("Failed to register bot commands: {}", e) # Start polling (this runs until stopped) await self._app.updater.start_polling( @@ -238,7 +238,7 @@ class TelegramChannel(BaseChannel): await sender(chat_id=chat_id, **{param: f}) except Exception as e: filename = media_path.rsplit("/", 1)[-1] - logger.error(f"Failed to send media {media_path}: {e}") + logger.error("Failed to send media {}: {}", media_path, e) await self._app.bot.send_message(chat_id=chat_id, text=f"[Failed to send: {filename}]") # Send text content @@ -248,11 +248,11 @@ class TelegramChannel(BaseChannel): html = _markdown_to_telegram_html(chunk) await self._app.bot.send_message(chat_id=chat_id, text=html, parse_mode="HTML") except Exception as e: - logger.warning(f"HTML parse failed, falling back to plain text: {e}") + logger.warning("HTML parse failed, falling back to plain text: {}", e) try: await self._app.bot.send_message(chat_id=chat_id, text=chunk) except Exception as e2: - logger.error(f"Error sending Telegram message: {e2}") + logger.error("Error sending Telegram message: {}", e2) async def _on_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: """Handle /start command.""" @@ -353,12 +353,12 @@ class TelegramChannel(BaseChannel): logger.debug(f"Downloaded {media_type} to {file_path}") except Exception as e: - logger.error(f"Failed to download media: {e}") + logger.error("Failed to download media: {}", e) content_parts.append(f"[{media_type}: download failed]") content = "\n".join(content_parts) if content_parts else "[empty message]" - logger.debug(f"Telegram message from {sender_id}: {content[:50]}...") + logger.debug("Telegram message from {}: {}...", sender_id, content[:50]) str_chat_id = str(chat_id) @@ -401,11 +401,11 @@ class TelegramChannel(BaseChannel): except asyncio.CancelledError: pass except Exception as e: - logger.debug(f"Typing indicator stopped for {chat_id}: {e}") + logger.debug("Typing indicator stopped for {}: {}", chat_id, e) async def _on_error(self, update: object, context: ContextTypes.DEFAULT_TYPE) -> None: """Log polling / handler errors instead of silently swallowing them.""" - logger.error(f"Telegram error: {context.error}") + logger.error("Telegram error: {}", context.error) def _get_extension(self, media_type: str, mime_type: str | None) -> str: """Get file extension based on media type.""" diff --git a/nanobot/channels/whatsapp.py b/nanobot/channels/whatsapp.py index 0cf2dd7..4d12360 100644 --- a/nanobot/channels/whatsapp.py +++ b/nanobot/channels/whatsapp.py @@ -53,14 +53,14 @@ class WhatsAppChannel(BaseChannel): try: await self._handle_bridge_message(message) except Exception as e: - logger.error(f"Error handling bridge message: {e}") + logger.error("Error handling bridge message: {}", e) except asyncio.CancelledError: break except Exception as e: self._connected = False self._ws = None - logger.warning(f"WhatsApp bridge connection error: {e}") + logger.warning("WhatsApp bridge connection error: {}", e) if self._running: logger.info("Reconnecting in 5 seconds...") @@ -89,14 +89,14 @@ class WhatsAppChannel(BaseChannel): } await self._ws.send(json.dumps(payload)) except Exception as e: - logger.error(f"Error sending WhatsApp message: {e}") + logger.error("Error sending WhatsApp message: {}", e) async def _handle_bridge_message(self, raw: str) -> None: """Handle a message from the bridge.""" try: data = json.loads(raw) except json.JSONDecodeError: - logger.warning(f"Invalid JSON from bridge: {raw[:100]}") + logger.warning("Invalid JSON from bridge: {}", raw[:100]) return msg_type = data.get("type") @@ -145,4 +145,4 @@ class WhatsAppChannel(BaseChannel): logger.info("Scan QR code in the bridge terminal to connect WhatsApp") elif msg_type == "error": - logger.error(f"WhatsApp bridge error: {data.get('error')}") + logger.error("WhatsApp bridge error: {}", data.get('error')) diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index 14666e8..d2b9ef7 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -99,7 +99,7 @@ class CronService: )) self._store = CronStore(jobs=jobs) except Exception as e: - logger.warning(f"Failed to load cron store: {e}") + logger.warning("Failed to load cron store: {}", e) self._store = CronStore() else: self._store = CronStore() @@ -236,7 +236,7 @@ class CronService: except Exception as e: job.state.last_status = "error" job.state.last_error = str(e) - logger.error(f"Cron: job '{job.name}' failed: {e}") + logger.error("Cron: job '{}' failed: {}", job.name, e) job.state.last_run_at_ms = start_ms job.updated_at_ms = _now_ms() diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index 221ed27..8bdc78f 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -97,7 +97,7 @@ class HeartbeatService: except asyncio.CancelledError: break except Exception as e: - logger.error(f"Heartbeat error: {e}") + logger.error("Heartbeat error: {}", e) async def _tick(self) -> None: """Execute a single heartbeat tick.""" @@ -121,7 +121,7 @@ class HeartbeatService: logger.info(f"Heartbeat: completed task") except Exception as e: - logger.error(f"Heartbeat execution failed: {e}") + logger.error("Heartbeat execution failed: {}", e) async def trigger_now(self) -> str | None: """Manually trigger a heartbeat.""" diff --git a/nanobot/providers/transcription.py b/nanobot/providers/transcription.py index 8ce909b..eb5969d 100644 --- a/nanobot/providers/transcription.py +++ b/nanobot/providers/transcription.py @@ -61,5 +61,5 @@ class GroqTranscriptionProvider: return data.get("text", "") except Exception as e: - logger.error(f"Groq transcription error: {e}") + logger.error("Groq transcription error: {}", e) return "" diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 752fce4..44dcecb 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -144,7 +144,7 @@ class SessionManager: last_consolidated=last_consolidated ) except Exception as e: - logger.warning(f"Failed to load session {key}: {e}") + logger.warning("Failed to load session {}: {}", key, e) return None def save(self, session: Session) -> None: From afca0278ad9e99be7f2778fdbdcb1bb3aac2ecb0 Mon Sep 17 00:00:00 2001 From: Rudolfs Tilgass Date: Thu, 19 Feb 2026 21:02:52 +0100 Subject: [PATCH 020/154] fix(memory): Enforce memory consolidation schema with a tool call --- nanobot/agent/loop.py | 111 +++++++++++++++++++++++------------------- 1 file changed, 62 insertions(+), 49 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5a5183..e9e225c 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -3,7 +3,6 @@ import asyncio from contextlib import AsyncExitStack import json -import json_repair from pathlib import Path import re from typing import Any, Awaitable, Callable @@ -84,13 +83,13 @@ class AgentLoop: exec_config=self.exec_config, restrict_to_workspace=restrict_to_workspace, ) - + self._running = False self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None self._mcp_connected = False self._register_default_tools() - + def _register_default_tools(self) -> None: """Register the default set of tools.""" # File tools (restrict to workspace if configured) @@ -99,30 +98,30 @@ class AgentLoop: self.tools.register(WriteFileTool(allowed_dir=allowed_dir)) self.tools.register(EditFileTool(allowed_dir=allowed_dir)) self.tools.register(ListDirTool(allowed_dir=allowed_dir)) - + # Shell tool self.tools.register(ExecTool( working_dir=str(self.workspace), timeout=self.exec_config.timeout, restrict_to_workspace=self.restrict_to_workspace, )) - + # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - + # Message tool message_tool = MessageTool(send_callback=self.bus.publish_outbound) self.tools.register(message_tool) - + # Spawn tool (for subagents) spawn_tool = SpawnTool(manager=self.subagents) self.tools.register(spawn_tool) - + # Cron tool (for scheduling) if self.cron_service: self.tools.register(CronTool(self.cron_service)) - + async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: @@ -255,7 +254,7 @@ class AgentLoop: )) except asyncio.TimeoutError: continue - + async def close_mcp(self) -> None: """Close MCP connections.""" if self._mcp_stack: @@ -269,7 +268,7 @@ class AgentLoop: """Stop the agent loop.""" self._running = False logger.info("Agent loop stopping") - + async def _process_message( self, msg: InboundMessage, @@ -278,25 +277,25 @@ class AgentLoop: ) -> OutboundMessage | None: """ Process a single inbound message. - + Args: msg: The inbound message to process. session_key: Override session key (used by process_direct). on_progress: Optional callback for intermediate output (defaults to bus publish). - + Returns: The response message, or None if no response needed. """ # System messages route back via chat_id ("channel:chat_id") if msg.channel == "system": return await self._process_system_message(msg) - + preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info(f"Processing message from {msg.channel}:{msg.sender_id}: {preview}") - + key = session_key or msg.session_key session = self.sessions.get_or_create(key) - + # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": @@ -317,7 +316,7 @@ class AgentLoop: if cmd == "/help": return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") - + if len(session.messages) > self.memory_window: asyncio.create_task(self._consolidate_memory(session)) @@ -342,31 +341,31 @@ class AgentLoop: if final_content is None: final_content = "I've completed processing but have no response to give." - + preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info(f"Response to {msg.channel}:{msg.sender_id}: {preview}") - + session.add_message("user", msg.content) session.add_message("assistant", final_content, tools_used=tools_used if tools_used else None) self.sessions.save(session) - + return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=final_content, metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) ) - + async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: """ Process a system message (e.g., subagent announce). - + The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ logger.info(f"Processing system message from {msg.sender_id}") - + # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: parts = msg.chat_id.split(":", 1) @@ -376,7 +375,7 @@ class AgentLoop: # Fallback origin_channel = "cli" origin_chat_id = msg.chat_id - + session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) self._set_tool_context(origin_channel, origin_chat_id) @@ -390,17 +389,17 @@ class AgentLoop: if final_content is None: final_content = "Background task completed." - + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") session.add_message("assistant", final_content) self.sessions.save(session) - + return OutboundMessage( channel=origin_channel, chat_id=origin_chat_id, content=final_content ) - + async def _consolidate_memory(self, session, archive_all: bool = False) -> None: """Consolidate old messages into MEMORY.md + HISTORY.md. @@ -439,42 +438,56 @@ class AgentLoop: conversation = "\n".join(lines) current_memory = memory.read_long_term() - prompt = f"""You are a memory consolidation agent. Process this conversation and return a JSON object with exactly two keys: - -1. "history_entry": A paragraph (2-5 sentences) summarizing the key events/decisions/topics. Start with a timestamp like [YYYY-MM-DD HH:MM]. Include enough detail to be useful when found by grep search later. - -2. "memory_update": The updated long-term memory content. Add any new facts: user location, preferences, personal info, habits, project context, technical decisions, tools/services used. If nothing new, return the existing content unchanged. + prompt = f"""Process this conversation and call the save_memory tool with your consolidation. ## Current Long-term Memory {current_memory or "(empty)"} ## Conversation to Process -{conversation} +{conversation}""" -Respond with ONLY valid JSON, no markdown fences.""" + save_memory_tool = [ + { + "type": "function", + "function": { + "name": "save_memory", + "description": "Save the memory consolidation result to persistent storage.", + "parameters": { + "type": "object", + "properties": { + "history_entry": { + "type": "string", + "description": "A paragraph (2-5 sentences) summarizing key events/decisions/topics. Start with a timestamp like [YYYY-MM-DD HH:MM]. Include enough detail to be useful when found by grep search later.", + }, + "memory_update": { + "type": "string", + "description": "The full updated long-term memory content as a markdown string. Include all existing facts plus any new facts: user location, preferences, personal info, habits, project context, technical decisions, tools/services used. If nothing new, return the existing content unchanged.", + }, + }, + "required": ["history_entry", "memory_update"], + }, + }, + } + ] try: response = await self.provider.chat( messages=[ - {"role": "system", "content": "You are a memory consolidation agent. Respond only with valid JSON."}, + {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."}, {"role": "user", "content": prompt}, ], + tools=save_memory_tool, model=self.model, ) - text = (response.content or "").strip() - if not text: - logger.warning("Memory consolidation: LLM returned empty response, skipping") - return - if text.startswith("```"): - text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip() - result = json_repair.loads(text) - if not isinstance(result, dict): - logger.warning(f"Memory consolidation: unexpected response type, skipping. Response: {text[:200]}") + + if not response.has_tool_calls: + logger.warning("Memory consolidation: LLM did not call save_memory tool, skipping") return - if entry := result.get("history_entry"): + args = response.tool_calls[0].arguments + if entry := args.get("history_entry"): memory.append_history(entry) - if update := result.get("memory_update"): + if update := args.get("memory_update"): if update != current_memory: memory.write_long_term(update) @@ -496,14 +509,14 @@ Respond with ONLY valid JSON, no markdown fences.""" ) -> str: """ Process a message directly (for CLI or cron usage). - + Args: content: The message content. session_key: Session identifier (overrides channel:chat_id for session lookup). channel: Source channel (for tool context routing). chat_id: Source chat ID (for tool context routing). on_progress: Optional callback for intermediate output. - + Returns: The agent's response. """ @@ -514,6 +527,6 @@ Respond with ONLY valid JSON, no markdown fences.""" chat_id=chat_id, content=content ) - + response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" From f3c7337356de507b6a1e0b10725bc2521f48ec95 Mon Sep 17 00:00:00 2001 From: dxtime Date: Fri, 20 Feb 2026 08:31:52 +0800 Subject: [PATCH 021/154] feat: Added custom headers for MCP Auth use, update README.md --- README.md | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 7fad9ce..e8aac1e 100644 --- a/README.md +++ b/README.md @@ -752,7 +752,14 @@ Add MCP servers to your `config.json`: "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"] } - } + }, + "urlMcpServers": { + "url": "https://xx.xx.xx.xx:xxxx/mcp/", + "headers": { + "Authorization": "Bearer xxxxx", + "X-API-Key": "xxxxxxx" + } + }, } } ``` @@ -762,7 +769,7 @@ Two transport modes are supported: | Mode | Config | Example | |------|--------|---------| | **Stdio** | `command` + `args` | Local process via `npx` / `uvx` | -| **HTTP** | `url` | Remote endpoint (`https://mcp.example.com/sse`) | +| **HTTP** | `url` + `option(headers)`| Remote endpoint (`https://mcp.example.com/sse`) | MCP tools are automatically discovered and registered on startup. The LLM can use them alongside built-in tools β€” no extra configuration needed. From 0001f286b578b6ecf9634b47c6605978038e5a61 Mon Sep 17 00:00:00 2001 From: AlexanderMerkel Date: Thu, 19 Feb 2026 19:00:25 -0700 Subject: [PATCH 022/154] fix: remove dead pub/sub code from MessageBus MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `subscribe_outbound()`, `dispatch_outbound()`, and `stop()` have zero callers β€” `ChannelManager._dispatch_outbound()` handles all outbound routing via `consume_outbound()` directly. Remove the dead methods and their unused imports (`Callable`, `Awaitable`, `logger`). Co-Authored-By: Claude Opus 4.6 --- nanobot/bus/queue.py | 53 +++++++------------------------------------- 1 file changed, 8 insertions(+), 45 deletions(-) diff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.py index 4123d06..7c0616f 100644 --- a/nanobot/bus/queue.py +++ b/nanobot/bus/queue.py @@ -1,9 +1,6 @@ """Async message queue for decoupled channel-agent communication.""" import asyncio -from typing import Callable, Awaitable - -from loguru import logger from nanobot.bus.events import InboundMessage, OutboundMessage @@ -11,70 +8,36 @@ from nanobot.bus.events import InboundMessage, OutboundMessage class MessageBus: """ Async message bus that decouples chat channels from the agent core. - + Channels push messages to the inbound queue, and the agent processes them and pushes responses to the outbound queue. """ - + def __init__(self): self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue() self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue() - self._outbound_subscribers: dict[str, list[Callable[[OutboundMessage], Awaitable[None]]]] = {} - self._running = False - + async def publish_inbound(self, msg: InboundMessage) -> None: """Publish a message from a channel to the agent.""" await self.inbound.put(msg) - + async def consume_inbound(self) -> InboundMessage: """Consume the next inbound message (blocks until available).""" return await self.inbound.get() - + async def publish_outbound(self, msg: OutboundMessage) -> None: """Publish a response from the agent to channels.""" await self.outbound.put(msg) - + async def consume_outbound(self) -> OutboundMessage: """Consume the next outbound message (blocks until available).""" return await self.outbound.get() - - def subscribe_outbound( - self, - channel: str, - callback: Callable[[OutboundMessage], Awaitable[None]] - ) -> None: - """Subscribe to outbound messages for a specific channel.""" - if channel not in self._outbound_subscribers: - self._outbound_subscribers[channel] = [] - self._outbound_subscribers[channel].append(callback) - - async def dispatch_outbound(self) -> None: - """ - Dispatch outbound messages to subscribed channels. - Run this as a background task. - """ - self._running = True - while self._running: - try: - msg = await asyncio.wait_for(self.outbound.get(), timeout=1.0) - subscribers = self._outbound_subscribers.get(msg.channel, []) - for callback in subscribers: - try: - await callback(msg) - except Exception as e: - logger.error(f"Error dispatching to {msg.channel}: {e}") - except asyncio.TimeoutError: - continue - - def stop(self) -> None: - """Stop the dispatcher loop.""" - self._running = False - + @property def inbound_size(self) -> int: """Number of pending inbound messages.""" return self.inbound.qsize() - + @property def outbound_size(self) -> int: """Number of pending outbound messages.""" From 37252a4226214367abea1cef0fae4591b2dc00c4 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 07:55:34 +0000 Subject: [PATCH 023/154] fix: complete loguru native formatting migration across all files --- nanobot/agent/loop.py | 12 ++++++------ nanobot/agent/subagent.py | 8 ++++---- nanobot/agent/tools/mcp.py | 6 +++--- nanobot/channels/dingtalk.py | 2 +- nanobot/channels/discord.py | 2 +- nanobot/channels/email.py | 2 +- nanobot/channels/feishu.py | 10 +++++----- nanobot/channels/manager.py | 24 ++++++++++++------------ nanobot/channels/qq.py | 2 +- nanobot/channels/slack.py | 4 ++-- nanobot/channels/telegram.py | 8 ++++---- nanobot/channels/whatsapp.py | 8 ++++---- nanobot/cron/service.py | 10 +++++----- nanobot/heartbeat/service.py | 4 ++-- nanobot/providers/transcription.py | 2 +- nanobot/session/manager.py | 2 +- 16 files changed, 53 insertions(+), 53 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index cbab5aa..1620cb0 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -365,7 +365,7 @@ class AgentLoop: The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ - logger.info(f"Processing system message from {msg.sender_id}") + logger.info("Processing system message from {}", msg.sender_id) # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: @@ -413,22 +413,22 @@ class AgentLoop: if archive_all: old_messages = session.messages keep_count = 0 - logger.info(f"Memory consolidation (archive_all): {len(session.messages)} total messages archived") + logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages)) else: keep_count = self.memory_window // 2 if len(session.messages) <= keep_count: - logger.debug(f"Session {session.key}: No consolidation needed (messages={len(session.messages)}, keep={keep_count})") + logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count) return messages_to_process = len(session.messages) - session.last_consolidated if messages_to_process <= 0: - logger.debug(f"Session {session.key}: No new messages to consolidate (last_consolidated={session.last_consolidated}, total={len(session.messages)})") + logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages)) return old_messages = session.messages[session.last_consolidated:-keep_count] if not old_messages: return - logger.info(f"Memory consolidation started: {len(session.messages)} total, {len(old_messages)} new to consolidate, {keep_count} keep") + logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count) lines = [] for m in old_messages: @@ -482,7 +482,7 @@ Respond with ONLY valid JSON, no markdown fences.""" session.last_consolidated = 0 else: session.last_consolidated = len(session.messages) - keep_count - logger.info(f"Memory consolidation done: {len(session.messages)} messages, last_consolidated={session.last_consolidated}") + logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) except Exception as e: logger.error("Memory consolidation failed: {}", e) diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index ae0e492..7d48cc4 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -86,7 +86,7 @@ class SubagentManager: # Cleanup when done bg_task.add_done_callback(lambda _: self._running_tasks.pop(task_id, None)) - logger.info(f"Spawned subagent [{task_id}]: {display_label}") + logger.info("Spawned subagent [{}]: {}", task_id, display_label) return f"Subagent [{display_label}] started (id: {task_id}). I'll notify you when it completes." async def _run_subagent( @@ -97,7 +97,7 @@ class SubagentManager: origin: dict[str, str], ) -> None: """Execute the subagent task and announce the result.""" - logger.info(f"Subagent [{task_id}] starting task: {label}") + logger.info("Subagent [{}] starting task: {}", task_id, label) try: # Build subagent tools (no message tool, no spawn tool) @@ -175,7 +175,7 @@ class SubagentManager: if final_result is None: final_result = "Task completed but no final response was generated." - logger.info(f"Subagent [{task_id}] completed successfully") + logger.info("Subagent [{}] completed successfully", task_id) await self._announce_result(task_id, label, task, final_result, origin, "ok") except Exception as e: @@ -213,7 +213,7 @@ Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not men ) await self.bus.publish_inbound(msg) - logger.debug(f"Subagent [{task_id}] announced result to {origin['channel']}:{origin['chat_id']}") + logger.debug("Subagent [{}] announced result to {}:{}", task_id, origin['channel'], origin['chat_id']) def _build_subagent_prompt(self, task: str) -> str: """Build a focused system prompt for the subagent.""" diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index 4e61923..7d9033d 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -63,7 +63,7 @@ async def connect_mcp_servers( streamable_http_client(cfg.url) ) else: - logger.warning(f"MCP server '{name}': no command or url configured, skipping") + logger.warning("MCP server '{}': no command or url configured, skipping", name) continue session = await stack.enter_async_context(ClientSession(read, write)) @@ -73,8 +73,8 @@ async def connect_mcp_servers( for tool_def in tools.tools: wrapper = MCPToolWrapper(session, name, tool_def) registry.register(wrapper) - logger.debug(f"MCP: registered tool '{wrapper.name}' from server '{name}'") + logger.debug("MCP: registered tool '{}' from server '{}'", wrapper.name, name) - logger.info(f"MCP server '{name}': connected, {len(tools.tools)} tools registered") + logger.info("MCP server '{}': connected, {} tools registered", name, len(tools.tools)) except Exception as e: logger.error("MCP server '{}': failed to connect: {}", name, e) diff --git a/nanobot/channels/dingtalk.py b/nanobot/channels/dingtalk.py index 3ac233f..f6dca30 100644 --- a/nanobot/channels/dingtalk.py +++ b/nanobot/channels/dingtalk.py @@ -220,7 +220,7 @@ class DingTalkChannel(BaseChannel): if resp.status_code != 200: logger.error("DingTalk send failed: {}", resp.text) else: - logger.debug(f"DingTalk message sent to {msg.chat_id}") + logger.debug("DingTalk message sent to {}", msg.chat_id) except Exception as e: logger.error("Error sending DingTalk message: {}", e) diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.py index ee54eed..8baecbf 100644 --- a/nanobot/channels/discord.py +++ b/nanobot/channels/discord.py @@ -94,7 +94,7 @@ class DiscordChannel(BaseChannel): if response.status_code == 429: data = response.json() retry_after = float(data.get("retry_after", 1.0)) - logger.warning(f"Discord rate limited, retrying in {retry_after}s") + logger.warning("Discord rate limited, retrying in {}s", retry_after) await asyncio.sleep(retry_after) continue response.raise_for_status() diff --git a/nanobot/channels/email.py b/nanobot/channels/email.py index 8a1ee79..1b6f46b 100644 --- a/nanobot/channels/email.py +++ b/nanobot/channels/email.py @@ -162,7 +162,7 @@ class EmailChannel(BaseChannel): missing.append("smtp_password") if missing: - logger.error(f"Email channel not configured, missing: {', '.join(missing)}") + logger.error("Email channel not configured, missing: {}", ', '.join(missing)) return False return True diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index 6f62202..c17bf1a 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -196,7 +196,7 @@ class FeishuChannel(BaseChannel): if not response.success(): logger.warning("Failed to add reaction: code={}, msg={}", response.code, response.msg) else: - logger.debug(f"Added {emoji_type} reaction to message {message_id}") + logger.debug("Added {} reaction to message {}", emoji_type, message_id) except Exception as e: logger.warning("Error adding reaction: {}", e) @@ -309,7 +309,7 @@ class FeishuChannel(BaseChannel): response = self._client.im.v1.image.create(request) if response.success(): image_key = response.data.image_key - logger.debug(f"Uploaded image {os.path.basename(file_path)}: {image_key}") + logger.debug("Uploaded image {}: {}", os.path.basename(file_path), image_key) return image_key else: logger.error("Failed to upload image: code={}, msg={}", response.code, response.msg) @@ -336,7 +336,7 @@ class FeishuChannel(BaseChannel): response = self._client.im.v1.file.create(request) if response.success(): file_key = response.data.file_key - logger.debug(f"Uploaded file {file_name}: {file_key}") + logger.debug("Uploaded file {}: {}", file_name, file_key) return file_key else: logger.error("Failed to upload file: code={}, msg={}", response.code, response.msg) @@ -364,7 +364,7 @@ class FeishuChannel(BaseChannel): msg_type, response.code, response.msg, response.get_log_id() ) return False - logger.debug(f"Feishu {msg_type} message sent to {receive_id}") + logger.debug("Feishu {} message sent to {}", msg_type, receive_id) return True except Exception as e: logger.error("Error sending Feishu {} message: {}", msg_type, e) @@ -382,7 +382,7 @@ class FeishuChannel(BaseChannel): for file_path in msg.media: if not os.path.isfile(file_path): - logger.warning(f"Media file not found: {file_path}") + logger.warning("Media file not found: {}", file_path) continue ext = os.path.splitext(file_path)[1].lower() if ext in self._IMAGE_EXTS: diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index 3e714c3..6fbab04 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -45,7 +45,7 @@ class ChannelManager: ) logger.info("Telegram channel enabled") except ImportError as e: - logger.warning(f"Telegram channel not available: {e}") + logger.warning("Telegram channel not available: {}", e) # WhatsApp channel if self.config.channels.whatsapp.enabled: @@ -56,7 +56,7 @@ class ChannelManager: ) logger.info("WhatsApp channel enabled") except ImportError as e: - logger.warning(f"WhatsApp channel not available: {e}") + logger.warning("WhatsApp channel not available: {}", e) # Discord channel if self.config.channels.discord.enabled: @@ -67,7 +67,7 @@ class ChannelManager: ) logger.info("Discord channel enabled") except ImportError as e: - logger.warning(f"Discord channel not available: {e}") + logger.warning("Discord channel not available: {}", e) # Feishu channel if self.config.channels.feishu.enabled: @@ -78,7 +78,7 @@ class ChannelManager: ) logger.info("Feishu channel enabled") except ImportError as e: - logger.warning(f"Feishu channel not available: {e}") + logger.warning("Feishu channel not available: {}", e) # Mochat channel if self.config.channels.mochat.enabled: @@ -90,7 +90,7 @@ class ChannelManager: ) logger.info("Mochat channel enabled") except ImportError as e: - logger.warning(f"Mochat channel not available: {e}") + logger.warning("Mochat channel not available: {}", e) # DingTalk channel if self.config.channels.dingtalk.enabled: @@ -101,7 +101,7 @@ class ChannelManager: ) logger.info("DingTalk channel enabled") except ImportError as e: - logger.warning(f"DingTalk channel not available: {e}") + logger.warning("DingTalk channel not available: {}", e) # Email channel if self.config.channels.email.enabled: @@ -112,7 +112,7 @@ class ChannelManager: ) logger.info("Email channel enabled") except ImportError as e: - logger.warning(f"Email channel not available: {e}") + logger.warning("Email channel not available: {}", e) # Slack channel if self.config.channels.slack.enabled: @@ -123,7 +123,7 @@ class ChannelManager: ) logger.info("Slack channel enabled") except ImportError as e: - logger.warning(f"Slack channel not available: {e}") + logger.warning("Slack channel not available: {}", e) # QQ channel if self.config.channels.qq.enabled: @@ -135,7 +135,7 @@ class ChannelManager: ) logger.info("QQ channel enabled") except ImportError as e: - logger.warning(f"QQ channel not available: {e}") + logger.warning("QQ channel not available: {}", e) async def _start_channel(self, name: str, channel: BaseChannel) -> None: """Start a channel and log any exceptions.""" @@ -156,7 +156,7 @@ class ChannelManager: # Start channels tasks = [] for name, channel in self.channels.items(): - logger.info(f"Starting {name} channel...") + logger.info("Starting {} channel...", name) tasks.append(asyncio.create_task(self._start_channel(name, channel))) # Wait for all to complete (they should run forever) @@ -178,7 +178,7 @@ class ChannelManager: for name, channel in self.channels.items(): try: await channel.stop() - logger.info(f"Stopped {name} channel") + logger.info("Stopped {} channel", name) except Exception as e: logger.error("Error stopping {}: {}", name, e) @@ -200,7 +200,7 @@ class ChannelManager: except Exception as e: logger.error("Error sending to {}: {}", msg.channel, e) else: - logger.warning(f"Unknown channel: {msg.channel}") + logger.warning("Unknown channel: {}", msg.channel) except asyncio.TimeoutError: continue diff --git a/nanobot/channels/qq.py b/nanobot/channels/qq.py index 1d00bc7..16cbfb8 100644 --- a/nanobot/channels/qq.py +++ b/nanobot/channels/qq.py @@ -34,7 +34,7 @@ def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]": super().__init__(intents=intents) async def on_ready(self): - logger.info(f"QQ bot ready: {self.robot.name}") + logger.info("QQ bot ready: {}", self.robot.name) async def on_c2c_message_create(self, message: "C2CMessage"): await channel._on_message(message) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index 7dd2971..79cbe76 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -36,7 +36,7 @@ class SlackChannel(BaseChannel): logger.error("Slack bot/app token not configured") return if self.config.mode != "socket": - logger.error(f"Unsupported Slack mode: {self.config.mode}") + logger.error("Unsupported Slack mode: {}", self.config.mode) return self._running = True @@ -53,7 +53,7 @@ class SlackChannel(BaseChannel): try: auth = await self._web_client.auth_test() self._bot_user_id = auth.get("user_id") - logger.info(f"Slack bot connected as {self._bot_user_id}") + logger.info("Slack bot connected as {}", self._bot_user_id) except Exception as e: logger.warning("Slack auth_test failed: {}", e) diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.py index 42db489..fa36c98 100644 --- a/nanobot/channels/telegram.py +++ b/nanobot/channels/telegram.py @@ -165,7 +165,7 @@ class TelegramChannel(BaseChannel): # Get bot info and register command menu bot_info = await self._app.bot.get_me() - logger.info(f"Telegram bot @{bot_info.username} connected") + logger.info("Telegram bot @{} connected", bot_info.username) try: await self._app.bot.set_my_commands(self.BOT_COMMANDS) @@ -221,7 +221,7 @@ class TelegramChannel(BaseChannel): try: chat_id = int(msg.chat_id) except ValueError: - logger.error(f"Invalid chat_id: {msg.chat_id}") + logger.error("Invalid chat_id: {}", msg.chat_id) return # Send media files @@ -344,14 +344,14 @@ class TelegramChannel(BaseChannel): transcriber = GroqTranscriptionProvider(api_key=self.groq_api_key) transcription = await transcriber.transcribe(file_path) if transcription: - logger.info(f"Transcribed {media_type}: {transcription[:50]}...") + logger.info("Transcribed {}: {}...", media_type, transcription[:50]) content_parts.append(f"[transcription: {transcription}]") else: content_parts.append(f"[{media_type}: {file_path}]") else: content_parts.append(f"[{media_type}: {file_path}]") - logger.debug(f"Downloaded {media_type} to {file_path}") + logger.debug("Downloaded {} to {}", media_type, file_path) except Exception as e: logger.error("Failed to download media: {}", e) content_parts.append(f"[{media_type}: download failed]") diff --git a/nanobot/channels/whatsapp.py b/nanobot/channels/whatsapp.py index 4d12360..f3e14d9 100644 --- a/nanobot/channels/whatsapp.py +++ b/nanobot/channels/whatsapp.py @@ -34,7 +34,7 @@ class WhatsAppChannel(BaseChannel): bridge_url = self.config.bridge_url - logger.info(f"Connecting to WhatsApp bridge at {bridge_url}...") + logger.info("Connecting to WhatsApp bridge at {}...", bridge_url) self._running = True @@ -112,11 +112,11 @@ class WhatsAppChannel(BaseChannel): # Extract just the phone number or lid as chat_id user_id = pn if pn else sender sender_id = user_id.split("@")[0] if "@" in user_id else user_id - logger.info(f"Sender {sender}") + logger.info("Sender {}", sender) # Handle voice transcription if it's a voice message if content == "[Voice Message]": - logger.info(f"Voice message received from {sender_id}, but direct download from bridge is not yet supported.") + logger.info("Voice message received from {}, but direct download from bridge is not yet supported.", sender_id) content = "[Voice Message: Transcription not available for WhatsApp yet]" await self._handle_message( @@ -133,7 +133,7 @@ class WhatsAppChannel(BaseChannel): elif msg_type == "status": # Connection status update status = data.get("status") - logger.info(f"WhatsApp status: {status}") + logger.info("WhatsApp status: {}", status) if status == "connected": self._connected = True diff --git a/nanobot/cron/service.py b/nanobot/cron/service.py index d2b9ef7..4c14ef7 100644 --- a/nanobot/cron/service.py +++ b/nanobot/cron/service.py @@ -157,7 +157,7 @@ class CronService: self._recompute_next_runs() self._save_store() self._arm_timer() - logger.info(f"Cron service started with {len(self._store.jobs if self._store else [])} jobs") + logger.info("Cron service started with {} jobs", len(self._store.jobs if self._store else [])) def stop(self) -> None: """Stop the cron service.""" @@ -222,7 +222,7 @@ class CronService: async def _execute_job(self, job: CronJob) -> None: """Execute a single job.""" start_ms = _now_ms() - logger.info(f"Cron: executing job '{job.name}' ({job.id})") + logger.info("Cron: executing job '{}' ({})", job.name, job.id) try: response = None @@ -231,7 +231,7 @@ class CronService: job.state.last_status = "ok" job.state.last_error = None - logger.info(f"Cron: job '{job.name}' completed") + logger.info("Cron: job '{}' completed", job.name) except Exception as e: job.state.last_status = "error" @@ -296,7 +296,7 @@ class CronService: self._save_store() self._arm_timer() - logger.info(f"Cron: added job '{name}' ({job.id})") + logger.info("Cron: added job '{}' ({})", name, job.id) return job def remove_job(self, job_id: str) -> bool: @@ -309,7 +309,7 @@ class CronService: if removed: self._save_store() self._arm_timer() - logger.info(f"Cron: removed job {job_id}") + logger.info("Cron: removed job {}", job_id) return removed diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index 8bdc78f..8b33e3a 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -78,7 +78,7 @@ class HeartbeatService: self._running = True self._task = asyncio.create_task(self._run_loop()) - logger.info(f"Heartbeat started (every {self.interval_s}s)") + logger.info("Heartbeat started (every {}s)", self.interval_s) def stop(self) -> None: """Stop the heartbeat service.""" @@ -118,7 +118,7 @@ class HeartbeatService: if HEARTBEAT_OK_TOKEN.replace("_", "") in response.upper().replace("_", ""): logger.info("Heartbeat: OK (no action needed)") else: - logger.info(f"Heartbeat: completed task") + logger.info("Heartbeat: completed task") except Exception as e: logger.error("Heartbeat execution failed: {}", e) diff --git a/nanobot/providers/transcription.py b/nanobot/providers/transcription.py index eb5969d..7a3c628 100644 --- a/nanobot/providers/transcription.py +++ b/nanobot/providers/transcription.py @@ -35,7 +35,7 @@ class GroqTranscriptionProvider: path = Path(file_path) if not path.exists(): - logger.error(f"Audio file not found: {file_path}") + logger.error("Audio file not found: {}", file_path) return "" try: diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 44dcecb..9c0c7de 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -110,7 +110,7 @@ class SessionManager: if legacy_path.exists(): import shutil shutil.move(str(legacy_path), str(path)) - logger.info(f"Migrated session {key} from legacy path") + logger.info("Migrated session {} from legacy path", key) if not path.exists(): return None From e17342ddfc812a629d54e4be28f7cb39a84be424 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:03:24 +0000 Subject: [PATCH 024/154] fix: pass workspace to file tools in subagent --- nanobot/agent/subagent.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.py index 767bc68..d87c61a 100644 --- a/nanobot/agent/subagent.py +++ b/nanobot/agent/subagent.py @@ -103,10 +103,10 @@ class SubagentManager: # Build subagent tools (no message tool, no spawn tool) tools = ToolRegistry() allowed_dir = self.workspace if self.restrict_to_workspace else None - tools.register(ReadFileTool(allowed_dir=allowed_dir)) - tools.register(WriteFileTool(allowed_dir=allowed_dir)) - tools.register(EditFileTool(allowed_dir=allowed_dir)) - tools.register(ListDirTool(allowed_dir=allowed_dir)) + tools.register(ReadFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) + tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) + tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) + tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) tools.register(ExecTool( working_dir=str(self.workspace), timeout=self.exec_config.timeout, From 002de466d769ffa81a0fa89ff8056f0eb9cdc5fd Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:12:23 +0000 Subject: [PATCH 025/154] chore: remove test file for memory consolidation fix --- README.md | 2 +- tests/test_memory_consolidation_types.py | 133 ----------------------- 2 files changed, 1 insertion(+), 134 deletions(-) delete mode 100644 tests/test_memory_consolidation_types.py diff --git a/README.md b/README.md index a474367..289ff28 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ⚑️ Delivers core agent functionality in just **~4,000** lines of code β€” **99% smaller** than Clawdbot's 430k+ lines. -πŸ“ Real-time line count: **3,761 lines** (run `bash core_agent_lines.sh` to verify anytime) +πŸ“ Real-time line count: **3,781 lines** (run `bash core_agent_lines.sh` to verify anytime) ## πŸ“’ News diff --git a/tests/test_memory_consolidation_types.py b/tests/test_memory_consolidation_types.py deleted file mode 100644 index 3b76596..0000000 --- a/tests/test_memory_consolidation_types.py +++ /dev/null @@ -1,133 +0,0 @@ -"""Test memory consolidation handles non-string values from LLM. - -This test verifies the fix for the bug where memory consolidation fails -when LLM returns JSON objects instead of strings for history_entry or -memory_update fields. - -Related issue: Memory consolidation fails with TypeError when LLM returns dict -""" - -import json -import tempfile -from pathlib import Path - -import pytest - -from nanobot.agent.memory import MemoryStore - - -class TestMemoryConsolidationTypeHandling: - """Test that MemoryStore methods handle type conversion correctly.""" - - def test_append_history_accepts_string(self): - """MemoryStore.append_history should accept string values.""" - with tempfile.TemporaryDirectory() as tmpdir: - memory = MemoryStore(Path(tmpdir)) - - # Should not raise TypeError - memory.append_history("[2026-02-14] Test entry") - - # Verify content was written - history_content = memory.history_file.read_text() - assert "Test entry" in history_content - - def test_write_long_term_accepts_string(self): - """MemoryStore.write_long_term should accept string values.""" - with tempfile.TemporaryDirectory() as tmpdir: - memory = MemoryStore(Path(tmpdir)) - - # Should not raise TypeError - memory.write_long_term("- Fact 1\n- Fact 2") - - # Verify content was written - memory_content = memory.read_long_term() - assert "Fact 1" in memory_content - - def test_type_conversion_dict_to_str(self): - """Dict values should be converted to JSON strings.""" - input_val = {"timestamp": "2026-02-14", "summary": "test"} - expected = '{"timestamp": "2026-02-14", "summary": "test"}' - - # Simulate the fix logic - if not isinstance(input_val, str): - result = json.dumps(input_val, ensure_ascii=False) - else: - result = input_val - - assert result == expected - assert isinstance(result, str) - - def test_type_conversion_list_to_str(self): - """List values should be converted to JSON strings.""" - input_val = ["item1", "item2"] - expected = '["item1", "item2"]' - - # Simulate the fix logic - if not isinstance(input_val, str): - result = json.dumps(input_val, ensure_ascii=False) - else: - result = input_val - - assert result == expected - assert isinstance(result, str) - - def test_type_conversion_str_unchanged(self): - """String values should remain unchanged.""" - input_val = "already a string" - - # Simulate the fix logic - if not isinstance(input_val, str): - result = json.dumps(input_val, ensure_ascii=False) - else: - result = input_val - - assert result == input_val - assert isinstance(result, str) - - def test_memory_consolidation_simulation(self): - """Simulate full consolidation with dict values from LLM.""" - with tempfile.TemporaryDirectory() as tmpdir: - memory = MemoryStore(Path(tmpdir)) - - # Simulate LLM returning dict values (the bug scenario) - history_entry = {"timestamp": "2026-02-14", "summary": "User asked about..."} - memory_update = {"facts": ["Location: Beijing", "Skill: Python"]} - - # Apply the fix: convert to str - if not isinstance(history_entry, str): - history_entry = json.dumps(history_entry, ensure_ascii=False) - if not isinstance(memory_update, str): - memory_update = json.dumps(memory_update, ensure_ascii=False) - - # Should not raise TypeError after conversion - memory.append_history(history_entry) - memory.write_long_term(memory_update) - - # Verify content - assert memory.history_file.exists() - assert memory.memory_file.exists() - - history_content = memory.history_file.read_text() - memory_content = memory.read_long_term() - - assert "timestamp" in history_content - assert "facts" in memory_content - - -class TestPromptOptimization: - """Test that prompt optimization helps prevent the issue.""" - - def test_prompt_includes_string_requirement(self): - """The prompt should explicitly require string values.""" - # This is a documentation test - verify the fix is in place - # by checking the expected prompt content - expected_keywords = [ - "MUST be strings", - "not objects or arrays", - "Example:", - ] - - # The actual prompt content is in nanobot/agent/loop.py - # This test serves as documentation of the expected behavior - for keyword in expected_keywords: - assert keyword, f"Prompt should include: {keyword}" From 9ffae47c13862c0942b16016e67725af199a5ace Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:21:02 +0000 Subject: [PATCH 026/154] refactor(litellm): remove redundant comments in cache_control methods --- nanobot/providers/litellm_provider.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 08c2f53..66751ed 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -117,7 +117,6 @@ class LiteLLMProvider(LLMProvider): tools: list[dict[str, Any]] | None, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]: """Return copies of messages and tools with cache_control injected.""" - # Transform the system message new_messages = [] for msg in messages: if msg.get("role") == "system": @@ -131,7 +130,6 @@ class LiteLLMProvider(LLMProvider): else: new_messages.append(msg) - # Add cache_control to the last tool definition new_tools = tools if tools: new_tools = list(tools) From 2383dcb3a82868162a970b91528945a84467af93 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:31:48 +0000 Subject: [PATCH 027/154] style: use loguru native format and trim comments in interim retry --- README.md | 2 +- nanobot/agent/loop.py | 11 +++-------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 289ff28..21c5491 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ⚑️ Delivers core agent functionality in just **~4,000** lines of code β€” **99% smaller** than Clawdbot's 430k+ lines. -πŸ“ Real-time line count: **3,781 lines** (run `bash core_agent_lines.sh` to verify anytime) +πŸ“ Real-time line count: **3,793 lines** (run `bash core_agent_lines.sh` to verify anytime) ## πŸ“’ News diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 3829626..a90dccb 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -227,16 +227,11 @@ class AgentLoop: ) else: final_content = self._strip_think(response.content) - # Some models (MiniMax, Gemini Flash, GPT-4.1, etc.) send an - # interim text response (e.g. "Let me investigate...") before - # making tool calls. If no tools have been used yet and we - # haven't already retried, add the text to the conversation - # and give the model one more chance to use tools. - # We do NOT forward the interim text as progress to avoid - # duplicate messages when the model simply answers directly. + # Some models send an interim text response before tool calls. + # Give them one retry; don't forward the text to avoid duplicates. if not tools_used and not text_only_retried and final_content: text_only_retried = True - logger.debug(f"Interim text response (no tools used yet), retrying: {final_content[:80]}") + logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) messages = self.context.add_assistant_message( messages, response.content, reasoning_content=response.reasoning_content, From 2f315ec567ab2432ab32332e3fa671a1bdc44dc6 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:39:26 +0000 Subject: [PATCH 028/154] style: trim _on_help docstring --- nanobot/channels/telegram.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.py index af161d4..768e565 100644 --- a/nanobot/channels/telegram.py +++ b/nanobot/channels/telegram.py @@ -267,11 +267,7 @@ class TelegramChannel(BaseChannel): ) async def _on_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: - """Handle /help command directly, bypassing access control. - - /help is informational and should be accessible to all users, - even those not in the allowFrom list. - """ + """Handle /help command, bypassing ACL so all users can access it.""" if not update.message: return await update.message.reply_text( From 25efd1bc543d2de31bb9f347b8fa168512b7dfde Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:45:42 +0000 Subject: [PATCH 029/154] docs: update docs for providers --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index dc85b54..c0bd4f4 100644 --- a/README.md +++ b/README.md @@ -591,7 +591,7 @@ Config file: `~/.nanobot/config.json` | `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | | `minimax` | LLM (MiniMax direct) | [platform.minimax.io](https://platform.minimax.io) | | `aihubmix` | LLM (API gateway, access to all models) | [aihubmix.com](https://aihubmix.com) | -| `siliconflow` | LLM (SiliconFlow/η‘…εŸΊζ΅εŠ¨, API gateway) | [siliconflow.cn](https://siliconflow.cn) | +| `siliconflow` | LLM (SiliconFlow/η‘…εŸΊζ΅εŠ¨) | [siliconflow.cn](https://siliconflow.cn) | | `volcengine` | LLM (VolcEngine/η«ε±±εΌ•ζ“Ž) | [volcengine.com](https://www.volcengine.com) | | `dashscope` | LLM (Qwen) | [dashscope.console.aliyun.com](https://dashscope.console.aliyun.com) | | `moonshot` | LLM (Moonshot/Kimi) | [platform.moonshot.cn](https://platform.moonshot.cn) | From f5fe74f5789be04028a03ed8c95c9f35feb2fd81 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 08:49:49 +0000 Subject: [PATCH 030/154] style: move httpx import to top-level and fix README example for MCP headers --- README.md | 17 ++++++++--------- nanobot/agent/tools/mcp.py | 2 +- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index ece47e0..b37f8bd 100644 --- a/README.md +++ b/README.md @@ -753,15 +753,14 @@ Add MCP servers to your `config.json`: "filesystem": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"] - } - }, - "urlMcpServers": { - "url": "https://xx.xx.xx.xx:xxxx/mcp/", - "headers": { - "Authorization": "Bearer xxxxx", - "X-API-Key": "xxxxxxx" - } }, + "my-remote-mcp": { + "url": "https://example.com/mcp/", + "headers": { + "Authorization": "Bearer xxxxx" + } + } + } } } ``` @@ -771,7 +770,7 @@ Two transport modes are supported: | Mode | Config | Example | |------|--------|---------| | **Stdio** | `command` + `args` | Local process via `npx` / `uvx` | -| **HTTP** | `url` + `option(headers)`| Remote endpoint (`https://mcp.example.com/sse`) | +| **HTTP** | `url` + `headers` (optional) | Remote endpoint (`https://mcp.example.com/sse`) | MCP tools are automatically discovered and registered on startup. The LLM can use them alongside built-in tools β€” no extra configuration needed. diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index a02f42b..ad352bf 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -3,6 +3,7 @@ from contextlib import AsyncExitStack from typing import Any +import httpx from loguru import logger from nanobot.agent.tools.base import Tool @@ -59,7 +60,6 @@ async def connect_mcp_servers( read, write = await stack.enter_async_context(stdio_client(params)) elif cfg.url: from mcp.client.streamable_http import streamable_http_client - import httpx if cfg.headers: http_client = await stack.enter_async_context( httpx.AsyncClient( From b97b1a5e91bd8778e5625b2debc48c49998f0ada Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 09:04:33 +0000 Subject: [PATCH 031/154] fix: pass full agent config including mcp_servers to cron run command --- nanobot/cli/commands.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 9389d0b..a135349 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -864,11 +864,12 @@ def cron_run( force: bool = typer.Option(False, "--force", "-f", help="Run even if disabled"), ): """Manually run a job.""" + from loguru import logger from nanobot.config.loader import load_config, get_data_dir from nanobot.cron.service import CronService + from nanobot.cron.types import CronJob from nanobot.bus.queue import MessageBus from nanobot.agent.loop import AgentLoop - from loguru import logger logger.disable("nanobot") config = load_config() @@ -879,10 +880,14 @@ def cron_run( provider=provider, workspace=config.workspace_path, model=config.agents.defaults.model, + temperature=config.agents.defaults.temperature, + max_tokens=config.agents.defaults.max_tokens, max_iterations=config.agents.defaults.max_tool_iterations, memory_window=config.agents.defaults.memory_window, + brave_api_key=config.tools.web.search.api_key or None, exec_config=config.tools.exec, restrict_to_workspace=config.tools.restrict_to_workspace, + mcp_servers=config.tools.mcp_servers, ) store_path = get_data_dir() / "cron" / "jobs.json" @@ -890,7 +895,7 @@ def cron_run( result_holder = [] - async def on_job(job): + async def on_job(job: CronJob) -> str | None: response = await agent_loop.process_direct( job.payload.message, session_key=f"cron:{job.id}", From e39bbaa9be85e57020be9735051e5f8044f53ed1 Mon Sep 17 00:00:00 2001 From: Paul Date: Fri, 20 Feb 2026 09:54:21 +0000 Subject: [PATCH 032/154] feat(slack): add media file upload support Use files_upload_v2 API to upload media attachments in Slack messages. This enables the message tool's media parameter to work correctly when sending images or other files through the Slack channel. Requires files:write OAuth scope. --- nanobot/channels/slack.py | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index dca5055..d29f1e1 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -84,11 +84,26 @@ class SlackChannel(BaseChannel): channel_type = slack_meta.get("channel_type") # Only reply in thread for channel/group messages; DMs don't use threads use_thread = thread_ts and channel_type != "im" - await self._web_client.chat_postMessage( - channel=msg.chat_id, - text=self._to_mrkdwn(msg.content), - thread_ts=thread_ts if use_thread else None, - ) + thread_ts_param = thread_ts if use_thread else None + + # Send text message if content is present + if msg.content: + await self._web_client.chat_postMessage( + channel=msg.chat_id, + text=self._to_mrkdwn(msg.content), + thread_ts=thread_ts_param, + ) + + # Upload media files if present + for media_path in msg.media or []: + try: + await self._web_client.files_upload_v2( + channel=msg.chat_id, + file=media_path, + thread_ts=thread_ts_param, + ) + except Exception as e: + logger.error(f"Failed to upload file {media_path}: {e}") except Exception as e: logger.error(f"Error sending Slack message: {e}") From e1854c4373cd7b944c18452bb0c852ee214c032d Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 11:13:10 +0000 Subject: [PATCH 033/154] feat: make Telegram reply-to-message behavior configurable, default false --- nanobot/channels/telegram.py | 14 +++++++------- nanobot/config/schema.py | 1 + 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.py index d29fdfd..6cd98e7 100644 --- a/nanobot/channels/telegram.py +++ b/nanobot/channels/telegram.py @@ -224,14 +224,14 @@ class TelegramChannel(BaseChannel): logger.error("Invalid chat_id: {}", msg.chat_id) return - # Build reply parameters (Will reply to the message if it exists) - reply_to_message_id = msg.metadata.get("message_id") reply_params = None - if reply_to_message_id: - reply_params = ReplyParameters( - message_id=reply_to_message_id, - allow_sending_without_reply=True - ) + if self.config.reply_to_message: + reply_to_message_id = msg.metadata.get("message_id") + if reply_to_message_id: + reply_params = ReplyParameters( + message_id=reply_to_message_id, + allow_sending_without_reply=True + ) # Send media files for media_path in (msg.media or []): diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index 570f322..966d11d 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -28,6 +28,7 @@ class TelegramConfig(Base): token: str = "" # Bot token from @BotFather allow_from: list[str] = Field(default_factory=list) # Allowed user IDs or usernames proxy: str | None = None # HTTP/SOCKS5 proxy URL, e.g. "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080" + reply_to_message: bool = False # If true, bot replies quote the original message class FeishuConfig(Base): From 8db91f59e26cd0ca83fc5eb01dd346a2410d98f9 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 11:18:57 +0000 Subject: [PATCH 034/154] style: remove trailing space --- README.md | 2 +- nanobot/agent/loop.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index b37f8bd..68ad5a9 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ⚑️ Delivers core agent functionality in just **~4,000** lines of code β€” **99% smaller** than Clawdbot's 430k+ lines. -πŸ“ Real-time line count: **3,793 lines** (run `bash core_agent_lines.sh` to verify anytime) +πŸ“ Real-time line count: **3,827 lines** (run `bash core_agent_lines.sh` to verify anytime) ## πŸ“’ News diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 14a8be6..3016d92 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -200,7 +200,7 @@ class AgentLoop: if response.has_tool_calls: if on_progress: clean = self._strip_think(response.content) - if clean: + if clean: await on_progress(clean) await on_progress(self._tool_hint(response.tool_calls)) From 5cc019bf1a53df1fd2ff1e50cd40b4e358804a4f Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 11:27:21 +0000 Subject: [PATCH 035/154] style: trim verbose comments in _sanitize_messages --- nanobot/providers/litellm_provider.py | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 4fe44f7..edeb5c6 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -12,9 +12,7 @@ from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest from nanobot.providers.registry import find_by_model, find_gateway -# Keys that are part of the OpenAI chat-completion message schema. -# Anything else (e.g. reasoning_content, timestamp) is stripped before sending -# to avoid "Unrecognized chat message" errors from strict providers like StepFun. +# Standard OpenAI chat-completion message keys; extras (e.g. reasoning_content) are stripped for strict providers. _ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name"}) @@ -155,13 +153,7 @@ class LiteLLMProvider(LLMProvider): @staticmethod def _sanitize_messages(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Strip non-standard keys from messages for strict providers. - - Some providers (e.g. StepFun via OpenRouter) reject messages that - contain extra keys like ``reasoning_content``. This method keeps - only the keys defined in the OpenAI chat-completion schema and - ensures every assistant message has a ``content`` key. - """ + """Strip non-standard keys and ensure assistant messages have a content key.""" sanitized = [] for msg in messages: clean = {k: v for k, v in msg.items() if k in _ALLOWED_MSG_KEYS} From 755e42412717c0c4372b79c4d53f0dcb050351f7 Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Fri, 20 Feb 2026 12:38:43 +0100 Subject: [PATCH 036/154] fix(loop): serialize /new consolidation and track task refs --- nanobot/agent/loop.py | 251 ++++++++++++++++++++----------- tests/test_consolidate_offset.py | 246 ++++++++++++++++++++++++++++++ 2 files changed, 407 insertions(+), 90 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 3016d92..7806fb8 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -21,7 +21,6 @@ from nanobot.agent.tools.web import WebSearchTool, WebFetchTool from nanobot.agent.tools.message import MessageTool from nanobot.agent.tools.spawn import SpawnTool from nanobot.agent.tools.cron import CronTool -from nanobot.agent.memory import MemoryStore from nanobot.agent.subagent import SubagentManager from nanobot.session.manager import Session, SessionManager @@ -57,6 +56,7 @@ class AgentLoop: ): from nanobot.config.schema import ExecToolConfig from nanobot.cron.service import CronService + self.bus = bus self.provider = provider self.workspace = workspace @@ -84,14 +84,16 @@ class AgentLoop: exec_config=self.exec_config, restrict_to_workspace=restrict_to_workspace, ) - + self._running = False self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None self._mcp_connected = False self._consolidating: set[str] = set() # Session keys with consolidation in progress + self._consolidation_tasks: set[asyncio.Task] = set() # Keep strong refs for in-flight tasks + self._consolidation_locks: dict[str, asyncio.Lock] = {} self._register_default_tools() - + def _register_default_tools(self) -> None: """Register the default set of tools.""" # File tools (workspace for relative paths, restrict if configured) @@ -100,36 +102,39 @@ class AgentLoop: self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) - + # Shell tool - self.tools.register(ExecTool( - working_dir=str(self.workspace), - timeout=self.exec_config.timeout, - restrict_to_workspace=self.restrict_to_workspace, - )) - + self.tools.register( + ExecTool( + working_dir=str(self.workspace), + timeout=self.exec_config.timeout, + restrict_to_workspace=self.restrict_to_workspace, + ) + ) + # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - + # Message tool message_tool = MessageTool(send_callback=self.bus.publish_outbound) self.tools.register(message_tool) - + # Spawn tool (for subagents) spawn_tool = SpawnTool(manager=self.subagents) self.tools.register(spawn_tool) - + # Cron tool (for scheduling) if self.cron_service: self.tools.register(CronTool(self.cron_service)) - + async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: return self._mcp_connected = True from nanobot.agent.tools.mcp import connect_mcp_servers + self._mcp_stack = AsyncExitStack() await self._mcp_stack.__aenter__() await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) @@ -158,11 +163,13 @@ class AgentLoop: @staticmethod def _tool_hint(tool_calls: list) -> str: """Format tool calls as concise hint, e.g. 'web_search("query")'.""" + def _fmt(tc): val = next(iter(tc.arguments.values()), None) if tc.arguments else None if not isinstance(val, str): return tc.name return f'{tc.name}("{val[:40]}…")' if len(val) > 40 else f'{tc.name}("{val}")' + return ", ".join(_fmt(tc) for tc in tool_calls) async def _run_agent_loop( @@ -210,13 +217,15 @@ class AgentLoop: "type": "function", "function": { "name": tc.name, - "arguments": json.dumps(tc.arguments, ensure_ascii=False) - } + "arguments": json.dumps(tc.arguments, ensure_ascii=False), + }, } for tc in response.tool_calls ] messages = self.context.add_assistant_message( - messages, response.content, tool_call_dicts, + messages, + response.content, + tool_call_dicts, reasoning_content=response.reasoning_content, ) @@ -234,9 +243,13 @@ class AgentLoop: # Give them one retry; don't forward the text to avoid duplicates. if not tools_used and not text_only_retried and final_content: text_only_retried = True - logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) + logger.debug( + "Interim text response (no tools used yet), retrying: {}", + final_content[:80], + ) messages = self.context.add_assistant_message( - messages, response.content, + messages, + response.content, reasoning_content=response.reasoning_content, ) final_content = None @@ -253,24 +266,23 @@ class AgentLoop: while self._running: try: - msg = await asyncio.wait_for( - self.bus.consume_inbound(), - timeout=1.0 - ) + msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0) try: response = await self._process_message(msg) if response: await self.bus.publish_outbound(response) except Exception as e: logger.error("Error processing message: {}", e) - await self.bus.publish_outbound(OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=f"Sorry, I encountered an error: {str(e)}" - )) + await self.bus.publish_outbound( + OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content=f"Sorry, I encountered an error: {str(e)}", + ) + ) except asyncio.TimeoutError: continue - + async def close_mcp(self) -> None: """Close MCP connections.""" if self._mcp_stack: @@ -284,7 +296,15 @@ class AgentLoop: """Stop the agent loop.""" self._running = False logger.info("Agent loop stopping") - + + def _get_consolidation_lock(self, session_key: str) -> asyncio.Lock: + """Return a per-session lock for memory consolidation writers.""" + lock = self._consolidation_locks.get(session_key) + if lock is None: + lock = asyncio.Lock() + self._consolidation_locks[session_key] = lock + return lock + async def _process_message( self, msg: InboundMessage, @@ -293,56 +313,75 @@ class AgentLoop: ) -> OutboundMessage | None: """ Process a single inbound message. - + Args: msg: The inbound message to process. session_key: Override session key (used by process_direct). on_progress: Optional callback for intermediate output (defaults to bus publish). - + Returns: The response message, or None if no response needed. """ # System messages route back via chat_id ("channel:chat_id") if msg.channel == "system": return await self._process_system_message(msg) - + preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) - + key = session_key or msg.session_key session = self.sessions.get_or_create(key) - + # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": - # Capture messages before clearing (avoid race condition with background task) messages_to_archive = session.messages.copy() + lock = self._get_consolidation_lock(session.key) + + try: + async with lock: + temp_session = Session(key=session.key) + temp_session.messages = messages_to_archive + await self._consolidate_memory(temp_session, archive_all=True) + except Exception as e: + logger.error("/new archival failed for {}: {}", session.key, e) + return OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="Could not start a new session because memory archival failed. Please try again.", + ) + session.clear() self.sessions.save(session) self.sessions.invalidate(session.key) - - async def _consolidate_and_cleanup(): - temp_session = Session(key=session.key) - temp_session.messages = messages_to_archive - await self._consolidate_memory(temp_session, archive_all=True) - - asyncio.create_task(_consolidate_and_cleanup()) - return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, - content="New session started. Memory consolidation in progress.") + return OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="New session started. Memory consolidation in progress.", + ) if cmd == "/help": - return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, - content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") - + return OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands", + ) + if len(session.messages) > self.memory_window and session.key not in self._consolidating: self._consolidating.add(session.key) + lock = self._get_consolidation_lock(session.key) async def _consolidate_and_unlock(): try: - await self._consolidate_memory(session) + async with lock: + await self._consolidate_memory(session) finally: self._consolidating.discard(session.key) + task = asyncio.current_task() + if task is not None: + self._consolidation_tasks.discard(task) - asyncio.create_task(_consolidate_and_unlock()) + task = asyncio.create_task(_consolidate_and_unlock()) + self._consolidation_tasks.add(task) self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id")) initial_messages = self.context.build_messages( @@ -354,42 +393,49 @@ class AgentLoop: ) async def _bus_progress(content: str) -> None: - await self.bus.publish_outbound(OutboundMessage( - channel=msg.channel, chat_id=msg.chat_id, content=content, - metadata=msg.metadata or {}, - )) + await self.bus.publish_outbound( + OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content=content, + metadata=msg.metadata or {}, + ) + ) final_content, tools_used = await self._run_agent_loop( - initial_messages, on_progress=on_progress or _bus_progress, + initial_messages, + on_progress=on_progress or _bus_progress, ) if final_content is None: final_content = "I've completed processing but have no response to give." - + preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) - + session.add_message("user", msg.content) - session.add_message("assistant", final_content, - tools_used=tools_used if tools_used else None) + session.add_message( + "assistant", final_content, tools_used=tools_used if tools_used else None + ) self.sessions.save(session) - + return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=final_content, - metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) + metadata=msg.metadata + or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) ) - + async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: """ Process a system message (e.g., subagent announce). - + The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ logger.info("Processing system message from {}", msg.sender_id) - + # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: parts = msg.chat_id.split(":", 1) @@ -399,7 +445,7 @@ class AgentLoop: # Fallback origin_channel = "cli" origin_chat_id = msg.chat_id - + session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) @@ -413,17 +459,15 @@ class AgentLoop: if final_content is None: final_content = "Background task completed." - + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") session.add_message("assistant", final_content) self.sessions.save(session) - + return OutboundMessage( - channel=origin_channel, - chat_id=origin_chat_id, - content=final_content + channel=origin_channel, chat_id=origin_chat_id, content=final_content ) - + async def _consolidate_memory(self, session, archive_all: bool = False) -> None: """Consolidate old messages into MEMORY.md + HISTORY.md. @@ -431,34 +475,54 @@ class AgentLoop: archive_all: If True, clear all messages and reset session (for /new command). If False, only write to files without modifying session. """ - memory = MemoryStore(self.workspace) + memory = self.context.memory if archive_all: old_messages = session.messages keep_count = 0 - logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages)) + logger.info( + "Memory consolidation (archive_all): {} total messages archived", + len(session.messages), + ) else: keep_count = self.memory_window // 2 if len(session.messages) <= keep_count: - logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count) + logger.debug( + "Session {}: No consolidation needed (messages={}, keep={})", + session.key, + len(session.messages), + keep_count, + ) return messages_to_process = len(session.messages) - session.last_consolidated if messages_to_process <= 0: - logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages)) + logger.debug( + "Session {}: No new messages to consolidate (last_consolidated={}, total={})", + session.key, + session.last_consolidated, + len(session.messages), + ) return - old_messages = session.messages[session.last_consolidated:-keep_count] + old_messages = session.messages[session.last_consolidated : -keep_count] if not old_messages: return - logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count) + logger.info( + "Memory consolidation started: {} total, {} new to consolidate, {} keep", + len(session.messages), + len(old_messages), + keep_count, + ) lines = [] for m in old_messages: if not m.get("content"): continue tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else "" - lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}") + lines.append( + f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}" + ) conversation = "\n".join(lines) current_memory = memory.read_long_term() @@ -487,7 +551,10 @@ Respond with ONLY valid JSON, no markdown fences.""" try: response = await self.provider.chat( messages=[ - {"role": "system", "content": "You are a memory consolidation agent. Respond only with valid JSON."}, + { + "role": "system", + "content": "You are a memory consolidation agent. Respond only with valid JSON.", + }, {"role": "user", "content": prompt}, ], model=self.model, @@ -500,7 +567,10 @@ Respond with ONLY valid JSON, no markdown fences.""" text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip() result = json_repair.loads(text) if not isinstance(result, dict): - logger.warning("Memory consolidation: unexpected response type, skipping. Response: {}", text[:200]) + logger.warning( + "Memory consolidation: unexpected response type, skipping. Response: {}", + text[:200], + ) return if entry := result.get("history_entry"): @@ -519,7 +589,11 @@ Respond with ONLY valid JSON, no markdown fences.""" session.last_consolidated = 0 else: session.last_consolidated = len(session.messages) - keep_count - logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) + logger.info( + "Memory consolidation done: {} messages, last_consolidated={}", + len(session.messages), + session.last_consolidated, + ) except Exception as e: logger.error("Memory consolidation failed: {}", e) @@ -533,24 +607,21 @@ Respond with ONLY valid JSON, no markdown fences.""" ) -> str: """ Process a message directly (for CLI or cron usage). - + Args: content: The message content. session_key: Session identifier (overrides channel:chat_id for session lookup). channel: Source channel (for tool context routing). chat_id: Source chat ID (for tool context routing). on_progress: Optional callback for intermediate output. - + Returns: The agent's response. """ await self._connect_mcp() - msg = InboundMessage( - channel=channel, - sender_id="user", - chat_id=chat_id, - content=content + msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content) + + response = await self._process_message( + msg, session_key=session_key, on_progress=on_progress ) - - response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" diff --git a/tests/test_consolidate_offset.py b/tests/test_consolidate_offset.py index e204733..6162fa0 100644 --- a/tests/test_consolidate_offset.py +++ b/tests/test_consolidate_offset.py @@ -1,5 +1,8 @@ """Test session management with cache-friendly message handling.""" +import asyncio +from unittest.mock import AsyncMock, MagicMock + import pytest from pathlib import Path from nanobot.session.manager import Session, SessionManager @@ -475,3 +478,246 @@ class TestEmptyAndBoundarySessions: expected_count = 60 - KEEP_COUNT - 10 assert len(old_messages) == expected_count assert_messages_content(old_messages, 10, 34) + + +class TestConsolidationDeduplicationGuard: + """Test that consolidation tasks are deduplicated and serialized.""" + + @pytest.mark.asyncio + async def test_consolidation_guard_prevents_duplicate_tasks(self, tmp_path: Path) -> None: + """Concurrent messages above memory_window spawn only one consolidation task.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(15): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + + consolidation_calls = 0 + + async def _fake_consolidate(_session, archive_all: bool = False) -> None: + nonlocal consolidation_calls + consolidation_calls += 1 + await asyncio.sleep(0.05) + + loop._consolidate_memory = _fake_consolidate # type: ignore[method-assign] + + msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="hello") + await loop._process_message(msg) + await loop._process_message(msg) + await asyncio.sleep(0.1) + + assert consolidation_calls == 1, ( + f"Expected exactly 1 consolidation, got {consolidation_calls}" + ) + + @pytest.mark.asyncio + async def test_new_command_guard_prevents_concurrent_consolidation( + self, tmp_path: Path + ) -> None: + """/new command does not run consolidation concurrently with in-flight consolidation.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(15): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + + consolidation_calls = 0 + active = 0 + max_active = 0 + + async def _fake_consolidate(_session, archive_all: bool = False) -> None: + nonlocal consolidation_calls, active, max_active + consolidation_calls += 1 + active += 1 + max_active = max(max_active, active) + await asyncio.sleep(0.05) + active -= 1 + + loop._consolidate_memory = _fake_consolidate # type: ignore[method-assign] + + msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="hello") + await loop._process_message(msg) + + new_msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/new") + await loop._process_message(new_msg) + await asyncio.sleep(0.1) + + assert consolidation_calls == 2, ( + f"Expected normal + /new consolidations, got {consolidation_calls}" + ) + assert max_active == 1, ( + f"Expected serialized consolidation, observed concurrency={max_active}" + ) + + @pytest.mark.asyncio + async def test_consolidation_tasks_are_referenced(self, tmp_path: Path) -> None: + """create_task results are tracked in _consolidation_tasks while in flight.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(15): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + + started = asyncio.Event() + + async def _slow_consolidate(_session, archive_all: bool = False) -> None: + started.set() + await asyncio.sleep(0.1) + + loop._consolidate_memory = _slow_consolidate # type: ignore[method-assign] + + msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="hello") + await loop._process_message(msg) + + await started.wait() + assert len(loop._consolidation_tasks) == 1, "Task must be referenced while in-flight" + + await asyncio.sleep(0.15) + assert len(loop._consolidation_tasks) == 0, ( + "Task reference must be removed after completion" + ) + + @pytest.mark.asyncio + async def test_new_waits_for_inflight_consolidation_and_preserves_messages( + self, tmp_path: Path + ) -> None: + """/new waits for in-flight consolidation and archives before clear.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(15): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + + started = asyncio.Event() + release = asyncio.Event() + archived_count = 0 + + async def _fake_consolidate(sess, archive_all: bool = False) -> None: + nonlocal archived_count + if archive_all: + archived_count = len(sess.messages) + return + started.set() + await release.wait() + + loop._consolidate_memory = _fake_consolidate # type: ignore[method-assign] + + msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="hello") + await loop._process_message(msg) + await started.wait() + + new_msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/new") + pending_new = asyncio.create_task(loop._process_message(new_msg)) + + await asyncio.sleep(0.02) + assert not pending_new.done(), "/new should wait while consolidation is in-flight" + + release.set() + response = await pending_new + assert response is not None + assert "new session started" in response.content.lower() + assert archived_count > 0, "Expected /new archival to process a non-empty snapshot" + + session_after = loop.sessions.get_or_create("cli:test") + assert session_after.messages == [], "Session should be cleared after successful archival" + + @pytest.mark.asyncio + async def test_new_does_not_clear_session_when_archive_fails(self, tmp_path: Path) -> None: + """/new keeps session data if archive step fails.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(5): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + before_count = len(session.messages) + + async def _failing_consolidate(_session, archive_all: bool = False) -> None: + if archive_all: + raise RuntimeError("forced archive failure") + + loop._consolidate_memory = _failing_consolidate # type: ignore[method-assign] + + new_msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/new") + response = await loop._process_message(new_msg) + + assert response is not None + assert "failed" in response.content.lower() + session_after = loop.sessions.get_or_create("cli:test") + assert len(session_after.messages) == before_count, ( + "Session must remain intact when /new archival fails" + ) From 5f9eca466484e52ce535d4f20f4d0b87581da5db Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Fri, 20 Feb 2026 12:46:11 +0100 Subject: [PATCH 037/154] style(loop): remove formatting-only changes from upstream PR 881 --- nanobot/agent/loop.py | 220 ++++++++++++++++-------------------------- 1 file changed, 85 insertions(+), 135 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 7806fb8..481b72e 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -56,7 +56,6 @@ class AgentLoop: ): from nanobot.config.schema import ExecToolConfig from nanobot.cron.service import CronService - self.bus = bus self.provider = provider self.workspace = workspace @@ -84,16 +83,16 @@ class AgentLoop: exec_config=self.exec_config, restrict_to_workspace=restrict_to_workspace, ) - + self._running = False self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None self._mcp_connected = False self._consolidating: set[str] = set() # Session keys with consolidation in progress - self._consolidation_tasks: set[asyncio.Task] = set() # Keep strong refs for in-flight tasks + self._consolidation_tasks: set[asyncio.Task] = set() # Strong refs to in-flight tasks self._consolidation_locks: dict[str, asyncio.Lock] = {} self._register_default_tools() - + def _register_default_tools(self) -> None: """Register the default set of tools.""" # File tools (workspace for relative paths, restrict if configured) @@ -102,39 +101,36 @@ class AgentLoop: self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) - + # Shell tool - self.tools.register( - ExecTool( - working_dir=str(self.workspace), - timeout=self.exec_config.timeout, - restrict_to_workspace=self.restrict_to_workspace, - ) - ) - + self.tools.register(ExecTool( + working_dir=str(self.workspace), + timeout=self.exec_config.timeout, + restrict_to_workspace=self.restrict_to_workspace, + )) + # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - + # Message tool message_tool = MessageTool(send_callback=self.bus.publish_outbound) self.tools.register(message_tool) - + # Spawn tool (for subagents) spawn_tool = SpawnTool(manager=self.subagents) self.tools.register(spawn_tool) - + # Cron tool (for scheduling) if self.cron_service: self.tools.register(CronTool(self.cron_service)) - + async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: return self._mcp_connected = True from nanobot.agent.tools.mcp import connect_mcp_servers - self._mcp_stack = AsyncExitStack() await self._mcp_stack.__aenter__() await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) @@ -163,13 +159,11 @@ class AgentLoop: @staticmethod def _tool_hint(tool_calls: list) -> str: """Format tool calls as concise hint, e.g. 'web_search("query")'.""" - def _fmt(tc): val = next(iter(tc.arguments.values()), None) if tc.arguments else None if not isinstance(val, str): return tc.name return f'{tc.name}("{val[:40]}…")' if len(val) > 40 else f'{tc.name}("{val}")' - return ", ".join(_fmt(tc) for tc in tool_calls) async def _run_agent_loop( @@ -217,15 +211,13 @@ class AgentLoop: "type": "function", "function": { "name": tc.name, - "arguments": json.dumps(tc.arguments, ensure_ascii=False), - }, + "arguments": json.dumps(tc.arguments, ensure_ascii=False) + } } for tc in response.tool_calls ] messages = self.context.add_assistant_message( - messages, - response.content, - tool_call_dicts, + messages, response.content, tool_call_dicts, reasoning_content=response.reasoning_content, ) @@ -243,13 +235,9 @@ class AgentLoop: # Give them one retry; don't forward the text to avoid duplicates. if not tools_used and not text_only_retried and final_content: text_only_retried = True - logger.debug( - "Interim text response (no tools used yet), retrying: {}", - final_content[:80], - ) + logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) messages = self.context.add_assistant_message( - messages, - response.content, + messages, response.content, reasoning_content=response.reasoning_content, ) final_content = None @@ -266,23 +254,24 @@ class AgentLoop: while self._running: try: - msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0) + msg = await asyncio.wait_for( + self.bus.consume_inbound(), + timeout=1.0 + ) try: response = await self._process_message(msg) if response: await self.bus.publish_outbound(response) except Exception as e: logger.error("Error processing message: {}", e) - await self.bus.publish_outbound( - OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=f"Sorry, I encountered an error: {str(e)}", - ) - ) + await self.bus.publish_outbound(OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content=f"Sorry, I encountered an error: {str(e)}" + )) except asyncio.TimeoutError: continue - + async def close_mcp(self) -> None: """Close MCP connections.""" if self._mcp_stack: @@ -298,13 +287,12 @@ class AgentLoop: logger.info("Agent loop stopping") def _get_consolidation_lock(self, session_key: str) -> asyncio.Lock: - """Return a per-session lock for memory consolidation writers.""" lock = self._consolidation_locks.get(session_key) if lock is None: lock = asyncio.Lock() self._consolidation_locks[session_key] = lock return lock - + async def _process_message( self, msg: InboundMessage, @@ -313,25 +301,25 @@ class AgentLoop: ) -> OutboundMessage | None: """ Process a single inbound message. - + Args: msg: The inbound message to process. session_key: Override session key (used by process_direct). on_progress: Optional callback for intermediate output (defaults to bus publish). - + Returns: The response message, or None if no response needed. """ # System messages route back via chat_id ("channel:chat_id") if msg.channel == "system": return await self._process_system_message(msg) - + preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) - + key = session_key or msg.session_key session = self.sessions.get_or_create(key) - + # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": @@ -348,24 +336,18 @@ class AgentLoop: return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, - content="Could not start a new session because memory archival failed. Please try again.", + content="Could not start a new session because memory archival failed. Please try again." ) session.clear() self.sessions.save(session) self.sessions.invalidate(session.key) - return OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content="New session started. Memory consolidation in progress.", - ) + return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, + content="New session started. Memory consolidation in progress.") if cmd == "/help": - return OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands", - ) - + return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, + content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") + if len(session.messages) > self.memory_window and session.key not in self._consolidating: self._consolidating.add(session.key) lock = self._get_consolidation_lock(session.key) @@ -376,12 +358,12 @@ class AgentLoop: await self._consolidate_memory(session) finally: self._consolidating.discard(session.key) - task = asyncio.current_task() - if task is not None: - self._consolidation_tasks.discard(task) + _task = asyncio.current_task() + if _task is not None: + self._consolidation_tasks.discard(_task) - task = asyncio.create_task(_consolidate_and_unlock()) - self._consolidation_tasks.add(task) + _task = asyncio.create_task(_consolidate_and_unlock()) + self._consolidation_tasks.add(_task) self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id")) initial_messages = self.context.build_messages( @@ -393,49 +375,42 @@ class AgentLoop: ) async def _bus_progress(content: str) -> None: - await self.bus.publish_outbound( - OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=content, - metadata=msg.metadata or {}, - ) - ) + await self.bus.publish_outbound(OutboundMessage( + channel=msg.channel, chat_id=msg.chat_id, content=content, + metadata=msg.metadata or {}, + )) final_content, tools_used = await self._run_agent_loop( - initial_messages, - on_progress=on_progress or _bus_progress, + initial_messages, on_progress=on_progress or _bus_progress, ) if final_content is None: final_content = "I've completed processing but have no response to give." - + preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) - + session.add_message("user", msg.content) - session.add_message( - "assistant", final_content, tools_used=tools_used if tools_used else None - ) + session.add_message("assistant", final_content, + tools_used=tools_used if tools_used else None) self.sessions.save(session) - + return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=final_content, - metadata=msg.metadata - or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) + metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) ) - + async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: """ Process a system message (e.g., subagent announce). - + The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ logger.info("Processing system message from {}", msg.sender_id) - + # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: parts = msg.chat_id.split(":", 1) @@ -445,7 +420,7 @@ class AgentLoop: # Fallback origin_channel = "cli" origin_chat_id = msg.chat_id - + session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) @@ -459,15 +434,17 @@ class AgentLoop: if final_content is None: final_content = "Background task completed." - + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") session.add_message("assistant", final_content) self.sessions.save(session) - + return OutboundMessage( - channel=origin_channel, chat_id=origin_chat_id, content=final_content + channel=origin_channel, + chat_id=origin_chat_id, + content=final_content ) - + async def _consolidate_memory(self, session, archive_all: bool = False) -> None: """Consolidate old messages into MEMORY.md + HISTORY.md. @@ -480,49 +457,29 @@ class AgentLoop: if archive_all: old_messages = session.messages keep_count = 0 - logger.info( - "Memory consolidation (archive_all): {} total messages archived", - len(session.messages), - ) + logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages)) else: keep_count = self.memory_window // 2 if len(session.messages) <= keep_count: - logger.debug( - "Session {}: No consolidation needed (messages={}, keep={})", - session.key, - len(session.messages), - keep_count, - ) + logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count) return messages_to_process = len(session.messages) - session.last_consolidated if messages_to_process <= 0: - logger.debug( - "Session {}: No new messages to consolidate (last_consolidated={}, total={})", - session.key, - session.last_consolidated, - len(session.messages), - ) + logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages)) return - old_messages = session.messages[session.last_consolidated : -keep_count] + old_messages = session.messages[session.last_consolidated:-keep_count] if not old_messages: return - logger.info( - "Memory consolidation started: {} total, {} new to consolidate, {} keep", - len(session.messages), - len(old_messages), - keep_count, - ) + logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count) lines = [] for m in old_messages: if not m.get("content"): continue tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else "" - lines.append( - f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}" - ) + lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}") conversation = "\n".join(lines) current_memory = memory.read_long_term() @@ -551,10 +508,7 @@ Respond with ONLY valid JSON, no markdown fences.""" try: response = await self.provider.chat( messages=[ - { - "role": "system", - "content": "You are a memory consolidation agent. Respond only with valid JSON.", - }, + {"role": "system", "content": "You are a memory consolidation agent. Respond only with valid JSON."}, {"role": "user", "content": prompt}, ], model=self.model, @@ -567,10 +521,7 @@ Respond with ONLY valid JSON, no markdown fences.""" text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip() result = json_repair.loads(text) if not isinstance(result, dict): - logger.warning( - "Memory consolidation: unexpected response type, skipping. Response: {}", - text[:200], - ) + logger.warning("Memory consolidation: unexpected response type, skipping. Response: {}", text[:200]) return if entry := result.get("history_entry"): @@ -589,11 +540,7 @@ Respond with ONLY valid JSON, no markdown fences.""" session.last_consolidated = 0 else: session.last_consolidated = len(session.messages) - keep_count - logger.info( - "Memory consolidation done: {} messages, last_consolidated={}", - len(session.messages), - session.last_consolidated, - ) + logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) except Exception as e: logger.error("Memory consolidation failed: {}", e) @@ -607,21 +554,24 @@ Respond with ONLY valid JSON, no markdown fences.""" ) -> str: """ Process a message directly (for CLI or cron usage). - + Args: content: The message content. session_key: Session identifier (overrides channel:chat_id for session lookup). channel: Source channel (for tool context routing). chat_id: Source chat ID (for tool context routing). on_progress: Optional callback for intermediate output. - + Returns: The agent's response. """ await self._connect_mcp() - msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content) - - response = await self._process_message( - msg, session_key=session_key, on_progress=on_progress + msg = InboundMessage( + channel=channel, + sender_id="user", + chat_id=chat_id, + content=content ) + + response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" From 9ada8e68547bae6daeb8e6e43b7c1babdb519724 Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Fri, 20 Feb 2026 12:48:54 +0100 Subject: [PATCH 038/154] fix(loop): require successful archival before /new clear --- nanobot/agent/loop.py | 230 +++++++++++++++++++------------ tests/test_consolidate_offset.py | 12 +- 2 files changed, 151 insertions(+), 91 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 481b72e..4ff01ea 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -56,6 +56,7 @@ class AgentLoop: ): from nanobot.config.schema import ExecToolConfig from nanobot.cron.service import CronService + self.bus = bus self.provider = provider self.workspace = workspace @@ -83,7 +84,7 @@ class AgentLoop: exec_config=self.exec_config, restrict_to_workspace=restrict_to_workspace, ) - + self._running = False self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None @@ -92,7 +93,7 @@ class AgentLoop: self._consolidation_tasks: set[asyncio.Task] = set() # Strong refs to in-flight tasks self._consolidation_locks: dict[str, asyncio.Lock] = {} self._register_default_tools() - + def _register_default_tools(self) -> None: """Register the default set of tools.""" # File tools (workspace for relative paths, restrict if configured) @@ -101,36 +102,39 @@ class AgentLoop: self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) - + # Shell tool - self.tools.register(ExecTool( - working_dir=str(self.workspace), - timeout=self.exec_config.timeout, - restrict_to_workspace=self.restrict_to_workspace, - )) - + self.tools.register( + ExecTool( + working_dir=str(self.workspace), + timeout=self.exec_config.timeout, + restrict_to_workspace=self.restrict_to_workspace, + ) + ) + # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - + # Message tool message_tool = MessageTool(send_callback=self.bus.publish_outbound) self.tools.register(message_tool) - + # Spawn tool (for subagents) spawn_tool = SpawnTool(manager=self.subagents) self.tools.register(spawn_tool) - + # Cron tool (for scheduling) if self.cron_service: self.tools.register(CronTool(self.cron_service)) - + async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: return self._mcp_connected = True from nanobot.agent.tools.mcp import connect_mcp_servers + self._mcp_stack = AsyncExitStack() await self._mcp_stack.__aenter__() await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) @@ -159,11 +163,13 @@ class AgentLoop: @staticmethod def _tool_hint(tool_calls: list) -> str: """Format tool calls as concise hint, e.g. 'web_search("query")'.""" + def _fmt(tc): val = next(iter(tc.arguments.values()), None) if tc.arguments else None if not isinstance(val, str): return tc.name return f'{tc.name}("{val[:40]}…")' if len(val) > 40 else f'{tc.name}("{val}")' + return ", ".join(_fmt(tc) for tc in tool_calls) async def _run_agent_loop( @@ -211,13 +217,15 @@ class AgentLoop: "type": "function", "function": { "name": tc.name, - "arguments": json.dumps(tc.arguments, ensure_ascii=False) - } + "arguments": json.dumps(tc.arguments, ensure_ascii=False), + }, } for tc in response.tool_calls ] messages = self.context.add_assistant_message( - messages, response.content, tool_call_dicts, + messages, + response.content, + tool_call_dicts, reasoning_content=response.reasoning_content, ) @@ -235,9 +243,13 @@ class AgentLoop: # Give them one retry; don't forward the text to avoid duplicates. if not tools_used and not text_only_retried and final_content: text_only_retried = True - logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) + logger.debug( + "Interim text response (no tools used yet), retrying: {}", + final_content[:80], + ) messages = self.context.add_assistant_message( - messages, response.content, + messages, + response.content, reasoning_content=response.reasoning_content, ) final_content = None @@ -254,24 +266,23 @@ class AgentLoop: while self._running: try: - msg = await asyncio.wait_for( - self.bus.consume_inbound(), - timeout=1.0 - ) + msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0) try: response = await self._process_message(msg) if response: await self.bus.publish_outbound(response) except Exception as e: logger.error("Error processing message: {}", e) - await self.bus.publish_outbound(OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=f"Sorry, I encountered an error: {str(e)}" - )) + await self.bus.publish_outbound( + OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content=f"Sorry, I encountered an error: {str(e)}", + ) + ) except asyncio.TimeoutError: continue - + async def close_mcp(self) -> None: """Close MCP connections.""" if self._mcp_stack: @@ -292,7 +303,7 @@ class AgentLoop: lock = asyncio.Lock() self._consolidation_locks[session_key] = lock return lock - + async def _process_message( self, msg: InboundMessage, @@ -301,25 +312,25 @@ class AgentLoop: ) -> OutboundMessage | None: """ Process a single inbound message. - + Args: msg: The inbound message to process. session_key: Override session key (used by process_direct). on_progress: Optional callback for intermediate output (defaults to bus publish). - + Returns: The response message, or None if no response needed. """ # System messages route back via chat_id ("channel:chat_id") if msg.channel == "system": return await self._process_system_message(msg) - + preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) - + key = session_key or msg.session_key session = self.sessions.get_or_create(key) - + # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": @@ -330,24 +341,37 @@ class AgentLoop: async with lock: temp_session = Session(key=session.key) temp_session.messages = messages_to_archive - await self._consolidate_memory(temp_session, archive_all=True) + archived = await self._consolidate_memory(temp_session, archive_all=True) except Exception as e: logger.error("/new archival failed for {}: {}", session.key, e) return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, - content="Could not start a new session because memory archival failed. Please try again." + content="Could not start a new session because memory archival failed. Please try again.", + ) + + if messages_to_archive and not archived: + return OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="Could not start a new session because memory archival failed. Please try again.", ) session.clear() self.sessions.save(session) self.sessions.invalidate(session.key) - return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, - content="New session started. Memory consolidation in progress.") + return OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="New session started. Memory consolidation in progress.", + ) if cmd == "/help": - return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, - content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") - + return OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands", + ) + if len(session.messages) > self.memory_window and session.key not in self._consolidating: self._consolidating.add(session.key) lock = self._get_consolidation_lock(session.key) @@ -375,42 +399,49 @@ class AgentLoop: ) async def _bus_progress(content: str) -> None: - await self.bus.publish_outbound(OutboundMessage( - channel=msg.channel, chat_id=msg.chat_id, content=content, - metadata=msg.metadata or {}, - )) + await self.bus.publish_outbound( + OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content=content, + metadata=msg.metadata or {}, + ) + ) final_content, tools_used = await self._run_agent_loop( - initial_messages, on_progress=on_progress or _bus_progress, + initial_messages, + on_progress=on_progress or _bus_progress, ) if final_content is None: final_content = "I've completed processing but have no response to give." - + preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) - + session.add_message("user", msg.content) - session.add_message("assistant", final_content, - tools_used=tools_used if tools_used else None) + session.add_message( + "assistant", final_content, tools_used=tools_used if tools_used else None + ) self.sessions.save(session) - + return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=final_content, - metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) + metadata=msg.metadata + or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) ) - + async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: """ Process a system message (e.g., subagent announce). - + The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ logger.info("Processing system message from {}", msg.sender_id) - + # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: parts = msg.chat_id.split(":", 1) @@ -420,7 +451,7 @@ class AgentLoop: # Fallback origin_channel = "cli" origin_chat_id = msg.chat_id - + session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) @@ -434,18 +465,16 @@ class AgentLoop: if final_content is None: final_content = "Background task completed." - + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") session.add_message("assistant", final_content) self.sessions.save(session) - + return OutboundMessage( - channel=origin_channel, - chat_id=origin_chat_id, - content=final_content + channel=origin_channel, chat_id=origin_chat_id, content=final_content ) - - async def _consolidate_memory(self, session, archive_all: bool = False) -> None: + + async def _consolidate_memory(self, session, archive_all: bool = False) -> bool: """Consolidate old messages into MEMORY.md + HISTORY.md. Args: @@ -457,29 +486,49 @@ class AgentLoop: if archive_all: old_messages = session.messages keep_count = 0 - logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages)) + logger.info( + "Memory consolidation (archive_all): {} total messages archived", + len(session.messages), + ) else: keep_count = self.memory_window // 2 if len(session.messages) <= keep_count: - logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count) - return + logger.debug( + "Session {}: No consolidation needed (messages={}, keep={})", + session.key, + len(session.messages), + keep_count, + ) + return True messages_to_process = len(session.messages) - session.last_consolidated if messages_to_process <= 0: - logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages)) - return + logger.debug( + "Session {}: No new messages to consolidate (last_consolidated={}, total={})", + session.key, + session.last_consolidated, + len(session.messages), + ) + return True - old_messages = session.messages[session.last_consolidated:-keep_count] + old_messages = session.messages[session.last_consolidated : -keep_count] if not old_messages: - return - logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count) + return True + logger.info( + "Memory consolidation started: {} total, {} new to consolidate, {} keep", + len(session.messages), + len(old_messages), + keep_count, + ) lines = [] for m in old_messages: if not m.get("content"): continue tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else "" - lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}") + lines.append( + f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}" + ) conversation = "\n".join(lines) current_memory = memory.read_long_term() @@ -508,7 +557,10 @@ Respond with ONLY valid JSON, no markdown fences.""" try: response = await self.provider.chat( messages=[ - {"role": "system", "content": "You are a memory consolidation agent. Respond only with valid JSON."}, + { + "role": "system", + "content": "You are a memory consolidation agent. Respond only with valid JSON.", + }, {"role": "user", "content": prompt}, ], model=self.model, @@ -516,13 +568,16 @@ Respond with ONLY valid JSON, no markdown fences.""" text = (response.content or "").strip() if not text: logger.warning("Memory consolidation: LLM returned empty response, skipping") - return + return False if text.startswith("```"): text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip() result = json_repair.loads(text) if not isinstance(result, dict): - logger.warning("Memory consolidation: unexpected response type, skipping. Response: {}", text[:200]) - return + logger.warning( + "Memory consolidation: unexpected response type, skipping. Response: {}", + text[:200], + ) + return False if entry := result.get("history_entry"): # Defensive: ensure entry is a string (LLM may return dict) @@ -540,9 +595,15 @@ Respond with ONLY valid JSON, no markdown fences.""" session.last_consolidated = 0 else: session.last_consolidated = len(session.messages) - keep_count - logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) + logger.info( + "Memory consolidation done: {} messages, last_consolidated={}", + len(session.messages), + session.last_consolidated, + ) + return True except Exception as e: logger.error("Memory consolidation failed: {}", e) + return False async def process_direct( self, @@ -554,24 +615,21 @@ Respond with ONLY valid JSON, no markdown fences.""" ) -> str: """ Process a message directly (for CLI or cron usage). - + Args: content: The message content. session_key: Session identifier (overrides channel:chat_id for session lookup). channel: Source channel (for tool context routing). chat_id: Source chat ID (for tool context routing). on_progress: Optional callback for intermediate output. - + Returns: The agent's response. """ await self._connect_mcp() - msg = InboundMessage( - channel=channel, - sender_id="user", - chat_id=chat_id, - content=content + msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content) + + response = await self._process_message( + msg, session_key=session_key, on_progress=on_progress ) - - response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" diff --git a/tests/test_consolidate_offset.py b/tests/test_consolidate_offset.py index 6162fa0..6be808d 100644 --- a/tests/test_consolidate_offset.py +++ b/tests/test_consolidate_offset.py @@ -652,13 +652,14 @@ class TestConsolidationDeduplicationGuard: release = asyncio.Event() archived_count = 0 - async def _fake_consolidate(sess, archive_all: bool = False) -> None: + async def _fake_consolidate(sess, archive_all: bool = False) -> bool: nonlocal archived_count if archive_all: archived_count = len(sess.messages) - return + return True started.set() await release.wait() + return True loop._consolidate_memory = _fake_consolidate # type: ignore[method-assign] @@ -683,7 +684,7 @@ class TestConsolidationDeduplicationGuard: @pytest.mark.asyncio async def test_new_does_not_clear_session_when_archive_fails(self, tmp_path: Path) -> None: - """/new keeps session data if archive step fails.""" + """/new must keep session data if archive step reports failure.""" from nanobot.agent.loop import AgentLoop from nanobot.bus.events import InboundMessage from nanobot.bus.queue import MessageBus @@ -706,9 +707,10 @@ class TestConsolidationDeduplicationGuard: loop.sessions.save(session) before_count = len(session.messages) - async def _failing_consolidate(_session, archive_all: bool = False) -> None: + async def _failing_consolidate(sess, archive_all: bool = False) -> bool: if archive_all: - raise RuntimeError("forced archive failure") + return False + return True loop._consolidate_memory = _failing_consolidate # type: ignore[method-assign] From ddae3e9d5f73ab9d95aa866d9894190d0f2200de Mon Sep 17 00:00:00 2001 From: Kim <150593189+KimGLee@users.noreply.github.com> Date: Thu, 19 Feb 2026 11:25:47 +0800 Subject: [PATCH 039/154] fix(agent): avoid duplicate final send when message tool already replied --- nanobot/agent/loop.py | 120 +++++++++++++++++++-------------- nanobot/agent/tools/message.py | 43 +++++++----- 2 files changed, 97 insertions(+), 66 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 3016d92..926fad9 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -1,30 +1,36 @@ """Agent loop: the core processing engine.""" -import asyncio -from contextlib import AsyncExitStack -import json -import json_repair -from pathlib import Path -import re -from typing import Any, Awaitable, Callable +from __future__ import annotations +import asyncio +import json +import re +from contextlib import AsyncExitStack +from pathlib import Path +from typing import TYPE_CHECKING, Awaitable, Callable + +import json_repair from loguru import logger +from nanobot.agent.context import ContextBuilder +from nanobot.agent.memory import MemoryStore +from nanobot.agent.subagent import SubagentManager +from nanobot.agent.tools.cron import CronTool +from nanobot.agent.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool +from nanobot.agent.tools.message import MessageTool +from nanobot.agent.tools.registry import ToolRegistry +from nanobot.agent.tools.shell import ExecTool +from nanobot.agent.tools.spawn import SpawnTool +from nanobot.agent.tools.web import WebFetchTool, WebSearchTool from nanobot.bus.events import InboundMessage, OutboundMessage from nanobot.bus.queue import MessageBus from nanobot.providers.base import LLMProvider -from nanobot.agent.context import ContextBuilder -from nanobot.agent.tools.registry import ToolRegistry -from nanobot.agent.tools.filesystem import ReadFileTool, WriteFileTool, EditFileTool, ListDirTool -from nanobot.agent.tools.shell import ExecTool -from nanobot.agent.tools.web import WebSearchTool, WebFetchTool -from nanobot.agent.tools.message import MessageTool -from nanobot.agent.tools.spawn import SpawnTool -from nanobot.agent.tools.cron import CronTool -from nanobot.agent.memory import MemoryStore -from nanobot.agent.subagent import SubagentManager from nanobot.session.manager import Session, SessionManager +if TYPE_CHECKING: + from nanobot.config.schema import ExecToolConfig + from nanobot.cron.service import CronService + class AgentLoop: """ @@ -49,14 +55,13 @@ class AgentLoop: max_tokens: int = 4096, memory_window: int = 50, brave_api_key: str | None = None, - exec_config: "ExecToolConfig | None" = None, - cron_service: "CronService | None" = None, + exec_config: ExecToolConfig | None = None, + cron_service: CronService | None = None, restrict_to_workspace: bool = False, session_manager: SessionManager | None = None, mcp_servers: dict | None = None, ): from nanobot.config.schema import ExecToolConfig - from nanobot.cron.service import CronService self.bus = bus self.provider = provider self.workspace = workspace @@ -84,14 +89,14 @@ class AgentLoop: exec_config=self.exec_config, restrict_to_workspace=restrict_to_workspace, ) - + self._running = False self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None self._mcp_connected = False self._consolidating: set[str] = set() # Session keys with consolidation in progress self._register_default_tools() - + def _register_default_tools(self) -> None: """Register the default set of tools.""" # File tools (workspace for relative paths, restrict if configured) @@ -100,30 +105,30 @@ class AgentLoop: self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) - + # Shell tool self.tools.register(ExecTool( working_dir=str(self.workspace), timeout=self.exec_config.timeout, restrict_to_workspace=self.restrict_to_workspace, )) - + # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - + # Message tool message_tool = MessageTool(send_callback=self.bus.publish_outbound) self.tools.register(message_tool) - + # Spawn tool (for subagents) spawn_tool = SpawnTool(manager=self.subagents) self.tools.register(spawn_tool) - + # Cron tool (for scheduling) if self.cron_service: self.tools.register(CronTool(self.cron_service)) - + async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: @@ -270,7 +275,7 @@ class AgentLoop: )) except asyncio.TimeoutError: continue - + async def close_mcp(self) -> None: """Close MCP connections.""" if self._mcp_stack: @@ -284,7 +289,7 @@ class AgentLoop: """Stop the agent loop.""" self._running = False logger.info("Agent loop stopping") - + async def _process_message( self, msg: InboundMessage, @@ -293,25 +298,25 @@ class AgentLoop: ) -> OutboundMessage | None: """ Process a single inbound message. - + Args: msg: The inbound message to process. session_key: Override session key (used by process_direct). on_progress: Optional callback for intermediate output (defaults to bus publish). - + Returns: The response message, or None if no response needed. """ # System messages route back via chat_id ("channel:chat_id") if msg.channel == "system": return await self._process_system_message(msg) - + preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) - + key = session_key or msg.session_key session = self.sessions.get_or_create(key) - + # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": @@ -332,7 +337,7 @@ class AgentLoop: if cmd == "/help": return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") - + if len(session.messages) > self.memory_window and session.key not in self._consolidating: self._consolidating.add(session.key) @@ -345,6 +350,10 @@ class AgentLoop: asyncio.create_task(_consolidate_and_unlock()) self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id")) + if message_tool := self.tools.get("message"): + if isinstance(message_tool, MessageTool): + message_tool.start_turn() + initial_messages = self.context.build_messages( history=session.get_history(max_messages=self.memory_window), current_message=msg.content, @@ -365,31 +374,44 @@ class AgentLoop: if final_content is None: final_content = "I've completed processing but have no response to give." - + preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) - + session.add_message("user", msg.content) session.add_message("assistant", final_content, tools_used=tools_used if tools_used else None) self.sessions.save(session) - + + suppress_final_reply = False + if message_tool := self.tools.get("message"): + if isinstance(message_tool, MessageTool): + sent_targets = set(message_tool.get_turn_sends()) + suppress_final_reply = (msg.channel, msg.chat_id) in sent_targets + + if suppress_final_reply: + logger.info( + "Skipping final auto-reply because message tool already sent to " + f"{msg.channel}:{msg.chat_id} in this turn" + ) + return None + return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=final_content, metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) ) - + async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: """ Process a system message (e.g., subagent announce). - + The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ logger.info("Processing system message from {}", msg.sender_id) - + # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: parts = msg.chat_id.split(":", 1) @@ -399,7 +421,7 @@ class AgentLoop: # Fallback origin_channel = "cli" origin_chat_id = msg.chat_id - + session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) @@ -413,17 +435,17 @@ class AgentLoop: if final_content is None: final_content = "Background task completed." - + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") session.add_message("assistant", final_content) self.sessions.save(session) - + return OutboundMessage( channel=origin_channel, chat_id=origin_chat_id, content=final_content ) - + async def _consolidate_memory(self, session, archive_all: bool = False) -> None: """Consolidate old messages into MEMORY.md + HISTORY.md. @@ -533,14 +555,14 @@ Respond with ONLY valid JSON, no markdown fences.""" ) -> str: """ Process a message directly (for CLI or cron usage). - + Args: content: The message content. session_key: Session identifier (overrides channel:chat_id for session lookup). channel: Source channel (for tool context routing). chat_id: Source chat ID (for tool context routing). on_progress: Optional callback for intermediate output. - + Returns: The agent's response. """ @@ -551,6 +573,6 @@ Respond with ONLY valid JSON, no markdown fences.""" chat_id=chat_id, content=content ) - + response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" diff --git a/nanobot/agent/tools/message.py b/nanobot/agent/tools/message.py index 10947c4..593bc44 100644 --- a/nanobot/agent/tools/message.py +++ b/nanobot/agent/tools/message.py @@ -1,6 +1,6 @@ """Message tool for sending messages to users.""" -from typing import Any, Callable, Awaitable +from typing import Any, Awaitable, Callable from nanobot.agent.tools.base import Tool from nanobot.bus.events import OutboundMessage @@ -8,37 +8,45 @@ from nanobot.bus.events import OutboundMessage class MessageTool(Tool): """Tool to send messages to users on chat channels.""" - + def __init__( - self, + self, send_callback: Callable[[OutboundMessage], Awaitable[None]] | None = None, default_channel: str = "", default_chat_id: str = "", - default_message_id: str | None = None + default_message_id: str | None = None, ): self._send_callback = send_callback self._default_channel = default_channel self._default_chat_id = default_chat_id self._default_message_id = default_message_id - + self._turn_sends: list[tuple[str, str]] = [] + def set_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None: """Set the current message context.""" self._default_channel = channel self._default_chat_id = chat_id self._default_message_id = message_id - def set_send_callback(self, callback: Callable[[OutboundMessage], Awaitable[None]]) -> None: """Set the callback for sending messages.""" self._send_callback = callback - + + def start_turn(self) -> None: + """Reset per-turn send tracking.""" + self._turn_sends.clear() + + def get_turn_sends(self) -> list[tuple[str, str]]: + """Get (channel, chat_id) targets sent in the current turn.""" + return list(self._turn_sends) + @property def name(self) -> str: return "message" - + @property def description(self) -> str: return "Send a message to the user. Use this when you want to communicate something." - + @property def parameters(self) -> dict[str, Any]: return { @@ -64,11 +72,11 @@ class MessageTool(Tool): }, "required": ["content"] } - + async def execute( - self, - content: str, - channel: str | None = None, + self, + content: str, + channel: str | None = None, chat_id: str | None = None, message_id: str | None = None, media: list[str] | None = None, @@ -77,13 +85,13 @@ class MessageTool(Tool): channel = channel or self._default_channel chat_id = chat_id or self._default_chat_id message_id = message_id or self._default_message_id - + if not channel or not chat_id: return "Error: No target channel/chat specified" - + if not self._send_callback: return "Error: Message sending not configured" - + msg = OutboundMessage( channel=channel, chat_id=chat_id, @@ -93,9 +101,10 @@ class MessageTool(Tool): "message_id": message_id, } ) - + try: await self._send_callback(msg) + self._turn_sends.append((channel, chat_id)) media_info = f" with {len(media)} attachments" if media else "" return f"Message sent to {channel}:{chat_id}{media_info}" except Exception as e: From 4eb07c44b982076f29331e2d41e1f6963cfc48db Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 09:21:27 -0300 Subject: [PATCH 040/154] fix: preserve interim content as fallback when retry produces empty response Fixes regression from #825 where models that respond with final text directly (no tools) had their answer discarded by the retry mechanism. Closes #878 --- nanobot/agent/loop.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 3016d92..d817815 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -185,6 +185,7 @@ class AgentLoop: final_content = None tools_used: list[str] = [] text_only_retried = False + interim_content: str | None = None # Fallback if retry produces nothing while iteration < self.max_iterations: iteration += 1 @@ -231,9 +232,11 @@ class AgentLoop: else: final_content = self._strip_think(response.content) # Some models send an interim text response before tool calls. - # Give them one retry; don't forward the text to avoid duplicates. + # Give them one retry; save the content as fallback in case + # the retry produces nothing useful (e.g. model already answered). if not tools_used and not text_only_retried and final_content: text_only_retried = True + interim_content = final_content logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) messages = self.context.add_assistant_message( messages, response.content, @@ -241,6 +244,9 @@ class AgentLoop: ) final_content = None continue + # Fall back to interim content if retry produced nothing + if not final_content and interim_content: + final_content = interim_content break return final_content, tools_used From 44f44b305a60ba27adf4ed8bdfb577412b6d9176 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 09:24:48 -0300 Subject: [PATCH 041/154] fix: move MCP connected flag after successful connection to allow retry The flag was set before the connection attempt, so if any MCP server was temporarily unavailable, the flag stayed True and MCP tools were permanently lost for the session. Closes #889 --- nanobot/agent/loop.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 3016d92..9078318 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -128,11 +128,20 @@ class AgentLoop: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: return - self._mcp_connected = True from nanobot.agent.tools.mcp import connect_mcp_servers - self._mcp_stack = AsyncExitStack() - await self._mcp_stack.__aenter__() - await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) + try: + self._mcp_stack = AsyncExitStack() + await self._mcp_stack.__aenter__() + await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) + self._mcp_connected = True + except Exception as e: + logger.error("Failed to connect MCP servers (will retry next message): {}", e) + if self._mcp_stack: + try: + await self._mcp_stack.aclose() + except Exception: + pass + self._mcp_stack = None def _set_tool_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None: """Update context for all tools that need routing info.""" From 8cc54b188d81504f39ea15cfd656b4b40af0eb8a Mon Sep 17 00:00:00 2001 From: Kim <150593189+KimGLee@users.noreply.github.com> Date: Fri, 20 Feb 2026 20:25:46 +0800 Subject: [PATCH 042/154] style(logging): use loguru parameterized formatting in suppression log --- nanobot/agent/loop.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 926fad9..646b658 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -391,8 +391,9 @@ class AgentLoop: if suppress_final_reply: logger.info( - "Skipping final auto-reply because message tool already sent to " - f"{msg.channel}:{msg.chat_id} in this turn" + "Skipping final auto-reply because message tool already sent to {}:{} in this turn", + msg.channel, + msg.chat_id, ) return None From c1b5e8c8d29a2225a1f82a36a93da5a0b61d702f Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Fri, 20 Feb 2026 13:29:18 +0100 Subject: [PATCH 043/154] fix(loop): lock /new snapshot and prune stale consolidation locks --- nanobot/agent/loop.py | 14 ++++- tests/test_consolidate_offset.py | 103 +++++++++++++++++++++++++++++++ 2 files changed, 115 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 4ff01ea..b0bace5 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -304,6 +304,14 @@ class AgentLoop: self._consolidation_locks[session_key] = lock return lock + def _prune_consolidation_lock(self, session_key: str, lock: asyncio.Lock) -> None: + """Drop unused per-session lock entries to avoid unbounded growth.""" + waiters = getattr(lock, "_waiters", None) + has_waiters = bool(waiters) + if lock.locked() or has_waiters: + return + self._consolidation_locks.pop(session_key, None) + async def _process_message( self, msg: InboundMessage, @@ -334,11 +342,11 @@ class AgentLoop: # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": - messages_to_archive = session.messages.copy() lock = self._get_consolidation_lock(session.key) - + messages_to_archive: list[dict[str, Any]] = [] try: async with lock: + messages_to_archive = session.messages[session.last_consolidated :].copy() temp_session = Session(key=session.key) temp_session.messages = messages_to_archive archived = await self._consolidate_memory(temp_session, archive_all=True) @@ -360,6 +368,7 @@ class AgentLoop: session.clear() self.sessions.save(session) self.sessions.invalidate(session.key) + self._prune_consolidation_lock(session.key, lock) return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, @@ -382,6 +391,7 @@ class AgentLoop: await self._consolidate_memory(session) finally: self._consolidating.discard(session.key) + self._prune_consolidation_lock(session.key, lock) _task = asyncio.current_task() if _task is not None: self._consolidation_tasks.discard(_task) diff --git a/tests/test_consolidate_offset.py b/tests/test_consolidate_offset.py index 6be808d..323519e 100644 --- a/tests/test_consolidate_offset.py +++ b/tests/test_consolidate_offset.py @@ -723,3 +723,106 @@ class TestConsolidationDeduplicationGuard: assert len(session_after.messages) == before_count, ( "Session must remain intact when /new archival fails" ) + + @pytest.mark.asyncio + async def test_new_archives_only_unconsolidated_messages_after_inflight_task( + self, tmp_path: Path + ) -> None: + """/new should archive only messages not yet consolidated by prior task.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(15): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + + started = asyncio.Event() + release = asyncio.Event() + archived_count = -1 + + async def _fake_consolidate(sess, archive_all: bool = False) -> bool: + nonlocal archived_count + if archive_all: + archived_count = len(sess.messages) + return True + + started.set() + await release.wait() + sess.last_consolidated = len(sess.messages) - 3 + return True + + loop._consolidate_memory = _fake_consolidate # type: ignore[method-assign] + + msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="hello") + await loop._process_message(msg) + await started.wait() + + new_msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/new") + pending_new = asyncio.create_task(loop._process_message(new_msg)) + await asyncio.sleep(0.02) + assert not pending_new.done() + + release.set() + response = await pending_new + + assert response is not None + assert "new session started" in response.content.lower() + assert archived_count == 3, ( + f"Expected only unconsolidated tail to archive, got {archived_count}" + ) + + @pytest.mark.asyncio + async def test_new_cleans_up_consolidation_lock_for_invalidated_session( + self, tmp_path: Path + ) -> None: + """/new should remove lock entry for fully invalidated session key.""" + from nanobot.agent.loop import AgentLoop + from nanobot.bus.events import InboundMessage + from nanobot.bus.queue import MessageBus + from nanobot.providers.base import LLMResponse + + bus = MessageBus() + provider = MagicMock() + provider.get_default_model.return_value = "test-model" + loop = AgentLoop( + bus=bus, provider=provider, workspace=tmp_path, model="test-model", memory_window=10 + ) + + loop.provider.chat = AsyncMock(return_value=LLMResponse(content="ok", tool_calls=[])) + loop.tools.get_definitions = MagicMock(return_value=[]) + + session = loop.sessions.get_or_create("cli:test") + for i in range(3): + session.add_message("user", f"msg{i}") + session.add_message("assistant", f"resp{i}") + loop.sessions.save(session) + + # Ensure lock exists before /new. + _ = loop._get_consolidation_lock(session.key) + assert session.key in loop._consolidation_locks + + async def _ok_consolidate(sess, archive_all: bool = False) -> bool: + return True + + loop._consolidate_memory = _ok_consolidate # type: ignore[method-assign] + + new_msg = InboundMessage(channel="cli", sender_id="user", chat_id="test", content="/new") + response = await loop._process_message(new_msg) + + assert response is not None + assert "new session started" in response.content.lower() + assert session.key not in loop._consolidation_locks From df022febaf4782270588431c0ba7c6b84f4b29c9 Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Fri, 20 Feb 2026 13:31:15 +0100 Subject: [PATCH 044/154] refactor(loop): drop redundant Any typing in /new snapshot --- nanobot/agent/loop.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index b0bace5..42ab351 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -6,7 +6,7 @@ import json import json_repair from pathlib import Path import re -from typing import Any, Awaitable, Callable +from typing import Awaitable, Callable from loguru import logger @@ -343,7 +343,7 @@ class AgentLoop: cmd = msg.content.strip().lower() if cmd == "/new": lock = self._get_consolidation_lock(session.key) - messages_to_archive: list[dict[str, Any]] = [] + messages_to_archive = [] try: async with lock: messages_to_archive = session.messages[session.last_consolidated :].copy() From 45f33853cf952b8642c104a5ecaa263a473f4963 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 09:37:42 -0300 Subject: [PATCH 045/154] fix: only apply interim fallback when no tools were used Addresses Codex review: if the model sent interim text then used tools, the interim text should not be used as fallback for the final response. --- nanobot/agent/loop.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index d817815..177302e 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -245,7 +245,8 @@ class AgentLoop: final_content = None continue # Fall back to interim content if retry produced nothing - if not final_content and interim_content: + # and no tools were used (if tools ran, interim was truly interim) + if not final_content and interim_content and not tools_used: final_content = interim_content break From 37222f9c0a118c449f0ef291c380916e3ad7ae62 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 09:38:22 -0300 Subject: [PATCH 046/154] fix: add connecting guard to prevent concurrent MCP connection attempts Addresses Codex review: concurrent callers could both pass the _mcp_connected guard and race through _connect_mcp(). Added _mcp_connecting flag set immediately to serialize attempts. --- nanobot/agent/loop.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 9078318..d14b6ea 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -89,6 +89,7 @@ class AgentLoop: self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None self._mcp_connected = False + self._mcp_connecting = False self._consolidating: set[str] = set() # Session keys with consolidation in progress self._register_default_tools() @@ -126,8 +127,9 @@ class AgentLoop: async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" - if self._mcp_connected or not self._mcp_servers: + if self._mcp_connected or self._mcp_connecting or not self._mcp_servers: return + self._mcp_connecting = True from nanobot.agent.tools.mcp import connect_mcp_servers try: self._mcp_stack = AsyncExitStack() @@ -142,6 +144,8 @@ class AgentLoop: except Exception: pass self._mcp_stack = None + finally: + self._mcp_connecting = False def _set_tool_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None: """Update context for all tools that need routing info.""" From 4c75e1673fb546a9da3e3730a91fb6fe0165e70b Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 09:55:22 -0300 Subject: [PATCH 047/154] fix: split Discord messages exceeding 2000-character limit Discord's API rejects messages longer than 2000 characters with HTTP 400. Previously, long agent responses were silently lost after retries exhausted. Adds _split_message() (matching Telegram's approach) to chunk content at line boundaries before sending. Only the first chunk carries the reply reference. Retry logic extracted to _send_payload() for reuse across chunks. Closes #898 --- nanobot/channels/discord.py | 74 ++++++++++++++++++++++++++----------- 1 file changed, 52 insertions(+), 22 deletions(-) diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.py index 8baecbf..c073a05 100644 --- a/nanobot/channels/discord.py +++ b/nanobot/channels/discord.py @@ -17,6 +17,27 @@ from nanobot.config.schema import DiscordConfig DISCORD_API_BASE = "https://discord.com/api/v10" MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB +MAX_MESSAGE_LEN = 2000 # Discord message character limit + + +def _split_message(content: str, max_len: int = MAX_MESSAGE_LEN) -> list[str]: + """Split content into chunks within max_len, preferring line breaks.""" + if len(content) <= max_len: + return [content] + chunks: list[str] = [] + while content: + if len(content) <= max_len: + chunks.append(content) + break + cut = content[:max_len] + pos = cut.rfind('\n') + if pos == -1: + pos = cut.rfind(' ') + if pos == -1: + pos = max_len + chunks.append(content[:pos]) + content = content[pos:].lstrip() + return chunks class DiscordChannel(BaseChannel): @@ -79,34 +100,43 @@ class DiscordChannel(BaseChannel): return url = f"{DISCORD_API_BASE}/channels/{msg.chat_id}/messages" - payload: dict[str, Any] = {"content": msg.content} - - if msg.reply_to: - payload["message_reference"] = {"message_id": msg.reply_to} - payload["allowed_mentions"] = {"replied_user": False} - headers = {"Authorization": f"Bot {self.config.token}"} try: - for attempt in range(3): - try: - response = await self._http.post(url, headers=headers, json=payload) - if response.status_code == 429: - data = response.json() - retry_after = float(data.get("retry_after", 1.0)) - logger.warning("Discord rate limited, retrying in {}s", retry_after) - await asyncio.sleep(retry_after) - continue - response.raise_for_status() - return - except Exception as e: - if attempt == 2: - logger.error("Error sending Discord message: {}", e) - else: - await asyncio.sleep(1) + chunks = _split_message(msg.content or "") + for i, chunk in enumerate(chunks): + payload: dict[str, Any] = {"content": chunk} + + # Only set reply reference on the first chunk + if i == 0 and msg.reply_to: + payload["message_reference"] = {"message_id": msg.reply_to} + payload["allowed_mentions"] = {"replied_user": False} + + await self._send_payload(url, headers, payload) finally: await self._stop_typing(msg.chat_id) + async def _send_payload( + self, url: str, headers: dict[str, str], payload: dict[str, Any] + ) -> None: + """Send a single Discord API payload with retry on rate-limit.""" + for attempt in range(3): + try: + response = await self._http.post(url, headers=headers, json=payload) + if response.status_code == 429: + data = response.json() + retry_after = float(data.get("retry_after", 1.0)) + logger.warning("Discord rate limited, retrying in {}s", retry_after) + await asyncio.sleep(retry_after) + continue + response.raise_for_status() + return + except Exception as e: + if attempt == 2: + logger.error("Error sending Discord message: {}", e) + else: + await asyncio.sleep(1) + async def _gateway_loop(self) -> None: """Main gateway loop: identify, heartbeat, dispatch events.""" if not self._ws: From 73530d51acc6229ac3c7020a4129f06813478b83 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 09:57:11 -0300 Subject: [PATCH 048/154] fix: store session key in JSONL metadata to avoid lossy filename reconstruction list_sessions() previously reconstructed the session key by replacing all underscores in the filename with colons. This is lossy: a key like 'cli:user_name' became 'cli:user:name' after round-tripping. Now the actual key is persisted in the metadata line during save() and read back in list_sessions(). Legacy files without the key field fall back to replacing only the first underscore, which handles the common channel:chat_id pattern correctly. Closes #899 --- nanobot/session/manager.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 9c1e427..35f8d13 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -154,6 +154,7 @@ class SessionManager: with open(path, "w", encoding="utf-8") as f: metadata_line = { "_type": "metadata", + "key": session.key, "created_at": session.created_at.isoformat(), "updated_at": session.updated_at.isoformat(), "metadata": session.metadata, @@ -186,8 +187,11 @@ class SessionManager: if first_line: data = json.loads(first_line) if data.get("_type") == "metadata": + # Prefer the key stored in metadata; fall back to + # filename-based heuristic for legacy files. + key = data.get("key") or path.stem.replace("_", ":", 1) sessions.append({ - "key": path.stem.replace("_", ":"), + "key": key, "created_at": data.get("created_at"), "updated_at": data.get("updated_at"), "path": str(path) From 426ef71ce7a87d0c104bbf34e63e2399166bf83e Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Fri, 20 Feb 2026 13:57:39 +0100 Subject: [PATCH 049/154] style(loop): drop formatting-only churn against upstream main --- nanobot/agent/loop.py | 209 ++++++++++++++++-------------------------- 1 file changed, 80 insertions(+), 129 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 42ab351..06ab1f7 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -6,7 +6,7 @@ import json import json_repair from pathlib import Path import re -from typing import Awaitable, Callable +from typing import Any, Awaitable, Callable from loguru import logger @@ -56,7 +56,6 @@ class AgentLoop: ): from nanobot.config.schema import ExecToolConfig from nanobot.cron.service import CronService - self.bus = bus self.provider = provider self.workspace = workspace @@ -84,7 +83,7 @@ class AgentLoop: exec_config=self.exec_config, restrict_to_workspace=restrict_to_workspace, ) - + self._running = False self._mcp_servers = mcp_servers or {} self._mcp_stack: AsyncExitStack | None = None @@ -93,7 +92,7 @@ class AgentLoop: self._consolidation_tasks: set[asyncio.Task] = set() # Strong refs to in-flight tasks self._consolidation_locks: dict[str, asyncio.Lock] = {} self._register_default_tools() - + def _register_default_tools(self) -> None: """Register the default set of tools.""" # File tools (workspace for relative paths, restrict if configured) @@ -102,39 +101,36 @@ class AgentLoop: self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) - + # Shell tool - self.tools.register( - ExecTool( - working_dir=str(self.workspace), - timeout=self.exec_config.timeout, - restrict_to_workspace=self.restrict_to_workspace, - ) - ) - + self.tools.register(ExecTool( + working_dir=str(self.workspace), + timeout=self.exec_config.timeout, + restrict_to_workspace=self.restrict_to_workspace, + )) + # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - + # Message tool message_tool = MessageTool(send_callback=self.bus.publish_outbound) self.tools.register(message_tool) - + # Spawn tool (for subagents) spawn_tool = SpawnTool(manager=self.subagents) self.tools.register(spawn_tool) - + # Cron tool (for scheduling) if self.cron_service: self.tools.register(CronTool(self.cron_service)) - + async def _connect_mcp(self) -> None: """Connect to configured MCP servers (one-time, lazy).""" if self._mcp_connected or not self._mcp_servers: return self._mcp_connected = True from nanobot.agent.tools.mcp import connect_mcp_servers - self._mcp_stack = AsyncExitStack() await self._mcp_stack.__aenter__() await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack) @@ -163,13 +159,11 @@ class AgentLoop: @staticmethod def _tool_hint(tool_calls: list) -> str: """Format tool calls as concise hint, e.g. 'web_search("query")'.""" - def _fmt(tc): val = next(iter(tc.arguments.values()), None) if tc.arguments else None if not isinstance(val, str): return tc.name return f'{tc.name}("{val[:40]}…")' if len(val) > 40 else f'{tc.name}("{val}")' - return ", ".join(_fmt(tc) for tc in tool_calls) async def _run_agent_loop( @@ -217,15 +211,13 @@ class AgentLoop: "type": "function", "function": { "name": tc.name, - "arguments": json.dumps(tc.arguments, ensure_ascii=False), - }, + "arguments": json.dumps(tc.arguments, ensure_ascii=False) + } } for tc in response.tool_calls ] messages = self.context.add_assistant_message( - messages, - response.content, - tool_call_dicts, + messages, response.content, tool_call_dicts, reasoning_content=response.reasoning_content, ) @@ -243,13 +235,9 @@ class AgentLoop: # Give them one retry; don't forward the text to avoid duplicates. if not tools_used and not text_only_retried and final_content: text_only_retried = True - logger.debug( - "Interim text response (no tools used yet), retrying: {}", - final_content[:80], - ) + logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) messages = self.context.add_assistant_message( - messages, - response.content, + messages, response.content, reasoning_content=response.reasoning_content, ) final_content = None @@ -266,23 +254,24 @@ class AgentLoop: while self._running: try: - msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0) + msg = await asyncio.wait_for( + self.bus.consume_inbound(), + timeout=1.0 + ) try: response = await self._process_message(msg) if response: await self.bus.publish_outbound(response) except Exception as e: logger.error("Error processing message: {}", e) - await self.bus.publish_outbound( - OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=f"Sorry, I encountered an error: {str(e)}", - ) - ) + await self.bus.publish_outbound(OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content=f"Sorry, I encountered an error: {str(e)}" + )) except asyncio.TimeoutError: continue - + async def close_mcp(self) -> None: """Close MCP connections.""" if self._mcp_stack: @@ -311,7 +300,7 @@ class AgentLoop: if lock.locked() or has_waiters: return self._consolidation_locks.pop(session_key, None) - + async def _process_message( self, msg: InboundMessage, @@ -320,30 +309,30 @@ class AgentLoop: ) -> OutboundMessage | None: """ Process a single inbound message. - + Args: msg: The inbound message to process. session_key: Override session key (used by process_direct). on_progress: Optional callback for intermediate output (defaults to bus publish). - + Returns: The response message, or None if no response needed. """ # System messages route back via chat_id ("channel:chat_id") if msg.channel == "system": return await self._process_system_message(msg) - + preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) - + key = session_key or msg.session_key session = self.sessions.get_or_create(key) - + # Handle slash commands cmd = msg.content.strip().lower() if cmd == "/new": lock = self._get_consolidation_lock(session.key) - messages_to_archive = [] + messages_to_archive: list[dict[str, Any]] = [] try: async with lock: messages_to_archive = session.messages[session.last_consolidated :].copy() @@ -369,18 +358,12 @@ class AgentLoop: self.sessions.save(session) self.sessions.invalidate(session.key) self._prune_consolidation_lock(session.key, lock) - return OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content="New session started. Memory consolidation in progress.", - ) + return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, + content="New session started. Memory consolidation in progress.") if cmd == "/help": - return OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands", - ) - + return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, + content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") + if len(session.messages) > self.memory_window and session.key not in self._consolidating: self._consolidating.add(session.key) lock = self._get_consolidation_lock(session.key) @@ -409,49 +392,42 @@ class AgentLoop: ) async def _bus_progress(content: str) -> None: - await self.bus.publish_outbound( - OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=content, - metadata=msg.metadata or {}, - ) - ) + await self.bus.publish_outbound(OutboundMessage( + channel=msg.channel, chat_id=msg.chat_id, content=content, + metadata=msg.metadata or {}, + )) final_content, tools_used = await self._run_agent_loop( - initial_messages, - on_progress=on_progress or _bus_progress, + initial_messages, on_progress=on_progress or _bus_progress, ) if final_content is None: final_content = "I've completed processing but have no response to give." - + preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) - + session.add_message("user", msg.content) - session.add_message( - "assistant", final_content, tools_used=tools_used if tools_used else None - ) + session.add_message("assistant", final_content, + tools_used=tools_used if tools_used else None) self.sessions.save(session) - + return OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=final_content, - metadata=msg.metadata - or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) + metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) ) - + async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: """ Process a system message (e.g., subagent announce). - + The chat_id field contains "original_channel:original_chat_id" to route the response back to the correct destination. """ logger.info("Processing system message from {}", msg.sender_id) - + # Parse origin from chat_id (format: "channel:chat_id") if ":" in msg.chat_id: parts = msg.chat_id.split(":", 1) @@ -461,7 +437,7 @@ class AgentLoop: # Fallback origin_channel = "cli" origin_chat_id = msg.chat_id - + session_key = f"{origin_channel}:{origin_chat_id}" session = self.sessions.get_or_create(session_key) self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) @@ -475,15 +451,17 @@ class AgentLoop: if final_content is None: final_content = "Background task completed." - + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") session.add_message("assistant", final_content) self.sessions.save(session) - + return OutboundMessage( - channel=origin_channel, chat_id=origin_chat_id, content=final_content + channel=origin_channel, + chat_id=origin_chat_id, + content=final_content ) - + async def _consolidate_memory(self, session, archive_all: bool = False) -> bool: """Consolidate old messages into MEMORY.md + HISTORY.md. @@ -496,49 +474,29 @@ class AgentLoop: if archive_all: old_messages = session.messages keep_count = 0 - logger.info( - "Memory consolidation (archive_all): {} total messages archived", - len(session.messages), - ) + logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages)) else: keep_count = self.memory_window // 2 if len(session.messages) <= keep_count: - logger.debug( - "Session {}: No consolidation needed (messages={}, keep={})", - session.key, - len(session.messages), - keep_count, - ) + logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count) return True messages_to_process = len(session.messages) - session.last_consolidated if messages_to_process <= 0: - logger.debug( - "Session {}: No new messages to consolidate (last_consolidated={}, total={})", - session.key, - session.last_consolidated, - len(session.messages), - ) + logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages)) return True - old_messages = session.messages[session.last_consolidated : -keep_count] + old_messages = session.messages[session.last_consolidated:-keep_count] if not old_messages: return True - logger.info( - "Memory consolidation started: {} total, {} new to consolidate, {} keep", - len(session.messages), - len(old_messages), - keep_count, - ) + logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count) lines = [] for m in old_messages: if not m.get("content"): continue tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else "" - lines.append( - f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}" - ) + lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}") conversation = "\n".join(lines) current_memory = memory.read_long_term() @@ -567,10 +525,7 @@ Respond with ONLY valid JSON, no markdown fences.""" try: response = await self.provider.chat( messages=[ - { - "role": "system", - "content": "You are a memory consolidation agent. Respond only with valid JSON.", - }, + {"role": "system", "content": "You are a memory consolidation agent. Respond only with valid JSON."}, {"role": "user", "content": prompt}, ], model=self.model, @@ -583,10 +538,7 @@ Respond with ONLY valid JSON, no markdown fences.""" text = text.split("\n", 1)[-1].rsplit("```", 1)[0].strip() result = json_repair.loads(text) if not isinstance(result, dict): - logger.warning( - "Memory consolidation: unexpected response type, skipping. Response: {}", - text[:200], - ) + logger.warning("Memory consolidation: unexpected response type, skipping. Response: {}", text[:200]) return False if entry := result.get("history_entry"): @@ -605,11 +557,7 @@ Respond with ONLY valid JSON, no markdown fences.""" session.last_consolidated = 0 else: session.last_consolidated = len(session.messages) - keep_count - logger.info( - "Memory consolidation done: {} messages, last_consolidated={}", - len(session.messages), - session.last_consolidated, - ) + logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) return True except Exception as e: logger.error("Memory consolidation failed: {}", e) @@ -625,21 +573,24 @@ Respond with ONLY valid JSON, no markdown fences.""" ) -> str: """ Process a message directly (for CLI or cron usage). - + Args: content: The message content. session_key: Session identifier (overrides channel:chat_id for session lookup). channel: Source channel (for tool context routing). chat_id: Source chat ID (for tool context routing). on_progress: Optional callback for intermediate output. - + Returns: The agent's response. """ await self._connect_mcp() - msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content) - - response = await self._process_message( - msg, session_key=session_key, on_progress=on_progress + msg = InboundMessage( + channel=channel, + sender_id="user", + chat_id=chat_id, + content=content ) + + response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" From f19baa8fc40f5a2a66c07d4e02847280dfbd55da Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 10:01:38 -0300 Subject: [PATCH 050/154] fix: convert remaining f-string logger calls to loguru native format Follow-up to #864. Three f-string logger calls in base.py and dingtalk.py were missed in the original sweep. These can cause KeyError if interpolated values contain curly braces, since loguru interprets them as format placeholders. --- nanobot/channels/base.py | 5 +++-- nanobot/channels/dingtalk.py | 6 ++++-- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/nanobot/channels/base.py b/nanobot/channels/base.py index 30fcd1a..3a5a785 100644 --- a/nanobot/channels/base.py +++ b/nanobot/channels/base.py @@ -105,8 +105,9 @@ class BaseChannel(ABC): """ if not self.is_allowed(sender_id): logger.warning( - f"Access denied for sender {sender_id} on channel {self.name}. " - f"Add them to allowFrom list in config to grant access." + "Access denied for sender {} on channel {}. " + "Add them to allowFrom list in config to grant access.", + sender_id, self.name, ) return diff --git a/nanobot/channels/dingtalk.py b/nanobot/channels/dingtalk.py index b7263b3..09c7714 100644 --- a/nanobot/channels/dingtalk.py +++ b/nanobot/channels/dingtalk.py @@ -58,7 +58,8 @@ class NanobotDingTalkHandler(CallbackHandler): if not content: logger.warning( - f"Received empty or unsupported message type: {chatbot_msg.message_type}" + "Received empty or unsupported message type: {}", + chatbot_msg.message_type, ) return AckMessage.STATUS_OK, "OK" @@ -126,7 +127,8 @@ class DingTalkChannel(BaseChannel): self._http = httpx.AsyncClient() logger.info( - f"Initializing DingTalk Stream Client with Client ID: {self.config.client_id}..." + "Initializing DingTalk Stream Client with Client ID: {}...", + self.config.client_id, ) credential = Credential(self.config.client_id, self.config.client_secret) self._client = DingTalkStreamClient(credential) From 4cbd8572504320f9ef54948db9d5fbbca7130e68 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Fri, 20 Feb 2026 10:09:04 -0300 Subject: [PATCH 051/154] fix: handle edge cases in message splitting and send failure - _split_message: return empty list for empty/None content instead of a list with one empty string (Discord rejects empty content) - _split_message: use pos <= 0 fallback to prevent empty chunks when content starts with a newline or space - _send_payload: return bool to indicate success/failure - send: abort remaining chunks when a chunk fails to send, preventing partial/corrupted message delivery --- nanobot/channels/discord.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.py index c073a05..5a1cf5c 100644 --- a/nanobot/channels/discord.py +++ b/nanobot/channels/discord.py @@ -22,6 +22,8 @@ MAX_MESSAGE_LEN = 2000 # Discord message character limit def _split_message(content: str, max_len: int = MAX_MESSAGE_LEN) -> list[str]: """Split content into chunks within max_len, preferring line breaks.""" + if not content: + return [] if len(content) <= max_len: return [content] chunks: list[str] = [] @@ -31,9 +33,9 @@ def _split_message(content: str, max_len: int = MAX_MESSAGE_LEN) -> list[str]: break cut = content[:max_len] pos = cut.rfind('\n') - if pos == -1: + if pos <= 0: pos = cut.rfind(' ') - if pos == -1: + if pos <= 0: pos = max_len chunks.append(content[:pos]) content = content[pos:].lstrip() @@ -104,6 +106,9 @@ class DiscordChannel(BaseChannel): try: chunks = _split_message(msg.content or "") + if not chunks: + return + for i, chunk in enumerate(chunks): payload: dict[str, Any] = {"content": chunk} @@ -112,14 +117,18 @@ class DiscordChannel(BaseChannel): payload["message_reference"] = {"message_id": msg.reply_to} payload["allowed_mentions"] = {"replied_user": False} - await self._send_payload(url, headers, payload) + if not await self._send_payload(url, headers, payload): + break # Abort remaining chunks on failure finally: await self._stop_typing(msg.chat_id) async def _send_payload( self, url: str, headers: dict[str, str], payload: dict[str, Any] - ) -> None: - """Send a single Discord API payload with retry on rate-limit.""" + ) -> bool: + """Send a single Discord API payload with retry on rate-limit. + + Returns True on success, False if all attempts failed. + """ for attempt in range(3): try: response = await self._http.post(url, headers=headers, json=payload) @@ -130,12 +139,13 @@ class DiscordChannel(BaseChannel): await asyncio.sleep(retry_after) continue response.raise_for_status() - return + return True except Exception as e: if attempt == 2: logger.error("Error sending Discord message: {}", e) else: await asyncio.sleep(1) + return False async def _gateway_loop(self) -> None: """Main gateway loop: identify, heartbeat, dispatch events.""" From b286457c854fd3d60228b680ec0dbc8d29286303 Mon Sep 17 00:00:00 2001 From: tercerapersona Date: Fri, 20 Feb 2026 11:34:50 -0300 Subject: [PATCH 052/154] add Openrouter prompt caching via cache_control --- nanobot/providers/registry.py | 1 + 1 file changed, 1 insertion(+) diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py index 445d977..ecf092f 100644 --- a/nanobot/providers/registry.py +++ b/nanobot/providers/registry.py @@ -100,6 +100,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = ( default_api_base="https://openrouter.ai/api/v1", strip_model_prefix=False, model_overrides=(), + supports_prompt_caching=True, ), # AiHubMix: global gateway, OpenAI-compatible interface. From cc04bc4dd1806f30e2f622a2628ddb40afc84fe7 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 15:14:45 +0000 Subject: [PATCH 053/154] fix: check gateway's supports_prompt_caching instead of always returning False --- nanobot/providers/litellm_provider.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index edeb5c6..58c9ac2 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -111,7 +111,7 @@ class LiteLLMProvider(LLMProvider): def _supports_cache_control(self, model: str) -> bool: """Return True when the provider supports cache_control on content blocks.""" if self._gateway is not None: - return False + return self._gateway.supports_prompt_caching spec = find_by_model(model) return spec is not None and spec.supports_prompt_caching From 6bcfbd9610687875c53ce65e64538e7200913591 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 15:19:18 +0000 Subject: [PATCH 054/154] style: remove redundant comments and use loguru native format --- nanobot/channels/slack.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index 26a3966..4fc1f41 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -86,7 +86,6 @@ class SlackChannel(BaseChannel): use_thread = thread_ts and channel_type != "im" thread_ts_param = thread_ts if use_thread else None - # Send text message if content is present if msg.content: await self._web_client.chat_postMessage( channel=msg.chat_id, @@ -94,7 +93,6 @@ class SlackChannel(BaseChannel): thread_ts=thread_ts_param, ) - # Upload media files if present for media_path in msg.media or []: try: await self._web_client.files_upload_v2( @@ -103,7 +101,7 @@ class SlackChannel(BaseChannel): thread_ts=thread_ts_param, ) except Exception as e: - logger.error(f"Failed to upload file {media_path}: {e}") + logger.error("Failed to upload file {}: {}", media_path, e) except Exception as e: logger.error("Error sending Slack message: {}", e) From b853222c8755bfb3405735b13bc2c1deae20d437 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 15:26:12 +0000 Subject: [PATCH 055/154] style: trim _send_payload docstring --- nanobot/channels/discord.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.py index 5a1cf5c..1d2d7a6 100644 --- a/nanobot/channels/discord.py +++ b/nanobot/channels/discord.py @@ -125,10 +125,7 @@ class DiscordChannel(BaseChannel): async def _send_payload( self, url: str, headers: dict[str, str], payload: dict[str, Any] ) -> bool: - """Send a single Discord API payload with retry on rate-limit. - - Returns True on success, False if all attempts failed. - """ + """Send a single Discord API payload with retry on rate-limit. Returns True on success.""" for attempt in range(3): try: response = await self._http.post(url, headers=headers, json=payload) From d9cc144575a5186b9ae6be8ff520d981f1f12fe5 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 15:42:24 +0000 Subject: [PATCH 056/154] style: remove redundant comment in list_sessions --- nanobot/session/manager.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 35f8d13..18e23b2 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -187,8 +187,6 @@ class SessionManager: if first_line: data = json.loads(first_line) if data.get("_type") == "metadata": - # Prefer the key stored in metadata; fall back to - # filename-based heuristic for legacy files. key = data.get("key") or path.stem.replace("_", ":", 1) sessions.append({ "key": key, From 132807a3fbbd851cfef2c21f469e32216aa18cb7 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 15:55:30 +0000 Subject: [PATCH 057/154] refactor: simplify message tool turn tracking to a single boolean flag --- nanobot/agent/loop.py | 14 ++------------ nanobot/agent/tools/message.py | 11 ++++------- 2 files changed, 6 insertions(+), 19 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 646b658..51d0bc0 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -383,19 +383,9 @@ class AgentLoop: tools_used=tools_used if tools_used else None) self.sessions.save(session) - suppress_final_reply = False if message_tool := self.tools.get("message"): - if isinstance(message_tool, MessageTool): - sent_targets = set(message_tool.get_turn_sends()) - suppress_final_reply = (msg.channel, msg.chat_id) in sent_targets - - if suppress_final_reply: - logger.info( - "Skipping final auto-reply because message tool already sent to {}:{} in this turn", - msg.channel, - msg.chat_id, - ) - return None + if isinstance(message_tool, MessageTool) and message_tool._sent_in_turn: + return None return OutboundMessage( channel=msg.channel, diff --git a/nanobot/agent/tools/message.py b/nanobot/agent/tools/message.py index 593bc44..40e76e3 100644 --- a/nanobot/agent/tools/message.py +++ b/nanobot/agent/tools/message.py @@ -20,24 +20,21 @@ class MessageTool(Tool): self._default_channel = default_channel self._default_chat_id = default_chat_id self._default_message_id = default_message_id - self._turn_sends: list[tuple[str, str]] = [] + self._sent_in_turn: bool = False def set_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None: """Set the current message context.""" self._default_channel = channel self._default_chat_id = chat_id self._default_message_id = message_id + def set_send_callback(self, callback: Callable[[OutboundMessage], Awaitable[None]]) -> None: """Set the callback for sending messages.""" self._send_callback = callback def start_turn(self) -> None: """Reset per-turn send tracking.""" - self._turn_sends.clear() - - def get_turn_sends(self) -> list[tuple[str, str]]: - """Get (channel, chat_id) targets sent in the current turn.""" - return list(self._turn_sends) + self._sent_in_turn = False @property def name(self) -> str: @@ -104,7 +101,7 @@ class MessageTool(Tool): try: await self._send_callback(msg) - self._turn_sends.append((channel, chat_id)) + self._sent_in_turn = True media_info = f" with {len(media)} attachments" if media else "" return f"Message sent to {channel}:{chat_id}{media_info}" except Exception as e: From 7279ff0167fbbdcd06f380b0c52e69371f95b73b Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 16:45:21 +0000 Subject: [PATCH 058/154] refactor: route CLI interactive mode through message bus for subagent support --- nanobot/agent/loop.py | 9 ++++-- nanobot/cli/commands.py | 62 +++++++++++++++++++++++++++++++++++------ 2 files changed, 60 insertions(+), 11 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index e5ed6e4..9f1e265 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -277,8 +277,9 @@ class AgentLoop: ) try: response = await self._process_message(msg) - if response: - await self.bus.publish_outbound(response) + await self.bus.publish_outbound(response or OutboundMessage( + channel=msg.channel, chat_id=msg.chat_id, content="", + )) except Exception as e: logger.error("Error processing message: {}", e) await self.bus.publish_outbound(OutboundMessage( @@ -376,9 +377,11 @@ class AgentLoop: ) async def _bus_progress(content: str) -> None: + meta = dict(msg.metadata or {}) + meta["_progress"] = True await self.bus.publish_outbound(OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=content, - metadata=msg.metadata or {}, + metadata=meta, )) final_content, tools_used = await self._run_agent_loop( diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index a135349..6155463 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -498,27 +498,58 @@ def agent( console.print(f" [dim]↳ {content}[/dim]") if message: - # Single message mode + # Single message mode β€” direct call, no bus needed async def run_once(): with _thinking_ctx(): response = await agent_loop.process_direct(message, session_id, on_progress=_cli_progress) _print_agent_response(response, render_markdown=markdown) await agent_loop.close_mcp() - + asyncio.run(run_once()) else: - # Interactive mode + # Interactive mode β€” route through bus like other channels + from nanobot.bus.events import InboundMessage _init_prompt_session() console.print(f"{__logo__} Interactive mode (type [bold]exit[/bold] or [bold]Ctrl+C[/bold] to quit)\n") + if ":" in session_id: + cli_channel, cli_chat_id = session_id.split(":", 1) + else: + cli_channel, cli_chat_id = "cli", session_id + def _exit_on_sigint(signum, frame): _restore_terminal() console.print("\nGoodbye!") os._exit(0) signal.signal(signal.SIGINT, _exit_on_sigint) - + async def run_interactive(): + bus_task = asyncio.create_task(agent_loop.run()) + turn_done = asyncio.Event() + turn_done.set() + turn_response: list[str] = [] + + async def _consume_outbound(): + while True: + try: + msg = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0) + if msg.metadata.get("_progress"): + console.print(f" [dim]↳ {msg.content}[/dim]") + elif not turn_done.is_set(): + if msg.content: + turn_response.append(msg.content) + turn_done.set() + elif msg.content: + console.print() + _print_agent_response(msg.content, render_markdown=markdown) + except asyncio.TimeoutError: + continue + except asyncio.CancelledError: + break + + outbound_task = asyncio.create_task(_consume_outbound()) + try: while True: try: @@ -532,10 +563,22 @@ def agent( _restore_terminal() console.print("\nGoodbye!") break - + + turn_done.clear() + turn_response.clear() + + await bus.publish_inbound(InboundMessage( + channel=cli_channel, + sender_id="user", + chat_id=cli_chat_id, + content=user_input, + )) + with _thinking_ctx(): - response = await agent_loop.process_direct(user_input, session_id, on_progress=_cli_progress) - _print_agent_response(response, render_markdown=markdown) + await turn_done.wait() + + if turn_response: + _print_agent_response(turn_response[0], render_markdown=markdown) except KeyboardInterrupt: _restore_terminal() console.print("\nGoodbye!") @@ -545,8 +588,11 @@ def agent( console.print("\nGoodbye!") break finally: + agent_loop.stop() + outbound_task.cancel() + await asyncio.gather(bus_task, outbound_task, return_exceptions=True) await agent_loop.close_mcp() - + asyncio.run(run_interactive()) From 9a31571b6dd9e5aec13df46aebdd13d65ccb99ad Mon Sep 17 00:00:00 2001 From: Re-bin Date: Fri, 20 Feb 2026 16:49:40 +0000 Subject: [PATCH 059/154] fix: don't append interim assistant message before retry to avoid prefill errors --- nanobot/agent/loop.py | 4 ---- 1 file changed, 4 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 9f1e265..4850f9c 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -253,10 +253,6 @@ class AgentLoop: if not tools_used and not text_only_retried and final_content: text_only_retried = True logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) - messages = self.context.add_assistant_message( - messages, response.content, - reasoning_content=response.reasoning_content, - ) final_content = None continue break From 33396a522aaf76d5da758666e63310e2a078894a Mon Sep 17 00:00:00 2001 From: themavik Date: Fri, 20 Feb 2026 23:52:40 -0500 Subject: [PATCH 060/154] fix(tools): provide detailed error messages in edit_file when old_text not found Uses difflib to find the best match and shows a helpful diff, making it easier to debug edit_file failures. Co-authored-by: Cursor --- nanobot/agent/tools/filesystem.py | 35 ++++++++++++++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index 419b088..d9ff265 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -150,7 +150,7 @@ class EditFileTool(Tool): content = file_path.read_text(encoding="utf-8") if old_text not in content: - return f"Error: old_text not found in file. Make sure it matches exactly." + return self._not_found_message(old_text, content, path) # Count occurrences count = content.count(old_text) @@ -166,6 +166,39 @@ class EditFileTool(Tool): except Exception as e: return f"Error editing file: {str(e)}" + @staticmethod + def _not_found_message(old_text: str, content: str, path: str) -> str: + """Build a helpful error when old_text is not found.""" + import difflib + + lines = content.splitlines(keepends=True) + old_lines = old_text.splitlines(keepends=True) + + best_ratio = 0.0 + best_start = 0 + window = len(old_lines) + + for i in range(max(1, len(lines) - window + 1)): + chunk = lines[i : i + window] + ratio = difflib.SequenceMatcher(None, old_lines, chunk).ratio() + if ratio > best_ratio: + best_ratio = ratio + best_start = i + + if best_ratio > 0.5: + best_chunk = lines[best_start : best_start + window] + diff = difflib.unified_diff( + old_lines, best_chunk, + fromfile="old_text (provided)", tofile=f"{path} (actual, line {best_start + 1})", + lineterm="", + ) + diff_str = "\n".join(diff) + return ( + f"Error: old_text not found in {path}.\n" + f"Best match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff_str}" + ) + return f"Error: old_text not found in {path}. No similar text found. Verify the file content." + class ListDirTool(Tool): """Tool to list directory contents.""" From 98ef57e3704860c54b86f6e8ae0d742c646883aa Mon Sep 17 00:00:00 2001 From: coldxiangyu Date: Sat, 21 Feb 2026 12:56:57 +0800 Subject: [PATCH 061/154] feat(feishu): add multimedia download support for images, audio and files Add download functionality for multimedia messages in Feishu channel, enabling agents to process images, audio recordings, and file attachments sent through Feishu. Co-Authored-By: Claude Opus 4.6 --- nanobot/channels/feishu.py | 143 ++++++++++++++++++++++++++++++------- 1 file changed, 117 insertions(+), 26 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index a8ca1fa..a948d84 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -27,6 +27,8 @@ try: CreateMessageReactionRequest, CreateMessageReactionRequestBody, Emoji, + GetFileRequest, + GetImageRequest, P2ImMessageReceiveV1, ) FEISHU_AVAILABLE = True @@ -345,6 +347,80 @@ class FeishuChannel(BaseChannel): logger.error("Error uploading file {}: {}", file_path, e) return None + def _download_image_sync(self, image_key: str) -> tuple[bytes | None, str | None]: + """Download an image from Feishu by image_key.""" + try: + request = GetImageRequest.builder().image_key(image_key).build() + response = self._client.im.v1.image.get(request) + if response.success(): + return response.file, response.file_name + else: + logger.error("Failed to download image: code={}, msg={}", response.code, response.msg) + return None, None + except Exception as e: + logger.error("Error downloading image {}: {}", image_key, e) + return None, None + + def _download_file_sync(self, file_key: str) -> tuple[bytes | None, str | None]: + """Download a file from Feishu by file_key.""" + try: + request = GetFileRequest.builder().file_key(file_key).build() + response = self._client.im.v1.file.get(request) + if response.success(): + return response.file, response.file_name + else: + logger.error("Failed to download file: code={}, msg={}", response.code, response.msg) + return None, None + except Exception as e: + logger.error("Error downloading file {}: {}", file_key, e) + return None, None + + async def _download_and_save_media( + self, + msg_type: str, + content_json: dict + ) -> tuple[str | None, str]: + """ + Download media from Feishu and save to local disk. + + Returns: + (file_path, content_text) - file_path is None if download failed + """ + from pathlib import Path + + loop = asyncio.get_running_loop() + media_dir = Path.home() / ".nanobot" / "media" + media_dir.mkdir(parents=True, exist_ok=True) + + data, filename = None, None + + if msg_type == "image": + image_key = content_json.get("image_key") + if image_key: + data, filename = await loop.run_in_executor( + None, self._download_image_sync, image_key + ) + if not filename: + filename = f"{image_key[:16]}.jpg" + + elif msg_type in ("audio", "file"): + file_key = content_json.get("file_key") + if file_key: + data, filename = await loop.run_in_executor( + None, self._download_file_sync, file_key + ) + if not filename: + ext = ".opus" if msg_type == "audio" else "" + filename = f"{file_key[:16]}{ext}" + + if data and filename: + file_path = media_dir / filename + file_path.write_bytes(data) + logger.debug("Downloaded {} to {}", msg_type, file_path) + return str(file_path), f"[{msg_type}: {filename}]" + + return None, f"[{msg_type}: download failed]" + def _send_message_sync(self, receive_id_type: str, receive_id: str, msg_type: str, content: str) -> bool: """Send a single message (text/image/file/interactive) synchronously.""" try: @@ -425,60 +501,75 @@ class FeishuChannel(BaseChannel): event = data.event message = event.message sender = event.sender - + # Deduplication check message_id = message.message_id if message_id in self._processed_message_ids: return self._processed_message_ids[message_id] = None - - # Trim cache: keep most recent 500 when exceeds 1000 + + # Trim cache while len(self._processed_message_ids) > 1000: self._processed_message_ids.popitem(last=False) - + # Skip bot messages - sender_type = sender.sender_type - if sender_type == "bot": + if sender.sender_type == "bot": return - + sender_id = sender.sender_id.open_id if sender.sender_id else "unknown" chat_id = message.chat_id - chat_type = message.chat_type # "p2p" or "group" + chat_type = message.chat_type msg_type = message.message_type - - # Add reaction to indicate "seen" + + # Add reaction await self._add_reaction(message_id, "THUMBSUP") - - # Parse message content + + # Parse content + content_parts = [] + media_paths = [] + + try: + content_json = json.loads(message.content) if message.content else {} + except json.JSONDecodeError: + content_json = {} + if msg_type == "text": - try: - content = json.loads(message.content).get("text", "") - except json.JSONDecodeError: - content = message.content or "" + text = content_json.get("text", "") + if text: + content_parts.append(text) + elif msg_type == "post": - try: - content_json = json.loads(message.content) - content = _extract_post_text(content_json) - except (json.JSONDecodeError, TypeError): - content = message.content or "" + text = _extract_post_text(content_json) + if text: + content_parts.append(text) + + elif msg_type in ("image", "audio", "file"): + file_path, content_text = await self._download_and_save_media(msg_type, content_json) + if file_path: + media_paths.append(file_path) + content_parts.append(content_text) + else: - content = MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]") - - if not content: + content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]")) + + content = "\n".join(content_parts) if content_parts else "" + + if not content and not media_paths: return - + # Forward to message bus reply_to = chat_id if chat_type == "group" else sender_id await self._handle_message( sender_id=sender_id, chat_id=reply_to, content=content, + media=media_paths, metadata={ "message_id": message_id, "chat_type": chat_type, "msg_type": msg_type, } ) - + except Exception as e: logger.error("Error processing Feishu message: {}", e) From b9c3f8a5a3520fe4815f8baf1aea2f095295b3f8 Mon Sep 17 00:00:00 2001 From: coldxiangyu Date: Sat, 21 Feb 2026 14:08:25 +0800 Subject: [PATCH 062/154] feat(feishu): add share card and interactive message parsing - Add content extraction for share cards (chat, user, calendar event) - Add recursive parsing for interactive card elements - Fix image download API to use GetMessageResourceRequest with message_id - Handle BytesIO response from message resource API Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com> --- nanobot/channels/feishu.py | 211 +++++++++++++++++++++++++++++++++++-- 1 file changed, 201 insertions(+), 10 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index a948d84..7e1d50a 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -28,7 +28,7 @@ try: CreateMessageReactionRequestBody, Emoji, GetFileRequest, - GetImageRequest, + GetMessageResourceRequest, P2ImMessageReceiveV1, ) FEISHU_AVAILABLE = True @@ -46,6 +46,182 @@ MSG_TYPE_MAP = { } +def _extract_share_card_content(content_json: dict, msg_type: str) -> str: + """Extract content from share cards and interactive messages. + + Handles: + - share_chat: Group share card + - share_user: User share card + - interactive: Interactive card (may contain links from external shares) + - share_calendar_event: Calendar event share + - system: System messages + """ + parts = [] + + if msg_type == "share_chat": + # Group share: {"chat_id": "oc_xxx"} + chat_id = content_json.get("chat_id", "") + parts.append(f"[εˆ†δΊ«ηΎ€θŠ: {chat_id}]") + + elif msg_type == "share_user": + # User share: {"user_id": "ou_xxx"} + user_id = content_json.get("user_id", "") + parts.append(f"[εˆ†δΊ«η”¨ζˆ·: {user_id}]") + + elif msg_type == "interactive": + # Interactive card - extract text and links recursively + parts.extend(_extract_interactive_content(content_json)) + + elif msg_type == "share_calendar_event": + # Calendar event share + event_key = content_json.get("event_key", "") + parts.append(f"[εˆ†δΊ«ζ—₯程: {event_key}]") + + elif msg_type == "system": + # System message + parts.append("[系统梈息]") + + elif msg_type == "merge_forward": + # Merged forward messages + parts.append("[εˆεΉΆθ½¬ε‘ζΆˆζ―]") + + return "\n".join(parts) if parts else f"[{msg_type}]" + + +def _extract_interactive_content(content: dict) -> list[str]: + """Recursively extract text and links from interactive card content.""" + parts = [] + + if isinstance(content, str): + # Try to parse as JSON + try: + content = json.loads(content) + except (json.JSONDecodeError, TypeError): + return [content] if content.strip() else [] + + if not isinstance(content, dict): + return parts + + # Extract title + if "title" in content: + title = content["title"] + if isinstance(title, dict): + title_content = title.get("content", "") or title.get("text", "") + if title_content: + parts.append(f"ζ ‡ι’˜: {title_content}") + elif isinstance(title, str): + parts.append(f"ζ ‡ι’˜: {title}") + + # Extract from elements array + elements = content.get("elements", []) + if isinstance(elements, list): + for element in elements: + parts.extend(_extract_element_content(element)) + + # Extract from card config + card = content.get("card", {}) + if card: + parts.extend(_extract_interactive_content(card)) + + # Extract header + header = content.get("header", {}) + if header: + header_title = header.get("title", {}) + if isinstance(header_title, dict): + header_text = header_title.get("content", "") or header_title.get("text", "") + if header_text: + parts.append(f"ζ ‡ι’˜: {header_text}") + + return parts + + +def _extract_element_content(element: dict) -> list[str]: + """Extract content from a single card element.""" + parts = [] + + if not isinstance(element, dict): + return parts + + tag = element.get("tag", "") + + # Markdown element + if tag == "markdown" or tag == "lark_md": + content = element.get("content", "") + if content: + parts.append(content) + + # Div element + elif tag == "div": + text = element.get("text", {}) + if isinstance(text, dict): + text_content = text.get("content", "") or text.get("text", "") + if text_content: + parts.append(text_content) + elif isinstance(text, str): + parts.append(text) + # Check for extra fields + fields = element.get("fields", []) + for field in fields: + if isinstance(field, dict): + field_text = field.get("text", {}) + if isinstance(field_text, dict): + parts.append(field_text.get("content", "")) + + # Link/URL element + elif tag == "a": + href = element.get("href", "") + text = element.get("text", "") + if href: + parts.append(f"ι“ΎζŽ₯: {href}") + if text: + parts.append(text) + + # Button element (may contain URL) + elif tag == "button": + text = element.get("text", {}) + if isinstance(text, dict): + parts.append(text.get("content", "")) + url = element.get("url", "") or element.get("multi_url", {}).get("url", "") + if url: + parts.append(f"ι“ΎζŽ₯: {url}") + + # Image element + elif tag == "img": + alt = element.get("alt", {}) + if isinstance(alt, dict): + parts.append(alt.get("content", "[图片]")) + else: + parts.append("[图片]") + + # Note element + elif tag == "note": + note_elements = element.get("elements", []) + for ne in note_elements: + parts.extend(_extract_element_content(ne)) + + # Column set + elif tag == "column_set": + columns = element.get("columns", []) + for col in columns: + col_elements = col.get("elements", []) + for ce in col_elements: + parts.extend(_extract_element_content(ce)) + + # Plain text + elif tag == "plain_text": + content = element.get("content", "") + if content: + parts.append(content) + + # Recursively check nested elements + nested = element.get("elements", []) + if isinstance(nested, list): + for ne in nested: + parts.extend(_extract_element_content(ne)) + + return parts + + def _extract_post_text(content_json: dict) -> str: """Extract plain text from Feishu post (rich text) message content. @@ -347,13 +523,21 @@ class FeishuChannel(BaseChannel): logger.error("Error uploading file {}: {}", file_path, e) return None - def _download_image_sync(self, image_key: str) -> tuple[bytes | None, str | None]: - """Download an image from Feishu by image_key.""" + def _download_image_sync(self, message_id: str, image_key: str) -> tuple[bytes | None, str | None]: + """Download an image from Feishu message by message_id and image_key.""" try: - request = GetImageRequest.builder().image_key(image_key).build() - response = self._client.im.v1.image.get(request) + request = GetMessageResourceRequest.builder() \ + .message_id(message_id) \ + .file_key(image_key) \ + .type("image") \ + .build() + response = self._client.im.v1.message_resource.get(request) if response.success(): - return response.file, response.file_name + file_data = response.file + # GetMessageResourceRequest returns BytesIO, need to read bytes + if hasattr(file_data, 'read'): + file_data = file_data.read() + return file_data, response.file_name else: logger.error("Failed to download image: code={}, msg={}", response.code, response.msg) return None, None @@ -378,7 +562,8 @@ class FeishuChannel(BaseChannel): async def _download_and_save_media( self, msg_type: str, - content_json: dict + content_json: dict, + message_id: str | None = None ) -> tuple[str | None, str]: """ Download media from Feishu and save to local disk. @@ -396,9 +581,9 @@ class FeishuChannel(BaseChannel): if msg_type == "image": image_key = content_json.get("image_key") - if image_key: + if image_key and message_id: data, filename = await loop.run_in_executor( - None, self._download_image_sync, image_key + None, self._download_image_sync, message_id, image_key ) if not filename: filename = f"{image_key[:16]}.jpg" @@ -544,11 +729,17 @@ class FeishuChannel(BaseChannel): content_parts.append(text) elif msg_type in ("image", "audio", "file"): - file_path, content_text = await self._download_and_save_media(msg_type, content_json) + file_path, content_text = await self._download_and_save_media(msg_type, content_json, message_id) if file_path: media_paths.append(file_path) content_parts.append(content_text) + elif msg_type in ("share_chat", "share_user", "interactive", "share_calendar_event", "system", "merge_forward"): + # Handle share cards and interactive messages + text = _extract_share_card_content(content_json, msg_type) + if text: + content_parts.append(text) + else: content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]")) From 8125d9b6bcf39a2d92f13833aa53be45ed3a9330 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 06:30:26 +0000 Subject: [PATCH 063/154] fix(feishu): fix double recursion, English placeholders, top-level Path import --- nanobot/channels/feishu.py | 130 ++++++++++++------------------------- 1 file changed, 43 insertions(+), 87 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index 7e1d50a..815d853 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -6,6 +6,7 @@ import os import re import threading from collections import OrderedDict +from pathlib import Path from typing import Any from loguru import logger @@ -47,44 +48,22 @@ MSG_TYPE_MAP = { def _extract_share_card_content(content_json: dict, msg_type: str) -> str: - """Extract content from share cards and interactive messages. - - Handles: - - share_chat: Group share card - - share_user: User share card - - interactive: Interactive card (may contain links from external shares) - - share_calendar_event: Calendar event share - - system: System messages - """ + """Extract text representation from share cards and interactive messages.""" parts = [] - + if msg_type == "share_chat": - # Group share: {"chat_id": "oc_xxx"} - chat_id = content_json.get("chat_id", "") - parts.append(f"[εˆ†δΊ«ηΎ€θŠ: {chat_id}]") - + parts.append(f"[shared chat: {content_json.get('chat_id', '')}]") elif msg_type == "share_user": - # User share: {"user_id": "ou_xxx"} - user_id = content_json.get("user_id", "") - parts.append(f"[εˆ†δΊ«η”¨ζˆ·: {user_id}]") - + parts.append(f"[shared user: {content_json.get('user_id', '')}]") elif msg_type == "interactive": - # Interactive card - extract text and links recursively parts.extend(_extract_interactive_content(content_json)) - elif msg_type == "share_calendar_event": - # Calendar event share - event_key = content_json.get("event_key", "") - parts.append(f"[εˆ†δΊ«ζ—₯程: {event_key}]") - + parts.append(f"[shared calendar event: {content_json.get('event_key', '')}]") elif msg_type == "system": - # System message - parts.append("[系统梈息]") - + parts.append("[system message]") elif msg_type == "merge_forward": - # Merged forward messages - parts.append("[εˆεΉΆθ½¬ε‘ζΆˆζ―]") - + parts.append("[merged forward messages]") + return "\n".join(parts) if parts else f"[{msg_type}]" @@ -93,44 +72,37 @@ def _extract_interactive_content(content: dict) -> list[str]: parts = [] if isinstance(content, str): - # Try to parse as JSON try: content = json.loads(content) except (json.JSONDecodeError, TypeError): return [content] if content.strip() else [] - + if not isinstance(content, dict): return parts - - # Extract title + if "title" in content: title = content["title"] if isinstance(title, dict): title_content = title.get("content", "") or title.get("text", "") if title_content: - parts.append(f"ζ ‡ι’˜: {title_content}") + parts.append(f"title: {title_content}") elif isinstance(title, str): - parts.append(f"ζ ‡ι’˜: {title}") - - # Extract from elements array - elements = content.get("elements", []) - if isinstance(elements, list): - for element in elements: - parts.extend(_extract_element_content(element)) - - # Extract from card config + parts.append(f"title: {title}") + + for element in content.get("elements", []) if isinstance(content.get("elements"), list) else []: + parts.extend(_extract_element_content(element)) + card = content.get("card", {}) if card: parts.extend(_extract_interactive_content(card)) - - # Extract header + header = content.get("header", {}) if header: header_title = header.get("title", {}) if isinstance(header_title, dict): header_text = header_title.get("content", "") or header_title.get("text", "") if header_text: - parts.append(f"ζ ‡ι’˜: {header_text}") + parts.append(f"title: {header_text}") return parts @@ -144,13 +116,11 @@ def _extract_element_content(element: dict) -> list[str]: tag = element.get("tag", "") - # Markdown element - if tag == "markdown" or tag == "lark_md": + if tag in ("markdown", "lark_md"): content = element.get("content", "") if content: parts.append(content) - - # Div element + elif tag == "div": text = element.get("text", {}) if isinstance(text, dict): @@ -159,64 +129,52 @@ def _extract_element_content(element: dict) -> list[str]: parts.append(text_content) elif isinstance(text, str): parts.append(text) - # Check for extra fields - fields = element.get("fields", []) - for field in fields: + for field in element.get("fields", []): if isinstance(field, dict): field_text = field.get("text", {}) if isinstance(field_text, dict): - parts.append(field_text.get("content", "")) - - # Link/URL element + c = field_text.get("content", "") + if c: + parts.append(c) + elif tag == "a": href = element.get("href", "") text = element.get("text", "") if href: - parts.append(f"ι“ΎζŽ₯: {href}") + parts.append(f"link: {href}") if text: parts.append(text) - - # Button element (may contain URL) + elif tag == "button": text = element.get("text", {}) if isinstance(text, dict): - parts.append(text.get("content", "")) + c = text.get("content", "") + if c: + parts.append(c) url = element.get("url", "") or element.get("multi_url", {}).get("url", "") if url: - parts.append(f"ι“ΎζŽ₯: {url}") - - # Image element + parts.append(f"link: {url}") + elif tag == "img": alt = element.get("alt", {}) - if isinstance(alt, dict): - parts.append(alt.get("content", "[图片]")) - else: - parts.append("[图片]") - - # Note element + parts.append(alt.get("content", "[image]") if isinstance(alt, dict) else "[image]") + elif tag == "note": - note_elements = element.get("elements", []) - for ne in note_elements: + for ne in element.get("elements", []): parts.extend(_extract_element_content(ne)) - - # Column set + elif tag == "column_set": - columns = element.get("columns", []) - for col in columns: - col_elements = col.get("elements", []) - for ce in col_elements: + for col in element.get("columns", []): + for ce in col.get("elements", []): parts.extend(_extract_element_content(ce)) - - # Plain text + elif tag == "plain_text": content = element.get("content", "") if content: parts.append(content) - - # Recursively check nested elements - nested = element.get("elements", []) - if isinstance(nested, list): - for ne in nested: + + else: + for ne in element.get("elements", []): parts.extend(_extract_element_content(ne)) return parts @@ -571,8 +529,6 @@ class FeishuChannel(BaseChannel): Returns: (file_path, content_text) - file_path is None if download failed """ - from pathlib import Path - loop = asyncio.get_running_loop() media_dir = Path.home() / ".nanobot" / "media" media_dir.mkdir(parents=True, exist_ok=True) From e0edb904bd337cf5a3aaf675f39627d022043377 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 06:35:10 +0000 Subject: [PATCH 064/154] style(filesystem): move difflib import to top level --- nanobot/agent/tools/filesystem.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index d9ff265..e6c407e 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -1,5 +1,6 @@ """File system tools: read, write, edit.""" +import difflib from pathlib import Path from typing import Any @@ -169,8 +170,6 @@ class EditFileTool(Tool): @staticmethod def _not_found_message(old_text: str, content: str, path: str) -> str: """Build a helpful error when old_text is not found.""" - import difflib - lines = content.splitlines(keepends=True) old_lines = old_text.splitlines(keepends=True) From 4f5cb7d1e421a593cc54d9d1d0aab34870c12a35 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 06:39:04 +0000 Subject: [PATCH 065/154] style(filesystem): simplify best-match loop --- nanobot/agent/tools/filesystem.py | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index e6c407e..9c169e4 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -172,30 +172,21 @@ class EditFileTool(Tool): """Build a helpful error when old_text is not found.""" lines = content.splitlines(keepends=True) old_lines = old_text.splitlines(keepends=True) - - best_ratio = 0.0 - best_start = 0 window = len(old_lines) + best_ratio, best_start = 0.0, 0 for i in range(max(1, len(lines) - window + 1)): - chunk = lines[i : i + window] - ratio = difflib.SequenceMatcher(None, old_lines, chunk).ratio() + ratio = difflib.SequenceMatcher(None, old_lines, lines[i : i + window]).ratio() if ratio > best_ratio: - best_ratio = ratio - best_start = i + best_ratio, best_start = ratio, i if best_ratio > 0.5: - best_chunk = lines[best_start : best_start + window] - diff = difflib.unified_diff( - old_lines, best_chunk, + diff = "\n".join(difflib.unified_diff( + old_lines, lines[best_start : best_start + window], fromfile="old_text (provided)", tofile=f"{path} (actual, line {best_start + 1})", lineterm="", - ) - diff_str = "\n".join(diff) - return ( - f"Error: old_text not found in {path}.\n" - f"Best match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff_str}" - ) + )) + return f"Error: old_text not found in {path}.\nBest match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff}" return f"Error: old_text not found in {path}. No similar text found. Verify the file content." From c4bee640b838045d6df079c734573523f23de48d Mon Sep 17 00:00:00 2001 From: Alexander Minges Date: Sat, 21 Feb 2026 07:51:28 +0100 Subject: [PATCH 066/154] fix(agent): skip empty fallback outbound for non-cli channels --- nanobot/agent/loop.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 4850f9c..336baec 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -273,9 +273,15 @@ class AgentLoop: ) try: response = await self._process_message(msg) - await self.bus.publish_outbound(response or OutboundMessage( - channel=msg.channel, chat_id=msg.chat_id, content="", - )) + if response is not None: + await self.bus.publish_outbound(response) + elif msg.channel == "cli": + await self.bus.publish_outbound(OutboundMessage( + channel=msg.channel, + chat_id=msg.chat_id, + content="", + metadata=msg.metadata or {}, + )) except Exception as e: logger.error("Error processing message: {}", e) await self.bus.publish_outbound(OutboundMessage( From aeb07d3450fafbcadb4ed649355ce2d3c4759225 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 07:32:58 +0000 Subject: [PATCH 067/154] refactor(loop): remove interim text retry, use system prompt constraint instead --- nanobot/agent/context.py | 1 + nanobot/agent/loop.py | 15 --------------- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index 67aad0c..9ef333c 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -106,6 +106,7 @@ Only use the 'message' tool when you need to send a message to a specific chat c For normal conversation, just respond with text - do not call the message tool. Always be helpful, accurate, and concise. Before calling tools, briefly tell the user what you're about to do (one short sentence in the user's language). +If you need to use tools, call them directly β€” never send a preliminary message like "Let me check" without actually calling a tool. When remembering something important, write to {workspace_path}/memory/MEMORY.md To recall past events, grep {workspace_path}/memory/HISTORY.md""" diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 2348df7..b9108e7 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -202,8 +202,6 @@ class AgentLoop: iteration = 0 final_content = None tools_used: list[str] = [] - text_only_retried = False - interim_content: str | None = None # Fallback if retry produces nothing while iteration < self.max_iterations: iteration += 1 @@ -249,19 +247,6 @@ class AgentLoop: ) else: final_content = self._strip_think(response.content) - # Some models send an interim text response before tool calls. - # Give them one retry; save the content as fallback in case - # the retry produces nothing useful (e.g. model already answered). - if not tools_used and not text_only_retried and final_content: - text_only_retried = True - interim_content = final_content - logger.debug("Interim text response (no tools used yet), retrying: {}", final_content[:80]) - final_content = None - continue - # Fall back to interim content if retry produced nothing - # and no tools were used (if tools ran, interim was truly interim) - if not final_content and interim_content and not tools_used: - final_content = interim_content break return final_content, tools_used From ab026c513162580443e1c386f13539b088aab770 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 08:14:46 +0000 Subject: [PATCH 068/154] refactor: extract memory consolidation to MemoryStore, slim down AgentLoop --- README.md | 2 +- nanobot/agent/loop.py | 257 ++++++---------------------------------- nanobot/agent/memory.py | 108 +++++++++++++++++ 3 files changed, 147 insertions(+), 220 deletions(-) diff --git a/README.md b/README.md index 68ad5a9..c5fd908 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ⚑️ Delivers core agent functionality in just **~4,000** lines of code β€” **99% smaller** than Clawdbot's 430k+ lines. -πŸ“ Real-time line count: **3,827 lines** (run `bash core_agent_lines.sh` to verify anytime) +πŸ“ Real-time line count: **3,806 lines** (run `bash core_agent_lines.sh` to verify anytime) ## πŸ“’ News diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 325c1ac..50f6ec2 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -99,33 +99,18 @@ class AgentLoop: def _register_default_tools(self) -> None: """Register the default set of tools.""" - # File tools (workspace for relative paths, restrict if configured) allowed_dir = self.workspace if self.restrict_to_workspace else None - self.tools.register(ReadFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) - self.tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) - self.tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir)) - self.tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir)) - - # Shell tool + for cls in (ReadFileTool, WriteFileTool, EditFileTool, ListDirTool): + self.tools.register(cls(workspace=self.workspace, allowed_dir=allowed_dir)) self.tools.register(ExecTool( working_dir=str(self.workspace), timeout=self.exec_config.timeout, restrict_to_workspace=self.restrict_to_workspace, )) - - # Web tools self.tools.register(WebSearchTool(api_key=self.brave_api_key)) self.tools.register(WebFetchTool()) - - # Message tool - message_tool = MessageTool(send_callback=self.bus.publish_outbound) - self.tools.register(message_tool) - - # Spawn tool (for subagents) - spawn_tool = SpawnTool(manager=self.subagents) - self.tools.register(spawn_tool) - - # Cron tool (for scheduling) + self.tools.register(MessageTool(send_callback=self.bus.publish_outbound)) + self.tools.register(SpawnTool(manager=self.subagents)) if self.cron_service: self.tools.register(CronTool(self.cron_service)) @@ -187,16 +172,7 @@ class AgentLoop: initial_messages: list[dict], on_progress: Callable[[str], Awaitable[None]] | None = None, ) -> tuple[str | None, list[str]]: - """ - Run the agent iteration loop. - - Args: - initial_messages: Starting messages for the LLM conversation. - on_progress: Optional callback to push intermediate content to the user. - - Returns: - Tuple of (final_content, list_of_tools_used). - """ + """Run the agent iteration loop. Returns (final_content, tools_used).""" messages = initial_messages iteration = 0 final_content = None @@ -297,20 +273,25 @@ class AgentLoop: session_key: str | None = None, on_progress: Callable[[str], Awaitable[None]] | None = None, ) -> OutboundMessage | None: - """ - Process a single inbound message. - - Args: - msg: The inbound message to process. - session_key: Override session key (used by process_direct). - on_progress: Optional callback for intermediate output (defaults to bus publish). - - Returns: - The response message, or None if no response needed. - """ - # System messages route back via chat_id ("channel:chat_id") + """Process a single inbound message and return the response.""" + # System messages: parse origin from chat_id ("channel:chat_id") if msg.channel == "system": - return await self._process_system_message(msg) + channel, chat_id = (msg.chat_id.split(":", 1) if ":" in msg.chat_id + else ("cli", msg.chat_id)) + logger.info("Processing system message from {}", msg.sender_id) + key = f"{channel}:{chat_id}" + session = self.sessions.get_or_create(key) + self._set_tool_context(channel, chat_id, msg.metadata.get("message_id")) + messages = self.context.build_messages( + history=session.get_history(max_messages=self.memory_window), + current_message=msg.content, channel=channel, chat_id=chat_id, + ) + final_content, _ = await self._run_agent_loop(messages) + session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") + session.add_message("assistant", final_content or "Background task completed.") + self.sessions.save(session) + return OutboundMessage(channel=channel, chat_id=chat_id, + content=final_content or "Background task completed.") preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview) @@ -318,19 +299,18 @@ class AgentLoop: key = session_key or msg.session_key session = self.sessions.get_or_create(key) - # Handle slash commands + # Slash commands cmd = msg.content.strip().lower() if cmd == "/new": - # Capture messages before clearing (avoid race condition with background task) messages_to_archive = session.messages.copy() session.clear() self.sessions.save(session) self.sessions.invalidate(session.key) async def _consolidate_and_cleanup(): - temp_session = Session(key=session.key) - temp_session.messages = messages_to_archive - await self._consolidate_memory(temp_session, archive_all=True) + temp = Session(key=session.key) + temp.messages = messages_to_archive + await self._consolidate_memory(temp, archive_all=True) asyncio.create_task(_consolidate_and_cleanup()) return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, @@ -359,16 +339,14 @@ class AgentLoop: history=session.get_history(max_messages=self.memory_window), current_message=msg.content, media=msg.media if msg.media else None, - channel=msg.channel, - chat_id=msg.chat_id, + channel=msg.channel, chat_id=msg.chat_id, ) async def _bus_progress(content: str) -> None: meta = dict(msg.metadata or {}) meta["_progress"] = True await self.bus.publish_outbound(OutboundMessage( - channel=msg.channel, chat_id=msg.chat_id, content=content, - metadata=meta, + channel=msg.channel, chat_id=msg.chat_id, content=content, metadata=meta, )) final_content, tools_used = await self._run_agent_loop( @@ -391,157 +369,16 @@ class AgentLoop: return None return OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content=final_content, - metadata=msg.metadata or {}, # Pass through for channel-specific needs (e.g. Slack thread_ts) - ) - - async def _process_system_message(self, msg: InboundMessage) -> OutboundMessage | None: - """ - Process a system message (e.g., subagent announce). - - The chat_id field contains "original_channel:original_chat_id" to route - the response back to the correct destination. - """ - logger.info("Processing system message from {}", msg.sender_id) - - # Parse origin from chat_id (format: "channel:chat_id") - if ":" in msg.chat_id: - parts = msg.chat_id.split(":", 1) - origin_channel = parts[0] - origin_chat_id = parts[1] - else: - # Fallback - origin_channel = "cli" - origin_chat_id = msg.chat_id - - session_key = f"{origin_channel}:{origin_chat_id}" - session = self.sessions.get_or_create(session_key) - self._set_tool_context(origin_channel, origin_chat_id, msg.metadata.get("message_id")) - initial_messages = self.context.build_messages( - history=session.get_history(max_messages=self.memory_window), - current_message=msg.content, - channel=origin_channel, - chat_id=origin_chat_id, - ) - final_content, _ = await self._run_agent_loop(initial_messages) - - if final_content is None: - final_content = "Background task completed." - - session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") - session.add_message("assistant", final_content) - self.sessions.save(session) - - return OutboundMessage( - channel=origin_channel, - chat_id=origin_chat_id, - content=final_content + channel=msg.channel, chat_id=msg.chat_id, content=final_content, + metadata=msg.metadata or {}, ) async def _consolidate_memory(self, session, archive_all: bool = False) -> None: - """Consolidate old messages into MEMORY.md + HISTORY.md. - - Args: - archive_all: If True, clear all messages and reset session (for /new command). - If False, only write to files without modifying session. - """ - memory = MemoryStore(self.workspace) - - if archive_all: - old_messages = session.messages - keep_count = 0 - logger.info("Memory consolidation (archive_all): {} total messages archived", len(session.messages)) - else: - keep_count = self.memory_window // 2 - if len(session.messages) <= keep_count: - logger.debug("Session {}: No consolidation needed (messages={}, keep={})", session.key, len(session.messages), keep_count) - return - - messages_to_process = len(session.messages) - session.last_consolidated - if messages_to_process <= 0: - logger.debug("Session {}: No new messages to consolidate (last_consolidated={}, total={})", session.key, session.last_consolidated, len(session.messages)) - return - - old_messages = session.messages[session.last_consolidated:-keep_count] - if not old_messages: - return - logger.info("Memory consolidation started: {} total, {} new to consolidate, {} keep", len(session.messages), len(old_messages), keep_count) - - lines = [] - for m in old_messages: - if not m.get("content"): - continue - tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else "" - lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}") - conversation = "\n".join(lines) - current_memory = memory.read_long_term() - - prompt = f"""Process this conversation and call the save_memory tool with your consolidation. - -## Current Long-term Memory -{current_memory or "(empty)"} - -## Conversation to Process -{conversation}""" - - save_memory_tool = [ - { - "type": "function", - "function": { - "name": "save_memory", - "description": "Save the memory consolidation result to persistent storage.", - "parameters": { - "type": "object", - "properties": { - "history_entry": { - "type": "string", - "description": "A paragraph (2-5 sentences) summarizing key events/decisions/topics. Start with a timestamp like [YYYY-MM-DD HH:MM]. Include enough detail to be useful when found by grep search later.", - }, - "memory_update": { - "type": "string", - "description": "The full updated long-term memory content as a markdown string. Include all existing facts plus any new facts: user location, preferences, personal info, habits, project context, technical decisions, tools/services used. If nothing new, return the existing content unchanged.", - }, - }, - "required": ["history_entry", "memory_update"], - }, - }, - } - ] - - try: - response = await self.provider.chat( - messages=[ - {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."}, - {"role": "user", "content": prompt}, - ], - tools=save_memory_tool, - model=self.model, - ) - - if not response.has_tool_calls: - logger.warning("Memory consolidation: LLM did not call save_memory tool, skipping") - return - - args = response.tool_calls[0].arguments - if entry := args.get("history_entry"): - if not isinstance(entry, str): - entry = json.dumps(entry, ensure_ascii=False) - memory.append_history(entry) - if update := args.get("memory_update"): - if not isinstance(update, str): - update = json.dumps(update, ensure_ascii=False) - if update != current_memory: - memory.write_long_term(update) - - if archive_all: - session.last_consolidated = 0 - else: - session.last_consolidated = len(session.messages) - keep_count - logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) - except Exception as e: - logger.error("Memory consolidation failed: {}", e) + """Delegate to MemoryStore.consolidate().""" + await MemoryStore(self.workspace).consolidate( + session, self.provider, self.model, + archive_all=archive_all, memory_window=self.memory_window, + ) async def process_direct( self, @@ -551,26 +388,8 @@ class AgentLoop: chat_id: str = "direct", on_progress: Callable[[str], Awaitable[None]] | None = None, ) -> str: - """ - Process a message directly (for CLI or cron usage). - - Args: - content: The message content. - session_key: Session identifier (overrides channel:chat_id for session lookup). - channel: Source channel (for tool context routing). - chat_id: Source chat ID (for tool context routing). - on_progress: Optional callback for intermediate output. - - Returns: - The agent's response. - """ + """Process a message directly (for CLI or cron usage).""" await self._connect_mcp() - msg = InboundMessage( - channel=channel, - sender_id="user", - chat_id=chat_id, - content=content - ) - + msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content) response = await self._process_message(msg, session_key=session_key, on_progress=on_progress) return response.content if response else "" diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.py index 29477c4..51abd8f 100644 --- a/nanobot/agent/memory.py +++ b/nanobot/agent/memory.py @@ -1,9 +1,46 @@ """Memory system for persistent agent memory.""" +from __future__ import annotations + +import json from pathlib import Path +from typing import TYPE_CHECKING + +from loguru import logger from nanobot.utils.helpers import ensure_dir +if TYPE_CHECKING: + from nanobot.providers.base import LLMProvider + from nanobot.session.manager import Session + + +_SAVE_MEMORY_TOOL = [ + { + "type": "function", + "function": { + "name": "save_memory", + "description": "Save the memory consolidation result to persistent storage.", + "parameters": { + "type": "object", + "properties": { + "history_entry": { + "type": "string", + "description": "A paragraph (2-5 sentences) summarizing key events/decisions/topics. " + "Start with [YYYY-MM-DD HH:MM]. Include detail useful for grep search.", + }, + "memory_update": { + "type": "string", + "description": "Full updated long-term memory as markdown. Include all existing " + "facts plus new ones. Return unchanged if nothing new.", + }, + }, + "required": ["history_entry", "memory_update"], + }, + }, + } +] + class MemoryStore: """Two-layer memory: MEMORY.md (long-term facts) + HISTORY.md (grep-searchable log).""" @@ -28,3 +65,74 @@ class MemoryStore: def get_memory_context(self) -> str: long_term = self.read_long_term() return f"## Long-term Memory\n{long_term}" if long_term else "" + + async def consolidate( + self, + session: Session, + provider: LLMProvider, + model: str, + *, + archive_all: bool = False, + memory_window: int = 50, + ) -> None: + """Consolidate old messages into MEMORY.md + HISTORY.md via LLM tool call.""" + if archive_all: + old_messages = session.messages + keep_count = 0 + logger.info("Memory consolidation (archive_all): {} messages", len(session.messages)) + else: + keep_count = memory_window // 2 + if len(session.messages) <= keep_count: + return + if len(session.messages) - session.last_consolidated <= 0: + return + old_messages = session.messages[session.last_consolidated:-keep_count] + if not old_messages: + return + logger.info("Memory consolidation: {} to consolidate, {} keep", len(old_messages), keep_count) + + lines = [] + for m in old_messages: + if not m.get("content"): + continue + tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else "" + lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}") + + current_memory = self.read_long_term() + prompt = f"""Process this conversation and call the save_memory tool with your consolidation. + +## Current Long-term Memory +{current_memory or "(empty)"} + +## Conversation to Process +{chr(10).join(lines)}""" + + try: + response = await provider.chat( + messages=[ + {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."}, + {"role": "user", "content": prompt}, + ], + tools=_SAVE_MEMORY_TOOL, + model=model, + ) + + if not response.has_tool_calls: + logger.warning("Memory consolidation: LLM did not call save_memory, skipping") + return + + args = response.tool_calls[0].arguments + if entry := args.get("history_entry"): + if not isinstance(entry, str): + entry = json.dumps(entry, ensure_ascii=False) + self.append_history(entry) + if update := args.get("memory_update"): + if not isinstance(update, str): + update = json.dumps(update, ensure_ascii=False) + if update != current_memory: + self.write_long_term(update) + + session.last_consolidated = 0 if archive_all else len(session.messages) - keep_count + logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated) + except Exception as e: + logger.error("Memory consolidation failed: {}", e) From 0b30f514b4bee99660dc57f27a8326e749df6979 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 08:27:49 +0000 Subject: [PATCH 069/154] style(loop): compact empty outbound message construction --- nanobot/agent/loop.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 5f0962a..7b9317c 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -244,10 +244,7 @@ class AgentLoop: await self.bus.publish_outbound(response) elif msg.channel == "cli": await self.bus.publish_outbound(OutboundMessage( - channel=msg.channel, - chat_id=msg.chat_id, - content="", - metadata=msg.metadata or {}, + channel=msg.channel, chat_id=msg.chat_id, content="", metadata=msg.metadata or {}, )) except Exception as e: logger.error("Error processing message: {}", e) From ec4bdb651fa13f9ced4fe9955b2c69c7bae7e39d Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 08:33:02 +0000 Subject: [PATCH 070/154] docs: update nanobot news --- README.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index c5fd908..bf627a0 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,9 @@ ## πŸ“’ News +- **2026-02-20** 🐦 Feishu now receives images, audio, and files from users. More reliable memory under the hood. +- **2026-02-19** ✨ Slack now sends files, Discord splits long messages, and subagents work in CLI mode. +- **2026-02-18** ⚑️ nanobot now supports VolcEngine, MCP custom auth headers, and Anthropic prompt caching. - **2026-02-17** πŸŽ‰ Released **v0.1.4** β€” MCP support, progress streaming, new providers, and multiple channel improvements. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4) for details. - **2026-02-16** 🦞 nanobot now integrates a [ClawHub](https://clawhub.ai) skill β€” search and install public agent skills. - **2026-02-15** πŸ”‘ nanobot now supports OpenAI Codex provider with OAuth login support. @@ -27,20 +30,18 @@ - **2026-02-13** πŸŽ‰ Released **v0.1.3.post7** β€” includes security hardening and multiple improvements. **Please upgrade to the latest version to address security issues**. See [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post7) for more details. - **2026-02-12** 🧠 Redesigned memory system β€” Less code, more reliable. Join the [discussion](https://github.com/HKUDS/nanobot/discussions/566) about it! - **2026-02-11** ✨ Enhanced CLI experience and added MiniMax support! -- **2026-02-10** πŸŽ‰ Released **v0.1.3.post6** with improvements! Check the updates [notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post6) and our [roadmap](https://github.com/HKUDS/nanobot/discussions/431). -- **2026-02-09** πŸ’¬ Added Slack, Email, and QQ support β€” nanobot now supports multiple chat platforms! -- **2026-02-08** πŸ”§ Refactored Providersβ€”adding a new LLM provider now takes just 2 simple steps! Check [here](#providers).
Earlier news - +- **2026-02-10** πŸŽ‰ Released **v0.1.3.post6** with improvements! Check the updates [notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post6) and our [roadmap](https://github.com/HKUDS/nanobot/discussions/431). +- **2026-02-09** πŸ’¬ Added Slack, Email, and QQ support β€” nanobot now supports multiple chat platforms! +- **2026-02-08** πŸ”§ Refactored Providersβ€”adding a new LLM provider now takes just 2 simple steps! Check [here](#providers). - **2026-02-07** πŸš€ Released **v0.1.3.post5** with Qwen support & several key improvements! Check [here](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post5) for details. - **2026-02-06** ✨ Added Moonshot/Kimi provider, Discord integration, and enhanced security hardening! - **2026-02-05** ✨ Added Feishu channel, DeepSeek provider, and enhanced scheduled tasks support! - **2026-02-04** πŸš€ Released **v0.1.3.post4** with multi-provider & Docker support! Check [here](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post4) for details. - **2026-02-03** ⚑ Integrated vLLM for local LLM support and improved natural language task scheduling! - **2026-02-02** πŸŽ‰ nanobot officially launched! Welcome to try 🐈 nanobot! -
## Key Features of nanobot: From 9c61e1389c0ba6d33fb357c5937a5552fd8711ac Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 08:33:31 +0000 Subject: [PATCH 071/154] docs: update nanobot news --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bf627a0..8e1202c 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ ## πŸ“’ News -- **2026-02-20** 🐦 Feishu now receives images, audio, and files from users. More reliable memory under the hood. +- **2026-02-20** 🐦 Feishu now receives multimodal files from users. More reliable memory under the hood. - **2026-02-19** ✨ Slack now sends files, Discord splits long messages, and subagents work in CLI mode. - **2026-02-18** ⚑️ nanobot now supports VolcEngine, MCP custom auth headers, and Anthropic prompt caching. - **2026-02-17** πŸŽ‰ Released **v0.1.4** β€” MCP support, progress streaming, new providers, and multiple channel improvements. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4) for details. From b3acd19c7ba2e012916d09ae7de52b328cbb5108 Mon Sep 17 00:00:00 2001 From: vincentchen Date: Sat, 21 Feb 2026 20:28:42 +0800 Subject: [PATCH 072/154] Remove redundant tools description (because tools information is passed in with each self.provider.chat() call) --- nanobot/agent/context.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index 9ef333c..5794918 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -82,12 +82,7 @@ Skills with available="false" need dependencies installed first - you can try in return f"""# nanobot 🐈 -You are nanobot, a helpful AI assistant. You have access to tools that allow you to: -- Read, write, and edit files -- Execute shell commands -- Search the web and fetch web pages -- Send messages to users on chat channels -- Spawn subagents for complex background tasks +You are nanobot, a helpful AI assistant. ## Current Time {now} ({tz}) From af71ccf0514721777aaae500f05016d844fe5fc6 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 13:05:14 +0000 Subject: [PATCH 073/154] release: v0.1.4.post1 --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 64a884d..c337d02 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "nanobot-ai" -version = "0.1.4" +version = "0.1.4.post1" description = "A lightweight personal AI assistant framework" requires-python = ">=3.11" license = {text = "MIT"} From 88ca2e05307b66dfebe469d884c17217ea3b17d6 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 13:20:55 +0000 Subject: [PATCH 074/154] docs: update v.0.1.4.post1 release news --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 8e1202c..1002872 100644 --- a/README.md +++ b/README.md @@ -20,6 +20,7 @@ ## πŸ“’ News +- **2026-02-21** πŸŽ‰ Released **v0.1.4.post1** β€” new providers, media support across channels, and major stability improvements. See [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post1) for details. - **2026-02-20** 🐦 Feishu now receives multimodal files from users. More reliable memory under the hood. - **2026-02-19** ✨ Slack now sends files, Discord splits long messages, and subagents work in CLI mode. - **2026-02-18** ⚑️ nanobot now supports VolcEngine, MCP custom auth headers, and Anthropic prompt caching. From 01c835aac2bfc676d6213261c6ad6cb7301bb83e Mon Sep 17 00:00:00 2001 From: nanobot-bot Date: Sat, 21 Feb 2026 23:07:18 +0800 Subject: [PATCH 075/154] fix(context): Fix 'Missing `reasoning_content` field' error for deepseek provider. --- nanobot/agent/context.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index 876d43d..b3de8da 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -235,7 +235,7 @@ To recall past events, grep {workspace_path}/memory/HISTORY.md""" msg["tool_calls"] = tool_calls # Include reasoning content when provided (required by some thinking models) - if reasoning_content: + if reasoning_content is not None: msg["reasoning_content"] = reasoning_content messages.append(msg) From 83ccdf61862ffcd665fb096922087b4924b15d9a Mon Sep 17 00:00:00 2001 From: muskliu <862259098@qq.com> Date: Sun, 22 Feb 2026 00:14:22 +0800 Subject: [PATCH 076/154] fix(provider): filter empty text content blocks causing API 400 When MCP tools return empty content, messages may contain empty-string text blocks. OpenAI-compatible providers reject these with HTTP 400. Changes: - Add _prevent_empty_text_blocks() to filter empty text items from content lists and handle empty string content - For assistant messages with tool_calls, set content to None (valid) - For other messages, replace with '(empty)' placeholder - Only copy message dict when modification is needed (zero-copy path for normal messages) Co-Authored-By: nanobot --- nanobot/providers/custom_provider.py | 52 ++++++++++++++++++++++++++-- 1 file changed, 50 insertions(+), 2 deletions(-) diff --git a/nanobot/providers/custom_provider.py b/nanobot/providers/custom_provider.py index f190ccf..ec5d48b 100644 --- a/nanobot/providers/custom_provider.py +++ b/nanobot/providers/custom_provider.py @@ -19,8 +19,12 @@ class CustomProvider(LLMProvider): async def chat(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None, model: str | None = None, max_tokens: int = 4096, temperature: float = 0.7) -> LLMResponse: - kwargs: dict[str, Any] = {"model": model or self.default_model, "messages": messages, - "max_tokens": max(1, max_tokens), "temperature": temperature} + kwargs: dict[str, Any] = { + "model": model or self.default_model, + "messages": self._prevent_empty_text_blocks(messages), + "max_tokens": max(1, max_tokens), + "temperature": temperature, + } if tools: kwargs.update(tools=tools, tool_choice="auto") try: @@ -45,3 +49,47 @@ class CustomProvider(LLMProvider): def get_default_model(self) -> str: return self.default_model + + @staticmethod + def _prevent_empty_text_blocks(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Filter empty text content blocks that cause provider 400 errors. + + When MCP tools return empty content, messages may contain empty-string + text blocks. Most providers (OpenAI-compatible) reject these with 400. + This method filters them out before sending to the API. + """ + patched: list[dict[str, Any]] = [] + for msg in messages: + content = msg.get("content") + + # Empty string content + if isinstance(content, str) and content == "": + clean = dict(msg) + if msg.get("role") == "assistant" and msg.get("tool_calls"): + clean["content"] = None + else: + clean["content"] = "(empty)" + patched.append(clean) + continue + + # List content β€” filter out empty text items + if isinstance(content, list): + filtered = [ + item for item in content + if not (isinstance(item, dict) + and item.get("type") in {"text", "input_text", "output_text"} + and item.get("text") == "") + ] + if filtered != content: + clean = dict(msg) + if filtered: + clean["content"] = filtered + elif msg.get("role") == "assistant" and msg.get("tool_calls"): + clean["content"] = None + else: + clean["content"] = "(empty)" + patched.append(clean) + continue + + patched.append(msg) + return patched From edc671a8a30fd05c46a15b0da7292fc9c4c4b5be Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sat, 21 Feb 2026 16:39:26 +0000 Subject: [PATCH 077/154] docs: update format of news section --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 1002872..cb751ba 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,7 @@
Earlier news + - **2026-02-10** πŸŽ‰ Released **v0.1.3.post6** with improvements! Check the updates [notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post6) and our [roadmap](https://github.com/HKUDS/nanobot/discussions/431). - **2026-02-09** πŸ’¬ Added Slack, Email, and QQ support β€” nanobot now supports multiple chat platforms! - **2026-02-08** πŸ”§ Refactored Providersβ€”adding a new LLM provider now takes just 2 simple steps! Check [here](#providers). @@ -43,6 +44,7 @@ - **2026-02-04** πŸš€ Released **v0.1.3.post4** with multi-provider & Docker support! Check [here](https://github.com/HKUDS/nanobot/releases/tag/v0.1.3.post4) for details. - **2026-02-03** ⚑ Integrated vLLM for local LLM support and improved natural language task scheduling! - **2026-02-02** πŸŽ‰ nanobot officially launched! Welcome to try 🐈 nanobot! +
## Key Features of nanobot: From 6b7d7e2eb8745103b0bf4a513515b972a27f5885 Mon Sep 17 00:00:00 2001 From: muskliu <862259098@qq.com> Date: Sun, 22 Feb 2026 00:39:53 +0800 Subject: [PATCH 078/154] fix(mcp): add 30s timeout to MCP tool calls to prevent agent hangs --- nanobot/agent/tools/mcp.py | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index ad352bf..a5e619a 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -1,11 +1,15 @@ """MCP client: connects to MCP servers and wraps their tools as native nanobot tools.""" +import asyncio from contextlib import AsyncExitStack from typing import Any import httpx from loguru import logger +# Timeout for individual MCP tool calls (seconds). +MCP_TOOL_TIMEOUT = 30 + from nanobot.agent.tools.base import Tool from nanobot.agent.tools.registry import ToolRegistry @@ -34,7 +38,14 @@ class MCPToolWrapper(Tool): async def execute(self, **kwargs: Any) -> str: from mcp import types - result = await self._session.call_tool(self._original_name, arguments=kwargs) + try: + result = await asyncio.wait_for( + self._session.call_tool(self._original_name, arguments=kwargs), + timeout=MCP_TOOL_TIMEOUT, + ) + except asyncio.TimeoutError: + logger.warning("MCP tool '{}' timed out after {}s", self._name, MCP_TOOL_TIMEOUT) + return f"(MCP tool call timed out after {MCP_TOOL_TIMEOUT}s)" parts = [] for block in result.content: if isinstance(block, types.TextContent): From deae84482d786f5cb99ed526bf84edeba17caba8 Mon Sep 17 00:00:00 2001 From: init-new-world Date: Sun, 22 Feb 2026 00:42:41 +0800 Subject: [PATCH 079/154] fix: change VolcEngine litellm prefix from openai to volcengine --- nanobot/providers/registry.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.py index ecf092f..2766929 100644 --- a/nanobot/providers/registry.py +++ b/nanobot/providers/registry.py @@ -147,7 +147,7 @@ PROVIDERS: tuple[ProviderSpec, ...] = ( keywords=("volcengine", "volces", "ark"), env_key="OPENAI_API_KEY", display_name="VolcEngine", - litellm_prefix="openai", + litellm_prefix="volcengine", skip_prefixes=(), env_extras=(), is_gateway=True, From de63c31d43426be1e276db111cdc4d31b4f6767f Mon Sep 17 00:00:00 2001 From: andienguyen-ecoligo Date: Sat, 21 Feb 2026 12:30:57 -0500 Subject: [PATCH 080/154] fix(providers): normalize empty reasoning_content to None at provider level MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR #947 fixed the consumer side (context.py) but the root cause is at the provider level β€” getattr returns "" (empty string) instead of None when reasoning_content is empty. This causes DeepSeek API to reject the request with "Missing reasoning_content field" error. `"" or None` evaluates to None, preventing empty strings from propagating downstream. Fixes #946 --- nanobot/providers/custom_provider.py | 2 +- nanobot/providers/litellm_provider.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nanobot/providers/custom_provider.py b/nanobot/providers/custom_provider.py index f190ccf..4022d9e 100644 --- a/nanobot/providers/custom_provider.py +++ b/nanobot/providers/custom_provider.py @@ -40,7 +40,7 @@ class CustomProvider(LLMProvider): return LLMResponse( content=msg.content, tool_calls=tool_calls, finish_reason=choice.finish_reason or "stop", usage={"prompt_tokens": u.prompt_tokens, "completion_tokens": u.completion_tokens, "total_tokens": u.total_tokens} if u else {}, - reasoning_content=getattr(msg, "reasoning_content", None), + reasoning_content=getattr(msg, "reasoning_content", None) or None, ) def get_default_model(self) -> str: diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 58c9ac2..784f02c 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -257,7 +257,7 @@ class LiteLLMProvider(LLMProvider): "total_tokens": response.usage.total_tokens, } - reasoning_content = getattr(message, "reasoning_content", None) + reasoning_content = getattr(message, "reasoning_content", None) or None return LLMResponse( content=message.content, From 5c9cb3a208a0a9b3e543c510753269073579adaa Mon Sep 17 00:00:00 2001 From: andienguyen-ecoligo Date: Sat, 21 Feb 2026 12:34:14 -0500 Subject: [PATCH 081/154] fix(security): prevent path traversal bypass via startswith check `startswith` string comparison allows bypassing directory restrictions. For example, `/home/user/workspace_evil` passes the check against `/home/user/workspace` because the string starts with the allowed path. Replace with `Path.relative_to()` which correctly validates that the resolved path is actually inside the allowed directory tree. Fixes #888 --- nanobot/agent/tools/filesystem.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.py index 9c169e4..b87da11 100644 --- a/nanobot/agent/tools/filesystem.py +++ b/nanobot/agent/tools/filesystem.py @@ -13,8 +13,11 @@ def _resolve_path(path: str, workspace: Path | None = None, allowed_dir: Path | if not p.is_absolute() and workspace: p = workspace / p resolved = p.resolve() - if allowed_dir and not str(resolved).startswith(str(allowed_dir.resolve())): - raise PermissionError(f"Path {path} is outside allowed directory {allowed_dir}") + if allowed_dir: + try: + resolved.relative_to(allowed_dir.resolve()) + except ValueError: + raise PermissionError(f"Path {path} is outside allowed directory {allowed_dir}") return resolved From ef96619039c98ccb45c61481cf1b5203aa5864ac Mon Sep 17 00:00:00 2001 From: andienguyen-ecoligo Date: Sat, 21 Feb 2026 12:34:50 -0500 Subject: [PATCH 082/154] fix(slack): add exception handling to socket listener _handle_message() in _on_socket_request() had no try/except. If it throws (bus full, permission error, etc.), the exception propagates up and crashes the Socket Mode event loop, causing missed messages. Other channels like Telegram already have explicit error handlers. Fixes #895 --- nanobot/channels/slack.py | 27 +++++++++++++++------------ 1 file changed, 15 insertions(+), 12 deletions(-) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index 4fc1f41..d1c5895 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -179,18 +179,21 @@ class SlackChannel(BaseChannel): except Exception as e: logger.debug("Slack reactions_add failed: {}", e) - await self._handle_message( - sender_id=sender_id, - chat_id=chat_id, - content=text, - metadata={ - "slack": { - "event": event, - "thread_ts": thread_ts, - "channel_type": channel_type, - } - }, - ) + try: + await self._handle_message( + sender_id=sender_id, + chat_id=chat_id, + content=text, + metadata={ + "slack": { + "event": event, + "thread_ts": thread_ts, + "channel_type": channel_type, + } + }, + ) + except Exception as e: + logger.error("Error handling Slack message from {}: {}", sender_id, e) def _is_allowed(self, sender_id: str, chat_id: str, channel_type: str) -> bool: if channel_type == "im": From 54a0f3d038e2a7f18315e1768a351010401cf6c2 Mon Sep 17 00:00:00 2001 From: andienguyen-ecoligo Date: Sat, 21 Feb 2026 12:35:21 -0500 Subject: [PATCH 083/154] fix(session): handle errors in legacy session migration shutil.move() in _load() can fail due to permissions, disk full, or concurrent access. Without error handling, the exception propagates up and prevents the session from loading entirely. Wrap in try/except so migration failures are logged as warnings and the session falls back to loading from the legacy path on next attempt. Fixes #863 --- nanobot/session/manager.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 18e23b2..19d4439 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -108,9 +108,12 @@ class SessionManager: if not path.exists(): legacy_path = self._get_legacy_session_path(key) if legacy_path.exists(): - import shutil - shutil.move(str(legacy_path), str(path)) - logger.info("Migrated session {} from legacy path", key) + try: + import shutil + shutil.move(str(legacy_path), str(path)) + logger.info("Migrated session {} from legacy path", key) + except Exception as e: + logger.warning("Failed to migrate session {}: {}", key, e) if not path.exists(): return None From ba66c6475025e8123e88732f5cec71e5b56b0b14 Mon Sep 17 00:00:00 2001 From: andienguyen-ecoligo Date: Sat, 21 Feb 2026 12:36:04 -0500 Subject: [PATCH 084/154] fix(email): evict oldest half of dedup set instead of clearing entirely When _processed_uids exceeds 100k entries, the entire set was cleared with .clear(), allowing all previously seen emails to be re-processed. Now evicts the oldest 50% of entries, keeping recent UIDs to prevent duplicate processing while still bounding memory usage. Fixes #890 --- nanobot/channels/email.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nanobot/channels/email.py b/nanobot/channels/email.py index 1b6f46b..c90a14d 100644 --- a/nanobot/channels/email.py +++ b/nanobot/channels/email.py @@ -304,7 +304,9 @@ class EmailChannel(BaseChannel): self._processed_uids.add(uid) # mark_seen is the primary dedup; this set is a safety net if len(self._processed_uids) > self._MAX_PROCESSED_UIDS: - self._processed_uids.clear() + # Evict oldest half instead of clearing entirely + to_keep = list(self._processed_uids)[len(self._processed_uids) // 2:] + self._processed_uids = set(to_keep) if mark_seen: client.store(imap_id, "+FLAGS", "\\Seen") From 8c55b40b9f383c5e11217cbd6234483a63f597aa Mon Sep 17 00:00:00 2001 From: andienguyen-ecoligo Date: Sat, 21 Feb 2026 12:38:24 -0500 Subject: [PATCH 085/154] fix(qq): make start() long-running per base channel contract QQ channel's start() created a background task and returned immediately, violating the base Channel contract which specifies start() should be "a long-running async task". This caused the gateway to exit prematurely when QQ was the only enabled channel. Now directly awaits _run_bot() to stay alive like other channels. Fixes #894 --- nanobot/channels/qq.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nanobot/channels/qq.py b/nanobot/channels/qq.py index 16cbfb8..a940a75 100644 --- a/nanobot/channels/qq.py +++ b/nanobot/channels/qq.py @@ -71,8 +71,8 @@ class QQChannel(BaseChannel): BotClass = _make_bot_class(self) self._client = BotClass() - self._bot_task = asyncio.create_task(self._run_bot()) logger.info("QQ bot started (C2C private message)") + await self._run_bot() async def _run_bot(self) -> None: """Run the bot connection with auto-reconnect.""" From 3e406004839ccb2590649736e2e1c8c93761161c Mon Sep 17 00:00:00 2001 From: Rok Pergarec Date: Sat, 21 Feb 2026 20:55:54 +0100 Subject: [PATCH 086/154] docs: add systemd user service instructions to README --- README.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/README.md b/README.md index cb751ba..2c5cdc9 100644 --- a/README.md +++ b/README.md @@ -865,6 +865,57 @@ docker run -v ~/.nanobot:/root/.nanobot --rm nanobot agent -m "Hello!" docker run -v ~/.nanobot:/root/.nanobot --rm nanobot status ``` +## 🐧 Linux Service + +Run the gateway as a systemd user service so it starts automatically and restarts on failure. Below example is for a +`pip` based installation. + +**1. Create the service file** at `~/.config/systemd/user/nanobot-gateway.service`: + +```ini +[Unit] +Description=Nanobot Gateway +After=network.target + +[Service] +Type=simple +ExecStart=%h/.local/bin/nanobot gateway +Restart=always +RestartSec=10 +NoNewPrivileges=yes +ProtectSystem=strict +ReadWritePaths=%h + +[Install] +WantedBy=default.target +``` + +**2. Enable and start:** + +```bash +systemctl --user daemon-reload +systemctl --user enable --now nanobot-gateway +``` + +**After config changes**, restart: + +```bash +systemctl --user restart nanobot-gateway +``` + +If you modify the `.service` file itself, reload the unit before restarting: + +```bash +systemctl --user daemon-reload +systemctl --user restart nanobot-gateway +``` + +> **Note:** By default, user services only run while you are logged in. To keep the gateway running after you log out, enable lingering: +> +> ```bash +> loginctl enable-linger $USER +> ``` + ## πŸ“ Project Structure ``` From b323087631561d4312affd17f57aa0643210a730 Mon Sep 17 00:00:00 2001 From: Yingwen Luo-LUOYW Date: Sun, 22 Feb 2026 12:42:33 +0800 Subject: [PATCH 087/154] feat(cli): add DingTalk, QQ, and Email to channels status output --- nanobot/cli/commands.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 6155463..f1f9b30 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -668,6 +668,33 @@ def channels_status(): slack_config ) + # DingTalk + dt = config.channels.dingtalk + dt_config = f"client_id: {dt.client_id[:10]}..." if dt.client_id else "[dim]not configured[/dim]" + table.add_row( + "DingTalk", + "βœ“" if dt.enabled else "βœ—", + dt_config + ) + + # QQ + qq = config.channels.qq + qq_config = f"app_id: {qq.app_id[:10]}..." if qq.app_id else "[dim]not configured[/dim]" + table.add_row( + "QQ", + "βœ“" if qq.enabled else "βœ—", + qq_config + ) + + # Email + em = config.channels.email + em_config = em.imap_host if em.imap_host else "[dim]not configured[/dim]" + table.add_row( + "Email", + "βœ“" if em.enabled else "βœ—", + em_config + ) + console.print(table) From 973061b01efed370ba6fa2e2f0db54be58861711 Mon Sep 17 00:00:00 2001 From: FloRa <2862182666@qq.com> Date: Sun, 22 Feb 2026 17:15:00 +0800 Subject: [PATCH 088/154] fix(feishu): replace file.get with message_resource.get to fix file download permission issue --- nanobot/channels/feishu.py | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index 815d853..0376e57 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -503,18 +503,28 @@ class FeishuChannel(BaseChannel): logger.error("Error downloading image {}: {}", image_key, e) return None, None - def _download_file_sync(self, file_key: str) -> tuple[bytes | None, str | None]: - """Download a file from Feishu by file_key.""" + def _download_file_sync(self, message_id: str, file_key: str, resource_type: str = "file") -> tuple[ + bytes | None, str | None]: + """Download a file or audio from a Feishu message by message_id and file_key.""" try: - request = GetFileRequest.builder().file_key(file_key).build() - response = self._client.im.v1.file.get(request) + request = GetMessageResourceRequest.builder() \ + .message_id(message_id) \ + .file_key(file_key) \ + .type(resource_type) \ + .build() + response = self._client.im.v1.message_resource.get(request) + if response.success(): - return response.file, response.file_name + file_data = response.file + # GetMessageResourceRequest θΏ”ε›žηš„ζ˜―η±»δΌΌ BytesIO ηš„ε―Ήθ±‘οΌŒιœ€θ¦ read() + if hasattr(file_data, 'read'): + file_data = file_data.read() + return file_data, response.file_name else: - logger.error("Failed to download file: code={}, msg={}", response.code, response.msg) + logger.error("Failed to download {}: code={}, msg={}", resource_type, response.code, response.msg) return None, None except Exception as e: - logger.error("Error downloading file {}: {}", file_key, e) + logger.error("Error downloading {} {}: {}", resource_type, file_key, e) return None, None async def _download_and_save_media( @@ -544,14 +554,18 @@ class FeishuChannel(BaseChannel): if not filename: filename = f"{image_key[:16]}.jpg" + elif msg_type in ("audio", "file"): + file_key = content_json.get("file_key") - if file_key: + + if file_key and message_id: data, filename = await loop.run_in_executor( - None, self._download_file_sync, file_key + None, self._download_file_sync, message_id, file_key, msg_type ) if not filename: ext = ".opus" if msg_type == "audio" else "" + filename = f"{file_key[:16]}{ext}" if data and filename: From 0d3a2963d0d57b66b14f5d2b9c25fb494e6d62f8 Mon Sep 17 00:00:00 2001 From: FloRa <2862182666@qq.com> Date: Sun, 22 Feb 2026 17:37:33 +0800 Subject: [PATCH 089/154] fix(feishu): replace file.get with message_resource.get to fix file download permission issue --- nanobot/channels/feishu.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index 0376e57..d1eeb2e 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -555,23 +555,29 @@ class FeishuChannel(BaseChannel): filename = f"{image_key[:16]}.jpg" - elif msg_type in ("audio", "file"): + elif msg_type in ("audio", "file", "media"): file_key = content_json.get("file_key") - if file_key and message_id: data, filename = await loop.run_in_executor( - None, self._download_file_sync, message_id, file_key, msg_type + None, self._download_file_sync, message_id, file_key ) if not filename: - ext = ".opus" if msg_type == "audio" else "" - + if msg_type == "audio": + ext = ".opus" + elif msg_type == "media": + ext = ".mp4" + else: + ext = "" filename = f"{file_key[:16]}{ext}" if data and filename: file_path = media_dir / filename + file_path.write_bytes(data) + logger.debug("Downloaded {} to {}", msg_type, file_path) + return str(file_path), f"[{msg_type}: {filename}]" return None, f"[{msg_type}: download failed]" @@ -698,7 +704,7 @@ class FeishuChannel(BaseChannel): if text: content_parts.append(text) - elif msg_type in ("image", "audio", "file"): + elif msg_type in ("image", "audio", "file", "media"): file_path, content_text = await self._download_and_save_media(msg_type, content_json, message_id) if file_path: media_paths.append(file_path) From b93b77a485d3a0c1632a5c3d590bc0b2a37c43bd Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 15:38:19 +0000 Subject: [PATCH 090/154] fix(slack): use logger.exception to capture full traceback --- nanobot/channels/slack.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index d1c5895..b0f9bbb 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -192,8 +192,8 @@ class SlackChannel(BaseChannel): } }, ) - except Exception as e: - logger.error("Error handling Slack message from {}: {}", sender_id, e) + except Exception: + logger.exception("Error handling Slack message from {}", sender_id) def _is_allowed(self, sender_id: str, chat_id: str, channel_type: str) -> bool: if channel_type == "im": From 71de1899e6dcf9e5d01396b6a90e6a63486bc6de Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 15:40:17 +0000 Subject: [PATCH 091/154] fix(session): use logger.exception and move import to top --- nanobot/session/manager.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 19d4439..5f23dc2 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -1,6 +1,7 @@ """Session management for conversation history.""" import json +import shutil from pathlib import Path from dataclasses import dataclass, field from datetime import datetime @@ -109,11 +110,10 @@ class SessionManager: legacy_path = self._get_legacy_session_path(key) if legacy_path.exists(): try: - import shutil shutil.move(str(legacy_path), str(path)) logger.info("Migrated session {} from legacy path", key) - except Exception as e: - logger.warning("Failed to migrate session {}: {}", key, e) + except Exception: + logger.exception("Failed to migrate session {}", key) if not path.exists(): return None From 4e8c8cc2274f1c5f505574e8fa7d5a5df790aff6 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 15:48:49 +0000 Subject: [PATCH 092/154] fix(email): fix misleading comment and simplify uid eviction --- nanobot/channels/email.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nanobot/channels/email.py b/nanobot/channels/email.py index c90a14d..5dc05fb 100644 --- a/nanobot/channels/email.py +++ b/nanobot/channels/email.py @@ -304,9 +304,8 @@ class EmailChannel(BaseChannel): self._processed_uids.add(uid) # mark_seen is the primary dedup; this set is a safety net if len(self._processed_uids) > self._MAX_PROCESSED_UIDS: - # Evict oldest half instead of clearing entirely - to_keep = list(self._processed_uids)[len(self._processed_uids) // 2:] - self._processed_uids = set(to_keep) + # Evict a random half to cap memory; mark_seen is the primary dedup + self._processed_uids = set(list(self._processed_uids)[len(self._processed_uids) // 2:]) if mark_seen: client.store(imap_id, "+FLAGS", "\\Seen") From b13d7f853e8173162df02af0dc1b8e25b674753b Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 17:17:35 +0000 Subject: [PATCH 093/154] fix(agent): make tool hint a fallback when no content in on_progress --- nanobot/agent/loop.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 5762fa9..b05ba90 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -196,7 +196,8 @@ class AgentLoop: clean = self._strip_think(response.content) if clean: await on_progress(clean) - await on_progress(self._tool_hint(response.tool_calls)) + else: + await on_progress(self._tool_hint(response.tool_calls)) tool_call_dicts = [ { From b53c3d39edece22484568bb1896cbe29bfb3c1ae Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 17:35:53 +0000 Subject: [PATCH 094/154] fix(qq): remove dead _bot_task field and fix stop() to close client --- nanobot/channels/qq.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/nanobot/channels/qq.py b/nanobot/channels/qq.py index a940a75..5352a30 100644 --- a/nanobot/channels/qq.py +++ b/nanobot/channels/qq.py @@ -55,7 +55,6 @@ class QQChannel(BaseChannel): self.config: QQConfig = config self._client: "botpy.Client | None" = None self._processed_ids: deque = deque(maxlen=1000) - self._bot_task: asyncio.Task | None = None async def start(self) -> None: """Start the QQ bot.""" @@ -88,11 +87,10 @@ class QQChannel(BaseChannel): async def stop(self) -> None: """Stop the QQ bot.""" self._running = False - if self._bot_task: - self._bot_task.cancel() + if self._client: try: - await self._bot_task - except asyncio.CancelledError: + await self._client.close() + except Exception: pass logger.info("QQ bot stopped") @@ -130,5 +128,5 @@ class QQChannel(BaseChannel): content=content, metadata={"message_id": data.id}, ) - except Exception as e: - logger.error("Error handling QQ message: {}", e) + except Exception: + logger.exception("Error handling QQ message") From 1aa06ea03dcd1c0fa4eed018e822918fe938706a Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 17:51:23 +0000 Subject: [PATCH 095/154] docs: improve Linux Service section in README --- README.md | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index 2c5cdc9..99f9681 100644 --- a/README.md +++ b/README.md @@ -867,10 +867,15 @@ docker run -v ~/.nanobot:/root/.nanobot --rm nanobot status ## 🐧 Linux Service -Run the gateway as a systemd user service so it starts automatically and restarts on failure. Below example is for a -`pip` based installation. +Run the gateway as a systemd user service so it starts automatically and restarts on failure. -**1. Create the service file** at `~/.config/systemd/user/nanobot-gateway.service`: +**1. Find the nanobot binary path:** + +```bash +which nanobot # e.g. /home/user/.local/bin/nanobot +``` + +**2. Create the service file** at `~/.config/systemd/user/nanobot-gateway.service` (replace `ExecStart` path if needed): ```ini [Unit] @@ -890,27 +895,24 @@ ReadWritePaths=%h WantedBy=default.target ``` -**2. Enable and start:** +**3. Enable and start:** ```bash systemctl --user daemon-reload systemctl --user enable --now nanobot-gateway ``` -**After config changes**, restart: +**Common operations:** ```bash -systemctl --user restart nanobot-gateway +systemctl --user status nanobot-gateway # check status +systemctl --user restart nanobot-gateway # restart after config changes +journalctl --user -u nanobot-gateway -f # follow logs ``` -If you modify the `.service` file itself, reload the unit before restarting: +If you edit the `.service` file itself, run `systemctl --user daemon-reload` before restarting. -```bash -systemctl --user daemon-reload -systemctl --user restart nanobot-gateway -``` - -> **Note:** By default, user services only run while you are logged in. To keep the gateway running after you log out, enable lingering: +> **Note:** User services only run while you are logged in. To keep the gateway running after logout, enable lingering: > > ```bash > loginctl enable-linger $USER From 437ebf4e6eda3711575d71878a92e19b32992912 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 18:04:13 +0000 Subject: [PATCH 096/154] feat(mcp): make tool_timeout configurable per server via config --- README.md | 17 ++++++++++++++++- nanobot/agent/tools/mcp.py | 14 ++++++-------- nanobot/config/schema.py | 1 + 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 99f9681..8399c45 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ⚑️ Delivers core agent functionality in just **~4,000** lines of code β€” **99% smaller** than Clawdbot's 430k+ lines. -πŸ“ Real-time line count: **3,806 lines** (run `bash core_agent_lines.sh` to verify anytime) +πŸ“ Real-time line count: **3,862 lines** (run `bash core_agent_lines.sh` to verify anytime) ## πŸ“’ News @@ -776,6 +776,21 @@ Two transport modes are supported: | **Stdio** | `command` + `args` | Local process via `npx` / `uvx` | | **HTTP** | `url` + `headers` (optional) | Remote endpoint (`https://mcp.example.com/sse`) | +Use `toolTimeout` to override the default 30s per-call timeout for slow servers: + +```json +{ + "tools": { + "mcpServers": { + "my-slow-server": { + "url": "https://example.com/mcp/", + "toolTimeout": 120 + } + } + } +} +``` + MCP tools are automatically discovered and registered on startup. The LLM can use them alongside built-in tools β€” no extra configuration needed. diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index a5e619a..0257d52 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -7,9 +7,6 @@ from typing import Any import httpx from loguru import logger -# Timeout for individual MCP tool calls (seconds). -MCP_TOOL_TIMEOUT = 30 - from nanobot.agent.tools.base import Tool from nanobot.agent.tools.registry import ToolRegistry @@ -17,12 +14,13 @@ from nanobot.agent.tools.registry import ToolRegistry class MCPToolWrapper(Tool): """Wraps a single MCP server tool as a nanobot Tool.""" - def __init__(self, session, server_name: str, tool_def): + def __init__(self, session, server_name: str, tool_def, tool_timeout: int = 30): self._session = session self._original_name = tool_def.name self._name = f"mcp_{server_name}_{tool_def.name}" self._description = tool_def.description or tool_def.name self._parameters = tool_def.inputSchema or {"type": "object", "properties": {}} + self._tool_timeout = tool_timeout @property def name(self) -> str: @@ -41,11 +39,11 @@ class MCPToolWrapper(Tool): try: result = await asyncio.wait_for( self._session.call_tool(self._original_name, arguments=kwargs), - timeout=MCP_TOOL_TIMEOUT, + timeout=self._tool_timeout, ) except asyncio.TimeoutError: - logger.warning("MCP tool '{}' timed out after {}s", self._name, MCP_TOOL_TIMEOUT) - return f"(MCP tool call timed out after {MCP_TOOL_TIMEOUT}s)" + logger.warning("MCP tool '{}' timed out after {}s", self._name, self._tool_timeout) + return f"(MCP tool call timed out after {self._tool_timeout}s)" parts = [] for block in result.content: if isinstance(block, types.TextContent): @@ -94,7 +92,7 @@ async def connect_mcp_servers( tools = await session.list_tools() for tool_def in tools.tools: - wrapper = MCPToolWrapper(session, name, tool_def) + wrapper = MCPToolWrapper(session, name, tool_def, tool_timeout=cfg.tool_timeout) registry.register(wrapper) logger.debug("MCP: registered tool '{}' from server '{}'", wrapper.name, name) diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index 966d11d..be36536 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -260,6 +260,7 @@ class MCPServerConfig(Base): env: dict[str, str] = Field(default_factory=dict) # Stdio: extra env vars url: str = "" # HTTP: streamable HTTP endpoint URL headers: dict[str, str] = Field(default_factory=dict) # HTTP: Custom HTTP Headers + tool_timeout: int = 30 # Seconds before a tool call is cancelled class ToolsConfig(Base): From efe89c90913d3fd7b8415b13e577021932a60795 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 18:16:45 +0000 Subject: [PATCH 097/154] fix(feishu): pass msg_type as resource_type and clean up style --- nanobot/channels/feishu.py | 39 +++++++++++++++----------------------- 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index d1eeb2e..2d50d74 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -503,28 +503,29 @@ class FeishuChannel(BaseChannel): logger.error("Error downloading image {}: {}", image_key, e) return None, None - def _download_file_sync(self, message_id: str, file_key: str, resource_type: str = "file") -> tuple[ - bytes | None, str | None]: - """Download a file or audio from a Feishu message by message_id and file_key.""" + def _download_file_sync( + self, message_id: str, file_key: str, resource_type: str = "file" + ) -> tuple[bytes | None, str | None]: + """Download a file/audio/media from a Feishu message by message_id and file_key.""" try: - request = GetMessageResourceRequest.builder() \ - .message_id(message_id) \ - .file_key(file_key) \ - .type(resource_type) \ + request = ( + GetMessageResourceRequest.builder() + .message_id(message_id) + .file_key(file_key) + .type(resource_type) .build() + ) response = self._client.im.v1.message_resource.get(request) - if response.success(): file_data = response.file - # GetMessageResourceRequest θΏ”ε›žηš„ζ˜―η±»δΌΌ BytesIO ηš„ε―Ήθ±‘οΌŒιœ€θ¦ read() - if hasattr(file_data, 'read'): + if hasattr(file_data, "read"): file_data = file_data.read() return file_data, response.file_name else: logger.error("Failed to download {}: code={}, msg={}", resource_type, response.code, response.msg) return None, None - except Exception as e: - logger.error("Error downloading {} {}: {}", resource_type, file_key, e) + except Exception: + logger.exception("Error downloading {} {}", resource_type, file_key) return None, None async def _download_and_save_media( @@ -554,30 +555,20 @@ class FeishuChannel(BaseChannel): if not filename: filename = f"{image_key[:16]}.jpg" - - elif msg_type in ("audio", "file", "media"): file_key = content_json.get("file_key") if file_key and message_id: data, filename = await loop.run_in_executor( - None, self._download_file_sync, message_id, file_key + None, self._download_file_sync, message_id, file_key, msg_type ) if not filename: - if msg_type == "audio": - ext = ".opus" - elif msg_type == "media": - ext = ".mp4" - else: - ext = "" + ext = {"audio": ".opus", "media": ".mp4"}.get(msg_type, "") filename = f"{file_key[:16]}{ext}" if data and filename: file_path = media_dir / filename - file_path.write_bytes(data) - logger.debug("Downloaded {} to {}", msg_type, file_path) - return str(file_path), f"[{msg_type}: {filename}]" return None, f"[{msg_type}: download failed]" From b653183bb0f76b0f3e157506e9906398efe7c311 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 18:26:42 +0000 Subject: [PATCH 098/154] refactor(providers): move empty content sanitization to base class --- nanobot/providers/base.py | 40 ++++++++++++++++++++++++ nanobot/providers/custom_provider.py | 45 +-------------------------- nanobot/providers/litellm_provider.py | 2 +- 3 files changed, 42 insertions(+), 45 deletions(-) diff --git a/nanobot/providers/base.py b/nanobot/providers/base.py index c69c38b..eb1599a 100644 --- a/nanobot/providers/base.py +++ b/nanobot/providers/base.py @@ -39,6 +39,46 @@ class LLMProvider(ABC): def __init__(self, api_key: str | None = None, api_base: str | None = None): self.api_key = api_key self.api_base = api_base + + @staticmethod + def _sanitize_empty_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Replace empty text content that causes provider 400 errors. + + Empty content can appear when MCP tools return nothing. Most providers + reject empty-string content or empty text blocks in list content. + """ + result: list[dict[str, Any]] = [] + for msg in messages: + content = msg.get("content") + + if isinstance(content, str) and not content: + clean = dict(msg) + clean["content"] = None if (msg.get("role") == "assistant" and msg.get("tool_calls")) else "(empty)" + result.append(clean) + continue + + if isinstance(content, list): + filtered = [ + item for item in content + if not ( + isinstance(item, dict) + and item.get("type") in ("text", "input_text", "output_text") + and not item.get("text") + ) + ] + if len(filtered) != len(content): + clean = dict(msg) + if filtered: + clean["content"] = filtered + elif msg.get("role") == "assistant" and msg.get("tool_calls"): + clean["content"] = None + else: + clean["content"] = "(empty)" + result.append(clean) + continue + + result.append(msg) + return result @abstractmethod async def chat( diff --git a/nanobot/providers/custom_provider.py b/nanobot/providers/custom_provider.py index 9a0901c..a578d14 100644 --- a/nanobot/providers/custom_provider.py +++ b/nanobot/providers/custom_provider.py @@ -21,7 +21,7 @@ class CustomProvider(LLMProvider): model: str | None = None, max_tokens: int = 4096, temperature: float = 0.7) -> LLMResponse: kwargs: dict[str, Any] = { "model": model or self.default_model, - "messages": self._prevent_empty_text_blocks(messages), + "messages": self._sanitize_empty_content(messages), "max_tokens": max(1, max_tokens), "temperature": temperature, } @@ -50,46 +50,3 @@ class CustomProvider(LLMProvider): def get_default_model(self) -> str: return self.default_model - @staticmethod - def _prevent_empty_text_blocks(messages: list[dict[str, Any]]) -> list[dict[str, Any]]: - """Filter empty text content blocks that cause provider 400 errors. - - When MCP tools return empty content, messages may contain empty-string - text blocks. Most providers (OpenAI-compatible) reject these with 400. - This method filters them out before sending to the API. - """ - patched: list[dict[str, Any]] = [] - for msg in messages: - content = msg.get("content") - - # Empty string content - if isinstance(content, str) and content == "": - clean = dict(msg) - if msg.get("role") == "assistant" and msg.get("tool_calls"): - clean["content"] = None - else: - clean["content"] = "(empty)" - patched.append(clean) - continue - - # List content β€” filter out empty text items - if isinstance(content, list): - filtered = [ - item for item in content - if not (isinstance(item, dict) - and item.get("type") in {"text", "input_text", "output_text"} - and item.get("text") == "") - ] - if filtered != content: - clean = dict(msg) - if filtered: - clean["content"] = filtered - elif msg.get("role") == "assistant" and msg.get("tool_calls"): - clean["content"] = None - else: - clean["content"] = "(empty)" - patched.append(clean) - continue - - patched.append(msg) - return patched diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 784f02c..7402a2b 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -196,7 +196,7 @@ class LiteLLMProvider(LLMProvider): kwargs: dict[str, Any] = { "model": model, - "messages": self._sanitize_messages(messages), + "messages": self._sanitize_messages(self._sanitize_empty_content(messages)), "max_tokens": max_tokens, "temperature": temperature, } From 25f0a236fdeabd9bda9f4de1622ccdab77bd184f Mon Sep 17 00:00:00 2001 From: Re-bin Date: Sun, 22 Feb 2026 18:29:09 +0000 Subject: [PATCH 099/154] docs: fix MiniMax API key link --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 8399c45..f20e21f 100644 --- a/README.md +++ b/README.md @@ -593,7 +593,7 @@ Config file: `~/.nanobot/config.json` | `deepseek` | LLM (DeepSeek direct) | [platform.deepseek.com](https://platform.deepseek.com) | | `groq` | LLM + **Voice transcription** (Whisper) | [console.groq.com](https://console.groq.com) | | `gemini` | LLM (Gemini direct) | [aistudio.google.com](https://aistudio.google.com) | -| `minimax` | LLM (MiniMax direct) | [platform.minimax.io](https://platform.minimax.io) | +| `minimax` | LLM (MiniMax direct) | [platform.minimaxi.com](https://platform.minimaxi.com) | | `aihubmix` | LLM (API gateway, access to all models) | [aihubmix.com](https://aihubmix.com) | | `siliconflow` | LLM (SiliconFlow/η‘…εŸΊζ΅εŠ¨) | [siliconflow.cn](https://siliconflow.cn) | | `volcengine` | LLM (VolcEngine/η«ε±±εΌ•ζ“Ž) | [volcengine.com](https://www.volcengine.com) | From 4303026e0da53c5f0b819df33bf91adda8aa3ba5 Mon Sep 17 00:00:00 2001 From: Nikolas de Hor Date: Sun, 22 Feb 2026 22:01:16 -0300 Subject: [PATCH 100/154] fix: break Discord typing loop on persistent HTTP failure The typing indicator loop catches all exceptions with bare except/pass, so a permanent HTTP failure (client closed, auth error, etc.) causes the loop to spin every 8 seconds doing nothing until the channel is explicitly stopped. Log the error and exit the loop instead, letting the task clean up naturally. --- nanobot/channels/discord.py | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.py index 1d2d7a6..b9227fb 100644 --- a/nanobot/channels/discord.py +++ b/nanobot/channels/discord.py @@ -285,8 +285,11 @@ class DiscordChannel(BaseChannel): while self._running: try: await self._http.post(url, headers=headers) - except Exception: - pass + except asyncio.CancelledError: + return + except Exception as e: + logger.debug("Discord typing indicator failed for {}: {}", channel_id, e) + return await asyncio.sleep(8) self._typing_tasks[channel_id] = asyncio.create_task(typing_loop()) From 0c412b3728a430f3fed7daea753a23962ad84fa1 Mon Sep 17 00:00:00 2001 From: Yingwen Luo-LUOYW Date: Sun, 22 Feb 2026 23:13:09 +0800 Subject: [PATCH 101/154] feat(channels): add send_progress option to control progress message delivery Add a boolean config option `channels.sendProgress` (default: false) to control whether progress messages (marked with `_progress` metadata) are sent to chat channels. When disabled, progress messages are filtered out in the outbound dispatcher. --- nanobot/channels/manager.py | 3 +++ nanobot/config/schema.py | 1 + 2 files changed, 4 insertions(+) diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index 6fbab04..8a03883 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -193,6 +193,9 @@ class ChannelManager: timeout=1.0 ) + if msg.metadata.get("_progress") and not self.config.channels.send_progress: + continue + channel = self.channels.get(msg.channel) if channel: try: diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index 966d11d..bd602dc 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -168,6 +168,7 @@ class QQConfig(Base): class ChannelsConfig(Base): """Configuration for chat channels.""" + send_progress: bool = False whatsapp: WhatsAppConfig = Field(default_factory=WhatsAppConfig) telegram: TelegramConfig = Field(default_factory=TelegramConfig) discord: DiscordConfig = Field(default_factory=DiscordConfig) From 9025c7088fe834a75addc72efc00630174da911f Mon Sep 17 00:00:00 2001 From: Kim <150593189+KimGLee@users.noreply.github.com> Date: Mon, 23 Feb 2026 12:28:21 +0800 Subject: [PATCH 102/154] fix(heartbeat): route heartbeat runs to enabled chat context --- nanobot/cli/commands.py | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index f1f9b30..b2f6bd3 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -389,11 +389,36 @@ def gateway( return response cron.on_job = on_cron_job + # Create channel manager + channels = ChannelManager(config, bus) + + def _pick_heartbeat_target() -> tuple[str, str]: + """Pick a routable channel/chat target for heartbeat-triggered messages.""" + enabled = set(channels.enabled_channels) + # Prefer the most recently updated non-internal session on an enabled channel. + for item in session_manager.list_sessions(): + key = item.get("key") or "" + if ":" not in key: + continue + channel, chat_id = key.split(":", 1) + if channel in {"cli", "system"}: + continue + if channel in enabled and chat_id: + return channel, chat_id + # Fallback keeps prior behavior but remains explicit. + return "cli", "direct" + # Create heartbeat service async def on_heartbeat(prompt: str) -> str: """Execute heartbeat through the agent.""" - return await agent.process_direct(prompt, session_key="heartbeat") - + channel, chat_id = _pick_heartbeat_target() + return await agent.process_direct( + prompt, + session_key="heartbeat", + channel=channel, + chat_id=chat_id, + ) + heartbeat = HeartbeatService( workspace=config.workspace_path, on_heartbeat=on_heartbeat, @@ -401,9 +426,6 @@ def gateway( enabled=True ) - # Create channel manager - channels = ChannelManager(config, bus) - if channels.enabled_channels: console.print(f"[green]βœ“[/green] Channels enabled: {', '.join(channels.enabled_channels)}") else: From bc32e85c25f2366322626d6c8ff98574614be711 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 05:51:44 +0000 Subject: [PATCH 103/154] fix(memory): trigger consolidation by unconsolidated count, not total --- nanobot/agent/loop.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index b05ba90..0bd05a8 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -352,7 +352,8 @@ class AgentLoop: return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id, content="🐈 nanobot commands:\n/new β€” Start a new conversation\n/help β€” Show available commands") - if len(session.messages) > self.memory_window and session.key not in self._consolidating: + unconsolidated = len(session.messages) - session.last_consolidated + if (unconsolidated >= self.memory_window and session.key not in self._consolidating): self._consolidating.add(session.key) lock = self._get_consolidation_lock(session.key) From bfdae1b177ed486580416c768f7c91d059464eff Mon Sep 17 00:00:00 2001 From: yzchen Date: Mon, 23 Feb 2026 13:56:37 +0800 Subject: [PATCH 104/154] fix(heartbeat): make start idempotent and check exact OK token --- nanobot/heartbeat/service.py | 15 ++++++++++++- tests/test_heartbeat_service.py | 40 +++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 tests/test_heartbeat_service.py diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index 3c1a6aa..ab2bfac 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -1,6 +1,7 @@ """Heartbeat service - periodic agent wake-up to check for tasks.""" import asyncio +import re from pathlib import Path from typing import Any, Callable, Coroutine @@ -35,6 +36,15 @@ def _is_heartbeat_empty(content: str | None) -> bool: return True +def _is_heartbeat_ok_response(response: str | None) -> bool: + """Return True only for an exact HEARTBEAT_OK token (with simple markdown wrappers).""" + if not response: + return False + + normalized = re.sub(r"[\s`*_>\-]", "", response).upper() + return normalized == HEARTBEAT_OK_TOKEN.replace("_", "") + + class HeartbeatService: """ Periodic heartbeat service that wakes the agent to check for tasks. @@ -75,6 +85,9 @@ class HeartbeatService: if not self.enabled: logger.info("Heartbeat disabled") return + if self._running: + logger.warning("Heartbeat already running") + return self._running = True self._task = asyncio.create_task(self._run_loop()) @@ -115,7 +128,7 @@ class HeartbeatService: response = await self.on_heartbeat(HEARTBEAT_PROMPT) # Check if agent said "nothing to do" - if HEARTBEAT_OK_TOKEN.replace("_", "") in response.upper().replace("_", ""): + if _is_heartbeat_ok_response(response): logger.info("Heartbeat: OK (no action needed)") else: logger.info("Heartbeat: completed task") diff --git a/tests/test_heartbeat_service.py b/tests/test_heartbeat_service.py new file mode 100644 index 0000000..52d1b96 --- /dev/null +++ b/tests/test_heartbeat_service.py @@ -0,0 +1,40 @@ +import asyncio + +import pytest + +from nanobot.heartbeat.service import ( + HeartbeatService, + _is_heartbeat_ok_response, +) + + +def test_heartbeat_ok_response_requires_exact_token() -> None: + assert _is_heartbeat_ok_response("HEARTBEAT_OK") + assert _is_heartbeat_ok_response("`HEARTBEAT_OK`") + assert _is_heartbeat_ok_response("**HEARTBEAT_OK**") + + assert not _is_heartbeat_ok_response("HEARTBEAT_OK, done") + assert not _is_heartbeat_ok_response("done HEARTBEAT_OK") + assert not _is_heartbeat_ok_response("HEARTBEAT_NOT_OK") + + +@pytest.mark.asyncio +async def test_start_is_idempotent(tmp_path) -> None: + async def _on_heartbeat(_: str) -> str: + return "HEARTBEAT_OK" + + service = HeartbeatService( + workspace=tmp_path, + on_heartbeat=_on_heartbeat, + interval_s=9999, + enabled=True, + ) + + await service.start() + first_task = service._task + await service.start() + + assert service._task is first_task + + service.stop() + await asyncio.sleep(0) From df2c837e252b76a8d3a91bd8a64b8987089f6892 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 07:12:41 +0000 Subject: [PATCH 105/154] feat(channels): split send_progress into send_progress + send_tool_hints --- nanobot/agent/loop.py | 12 +++++++----- nanobot/channels/manager.py | 7 +++++-- nanobot/cli/commands.py | 19 +++++++++++++++++-- nanobot/config/schema.py | 3 ++- 4 files changed, 31 insertions(+), 10 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 0bd05a8..cd67bdc 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -27,7 +27,7 @@ from nanobot.providers.base import LLMProvider from nanobot.session.manager import Session, SessionManager if TYPE_CHECKING: - from nanobot.config.schema import ExecToolConfig + from nanobot.config.schema import ChannelsConfig, ExecToolConfig from nanobot.cron.service import CronService @@ -59,9 +59,11 @@ class AgentLoop: restrict_to_workspace: bool = False, session_manager: SessionManager | None = None, mcp_servers: dict | None = None, + channels_config: ChannelsConfig | None = None, ): from nanobot.config.schema import ExecToolConfig self.bus = bus + self.channels_config = channels_config self.provider = provider self.workspace = workspace self.model = model or provider.get_default_model() @@ -172,7 +174,7 @@ class AgentLoop: async def _run_agent_loop( self, initial_messages: list[dict], - on_progress: Callable[[str], Awaitable[None]] | None = None, + on_progress: Callable[..., Awaitable[None]] | None = None, ) -> tuple[str | None, list[str]]: """Run the agent iteration loop. Returns (final_content, tools_used).""" messages = initial_messages @@ -196,8 +198,7 @@ class AgentLoop: clean = self._strip_think(response.content) if clean: await on_progress(clean) - else: - await on_progress(self._tool_hint(response.tool_calls)) + await on_progress(self._tool_hint(response.tool_calls), tool_hint=True) tool_call_dicts = [ { @@ -383,9 +384,10 @@ class AgentLoop: channel=msg.channel, chat_id=msg.chat_id, ) - async def _bus_progress(content: str) -> None: + async def _bus_progress(content: str, *, tool_hint: bool = False) -> None: meta = dict(msg.metadata or {}) meta["_progress"] = True + meta["_tool_hint"] = tool_hint await self.bus.publish_outbound(OutboundMessage( channel=msg.channel, chat_id=msg.chat_id, content=content, metadata=meta, )) diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.py index 8a03883..77b7294 100644 --- a/nanobot/channels/manager.py +++ b/nanobot/channels/manager.py @@ -193,8 +193,11 @@ class ChannelManager: timeout=1.0 ) - if msg.metadata.get("_progress") and not self.config.channels.send_progress: - continue + if msg.metadata.get("_progress"): + if msg.metadata.get("_tool_hint") and not self.config.channels.send_tool_hints: + continue + if not msg.metadata.get("_tool_hint") and not self.config.channels.send_progress: + continue channel = self.channels.get(msg.channel) if channel: diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index f1f9b30..fcbd370 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -368,6 +368,7 @@ def gateway( restrict_to_workspace=config.tools.restrict_to_workspace, session_manager=session_manager, mcp_servers=config.tools.mcp_servers, + channels_config=config.channels, ) # Set cron callback (needs agent) @@ -484,6 +485,7 @@ def agent( cron_service=cron, restrict_to_workspace=config.tools.restrict_to_workspace, mcp_servers=config.tools.mcp_servers, + channels_config=config.channels, ) # Show spinner when logs are off (no output to miss); skip when logs are on @@ -494,7 +496,12 @@ def agent( # Animated spinner is safe to use with prompt_toolkit input handling return console.status("[dim]nanobot is thinking...[/dim]", spinner="dots") - async def _cli_progress(content: str) -> None: + async def _cli_progress(content: str, *, tool_hint: bool = False) -> None: + ch = agent_loop.channels_config + if ch and tool_hint and not ch.send_tool_hints: + return + if ch and not tool_hint and not ch.send_progress: + return console.print(f" [dim]↳ {content}[/dim]") if message: @@ -535,7 +542,14 @@ def agent( try: msg = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0) if msg.metadata.get("_progress"): - console.print(f" [dim]↳ {msg.content}[/dim]") + is_tool_hint = msg.metadata.get("_tool_hint", False) + ch = agent_loop.channels_config + if ch and is_tool_hint and not ch.send_tool_hints: + pass + elif ch and not is_tool_hint and not ch.send_progress: + pass + else: + console.print(f" [dim]↳ {msg.content}[/dim]") elif not turn_done.is_set(): if msg.content: turn_response.append(msg.content) @@ -961,6 +975,7 @@ def cron_run( exec_config=config.tools.exec, restrict_to_workspace=config.tools.restrict_to_workspace, mcp_servers=config.tools.mcp_servers, + channels_config=config.channels, ) store_path = get_data_dir() / "cron" / "jobs.json" diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index fc9fede..9265602 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -168,7 +168,8 @@ class QQConfig(Base): class ChannelsConfig(Base): """Configuration for chat channels.""" - send_progress: bool = False + send_progress: bool = True # stream agent's text progress to the channel + send_tool_hints: bool = False # stream tool-call hints (e.g. read_file("…")) whatsapp: WhatsAppConfig = Field(default_factory=WhatsAppConfig) telegram: TelegramConfig = Field(default_factory=TelegramConfig) discord: DiscordConfig = Field(default_factory=DiscordConfig) From 577b3d104a2f2e55e91e89ddbcbf154c760ece4c Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 08:08:01 +0000 Subject: [PATCH 106/154] refactor: move workspace/ to nanobot/templates/ for packaging --- README.md | 20 +++ nanobot/cli/commands.py | 80 ++-------- nanobot/templates/AGENTS.md | 29 ++++ {workspace => nanobot/templates}/HEARTBEAT.md | 0 {workspace => nanobot/templates}/SOUL.md | 0 nanobot/templates/TOOLS.md | 36 +++++ {workspace => nanobot/templates}/USER.md | 0 nanobot/templates/__init__.py | 0 .../templates}/memory/MEMORY.md | 0 nanobot/templates/memory/__init__.py | 0 pyproject.toml | 3 +- workspace/AGENTS.md | 51 ------ workspace/TOOLS.md | 150 ------------------ 13 files changed, 102 insertions(+), 267 deletions(-) create mode 100644 nanobot/templates/AGENTS.md rename {workspace => nanobot/templates}/HEARTBEAT.md (100%) rename {workspace => nanobot/templates}/SOUL.md (100%) create mode 100644 nanobot/templates/TOOLS.md rename {workspace => nanobot/templates}/USER.md (100%) create mode 100644 nanobot/templates/__init__.py rename {workspace => nanobot/templates}/memory/MEMORY.md (100%) create mode 100644 nanobot/templates/memory/__init__.py delete mode 100644 workspace/AGENTS.md delete mode 100644 workspace/TOOLS.md diff --git a/README.md b/README.md index f20e21f..8c47f0f 100644 --- a/README.md +++ b/README.md @@ -841,6 +841,26 @@ nanobot cron remove +
+Heartbeat (Periodic Tasks) + +The gateway wakes up every 30 minutes and checks `HEARTBEAT.md` in your workspace (`~/.nanobot/workspace/HEARTBEAT.md`). If the file has tasks, the agent executes them and delivers results to your most recently active chat channel. + +**Setup:** edit `~/.nanobot/workspace/HEARTBEAT.md` (created automatically by `nanobot onboard`): + +```markdown +## Periodic Tasks + +- [ ] Check weather forecast and send a summary +- [ ] Scan inbox for urgent emails +``` + +The agent can also manage this file itself β€” ask it to "add a periodic task" and it will update `HEARTBEAT.md` for you. + +> **Note:** The gateway must be running (`nanobot gateway`) and you must have chatted with the bot at least once so it knows which channel to deliver to. + +
+ ## 🐳 Docker > [!TIP] diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index c8948ee..5edebfa 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -199,84 +199,34 @@ def onboard(): def _create_workspace_templates(workspace: Path): - """Create default workspace template files.""" - templates = { - "AGENTS.md": """# Agent Instructions + """Create default workspace template files from bundled templates.""" + from importlib.resources import files as pkg_files -You are a helpful AI assistant. Be concise, accurate, and friendly. + templates_dir = pkg_files("nanobot") / "templates" -## Guidelines + for item in templates_dir.iterdir(): + if not item.name.endswith(".md"): + continue + dest = workspace / item.name + if not dest.exists(): + dest.write_text(item.read_text(encoding="utf-8"), encoding="utf-8") + console.print(f" [dim]Created {item.name}[/dim]") -- Always explain what you're doing before taking actions -- Ask for clarification when the request is ambiguous -- Use tools to help accomplish tasks -- Remember important information in memory/MEMORY.md; past events are logged in memory/HISTORY.md -""", - "SOUL.md": """# Soul - -I am nanobot, a lightweight AI assistant. - -## Personality - -- Helpful and friendly -- Concise and to the point -- Curious and eager to learn - -## Values - -- Accuracy over speed -- User privacy and safety -- Transparency in actions -""", - "USER.md": """# User - -Information about the user goes here. - -## Preferences - -- Communication style: (casual/formal) -- Timezone: (your timezone) -- Language: (your preferred language) -""", - } - - for filename, content in templates.items(): - file_path = workspace / filename - if not file_path.exists(): - file_path.write_text(content, encoding="utf-8") - console.print(f" [dim]Created {filename}[/dim]") - - # Create memory directory and MEMORY.md memory_dir = workspace / "memory" memory_dir.mkdir(exist_ok=True) + + memory_template = templates_dir / "memory" / "MEMORY.md" memory_file = memory_dir / "MEMORY.md" if not memory_file.exists(): - memory_file.write_text("""# Long-term Memory - -This file stores important information that should persist across sessions. - -## User Information - -(Important facts about the user) - -## Preferences - -(User preferences learned over time) - -## Important Notes - -(Things to remember) -""", encoding="utf-8") + memory_file.write_text(memory_template.read_text(encoding="utf-8"), encoding="utf-8") console.print(" [dim]Created memory/MEMORY.md[/dim]") - + history_file = memory_dir / "HISTORY.md" if not history_file.exists(): history_file.write_text("", encoding="utf-8") console.print(" [dim]Created memory/HISTORY.md[/dim]") - # Create skills directory for custom user skills - skills_dir = workspace / "skills" - skills_dir.mkdir(exist_ok=True) + (workspace / "skills").mkdir(exist_ok=True) def _make_provider(config: Config): diff --git a/nanobot/templates/AGENTS.md b/nanobot/templates/AGENTS.md new file mode 100644 index 0000000..155a0b2 --- /dev/null +++ b/nanobot/templates/AGENTS.md @@ -0,0 +1,29 @@ +# Agent Instructions + +You are a helpful AI assistant. Be concise, accurate, and friendly. + +## Guidelines + +- Always explain what you're doing before taking actions +- Ask for clarification when the request is ambiguous +- Remember important information in `memory/MEMORY.md`; past events are logged in `memory/HISTORY.md` + +## Scheduled Reminders + +When user asks for a reminder at a specific time, use `exec` to run: +``` +nanobot cron add --name "reminder" --message "Your message" --at "YYYY-MM-DDTHH:MM:SS" --deliver --to "USER_ID" --channel "CHANNEL" +``` +Get USER_ID and CHANNEL from the current session (e.g., `8281248569` and `telegram` from `telegram:8281248569`). + +**Do NOT just write reminders to MEMORY.md** β€” that won't trigger actual notifications. + +## Heartbeat Tasks + +`HEARTBEAT.md` is checked every 30 minutes. Use file tools to manage periodic tasks: + +- **Add**: `edit_file` to append new tasks +- **Remove**: `edit_file` to delete completed tasks +- **Rewrite**: `write_file` to replace all tasks + +When the user asks for a recurring/periodic task, update `HEARTBEAT.md` instead of creating a one-time cron reminder. diff --git a/workspace/HEARTBEAT.md b/nanobot/templates/HEARTBEAT.md similarity index 100% rename from workspace/HEARTBEAT.md rename to nanobot/templates/HEARTBEAT.md diff --git a/workspace/SOUL.md b/nanobot/templates/SOUL.md similarity index 100% rename from workspace/SOUL.md rename to nanobot/templates/SOUL.md diff --git a/nanobot/templates/TOOLS.md b/nanobot/templates/TOOLS.md new file mode 100644 index 0000000..757edd2 --- /dev/null +++ b/nanobot/templates/TOOLS.md @@ -0,0 +1,36 @@ +# Tool Usage Notes + +Tool signatures are provided automatically via function calling. +This file documents non-obvious constraints and usage patterns. + +## exec β€” Safety Limits + +- Commands have a configurable timeout (default 60s) +- Dangerous commands are blocked (rm -rf, format, dd, shutdown, etc.) +- Output is truncated at 10,000 characters +- `restrictToWorkspace` config can limit file access to the workspace + +## Cron β€” Scheduled Reminders + +Use `exec` to create scheduled reminders: + +```bash +# Recurring: every day at 9am +nanobot cron add --name "morning" --message "Good morning!" --cron "0 9 * * *" + +# With timezone (--tz only works with --cron) +nanobot cron add --name "standup" --message "Standup time!" --cron "0 10 * * 1-5" --tz "Asia/Shanghai" + +# Recurring: every 2 hours +nanobot cron add --name "water" --message "Drink water!" --every 7200 + +# One-time: specific ISO time +nanobot cron add --name "meeting" --message "Meeting starts now!" --at "2025-01-31T15:00:00" + +# Deliver to a specific channel/user +nanobot cron add --name "reminder" --message "Check email" --at "2025-01-31T09:00:00" --deliver --to "USER_ID" --channel "CHANNEL" + +# Manage jobs +nanobot cron list +nanobot cron remove +``` diff --git a/workspace/USER.md b/nanobot/templates/USER.md similarity index 100% rename from workspace/USER.md rename to nanobot/templates/USER.md diff --git a/nanobot/templates/__init__.py b/nanobot/templates/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/workspace/memory/MEMORY.md b/nanobot/templates/memory/MEMORY.md similarity index 100% rename from workspace/memory/MEMORY.md rename to nanobot/templates/memory/MEMORY.md diff --git a/nanobot/templates/memory/__init__.py b/nanobot/templates/memory/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pyproject.toml b/pyproject.toml index c337d02..cb58ec5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,10 +64,11 @@ packages = ["nanobot"] [tool.hatch.build.targets.wheel.sources] "nanobot" = "nanobot" -# Include non-Python files in skills +# Include non-Python files in skills and templates [tool.hatch.build] include = [ "nanobot/**/*.py", + "nanobot/templates/**/*.md", "nanobot/skills/**/*.md", "nanobot/skills/**/*.sh", ] diff --git a/workspace/AGENTS.md b/workspace/AGENTS.md deleted file mode 100644 index 69bd823..0000000 --- a/workspace/AGENTS.md +++ /dev/null @@ -1,51 +0,0 @@ -# Agent Instructions - -You are a helpful AI assistant. Be concise, accurate, and friendly. - -## Guidelines - -- Always explain what you're doing before taking actions -- Ask for clarification when the request is ambiguous -- Use tools to help accomplish tasks -- Remember important information in your memory files - -## Tools Available - -You have access to: -- File operations (read, write, edit, list) -- Shell commands (exec) -- Web access (search, fetch) -- Messaging (message) -- Background tasks (spawn) - -## Memory - -- `memory/MEMORY.md` β€” long-term facts (preferences, context, relationships) -- `memory/HISTORY.md` β€” append-only event log, search with grep to recall past events - -## Scheduled Reminders - -When user asks for a reminder at a specific time, use `exec` to run: -``` -nanobot cron add --name "reminder" --message "Your message" --at "YYYY-MM-DDTHH:MM:SS" --deliver --to "USER_ID" --channel "CHANNEL" -``` -Get USER_ID and CHANNEL from the current session (e.g., `8281248569` and `telegram` from `telegram:8281248569`). - -**Do NOT just write reminders to MEMORY.md** β€” that won't trigger actual notifications. - -## Heartbeat Tasks - -`HEARTBEAT.md` is checked every 30 minutes. You can manage periodic tasks by editing this file: - -- **Add a task**: Use `edit_file` to append new tasks to `HEARTBEAT.md` -- **Remove a task**: Use `edit_file` to remove completed or obsolete tasks -- **Rewrite tasks**: Use `write_file` to completely rewrite the task list - -Task format examples: -``` -- [ ] Check calendar and remind of upcoming events -- [ ] Scan inbox for urgent emails -- [ ] Check weather forecast for today -``` - -When the user asks you to add a recurring/periodic task, update `HEARTBEAT.md` instead of creating a one-time reminder. Keep the file small to minimize token usage. diff --git a/workspace/TOOLS.md b/workspace/TOOLS.md deleted file mode 100644 index 0134a64..0000000 --- a/workspace/TOOLS.md +++ /dev/null @@ -1,150 +0,0 @@ -# Available Tools - -This document describes the tools available to nanobot. - -## File Operations - -### read_file -Read the contents of a file. -``` -read_file(path: str) -> str -``` - -### write_file -Write content to a file (creates parent directories if needed). -``` -write_file(path: str, content: str) -> str -``` - -### edit_file -Edit a file by replacing specific text. -``` -edit_file(path: str, old_text: str, new_text: str) -> str -``` - -### list_dir -List contents of a directory. -``` -list_dir(path: str) -> str -``` - -## Shell Execution - -### exec -Execute a shell command and return output. -``` -exec(command: str, working_dir: str = None) -> str -``` - -**Safety Notes:** -- Commands have a configurable timeout (default 60s) -- Dangerous commands are blocked (rm -rf, format, dd, shutdown, etc.) -- Output is truncated at 10,000 characters -- Optional `restrictToWorkspace` config to limit paths - -## Web Access - -### web_search -Search the web using Brave Search API. -``` -web_search(query: str, count: int = 5) -> str -``` - -Returns search results with titles, URLs, and snippets. Requires `tools.web.search.apiKey` in config. - -### web_fetch -Fetch and extract main content from a URL. -``` -web_fetch(url: str, extractMode: str = "markdown", maxChars: int = 50000) -> str -``` - -**Notes:** -- Content is extracted using readability -- Supports markdown or plain text extraction -- Output is truncated at 50,000 characters by default - -## Communication - -### message -Send a message to the user (used internally). -``` -message(content: str, channel: str = None, chat_id: str = None) -> str -``` - -## Background Tasks - -### spawn -Spawn a subagent to handle a task in the background. -``` -spawn(task: str, label: str = None) -> str -``` - -Use for complex or time-consuming tasks that can run independently. The subagent will complete the task and report back when done. - -## Scheduled Reminders (Cron) - -Use the `exec` tool to create scheduled reminders with `nanobot cron add`: - -### Set a recurring reminder -```bash -# Every day at 9am -nanobot cron add --name "morning" --message "Good morning! β˜€οΈ" --cron "0 9 * * *" - -# Every 2 hours -nanobot cron add --name "water" --message "Drink water! πŸ’§" --every 7200 -``` - -### Set a one-time reminder -```bash -# At a specific time (ISO format) -nanobot cron add --name "meeting" --message "Meeting starts now!" --at "2025-01-31T15:00:00" -``` - -### Manage reminders -```bash -nanobot cron list # List all jobs -nanobot cron remove # Remove a job -``` - -## Heartbeat Task Management - -The `HEARTBEAT.md` file in the workspace is checked every 30 minutes. -Use file operations to manage periodic tasks: - -### Add a heartbeat task -```python -# Append a new task -edit_file( - path="HEARTBEAT.md", - old_text="## Example Tasks", - new_text="- [ ] New periodic task here\n\n## Example Tasks" -) -``` - -### Remove a heartbeat task -```python -# Remove a specific task -edit_file( - path="HEARTBEAT.md", - old_text="- [ ] Task to remove\n", - new_text="" -) -``` - -### Rewrite all tasks -```python -# Replace the entire file -write_file( - path="HEARTBEAT.md", - content="# Heartbeat Tasks\n\n- [ ] Task 1\n- [ ] Task 2\n" -) -``` - ---- - -## Adding Custom Tools - -To add custom tools: -1. Create a class that extends `Tool` in `nanobot/agent/tools/` -2. Implement `name`, `description`, `parameters`, and `execute` -3. Register it in `AgentLoop._register_default_tools()` From 491739223d8a5e8bfea0fc040971dffb8a6f3d0f Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 08:24:53 +0000 Subject: [PATCH 107/154] fix: lower default temperature from 0.7 to 0.1 --- nanobot/agent/loop.py | 2 +- nanobot/config/schema.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index cd67bdc..296c908 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -50,7 +50,7 @@ class AgentLoop: workspace: Path, model: str | None = None, max_iterations: int = 20, - temperature: float = 0.7, + temperature: float = 0.1, max_tokens: int = 4096, memory_window: int = 50, brave_api_key: str | None = None, diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index 9265602..10e3fa5 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -187,7 +187,7 @@ class AgentDefaults(Base): workspace: str = "~/.nanobot/workspace" model: str = "anthropic/claude-opus-4-5" max_tokens: int = 8192 - temperature: float = 0.7 + temperature: float = 0.1 max_tool_iterations: int = 20 memory_window: int = 50 From d9462284e1549f86570874096e2e4ea343a7bc17 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 09:13:08 +0000 Subject: [PATCH 108/154] improve agent reliability: behavioral constraints, full tool history, error hints --- README.md | 2 +- nanobot/agent/context.py | 18 +++++++----- nanobot/agent/loop.py | 49 +++++++++++++++++++++++---------- nanobot/agent/tools/registry.py | 13 ++++++--- nanobot/config/schema.py | 4 +-- 5 files changed, 58 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index 8c47f0f..148c8f4 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ ⚑️ Delivers core agent functionality in just **~4,000** lines of code β€” **99% smaller** than Clawdbot's 430k+ lines. -πŸ“ Real-time line count: **3,862 lines** (run `bash core_agent_lines.sh` to verify anytime) +πŸ“ Real-time line count: **3,897 lines** (run `bash core_agent_lines.sh` to verify anytime) ## πŸ“’ News diff --git a/nanobot/agent/context.py b/nanobot/agent/context.py index c5869f3..98c13f2 100644 --- a/nanobot/agent/context.py +++ b/nanobot/agent/context.py @@ -96,14 +96,18 @@ Your workspace is at: {workspace_path} - History log: {workspace_path}/memory/HISTORY.md (grep-searchable) - Custom skills: {workspace_path}/skills/{{skill-name}}/SKILL.md -IMPORTANT: When responding to direct questions or conversations, reply directly with your text response. -Only use the 'message' tool when you need to send a message to a specific chat channel (like WhatsApp). -For normal conversation, just respond with text - do not call the message tool. +Reply directly with text for conversations. Only use the 'message' tool to send to a specific chat channel. -Always be helpful, accurate, and concise. Before calling tools, briefly tell the user what you're about to do (one short sentence in the user's language). -If you need to use tools, call them directly β€” never send a preliminary message like "Let me check" without actually calling a tool. -When remembering something important, write to {workspace_path}/memory/MEMORY.md -To recall past events, grep {workspace_path}/memory/HISTORY.md""" +## Tool Call Guidelines +- Before calling tools, you may briefly state your intent (e.g. "Let me check that"), but NEVER predict or describe the expected result before receiving it. +- Before modifying a file, read it first to confirm its current content. +- Do not assume a file or directory exists β€” use list_dir or read_file to verify. +- After writing or editing a file, re-read it if accuracy matters. +- If a tool call fails, analyze the error before retrying with a different approach. + +## Memory +- Remember important facts: write to {workspace_path}/memory/MEMORY.md +- Recall past events: grep {workspace_path}/memory/HISTORY.md""" def _load_bootstrap_files(self) -> str: """Load all bootstrap files from workspace.""" diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 296c908..8be8e51 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -49,10 +49,10 @@ class AgentLoop: provider: LLMProvider, workspace: Path, model: str | None = None, - max_iterations: int = 20, + max_iterations: int = 40, temperature: float = 0.1, max_tokens: int = 4096, - memory_window: int = 50, + memory_window: int = 100, brave_api_key: str | None = None, exec_config: ExecToolConfig | None = None, cron_service: CronService | None = None, @@ -175,8 +175,8 @@ class AgentLoop: self, initial_messages: list[dict], on_progress: Callable[..., Awaitable[None]] | None = None, - ) -> tuple[str | None, list[str]]: - """Run the agent iteration loop. Returns (final_content, tools_used).""" + ) -> tuple[str | None, list[str], list[dict]]: + """Run the agent iteration loop. Returns (final_content, tools_used, messages).""" messages = initial_messages iteration = 0 final_content = None @@ -228,7 +228,14 @@ class AgentLoop: final_content = self._strip_think(response.content) break - return final_content, tools_used + if final_content is None and iteration >= self.max_iterations: + logger.warning("Max iterations ({}) reached", self.max_iterations) + final_content = ( + f"I reached the maximum number of tool call iterations ({self.max_iterations}) " + "without completing the task. You can try breaking the task into smaller steps." + ) + + return final_content, tools_used, messages async def run(self) -> None: """Run the agent loop, processing messages from the bus.""" @@ -301,13 +308,13 @@ class AgentLoop: key = f"{channel}:{chat_id}" session = self.sessions.get_or_create(key) self._set_tool_context(channel, chat_id, msg.metadata.get("message_id")) + history = session.get_history(max_messages=self.memory_window) messages = self.context.build_messages( - history=session.get_history(max_messages=self.memory_window), + history=history, current_message=msg.content, channel=channel, chat_id=chat_id, ) - final_content, _ = await self._run_agent_loop(messages) - session.add_message("user", f"[System: {msg.sender_id}] {msg.content}") - session.add_message("assistant", final_content or "Background task completed.") + final_content, _, all_msgs = await self._run_agent_loop(messages) + self._save_turn(session, all_msgs, 1 + len(history)) self.sessions.save(session) return OutboundMessage(channel=channel, chat_id=chat_id, content=final_content or "Background task completed.") @@ -377,8 +384,9 @@ class AgentLoop: if isinstance(message_tool, MessageTool): message_tool.start_turn() + history = session.get_history(max_messages=self.memory_window) initial_messages = self.context.build_messages( - history=session.get_history(max_messages=self.memory_window), + history=history, current_message=msg.content, media=msg.media if msg.media else None, channel=msg.channel, chat_id=msg.chat_id, @@ -392,7 +400,7 @@ class AgentLoop: channel=msg.channel, chat_id=msg.chat_id, content=content, metadata=meta, )) - final_content, tools_used = await self._run_agent_loop( + final_content, _, all_msgs = await self._run_agent_loop( initial_messages, on_progress=on_progress or _bus_progress, ) @@ -402,9 +410,7 @@ class AgentLoop: preview = final_content[:120] + "..." if len(final_content) > 120 else final_content logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview) - session.add_message("user", msg.content) - session.add_message("assistant", final_content, - tools_used=tools_used if tools_used else None) + self._save_turn(session, all_msgs, 1 + len(history)) self.sessions.save(session) if message_tool := self.tools.get("message"): @@ -416,6 +422,21 @@ class AgentLoop: metadata=msg.metadata or {}, ) + _TOOL_RESULT_MAX_CHARS = 500 + + def _save_turn(self, session: Session, messages: list[dict], skip: int) -> None: + """Save new-turn messages into session, truncating large tool results.""" + from datetime import datetime + for m in messages[skip:]: + entry = {k: v for k, v in m.items() if k != "reasoning_content"} + if entry.get("role") == "tool" and isinstance(entry.get("content"), str): + content = entry["content"] + if len(content) > self._TOOL_RESULT_MAX_CHARS: + entry["content"] = content[:self._TOOL_RESULT_MAX_CHARS] + "\n... (truncated)" + entry.setdefault("timestamp", datetime.now().isoformat()) + session.messages.append(entry) + session.updated_at = datetime.now() + async def _consolidate_memory(self, session, archive_all: bool = False) -> bool: """Delegate to MemoryStore.consolidate(). Returns True on success.""" return await MemoryStore(self.workspace).consolidate( diff --git a/nanobot/agent/tools/registry.py b/nanobot/agent/tools/registry.py index d9b33ff..8256a59 100644 --- a/nanobot/agent/tools/registry.py +++ b/nanobot/agent/tools/registry.py @@ -49,17 +49,22 @@ class ToolRegistry: Raises: KeyError: If tool not found. """ + _HINT = "\n\n[Analyze the error above and try a different approach.]" + tool = self._tools.get(name) if not tool: - return f"Error: Tool '{name}' not found" + return f"Error: Tool '{name}' not found. Available: {', '.join(self.tool_names)}" try: errors = tool.validate_params(params) if errors: - return f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors) - return await tool.execute(**params) + return f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors) + _HINT + result = await tool.execute(**params) + if isinstance(result, str) and result.startswith("Error"): + return result + _HINT + return result except Exception as e: - return f"Error executing {name}: {str(e)}" + return f"Error executing {name}: {str(e)}" + _HINT @property def tool_names(self) -> list[str]: diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index 10e3fa5..fe8dd83 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -188,8 +188,8 @@ class AgentDefaults(Base): model: str = "anthropic/claude-opus-4-5" max_tokens: int = 8192 temperature: float = 0.1 - max_tool_iterations: int = 20 - memory_window: int = 50 + max_tool_iterations: int = 40 + memory_window: int = 100 class AgentsConfig(Base): From 1f7a81e5eebafad5e21c5760a92880c3155bcefe Mon Sep 17 00:00:00 2001 From: Paul Date: Mon, 23 Feb 2026 10:15:12 +0000 Subject: [PATCH 109/154] feat(slack): isolate session context per thread Each Slack thread now gets its own conversation session instead of sharing one session per channel. DM sessions are unchanged. Added as a generic feature to also support if Feishu threads support is added in the future. --- nanobot/bus/events.py | 3 ++- nanobot/channels/base.py | 4 +++- nanobot/channels/slack.py | 6 +++++- 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/nanobot/bus/events.py b/nanobot/bus/events.py index a149e20..a48660d 100644 --- a/nanobot/bus/events.py +++ b/nanobot/bus/events.py @@ -16,11 +16,12 @@ class InboundMessage: timestamp: datetime = field(default_factory=datetime.now) media: list[str] = field(default_factory=list) # Media URLs metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data + session_key_override: str | None = None # Optional override for thread-scoped sessions @property def session_key(self) -> str: """Unique key for session identification.""" - return f"{self.channel}:{self.chat_id}" + return self.session_key_override or f"{self.channel}:{self.chat_id}" @dataclass diff --git a/nanobot/channels/base.py b/nanobot/channels/base.py index 3a5a785..2201686 100644 --- a/nanobot/channels/base.py +++ b/nanobot/channels/base.py @@ -111,13 +111,15 @@ class BaseChannel(ABC): ) return + meta = metadata or {} msg = InboundMessage( channel=self.name, sender_id=str(sender_id), chat_id=str(chat_id), content=content, media=media or [], - metadata=metadata or {} + metadata=meta, + session_key_override=meta.get("session_key"), ) await self.bus.publish_inbound(msg) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index b0f9bbb..2e91f7b 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -179,6 +179,9 @@ class SlackChannel(BaseChannel): except Exception as e: logger.debug("Slack reactions_add failed: {}", e) + # Thread-scoped session key for channel/group messages + session_key = f"slack:{chat_id}:{thread_ts}" if thread_ts and channel_type != "im" else None + try: await self._handle_message( sender_id=sender_id, @@ -189,7 +192,8 @@ class SlackChannel(BaseChannel): "event": event, "thread_ts": thread_ts, "channel_type": channel_type, - } + }, + "session_key": session_key, }, ) except Exception: From ea1c4ef02566a94d9d2c9593698a626365e183de Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 12:33:29 +0000 Subject: [PATCH 110/154] fix: suppress heartbeat progress messages to external channels --- nanobot/cli/commands.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 5edebfa..e1df6ad 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -363,11 +363,17 @@ def gateway( async def on_heartbeat(prompt: str) -> str: """Execute heartbeat through the agent.""" channel, chat_id = _pick_heartbeat_target() + + async def _silent(*_args, **_kwargs): + pass + return await agent.process_direct( prompt, session_key="heartbeat", channel=channel, chat_id=chat_id, + # suppress: heartbeat should not push progress to external channels + on_progress=_silent, ) heartbeat = HeartbeatService( From 2b983c708dc0f99ad8402b1eaafdf2b14894eeeb Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 13:10:47 +0000 Subject: [PATCH 111/154] refactor: pass session_key as explicit param instead of via metadata --- nanobot/channels/base.py | 9 +++++---- nanobot/channels/slack.py | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/nanobot/channels/base.py b/nanobot/channels/base.py index 2201686..3010373 100644 --- a/nanobot/channels/base.py +++ b/nanobot/channels/base.py @@ -89,7 +89,8 @@ class BaseChannel(ABC): chat_id: str, content: str, media: list[str] | None = None, - metadata: dict[str, Any] | None = None + metadata: dict[str, Any] | None = None, + session_key: str | None = None, ) -> None: """ Handle an incoming message from the chat platform. @@ -102,6 +103,7 @@ class BaseChannel(ABC): content: Message text content. media: Optional list of media URLs. metadata: Optional channel-specific metadata. + session_key: Optional session key override (e.g. thread-scoped sessions). """ if not self.is_allowed(sender_id): logger.warning( @@ -111,15 +113,14 @@ class BaseChannel(ABC): ) return - meta = metadata or {} msg = InboundMessage( channel=self.name, sender_id=str(sender_id), chat_id=str(chat_id), content=content, media=media or [], - metadata=meta, - session_key_override=meta.get("session_key"), + metadata=metadata or {}, + session_key_override=session_key, ) await self.bus.publish_inbound(msg) diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.py index 2e91f7b..906593b 100644 --- a/nanobot/channels/slack.py +++ b/nanobot/channels/slack.py @@ -193,8 +193,8 @@ class SlackChannel(BaseChannel): "thread_ts": thread_ts, "channel_type": channel_type, }, - "session_key": session_key, }, + session_key=session_key, ) except Exception: logger.exception("Error handling Slack message from {}", sender_id) From 7671239902f479c8c0b60aac53454e6ef8f28146 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 13:45:09 +0000 Subject: [PATCH 112/154] fix(heartbeat): suppress progress messages and deliver agent response to user --- nanobot/cli/commands.py | 12 +++++++++-- nanobot/heartbeat/service.py | 40 ++++++++++++++++++++---------------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index e1df6ad..90b9f44 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -372,13 +372,21 @@ def gateway( session_key="heartbeat", channel=channel, chat_id=chat_id, - # suppress: heartbeat should not push progress to external channels - on_progress=_silent, + on_progress=_silent, # suppress: heartbeat should not push progress to external channels ) + async def on_heartbeat_notify(response: str) -> None: + """Deliver a heartbeat response to the user's channel.""" + from nanobot.bus.events import OutboundMessage + channel, chat_id = _pick_heartbeat_target() + if channel == "cli": + return # No external channel available to deliver to + await bus.publish_outbound(OutboundMessage(channel=channel, chat_id=chat_id, content=response)) + heartbeat = HeartbeatService( workspace=config.workspace_path, on_heartbeat=on_heartbeat, + on_notify=on_heartbeat_notify, interval_s=30 * 60, # 30 minutes enabled=True ) diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index 3c1a6aa..7dbdc03 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -9,14 +9,15 @@ from loguru import logger # Default interval: 30 minutes DEFAULT_HEARTBEAT_INTERVAL_S = 30 * 60 -# The prompt sent to agent during heartbeat -HEARTBEAT_PROMPT = """Read HEARTBEAT.md in your workspace (if it exists). -Follow any instructions or tasks listed there. -If nothing needs attention, reply with just: HEARTBEAT_OK""" - -# Token that indicates "nothing to do" +# Token the agent replies with when there is nothing to report HEARTBEAT_OK_TOKEN = "HEARTBEAT_OK" +# The prompt sent to agent during heartbeat +HEARTBEAT_PROMPT = ( + "Read HEARTBEAT.md in your workspace and follow any instructions listed there. " + f"If nothing needs attention, reply with exactly: {HEARTBEAT_OK_TOKEN}" +) + def _is_heartbeat_empty(content: str | None) -> bool: """Check if HEARTBEAT.md has no actionable content.""" @@ -38,20 +39,24 @@ def _is_heartbeat_empty(content: str | None) -> bool: class HeartbeatService: """ Periodic heartbeat service that wakes the agent to check for tasks. - - The agent reads HEARTBEAT.md from the workspace and executes any - tasks listed there. If nothing needs attention, it replies HEARTBEAT_OK. + + The agent reads HEARTBEAT.md from the workspace and executes any tasks + listed there. If it has something to report, the response is forwarded + to the user via on_notify. If nothing needs attention, the agent replies + HEARTBEAT_OK and the response is silently dropped. """ - + def __init__( self, workspace: Path, on_heartbeat: Callable[[str], Coroutine[Any, Any, str]] | None = None, + on_notify: Callable[[str], Coroutine[Any, Any, None]] | None = None, interval_s: int = DEFAULT_HEARTBEAT_INTERVAL_S, enabled: bool = True, ): self.workspace = workspace self.on_heartbeat = on_heartbeat + self.on_notify = on_notify self.interval_s = interval_s self.enabled = enabled self._running = False @@ -113,15 +118,14 @@ class HeartbeatService: if self.on_heartbeat: try: response = await self.on_heartbeat(HEARTBEAT_PROMPT) - - # Check if agent said "nothing to do" - if HEARTBEAT_OK_TOKEN.replace("_", "") in response.upper().replace("_", ""): - logger.info("Heartbeat: OK (no action needed)") + if HEARTBEAT_OK_TOKEN in response.upper(): + logger.info("Heartbeat: OK (nothing to report)") else: - logger.info("Heartbeat: completed task") - - except Exception as e: - logger.error("Heartbeat execution failed: {}", e) + logger.info("Heartbeat: completed, delivering response") + if self.on_notify: + await self.on_notify(response) + except Exception: + logger.exception("Heartbeat execution failed") async def trigger_now(self) -> str | None: """Manually trigger a heartbeat.""" From eae6059889bcb8000ab8f5dc8fdbe4b9c8816180 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 13:59:47 +0000 Subject: [PATCH 113/154] fix: remove extra blank line --- nanobot/heartbeat/service.py | 1 - 1 file changed, 1 deletion(-) diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index 3e40f2f..cb1a1c7 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -36,7 +36,6 @@ def _is_heartbeat_empty(content: str | None) -> bool: return True - class HeartbeatService: """ Periodic heartbeat service that wakes the agent to check for tasks. From 35e3f7ed26a02c9d6e47393944069b8ad297175d Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 14:10:43 +0000 Subject: [PATCH 114/154] fix(templates): tighten AGENTS.md tool call guidelines to reduce hallucinations --- nanobot/templates/AGENTS.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nanobot/templates/AGENTS.md b/nanobot/templates/AGENTS.md index 155a0b2..84ba657 100644 --- a/nanobot/templates/AGENTS.md +++ b/nanobot/templates/AGENTS.md @@ -4,7 +4,9 @@ You are a helpful AI assistant. Be concise, accurate, and friendly. ## Guidelines -- Always explain what you're doing before taking actions +- Before calling tools, briefly state your intent β€” but NEVER predict results before receiving them +- Use precise tense: "I will run X" before the call, "X returned Y" after +- NEVER claim success before a tool result confirms it - Ask for clarification when the request is ambiguous - Remember important information in `memory/MEMORY.md`; past events are logged in `memory/HISTORY.md` From 2f573e591bce5e851bb0926588af7fc5f87718e6 Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 16:57:08 +0000 Subject: [PATCH 115/154] fix(session): get_history uses last_consolidated cursor, aligns to user turn --- nanobot/session/manager.py | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/nanobot/session/manager.py b/nanobot/session/manager.py index 5f23dc2..d59b7c9 100644 --- a/nanobot/session/manager.py +++ b/nanobot/session/manager.py @@ -43,9 +43,18 @@ class Session: self.updated_at = datetime.now() def get_history(self, max_messages: int = 500) -> list[dict[str, Any]]: - """Get recent messages in LLM format, preserving tool metadata.""" + """Return unconsolidated messages for LLM input, aligned to a user turn.""" + unconsolidated = self.messages[self.last_consolidated:] + sliced = unconsolidated[-max_messages:] + + # Drop leading non-user messages to avoid orphaned tool_result blocks + for i, m in enumerate(sliced): + if m.get("role") == "user": + sliced = sliced[i:] + break + out: list[dict[str, Any]] = [] - for m in self.messages[-max_messages:]: + for m in sliced: entry: dict[str, Any] = {"role": m["role"], "content": m.get("content", "")} for k in ("tool_calls", "tool_call_id", "name"): if k in m: From 3eeac4e8f89c979e9f922a7731100fa23a642c64 Mon Sep 17 00:00:00 2001 From: alairjt Date: Mon, 23 Feb 2026 13:59:49 -0300 Subject: [PATCH 116/154] Fix: handle non-string tool call arguments in memory consolidation Fixes #1042. When the LLM returns tool call arguments as a dict or JSON string instead of parsed values, memory consolidation would fail with "TypeError: data must be str, not dict". Changes: - Add type guard in MemoryStore.consolidate() to parse string arguments and reject unexpected types gracefully - Add regression tests covering dict args, string args, and edge cases --- nanobot/agent/memory.py | 7 ++ tests/test_memory_consolidation_types.py | 147 +++++++++++++++++++++++ 2 files changed, 154 insertions(+) create mode 100644 tests/test_memory_consolidation_types.py diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.py index cdbc49f..978b1bc 100644 --- a/nanobot/agent/memory.py +++ b/nanobot/agent/memory.py @@ -125,6 +125,13 @@ class MemoryStore: return False args = response.tool_calls[0].arguments + # Some providers return arguments as a JSON string instead of dict + if isinstance(args, str): + args = json.loads(args) + if not isinstance(args, dict): + logger.warning("Memory consolidation: unexpected arguments type %s", type(args).__name__) + return False + if entry := args.get("history_entry"): if not isinstance(entry, str): entry = json.dumps(entry, ensure_ascii=False) diff --git a/tests/test_memory_consolidation_types.py b/tests/test_memory_consolidation_types.py new file mode 100644 index 0000000..375c802 --- /dev/null +++ b/tests/test_memory_consolidation_types.py @@ -0,0 +1,147 @@ +"""Test MemoryStore.consolidate() handles non-string tool call arguments. + +Regression test for https://github.com/HKUDS/nanobot/issues/1042 +When memory consolidation receives dict values instead of strings from the LLM +tool call response, it should serialize them to JSON instead of raising TypeError. +""" + +import json +from pathlib import Path +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from nanobot.agent.memory import MemoryStore +from nanobot.providers.base import LLMResponse, ToolCallRequest + + +def _make_session(message_count: int = 30, memory_window: int = 50): + """Create a mock session with messages.""" + session = MagicMock() + session.messages = [ + {"role": "user", "content": f"msg{i}", "timestamp": "2026-01-01 00:00"} + for i in range(message_count) + ] + session.last_consolidated = 0 + return session + + +def _make_tool_response(history_entry, memory_update): + """Create an LLMResponse with a save_memory tool call.""" + return LLMResponse( + content=None, + tool_calls=[ + ToolCallRequest( + id="call_1", + name="save_memory", + arguments={ + "history_entry": history_entry, + "memory_update": memory_update, + }, + ) + ], + ) + + +class TestMemoryConsolidationTypeHandling: + """Test that consolidation handles various argument types correctly.""" + + @pytest.mark.asyncio + async def test_string_arguments_work(self, tmp_path: Path) -> None: + """Normal case: LLM returns string arguments.""" + store = MemoryStore(tmp_path) + provider = AsyncMock() + provider.chat = AsyncMock( + return_value=_make_tool_response( + history_entry="[2026-01-01] User discussed testing.", + memory_update="# Memory\nUser likes testing.", + ) + ) + session = _make_session(message_count=60) + + result = await store.consolidate(session, provider, "test-model", memory_window=50) + + assert result is True + assert store.history_file.exists() + assert "[2026-01-01] User discussed testing." in store.history_file.read_text() + assert "User likes testing." in store.memory_file.read_text() + + @pytest.mark.asyncio + async def test_dict_arguments_serialized_to_json(self, tmp_path: Path) -> None: + """Issue #1042: LLM returns dict instead of string β€” must not raise TypeError.""" + store = MemoryStore(tmp_path) + provider = AsyncMock() + provider.chat = AsyncMock( + return_value=_make_tool_response( + history_entry={"timestamp": "2026-01-01", "summary": "User discussed testing."}, + memory_update={"facts": ["User likes testing"], "topics": ["testing"]}, + ) + ) + session = _make_session(message_count=60) + + result = await store.consolidate(session, provider, "test-model", memory_window=50) + + assert result is True + assert store.history_file.exists() + history_content = store.history_file.read_text() + parsed = json.loads(history_content.strip()) + assert parsed["summary"] == "User discussed testing." + + memory_content = store.memory_file.read_text() + parsed_mem = json.loads(memory_content) + assert "User likes testing" in parsed_mem["facts"] + + @pytest.mark.asyncio + async def test_string_arguments_as_raw_json(self, tmp_path: Path) -> None: + """Some providers return arguments as a JSON string instead of parsed dict.""" + store = MemoryStore(tmp_path) + provider = AsyncMock() + + # Simulate arguments being a JSON string (not yet parsed) + response = LLMResponse( + content=None, + tool_calls=[ + ToolCallRequest( + id="call_1", + name="save_memory", + arguments=json.dumps({ + "history_entry": "[2026-01-01] User discussed testing.", + "memory_update": "# Memory\nUser likes testing.", + }), + ) + ], + ) + provider.chat = AsyncMock(return_value=response) + session = _make_session(message_count=60) + + result = await store.consolidate(session, provider, "test-model", memory_window=50) + + assert result is True + assert "User discussed testing." in store.history_file.read_text() + + @pytest.mark.asyncio + async def test_no_tool_call_returns_false(self, tmp_path: Path) -> None: + """When LLM doesn't use the save_memory tool, return False.""" + store = MemoryStore(tmp_path) + provider = AsyncMock() + provider.chat = AsyncMock( + return_value=LLMResponse(content="I summarized the conversation.", tool_calls=[]) + ) + session = _make_session(message_count=60) + + result = await store.consolidate(session, provider, "test-model", memory_window=50) + + assert result is False + assert not store.history_file.exists() + + @pytest.mark.asyncio + async def test_skips_when_few_messages(self, tmp_path: Path) -> None: + """Consolidation should be a no-op when messages < keep_count.""" + store = MemoryStore(tmp_path) + provider = AsyncMock() + session = _make_session(message_count=10) + + result = await store.consolidate(session, provider, "test-model", memory_window=50) + + assert result is True + provider.chat.assert_not_called() From f8dc6fafa946ef87266448c97e05135ace6d640e Mon Sep 17 00:00:00 2001 From: dulltackle Date: Tue, 24 Feb 2026 01:26:56 +0800 Subject: [PATCH 117/154] **fix(mcp): Remove default timeout for HTTP transport to avoid tool timeout conflicts** Always provide an explicit httpx client to prevent MCP HTTP transport from inheriting httpx's default 5-second timeout, thereby avoiding conflicts with the upper layer tool's timeout settings. --- nanobot/agent/tools/mcp.py | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.py index 0257d52..37464e1 100644 --- a/nanobot/agent/tools/mcp.py +++ b/nanobot/agent/tools/mcp.py @@ -69,20 +69,18 @@ async def connect_mcp_servers( read, write = await stack.enter_async_context(stdio_client(params)) elif cfg.url: from mcp.client.streamable_http import streamable_http_client - if cfg.headers: - http_client = await stack.enter_async_context( - httpx.AsyncClient( - headers=cfg.headers, - follow_redirects=True - ) - ) - read, write, _ = await stack.enter_async_context( - streamable_http_client(cfg.url, http_client=http_client) - ) - else: - read, write, _ = await stack.enter_async_context( - streamable_http_client(cfg.url) + # Always provide an explicit httpx client so MCP HTTP transport does not + # inherit httpx's default 5s timeout and preempt the higher-level tool timeout. + http_client = await stack.enter_async_context( + httpx.AsyncClient( + headers=cfg.headers or None, + follow_redirects=True, + timeout=None, ) + ) + read, write, _ = await stack.enter_async_context( + streamable_http_client(cfg.url, http_client=http_client) + ) else: logger.warning("MCP server '{}': no command or url configured, skipping", name) continue From 30361c9307f9014f49530d80abd5717bc97f554a Mon Sep 17 00:00:00 2001 From: Re-bin Date: Mon, 23 Feb 2026 18:28:09 +0000 Subject: [PATCH 118/154] refactor: replace cron usage docs in TOOLS.md with reference to cron skill --- nanobot/templates/TOOLS.md | 25 ++----------------------- 1 file changed, 2 insertions(+), 23 deletions(-) diff --git a/nanobot/templates/TOOLS.md b/nanobot/templates/TOOLS.md index 757edd2..51c3a2d 100644 --- a/nanobot/templates/TOOLS.md +++ b/nanobot/templates/TOOLS.md @@ -10,27 +10,6 @@ This file documents non-obvious constraints and usage patterns. - Output is truncated at 10,000 characters - `restrictToWorkspace` config can limit file access to the workspace -## Cron β€” Scheduled Reminders +## cron β€” Scheduled Reminders -Use `exec` to create scheduled reminders: - -```bash -# Recurring: every day at 9am -nanobot cron add --name "morning" --message "Good morning!" --cron "0 9 * * *" - -# With timezone (--tz only works with --cron) -nanobot cron add --name "standup" --message "Standup time!" --cron "0 10 * * 1-5" --tz "Asia/Shanghai" - -# Recurring: every 2 hours -nanobot cron add --name "water" --message "Drink water!" --every 7200 - -# One-time: specific ISO time -nanobot cron add --name "meeting" --message "Meeting starts now!" --at "2025-01-31T15:00:00" - -# Deliver to a specific channel/user -nanobot cron add --name "reminder" --message "Check email" --at "2025-01-31T09:00:00" --deliver --to "USER_ID" --channel "CHANNEL" - -# Manage jobs -nanobot cron list -nanobot cron remove -``` +- Please refer to cron skill for usage. From eeaad6e0c2ffb0e684ee7c19eef7d09dbdf0c447 Mon Sep 17 00:00:00 2001 From: haosenwang1018 Date: Tue, 24 Feb 2026 04:06:22 +0800 Subject: [PATCH 119/154] fix: resolve API key at call time so config changes take effect without restart Previously, WebSearchTool cached the API key in __init__, so keys added to config.json or env vars after gateway startup were never picked up. This caused a confusing 'BRAVE_API_KEY not configured' error even after the key was correctly set (issue #1069). Changes: - Store the init-time key separately, resolve via property at each call - Improve error message to guide users toward the correct fix Closes #1069 --- nanobot/agent/tools/web.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.py index 90cdda8..ae69e9e 100644 --- a/nanobot/agent/tools/web.py +++ b/nanobot/agent/tools/web.py @@ -58,12 +58,22 @@ class WebSearchTool(Tool): } def __init__(self, api_key: str | None = None, max_results: int = 5): - self.api_key = api_key or os.environ.get("BRAVE_API_KEY", "") + self._init_api_key = api_key self.max_results = max_results + + @property + def api_key(self) -> str: + """Resolve API key at call time so env/config changes are picked up.""" + return self._init_api_key or os.environ.get("BRAVE_API_KEY", "") async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str: if not self.api_key: - return "Error: BRAVE_API_KEY not configured" + return ( + "Error: Brave Search API key not configured. " + "Set BRAVE_API_KEY environment variable or add " + "tools.web.search.apiKey to ~/.nanobot/config.json, " + "then restart the gateway." + ) try: n = min(max(count or self.max_results, 1), 10) From 8de2f8d58845a13aa7c8df290a9da37705fd4160 Mon Sep 17 00:00:00 2001 From: haosenwang1018 Date: Tue, 24 Feb 2026 04:21:55 +0800 Subject: [PATCH 120/154] fix: preserve reasoning_content in message sanitization for thinking models _sanitize_messages strips all non-standard keys from messages, including reasoning_content. Thinking-enabled models like Moonshot Kimi k2.5 require reasoning_content to be present in assistant tool call messages when thinking mode is on, causing a BadRequestError (#1014). Add reasoning_content to _ALLOWED_MSG_KEYS so it passes through sanitization when present. Fixes #1014 --- nanobot/providers/litellm_provider.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.py index 7402a2b..0918954 100644 --- a/nanobot/providers/litellm_provider.py +++ b/nanobot/providers/litellm_provider.py @@ -12,8 +12,9 @@ from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest from nanobot.providers.registry import find_by_model, find_gateway -# Standard OpenAI chat-completion message keys; extras (e.g. reasoning_content) are stripped for strict providers. -_ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name"}) +# Standard OpenAI chat-completion message keys plus reasoning_content for +# thinking-enabled models (Kimi k2.5, DeepSeek-R1, etc.). +_ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name", "reasoning_content"}) class LiteLLMProvider(LLMProvider): From 91e13d91ac1001d0e10fbe04fa13225c6efecb3a Mon Sep 17 00:00:00 2001 From: chengyongru <2755839590@qq.com> Date: Tue, 24 Feb 2026 04:26:26 +0800 Subject: [PATCH 121/154] fix(email): allow proactive sends when autoReplyEnabled is false Previously, `autoReplyEnabled=false` would block ALL email sends, including proactive emails triggered from other channels (e.g., asking nanobot on Feishu to send an email). Now `autoReplyEnabled` only controls automatic replies to incoming emails, not proactive sends. This allows users to disable auto-replies while still being able to ask nanobot to send emails on demand. Changes: - Check if recipient is in `_last_subject_by_chat` to determine if it's a reply - Only skip sending when it's a reply AND auto_reply_enabled is false - Add test for proactive send with auto_reply_enabled=false - Update existing test to verify reply behavior --- nanobot/channels/email.py | 14 +++++---- tests/test_email_channel.py | 59 ++++++++++++++++++++++++++++++++++++- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/nanobot/channels/email.py b/nanobot/channels/email.py index 5dc05fb..16771fb 100644 --- a/nanobot/channels/email.py +++ b/nanobot/channels/email.py @@ -108,11 +108,6 @@ class EmailChannel(BaseChannel): logger.warning("Skip email send: consent_granted is false") return - force_send = bool((msg.metadata or {}).get("force_send")) - if not self.config.auto_reply_enabled and not force_send: - logger.info("Skip automatic email reply: auto_reply_enabled is false") - return - if not self.config.smtp_host: logger.warning("Email channel SMTP host not configured") return @@ -122,6 +117,15 @@ class EmailChannel(BaseChannel): logger.warning("Email channel missing recipient address") return + # Determine if this is a reply (recipient has sent us an email before) + is_reply = to_addr in self._last_subject_by_chat + force_send = bool((msg.metadata or {}).get("force_send")) + + # autoReplyEnabled only controls automatic replies, not proactive sends + if is_reply and not self.config.auto_reply_enabled and not force_send: + logger.info("Skip automatic email reply to {}: auto_reply_enabled is false", to_addr) + return + base_subject = self._last_subject_by_chat.get(to_addr, "nanobot reply") subject = self._reply_subject(base_subject) if msg.metadata and isinstance(msg.metadata.get("subject"), str): diff --git a/tests/test_email_channel.py b/tests/test_email_channel.py index 8b22d8d..adf35a8 100644 --- a/tests/test_email_channel.py +++ b/tests/test_email_channel.py @@ -169,7 +169,8 @@ async def test_send_uses_smtp_and_reply_subject(monkeypatch) -> None: @pytest.mark.asyncio -async def test_send_skips_when_auto_reply_disabled(monkeypatch) -> None: +async def test_send_skips_reply_when_auto_reply_disabled(monkeypatch) -> None: + """When auto_reply_enabled=False, replies should be skipped but proactive sends allowed.""" class FakeSMTP: def __init__(self, _host: str, _port: int, timeout: int = 30) -> None: self.sent_messages: list[EmailMessage] = [] @@ -201,6 +202,11 @@ async def test_send_skips_when_auto_reply_disabled(monkeypatch) -> None: cfg = _make_config() cfg.auto_reply_enabled = False channel = EmailChannel(cfg, MessageBus()) + + # Mark alice as someone who sent us an email (making this a "reply") + channel._last_subject_by_chat["alice@example.com"] = "Previous email" + + # Reply should be skipped (auto_reply_enabled=False) await channel.send( OutboundMessage( channel="email", @@ -210,6 +216,7 @@ async def test_send_skips_when_auto_reply_disabled(monkeypatch) -> None: ) assert fake_instances == [] + # Reply with force_send=True should be sent await channel.send( OutboundMessage( channel="email", @@ -222,6 +229,56 @@ async def test_send_skips_when_auto_reply_disabled(monkeypatch) -> None: assert len(fake_instances[0].sent_messages) == 1 +@pytest.mark.asyncio +async def test_send_proactive_email_when_auto_reply_disabled(monkeypatch) -> None: + """Proactive emails (not replies) should be sent even when auto_reply_enabled=False.""" + class FakeSMTP: + def __init__(self, _host: str, _port: int, timeout: int = 30) -> None: + self.sent_messages: list[EmailMessage] = [] + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + def starttls(self, context=None): + return None + + def login(self, _user: str, _pw: str): + return None + + def send_message(self, msg: EmailMessage): + self.sent_messages.append(msg) + + fake_instances: list[FakeSMTP] = [] + + def _smtp_factory(host: str, port: int, timeout: int = 30): + instance = FakeSMTP(host, port, timeout=timeout) + fake_instances.append(instance) + return instance + + monkeypatch.setattr("nanobot.channels.email.smtplib.SMTP", _smtp_factory) + + cfg = _make_config() + cfg.auto_reply_enabled = False + channel = EmailChannel(cfg, MessageBus()) + + # bob@example.com has never sent us an email (proactive send) + # This should be sent even with auto_reply_enabled=False + await channel.send( + OutboundMessage( + channel="email", + chat_id="bob@example.com", + content="Hello, this is a proactive email.", + ) + ) + assert len(fake_instances) == 1 + assert len(fake_instances[0].sent_messages) == 1 + sent = fake_instances[0].sent_messages[0] + assert sent["To"] == "bob@example.com" + + @pytest.mark.asyncio async def test_send_skips_when_consent_not_granted(monkeypatch) -> None: class FakeSMTP: From abcce1e1db3282651a916f5de9193bb4025ff559 Mon Sep 17 00:00:00 2001 From: aiguozhi123456 Date: Tue, 24 Feb 2026 03:18:23 +0000 Subject: [PATCH 122/154] feat(exec): add path_append config to extend PATH for subprocess --- nanobot/agent/tools/shell.py | 7 +++++++ nanobot/config/schema.py | 1 + 2 files changed, 8 insertions(+) diff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.py index e3592a7..c11fa2d 100644 --- a/nanobot/agent/tools/shell.py +++ b/nanobot/agent/tools/shell.py @@ -19,6 +19,7 @@ class ExecTool(Tool): deny_patterns: list[str] | None = None, allow_patterns: list[str] | None = None, restrict_to_workspace: bool = False, + path_append: str = "/usr/sbin:/usr/local/sbin", ): self.timeout = timeout self.working_dir = working_dir @@ -35,6 +36,7 @@ class ExecTool(Tool): ] self.allow_patterns = allow_patterns or [] self.restrict_to_workspace = restrict_to_workspace + self.path_append = path_append @property def name(self) -> str: @@ -67,12 +69,17 @@ class ExecTool(Tool): if guard_error: return guard_error + env = os.environ.copy() + if self.path_append: + env["PATH"] = env.get("PATH", "") + ":" + self.path_append + try: process = await asyncio.create_subprocess_shell( command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=cwd, + env=env, ) try: diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index fe8dd83..dd856fe 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -252,6 +252,7 @@ class ExecToolConfig(Base): """Shell exec tool configuration.""" timeout: int = 60 + path_append: str = "/usr/sbin:/usr/local/sbin" class MCPServerConfig(Base): From 4f8033627e05ad3d92fa4e31a5fdfad4f3711273 Mon Sep 17 00:00:00 2001 From: "xzq.xu" Date: Tue, 24 Feb 2026 13:42:07 +0800 Subject: [PATCH 123/154] feat(feishu): support images in post (rich text) messages Co-authored-by: Cursor --- nanobot/channels/feishu.py | 54 ++++++++++++++++++++++++++++---------- 1 file changed, 40 insertions(+), 14 deletions(-) diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.py index 2d50d74..480bf7b 100644 --- a/nanobot/channels/feishu.py +++ b/nanobot/channels/feishu.py @@ -180,21 +180,25 @@ def _extract_element_content(element: dict) -> list[str]: return parts -def _extract_post_text(content_json: dict) -> str: - """Extract plain text from Feishu post (rich text) message content. +def _extract_post_content(content_json: dict) -> tuple[str, list[str]]: + """Extract text and image keys from Feishu post (rich text) message content. Supports two formats: 1. Direct format: {"title": "...", "content": [...]} 2. Localized format: {"zh_cn": {"title": "...", "content": [...]}} + + Returns: + (text, image_keys) - extracted text and list of image keys """ - def extract_from_lang(lang_content: dict) -> str | None: + def extract_from_lang(lang_content: dict) -> tuple[str | None, list[str]]: if not isinstance(lang_content, dict): - return None + return None, [] title = lang_content.get("title", "") content_blocks = lang_content.get("content", []) if not isinstance(content_blocks, list): - return None + return None, [] text_parts = [] + image_keys = [] if title: text_parts.append(title) for block in content_blocks: @@ -209,22 +213,36 @@ def _extract_post_text(content_json: dict) -> str: text_parts.append(element.get("text", "")) elif tag == "at": text_parts.append(f"@{element.get('user_name', 'user')}") - return " ".join(text_parts).strip() if text_parts else None + elif tag == "img": + img_key = element.get("image_key") + if img_key: + image_keys.append(img_key) + text = " ".join(text_parts).strip() if text_parts else None + return text, image_keys # Try direct format first if "content" in content_json: - result = extract_from_lang(content_json) - if result: - return result + text, images = extract_from_lang(content_json) + if text or images: + return text or "", images # Try localized format for lang_key in ("zh_cn", "en_us", "ja_jp"): lang_content = content_json.get(lang_key) - result = extract_from_lang(lang_content) - if result: - return result + text, images = extract_from_lang(lang_content) + if text or images: + return text or "", images - return "" + return "", [] + + +def _extract_post_text(content_json: dict) -> str: + """Extract plain text from Feishu post (rich text) message content. + + Legacy wrapper for _extract_post_content, returns only text. + """ + text, _ = _extract_post_content(content_json) + return text class FeishuChannel(BaseChannel): @@ -691,9 +709,17 @@ class FeishuChannel(BaseChannel): content_parts.append(text) elif msg_type == "post": - text = _extract_post_text(content_json) + text, image_keys = _extract_post_content(content_json) if text: content_parts.append(text) + # Download images embedded in post + for img_key in image_keys: + file_path, content_text = await self._download_and_save_media( + "image", {"image_key": img_key}, message_id + ) + if file_path: + media_paths.append(file_path) + content_parts.append(content_text) elif msg_type in ("image", "audio", "file", "media"): file_path, content_text = await self._download_and_save_media(msg_type, content_json, message_id) From ef572259747a59625865ef7d7c6fc72edb448c0c Mon Sep 17 00:00:00 2001 From: coldxiangyu Date: Tue, 24 Feb 2026 18:19:47 +0800 Subject: [PATCH 124/154] fix(web): resolve API key on each call + improve error message - Defer Brave API key resolution to execute() time instead of __init__, so env var or config changes take effect without gateway restart - Improve error message to reference actual config path (tools.web.search.apiKey) instead of only mentioning env var Fixes #1069 (issues 1 and 2 of 3) --- nanobot/agent/tools/web.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.py index 90cdda8..4ca788c 100644 --- a/nanobot/agent/tools/web.py +++ b/nanobot/agent/tools/web.py @@ -58,12 +58,21 @@ class WebSearchTool(Tool): } def __init__(self, api_key: str | None = None, max_results: int = 5): - self.api_key = api_key or os.environ.get("BRAVE_API_KEY", "") + self._config_api_key = api_key self.max_results = max_results - + + def _resolve_api_key(self) -> str: + """Resolve API key on each call to support hot-reload and env var changes.""" + return self._config_api_key or os.environ.get("BRAVE_API_KEY", "") + async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str: - if not self.api_key: - return "Error: BRAVE_API_KEY not configured" + api_key = self._resolve_api_key() + if not api_key: + return ( + "Error: Brave Search API key not configured. " + "Set it in ~/.nanobot/config.json under tools.web.search.apiKey " + "(or export BRAVE_API_KEY), then restart the gateway." + ) try: n = min(max(count or self.max_results, 1), 10) @@ -71,7 +80,7 @@ class WebSearchTool(Tool): r = await client.get( "https://api.search.brave.com/res/v1/web/search", params={"q": query, "count": n}, - headers={"Accept": "application/json", "X-Subscription-Token": self.api_key}, + headers={"Accept": "application/json", "X-Subscription-Token": api_key}, timeout=10.0 ) r.raise_for_status() From ec55f7791256cfcec28d947296247aac72f5701b Mon Sep 17 00:00:00 2001 From: Re-bin Date: Tue, 24 Feb 2026 11:04:56 +0000 Subject: [PATCH 125/154] fix(heartbeat): replace HEARTBEAT_OK token with virtual tool-call decision --- nanobot/cli/commands.py | 17 ++-- nanobot/config/schema.py | 8 ++ nanobot/heartbeat/service.py | 162 +++++++++++++++++++++-------------- 3 files changed, 117 insertions(+), 70 deletions(-) diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py index 90b9f44..ca71694 100644 --- a/nanobot/cli/commands.py +++ b/nanobot/cli/commands.py @@ -360,19 +360,19 @@ def gateway( return "cli", "direct" # Create heartbeat service - async def on_heartbeat(prompt: str) -> str: - """Execute heartbeat through the agent.""" + async def on_heartbeat_execute(tasks: str) -> str: + """Phase 2: execute heartbeat tasks through the full agent loop.""" channel, chat_id = _pick_heartbeat_target() async def _silent(*_args, **_kwargs): pass return await agent.process_direct( - prompt, + tasks, session_key="heartbeat", channel=channel, chat_id=chat_id, - on_progress=_silent, # suppress: heartbeat should not push progress to external channels + on_progress=_silent, ) async def on_heartbeat_notify(response: str) -> None: @@ -383,12 +383,15 @@ def gateway( return # No external channel available to deliver to await bus.publish_outbound(OutboundMessage(channel=channel, chat_id=chat_id, content=response)) + hb_cfg = config.gateway.heartbeat heartbeat = HeartbeatService( workspace=config.workspace_path, - on_heartbeat=on_heartbeat, + provider=provider, + model=agent.model, + on_execute=on_heartbeat_execute, on_notify=on_heartbeat_notify, - interval_s=30 * 60, # 30 minutes - enabled=True + interval_s=hb_cfg.interval_s, + enabled=hb_cfg.enabled, ) if channels.enabled_channels: diff --git a/nanobot/config/schema.py b/nanobot/config/schema.py index fe8dd83..215f38d 100644 --- a/nanobot/config/schema.py +++ b/nanobot/config/schema.py @@ -228,11 +228,19 @@ class ProvidersConfig(Base): github_copilot: ProviderConfig = Field(default_factory=ProviderConfig) # Github Copilot (OAuth) +class HeartbeatConfig(Base): + """Heartbeat service configuration.""" + + enabled: bool = True + interval_s: int = 30 * 60 # 30 minutes + + class GatewayConfig(Base): """Gateway/server configuration.""" host: str = "0.0.0.0" port: int = 18790 + heartbeat: HeartbeatConfig = Field(default_factory=HeartbeatConfig) class WebSearchConfig(Base): diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.py index cb1a1c7..e534017 100644 --- a/nanobot/heartbeat/service.py +++ b/nanobot/heartbeat/service.py @@ -1,80 +1,110 @@ """Heartbeat service - periodic agent wake-up to check for tasks.""" +from __future__ import annotations + import asyncio from pathlib import Path -from typing import Any, Callable, Coroutine +from typing import TYPE_CHECKING, Any, Callable, Coroutine from loguru import logger -# Default interval: 30 minutes -DEFAULT_HEARTBEAT_INTERVAL_S = 30 * 60 +if TYPE_CHECKING: + from nanobot.providers.base import LLMProvider -# Token the agent replies with when there is nothing to report -HEARTBEAT_OK_TOKEN = "HEARTBEAT_OK" - -# The prompt sent to agent during heartbeat -HEARTBEAT_PROMPT = ( - "Read HEARTBEAT.md in your workspace and follow any instructions listed there. " - f"If nothing needs attention, reply with exactly: {HEARTBEAT_OK_TOKEN}" -) - - -def _is_heartbeat_empty(content: str | None) -> bool: - """Check if HEARTBEAT.md has no actionable content.""" - if not content: - return True - - # Lines to skip: empty, headers, HTML comments, empty checkboxes - skip_patterns = {"- [ ]", "* [ ]", "- [x]", "* [x]"} - - for line in content.split("\n"): - line = line.strip() - if not line or line.startswith("#") or line.startswith("