Compare commits

..
795 changed files with 12449 additions and 67935 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ Example valid usage:
## Windows Compatibility
nanobot explicitly supports Windows. Key differences to keep in mind:
- `ExecTool` defaults to PowerShell on Windows (`pwsh` when available, otherwise Windows PowerShell); pass `shell="cmd"` for cmd.exe syntax or cmd built-ins (`shell.py`).
- `ExecTool` uses `cmd /c` on Windows instead of `sh -c` (`shell.py`).
- `cli/commands.py` forces `sys.stdout`/`stderr` to UTF-8 on startup to handle emoji and multilingual input.
- MCP stdio server commands are normalized for Windows path separators (`mcp.py`).
- Always use `pathlib.Path` for path manipulation; do not assume `/` separators.
+7 -33
View File
@@ -19,25 +19,14 @@ permissions:
jobs:
test:
name: Python (${{ matrix.name }})
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
include:
- name: minimum, 3.11
os: ubuntu-latest
python-version: "3.11"
coverage: false
- name: latest, 3.14 + coverage
os: ubuntu-latest
python-version: "3.14"
coverage: true
- name: Windows, 3.14
os: windows-latest
python-version: "3.14"
coverage: false
os: ${{ fromJSON('["ubuntu-latest","windows-latest"]') }}
# CI concentrates on newer runtimes (3.11/3.12 still supported per pyproject requires-python).
python-version: ${{ fromJSON('["3.13","3.14"]') }}
steps:
- uses: actions/checkout@v4
@@ -58,21 +47,10 @@ jobs:
run: uv sync --all-extras --dev
- name: Lint with ruff
if: matrix.coverage
run: uv run ruff check nanobot tests conftest.py
run: uv run ruff check nanobot --select F
- name: Run tests with coverage
if: matrix.coverage
run: >-
uv run python -m pytest
--cov=nanobot --cov-report=term-missing:skip-covered
--durations=25 --durations-min=1.0
- name: Run compatibility tests
if: ${{ !matrix.coverage }}
run: >-
uv run python -m pytest
--durations=25 --durations-min=1.0
- name: Run tests
run: uv run python -m pytest tests/ --cov=nanobot --cov-report=term-missing:skip-covered
webui:
runs-on: ubuntu-latest
@@ -86,13 +64,9 @@ jobs:
with:
bun-version: 1.3.6
- name: Verify npm lockfile
working-directory: webui
run: npm ci --ignore-scripts --dry-run
- name: Install WebUI dependencies
working-directory: webui
run: bun install --frozen-lockfile
run: bun install
- name: Lint WebUI
working-directory: webui
+2 -2
View File
@@ -36,7 +36,7 @@ Messages flow through an async `MessageBus` (`nanobot/bus/queue.py`) that decoup
- **Agent Loop** (`nanobot/agent/loop.py`, `runner.py`): The core processing engine. `AgentLoop` manages session keys, hooks, and context building. `AgentRunner` executes the multi-turn LLM conversation with tool execution.
- **LLM Providers** (`nanobot/providers/`): Provider implementations (Anthropic, OpenAI-compatible, OpenAI Responses API, Azure, Bedrock, GitHub Copilot, OpenAI Codex, etc.) built on a common base (`base.py`). Includes image generation (`image_generation.py`) and audio transcription (`transcription.py`). `factory.py` and `registry.py` handle instantiation and model discovery.
- **Channels** (`nanobot/channels/`): Platform integrations (Telegram, Discord, Slack, Feishu, Matrix, WhatsApp, QQ, WeChat, WeCom, DingTalk, Email, MoChat, MS Teams, WebSocket, Mattermost). `manager.py` discovers and coordinates them. Channels are self-contained packages auto-discovered via `pkgutil` scanning.
- **Channels** (`nanobot/channels/`): Platform integrations (Telegram, Discord, Slack, Feishu, Matrix, WhatsApp, QQ, WeChat, WeCom, DingTalk, Email, MoChat, MS Teams, WebSocket). `manager.py` discovers and coordinates them. Channels are auto-discovered via `pkgutil` scan + entry-point plugins.
- **Tools** (`nanobot/agent/tools/`): Agent capabilities exposed to the LLM: filesystem (read/write/edit/list), shell execution (with sandbox backends), web search/fetch, MCP servers, cron, notebook editing, subagent spawning, long-running tasks / sustained goals (`long_task.py`), image generation, and self-modification. Tools are auto-discovered via `pkgutil` scan + entry-point plugins.
- **Memory** (`nanobot/agent/memory.py`): Session history persistence with Dream two-phase memory consolidation. Uses atomic writes with fsync for durability.
- **Session Management** (`nanobot/session/`): Per-session history, context compaction, TTL-based auto-compaction (`manager.py`), and sustained goal state tracking (`goal_state.py`).
@@ -46,7 +46,7 @@ Messages flow through an async `MessageBus` (`nanobot/bus/queue.py`) that decoup
- **Command Router** (`nanobot/command/`): Slash command routing and built-in command handlers.
- **Heartbeat** (`nanobot/templates/HEARTBEAT.md`): Periodic task list checked via `cron` jobs (legacy dedicated service removed).
- **Pairing** (`nanobot/pairing/`): DM sender approval store with persistent pairing codes per channel.
- **Skills** (`nanobot/skills/`): Built-in skill definitions (cron, github, image-generation, etc.) loaded into agent context.
- **Skills** (`nanobot/skills/`): Built-in skill definitions (long-goal, cron, github, image-generation, etc.) loaded into agent context.
- **Security** (`nanobot/security/`): PTH file guard and other security measures activated at CLI entry.
### Entry Points
+3 -18
View File
@@ -17,22 +17,15 @@ WORKDIR /app
# Install Python dependencies first (cached layer). Hatch reads the custom build
# hook from hatch_build.py even for this metadata-only install.
ARG NANOBOT_EXTRAS=whatsapp
COPY pyproject.toml README.md LICENSE THIRD_PARTY_NOTICES.md hatch_build.py ./
RUN mkdir -p nanobot && touch nanobot/__init__.py && \
NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[$NANOBOT_EXTRAS]" && \
NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[whatsapp]" && \
rm -rf nanobot
# Copy the full source and install
COPY nanobot/ nanobot/
COPY --from=webui-builder /app/nanobot/web/dist/ nanobot/web/dist/
RUN NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[$NANOBOT_EXTRAS]"
# Render deploy template (see render.yaml): committed gateway config that wires
# secrets through ${ANTHROPIC_API_KEY} / ${NANOBOT_WEB_TOKEN} env vars (resolved
# at startup). Lives in the code dir (/app), not the data dir, so a mounted disk
# won't shadow it. Only used when RENDER=true; ignored by local runs.
COPY render-config.json ./
RUN NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[whatsapp]"
# Create non-root user and config directory
RUN useradd -m -u 1000 -s /bin/bash nanobot && \
@@ -42,16 +35,8 @@ RUN useradd -m -u 1000 -s /bin/bash nanobot && \
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN sed -i 's/\r$//' /usr/local/bin/entrypoint.sh && chmod +x /usr/local/bin/entrypoint.sh
# Start as root so the entrypoint can chown the data dir (on Render, the
# freshly-mounted root-owned persistent disk) before dropping to the non-root
# nanobot user via setpriv. The entrypoint drops privileges on every root start
# and fails closed if it cannot, so the agent never runs as root (see
# entrypoint.sh).
USER root
USER nanobot
ENV HOME=/home/nanobot
# Ensure crash output reaches Render logs (app output is otherwise swallowed on
# non-graceful exit).
ENV PYTHONUNBUFFERED=1 PYTHONFAULTHANDLER=1
# Gateway health endpoint and optional WebUI/WebSocket channel ports
EXPOSE 18790 8765
+195 -66
View File
@@ -42,45 +42,10 @@
|---|---|
| Install nanobot with no terminal/config background | [Start Without Technical Background](./docs/start-without-technical-background.md) |
| Install quickly and get one CLI reply | [Install](#-install) and [Quick Start](#-quick-start) |
| Open the bundled browser UI | [WebUI](#-webui) |
| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, or another chat app | [Chat Apps](./docs/chat-apps.md) |
| Open the bundled browser UI after the CLI works | [WebUI](#-webui) |
| Connect Telegram, Discord, WeChat, Slack, Email, or another chat app | [Chat Apps](./docs/chat-apps.md) |
| Configure providers, fallback models, Langfuse, MCP, web tools, or security | [Docs](./docs/README.md) and [Configuration](./docs/configuration.md) |
| Understand or extend the internals | [Architecture](./docs/architecture.md) and [Development](./docs/development.md) |
| Deploy to the cloud in one click | [Deploy to Render](#deploy-to-render) |
## Deploy to Render
Deploy nanobot's gateway and bundled WebUI as a single web service with persistent memory. Render reads [`render.yaml`](./render.yaml) and prompts for two secrets on deploy: `ANTHROPIC_API_KEY` and `NANOBOT_WEB_TOKEN` (the password that gates the public WebUI — generate a strong random value, e.g. `openssl rand -hex 32`).
> **Note:** The blueprint attaches a persistent disk so sessions, memory, and WebUI history survive restarts. Persistent disks require a paid service (they are not available on Render's free tier).
[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/HKUDS/nanobot)
## What can nanobot do?
nanobot is a self-hosted personal AI agent runtime. It can:
- run in a browser WebUI or terminal
- connect to Telegram, Discord, Slack, WeChat, Email, Mattermost, and other chat apps
- use tools such as files, shell, web search, web fetch, MCP, cron, image generation, and subagents
- keep session history and long-term memory through Dream
- run long-horizon goals and scheduled automations
- expose a Python SDK and OpenAI-compatible API for integrations
- deploy as a long-running local or server-side agent gateway
## Latest Release
**v0.2.2 - Durability Release**
Highlights:
- Segmented WebUI transcripts
- Python SDK runtime controls
- Automation management
- Search/STT provider improvements
- Gateway/session/provider reliability
[See full changelog](https://github.com/HKUDS/nanobot/releases/tag/v0.2.2)
## Open Source Partners
@@ -89,20 +54,158 @@ Highlights:
<a href="https://platform.minimaxi.com/subscribe/token-plan?code=GILTJpMTqZ&source=link"><img alt="MiniMax" height="40" src="https://mintcdn.com/minimax-zh/1UjvBcdoC6r0UeyA/logo/light.svg?fit=max&auto=format&n=1UjvBcdoC6r0UeyA&q=85&s=672d724b639b2d88d0702fae329ea4f8"></a>
</p>
## Recent Updates
## 📢 News
- **2026-07-12** Explicit `/goal` activation, safer runtime and workspace access.
- **2026-07-11** Syntax-highlighted previews and diffs, queued prompts, safer edits.
- **2026-07-10** Stable model routing, multiline CLI input, new automation guide.
- **2026-07-09** Live file-edit diffs, safer localhost setup, Matrix image fixes.
- **2026-07-08** Safer WebUI/API setup, onboard refresh, responsive prompt rail.
- **2026-06-22** 🚀 Released **v0.2.2****The Durability Release** makes nanobot sturdier for daily agent work: segmented WebUI transcripts, first-class Python SDK runtime controls, automation management, richer search/STT providers, and stronger gateway/session/provider reliability. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.2.2) for details.
- **2026-06-21** 🧰 Python SDK runtime controls, optional Keenable key, cleaner run hooks.
- **2026-06-20** 💬 Telegram rich messages, safer SDK concurrency, smoother Quick Start.
- **2026-06-19** 🔎 Firecrawl app, OpenAI image edits, safer session deletion.
- **2026-06-18** 💬 Feishu recovery, Keenable search, Mistral polish, workspace-aware git.
- **2026-06-17** 🧠 Default idle auto-compact, clearer `/dream`, macOS installer fixes.
- **2026-06-16** 🎯 Fresher goal context, Kimi K2.7 thinking, cleaner API retries.
- **2026-06-15** 📱 Mobile WebUI polish, optional file tools, real API usage.
- **2026-06-14** 🖼️ Themed cover, partner links, stronger Codex image streaming.
- **2026-06-13** 🗓️ Session-bound automations, sturdier WhatsApp, faster WebUI startup.
<details>
<summary>Earlier news</summary>
- **2026-06-12** 💬 Slack allowlisted channels can require mentions.
- **2026-06-11** ✂️ Fenced-code message splitting.
- **2026-06-10** 📜 Segmented transcripts, Exa/Bocha search, StepFun/SiliconFlow ASR.
- **2026-06-09** 🎙️ Shared voice input, more STT providers, TeX and email polish.
- **2026-06-08** 🧮 Token heatmap fix, safer MCP HTTP probing, docs cleanup.
- **2026-06-06** 🧰 SDK MCP cleanup, removable OpenAI image defaults.
- **2026-06-05** 🖼️ Azure AAD, custom image providers, `/skill`, steadier pairing.
- **2026-06-04** 🔌 MCP reconnects, `uv pip` install fallback, QQ pairing.
- **2026-06-03** 🧠 Hidden-history recovery, quieter email progress handling.
- **2026-06-02** 📬 Email attachments, Napcat QQ, Volcengine search, simpler Dream.
- **2026-06-01** 🚀 Released **v0.2.1****The Workbench Release** turns the packaged WebUI into a daily agent workbench: clearer Thought/response timelines, live file-edit activity, project workspaces, model and context controls, steadier sustained goals, CLI Apps + MCP extensions, and broader provider/channel support. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.2.1) for details.
- **2026-05-30** 🔐 Safer Matrix verification, bounded media downloads, clearer WebUI model timeline.
- **2026-05-29** 🧩 Extension registry, context-window tuning, document extraction controls.
- **2026-05-28** 🗂️ Project workspaces, access controls, steadier goals and streaming.
- **2026-05-27** ⏱️ Codex streams respect idle timeouts during long runs.
- **2026-05-26** 📡 Telegram webhooks, refreshed Kagi search, cleaner transport errors.
- **2026-05-25** 🔌 Unified CLI Apps and MCP, Step Plan support, steadier sustained goals.
- **2026-05-24** 🧰 MCP presets, richer slash actions, configurable OpenAI-compatible requests.
- **2026-05-23** 🖼️ Zhipu image generation, longer exec windows, cleaner transcription config.
- **2026-05-22** 🛠️ CLI Apps, more image providers, safer web redirects and edits.
- **2026-05-21** ⚡ Novita provider, faster sidebar, smoother coding tools and Weixin replies.
- **2026-05-20** 📶 Signal channel, faster gateway startup, multilingual README links.
- **2026-05-19** 🎨 Image provider registry, StepFun and Skywork, stronger WebUI controls.
- **2026-05-18** 🖌️ Gemini and MiniMax images, Ant Ling, live file-edit activity.
- **2026-05-17** 🌊 Smoother WebUI streaming, AutoCompact fixes, buffered CLI reasoning.
- **2026-05-16** 🧠 Atomic Chat provider, goal-aware timeouts, safer exec URL handling.
- **2026-05-15** 🚀 Released **v0.2.0****`/goal`** holds sustained objectives across turns, WebUI now ships inside the wheel, image generation end to end, 5 new providers with `fallback_models`, and a real agent-loop refactor. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.2.0) for details.
- **2026-05-14** 🎯 **`/goal`** for long-term objectives, visible multi-step progress, long-horizon missions in chat.
- **2026-05-13** 🧠 Streaming reasoning before answers, automatic backup models, smoother plug-in reconnects.
- **2026-05-12** 🎛️ Saved model presets with WebUI badge, simpler plug-in tools, quieter Feishu topic threads.
- **2026-05-11** 🖥️ NVIDIA NIM support, terminal bot name and icon, streamed reasoning and MiMo toggle clarity.
- **2026-05-09** 🖼️ Sharper image replay, BYO web-search keys in Settings, Feishu threads routed cleanly.
- **2026-05-08** ✨ Inline chat image, redesigned Settings and keys, Dream memory aligned with visible history.
- **2026-05-07** 📜 Locale-aware slash palette in WebUI, LAN login, faithful HTTP streaming responses.
- **2026-05-06** 🧩 Tunable tool hint, steadier voice and plug-in startups, schedules and reminders that stick.
- **2026-05-05** 🛡️ Quiet deny for unknown Telegram chats, Dream cleanup, fuller automation summaries.
- **2026-05-04** 🔐 Safer DingTalk outbound media links, durable cron persistence, DeepSeek polish.
- **2026-05-03** ⚙️ Predictable shell allow-list behavior, isolated chats mid-reply, cleaner interactive retries.
- **2026-05-02** 🐈 LongCat support, smarter token sizing hints, clearer bundled upgrade guidance.
- **2026-05-01** ☁️ Native AWS Bedrock provider, tighter helper handoffs and scoped session files.
- **2026-04-30** 💬 Feishu threads that honor replies and topics, WhatsApp bridge refresh on source edits.
- **2026-04-29** 🚀 Released **v0.1.5.post3** — Smarter threads on Feishu, Discord, Slack, and Teams; **DeepSeek-V4**; Hugging Face & Olostep; choices, `/history`, and steadier long chats. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5.post3) for details.
- **2026-04-28** 🌐 Olostep web search, Hugging Face provider, safer workspace-tool interruptions.
- **2026-04-27** 💬 `/history` command, smarter session replay caps, smoother Discord / Slack threads.
- **2026-04-26** 🧭 Natural cron reminders, thread-aware restarts, safer local provider and shell behavior.
- **2026-04-25** 🧩 `ask_user` choices, macOS LaunchAgent deployment, MSTeams stale-reference cleanup.
- **2026-04-24** 🎥 Video attachments for channels, DeepSeek thinking control, faster document startup.
- **2026-04-23** 🧵 Discord thread sessions, Telegram inline buttons, structured tool progress updates.
- **2026-04-22** 🔎 GitHub Copilot GPT-5 / o-series support, configurable web fetch, WebUI image uploads.
- **2026-04-21** 🚀 Released **v0.1.5.post2** — Windows & Python 3.14 support, Office document reading, SSE streaming for the OpenAI-compatible API, and stronger reliability across sessions, memory, and channels. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5.post2) for details.
- **2026-04-20** 🎨 Kimi K2.6 support, Telegram long-message split, WebUI typography & dark-mode polish.
- **2026-04-19** 🌐 WebUI i18n locale switcher, atomic session writes with auto-repair.
- **2026-04-18** 🧪 Initial WebUI chat, smarter setup wizard menus, WebSocket multi-chat multiplexing.
- **2026-04-17** 🪟 Windows & Python 3.14 CI, Dream line-age memory, email self-loop guard.
- **2026-04-16** 📡 SSE streaming for OpenAI-compatible API, Discord channel allow-list.
- **2026-04-15** 🎛️ LM Studio & nullable API keys, MiniMax thinking endpoint, runtime SelfTool.
- **2026-04-14** 🚀 Released **v0.1.5.post1** — Dream skill discovery, mid-turn follow-up injection, WebSocket channel, and deeper channel integrations. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5.post1) for details.
- **2026-04-13** 🛡️ Agent turn hardened — user messages persisted early, auto-compact skips active tasks.
- **2026-04-12** 🔒 Lark global domain support, Dream learns discovered skills, shell sandbox tightened.
- **2026-04-11** ⚡ Context compact shrinks sessions on the fly; Kagi web search; QQ & WeCom full media.
- **2026-04-10** 📓 Multiple MCP servers, Feishu streaming & done-emoji.
- **2026-04-09** 🔌 WebSocket channel, unified cross-channel session, `disabled_skills` config.
- **2026-04-08** 📤 API file uploads, OpenAI reasoning auto-routing with Responses fallback.
- **2026-04-07** 🧠 Anthropic adaptive thinking, MCP resources & prompts exposed as tools.
- **2026-04-06** 🛰️ Langfuse observability, unified Whisper transcription, email attachments.
- **2026-04-05** 🚀 Released **v0.1.5** — sturdier long-running tasks, Dream two-stage memory, production-ready sandboxing and programming Agent SDK. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5) for details.
- **2026-04-04** 🚀 Jinja2 response templates, Dream memory hardened, smarter retry handling.
- **2026-04-03** 🧠 Xiaomi MiMo provider, chain-of-thought reasoning visible, Telegram UX polish.
- **2026-04-02** 🧱 Long-running tasks run more reliably — core runtime hardening.
- **2026-04-01** 🔑 GitHub Copilot auth restored; stricter workspace paths; OpenRouter Claude caching fix.
- **2026-03-31** 🛰️ WeChat multimodal alignment, Discord/Matrix polish, Python SDK facade, MCP and tool fixes.
- **2026-03-30** 🧩 OpenAI-compatible API tightened; composable agent lifecycle hooks.
- **2026-03-29** 💬 WeChat voice, typing, QR/media resilience; fixed-session OpenAI-compatible API.
- **2026-03-28** 📚 Provider docs refresh; skill template wording fix.
- **2026-03-27** 🚀 Released **v0.1.4.post6** — architecture decoupling, litellm removal, end-to-end streaming, WeChat channel, and a security fix. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post6) for details.
- **2026-03-26** 🏗️ Agent runner extracted and lifecycle hooks unified; stream delta coalescing at boundaries.
- **2026-03-25** 🌏 StepFun provider, configurable timezone, Gemini thought signatures.
- **2026-03-24** 🔧 WeChat compatibility, Feishu CardKit streaming, test suite restructured.
- **2026-03-23** 🔧 Command routing refactored for plugins, WhatsApp/WeChat media, unified channel login CLI.
- **2026-03-22** ⚡ End-to-end streaming, WeChat channel, Anthropic cache optimization, `/status` command.
- **2026-03-21** 🔒 Replace `litellm` with native `openai` + `anthropic` SDKs. Please see [commit](https://github.com/HKUDS/nanobot/commit/3dfdab7).
- **2026-03-20** 🧙 Interactive setup wizard — pick your provider, model autocomplete, and you're good to go.
- **2026-03-19** 💬 Telegram gets more resilient under load; Feishu now renders code blocks properly.
- **2026-03-18** 📷 Telegram can now send media via URL. Cron schedules show human-readable details.
- **2026-03-17** ✨ Feishu formatting glow-up, Slack reacts when done, custom endpoints support extra headers, and image handling is more reliable.
- **2026-03-16** 🚀 Released **v0.1.4.post5** — a refinement-focused release with stronger reliability and channel support, and a more dependable day-to-day experience. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post5) for details.
- **2026-03-15** 🧩 DingTalk rich media, smarter built-in skills, and cleaner model compatibility.
- **2026-03-14** 💬 Channel plugins, Feishu replies, and steadier MCP, QQ, and media handling.
- **2026-03-13** 🌐 Multi-provider web search, LangSmith, and broader reliability improvements.
- **2026-03-12** 🚀 VolcEngine support, Telegram reply context, `/restart`, and sturdier memory.
- **2026-03-11** 🔌 WeCom, Ollama, cleaner discovery, and safer tool behavior.
- **2026-03-10** 🧠 Token-based memory, shared retries, and cleaner gateway and Telegram behavior.
- **2026-03-09** 💬 Slack thread polish and better Feishu audio compatibility.
- **2026-03-08** 🚀 Released **v0.1.4.post4** — a reliability-packed release with safer defaults, better multi-instance support, sturdier MCP, and major channel and provider improvements. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post4) for details.
- **2026-03-07** 🚀 Azure OpenAI provider, WhatsApp media, QQ group chats, and more Telegram/Feishu polish.
- **2026-03-06** 🪄 Lighter providers, smarter media handling, and sturdier memory and CLI compatibility.
- **2026-03-05** ⚡️ Telegram draft streaming, MCP SSE support, and broader channel reliability fixes.
- **2026-03-04** 🛠️ Dependency cleanup, safer file reads, and another round of test and Cron fixes.
- **2026-03-03** 🧠 Cleaner user-message merging, safer multimodal saves, and stronger Cron guards.
- **2026-03-02** 🛡️ Safer default access control, sturdier Cron reloads, and cleaner Matrix media handling.
- **2026-03-01** 🌐 Web proxy support, smarter Cron reminders, and Feishu rich-text parsing improvements.
- **2026-02-28** 🚀 Released **v0.1.4.post3** — cleaner context, hardened session history, and smarter agent. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post3) for details.
- **2026-02-27** 🧠 Experimental thinking mode support, DingTalk media messages, Feishu and QQ channel fixes.
- **2026-02-26** 🛡️ Session poisoning fix, WhatsApp dedup, Windows path guard, Mistral compatibility.
- **2026-02-25** 🧹 New Matrix channel, cleaner session context, auto workspace template sync.
- **2026-02-24** 🚀 Released **v0.1.4.post2** — a reliability-focused release with a redesigned heartbeat, prompt cache optimization, and hardened provider & channel stability. See [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post2) for details.
- **2026-02-23** 🔧 Virtual tool-call heartbeat, prompt cache optimization, Slack mrkdwn fixes.
- **2026-02-22** 🛡️ Slack thread isolation, Discord typing fix, agent reliability improvements.
- **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.
- **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.
- **2026-02-14** 🔌 nanobot now supports MCP! See [MCP section](./docs/configuration.md#mcp-model-context-protocol) for details.
- **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](./docs/configuration.md#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!
</details>
For older updates, see the [release archive](./docs/release-archive.md) or [GitHub releases](https://github.com/HKUDS/nanobot/releases).
## 💡 Why nanobot
- **Persistent workflows**: goals, memory, tools, and chat context survive long-running work.
- **Chat-native reach**: WebUI, API, Telegram, Feishu, Slack, Discord, Teams, email, and Mattermost.
- **Chat-native reach**: WebUI, API, Telegram, Feishu, Slack, Discord, Teams, and email.
- **Model freedom**: OpenAI-compatible APIs, local LLMs, image generation, search, and fallbacks.
- **Small core**: readable internals with MCP, memory, deployment, and automation built in.
- **Own your stack**: inspect, customize, self-host, and extend without a giant platform.
@@ -110,13 +213,13 @@ For older updates, see the [release archive](./docs/release-archive.md) or [GitH
## 📦 Install
> [!IMPORTANT]
> If you want the newest features and experiments, install from source.
>
> If you want the newest features and experiments, install from source.
>
> If you want the most stable day-to-day experience, install from PyPI or with `uv`.
Pick **one** install method:
Prerequisites: Python 3.11 or newer. Git is only needed for a source install. Published packages already include the WebUI; a current-source install needs `bun` or `npm` to build it.
Prerequisites: Python 3.11 or newer. Git is only needed for a source install; Node.js/Bun are only needed if you are developing the WebUI itself.
If terminals, API keys, or config files are new to you, use the guided zero-background walkthrough in [Start Without Technical Background](./docs/start-without-technical-background.md) instead of this compact README path.
@@ -134,7 +237,7 @@ Windows PowerShell:
irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | iex
```
The default command installs or upgrades `nanobot-ai` from PyPI, then starts `nanobot onboard --wizard`. It avoids system-wide pip installs by using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`. If Quick Start finishes, skip the manual initialize/configure steps below and go straight to **Open the WebUI**. The installer also prints the exact command it used to run nanobot; reuse that full command below if `nanobot` is not on `PATH`.
The default command installs or upgrades `nanobot-ai` from PyPI, then starts `nanobot onboard --wizard`. It avoids system-wide pip installs by using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`. If Quick Start finishes and you enabled the WebSocket channel, skip the manual initialize/configure steps below and go straight to **Open the WebUI**.
To preview the plan without changing your environment, pass `--dry-run`; combine it with `--dev` when you want to preview the main-branch install.
@@ -174,24 +277,18 @@ If pip reports `externally-managed-environment` on macOS or Linux, use the one-c
**Install from source**
`bun` or `npm` must be available. From an activated virtual environment:
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install .
python -m pip install -e .
```
On Windows, if pip reports that it cannot launch `npm`, run `cd webui`, `npm.cmd install --package-lock=false`, `npm.cmd run build`, and `cd ..` in order, then retry the install. Contributors who need an editable checkout should follow [`CONTRIBUTING.md`](./CONTRIBUTING.md) and [`webui/README.md`](./webui/README.md).
Verify the install:
```bash
nanobot --version
```
If `nanobot` is not on `PATH`, invoke it through the method that installed it: reuse the recommended installer's command, use `uv tool run --from nanobot-ai nanobot ...` or `pipx run --spec nanobot-ai nanobot ...`, or use the Python executable from the environment where pip installed the package.
## 🚀 Quick Start
**1. Initialize**
@@ -261,13 +358,14 @@ For another provider, the same config shape still applies:
**3. Open the WebUI**
The stable-compatible path is:
If Quick Start enabled the WebSocket channel, start the gateway:
```bash
nanobot gateway
```
Leave the terminal open and visit `http://127.0.0.1:8765`. Current source versions also provide `nanobot webui`, which prepares the local WebSocket channel if needed, starts the gateway, and opens the browser automatically. The first-run WebUI binds to `127.0.0.1` by default, so it is not exposed to your LAN. Prefer not to keep a terminal open? Use `nanobot gateway --background`, then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password you set in the wizard, then send your first message there.
Prefer not to keep a terminal open? Use `nanobot gateway --background`, then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
For manual or terminal-only setup, test one CLI message:
@@ -301,13 +399,33 @@ The WebUI ships **inside the published wheel** — no extra build step. It is th
<img src="images/nanobot_webui.png" alt="nanobot webui preview" width="900">
</p>
**Open it**
**1. Enable the WebSocket channel in `~/.nanobot/config.json`**
```bash
nanobot webui
Merge this block into your existing config:
```json
{
"channels": {
"websocket": {
"enabled": true,
"tokenIssueSecret": "your-webui-password",
"websocketRequiresToken": true
}
}
}
```
On current source versions, the command enables the local WebSocket channel after confirmation, starts the gateway, and opens [`http://127.0.0.1:8765`](http://127.0.0.1:8765). If your installed stable release does not include `nanobot webui`, run `nanobot gateway` and open that address manually. To open it from another device on your LAN, see [WebUI docs -> LAN access](./docs/webui.md#lan-access).
**2. Start the gateway**
```bash
nanobot gateway
```
Use `nanobot gateway --background` for a local background process you can manage later with `nanobot gateway status`, `logs`, `restart`, and `stop`.
**3. Open the WebUI**
Visit [`http://127.0.0.1:8765`](http://127.0.0.1:8765) in your browser. To open it from another device on your LAN, see [WebUI docs -> LAN access](./docs/webui.md#lan-access).
The WebUI is served by the WebSocket channel on port `8765` by default. The gateway's `18790` port is for the health endpoint, not the browser UI.
@@ -349,7 +467,6 @@ The WebUI is served by the WebSocket channel on port `8765` by default. The gate
Browse the [repo docs](./docs/README.md) for the latest features and GitHub development version, or visit [nanobot.wiki](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview) for the stable release documentation.
- Use task-oriented guides: [Guides](./docs/guides/README.md)
- Start with no technical background: [Start Without Technical Background](./docs/start-without-technical-background.md)
- Start from zero with developer basics: [Install and Quick Start](./docs/quick-start.md)
- Understand the runtime model: [Concepts](./docs/concepts.md)
@@ -357,8 +474,7 @@ Browse the [repo docs](./docs/README.md) for the latest features and GitHub deve
- Choose a provider/model: [Providers and Models](./docs/providers.md)
- Copy provider setup recipes: [Provider Cookbook](./docs/provider-cookbook.md)
- Debug setup and runtime failures: [Troubleshooting](./docs/troubleshooting.md)
- Talk to your nanobot with familiar chat apps: [Chat App AI Agent](./docs/guides/chat-app-ai-agent.md) · [Chat Apps](./docs/chat-apps.md)
- Schedule or trigger agent work: [Automations](./docs/automations.md)
- Talk to your nanobot with familiar chat apps: [Chat Apps](./docs/chat-apps.md)
- Configure providers, web search, MCP, and runtime behavior: [Configuration](./docs/configuration.md)
- Integrate nanobot with local tools and automations: [OpenAI-Compatible API](./docs/openai-api.md) · [Python SDK](./docs/python-sdk.md)
- Run nanobot with Docker or as a Linux service: [Deployment](./docs/deployment.md)
@@ -381,7 +497,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, review, and contribution gui
## Contact
Nanobot was started by [Xubin Ren](https://github.com/re-bin) as a personal open-source project and is now maintained collaboratively with contributors from the open-source community. Feel free to contact [xubinrencs@gmail.com](mailto:xubinrencs@gmail.com) for questions, ideas, or collaboration.
This project was started by [Xubin Ren](https://github.com/re-bin) as a personal open-source project and continues to be maintained in an individual capacity using personal resources, with contributions from the open-source community. Feel free to contact [xubinrencs@gmail.com](mailto:xubinrencs@gmail.com) for questions, ideas, or collaboration.
### Contributors
@@ -389,6 +505,19 @@ Nanobot was started by [Xubin Ren](https://github.com/re-bin) as a personal open
<img src="https://contrib.rocks/image?repo=HKUDS/nanobot&max=100&columns=12&updated=20260210" alt="Contributors" />
</a>
## ⭐ Star History
<div align="center">
<a href="https://star-history.com/#HKUDS/nanobot&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/nanobot&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/nanobot&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/nanobot&type=Date" style="border-radius: 15px; box-shadow: 0 0 30px rgba(0, 217, 255, 0.3);" />
</picture>
</a>
</div>
<p align="center">
<em> Thanks for visiting ✨ nanobot!</em><br><br>
<img src="https://visitor-badge.laobi.icu/badge?page_id=HKUDS.nanobot&style=for-the-badge&color=00d4ff" alt="Views">
+1 -2
View File
@@ -107,7 +107,6 @@ File operations have path traversal protection, but:
**API Calls:**
- All external API calls use HTTPS by default
- Timeouts are configured to prevent hanging requests
- The OpenAI-compatible API server must set `api.api_key` when binding to `0.0.0.0` or `::`; otherwise startup fails to prevent unauthenticated network access
- Consider using a firewall to restrict outbound connections if needed
**WhatsApp:**
@@ -129,7 +128,7 @@ pip install --upgrade nanobot-ai
**Important Notes:**
- Keep `litellm` updated to the latest version for security fixes
- Run `pip-audit` regularly after enabling the channels used in production; their manifest-declared dependencies are installed into the same environment
- Run `pip-audit` regularly, including optional channel dependencies such as `nanobot-ai[whatsapp]`
- Subscribe to security advisories for nanobot and its dependencies
### 7. Production Deployment
-51
View File
@@ -1,51 +0,0 @@
"""Cross-suite test infrastructure."""
from __future__ import annotations
import os
import ssl
import sys
from collections.abc import Iterator
import certifi
import pytest
@pytest.fixture(scope="session", autouse=True)
def _use_windows_system_ca_for_default_http_clients() -> Iterator[None]:
"""Avoid reparsing certifi's CA bundle for every offline HTTP client.
Loading certifi takes roughly 0.7 seconds per client on Windows. The test
suite constructs hundreds of clients while mocking their I/O. System roots
preserve certificate verification for accidental local requests; explicit
``cafile``, ``capath``, and ``cadata`` arguments still use the real loader.
"""
if sys.platform != "win32":
yield
return
original = ssl.create_default_context
certifi_path = os.path.normcase(os.path.abspath(certifi.where()))
def create_default_context(
purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH,
*,
cafile: str | None = None,
capath: str | None = None,
cadata: str | bytes | None = None,
) -> ssl.SSLContext:
requested_path = os.path.normcase(os.path.abspath(cafile)) if cafile else None
if requested_path == certifi_path and capath is None and cadata is None:
return original(purpose)
return original(
purpose,
cafile=cafile,
capath=capath,
cadata=cadata,
)
ssl.create_default_context = create_default_context
try:
yield
finally:
ssl.create_default_context = original
-16
View File
@@ -1,16 +0,0 @@
x-bwrap-security: &bwrap-security
cap_add:
- SYS_ADMIN
security_opt:
- apparmor=unconfined
- seccomp=unconfined
services:
nanobot-gateway:
<<: *bwrap-security
nanobot-api:
<<: *bwrap-security
nanobot-cli:
<<: *bwrap-security
+6 -1
View File
@@ -6,6 +6,11 @@ x-common-config: &common-config
- ~/.nanobot:/home/nanobot/.nanobot
cap_drop:
- ALL
cap_add:
- SYS_ADMIN
security_opt:
- apparmor=unconfined
- seccomp=unconfined
services:
nanobot-gateway:
@@ -14,7 +19,7 @@ services:
command: ["gateway"]
restart: unless-stopped
ports:
- 127.0.0.1:18790:18790
- 18790:18790
- 8765:8765
deploy:
resources:
+86 -62
View File
@@ -1,84 +1,108 @@
# nanobot Documentation
# nanobot Docs
Use these docs to get a working agent first, then open a task guide only when you need the next capability. Source-level design and extension details are kept in the contributor section.
For published release documentation, visit [nanobot.wiki](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview). The pages in this directory track the current repository and may describe features that have not reached the published site yet.
Repository docs follow the current source tree and can be newer than the latest package release. For published release docs, visit [nanobot.wiki](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview).
If you have never used a terminal or edited a config file before, start with [`start-without-technical-background.md`](./start-without-technical-background.md). Otherwise, start with [`quick-start.md`](./quick-start.md) and get one local `nanobot agent -m "Hello!"` reply working before connecting chat apps, WebUI, Docker, or custom tools.
Most JSON examples in these docs are snippets to merge into `~/.nanobot/config.json`, not full replacement files.
Provider examples are concrete walkthroughs, not rankings or endorsements. Use the provider whose key, endpoint, and model ID you actually control.
If you find a docs mistake, outdated command, or confusing step, please open an issue: <https://github.com/HKUDS/nanobot/issues>.
## Pick a Track
| You are | Start with | Then use |
|---|---|---|
| New to terminals and config files | [`start-without-technical-background.md`](./start-without-technical-background.md) | [`troubleshooting.md`](./troubleshooting.md) if the first reply fails |
| Comfortable pasting commands and JSON | [`quick-start.md`](./quick-start.md) | [`provider-cookbook.md`](./provider-cookbook.md) for pasteable provider setups |
| Operating a long-running bot | [`concepts.md`](./concepts.md) | [`chat-apps.md`](./chat-apps.md), [`webui.md`](./webui.md), and [`deployment.md`](./deployment.md) |
| Integrating or extending nanobot | [`architecture.md`](./architecture.md) | [`configuration.md`](./configuration.md), [`openai-api.md`](./openai-api.md), [`python-sdk.md`](./python-sdk.md), [`development.md`](./development.md), and [`channel-plugin-guide.md`](./channel-plugin-guide.md) |
## Start Here
| Your situation | Read this | You are done when... |
| Goal | Read | Outcome |
|---|---|---|
| Terminals, Python, or API keys are new to you | [Beginner walkthrough](./start-without-technical-background.md) | The browser can send `Hello!` and receive a reply |
| You are comfortable running commands | [Install and Quick Start](./quick-start.md) | `nanobot status` is healthy and the WebUI or CLI can get one reply |
| Something already failed | [Troubleshooting](./troubleshooting.md) | You have isolated the problem to install, config, model, gateway, channel, or tool access |
| Start with no technical background | [`start-without-technical-background.md`](./start-without-technical-background.md) | One-command setup, terminal basics, config, API keys, and the first reply |
| Install and get the first reply | [`quick-start.md`](./quick-start.md) | A working CLI agent and a known-good config path |
| Understand how the pieces fit | [`concepts.md`](./concepts.md) | Mental model for config, workspace, gateway, channels, tools, memory, and sessions |
| Choose or change a model provider | [`providers.md`](./providers.md) | Correct provider/model pairing without reading the full config reference |
| Copy a provider setup recipe | [`provider-cookbook.md`](./provider-cookbook.md) | Pasteable OpenRouter, OpenAI, Anthropic, local model, fallback, and Langfuse setups |
| Fix a first-run or runtime problem | [`troubleshooting.md`](./troubleshooting.md) | A diagnosis order and targeted checks for common failures |
The recommended first-run path is:
## After the First Reply Works
1. Install nanobot.
2. Choose **Quick Start** in `nanobot onboard --wizard`.
3. Run `nanobot gateway` and open `http://127.0.0.1:8765`.
4. Send `Hello!` before configuring anything else.
Do not configure everything at once. Pick one next surface:
Most people do not need to edit JSON for the first run. The wizard handles the initial provider, model, and local WebUI settings. Current source versions also provide `nanobot webui` to start the gateway and open the browser in one step. After the WebUI opens, use **Settings** for models and built-in capabilities, **Settings → Channels** for chat apps, and **Apps** for CLI App or MCP integrations.
If a local `nanobot agent` session can already answer normally, you can also ask nanobot to help configure itself: have it read the relevant docs, inspect your current config, make one specific next change, and tell you when to run `/restart`.
## Add One Capability
| Next goal | Read | First check |
|---|---|---|
| Use nanobot in a browser | [`webui.md`](./webui.md) | Enable WebSocket, run `nanobot gateway`, open `http://127.0.0.1:8765` |
| Talk through a chat app | [`chat-apps.md`](./chat-apps.md) | Merge one channel snippet, run `nanobot channels status`, keep `nanobot gateway` running |
| Change provider or add fallbacks | [`provider-cookbook.md`](./provider-cookbook.md) | Keep `modelPresets` named and set `agents.defaults.modelPreset` |
| Call nanobot from Python | [`python-sdk.md`](./python-sdk.md) | Reuse the same config/workspace from code, then run or stream one agent turn |
| Understand before operating long-term | [`concepts.md`](./concepts.md) | Know what config, workspace, gateway, sessions, memory, and tools mean |
| Diagnose a new failure | [`troubleshooting.md`](./troubleshooting.md) | Start with `nanobot status`, then `nanobot agent -m "Hello!"` |
Pick the row that matches what you want to accomplish next:
## Use nanobot
| Goal | Guide |
|---|---|
| Learn the browser workbench | [WebUI](./webui.md) |
| Connect Telegram, Discord, Slack, Feishu, WeChat, Email, or another chat app | [Chat Apps](./chat-apps.md) |
| Choose a hosted, OAuth, company, or local model | [Provider Cookbook](./provider-cookbook.md) |
| Add model fallbacks | [Configure Model Fallback](./guides/configure-model-fallback.md) |
| Enable web search | [Configure Web Search](./guides/configure-web-search.md) |
| Add an MCP tool server | [Configure MCP Tools](./guides/configure-mcp-tools.md) |
| Generate images | [Image Generation](./image-generation.md) |
| Schedule work or create a local trigger | [Automations](./automations.md) |
| Understand and manage long-term memory | [Memory](./memory.md) |
| Run nanobot continuously | [Deployment](./deployment.md) |
| Run separate bots or workspaces | [Multiple Instances](./multiple-instances.md) |
| Call nanobot from Python | [Python SDK](./python-sdk.md) |
| Expose an OpenAI-compatible endpoint | [OpenAI-Compatible API](./openai-api.md) |
For shorter, outcome-focused walkthroughs, browse the [task guide index](./guides/README.md).
## Operate nanobot
| Need | Read |
|---|---|
| Commands and flags | [CLI Reference](./cli-reference.md) |
| In-chat slash commands | [In-Chat Commands](./chat-commands.md) |
| Config, workspace, gateway, sessions, tools, and memory in plain language | [Concepts](./concepts.md) |
| Provider/model matching and selection | [Providers and Models](./providers.md) |
| Setup and runtime diagnosis | [Troubleshooting](./troubleshooting.md) |
| Older development highlights | [Release Archive](./release-archive.md) |
| Goal | Read | Outcome |
|---|---|---|
| Open the bundled browser UI | [`webui.md`](./webui.md) | WebUI on port `8765`, chat workspace, Apps, Skills, Automations, and settings |
| Connect Telegram, Discord, WeChat, Slack, and other apps | [`chat-apps.md`](./chat-apps.md) | A gateway-backed chat channel with access control |
| Use slash commands and periodic tasks | [`chat-commands.md`](./chat-commands.md) | Pairing, model presets, heartbeat tasks, and chat-side controls |
| Generate images | [`image-generation.md`](./image-generation.md) | Image provider config, WebUI image mode, and artifact behavior |
| Run several isolated bots | [`multiple-instances.md`](./multiple-instances.md) | Separate configs, workspaces, ports, and sessions |
| Deploy outside a terminal | [`deployment.md`](./deployment.md) | Docker, systemd user services, and macOS LaunchAgent setup |
| Join agent communities | [`agent-social-network.md`](./agent-social-network.md) | External agent-community setup |
## Reference
Use reference pages to look up an exact option after you know what you are trying to configure:
| Area | Read | Best for |
|---|---|---|
| Full configuration schema | [`configuration.md`](./configuration.md) | Exact fields, defaults, provider tables, web tools, MCP, security, and runtime options |
| CLI commands | [`cli-reference.md`](./cli-reference.md) | Command names, common flags, and entrypoints |
| Architecture | [`architecture.md`](./architecture.md) | Source-level runtime map for core flow, providers, channels, tools, WebUI, memory, security, and extension points |
| Development | [`development.md`](./development.md) | Contributor notes for adding providers and transcription adapters |
| Memory | [`memory.md`](./memory.md) | Session history, Dream consolidation, memory files, and versioning |
| Observability | [`configuration.md#langfuse-observability`](./configuration.md#langfuse-observability) | Langfuse tracing setup and required environment variables |
| WebSocket protocol | [`websocket.md`](./websocket.md) | Custom clients, token issuance, multiplexed chats, media, and protocol events |
| OpenAI-compatible API | [`openai-api.md`](./openai-api.md) | `/v1/chat/completions`, `/v1/models`, file uploads, and SDK-compatible usage |
| Python SDK | [`python-sdk.md`](./python-sdk.md) | SDK 101, sessions, streaming, model overrides, runtime helpers, and hooks |
| Runtime self-inspection | [`my-tool.md`](./my-tool.md) | Inspecting and tuning the current agent run |
| Area | Reference |
## Fast Lookup
| Need | Jump to |
|---|---|
| Every configuration field and default | [Configuration](./configuration.md) |
| Provider and model behavior | [Providers and Models](./providers.md) |
| Chat channel prerequisites and manual JSON | [Chat Apps](./chat-apps.md) |
| WebSocket authentication and wire protocol | [WebSocket](./websocket.md) |
| Python SDK classes, events, sessions, and hooks | [Python SDK](./python-sdk.md) |
| OpenAI-compatible HTTP routes and payloads | [OpenAI-Compatible API](./openai-api.md) |
| Runtime self-inspection and tuning | [My Tool](./my-tool.md) |
| Provider/model resolution order | [`providers.md#provider-resolution`](./providers.md#provider-resolution) |
| Model presets and fallback chains | [`providers.md#model-presets`](./providers.md#model-presets) and [`providers.md#fallback-models`](./providers.md#fallback-models) |
| Langfuse environment variables | [`configuration.md#langfuse-observability`](./configuration.md#langfuse-observability) |
| WebSocket/WebUI protocol details | [`websocket.md`](./websocket.md) |
| OpenAI-compatible API usage | [`openai-api.md`](./openai-api.md) |
| Python SDK usage | [`python-sdk.md`](./python-sdk.md) |
| Multiple configs, workspaces, and ports | [`multiple-instances.md`](./multiple-instances.md) |
| Security, sandboxing, and SSRF controls | [`configuration.md#security`](./configuration.md#security) |
| Channel plugin development | [`channel-plugin-guide.md`](./channel-plugin-guide.md) |
Configuration examples are usually snippets to merge into `~/.nanobot/config.json`, not complete replacement files. The docs use camelCase because nanobot writes config that way. Keep real API keys, bot tokens, and passwords out of issues and public logs.
## Extend nanobot
## Extend or Contribute
| Goal | Read | Outcome |
|---|---|---|
| Add a provider or transcription adapter | [`development.md`](./development.md) | A registry/schema-aligned implementation path |
| Add a chat channel plugin | [`channel-plugin-guide.md`](./channel-plugin-guide.md) | A packaged channel discovered through entry points |
| Add custom MCP servers | [`configuration.md#mcp-model-context-protocol`](./configuration.md#mcp-model-context-protocol) | External tools exposed to the agent through MCP |
| Tune tool safety | [`configuration.md#security`](./configuration.md#security) | Shell sandboxing, workspace restriction, and SSRF policy |
These pages explain implementation and extension points. You do not need them to install or operate nanobot.
## Reading Strategy
| Goal | Read |
|---|---|
| Understand source ownership and runtime flow | [Architecture](./architecture.md) |
| Set up a development environment | [Development](./development.md) and [CONTRIBUTING.md](../CONTRIBUTING.md) |
| Add a channel package | [Channel Package Guide](./channel-package-guide.md) |
| Build the WebUI source | [WebUI Development](../webui/README.md) |
Use the docs in this order when you are unsure where to go:
If a command or screen no longer matches these docs, please [open an issue](https://github.com/HKUDS/nanobot/issues) with your nanobot version, operating system, and the page that needs correction.
1. If terminal commands or config files are new to you, [`start-without-technical-background.md`](./start-without-technical-background.md) explains the setup words and uses one concrete provider example so there is only one decision at a time.
2. [`quick-start.md`](./quick-start.md) proves installation, config loading, and provider access.
3. [`concepts.md`](./concepts.md) explains the runtime model so later pages are easier to scan.
4. [`provider-cookbook.md`](./provider-cookbook.md) gives pasteable provider, fallback, local model, and Langfuse recipes.
5. A task guide, such as [`chat-apps.md`](./chat-apps.md), [`image-generation.md`](./image-generation.md), or [`deployment.md`](./deployment.md), gets one workflow working.
6. [`configuration.md`](./configuration.md) is the source of truth when you need a specific field, default value, or advanced option.
7. [`troubleshooting.md`](./troubleshooting.md) helps isolate whether a failure is install, config, provider, gateway, channel, or tool related.
+6 -95
View File
@@ -1,99 +1,10 @@
# Agent Social Network
An agent social network lets a nanobot instance join an external agent community
or chat network as a bot identity. After joining, nanobot can receive messages
through that network, answer with its normal agent runtime, and use the same
workspace, tools, memory, and channel access controls that apply elsewhere.
🐈 nanobot is capable of linking to the agent social network (agent community). **Just send one message and your nanobot joins automatically!**
This page describes the current entry points and the safety model. Treat each
network as an external integration: only join networks you trust, keep owner
approval narrow, and review the skill instructions before asking nanobot to
follow them.
| Platform | How to Join (send this message to your bot) |
|----------|-------------|
| [**Moltbook**](https://www.moltbook.com/) | `Read https://moltbook.com/skill.md and follow the instructions to join Moltbook` |
| [**ClawdChat**](https://clawdchat.ai/) | `Read https://clawdchat.ai/skill.md and follow the instructions to join ClawdChat` |
## What is an agent social network?
In nanobot docs, an agent social network is an external community that publishes
setup instructions for nanobot-compatible agents. The setup usually lives in a
remote `skill.md` file. You send nanobot a message asking it to read that file
and follow the network's registration flow.
The external network is not part of nanobot core. nanobot provides the runtime:
model calls, tools, memory, sessions, and channel delivery.
> [!WARNING]
> Remote `skill.md` files are external instructions. Review them before asking
> nanobot to follow them, especially when file, shell, network, or chat-delivery
> tools are enabled. Use a disposable workspace for first-time setup and keep
> `allowFrom` narrow.
## What nanobot can do after joining
After setup, the exact behavior depends on the network, but the normal pattern
is:
- receive direct messages or community messages addressed to the bot
- reply through the configured network channel
- use normal nanobot tools allowed by your configuration
- keep session history for conversations that flow through the network
- use Dream memory if memory is enabled for the workspace
## Supported networks
| Platform | Join message to send to your bot |
|---|---|
| [Moltbook](https://www.moltbook.com/) | `Read https://moltbook.com/skill.md and follow the instructions to join Moltbook` |
| [ClawdChat](https://clawdchat.ai/) | `Read https://clawdchat.ai/skill.md and follow the instructions to join ClawdChat` |
Send the message from the CLI, WebUI, or an already configured chat channel.
nanobot will read the public setup instructions and perform the requested setup
using its available tools.
## Security model
- The remote setup instructions are external content. Read them yourself before
running the join prompt if the bot has file, shell, or network tools enabled.
- Keep `allowFrom` narrow on the channel you use for setup so only trusted users
can issue registration commands.
- Keep `tools.restrictToWorkspace` enabled unless the network setup explicitly
needs another path.
- Avoid `allowFrom: ["*"]` during setup unless the bot is isolated in a test
workspace.
- Store network tokens through environment variables when the integration
supports secrets.
## Example workflow
1. Confirm the local agent works:
```bash
nanobot agent -m "Hello!"
```
2. Open the WebUI or a trusted chat channel.
3. Send the join message for the network you want.
4. Restart the gateway if the setup changes channel configuration:
```bash
nanobot gateway
```
5. Send a test message through the external network and confirm the session is
routed to the expected workspace and model.
## Limitations
- Network features, identity, and moderation rules are controlled by the
external network.
- Availability depends on the remote setup instructions remaining reachable.
- nanobot does not automatically audit remote skills for you.
- Some networks may require public callbacks, tokens, or channel-specific
account setup.
## Related docs
- [Chat Apps](./chat-apps.md)
- [Security configuration](./configuration.md#security)
- [Pairing](./configuration.md#pairing)
- [Runtime self-inspection](./my-tool.md)
Simply send the command above to your nanobot (via CLI or any chat channel), and it will handle the rest.
+4 -4
View File
@@ -81,11 +81,11 @@ Main files:
| Area | Files |
|---|---|
| Base channel contract | `nanobot/channels/base.py` |
| Channel packages | `nanobot/channels/<channel>/` |
| Built-in channels | `nanobot/channels/*.py` |
| Discovery and lifecycle | `nanobot/channels/manager.py` |
| WebSocket/WebUI channel | `nanobot/channels/websocket/` |
| WebSocket/WebUI channel | `nanobot/channels/websocket.py` |
Channels are discovered by scanning self-contained packages under `nanobot/channels/`. Add a channel by contributing one package that follows [`channel-package-guide.md`](./channel-package-guide.md).
Channels are discovered through built-in module scanning and plugin entry points. A custom channel should follow [`channel-plugin-guide.md`](./channel-plugin-guide.md).
## WebUI and Gateway
@@ -181,7 +181,7 @@ When changing tools, channels, file access, WebUI workspace behavior, or network
| Extension | How |
|---|---|
| Provider | Add `ProviderSpec` in `providers/registry.py`, add schema field in `config/schema.py`, implement provider only if the generic backend is not enough |
| Channel | Export a `ChannelPlugin` descriptor, keep its runtime and optional setup surfaces in one package, and follow [`channel-package-guide.md`](./channel-package-guide.md) |
| Channel | Implement `BaseChannel`, expose an entry point, follow [`channel-plugin-guide.md`](./channel-plugin-guide.md) |
| Tool | Implement a tool under `agent/tools/` or expose a plugin entry point |
| MCP | Add `tools.mcpServers` config |
| Skill | Add workspace skill files under `<workspace>/skills/` or built-in skills under `nanobot/skills/` |
-201
View File
@@ -1,201 +0,0 @@
# Automations
<!-- Meta description: Create, run, and manage nanobot scheduled automations, local triggers, and heartbeat-backed background checks. -->
Automations are agent turns that run later in a linked chat/session. Use them
when nanobot should do work without someone actively typing: reminders,
recurring checks, nightly summaries, CI follow-ups, local script reports, or
webhook-driven events.
Create automations from the chat, channel, or WebUI session where the result
should appear. That lets nanobot keep the right session history, workspace, and
reply target.
## Choose an Automation Type
| Type | Starts from | Best for | Created with |
|---|---|---|---|
| Scheduled automation | Time, interval, or cron expression | Recurring reminders, scheduled summaries, one-time future tasks | Ask nanobot in the target session to schedule it with the `cron` tool |
| Local trigger | A local `nanobot trigger ...` command | CI jobs, webhooks, shell scripts, generated reports | `/trigger <name>` in the target session |
| Heartbeat | Protected system schedule | Quiet recurring checks that should only report useful results | Edit `<workspace>/HEARTBEAT.md` |
The two user-created automation types are scheduled automations and local
triggers. Heartbeat uses the same background service but is system-managed and
protected from normal automation edits.
## Before You Create One
Keep `nanobot gateway` running. The gateway owns background delivery for chat
apps, WebUI sessions, scheduled automations, local triggers, heartbeat, and
Dream jobs.
Use the same workspace and config for the gateway and any process that sends
local trigger messages. If you run multiple nanobot instances, pass the matching
`--config` or `--workspace` option to `nanobot trigger`.
Create each automation from the target session. An automation without a linked
chat/session cannot be enabled or run from the WebUI because nanobot would not
know where to deliver the turn.
## Scheduled Automations
Scheduled automations are created by the agent's `cron` tool. In practice, ask
nanobot from the target chat or WebUI session:
```text
Every weekday at 9am, check open pull requests and summarize blockers here.
```
or:
```text
Tomorrow at 4pm, remind me to send the release notes.
```
The cron tool supports interval schedules, cron expressions, and one-time
scheduled tasks. Cron expressions can include an IANA timezone such as
`America/Vancouver`; otherwise nanobot uses the runtime default timezone.
Scheduled automations normally deliver the result back to the session where they
were created. Use them for work that should run on a predictable schedule and
report each run.
For background checks that should stay quiet unless there is something useful to
report, use heartbeat instead of a user-created scheduled automation.
## Local Triggers
Local triggers let a local script or external service send a message into a
specific nanobot session later.
Create the trigger from the chat or WebUI session where future messages should
arrive:
```text
/trigger PR review
```
nanobot replies with a trigger ID and a command shaped like:
```bash
nanobot trigger trg_8K4P2Q9X "Review PR #4502"
```
Replace the quoted text with the message nanobot should receive. For generated
or longer content, pipe stdin:
```bash
generate-report | nanobot trigger trg_8K4P2Q9X
```
For multiple instances, use the same config or workspace selector as the
gateway:
```bash
nanobot trigger --config ./bot-a/config.json trg_8K4P2Q9X "Nightly report"
nanobot trigger --workspace ./bot-a/workspace trg_8K4P2Q9X "Nightly report"
```
nanobot does not provide a built-in public webhook receiver for local triggers.
If GitHub, CI, or another external system should wake nanobot, run your own
small webhook service and have it call `nanobot trigger` after it builds the
final message.
## Heartbeat
Heartbeat is for recurring workspace checks that should usually stay quiet. It
reads `<workspace>/HEARTBEAT.md`, executes active tasks, and sends only useful or
actionable results to the most recently active chat target.
Use heartbeat for checks such as "watch this repo for important failures" or
"periodically inspect this workspace and only tell me when action is needed." Use
a scheduled automation instead when every run should produce a visible reminder
or report.
Heartbeat is enabled by default when `nanobot gateway` starts. Configure it in
[`configuration.md#gateway-heartbeat`](./configuration.md#gateway-heartbeat).
## Manage Automations
Use the WebUI Automations view to:
- filter by all, active, paused, needs-attention, or system jobs;
- search by task name, message, trigger command, linked chat, schedule, or
status;
- sort by next run, last run, updated time, or name;
- run scheduled automations now;
- pause or resume, rename, or delete user-created automations;
- copy the CLI command for local triggers;
- inspect protected system automations without changing them.
Local triggers do not have a WebUI "Run now" action because each run needs a
message. Copy the `nanobot trigger ...` command from the WebUI and replace
`"message"` with the content that should be delivered.
## Delivery and Reliability
Automation delivery is workspace-local. Scheduled jobs and local trigger
deliveries use the same workspace as the gateway.
Local trigger messages are written to a durable queue. If the gateway is not
running yet, the message waits in that workspace. If the linked session is
already running a turn, the trigger waits until the session becomes idle instead
of being injected into the active turn.
The local trigger queue is at-least-once, not exactly-once. If the gateway exits
after claiming a delivery but before the linked turn completes, the next gateway
start requeues that delivery. External scripts should make repeated trigger
messages safe. If the delivery reaches the agent and the turn fails, the
delivery is marked failed instead of retrying forever.
Each local trigger delivery writes an audit record under
`<workspace>/triggers/runs`. Run one gateway consumer per workspace; the local
queue is not a distributed multi-consumer queue.
## Common Patterns
For a nightly report, ask from the target session:
```text
Every night at 9pm, review today's workspace changes and summarize anything I should handle tomorrow.
```
For a CI follow-up, create a trigger once:
```text
/trigger CI follow-up
```
Then have your CI or webhook adapter call:
```bash
nanobot trigger <trigger-id> "Build failed on main. Inspect the logs and suggest the next fix."
```
For a local report script:
```bash
generate-report | nanobot trigger <trigger-id>
```
## Troubleshooting
If an automation does not run, check that `nanobot gateway` is running, the
automation is enabled, and it was created from a linked chat/session.
If a local trigger waits forever, confirm the command uses the same workspace or
config as the gateway.
If a trigger message appears twice after a restart, treat it as expected
at-least-once delivery and make the external message idempotent.
If you need to edit, pause, resume, rename, delete, or inspect automations, use
the WebUI Automations view.
## Related Docs
- [`webui.md#automations`](./webui.md#automations) for the browser management view
- [`chat-commands.md#local-triggers`](./chat-commands.md#local-triggers) for `/trigger`
- [`cli-reference.md#local-triggers`](./cli-reference.md#local-triggers) for `nanobot trigger`
- [`configuration.md#gateway-heartbeat`](./configuration.md#gateway-heartbeat) for heartbeat settings
- [`guides/long-running-ai-agent.md`](./guides/long-running-ai-agent.md) for long-running agent work
-792
View File
@@ -1,792 +0,0 @@
# Channel Package Guide
Use this guide to add a self-contained channel package to the nanobot repository. A channel is part of nanobot when its package lives at `nanobot/channels/<channel>/`; there is no separate external channel-plugin path.
> **Breaking change:** nanobot no longer discovers the `nanobot.channels` Python entry-point group. Move an entry-point implementation into `nanobot/channels/<channel>/` with a package-owned manifest, runtime, tests, and optional WebUI contribution.
## How It Works
When `nanobot gateway` starts, nanobot scans the packages under `nanobot/channels/` and loads each dependency-free `ChannelPlugin` descriptor from `manifest.py`.
If a matching config section has `"enabled": true`, the channel is instantiated and started.
## Ownership and Sources of Truth
| Concern | Owner and source of truth |
|---------|---------------------------|
| Runtime behavior and platform SDK use | `runtime.py` and package-local helpers |
| Python package requirements | `ChannelPlugin.dependencies` in `manifest.py` |
| Writable settings fields, types, defaults, requirements, secret handling, and validation | `ChannelPlugin.setup` in `manifest.py` |
| Persisted config expansion, instance updates, and runtime naming | `ChannelPlugin.management` backed by a dependency-free module |
| Interactive setup connections and their short-lived state | `ChannelPlugin.connector` backed by package-local `connect.py` |
| Reusable local login-state detection | `ChannelPlugin.management.local_state_present` backed by package-local code |
| Discovery metadata and lazy runtime target | `PLUGIN` in `manifest.py` |
| WebUI structure, components, URLs, field keys, actions, and preset values | `webui/index.ts` or `webui/index.tsx` |
| Channel-specific user-facing copy | `webui/locales/<locale>.json` |
| Generic settings-shell copy shared by every channel | `webui/src/i18n/locales/<locale>/common.json` |
Keep one source of truth for each concern. In particular, the backend setup contract decides what may be written, the TypeScript contribution decides how those fields are presented, and locale JSON supplies the channel-specific words shown to users.
## Quick Start
We'll build a minimal webhook channel that receives messages via HTTP POST and sends replies back.
### Project Structure
```text
nanobot/channels/webhook/
├── __init__.py # lightweight package marker; do not import the runtime
├── manifest.py # dependency-free ChannelPlugin descriptor
├── runtime.py # channel implementation and optional SDK imports
├── tests/ # package-local tests
└── webui/ # optional settings UI and translations
```
### 1. Create Your Channel
```python
# nanobot/channels/webhook/__init__.py
"""Webhook channel package."""
```
```python
# nanobot/channels/webhook/manifest.py
from nanobot.channels.contracts import ChannelFieldSpec, ChannelSetupSpec
from nanobot.channels.plugin import ChannelPlugin
PLUGIN = ChannelPlugin(
name="webhook",
display_name="Webhook",
runtime=f"{__package__}.runtime:WebhookChannel",
dependencies=("aiohttp>=3.9.0,<4.0.0",),
setup=ChannelSetupSpec(
fields={
"port": ChannelFieldSpec(kind="int", default=9000),
"allowFrom": ChannelFieldSpec(kind="list"),
},
),
)
```
```python
# nanobot/channels/webhook/runtime.py
import asyncio
from typing import Any
from aiohttp import web
from loguru import logger
from pydantic import Field
from nanobot.channels.base import BaseChannel
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
@classmethod
def default_config(cls) -> dict[str, Any]:
return WebhookConfig().model_dump(by_alias=True)
async def start(self) -> None:
"""Start an HTTP server that listens for incoming messages.
IMPORTANT: start() must block forever (or until stop() is called).
If it returns, the channel is considered dead.
"""
self._running = True
port = self.config.port
app = web.Application()
app.router.add_post("/message", self._on_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", port)
await site.start()
logger.info("Webhook listening on :{}", port)
# Block until stopped
while self._running:
await asyncio.sleep(1)
await runner.cleanup()
async def stop(self) -> None:
self._running = False
async def send(self, msg: OutboundMessage) -> None:
"""Deliver an outbound message.
msg.content — markdown text (convert to platform format as needed)
msg.media — list of local file paths to attach
msg.chat_id — the recipient (same chat_id you passed to _handle_message)
msg.metadata — channel routing context such as message/thread ids
msg.event — typed runtime event for progress/status messages
"""
logger.info("[webhook] -> {}: {}", msg.chat_id, msg.content[:80])
# In a real plugin: POST to a callback URL, send via SDK, etc.
async def _on_request(self, request: web.Request) -> web.Response:
"""Handle an incoming HTTP POST."""
body = await request.json()
sender = body.get("sender", "unknown")
chat_id = body.get("chat_id", sender)
text = body.get("text", "")
media = body.get("media", []) # list of URLs
# This is the key call: validates allowFrom, then puts the
# message onto the bus for the agent to process.
await self._handle_message(
sender_id=sender,
chat_id=chat_id,
content=text,
media=media,
)
return web.json_response({"ok": True})
```
The package directory, `PLUGIN.name`, runtime class name, and config section must all use `webhook`. Channel names use a portable ASCII package identifier: they start with a letter and contain only letters, digits, or underscores.
Declare runtime requirements directly in `ChannelPlugin.dependencies`. Do not add channel requirements to the root `pyproject.toml`: the package manifest is the source of truth used by the CLI, WebUI, and gateway startup. Keep the manifest and anything it imports free of the optional SDK itself.
### 2. Configure
```bash
nanobot plugins list # verify the channel package appears as "webhook"
nanobot onboard # add default config for detected channels
```
Edit `~/.nanobot/config.json`:
```json
{
"channels": {
"webhook": {
"enabled": true,
"port": 9000,
"allowFrom": ["*"]
}
}
}
```
nanobot always loads the dependency-free descriptor during discovery. When the WebUI gateway starts, it installs missing requirements for enabled channels before importing their runtimes. It also installs them when a channel is enabled from the CLI or WebUI. Status, configuration, and disable operations do not need the runtime. Single-instance and multi-instance channels use the same activation rules.
### 3. Run & Test
```bash
nanobot gateway
```
In another terminal:
```bash
curl -X POST http://localhost:9000/message \
-H "Content-Type: application/json" \
-d '{"sender": "user1", "chat_id": "user1", "text": "Hello!"}'
```
The agent receives the message and processes it. Replies arrive in your `send()` method.
## Channel Package Requirements
Every channel is a self-contained package at `nanobot/channels/<channel>/`; channel-specific runtime code, setup metadata, tests, WebUI structure, components, and translations stay under that directory.
### Package Layout
```text
nanobot/channels/<channel>/
├── __init__.py # package marker only; no runtime or SDK imports
├── manifest.py # dependency-free ChannelPlugin and ChannelSetupSpec
├── config.py # optional dependency-free config model and defaults
├── connect.py # optional interactive setup connector
├── instances.py # optional dependency-free multi-instance management adapter
├── state.py # optional persisted login-state detection
├── validation.py # optional package-owned setup checks
├── runtime.py # BaseChannel implementation and platform SDK imports
├── tests/ # channel-specific Python tests
└── webui/ # optional, compiled into the shared WebUI
├── index.ts or index.tsx # structure and optional React components
└── locales/
├── en.json # canonical locale shape
└── <locale>.json # one file for every supported WebUI locale
```
Do not add a runtime module directly under `nanobot/channels/`, create a parallel manifest tree, or add a central per-channel UI catalog. If existing channel files move, use `git mv` so history remains traceable.
### Manifest and Runtime Boundary
`manifest.py` exports a typed `ChannelPlugin` whose `runtime` target is an absolute import target, such as `nanobot.channels.telegram.runtime:TelegramChannel`; using `f"{__package__}.runtime:TelegramChannel"` keeps it package-owned without repeating the package path. Discovery imports the manifest before it knows whether the optional platform dependency is installed, so `manifest.py` must not import `runtime.py` or any platform SDK. Import runtime symbols from `runtime.py` explicitly; `__init__.py` remains an inert package marker.
The manifest owns the channel name, display name, setup contract, management adapter, optional connector target, optional dependency extra, capabilities, default activation, and optional WebUI entry path. The management adapter alone decides whether a channel is single-instance or multi-instance.
Interactive browser setup uses one small connector contract. Set `connector=f"{__package__}.connect:MyConnectStore"`; the target is loaded only when `/api/settings/channels/<name>/connect/{start,poll,cancel}` is called. The store exposes one async `handle(action, query)` method and keeps platform-specific parsing, sessions, and errors inside the channel package. The shared settings router only authenticates, dispatches, and applies a successful connection.
Use the small constructors in [`nanobot/channels/_manifest.py`](../nanobot/channels/_manifest.py) for declarative field and requirement definitions. Use [`nanobot/channels/dingtalk/manifest.py`](../nanobot/channels/dingtalk/manifest.py) as a compact single-instance example and [`nanobot/channels/feishu/`](../nanobot/channels/feishu/) as a multi-instance example.
### Package-owned WebUI
Set `webui="webui/index.ts"` or `webui="webui/index.tsx"` in the channel manifest. Candidate modules are bundled from channel packages, but the settings UI activates only the exact path returned by the backend feature payload.
The entry module exports one default `ChannelUiContribution`. Channel identity comes from the package directory, so do not repeat a `channel` field in TypeScript. Keep only structure and executable UI data in this module: presentation metadata, icons or logo URLs, docs URLs, config field keys, action payloads, preset values, aliases, and optional `Panel` or `ConnectFlow` components.
Do not put static descriptions, setup steps, labels, placeholders, help text, action labels, or preset labels in TSX. Those strings belong in the channel's locale JSON. TSX remains appropriate for dynamic rendering, interpolation, conditions, and rich component composition.
### Channel-owned i18n
Create `webui/locales/<locale>.json` for every locale code declared in [`webui/src/i18n/config.ts`](../webui/src/i18n/config.ts). Treat `en.json` as the canonical shape; every other locale must contain the same message keys and the same interpolation variables. `displayName` may be omitted when the product name should remain unchanged.
```json
{
"description": "Use nanobot from Example chats.",
"requirements": "Example app credentials and gateway",
"setup": {
"docsLabel": "Open Example setup",
"officialLabel": "Open Example console",
"summary": "Example needs app credentials.",
"tryIt": "Send a test message.",
"steps": [
"Create an Example app.",
"Add the credentials.",
"Save, enable, and test the channel."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Example client ID",
"help": "Copy it from the Example console."
}
},
"actions": {
"copyManifest": "Copy manifest"
},
"presets": {
"default": "Default"
}
},
"custom": {
"connected": "{{name}} is connected."
}
}
```
Field messages are keyed by the config path after `channels.<channel>.`, with remaining punctuation converted to underscores. For example, `channels.signal.dm.allowFrom` maps to `setup.fields.dm_allowFrom`. Action and preset messages use the IDs declared in the TypeScript contribution.
Custom channel components should read dynamic copy with `channelTranslator(t, "<channel>")`; keep the English fallback adjacent to the call so an incomplete translation still renders useful text. Aliases reuse the owning channel's locale namespace rather than duplicating translations.
The dependency direction is intentional:
- [`webui/src/i18n/index.ts`](../webui/src/i18n/index.ts) imports the pure JSON [`channel-plugins/locale-registry.ts`](../webui/src/channel-plugins/locale-registry.ts).
- The locale registry discovers only `nanobot/channels/*/webui/locales/*.json` and must not import the UI registry, React, or TSX.
- Settings components may consume both the UI registry and locale registry.
- Channel UI code may use shared types and generic settings components, but core settings code must not add `if (feature.name === "...")` branches for individual channels.
This separation prevents i18n initialization from eagerly loading every channel React component and keeps channel-specific ownership below the channel package.
### Tests and Definition of Done
Put channel-specific Python tests in `nanobot/channels/<channel>/tests/`. Keep only shared registry, manager, base-class, and cross-channel contract tests in `tests/channels/`. Release builds exclude package-local tests while the repository test configuration discovers both trees.
For a focused channel change, run the smallest relevant set:
```bash
uv run pytest nanobot/channels/<channel>/tests -q
cd webui
bun run test -- src/tests/channel-locale-registry.test.ts src/tests/channel-ui-registry.test.ts src/tests/channel-identity.test.ts
bun run lint
bun run build
```
Before considering the change complete, verify all of the following:
- The manifest can be discovered without importing the runtime or optional platform SDK.
- `ChannelSetupSpec` contains every writable field and rejects unknown fields.
- The TypeScript field, action, and preset IDs have matching English locale messages.
- Every supported locale matches the English key shape and interpolation variables.
- Generic settings copy remains in core `common.json`; channel-specific copy remains inside the channel package.
- User-facing WebUI changes work through the built frontend served by a real gateway, including language switching and refresh persistence.
- Markdown prose paragraphs and individual list items remain on one source line; let the renderer handle visual wrapping.
## BaseChannel API
### Required (abstract)
| Method | Description |
|--------|-------------|
| `async start()` | **Must block forever.** Connect to platform, listen for messages, call `_handle_message()` on each. If this returns, the channel is dead. |
| `async stop()` | Set `self._running = False` and clean up. Called when gateway shuts down. |
| `async send(msg: OutboundMessage)` | Deliver an outbound message to the platform. Raise when the transport does not accept it. |
#### Outbound delivery contract
A normal return from `send()` means either the visible payload was accepted by the platform transport/API, or the channel deliberately had nothing to deliver, such as an empty progress event. Do not log and return when the client is disconnected, still starting, or the platform rejects the request. Raise an exception so `ChannelManager` can apply the shared retry policy.
`send()` may run as soon as `is_running` becomes true. If a channel sets `_running` before its transport is ready, it must keep raising until delivery can be attempted safely. Small platform-specific retries are fine, but the final failure must still reach the manager.
### Interactive Login
If your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:
```python
async def login(self, force: bool = False) -> bool:
"""
Perform channel-specific interactive login.
Args:
force: If True, ignore existing credentials and re-authenticate.
Returns True if already authenticated or login succeeds.
"""
# For QR-code-based login:
# 1. If force, clear saved credentials
# 2. Check if already authenticated (load from disk/state)
# 3. If not, show QR code and poll for confirmation
# 4. Save token on success
```
Channels that don't need interactive login (e.g. Telegram with bot token, Discord with bot token) inherit the default `login()` which just returns `True`.
Users trigger interactive login via:
```bash
nanobot channels login <channel_name>
nanobot channels login <channel_name> --force # re-authenticate
```
### Provided by Base
| Method / Property | Description |
|-------------------|-------------|
| `_handle_message(sender_id, chat_id, content, media?, metadata?, session_key?)` | **Call this when you receive a message.** Checks `is_allowed()`, then publishes to the bus. Automatically sets `_wants_stream` if `supports_streaming` is true. |
| `is_allowed(sender_id)` | Checks against `config.allow_from`; `"*"` allows all, `[]` denies all. |
| `default_config()` (classmethod) | Returns runtime-local defaults for callers that construct the class directly. Discovery and onboarding use the descriptor instead. |
| `refresh_feature_metadata(config_path, instance_id)` (classmethod) | Optionally refreshes saved display metadata after an explicit settings action. It is never called by a read-only feature GET. |
| `transcribe_audio(file_path)` | Transcribes audio via the shared top-level `transcription` config (if configured). |
| `supports_streaming` (property) | `True` when config has `"streaming": true` **and** subclass overrides `send_delta()`. |
| `is_running` | Returns `self._running`. |
| `login(force=False)` | Perform interactive login (e.g. QR code scan). Returns `True` if already authenticated or login succeeds. Override in subclasses that support interactive login. |
| `send_reasoning_delta(chat_id, delta, metadata?, *, stream_id?)` | Optional hook for streamed model reasoning/thinking content. Default is no-op. |
| `send_reasoning_end(chat_id, metadata?, *, stream_id?)` | Optional hook marking the end of a reasoning block. Default is no-op. |
| `send_reasoning(msg)` | Optional one-shot reasoning fallback. Default translates to `send_reasoning_delta()` + `send_reasoning_end()`. |
### Optional management contract
Persisted-state management belongs to `ChannelPlugin.management`, not `BaseChannel`. Keep the adapter and anything it imports free of optional platform SDKs so status, settings, and disable operations still work when the runtime cannot be imported. Runtime classes own network lifecycle, message delivery, interactive login, enable-time availability checks, and explicit runtime-only actions such as metadata refresh.
```python
from nanobot.channels.contracts import ChannelFieldSpec, ChannelSetupSpec, SetupRequirement
from nanobot.channels.plugin import ChannelPlugin
from .instances import MANAGEMENT
PLUGIN = ChannelPlugin(
name="webhook",
display_name="Webhook",
runtime=f"{__package__}.channel:WebhookChannel",
setup=ChannelSetupSpec(
fields={
"token": ChannelFieldSpec(kind="secret"),
"region": ChannelFieldSpec(
kind="enum",
choices=frozenset({"us", "eu"}),
default="us",
),
},
required=(SetupRequirement.field("token"),),
),
management=MANAGEMENT,
)
```
`instances.py` then exports the dependency-free adapter assembled from channel-owned callbacks:
```python
from typing import Any
from nanobot.channels.contracts import ChannelInstanceSpec, ChannelManagementSpec
from .config import default_config
def instance_specs(section: Any, *, enabled_only: bool = True) -> list[ChannelInstanceSpec]:
... # Expand the persisted channel-owned envelope.
def update_instance_config(
section: Any,
values: dict[str, Any],
*,
instance_id: str = "default",
) -> dict[str, Any]:
... # Update one instance without discarding sibling data.
MANAGEMENT = ChannelManagementSpec(
multi_instance=True,
default_config=default_config,
instance_specs=instance_specs,
update_instance_config=update_instance_config,
)
```
`ChannelSetupSpec` is authoritative for writable field names, field types, choices, defaults, required setup, secret redaction, and optional backend validation. The settings API rejects fields outside this contract. A validator receives `(values, context)`; use `context.allow_local_service_access` for host network policy instead of loading global config from the channel package.
The dependency-free `MANAGEMENT` value is a `ChannelManagementSpec`. Multi-instance plugins provide `instance_specs(section, enabled_only=True)` and `update_instance_config(section, values, instance_id=...)`; they may also provide `default_config`, `runtime_name`, presentation-only `feature_instances`, and `local_state_present`. Single-instance plugins normally derive onboarding defaults from `ChannelSetupSpec`; use `default_config` only when persisted defaults include fields that are not part of generic setup.
Multi-instance adapters return `ChannelInstanceSpec` objects and preserve their persisted envelope when updating one instance. Their descriptor sets `ChannelManagementSpec(multi_instance=True)`. The shared contract enforces these invariants:
- every `instance_id` is non-empty and unique;
- the management adapter's `runtime_name(channel_name, instance_id)` is the single source of routing names, and every derived name is unique and is either the channel name or starts with `<channel-name>.`;
- runtime names cannot overwrite a runtime already owned by another channel;
- settings instance summaries are generated from `instance_specs()` and `ChannelPlugin.setup`. They contain the authoritative `enabled` and `configured` state plus secret-safe `config_values` and `configured_fields` for the generic instance editor;
- the management adapter's `feature_instances()` may return `None` or presentation overrides containing an `id` plus `name`, `display_name`, or `avatar_url`. It cannot override runtime state or the configuration snapshot.
`ChannelInstanceSpec` contains only `instance_id` and the instance config; nanobot derives its runtime name through the adapter. Single-instance plugins keep ownership of their entire config, including a field named `instances`. Only plugins whose management spec sets `multi_instance=True` opt into instance expansion.
The package/config section name owns every runtime produced from that section. Class inheritance does not transfer runtime ownership to another package.
Return a concrete iterable or generator from the adapter's `instance_specs()`; nanobot materializes and validates it before constructing any runtime. Raise an exception for malformed persisted data rather than silently changing instance identity. Keep network-backed metadata refresh behind the runtime's `refresh_feature_metadata()` so feature GET requests remain dependency-free and read-only.
For package layout, WebUI ownership, and localization rules, see [Channel Package Requirements](#channel-package-requirements).
### Optional (streaming)
| Method | Description |
|--------|-------------|
| `async send_delta(chat_id, delta, metadata?, *, stream_id?, stream_end=False, resuming=False)` | Override to receive streaming chunks. See [Streaming Support](#streaming-support) for details. |
### Message Types
```python
@dataclass
class OutboundMessage:
channel: str # your channel name
chat_id: str # recipient (same value you passed to _handle_message)
content: str # markdown text — convert to platform format as needed
media: list[str] # local file paths to attach (images, audio, docs)
metadata: dict # channel routing context, e.g. "message_id" for threading
event: object | None # typed runtime/UI event; usually inspect with isinstance()
```
Runtime/UI semantics live on `msg.event`. Plugin-authored outbound messages should use typed events instead of legacy metadata flags such as `_progress`, `_stream_delta`, `_stream_end`, `_reasoning_delta`, `_turn_end`, or `_goal_status`. nanobot still accepts those old flags as a compatibility bridge for existing in-process extensions, but new plugin code should not add fresh dependencies on them.
## Streaming Support
Channels can opt into real-time streaming — the agent sends content token-by-token instead of one final message. This is entirely optional; channels work fine without it.
### How It Works
When **both** conditions are met, the agent streams content through your channel:
1. Config has `"streaming": true`
2. Your subclass overrides `send_delta()`
If either is missing, the agent falls back to the normal one-shot `send()` path.
### Implementing `send_delta`
Override `send_delta` to handle two types of calls:
```python
async def send_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
stream_end: bool = False,
resuming: bool = False,
) -> None:
buffer_key = stream_id or chat_id
if stream_end:
# Streaming finished — do final formatting, cleanup, etc.
return
# Regular delta — append text, update the message on screen
# delta contains a small chunk of text (a few tokens)
```
Streaming state is passed through keyword-only arguments, not `_stream_delta` or `_stream_end` metadata flags. Use `stream_id` to key any per-stream buffers; fall back to `chat_id` when it is missing.
### Example: Webhook with Streaming
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._buffers: dict[str, str] = {}
async def send_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
stream_end: bool = False,
resuming: bool = False,
) -> None:
buffer_key = stream_id or chat_id
if stream_end:
text = self._buffers.pop(buffer_key, "")
# Final delivery — format and send the complete message
await self._deliver(chat_id, text, final=True)
return
self._buffers.setdefault(buffer_key, "")
self._buffers[buffer_key] += delta
# Incremental update — push partial text to the client
await self._deliver(chat_id, self._buffers[buffer_key], final=False)
async def send(self, msg: OutboundMessage) -> None:
# Non-streaming path — unchanged
await self._deliver(msg.chat_id, msg.content, final=True)
```
### Config
Enable streaming per channel:
```json
{
"channels": {
"webhook": {
"enabled": true,
"streaming": true,
"allowFrom": ["*"]
}
}
}
```
When `streaming` is `false` (default) or omitted, only `send()` is called — no streaming overhead.
### BaseChannel Streaming API
| Method / Property | Description |
|-------------------|-------------|
| `async send_delta(chat_id, delta, metadata?, *, stream_id?, stream_end=False, resuming=False)` | Override to handle streaming chunks. No-op by default. |
| `supports_streaming` (property) | Returns `True` when config has `streaming: true` **and** subclass overrides `send_delta`. |
## Progress, Tool Hints, and Reasoning
Besides normal assistant text, nanobot can emit low-emphasis trace blocks. These are intended for UI affordances like status rows, collapsible "used tools" groups, or reasoning/thinking blocks. Platforms that do not have a good place for them can ignore them safely.
### Progress and Tool Hints
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.event` before rendering:
```python
from nanobot.bus.outbound_events import ProgressEvent
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, ProgressEvent) and event.tool_hint:
# A short tool breadcrumb, e.g. read_file("config.json")
await self._send_trace(msg.chat_id, msg.content, kind="tool")
return
if isinstance(event, ProgressEvent):
# Generic non-final status, e.g. "Thinking..." or "Running command..."
await self._send_trace(msg.chat_id, msg.content, kind="progress")
return
await self._send_message(msg.chat_id, msg.content, media=msg.media)
```
Tool hints are off by default for most channels. Users can enable them globally or per channel:
```json
{
"channels": {
"sendToolHints": true,
"webhook": {
"enabled": true,
"sendToolHints": true
}
}
}
```
### Reasoning Blocks
Reasoning is delivered through dedicated optional hooks, not `send()`. Override `send_reasoning_delta()` and `send_reasoning_end()` if your platform can show model reasoning as a subdued/collapsible block. The default implementation is a no-op, so unsupported channels simply drop reasoning content.
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._reasoning_buffers: dict[str, str] = {}
async def send_reasoning_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
) -> None:
buffer_key = stream_id or chat_id
self._reasoning_buffers[buffer_key] = self._reasoning_buffers.get(buffer_key, "") + delta
await self._update_reasoning_block(chat_id, self._reasoning_buffers[buffer_key], final=False)
async def send_reasoning_end(
self,
chat_id: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
) -> None:
buffer_key = stream_id or chat_id
text = self._reasoning_buffers.pop(buffer_key, "")
if text:
await self._update_reasoning_block(chat_id, text, final=True)
```
**Reasoning arguments:**
| Argument | Meaning |
|------|---------|
| `delta` | A reasoning/thinking chunk for `send_reasoning_delta()`. |
| `stream_id` | Stable id for this assistant turn/segment. Use it to key buffers instead of only `chat_id`. |
| `send_reasoning_end()` | The current reasoning block is complete. |
Reasoning visibility is controlled by `showReasoning` globally or per channel:
```json
{
"channels": {
"showReasoning": true,
"webhook": {
"enabled": true,
"showReasoning": true
}
}
}
```
Recommended rendering:
- Render tool hints and progress as trace/status UI, not as normal assistant replies.
- Render reasoning with lower visual emphasis and collapse it after completion when the platform supports that.
- Keep reasoning separate from final answer text. A final answer still arrives through `send()` or `send_delta()`.
## Config
### Why Pydantic model is required
`BaseChannel.is_allowed()` reads the permission list via `getattr(self.config, "allow_from", [])`. This works for Pydantic models where `allow_from` is a real Python attribute, but **fails silently for plain `dict`**`dict` has no `allow_from` attribute, so `getattr` always returns the default `[]`, causing all messages to be denied.
Channel runtimes use Pydantic config models by subclassing `Base` from `nanobot.config.schema`.
### Pattern
1. Define a Pydantic model inheriting from `nanobot.config.schema.Base`:
```python
from pydantic import Field
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
```
`Base` is configured with `alias_generator=to_camel` and `populate_by_name=True`, so JSON keys like `"allowFrom"` and `"allow_from"` are both accepted.
2. Convert `dict` → model in `__init__`:
```python
from typing import Any
from nanobot.bus.queue import MessageBus
class WebhookChannel(BaseChannel):
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
```
3. Access config as attributes (not `.get()`):
```python
async def start(self) -> None:
port = self.config.port
token = self.config.token
```
`allowFrom` is handled automatically by `_handle_message()` — you don't need to check it yourself.
`nanobot onboard` reads the descriptor without importing the runtime. Put writable defaults in `ChannelSetupSpec`:
```python
setup=ChannelSetupSpec(
fields={
"port": ChannelFieldSpec(kind="int", default=9000),
"allowFrom": ChannelFieldSpec(kind="list"),
},
)
```
String and secret fields default to `""`, list fields to `[]`, and boolean fields to `false` when no explicit default is declared. For non-setup or multi-instance persisted defaults, provide `ChannelManagementSpec.default_config` from a dependency-free package-local module.
## Naming Convention
| What | Format | Example |
|------|--------|---------|
| Package directory | `nanobot/channels/{name}` | `nanobot/channels/webhook` |
| Manifest name | `{name}` | `webhook` |
| Config section | `channels.{name}` | `channels.webhook` |
| Runtime import | `nanobot.channels.{name}.runtime` | `nanobot.channels.webhook.runtime` |
## Local Development
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install -e .
nanobot plugins list # should show the package as "webhook"
nanobot gateway # test end-to-end
```
## Verify
```bash
$ nanobot plugins list
Name Type Enabled
discord channel no
telegram channel yes
webhook channel yes
```
+550
View File
@@ -0,0 +1,550 @@
# Channel Plugin Guide
Build a custom nanobot channel in three steps: subclass, package, install.
> **Note:** We recommend developing channel plugins against a source checkout of nanobot (`python -m pip install -e .`) rather than a PyPI release, so you always have access to the latest base-channel features and APIs.
## How It Works
nanobot discovers channel plugins via Python [entry points](https://packaging.python.org/en/latest/specifications/entry-points/). When `nanobot gateway` starts, it scans:
1. Built-in channels in `nanobot/channels/`
2. External packages registered under the `nanobot.channels` entry point group
If a matching config section has `"enabled": true`, the channel is instantiated and started.
## Quick Start
We'll build a minimal webhook channel that receives messages via HTTP POST and sends replies back.
### Project Structure
```text
nanobot-channel-webhook/
├── nanobot_channel_webhook/
│ ├── __init__.py # re-export WebhookChannel
│ └── channel.py # channel implementation
└── pyproject.toml
```
### 1. Create Your Channel
```python
# nanobot_channel_webhook/__init__.py
from nanobot_channel_webhook.channel import WebhookChannel
__all__ = ["WebhookChannel"]
```
```python
# nanobot_channel_webhook/channel.py
import asyncio
from typing import Any
from aiohttp import web
from loguru import logger
from pydantic import Field
from nanobot.channels.base import BaseChannel
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
@classmethod
def default_config(cls) -> dict[str, Any]:
return WebhookConfig().model_dump(by_alias=True)
async def start(self) -> None:
"""Start an HTTP server that listens for incoming messages.
IMPORTANT: start() must block forever (or until stop() is called).
If it returns, the channel is considered dead.
"""
self._running = True
port = self.config.port
app = web.Application()
app.router.add_post("/message", self._on_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", port)
await site.start()
logger.info("Webhook listening on :{}", port)
# Block until stopped
while self._running:
await asyncio.sleep(1)
await runner.cleanup()
async def stop(self) -> None:
self._running = False
async def send(self, msg: OutboundMessage) -> None:
"""Deliver an outbound message.
msg.content — markdown text (convert to platform format as needed)
msg.media — list of local file paths to attach
msg.chat_id — the recipient (same chat_id you passed to _handle_message)
msg.metadata — may contain "_progress": True for streaming chunks
"""
logger.info("[webhook] -> {}: {}", msg.chat_id, msg.content[:80])
# In a real plugin: POST to a callback URL, send via SDK, etc.
async def _on_request(self, request: web.Request) -> web.Response:
"""Handle an incoming HTTP POST."""
body = await request.json()
sender = body.get("sender", "unknown")
chat_id = body.get("chat_id", sender)
text = body.get("text", "")
media = body.get("media", []) # list of URLs
# This is the key call: validates allowFrom, then puts the
# message onto the bus for the agent to process.
await self._handle_message(
sender_id=sender,
chat_id=chat_id,
content=text,
media=media,
)
return web.json_response({"ok": True})
```
### 2. Register the Entry Point
```toml
# pyproject.toml
[project]
name = "nanobot-channel-webhook"
version = "0.1.0"
dependencies = ["nanobot-ai", "aiohttp"]
[project.entry-points."nanobot.channels"]
webhook = "nanobot_channel_webhook:WebhookChannel"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["nanobot_channel_webhook"]
```
The key (`webhook`) becomes the config section name. The value points to your `BaseChannel` subclass.
### 3. Install & Configure
```bash
python -m pip install -e .
nanobot plugins list # verify "Webhook" shows as "plugin"
nanobot onboard # auto-adds default config for detected plugins
```
Edit `~/.nanobot/config.json`:
```json
{
"channels": {
"webhook": {
"enabled": true,
"port": 9000,
"allowFrom": ["*"]
}
}
}
```
### 4. Run & Test
```bash
nanobot gateway
```
In another terminal:
```bash
curl -X POST http://localhost:9000/message \
-H "Content-Type: application/json" \
-d '{"sender": "user1", "chat_id": "user1", "text": "Hello!"}'
```
The agent receives the message and processes it. Replies arrive in your `send()` method.
## BaseChannel API
### Required (abstract)
| Method | Description |
|--------|-------------|
| `async start()` | **Must block forever.** Connect to platform, listen for messages, call `_handle_message()` on each. If this returns, the channel is dead. |
| `async stop()` | Set `self._running = False` and clean up. Called when gateway shuts down. |
| `async send(msg: OutboundMessage)` | Deliver an outbound message to the platform. |
### Interactive Login
If your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:
```python
async def login(self, force: bool = False) -> bool:
"""
Perform channel-specific interactive login.
Args:
force: If True, ignore existing credentials and re-authenticate.
Returns True if already authenticated or login succeeds.
"""
# For QR-code-based login:
# 1. If force, clear saved credentials
# 2. Check if already authenticated (load from disk/state)
# 3. If not, show QR code and poll for confirmation
# 4. Save token on success
```
Channels that don't need interactive login (e.g. Telegram with bot token, Discord with bot token) inherit the default `login()` which just returns `True`.
Users trigger interactive login via:
```bash
nanobot channels login <channel_name>
nanobot channels login <channel_name> --force # re-authenticate
```
### Provided by Base
| Method / Property | Description |
|-------------------|-------------|
| `_handle_message(sender_id, chat_id, content, media?, metadata?, session_key?)` | **Call this when you receive a message.** Checks `is_allowed()`, then publishes to the bus. Automatically sets `_wants_stream` if `supports_streaming` is true. |
| `is_allowed(sender_id)` | Checks against `config.allow_from`; `"*"` allows all, `[]` denies all. |
| `default_config()` (classmethod) | Returns default config dict for `nanobot onboard`. Override to declare your fields. |
| `transcribe_audio(file_path)` | Transcribes audio via the shared top-level `transcription` config (if configured). |
| `supports_streaming` (property) | `True` when config has `"streaming": true` **and** subclass overrides `send_delta()`. |
| `is_running` | Returns `self._running`. |
| `login(force=False)` | Perform interactive login (e.g. QR code scan). Returns `True` if already authenticated or login succeeds. Override in subclasses that support interactive login. |
| `send_reasoning_delta(chat_id, delta, metadata?)` | Optional hook for streamed model reasoning/thinking content. Default is no-op. |
| `send_reasoning_end(chat_id, metadata?)` | Optional hook marking the end of a reasoning block. Default is no-op. |
| `send_reasoning(msg)` | Optional one-shot reasoning fallback. Default translates to `send_reasoning_delta()` + `send_reasoning_end()`. |
### Optional (streaming)
| Method | Description |
|--------|-------------|
| `async send_delta(chat_id, delta, metadata?)` | Override to receive streaming chunks. See [Streaming Support](#streaming-support) for details. |
### Message Types
```python
@dataclass
class OutboundMessage:
channel: str # your channel name
chat_id: str # recipient (same value you passed to _handle_message)
content: str # markdown text — convert to platform format as needed
media: list[str] # local file paths to attach (images, audio, docs)
metadata: dict # may contain: "_progress" (bool) for streaming chunks,
# "message_id" for reply threading
```
## Streaming Support
Channels can opt into real-time streaming — the agent sends content token-by-token instead of one final message. This is entirely optional; channels work fine without it.
### How It Works
When **both** conditions are met, the agent streams content through your channel:
1. Config has `"streaming": true`
2. Your subclass overrides `send_delta()`
If either is missing, the agent falls back to the normal one-shot `send()` path.
### Implementing `send_delta`
Override `send_delta` to handle two types of calls:
```python
async def send_delta(self, chat_id: str, delta: str, metadata: dict[str, Any] | None = None) -> None:
meta = metadata or {}
if meta.get("_stream_end"):
# Streaming finished — do final formatting, cleanup, etc.
return
# Regular delta — append text, update the message on screen
# delta contains a small chunk of text (a few tokens)
```
**Metadata flags:**
| Flag | Meaning |
|------|---------|
| `_stream_delta: True` | A content chunk (delta contains the new text) |
| `_stream_end: True` | Streaming finished (delta is empty) |
### Example: Webhook with Streaming
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._buffers: dict[str, str] = {}
async def send_delta(self, chat_id: str, delta: str, metadata: dict[str, Any] | None = None) -> None:
meta = metadata or {}
if meta.get("_stream_end"):
text = self._buffers.pop(chat_id, "")
# Final delivery — format and send the complete message
await self._deliver(chat_id, text, final=True)
return
self._buffers.setdefault(chat_id, "")
self._buffers[chat_id] += delta
# Incremental update — push partial text to the client
await self._deliver(chat_id, self._buffers[chat_id], final=False)
async def send(self, msg: OutboundMessage) -> None:
# Non-streaming path — unchanged
await self._deliver(msg.chat_id, msg.content, final=True)
```
### Config
Enable streaming per channel:
```json
{
"channels": {
"webhook": {
"enabled": true,
"streaming": true,
"allowFrom": ["*"]
}
}
}
```
When `streaming` is `false` (default) or omitted, only `send()` is called — no streaming overhead.
### BaseChannel Streaming API
| Method / Property | Description |
|-------------------|-------------|
| `async send_delta(chat_id, delta, metadata?)` | Override to handle streaming chunks. No-op by default. |
| `supports_streaming` (property) | Returns `True` when config has `streaming: true` **and** subclass overrides `send_delta`. |
## Progress, Tool Hints, and Reasoning
Besides normal assistant text, nanobot can emit low-emphasis trace blocks. These are intended for UI affordances like status rows, collapsible "used tools" groups, or reasoning/thinking blocks. Platforms that do not have a good place for them can ignore them safely.
### Progress and Tool Hints
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.metadata` before rendering:
```python
async def send(self, msg: OutboundMessage) -> None:
meta = msg.metadata or {}
if meta.get("_tool_hint"):
# A short tool breadcrumb, e.g. read_file("config.json")
await self._send_trace(msg.chat_id, msg.content, kind="tool")
return
if meta.get("_progress"):
# Generic non-final status, e.g. "Thinking..." or "Running command..."
await self._send_trace(msg.chat_id, msg.content, kind="progress")
return
await self._send_message(msg.chat_id, msg.content, media=msg.media)
```
Tool hints are off by default for most channels. Users can enable them globally or per channel:
```json
{
"channels": {
"sendToolHints": true,
"webhook": {
"enabled": true,
"sendToolHints": true
}
}
}
```
### Reasoning Blocks
Reasoning is delivered through dedicated optional hooks, not `send()`. Override `send_reasoning_delta()` and `send_reasoning_end()` if your platform can show model reasoning as a subdued/collapsible block. The default implementation is a no-op, so unsupported channels simply drop reasoning content.
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._reasoning_buffers: dict[str, str] = {}
async def send_reasoning_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
) -> None:
meta = metadata or {}
stream_id = str(meta.get("_stream_id") or chat_id)
self._reasoning_buffers[stream_id] = self._reasoning_buffers.get(stream_id, "") + delta
await self._update_reasoning_block(chat_id, self._reasoning_buffers[stream_id], final=False)
async def send_reasoning_end(
self,
chat_id: str,
metadata: dict[str, Any] | None = None,
) -> None:
meta = metadata or {}
stream_id = str(meta.get("_stream_id") or chat_id)
text = self._reasoning_buffers.pop(stream_id, "")
if text:
await self._update_reasoning_block(chat_id, text, final=True)
```
**Reasoning metadata flags:**
| Flag | Meaning |
|------|---------|
| `_reasoning_delta: True` | A reasoning/thinking chunk; `delta` contains the new text. |
| `_reasoning_end: True` | The current reasoning block is complete; `delta` is empty. |
| `_reasoning: True` | Legacy one-shot reasoning. `BaseChannel.send_reasoning()` converts it to delta + end. |
| `_stream_id` | Stable id for this assistant turn/segment. Use it to key buffers instead of only `chat_id`. |
Reasoning visibility is controlled by `showReasoning` globally or per channel:
```json
{
"channels": {
"showReasoning": true,
"webhook": {
"enabled": true,
"showReasoning": true
}
}
}
```
Recommended rendering:
- Render tool hints and progress as trace/status UI, not as normal assistant replies.
- Render reasoning with lower visual emphasis and collapse it after completion when the platform supports that.
- Keep reasoning separate from final answer text. A final answer still arrives through `send()` or `send_delta()`.
## Config
### Why Pydantic model is required
`BaseChannel.is_allowed()` reads the permission list via `getattr(self.config, "allow_from", [])`. This works for Pydantic models where `allow_from` is a real Python attribute, but **fails silently for plain `dict`**`dict` has no `allow_from` attribute, so `getattr` always returns the default `[]`, causing all messages to be denied.
Built-in channels use Pydantic config models (subclassing `Base` from `nanobot.config.schema`). Plugin channels **must do the same**.
### Pattern
1. Define a Pydantic model inheriting from `nanobot.config.schema.Base`:
```python
from pydantic import Field
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
```
`Base` is configured with `alias_generator=to_camel` and `populate_by_name=True`, so JSON keys like `"allowFrom"` and `"allow_from"` are both accepted.
2. Convert `dict` → model in `__init__`:
```python
from typing import Any
from nanobot.bus.queue import MessageBus
class WebhookChannel(BaseChannel):
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
```
3. Access config as attributes (not `.get()`):
```python
async def start(self) -> None:
port = self.config.port
token = self.config.token
```
`allowFrom` is handled automatically by `_handle_message()` — you don't need to check it yourself.
Override `default_config()` so `nanobot onboard` auto-populates `config.json`:
```python
@classmethod
def default_config(cls) -> dict[str, Any]:
return WebhookConfig().model_dump(by_alias=True)
```
> **Note:** `default_config()` returns a plain `dict` (not a Pydantic model) because it's used to serialize into `config.json`. The recommended way is to instantiate your config model and call `model_dump(by_alias=True)` — this automatically uses camelCase keys (`allowFrom`) and keeps defaults in a single source of truth.
If not overridden, the base class returns `{"enabled": false}`.
## Naming Convention
| What | Format | Example |
|------|--------|---------|
| PyPI package | `nanobot-channel-{name}` | `nanobot-channel-webhook` |
| Entry point key | `{name}` | `webhook` |
| Config section | `channels.{name}` | `channels.webhook` |
| Python package | `nanobot_channel_{name}` | `nanobot_channel_webhook` |
## Local Development
```bash
git clone https://github.com/you/nanobot-channel-webhook
cd nanobot-channel-webhook
python -m pip install -e .
nanobot plugins list # should show "Webhook" as "plugin"
nanobot gateway # test end-to-end
```
## Verify
```bash
$ nanobot plugins list
Name Source Enabled
telegram builtin yes
discord builtin no
webhook plugin yes
```
+21 -112
View File
@@ -1,22 +1,6 @@
# Chat Apps for Self-Hosted AI Agents
# Chat Apps
Connect nanobot to Telegram, Discord, Slack, WeChat, Email, Mattermost, and
other chat platforms. This page is the full chat-channel reference. If you want
a focused setup path for one platform, start with a guide:
| Platform | Guide |
|---|---|
| Telegram | [Build a Telegram AI Agent with nanobot](./guides/telegram-ai-agent.md) |
| Discord | [Build a Discord AI Agent with nanobot](./guides/discord-ai-agent.md) |
| Slack | [Build a Slack AI Agent with nanobot](./guides/slack-ai-agent.md) |
| Feishu | [Build a Feishu AI Agent with nanobot](./guides/feishu-ai-agent.md) |
| WhatsApp | [Build a WhatsApp AI Agent with nanobot](./guides/whatsapp-ai-agent.md) |
| WeChat | [Build a WeChat AI Agent with nanobot](./guides/wechat-ai-agent.md) |
| QQ | [Build a QQ AI Agent with nanobot](./guides/qq-ai-agent.md) |
| Email | [Build an Email AI Agent with nanobot](./guides/email-ai-agent.md) |
| Mattermost | [Build a Mattermost AI Agent with nanobot](./guides/mattermost-ai-agent.md) |
Want to build your own channel? See the [Channel Package Guide](./channel-package-guide.md).
Connect nanobot to your favorite chat platform. Want to build your own? See the [Channel Plugin Guide](./channel-plugin-guide.md).
Before configuring a chat app, make sure the local CLI path works:
@@ -26,67 +10,33 @@ nanobot agent -m "Hello!"
If that fails, fix installation, config, provider, or model setup first with [`quick-start.md`](./quick-start.md), [`providers.md`](./providers.md), and [`troubleshooting.md`](./troubleshooting.md). Chat apps require `nanobot gateway` to stay running after the channel is configured.
## Recommended Setup in the WebUI
Most examples below are snippets to merge into `~/.nanobot/config.json`.
For normal local setup, let the WebUI write and validate the channel config:
1. Run `nanobot webui`.
2. Open **Settings → Channels**.
3. Search for the platform and open its setup panel.
4. Follow the credential fields or QR flow. The screen tells you which platform-side token, permission, account, or URL it needs.
5. Let nanobot install the optional channel support when prompted.
6. Restart from the WebUI if it reports that a restart is required.
7. Send a private test message. If the channel returns a pairing code, approve the pending request in the WebUI and send the message again.
If your installed stable release does not show **Settings → Channels**, continue with the [manual setup pattern](#manual-setup-pattern) below or install current source.
Optional package installation is available to a same-machine WebUI by default. Remote browser clients cannot change the Python environment unless an administrator explicitly enables that capability. Run `nanobot plugins enable <channel>` locally when the guided install is unavailable.
The sections below explain what each chat platform requires and provide manual config for deployments that manage `config.json` directly.
> [!NOTE]
> If you are upgrading from a version where chat app SDKs were installed by default,
> install the channel extra in the same Python environment before enabling or
> restarting that channel:
>
> ```bash
> nanobot plugins enable <channel>
> ```
>
> Replace `<channel>` with names such as `telegram`, `slack`, `feishu`,
> `dingtalk`, `matrix`, `qq`, `napcat`, `weixin`, `wecom`, or `msteams`.
> To turn a channel off later, run `nanobot plugins disable <channel>`.
> nanobot keeps the saved settings, but stops loading that channel after the
> next restart.
## Manual Setup Pattern
Most examples below are snippets to merge into `~/.nanobot/config.json`. When a snippet includes `allowFrom`, it is showing a static allowlist. For pairing-based access on supported channels, omit `allowFrom`; Slack and Mattermost also need `dm.policy` set to `"allowlist"` for DMs to issue pairing codes.
## Common Setup Pattern
Every chat app uses the same shape:
1. Create or prepare the bot/account in the chat platform.
2. Copy the token, secret, QR login state, webhook URL, or account ID that platform gives you.
3. Merge that platform's JSON snippet into `~/.nanobot/config.json`.
4. Prefer pairing for DM-capable channels: omit `allowFrom`, let the first DM receive a pairing code, then approve it with `/pairing approve <code>`.
5. For channels without pairing, such as Email, keep access narrow with `allowFrom` or the platform-specific allow list.
6. Check that nanobot can see the configured channel:
4. Keep access control narrow at first with `allowFrom` or the platform-specific allow list.
5. Check that nanobot can see the configured channel:
```bash
nanobot channels status
```
7. Start the gateway and leave that terminal running:
6. Start the gateway and leave that terminal running:
```bash
nanobot gateway
```
8. Send a test DM. If the bot returns a pairing code, approve it and send the message again. In group chats, follow that channel's `groupPolicy` behavior: many channels default to mention-only, while Matrix and WhatsApp default to open group replies.
7. Send a message from the allowed account. In group chats, follow that channel's `groupPolicy` behavior: many channels default to mention-only, while Matrix and WhatsApp default to open group replies.
If `nanobot channels status` does not show the channel as enabled, the config snippet is in the wrong place, the channel name is misspelled, or the config file you edited is not the one nanobot is reading. If the channel is enabled but messages do not arrive, run `nanobot gateway --verbose` and compare the platform-side credentials, event permissions, and allow lists.
> `allowFrom: ["*"]` bypasses pairing and allows anyone who can reach that channel to talk to the bot. Use it only when that is intentional, or temporarily while testing in a private sandbox.
> `["*"]` allows anyone who can reach that channel to talk to the bot. Use it only when that is intentional, or temporarily while testing in a private sandbox.
| Channel | What you need |
|---------|---------------|
@@ -109,12 +59,6 @@ If `nanobot channels status` does not show the channel as enabled, the config sn
<details>
<summary><b>Telegram</b></summary>
**Install the optional channel dependency**
```bash
nanobot plugins enable telegram
```
**1. Create a bot**
- Open Telegram, search `@BotFather`
- Send `/newbot`, follow prompts
@@ -179,14 +123,6 @@ Telegram uses long polling by default. To receive updates through a webhook, exp
Uses **Socket.IO WebSocket** by default, with HTTP polling fallback.
**Install the optional realtime dependency**
```bash
nanobot plugins enable mochat
```
Without this extra, Mochat still works through HTTP polling.
**1. Ask nanobot to set up Mochat for you**
Simply send this message to nanobot (replace `xxx@xxx` with your real email):
@@ -297,14 +233,14 @@ nanobot gateway
<details>
<summary><b>Matrix (Element)</b></summary>
Enable Matrix support first:
Install Matrix dependencies first:
```bash
nanobot plugins enable matrix
python -m pip install "nanobot-ai[matrix]"
```
> [!NOTE]
> Matrix encryption is disabled by default on Windows because `matrix-nio[e2e]` depends on `python-olm`, which has no pre-built Windows wheel. Use macOS, Linux, or WSL2 if you need Matrix E2EE.
> Matrix is not supported on Windows. `matrix-nio[e2e]` depends on `python-olm`, which has no pre-built Windows wheel and is skipped by the `matrix` extra on `sys_platform == 'win32'`. The command above will still succeed on Windows but without `matrix-nio` installed, so enabling the Matrix channel will fail at startup. Use macOS, Linux, or WSL2.
**1. Create/choose a Matrix account**
@@ -370,7 +306,9 @@ nanobot gateway
Requires the WhatsApp optional dependencies:
```bash
nanobot plugins enable whatsapp
pip install "nanobot-ai[whatsapp]"
# Source checkout:
python -m pip install -e ".[whatsapp]"
```
**1. Link device with QR**
@@ -393,10 +331,6 @@ nanobot channels login whatsapp
}
```
For groups, `allowFrom` can contain either a participant sender ID/LID or a
group JID/bare group ID. A participant entry allows that sender wherever the bot
can see them; a group entry allows replies in that group.
Optional session database path:
```json
@@ -450,7 +384,6 @@ Uses **WebSocket** long connection — no public IP required.
**Quick setup: QR login**
```bash
nanobot plugins enable feishu
nanobot channels login feishu
# Use --force to create/sign in with a new bot
```
@@ -521,12 +454,6 @@ nanobot gateway
Uses **botpy SDK** with WebSocket — no public IP required. Currently supports **private messages only**.
**Install the optional channel dependency**
```bash
nanobot plugins enable qq
```
**1. Register & create bot**
- Visit [QQ Open Platform](https://q.qq.com) → Register as a developer (personal or enterprise)
- Create a new bot application
@@ -579,12 +506,6 @@ Connects to a [Napcat](https://github.com/NapNeko/NapCatQQ) instance over its **
- Copy the forward websocket server's token
- (Optional) In the webui, follow "系统配置" -> "登陆配置" -> "快速登录QQ" to automatically login after restarts
**Install the optional channel dependency**
```bash
nanobot plugins enable napcat
```
**2. Configure**
```json
@@ -622,12 +543,6 @@ nanobot plugins enable napcat
Uses **Stream Mode** — no public IP required.
**Install the optional channel dependency**
```bash
nanobot plugins enable dingtalk
```
**1. Create a DingTalk bot**
- Visit [DingTalk Open Platform](https://open-dev.dingtalk.com/)
- Create a new app -> Add **Robot** capability
@@ -670,12 +585,6 @@ nanobot gateway
Uses **Socket Mode** — no public URL required.
**Install the optional channel dependency**
```bash
nanobot plugins enable slack
```
**1. Create a Slack app**
- Go to [Slack API](https://api.slack.com/apps) → **Create New App** → "From scratch"
- Pick a name and select your workspace
@@ -786,10 +695,10 @@ nanobot gateway
Uses **HTTP long-poll** with QR-code login via the ilinkai personal WeChat API. No local WeChat desktop client is required.
**1. Enable WeChat support**
**1. Install with WeChat support**
```bash
nanobot plugins enable weixin
python -m pip install "nanobot-ai[weixin]"
```
**2. Configure**
@@ -838,10 +747,10 @@ nanobot gateway
>
> Uses **WebSocket** long connection — no public IP required.
**1. Enable WeCom support**
**1. Install the optional dependency**
```bash
nanobot plugins enable wecom
python -m pip install "nanobot-ai[wecom]"
```
**2. Create a WeCom AI Bot**
@@ -877,10 +786,10 @@ nanobot gateway
> Direct-message text in/out, tenant-aware OAuth, conversation reference persistence.
> Uses a public HTTPS webhook — no WebSocket; you need a tunnel or reverse proxy.
**1. Enable Microsoft Teams support**
**1. Install the optional dependency**
```bash
nanobot plugins enable msteams
python -m pip install "nanobot-ai[msteams]"
```
**2. Create a Teams / Azure bot app registration**
-66
View File
@@ -15,11 +15,7 @@ These commands work inside chat channels and interactive agent sessions:
| `/dream-log <sha>` | Show a specific Dream memory change |
| `/dream-restore` | List recent Dream memory versions |
| `/dream-restore <sha>` | Restore memory to the state before a specific change |
| `/dream-prompt` | Show how Dream is being guided for memory |
| `/dream-prompt init` | Create an editable Dream memory guide at `prompts/dream.md` |
| `/skill` | List enabled skills and their descriptions |
| `/trigger` | Show local trigger usage |
| `/trigger <name>` | Create a named local trigger for the current chat/session |
| `/pairing` | List pending pairing requests |
| `/pairing approve <code>` | Approve a pairing code |
| `/pairing deny <code>` | Deny a pending pairing request |
@@ -59,68 +55,6 @@ To switch presets for future turns:
Preset names come from the top-level `modelPresets` config. Switching is runtime-only: it does not rewrite `config.json`, and an in-progress turn keeps using the model it started with. See [Configuration: Model presets](./configuration.md#model-presets) for setup details.
## Local triggers
Use `/trigger <name>` when a local script or another service should be able to
send a message into the current chat/session later. A name is required; plain
`/trigger` only shows the usage hint.
Create the trigger from the chat where future messages should arrive:
```text
/trigger PR review
```
nanobot replies with a trigger ID and a command shaped like:
```bash
nanobot trigger trg_8K4P2Q9X "Review PR #4502"
```
Replace `"Review PR #4502"` with the message you want nanobot to receive. The
trigger is bound to the session where it was created, so the message goes back
to that same chat. Keep `nanobot gateway` running so trigger messages can be
delivered. The trigger message starts an automation turn recorded in that
session with the message you passed to the CLI; it is not treated as a normal
user message. If that session is already running a turn, the trigger waits
until the session is idle instead of being injected into the active turn.
Trigger deliveries are stored in the workspace until their linked agent turn
finishes successfully. If the gateway exits after claiming a delivery but before
the turn completes, the next gateway start requeues that delivery. This is an
at-least-once local queue: a delivery may run more than once if the process
exits at the wrong time, so external scripts should make repeated trigger
messages safe. If the delivery reaches the agent and the agent turn fails, the
delivery is marked failed in Automations instead of retrying forever.
For longer or generated content, omit the message argument and pipe stdin:
```bash
printf '%s\n' "Review the latest failed CI job" | nanobot trigger trg_8K4P2Q9X
```
If an external webhook should wake nanobot up, run your own small webhook
service and have it call the trigger command after it builds the final message:
```bash
nanobot trigger <trigger-id> "<message>"
```
If you run multiple nanobot instances, pass the same config or workspace
selector used by the gateway:
```bash
nanobot trigger --config ./bot-a/config.json trg_8K4P2Q9X "Nightly report"
nanobot trigger --workspace ./bot-a/workspace trg_8K4P2Q9X "Nightly report"
```
Manage triggers from the WebUI Automations view. You can search, pause/resume,
rename, delete, and copy the trigger command there. A session may have multiple
triggers, just like it may have multiple scheduled automations.
See [Automations](./automations.md) for how local triggers fit with scheduled
automations, heartbeat, and gateway delivery.
## Periodic Tasks
Periodic background checks are driven by `HEARTBEAT.md` in your workspace (`~/.nanobot/workspace/HEARTBEAT.md`). When `nanobot gateway` starts, it registers a protected heartbeat cron job by default. Every 30 minutes, that job checks the file; if it finds tasks under `## Active Tasks`, the agent executes them and delivers only results that pass the notification gate to your most recently active chat channel. If there are no active tasks, or the result is routine with nothing useful to report, the heartbeat is skipped silently.
+6 -118
View File
@@ -8,17 +8,13 @@ Use this page when you know what you want to run and need the command shape. For
|---|---|---|
| Check the install | `nanobot --version` | If this fails, try `python -m nanobot --version` |
| Create or refresh config | `nanobot onboard` | Creates `~/.nanobot/config.json` and `~/.nanobot/workspace/` |
| Refresh config non-interactively | `nanobot onboard --refresh` | Preserves existing values and adds missing default fields without prompting |
| Use guided setup | `nanobot onboard --wizard` | Best when you prefer prompts over hand-editing JSON |
| Open the browser workbench | `nanobot webui` | Prepares local WebUI settings, starts the gateway, and opens the browser |
| Check config without calling a model | `nanobot status` | Summarizes the selected config, workspace, active model, and providers |
| Check config without calling a model | `nanobot status` | Reads the default config and summarizes the active model/provider |
| Send one test message | `nanobot agent -m "Hello!"` | First proof that install, config, provider, model, and workspace all work |
| Chat in the terminal | `nanobot agent` | Interactive local chat; exit with `exit`, `/exit`, `:q`, or `Ctrl+D` |
| Run the gateway directly | `nanobot gateway` | Service/ops command for WebUI, chat apps, cron, and heartbeat |
| Deliver a local trigger | `nanobot trigger <id> "message"` | Created first with `/trigger <name>` in the target chat/session |
| Use WebUI or chat apps | `nanobot gateway` | Keep this terminal running, or use `nanobot gateway --background` |
| Serve an OpenAI-compatible API | `nanobot serve` | Starts `/v1/chat/completions`, `/v1/models`, and `/health` |
| Check chat channel setup | `nanobot channels status` | Useful before starting `nanobot gateway` |
| Manage optional features | `nanobot plugins list` | Shows channels and optional capabilities you can turn on |
| Log in to QR/OAuth-style channels | `nanobot channels login <channel>` | Used by channels such as WhatsApp and WeChat |
| Log in to OAuth model providers | `nanobot provider login <provider>` | Used by OAuth providers such as OpenAI Codex and GitHub Copilot |
@@ -59,7 +55,6 @@ with `--background`, use `nanobot gateway stop`.
| Command | Description |
|---|---|
| `nanobot onboard` | Initialize or refresh the default config and workspace |
| `nanobot onboard --refresh` | Refresh an existing config without prompting, preserving existing values |
| `nanobot onboard --wizard` | Use the interactive setup wizard |
| `nanobot onboard --config <path> --workspace <path>` | Initialize or refresh a specific instance |
@@ -82,26 +77,11 @@ Default paths:
| `nanobot agent --no-markdown` | Print plain text instead of Rich-rendered Markdown |
| `nanobot agent --logs` | Show runtime logs while chatting |
In interactive mode, `Enter` sends the current message. Press `Alt+Enter` to add a newline before sending.
Interactive mode exits with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
## WebUI
| Command | Description |
|---|---|
| `nanobot webui` | Create config/workspace if needed, enable the local WebUI channel after confirmation, start the gateway, and open `http://127.0.0.1:8765` |
| `nanobot webui --background` | Start or reuse a background gateway, then open the WebUI |
| `nanobot webui --no-open` | Prepare and start the WebUI without opening a browser |
| `nanobot webui --port <port>` | Set the WebUI/WebSocket port |
| `nanobot webui --gateway-port <port>` | Override the gateway health port |
| `nanobot webui --yes` | Apply safe localhost WebUI defaults without confirmation; provider credentials still require interactive setup |
First-run WebUI setup binds to `127.0.0.1` by default. Use manual configuration and a WebUI password before exposing the WebSocket channel beyond localhost.
## Gateway
`nanobot gateway` starts enabled chat channels, WebUI/WebSocket when configured, cron-backed system jobs, Dream, heartbeat, and the health endpoint. Most local browser users should start with `nanobot webui`; use `gateway` directly for service management, chat app operation, and advanced deployment. By default it runs in the foreground, which keeps existing scripts and terminal workflows unchanged. Use `--background` when you want a local macOS, Linux, or Windows process that you can manage from the CLI.
`nanobot gateway` starts enabled chat channels, WebUI/WebSocket when configured, cron-backed system jobs, Dream, heartbeat, and the health endpoint. By default it runs in the foreground, which keeps existing scripts and terminal workflows unchanged. Use `--background` when you want a local macOS, Linux, or Windows process that you can manage from the CLI.
| Command | Description |
|---|---|
@@ -142,55 +122,6 @@ http://127.0.0.1:18790/health
The bundled WebUI is served by the WebSocket channel, usually on port `8765`, not by the gateway health endpoint.
## Local Triggers
`nanobot trigger` delivers one local message to a trigger that was created from
a chat/session with `/trigger <name>`.
```bash
nanobot trigger trg_8K4P2Q9X "Review PR #4502"
```
Keep `nanobot gateway` running so the message can be delivered to the linked
chat/session. The message is recorded as an automation turn in that session,
not as a normal chat message typed by the user.
The command writes to a workspace-local durable queue. If `nanobot gateway` is
not running yet, the message waits in that workspace. If the target session is
already running a turn, the trigger waits for that session to become idle. If the
gateway exits after claiming a delivery but before the linked turn completes,
the next gateway start requeues that delivery. The queue is at-least-once, not
exactly-once, so the same message can be delivered again after an interrupted
process. If the agent receives the delivery and the turn fails, the delivery is
marked failed instead of retried indefinitely. Each delivery also writes an
audit record under `<workspace>/triggers/runs`. Run one gateway consumer per
workspace; this local queue is not a distributed multi-consumer queue.
Use stdin when another local process generates the message:
```bash
generate-report | nanobot trigger trg_8K4P2Q9X
```
Options:
| Command | Description |
|---|---|
| `nanobot trigger <id> "message"` | Deliver one message through a trigger |
| `nanobot trigger <id>` | Read the message from stdin |
| `nanobot trigger --config <path> <id> "message"` | Use the workspace from a specific config |
| `nanobot trigger --workspace <path> <id> "message"` | Use a specific workspace |
Triggers are managed in the WebUI Automations view instead of through separate
`list`, `revoke`, or `delete` CLI subcommands. From there you can pause/resume,
rename, delete, search, and copy the command for each trigger.
For webhooks or other external systems, run your own small service and have it
call this CLI after it decides what message nanobot should receive.
See [Automations](./automations.md) for the broader automation model, WebUI
management, and delivery behavior.
## OpenAI-Compatible API
| Command | Description |
@@ -209,8 +140,6 @@ Default API endpoint:
http://127.0.0.1:8900
```
Public binds (`0.0.0.0` or `::`) require `api.apiKey`; send it as a Bearer token on API routes.
See [`openai-api.md`](./openai-api.md) for request examples.
## Status
@@ -219,13 +148,7 @@ See [`openai-api.md`](./openai-api.md) for request examples.
nanobot status
```
Shows the config path, workspace path, active model, and provider summary without calling a model.
| Command | Description |
|---|---|
| `nanobot status` | Inspect the default instance |
| `nanobot status --config <path>` | Inspect a specific config |
| `nanobot status --config <path> --workspace <path>` | Inspect a specific config with a workspace override |
Shows the default config path, workspace path, active model, and provider summary. This command does not currently accept `--config`; use explicit `--config` and `--workspace` on `agent`, `gateway`, or `serve` when debugging a specific instance.
## Channels
@@ -236,7 +159,6 @@ Shows the config path, workspace path, active model, and provider summary withou
| `nanobot channels login <channel>` | Run interactive login for supported channels |
| `nanobot channels login <channel> --force` | Re-authenticate even if credentials already exist |
| `nanobot channels login <channel> --config <path>` | Use a specific config file |
| `nanobot plugins list --config <path>` | Show plugin/channel enabled state for a specific config |
Examples:
@@ -248,46 +170,12 @@ nanobot channels status
See [`chat-apps.md`](./chat-apps.md) for channel-specific setup.
## Optional Features
Use these commands when you want nanobot to add or remove a built-in capability
without hand-editing JSON. Enabling may install the support package first.
Disabling is for channels such as Telegram, Matrix, or Slack; it keeps your
saved settings and turns the channel off.
The `plugins` command name is retained for compatibility, but these entries are
nanobot runtime support packages, not the user-invokable tools shown in WebUI
Apps. They cannot be attached to a chat turn with `@`.
| Feature name | What it enables |
|---|---|
| `api` | Dependencies required by the OpenAI-compatible `nanobot serve` process |
| `azure` | Azure identity support for Azure-hosted models |
| `bedrock` | AWS Bedrock model provider support |
| `langfuse` | Langfuse tracing support for OpenAI-compatible providers |
| `olostep` | Olostep web search provider support |
| A channel name such as `telegram` or `slack` | The connector package and saved channel enablement |
| Command | Description |
|---|---|
| `nanobot plugins list` | Show available channels and optional capabilities |
| `nanobot plugins enable <name>` | Install missing support and enable the feature or channel |
| `nanobot plugins enable <name> --logs` | Show package install logs while enabling |
| `nanobot plugins disable <channel>` | Turn off a channel without deleting its saved settings |
| `nanobot plugins list --config <path>` | Read a specific config file |
| `nanobot plugins enable <name> --config <path>` | Update a specific config file |
| `nanobot plugins disable <channel> --config <path>` | Turn off a channel in a specific config file |
Document and PDF reading are included in the standard installation. The old
`nanobot plugins enable documents` and `nanobot plugins enable pdf` commands
remain accepted as no-op compatibility aliases.
## Provider OAuth
| Command | Description |
|---|---|
| `nanobot provider login openai-codex --set-main` | Authenticate Codex and select its current default model |
| `nanobot provider login github-copilot --set-main` | Authenticate GitHub Copilot and select its current default model |
| `nanobot provider login openai-codex` | Authenticate OpenAI Codex provider |
| `nanobot provider login github-copilot` | Authenticate GitHub Copilot provider |
| `nanobot provider logout openai-codex` | Remove OpenAI Codex OAuth state |
| `nanobot provider logout github-copilot` | Remove GitHub Copilot OAuth state |
+6 -21
View File
@@ -12,7 +12,7 @@ nanobot has one small core loop and several ways to enter it:
|---|---|
| Agent loop | Builds context, selects the session, calls the provider, runs tools, and publishes replies |
| Providers | LLM backends such as OpenRouter, Anthropic, OpenAI, Bedrock, Ollama, vLLM, and other OpenAI-compatible APIs |
| Channels | User-facing transports such as CLI, WebUI/WebSocket, Telegram, Discord, Slack, Feishu, WeChat, Email, Mattermost, and others |
| Channels | User-facing transports such as CLI, WebUI/WebSocket, Telegram, Discord, Slack, Feishu, WeChat, Email, and others |
| Tools | Capabilities the model may call, including files, shell, web search/fetch, MCP, cron, image generation, and subagents |
| Memory | Workspace files and session history that keep useful context across turns |
| Gateway | Long-running process that connects enabled channels and serves the health endpoint |
@@ -64,9 +64,9 @@ That flow is the same whether the message starts in the CLI, WebUI, Telegram, Di
| CLI interactive | `nanobot agent` | Terminal chat with persistent session history |
| Gateway | `nanobot gateway` | Chat apps, WebUI, heartbeat, Dream, and long-running service mode |
| OpenAI-compatible API | `nanobot serve` | Programmatic access through `/v1/chat/completions` |
| WebUI | `nanobot webui` | Prepare the local WebUI, start the gateway, and open the browser workbench |
| WebUI | `nanobot gateway` plus WebSocket channel | Browser workbench served by the WebSocket channel on port `8765` |
The WebUI launcher is the normal browser entry point. Underneath, the gateway keeps the WebSocket channel and other long-running services alive. The gateway health endpoint is on `gateway.port` (`18790` by default); the browser WebUI is served on `8765` by default, not by the health endpoint.
The gateway health endpoint is on `gateway.port` (`18790` by default). The browser WebUI is served by the WebSocket channel (`8765` by default), not by the health endpoint.
## Provider and Model Selection
@@ -123,7 +123,7 @@ Tools are discovered automatically from built-in modules and plugin entry points
- shell execution with configurable sandboxing;
- web search and web fetch with SSRF checks;
- MCP servers;
- cron reminders, local triggers, and heartbeat tasks;
- cron reminders and heartbeat tasks;
- image generation;
- subagents and runtime self-inspection.
@@ -131,29 +131,14 @@ Security-sensitive controls live in [`configuration.md#security`](./configuratio
## Background Jobs
When `nanobot gateway` starts, it runs workspace-scoped automations and
registers system jobs:
When `nanobot gateway` starts, it creates workspace-scoped cron storage at `<workspace>/cron/jobs.json` and registers system jobs:
- `dream`, when `agents.defaults.dream.enabled` is true;
- `heartbeat`, when `gateway.heartbeat.enabled` is true.
Heartbeat reads `<workspace>/HEARTBEAT.md`. If the file has tasks under `## Active Tasks`, nanobot executes them and sends only useful/actionable results to the most recently active chat target. Routine "nothing changed" results are suppressed.
User-created reminders use the same cron service but are not the same as the
protected heartbeat system job. They run as scheduled turns in their origin
chat/session and normally deliver the result back to that channel.
Local triggers are also session-bound, but they do not have their own
schedule. Create one from the target chat with `/trigger <name>`, then call
`nanobot trigger <id> "<message>"` when a local script or external service wants
nanobot to respond in that session. Webhook servers, third-party auth, and
event-to-message formatting stay outside nanobot. Trigger deliveries are stored
in the workspace until the linked agent turn finishes successfully. If the
target session is busy, the trigger waits until that session is idle instead of
being injected into the active turn. The message is recorded as an automation
turn in that session. Delivery is at-least-once, so external systems should
tolerate repeated trigger messages; a delivery that reaches the agent but fails
is marked failed rather than retried forever.
User-created reminders use the same cron service but are not the same as the protected heartbeat system job. They run as scheduled turns in their origin chat/session and normally deliver the result back to that channel.
## Where to Go Next
+51 -111
View File
@@ -4,8 +4,6 @@ Config file: `~/.nanobot/config.json`
This is the full reference. If this is your first install, start with [`quick-start.md`](./quick-start.md). If you are trying to choose a model or fix provider/model matching, use [`providers.md`](./providers.md) first and come back here for exact fields and advanced options.
For normal local use, prefer the WebUI before editing JSON: **Settings → Models** manages model choices and provider credentials, **Settings → Channels** guides chat-platform setup, other Settings pages cover built-in capabilities, and **Apps** manages CLI App and MCP integrations. Edit `config.json` directly when you need an advanced field, automate deployment, or intentionally manage configuration as code.
The JSON examples below are usually partial snippets to merge into your existing config, not full replacement files. For the mental model behind config, workspace, gateway, channels, sessions, tools, and memory, see [`concepts.md`](./concepts.md).
The generated `config.json` uses camelCase keys such as `apiKey` and `intervalS`. snake_case keys are also accepted for compatibility, but the docs prefer camelCase because that is what nanobot writes back to disk.
@@ -13,22 +11,7 @@ The generated `config.json` uses camelCase keys such as `apiKey` and `intervalS`
For setup and runtime failures, follow the diagnosis order in [`troubleshooting.md`](./troubleshooting.md) before changing multiple config areas at once.
> [!NOTE]
> If your config file is older than the current schema, run `nanobot onboard --refresh`. nanobot adds missing default fields while preserving your existing values.
## Configuration Guides
This page is the complete configuration reference. For task-oriented setup, use
the focused guides first and come back here for exact fields and defaults.
| Task | Guide |
|---|---|
| Add MCP tools | [`guides/configure-mcp-tools.md`](./guides/configure-mcp-tools.md) |
| Enable web search and web fetch | [`guides/configure-web-search.md`](./guides/configure-web-search.md) |
| Configure model fallback | [`guides/configure-model-fallback.md`](./guides/configure-model-fallback.md) |
| Add an OpenAI-compatible provider | [`guides/configure-openai-compatible-provider.md`](./guides/configure-openai-compatible-provider.md) |
| Add Langfuse observability | [`guides/configure-langfuse-observability.md`](./guides/configure-langfuse-observability.md) |
| Secure a local AI agent | [`guides/secure-local-ai-agent.md`](./guides/secure-local-ai-agent.md) |
| Deploy the gateway | [`guides/deploy-nanobot-gateway.md`](./guides/deploy-nanobot-gateway.md) |
> If your config file is older than the current schema, you can refresh it without overwriting your existing values: run `nanobot onboard`, then answer `N` when asked whether to overwrite the config. nanobot will merge in missing default fields and keep your current settings.
## Quick Jump
@@ -49,24 +32,24 @@ the focused guides first and come back here for exact fields and defaults.
| Control access and pairing | [Pairing](#pairing) |
| Tune gateway jobs, sessions, and tools | [Gateway Heartbeat](#gateway-heartbeat), [Auto Compact](#auto-compact), [Unified Session](#unified-session), [Tool Hint Max Length](#tool-hint-max-length) |
## Where a Setting Lives
## Where to Edit First
If the WebUI does not expose the option you need, start from the task below. Most advanced changes touch one config section and one verification command.
If you are not sure where a setting belongs, start from the task you are trying to complete. Most changes touch one config section and one verification command.
| Task | First keys to check | Verify with | Deep dive |
|---|---|---|---|
| Make the first model reply work | `providers.<name>.apiKey`, optional `providers.<name>.apiBase`, `modelPresets.<preset>`, `agents.defaults.modelPreset` | `nanobot status`, then `nanobot agent -m "Hello!"` | [Providers](#providers), [Model Presets](#model-presets) |
| Add fallback models | `modelPresets.<fallback>`, `agents.defaults.fallbackModels` | `nanobot status`, then a normal agent run | [Model Fallbacks](#model-fallbacks) |
| Keep secrets out of the config file | `${ENV_VAR}` placeholders inside any string value | Start nanobot from the same environment that sets the variable | [Environment Variables for Secrets](#environment-variables-for-secrets) |
| Open the bundled WebUI | `channels.websocket.enabled`, optional `channels.websocket.port`, `channels.websocket.tokenIssueSecret` | `nanobot webui` | [Channel Settings](#channel-settings), [WebSocket docs](./websocket.md) |
| Connect one chat app | `channels.<channel>.enabled`, channel credentials, optional pairing or `channels.<channel>.allowFrom` | `nanobot channels status`, then `nanobot gateway --verbose` | [Channel Settings](#channel-settings), [Chat Apps](./chat-apps.md) |
| Open the bundled WebUI | `channels.websocket.enabled`, optional `channels.websocket.port`, `channels.websocket.tokenIssueSecret` | `nanobot gateway`, then open `http://127.0.0.1:8765` | [Channel Settings](#channel-settings), [WebSocket docs](./websocket.md) |
| Connect one chat app | `channels.<channel>.enabled`, channel credentials, `channels.<channel>.allowFrom` | `nanobot channels status`, then `nanobot gateway --verbose` | [Channel Settings](#channel-settings), [Chat Apps](./chat-apps.md) |
| Enable voice transcription | `transcription.enabled`, `transcription.provider`, matching `providers.<name>.apiKey` | Send or upload a short voice message through a configured surface | [Transcription Settings](#transcription-settings) |
| Enable web search or fetch | `tools.web.search.*`, `tools.web.fetch.*`, optional `tools.ssrfWhitelist` | Ask a question that requires current web information, then inspect logs if needed | [Web Tools](#web-tools), [Security](#security) |
| Enable image generation | `tools.imageGeneration.enabled`, `tools.imageGeneration.provider`, `tools.imageGeneration.model`, matching provider credentials | Enable Image Generation in the WebUI and send one image request | [Image Generation](#image-generation) |
| Add external tools through MCP | `tools.mcpServers.<name>` | Start `nanobot gateway --verbose` and check startup/tool logs | [MCP](#mcp-model-context-protocol) |
| Tighten tool and network safety | `tools.restrictToWorkspace`, `tools.exec.sandbox`, `tools.ssrfWhitelist`, `channels.*.allowFrom` | Run the same workflow through the channel or CLI you plan to expose | [Security](#security), [Pairing](#pairing) |
| Tune request timeouts or process concurrency | `NANOBOT_LLM_TIMEOUT_S`, `NANOBOT_STREAM_IDLE_TIMEOUT_S`, `NANOBOT_MAX_CONCURRENT_REQUESTS` | Start nanobot from the same environment and inspect startup/runtime logs | [Runtime Environment Variables](#runtime-environment-variables) |
| Run multiple isolated bots | separate `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Use the same explicit paths with `nanobot status`, `agent`, `webui`, `gateway`, and `serve` | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |
| Run multiple isolated bots | separate `--config` and `--workspace` paths, plus distinct `gateway.port` or channel ports when processes run together | Start each process with explicit paths and run `nanobot status` for the default instance only | [Multiple Instances](./multiple-instances.md), [CLI Reference](./cli-reference.md) |
| Observe model calls | `LANGFUSE_SECRET_KEY`, `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_BASE_URL` environment variables | Run one model call, then check the matching Langfuse project | [Langfuse Observability](#langfuse-observability) |
## Environment Variables for Secrets
@@ -187,7 +170,7 @@ These variables are process-level switches. Set them in the same terminal, servi
| Variable | Default | Description |
|----------|---------|-------------|
| `NANOBOT_MAX_CONCURRENT_REQUESTS` | `3` | Maximum concurrently running inbound agent requests. Must be an integer; set `0` or a negative value for unlimited. |
| `NANOBOT_LLM_TIMEOUT_S` | `300` | Wall-clock timeout, in seconds. Ordinary requests use this value; streaming requests use the greater of 300 seconds or twice this value. Set `0` to disable. Sustained-goal turns bypass this wall-clock cap. |
| `NANOBOT_LLM_TIMEOUT_S` | `300` | Wall-clock timeout, in seconds, around ordinary LLM requests. Set `0` to disable. Sustained-goal turns bypass this wall-clock cap. |
| `NANOBOT_STREAM_IDLE_TIMEOUT_S` | `90` | Streaming idle timeout, in seconds, used by streaming providers. Invalid or non-positive values are ignored; values above `3600` are clamped. |
| `NANOBOT_OPENAI_COMPAT_TIMEOUT_S` | `120` | HTTP request timeout, in seconds, for OpenAI-compatible providers. Invalid or non-positive values are ignored. |
| `NANOBOT_WORKSPACE_SANDBOX_ENFORCED` | unset | Marks that an external workspace sandbox is already enforced. Truthy values (`1`, `true`, `yes`, `on`, `enabled`) use `NANOBOT_WORKSPACE_SANDBOX_PROVIDER` as the label; any other non-false value is treated as the provider name. |
@@ -215,7 +198,7 @@ nanobot can trace OpenAI-compatible provider calls through Langfuse's OpenAI SDK
Install the optional package in the same Python environment that runs nanobot:
```bash
nanobot plugins enable langfuse
python -m pip install langfuse
```
Set Langfuse credentials before starting `nanobot agent`, `nanobot gateway`, or `nanobot serve`:
@@ -249,7 +232,7 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
> - **MiniMax thinking mode**: `providers.minimaxAnthropic` is the config block for `reasoningEffort` / thinking mode. MiniMax exposes that capability through its Anthropic-compatible endpoint, so nanobot keeps it as a separate provider instead of guessing MiniMax-specific thinking parameters on the generic OpenAI-compatible `minimax` endpoint. It uses the same `MINIMAX_API_KEY`. Default Anthropic-compatible base URL: `https://api.minimax.io/anthropic`; for mainland China use `https://api.minimaxi.com/anthropic`.
> - **Kimi Coding Plan**: Use `providers.kimiCoding` with `provider: "kimi_coding"` for Kimi's dedicated Anthropic Messages API endpoint. The endpoint requires a Claude-compatible `User-Agent`; nanobot sends `claude-code/0.1.0` by default, and you can override it with `extraHeaders.User-Agent` if your account requires a different value.
> - **VolcEngine / BytePlus Coding Plan**: Subscription endpoints are configured through dedicated providers `volcengineCodingPlan` or `byteplusCodingPlan`, separate from the pay-per-use `volcengine` / `byteplus` providers.
> - **OpenCode Zen / Go**: `providers.opencode` (canonical Zen), the legacy-compatible `providers.opencodeZen`, and `providers.opencodeGo` use the same `OPENCODE_API_KEY`, but route to different OpenCode gateways. These providers use OpenCode's OpenAI-compatible `chat/completions` endpoints; choose model IDs from that endpoint family.
> - **OpenCode Zen / Go**: `providers.opencodeZen` and `providers.opencodeGo` use the same `OPENCODE_API_KEY`, but route to different OpenCode gateways. These providers use OpenCode's OpenAI-compatible `chat/completions` endpoints; choose model IDs from that endpoint family.
> - **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.
> - **Alibaba Cloud BaiLian**: If you're using Alibaba Cloud BaiLian's OpenAI-compatible endpoint, set `"apiBase": "https://dashscope.aliyuncs.com/compatible-mode/v1"` in your dashscope provider config.
> - **StepFun Step Plan**: If you're on StepFun's Step Plan subscription, set `"apiBase": "https://api.stepfun.ai/step_plan/v1"` in your stepfun provider config. Supported models include `step-3.5-flash`, `step-3.5-flash-2603`, and `step-router-v1`.
@@ -257,14 +240,12 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
> - **Xiaomi MiMo thinking mode**: MiMo models (e.g. `mimo-v2.5-pro`) default to enabled thinking. Use `agents.defaults.reasoningEffort: "none"` to disable it, or `"low"` / `"medium"` / `"high"` to keep it on. Omitting the field preserves the provider's per-model default.
> - **Xiaomi MiMo Token Plan**: If you're on MiMo's token plan, set `"apiBase": "https://token-plan-sgp.xiaomimimo.com/v1"` in your xiaomi_mimo provider config.
> - **Custom OpenAI-compatible providers**: Besides the built-in `custom` provider, any extra key under `providers` can define its own OpenAI-compatible endpoint. For example, `providers.companyProxy.apiBase` plus `modelPresets.primary.provider: "companyProxy"` creates a separate custom provider. Set `apiBase`; set `apiKey` only when the endpoint requires it. This named-custom path uses the OpenAI-compatible request format only. For Anthropic-compatible proxies, use `providers.anthropic.apiBase` with `provider: "anthropic"`.
> - **Provider-scoped proxy**: `providers.<name>.proxy` routes only that provider through an HTTP proxy. It is supported for OpenAI-compatible providers and `openai_codex`. Native provider backends such as `anthropic`, `bedrock`, `azure_openai`, and `github_copilot` reject `proxy`.
| Provider | Purpose | Get API Key |
|----------|---------|-------------|
| `custom` | Any OpenAI-compatible endpoint | — |
| `openrouter` | LLM gateway for hosted model families + Voice transcription (STT models) | [openrouter.ai](https://openrouter.ai) |
| `opencode` | LLM gateway (OpenCode Zen coding-agent models) | [opencode.ai/docs/zen](https://opencode.ai/docs/zen/) |
| `opencode_zen` | LLM gateway (legacy alias for OpenCode Zen) | [opencode.ai/docs/zen](https://opencode.ai/docs/zen/) |
| `opencode_zen` | LLM gateway (OpenCode Zen coding-agent models) | [opencode.ai/docs/zen](https://opencode.ai/docs/zen/) |
| `opencode_go` | LLM gateway (OpenCode Go low-cost coding models) | [opencode.ai/docs/go](https://opencode.ai/docs/go/) |
| `huggingface` | LLM (Hugging Face Inference Providers) | [huggingface.co/settings/tokens](https://huggingface.co/settings/tokens) |
| `skywork` | LLM (Skywork / APIFree API gateway) | [apifree.ai](https://www.apifree.ai) |
@@ -300,7 +281,7 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
| `ovms` | LLM (local, OpenVINO Model Server) | [docs.openvino.ai](https://docs.openvino.ai/2026/model-server/ovms_docs_llm_quickstart.html) |
| `vllm` | LLM (local, any OpenAI-compatible server) | — |
| `nvidia` | LLM (NVIDIA NIM) | [build.nvidia.com](https://build.nvidia.com/) |
| `openai_codex` | LLM (Codex, OAuth) | `nanobot provider login openai-codex --set-main` |
| `openai_codex` | LLM (Codex, OAuth) | `nanobot provider login openai-codex` |
| `github_copilot` | LLM (GitHub Copilot, OAuth) | `nanobot provider login github-copilot` |
| `qianfan` | LLM (Baidu Qianfan) | [cloud.baidu.com](https://cloud.baidu.com/doc/qianfan/s/Hmh4suq26) |
@@ -398,7 +379,7 @@ Omit `apiKey` (or leave it empty / unset). The provider falls back to [`DefaultA
Install the optional dependency:
```bash
nanobot plugins enable azure
python -m pip install 'nanobot-ai[azure]'
```
`DefaultAzureCredential` walks this chain in order and uses the first identity that succeeds:
@@ -413,7 +394,7 @@ nanobot plugins enable azure
The identity that ends up signing the request **must be assigned the `Cognitive Services OpenAI User` RBAC role** (or higher) on the Azure OpenAI resource. Without that role you will see `401`/`403` errors at the first request.
> `apiBase` remains mandatory in both modes — it's your Azure resource endpoint and cannot be inferred. If neither `apiKey` is set nor `azure-identity` is installed, the provider raises a clear error pointing you at `nanobot plugins enable azure`.
> `apiBase` remains mandatory in both modes — it's your Azure resource endpoint and cannot be inferred. If neither `apiKey` is set nor `azure-identity` is installed, the provider raises a clear error pointing you at `python -m pip install 'nanobot-ai[azure]'`.
</details>
@@ -457,17 +438,6 @@ Bedrock uses the native `bedrock-runtime` Converse API, so it can call Bedrock m
This provider is for Bedrock's native Converse API, not Bedrock's OpenAI-compatible `/openai/v1` endpoint. For OpenAI-compatible Bedrock models, you can still use `custom` if you specifically want that API surface.
Install Bedrock support first:
```bash
nanobot plugins enable bedrock
```
> [!NOTE]
> If you configured Bedrock before `boto3` became an optional dependency, run
> `nanobot plugins enable bedrock` after upgrading. Otherwise the provider will
> fail when it first tries to create a Bedrock client.
**1. Configure credentials**
Use the normal AWS credential chain (`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`, an AWS profile, or an IAM role). The IAM identity needs:
@@ -662,19 +632,42 @@ nanobot agent -m "Reply with one short sentence."
<details>
<summary><b>OpenAI Codex (OAuth)</b></summary>
Codex uses OAuth instead of API keys and requires a ChatGPT Plus or Pro account. Authenticate it and make the current flagship model the active agent model with one command:
Codex uses OAuth instead of API keys. Requires a ChatGPT Plus or Pro account. No `providers.openaiCodex` block is needed in `config.json`; `nanobot provider login` stores the OAuth session outside config.
**1. Login:**
```bash
nanobot provider login openai-codex --set-main
nanobot provider login openai-codex
```
Then run:
**2. Set model** (merge into `~/.nanobot/config.json`):
```json
{
"modelPresets": {
"codex": {
"provider": "openai_codex",
"model": "openai-codex/gpt-5.1-codex"
}
},
"agents": {
"defaults": {
"modelPreset": "codex"
}
}
}
```
**3. Chat:**
```bash
nanobot agent -m "Hello!"
# Target a specific workspace/config locally
nanobot agent -c ~/.nanobot-telegram/config.json -m "Hello!"
# One-off workspace override on top of that config
nanobot agent -c ~/.nanobot-telegram/config.json -w /tmp/nanobot-telegram-test -m "Hello!"
```
For proxy, remote/headless login, model-name, or config-key errors, see [`troubleshooting.md`](./troubleshooting.md#provider-and-model-problems).
> Docker users: use `docker run -it` for interactive OAuth login.
</details>
@@ -682,17 +675,7 @@ For proxy, remote/headless login, model-name, or config-key errors, see [`troubl
<details>
<summary><b>GitHub Copilot (OAuth)</b></summary>
GitHub Copilot uses OAuth instead of API keys. Requires a [GitHub account with a plan](https://github.com/features/copilot/plans) configured. No `providers.github_copilot` block is needed in `config.json`; `nanobot provider login` stores the OAuth session outside config.
For GitHub Enterprise / Copilot for Business, set the endpoint overrides you need before login:
```bash
export NANOBOT_GITHUB_COPILOT_CLIENT_ID="your-enterprise-client-id"
export NANOBOT_GITHUB_DEVICE_CODE_URL="https://ghe.example/login/device/code"
export NANOBOT_GITHUB_ACCESS_TOKEN_URL="https://ghe.example/login/oauth/access_token"
export NANOBOT_GITHUB_USER_URL="https://api.ghe.example/user"
export NANOBOT_COPILOT_TOKEN_URL="https://api.ghe.example/copilot_internal/v2/token"
export NANOBOT_COPILOT_BASE_URL="https://copilot-api.ghe.example"
```
GitHub Copilot uses OAuth instead of API keys. Requires a [GitHub account with a plan](https://github.com/features/copilot/plans) configured. No `providers.githubCopilot` block is needed in `config.json`; `nanobot provider login` stores the OAuth session outside config.
**1. Login:**
```bash
@@ -740,7 +723,6 @@ variable, but use separate provider keys and default base URLs:
| Provider | Default API base | Model prefix accepted by nanobot |
|----------|------------------|-----------------------------------|
| `opencode` | `https://opencode.ai/zen/v1` | `opencode/<model-id>` |
| `opencode_zen` | `https://opencode.ai/zen/v1` | `opencode/<model-id>` |
| `opencode_go` | `https://opencode.ai/zen/go/v1` | `opencode-go/<model-id>` |
@@ -749,13 +731,13 @@ OpenCode Zen:
```json
{
"providers": {
"opencode": {
"opencodeZen": {
"apiKey": "${OPENCODE_API_KEY}"
}
},
"modelPresets": {
"opencodeZen": {
"provider": "opencode",
"provider": "opencode_zen",
"model": "opencode/deepseek-v4-pro"
}
},
@@ -767,8 +749,6 @@ OpenCode Zen:
}
```
`providers.opencodeZen` / `provider: "opencode_zen"` still work as compatibility aliases for existing configs.
OpenCode Go:
```json
@@ -1500,8 +1480,8 @@ Global settings that apply to all channels. Configure under the `channels` secti
|---------|---------|-------------|
| `sendProgress` | `true` | Stream agent's text progress to the channel |
| `sendToolHints` | `false` | Stream tool-call hints (e.g. `read_file("…")`) |
| `showReasoning` | `true` | Allow channels to surface model reasoning/thinking content (DeepSeek-R1 `reasoning_content`, Anthropic `thinking_blocks`, inline `<think>` tags). Reasoning flows as a dedicated stream with `_reasoning_delta` / `_reasoning_end` markers — channels override `send_reasoning_delta` / `send_reasoning_end` to render in-place updates. Even with `true`, channels without those overrides stay no-op silently. Currently surfaced on CLI and WebSocket/WebUI (italic shimmer header, auto-collapses after the stream ends); Telegram / Slack / Discord / Feishu / WeChat / Matrix / Mattermost keep the base no-op until their bubble UI is adapted. Independent of `sendProgress`. |
| `extractDocumentText` | `true` | Extract supported document/text attachments into the model prompt. PDF, DOCX, XLSX, and PPTX readers are included in the standard installation. Set to `false` to keep document content out of the prompt and include attachment path references instead. |
| `showReasoning` | `true` | Allow channels to surface model reasoning/thinking content (DeepSeek-R1 `reasoning_content`, Anthropic `thinking_blocks`, inline `<think>` tags). Reasoning flows as a dedicated stream with `_reasoning_delta` / `_reasoning_end` markers — channels override `send_reasoning_delta` / `send_reasoning_end` to render in-place updates. Even with `true`, channels without those overrides stay no-op silently. Currently surfaced on CLI and WebSocket/WebUI (italic shimmer header, auto-collapses after the stream ends); Telegram / Slack / Discord / Feishu / WeChat / Matrix keep the base no-op until their bubble UI is adapted. Independent of `sendProgress`. |
| `extractDocumentText` | `true` | Extract supported document/text attachments into the model prompt. Set to `false` to keep document content out of the prompt and include attachment path references instead. |
| `sendMaxRetries` | `3` | Max delivery attempts per outbound message, including the initial send (0-10 configured, minimum 1 actual attempt) |
`channels.transcriptionProvider` and `channels.transcriptionLanguage` are deprecated compatibility fields. They remain as a read-only fallback for older configs, but new configuration should use top-level `transcription.provider` and `transcription.language`.
@@ -1575,21 +1555,18 @@ nanobot uses a shared SSRF guard for built-in web fetches and HTTP/SSE MCP conne
Keep whitelist entries as narrow as possible, such as a single host CIDR (`192.168.1.50/32`). The whitelist is global for the shared SSRF guard; it is not limited to one tool or one MCP server.
HTTP/SSE MCP connections use the same process-wide proxy environment behavior as `web_fetch`: proxied targets use the configured proxy, and URLs excluded by `NO_PROXY` remain DNS-pinned direct connections.
> [!TIP]
> Use `proxy` in `tools.web` to route web requests through a proxy:
> Use `proxy` in `tools.web` to route all web requests (search + fetch) through a proxy:
> ```json
> { "tools": { "web": { "proxy": "http://127.0.0.1:7890" } } }
> ```
> `web_fetch` applies DNS pinning for direct connections. When an explicit `tools.web.proxy` or a process-wide proxy environment variable applies to the target URL, nanobot still validates the requested URL locally, but DNS resolution for the outbound fetch happens at the proxy; configure only trusted proxies. URLs excluded by `NO_PROXY` keep the DNS-pinned direct path unless `tools.web.proxy` is configured.
### `tools.web`
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `enable` | boolean | `true` | Enable or disable all built-in web tools (`web_search` + `web_fetch`) |
| `proxy` | string or null | `null` | Proxy for web requests, for example `http://127.0.0.1:7890`. `web_fetch` DNS pinning applies only to direct connections; proxied fetches rely on the configured proxy as the trusted network exit. |
| `proxy` | string or null | `null` | Proxy for all web requests, for example `http://127.0.0.1:7890` |
| `userAgent` | string or null | `null` | User-Agent header for all web requests. If null, a browser one will be used |
### Web Search
@@ -1732,22 +1709,6 @@ You can also set `WEB_SEARCH_API_KEY` for compatibility with the Volcengine web-
Keenable search works out of the box with no account, via its token-less public endpoint (free tier, limited to 1,000 requests/hour). Set `apiKey` (or `KEENABLE_API_KEY`) from [keenable.ai](https://keenable.ai) to remove the hourly limit.
**Serper** (Google Search API):
```json
{
"tools": {
"web": {
"search": {
"provider": "serper",
"apiKey": "${SERPER_API_KEY}"
}
}
}
}
```
Create a key at [serper.dev](https://serper.dev). You can also set `SERPER_API_KEY` in the environment instead of storing it in config.
**SearXNG** (self-hosted, no API key needed):
```json
{
@@ -1779,7 +1740,7 @@ Create a key at [serper.dev](https://serper.dev). You can also set `SERPER_API_K
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `provider` | string | `"duckduckgo"` | Search backend: `brave`, `tavily`, `jina`, `kagi`, `olostep`, `bocha`, `volcengine`, `keenable`, `serper`, `searxng`, `duckduckgo` |
| `provider` | string | `"duckduckgo"` | Search backend: `brave`, `tavily`, `jina`, `kagi`, `olostep`, `bocha`, `volcengine`, `keenable`, `searxng`, `duckduckgo` |
| `apiKey` | string | `""` | API key for API-backed search providers |
| `baseUrl` | string | `""` | Base URL for SearXNG |
| `maxResults` | integer | `5` | Results per search (110) |
@@ -1915,11 +1876,10 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]
| `tools.exec.timeout` | `60` | Default hard timeout in seconds for shell commands. Config values may exceed the per-call tool cap; set `0` to disable the hard timeout for trusted long-running commands. |
| `tools.exec.pathPrepend` | `""` | Extra directories to prepend to `PATH` when running shell commands. Use this when configured tools should win executable lookup precedence, such as a Python virtual environment's `bin` or `Scripts` directory. |
| `tools.exec.pathAppend` | `""` | Extra directories to append to `PATH` when running shell commands (e.g. `/usr/sbin` for `ufw`). |
| `tools.webuiAllowRemotePackageInstall` | `false` | When `false`, the WebUI can install missing optional packages only from a browser opened on the same machine as nanobot. Set to `true` only when a trusted remote admin is allowed to install Python packages into this nanobot environment. |
| `tools.ssrfWhitelist` | `[]` | CIDR ranges exempted from the shared SSRF guard used by web fetches and HTTP/SSE MCP connections. Prefer exact host CIDRs such as `192.168.1.50/32`; broad ranges increase SSRF exposure. |
| `channels.*.allowFrom` | omitted | Access control per channel. Omit to use pairing-only mode; set `["*"]` to allow everyone; or list specific user IDs. See [Pairing](#pairing) for details. |
**Docker security**: The official Docker image runs as a non-root user (`nanobot`, UID 1000) with bubblewrap pre-installed. The default `docker-compose.yml` drops all Linux capabilities and keeps Docker's default AppArmor/seccomp profiles enabled. If you enable `"tools.exec.sandbox": "bwrap"` inside Docker, start Compose with `docker-compose.bwrap.yml` as an additional override so bubblewrap can create nested namespaces.
**Docker security**: The official Docker image runs as a non-root user (`nanobot`, UID 1000) with bubblewrap pre-installed. When using `docker-compose.yml`, the container drops all Linux capabilities except `SYS_ADMIN` (required for bwrap's namespace isolation).
## Pairing
@@ -1928,7 +1888,7 @@ Pairing lets users get access to the bot through a simple code exchange — no c
### How it works
1. A user sends a DM to the bot on a pairing-capable channel where they aren't yet approved. This includes Telegram, Discord, WeChat, and channels such as Slack or Mattermost when their DM policy is set to `allowlist`.
1. A user sends a DM to the bot on any channel (Telegram, Discord, Slack, etc.) where they aren't yet approved.
2. The bot replies with a pairing code (like `ABCD-EFGH`) and tells them to forward it to you.
3. You approve the code:
@@ -1942,7 +1902,7 @@ Pairing only works in **DMs** — unapproved users in group chats are silently i
### Pairing-only mode
By default, if you don't set `allowFrom`, pairing-capable channels can issue a pairing code when an unapproved user DMs the bot. This means you can skip `allowFrom` entirely and manage access through pairing:
By default, if you don't set `allowFrom`, anyone who isn't approved yet will get a pairing code when they DM the bot. This means you can skip `allowFrom` entirely and manage all access through pairing:
```json
{
@@ -1954,21 +1914,6 @@ By default, if you don't set `allowFrom`, pairing-capable channels can issue a p
}
```
Slack and Mattermost DMs are open by default. To use pairing there, set the
channel's `dm.policy` to `"allowlist"` and leave `dm.allowFrom` empty until you
approve users:
```json
{
"channels": {
"slack": {
"enabled": true,
"dm": { "policy": "allowlist" }
}
}
}
```
If you prefer to allow everyone without approval:
```json
@@ -2029,11 +1974,6 @@ The heartbeat job is backed by the same cron service as user-created reminders.
| `gateway.heartbeat.enabled` | `true` | Register the built-in heartbeat cron job on gateway startup. |
| `gateway.heartbeat.intervalS` | `1800` | Seconds between heartbeat checks. |
| `gateway.heartbeat.keepRecentMessages` | `8` | Number of recent heartbeat-session messages to retain after each run. |
| `gateway.restartMode` | `auto` | Restart strategy for `/restart`: `auto` uses `spawn` on Windows foreground runs and `exec` elsewhere. Use `exit` with Windows service wrappers such as WinSW or nssm so the service manager owns the restart. |
### Custom heartbeat evaluator prompt
The notification gate runs on a built-in system prompt. Advanced users can override it, but you rarely need to — it's strongly advised to first read the evaluator code and the default `evaluator.md`. To override, drop your prompt at `<workspace>/prompts/evaluator.md`. It must still instruct the model to call the `evaluate_notification` tool; otherwise the gate fails closed and stays silent.
## Subagent Concurrency
+10 -33
View File
@@ -13,7 +13,7 @@ Check these once before Docker, systemd, or LaunchAgent:
| Secrets are in environment variables or protected config files | API keys, bot tokens, OAuth state, and chat credentials should not be world-readable |
| `~/.nanobot/` or your custom config/workspace path is persistent | Sessions, memory, channel login state, generated artifacts, and cron jobs live there |
| Channel access control is intentional | Use `allowFrom`, pairing, WebSocket `token`/`tokenIssueSecret`, or private test channels before exposing the bot |
| Ports are planned | Gateway health defaults to local-only `127.0.0.1:18790`; WebUI/WebSocket defaults to `8765`; `nanobot serve` defaults to `8900` |
| Ports are planned | Gateway health defaults to `18790`; WebUI/WebSocket defaults to `8765`; `nanobot serve` defaults to `8900` |
| Logs are easy to reach | Use `docker compose logs`, `journalctl`, LaunchAgent log files, or `nanobot gateway --verbose` while diagnosing startup |
Restart the deployed process after editing `config.json`. Long-running processes read config at startup.
@@ -38,13 +38,14 @@ Restart the deployed process after editing `config.json`. Long-running processes
> Official Docker usage currently means building from this repository with the included `Dockerfile`. Docker Hub images under third-party namespaces are not maintained or verified by HKUDS/nanobot; do not mount API keys or bot tokens into them unless you trust the publisher.
> [!IMPORTANT]
> The gateway and WebSocket channel default to `host: "127.0.0.1"` in `config.json` (set in `nanobot/config/schema.py`). Docker `-p` port forwarding cannot reach a container's loopback interface, so for the host or LAN to reach the exposed ports you must set both binds to `0.0.0.0` in `~/.nanobot/config.json` before starting the container. To serve the bundled WebUI from Docker, bind the WebSocket channel externally and protect bootstrap with a secret:
> The gateway and WebSocket channel default to `host: "127.0.0.1"` in `config.json` (set in `nanobot/config/schema.py`). Docker `-p` port forwarding cannot reach a container's loopback interface, so for the host or LAN to reach the exposed ports you must set both binds to `0.0.0.0` in `~/.nanobot/config.json` before starting the container. To serve the bundled WebUI from Docker, enable the WebSocket channel and protect bootstrap with a secret:
>
> ```json
> {
> "gateway": { "host": "0.0.0.0" },
> "channels": {
> "websocket": {
> "enabled": true,
> "host": "0.0.0.0",
> "port": 8765,
> "tokenIssueSecret": "your-secret-here"
@@ -54,11 +55,6 @@ Restart the deployed process after editing `config.json`. Long-running processes
> ```
>
> When the WebSocket `host` is `0.0.0.0`, the channel refuses to start unless `token` or `tokenIssueSecret` is also configured. See [`webui.md#lan-access`](./webui.md#lan-access) for details.
> The gateway health route itself is intentionally minimal and unauthenticated. When the
> container binds it to `0.0.0.0`, publish port `18790` to host loopback only; place any
> remotely monitored health endpoint behind a firewall or reverse proxy. If another host
> must probe it directly, replace `127.0.0.1` in the port mapping with a trusted host
> interface and restrict inbound traffic to the monitoring system.
### Docker Compose
@@ -74,20 +70,6 @@ docker compose logs -f nanobot-gateway # view logs
docker compose down # stop
```
The default Compose file drops all Linux capabilities and keeps Docker's default
AppArmor/seccomp profiles enabled. If you explicitly set
`"tools.exec.sandbox": "bwrap"` in `~/.nanobot/config.json`, add the bwrap
override file when starting containers:
```bash
docker compose -f docker-compose.yml -f docker-compose.bwrap.yml up -d nanobot-gateway
docker compose -f docker-compose.yml -f docker-compose.bwrap.yml run --rm nanobot-cli agent -m "Hello!"
```
The override grants `CAP_SYS_ADMIN` and disables AppArmor/seccomp confinement for
the container so bubblewrap can create its nested namespaces. Use it only when the
bwrap sandbox is enabled.
### Docker
```bash
@@ -101,23 +83,18 @@ docker run -v ~/.nanobot:/home/nanobot/.nanobot --rm nanobot onboard
vim ~/.nanobot/config.json
# Run gateway (connects to enabled channels, e.g. Telegram/Discord/Mochat).
# `-p 8765:8765` exposes the WebSocket channel / WebUI alongside the gateway
# health endpoint on 18790.
docker run \
--cap-drop ALL \
-v ~/.nanobot:/home/nanobot/.nanobot \
-p 18790:18790 -p 8765:8765 \
nanobot gateway
# If `tools.exec.sandbox: "bwrap"` is enabled, run with the extra permissions
# bubblewrap needs for nested namespaces. Without them, `bwrap` may exit with
# `clone3: Operation not permitted`.
# Mirrors the security caps and port mappings declared in docker-compose.yml:
# - `--cap-drop ALL --cap-add SYS_ADMIN` + unconfined apparmor/seccomp are required
# when `tools.exec.sandbox: "bwrap"` is enabled (bwrap needs CAP_SYS_ADMIN for
# user namespaces). Without them, `bwrap` exits with `clone3: Operation not permitted`.
# - `-p 8765:8765` exposes the WebSocket channel / WebUI alongside the gateway health
# endpoint on 18790.
docker run \
--cap-drop ALL --cap-add SYS_ADMIN \
--security-opt apparmor=unconfined \
--security-opt seccomp=unconfined \
-v ~/.nanobot:/home/nanobot/.nanobot \
-p 127.0.0.1:18790:18790 -p 8765:8765 \
-p 18790:18790 -p 8765:8765 \
nanobot gateway
# Or run a single command
-49
View File
@@ -1,49 +0,0 @@
# nanobot Task Guides
Start with [Install and Quick Start](../quick-start.md) and get one reply before using a guide below. Each guide targets one outcome; linked reference pages hold the complete option tables and edge cases.
## Start and Use
| Goal | Guide |
|---|---|
| Build a personal AI agent | [Build a personal AI agent](./build-a-personal-ai-agent.md) |
| Use the browser workbench | [AI agent WebUI](./ai-agent-webui.md) |
| Run a self-hosted AI agent | [Self-hosted AI agent](./self-hosted-ai-agent.md) |
| Run a sustained goal | [Long-running AI agent](./long-running-ai-agent.md) |
| Add long-term memory | [AI agent memory](./ai-agent-memory.md) |
## Connect a Chat App
Use **Settings → Channels** in the WebUI for guided setup. These guides explain the account, bot, token, permission, and test-message steps on each platform.
| Goal | Guide |
|---|---|
| Connect chat apps | [Chat app AI agent](./chat-app-ai-agent.md) |
| Connect Telegram | [Telegram AI agent](./telegram-ai-agent.md) |
| Connect Discord | [Discord AI agent](./discord-ai-agent.md) |
| Connect Slack | [Slack AI agent](./slack-ai-agent.md) |
| Connect Feishu | [Feishu AI agent](./feishu-ai-agent.md) |
| Connect WhatsApp | [WhatsApp AI agent](./whatsapp-ai-agent.md) |
| Connect WeChat | [WeChat AI agent](./wechat-ai-agent.md) |
| Connect QQ | [QQ AI agent](./qq-ai-agent.md) |
| Connect Email | [Email AI agent](./email-ai-agent.md) |
| Connect Mattermost | [Mattermost AI agent](./mattermost-ai-agent.md) |
## Integrate from Code
| Goal | Guide |
|---|---|
| Run from Python | [Python AI agent SDK](./python-ai-agent-sdk.md) |
| Expose `/v1/chat/completions` | [OpenAI-compatible agent API](./openai-compatible-agent-api.md) |
## Configure and Operate
| Goal | Guide |
|---|---|
| Add MCP tools | [Configure MCP tools](./configure-mcp-tools.md) |
| Enable web search | [Configure web search](./configure-web-search.md) |
| Add model fallback | [Configure model fallback](./configure-model-fallback.md) |
| Add an OpenAI-compatible provider | [Configure an OpenAI-compatible provider](./configure-openai-compatible-provider.md) |
| Add Langfuse tracing | [Configure Langfuse observability](./configure-langfuse-observability.md) |
| Secure local tools | [Secure a local AI agent](./secure-local-ai-agent.md) |
| Deploy the gateway | [Deploy nanobot gateway](./deploy-nanobot-gateway.md) |
-72
View File
@@ -1,72 +0,0 @@
# How AI Agent Memory Works in nanobot
This guide explains how to use nanobot's long-term AI agent memory: session
history, compressed archives, durable memory files, Dream consolidation, and
Git-backed memory changes.
## What you will build
- a workspace with persistent session history
- compressed history archives for older turns
- durable memory files such as `USER.md` and `MEMORY.md`
- a Dream workflow for curating long-term memory
## When to use this
Use memory when an agent should remember stable preferences, project facts,
decisions, and recurring context across sessions. Do not use memory as a dumping
ground for every raw transcript; nanobot separates short-term messages from
curated durable knowledge.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
## Minimal working example
Ask the agent to remember a stable fact in a normal session, then run Dream:
```text
/dream
```
Inspect recent memory changes:
```text
/dream-log
```
The exact files live in the active workspace, usually under
`~/.nanobot/workspace/`.
## Production notes
- Use one workspace per project or personal context.
- Keep durable facts concise; old session details belong in `history.jsonl`.
- Use `/dream-prompt init` when a workspace needs custom memory guidance.
- Review Git-backed memory changes when memory affects important workflows.
## Security notes
- Memory files may contain sensitive user or project facts.
- Avoid sharing workspaces without reviewing `SOUL.md`, `USER.md`, and
`memory/MEMORY.md`.
- Use separate workspaces for personal and team contexts.
## Troubleshooting
- If memory feels stale, run `/dream` and inspect `/dream-log`.
- If memory changed incorrectly, use `/dream-restore` to inspect and restore
previous versions.
- If a new session lacks context, confirm it uses the same workspace.
## Related nanobot docs
- [AI Agent Memory in nanobot](../memory.md)
- [Concepts](../concepts.md)
- [Configuration](../configuration.md#auto-compact)
- [Chat Commands](../chat-commands.md)
-73
View File
@@ -1,73 +0,0 @@
# How to Use an AI Agent WebUI with nanobot
nanobot includes a browser WebUI for persistent chat sessions, visible agent
activity, workspace controls, Apps, MCP presets, Skills, settings, and
Automations.
## What you will build
- a local browser workbench
- one persistent chat session
- a visible timeline of agent messages, tool calls, and file edit diffs
- a gateway-backed WebSocket connection
## When to use this
Use the WebUI when you want a local AI agent interface that is easier to operate
than a terminal, especially for project work, file attachments, model switching,
workspace selection, Apps, Skills, and scheduled automations.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
The published wheel already includes the WebUI bundle. You only need the
`webui/` source directory when changing the frontend.
## Minimal working example
```bash
nanobot webui
```
The launcher checks setup, enables the local WebSocket channel after
confirmation, starts the gateway, and opens the browser.
When nanobot edits a file, the WebUI activity timeline can show the changed
line counts, a unified diff, and an **Open file** action for a read-only
preview. File previews use the chat's current workspace access mode: restricted
access stays inside the selected workspace, while Full Access can preview files
outside the workspace when the gateway allows it.
## Production notes
- Use `nanobot webui --background` when you do not want to keep a terminal open.
- Use `nanobot gateway status`, `logs`, `restart`, and `stop` to manage a
background gateway.
- If you expose the WebUI beyond localhost, set a token issue secret and review
workspace/tool access.
## Security notes
- The first-run WebUI path binds to `127.0.0.1` by default.
- Do not expose the WebUI on a LAN or public host without an intentional access
model.
- Keep file and shell tools scoped to the workspace before inviting other users.
## Troubleshooting
- The WebUI is served by the WebSocket channel on port `8765` by default.
- The gateway health endpoint is separate from the browser UI.
- If the page opens but messages fail, check provider setup with
`nanobot agent -m "Hello!"`.
## Related nanobot docs
- [Nanobot WebUI](../webui.md)
- [Quick Start](../quick-start.md)
- [WebSocket protocol](../websocket.md)
- [Configuration](../configuration.md)
-83
View File
@@ -1,83 +0,0 @@
# How to Build a Personal AI Agent with nanobot
This guide builds a personal AI agent you can run locally, talk to from the
terminal or browser, and later connect to chat apps, memory, tools, and
automations.
## What you will build
- a configured nanobot install
- one working model provider
- one local agent reply
- a browser WebUI session for ongoing work
## When to use this
Use this when you want a personal AI agent that you control rather than a hosted
chat-only interface. nanobot is useful when the agent needs local workspace
access, tool calls, session history, memory, scheduled work, or chat app
delivery.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
The wizard creates `~/.nanobot/config.json` and helps you choose a provider and
model. If terminals and config files are new to you, use
[Start Without Technical Background](../start-without-technical-background.md)
instead.
## Minimal working example
First prove the runtime can answer:
```bash
nanobot agent -m "Hello!"
```
Then open the browser workbench:
```bash
nanobot webui
```
The WebUI starts the local gateway, opens a browser, and keeps persistent chat
sessions for longer work.
## Production notes
- Keep one workspace per project or personal context.
- Use `modelPresets` when you want stable names for fast, deep, local, or
fallback models.
- Keep `nanobot gateway` running for WebUI, chat apps, automations, and the
WebSocket channel.
- Use the Python SDK or OpenAI-compatible API when another program should call
the agent.
## Security notes
- Do not store API keys directly in shared files; use environment variables.
- Prefer chat app pairing for first setup. Use `allowFrom` only for static
allowlists, and keep those lists narrow.
- Enable workspace restriction before exposing file or shell tools to other
users.
- Use a separate workspace for experiments that can modify files.
## Troubleshooting
- `nanobot status` shows the config path, workspace path, and active model.
- If `nanobot agent -m "Hello!"` fails, fix provider setup before opening the
WebUI or chat apps.
- If the WebUI opens but does not answer, check gateway logs and provider
credentials.
## Related nanobot docs
- [Quick Start](../quick-start.md)
- [Concepts](../concepts.md)
- [WebUI](../webui.md)
- [Configuration](../configuration.md)
- [Troubleshooting](../troubleshooting.md)
-96
View File
@@ -1,96 +0,0 @@
# How to Connect an AI Agent to Chat Apps with nanobot
nanobot can run as a self-hosted chatbot or AI agent in Telegram, Discord,
Slack, WeChat, Email, Mattermost, and other chat apps. The gateway receives chat
messages, runs the agent, and sends replies back to the same channel.
## What you will build
- a working local agent
- one enabled chat channel
- a running gateway
- a pairing-based approval flow or a narrow static allowlist
## When to use this
Use chat apps when the agent should live where users already communicate:
private DMs, team channels, group chats, email threads, or bot workspaces.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot webui
```
Send `Hello!` in the WebUI before adding a channel. Then choose one platform guide for the bot/account prerequisites:
- [Telegram AI agent](./telegram-ai-agent.md)
- [Discord AI agent](./discord-ai-agent.md)
- [Slack AI agent](./slack-ai-agent.md)
- [Feishu AI agent](./feishu-ai-agent.md)
- [WhatsApp AI agent](./whatsapp-ai-agent.md)
- [WeChat AI agent](./wechat-ai-agent.md)
- [QQ AI agent](./qq-ai-agent.md)
- [Email AI agent](./email-ai-agent.md)
- [Mattermost AI agent](./mattermost-ai-agent.md)
## Minimal working example
Use the guided channel setup:
1. Get the platform token, login state, webhook, or mailbox credentials.
2. Open **Settings → Channels** in the WebUI.
3. Choose the platform and open its setup panel.
4. Complete the credential or QR flow and install optional support if prompted.
5. Restart when the WebUI requests it.
6. Send a private test message.
7. Approve the pairing request in the WebUI when a DM-capable channel asks for one.
If your installed release does not show **Settings → Channels**, use the full [Chat Apps reference](../chat-apps.md#manual-setup-pattern) to configure the channel manually.
Check status from the terminal when you need a lower-level confirmation:
```bash
nanobot channels status
```
The `nanobot webui` command already runs the gateway. For a chat-only or server deployment, start it directly:
```bash
nanobot gateway
```
Use the full [Chat Apps reference](../chat-apps.md) when you manage `config.json` directly or need platform-specific advanced settings.
## Production notes
- Keep the gateway running as a service for always-on chat apps.
- Use mention-only group policies before opening a bot to busy channels.
- Use one channel at a time while debugging.
- Prefer DMs for first tests; pairing only works in DMs, and group chats add
permissions and routing behavior.
## Security notes
- Prefer pairing or explicit allowlists; do not use `allowFrom: ["*"]` outside
an intentional sandbox.
- Rotate bot tokens if they are pasted into logs or shared files.
- Review file, shell, and web tool access before inviting other users.
## Troubleshooting
- If `nanobot channels status` does not show the channel, the config key or
optional dependency is likely missing.
- If the first DM returns a pairing code, approve the pending request in the WebUI or use `/pairing approve <code>` from an authorized chat.
- If messages do not arrive, run `nanobot gateway --verbose` and compare
platform credentials, event permissions, and allow lists.
- If group replies are unexpected, review that channel's group policy.
## Related nanobot docs
- [Chat Apps](../chat-apps.md)
- [Configuration](../configuration.md#channel-settings)
- [Pairing](../configuration.md#pairing)
- [Deployment](../deployment.md)
@@ -1,79 +0,0 @@
# How to Configure Langfuse Observability for nanobot
nanobot can trace supported OpenAI-compatible provider calls through Langfuse's
OpenAI SDK wrapper.
## What you will build
- Langfuse installed in the same Python environment as nanobot
- Langfuse environment variables set before startup
- one traced nanobot model call
## When to use this
Use Langfuse when you need observability for model requests, latency, errors,
cost, or prompt behavior during development or production operation.
## Install
Install nanobot and prove the agent works:
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Install Langfuse:
```bash
python -m pip install langfuse
```
## Minimal working example
Set credentials before starting nanobot:
```bash
export LANGFUSE_SECRET_KEY="sk-lf-..."
export LANGFUSE_PUBLIC_KEY="pk-lf-..."
export LANGFUSE_BASE_URL="https://cloud.langfuse.com"
nanobot agent -m "Hello!"
```
PowerShell:
```powershell
$env:LANGFUSE_SECRET_KEY = "sk-lf-..."
$env:LANGFUSE_PUBLIC_KEY = "pk-lf-..."
$env:LANGFUSE_BASE_URL = "https://cloud.langfuse.com"
nanobot agent -m "Hello!"
```
## Production notes
- Langfuse is configured with environment variables, not `config.json`.
- Start services from an environment that exports the same variables.
- Add tracing after the provider works; it should not be the first setup step.
- Native providers that do not use the OpenAI-compatible client path may not
produce Langfuse OpenAI-wrapper traces.
## Security notes
- Treat Langfuse projects as observability stores for sensitive prompts and
outputs.
- Use separate projects for personal, staging, and production traffic.
- Keep Langfuse keys out of committed service files.
## Troubleshooting
- If no traces appear, confirm the service process sees the environment
variables.
- Confirm the provider path is OpenAI-compatible.
- Run one local `nanobot agent -m "Hello!"` call before debugging service logs.
## Related nanobot docs
- [Configuration: Langfuse Observability](../configuration.md#langfuse-observability)
- [Provider Cookbook: Langfuse Tracing](../provider-cookbook.md#recipe-langfuse-tracing)
- [Deployment](../deployment.md)
-82
View File
@@ -1,82 +0,0 @@
# How to Configure MCP Tools in nanobot
This guide adds an MCP server to nanobot so the agent can use external tools
through the Model Context Protocol.
## What you will build
- a working nanobot agent
- one MCP integration configured through Apps or `~/.nanobot/config.json`
- a restricted set of MCP tools exposed to the model
## When to use this
Use MCP when the capability you need already exists as an MCP server, or when
you want external tools to be managed outside nanobot core.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Install the MCP server runtime separately. Many examples use `npx`, `uvx`, or a
remote HTTP endpoint.
## Minimal working example
For local interactive setup:
1. Run `nanobot webui` and open **Apps**.
2. Choose a known integration preset, or add a custom stdio, HTTP, or SSE server.
3. Limit the enabled tools when the server exposes more than the task needs.
4. Save and restart when prompted.
5. Mention the integration with `@` in the next message and ask for a small test action.
For manual or deployment-managed config, add this to `~/.nanobot/config.json`:
```json
{
"tools": {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
"enabledTools": ["read_file"]
}
}
}
}
```
Restart nanobot and ask a question that requires the MCP tool.
## Production notes
- Prefer `enabledTools` over exposing every tool by default.
- Use `toolTimeout` for slow MCP operations.
- Use HTTP MCP only for endpoints you trust.
- Keep MCP server commands stable and versioned in deployment docs or scripts.
## Security notes
- Stdio MCP starts a local process; review the command before enabling it.
- HTTP/SSE MCP uses nanobot's SSRF guard.
- Allow private HTTP MCP hosts only with narrow `tools.ssrfWhitelist` CIDRs.
- Do not place secrets in command arguments when environment variables or
headers can be used.
## Troubleshooting
- Run the MCP command outside nanobot first.
- Start `nanobot gateway --verbose` and inspect tool registration logs.
- If an HTTP MCP URL is blocked, check whether it points to loopback or a
private address that needs explicit allowlisting.
## Related nanobot docs
- [MCP tools for AI agents](./mcp-tools-for-ai-agents.md)
- [Configuration: MCP](../configuration.md#mcp-model-context-protocol)
- [Security](../configuration.md#security)
-93
View File
@@ -1,93 +0,0 @@
# How to Configure Model Fallback in nanobot
Model fallback lets nanobot try a primary model first, then fall back to one or
more named presets when the primary provider fails or rate-limits.
## What you will build
- two or more `modelPresets`
- a primary `agents.defaults.modelPreset`
- an ordered `agents.defaults.fallbackModels` chain
## When to use this
Use fallback when you want better reliability across rate limits, provider
outages, local model downtime, or cost-sensitive routing.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Verify each provider works before adding it as a fallback.
## Minimal working example
Merge this shape into `~/.nanobot/config.json` and replace provider/model names
with ones you control:
```json
{
"modelPresets": {
"fast": {
"label": "Fast",
"provider": "primary-provider",
"model": "primary-model-id",
"maxTokens": 4096,
"contextWindowTokens": 65536,
"temperature": 0.1
},
"deep": {
"label": "Deep",
"provider": "fallback-provider",
"model": "fallback-model-id",
"maxTokens": 4096,
"contextWindowTokens": 200000,
"temperature": 0.1
}
},
"agents": {
"defaults": {
"modelPreset": "fast",
"fallbackModels": ["deep"]
}
}
}
```
String entries in `fallbackModels` are preset names, not raw model IDs.
Replace the placeholder model IDs with currently supported model IDs from your
provider. The [Provider Cookbook](../provider-cookbook.md) has concrete recipes
for common providers.
## Production notes
- Keep fallback context windows realistic; smaller fallback windows constrain
how much context can fit.
- Put cheaper or faster fallbacks before expensive ones when acceptable.
- Use `/model <preset>` for runtime switching without editing config.
- Keep labels human-readable for WebUI model lists.
## Security notes
- Different providers may have different data handling policies.
- Do not put provider keys directly in shared config files.
- Confirm fallback models can safely receive the same prompts and files.
## Troubleshooting
- If a fallback never triggers, confirm the primary error is treated as
retryable/fallbackable.
- If startup fails, check that each fallback string matches a key under
`modelPresets`.
- If output is truncated after fallback, review `maxTokens` and
`contextWindowTokens`.
## Related nanobot docs
- [Providers and Models](../providers.md)
- [Provider Cookbook: Fallback Presets](../provider-cookbook.md#recipe-fallback-presets)
- [Configuration: Model Fallbacks](../configuration.md#model-fallbacks)
@@ -1,93 +0,0 @@
# How to Configure an OpenAI-Compatible Provider in nanobot
nanobot can call OpenAI-compatible model providers by configuring an `apiBase`,
optional `apiKey`, and a model preset that references that provider name.
## What you will build
- a custom provider entry
- a model preset pointing at that provider
- one successful `nanobot agent` run
## When to use this
Use this for local or hosted services that expose OpenAI-compatible endpoints,
including internal gateways, local model servers, and provider proxies that are
not already named in nanobot.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
Verify the endpoint responds before debugging nanobot:
```bash
curl -sS https://api.example.com/v1/models
```
## Minimal working example
Merge this into `~/.nanobot/config.json`:
```json
{
"providers": {
"custom": {
"apiKey": "${CUSTOM_API_KEY}",
"apiBase": "https://api.example.com/v1"
}
},
"modelPresets": {
"primary": {
"label": "Custom",
"provider": "custom",
"model": "provider-model-name",
"maxTokens": 4096,
"contextWindowTokens": 65536,
"temperature": 0.1
}
},
"agents": {
"defaults": {
"modelPreset": "primary"
}
}
}
```
Then run:
```bash
nanobot agent -m "Hello!"
```
## Production notes
- Include the version path in `apiBase` when the service expects `/v1`.
- Use separate provider names for separate endpoints.
- Use a placeholder key such as `EMPTY` only when the endpoint requires a
non-empty key but does not validate it.
- Leave `apiType` unset for OpenAI-compatible custom endpoints.
## Security notes
- Keep provider keys in environment variables.
- Treat internal model gateways as sensitive network services.
- Do not point nanobot at untrusted proxy endpoints for private workspaces.
## Troubleshooting
- If `curl /models` fails, fix the provider endpoint before changing nanobot.
- If nanobot says the model is unknown, check the model ID expected by the
provider.
- If auth fails, confirm whether the provider wants Bearer auth and whether the
key is present in the environment that starts nanobot.
## Related nanobot docs
- [Provider Cookbook: Custom OpenAI-Compatible Provider](../provider-cookbook.md#recipe-custom-openai-compatible-provider)
- [Providers: Custom OpenAI-Compatible Endpoint](../providers.md#custom-openai-compatible-endpoint)
- [OpenAI-Compatible Agent API](./openai-compatible-agent-api.md)
-98
View File
@@ -1,98 +0,0 @@
# How to Configure Web Search for a nanobot AI Agent
nanobot includes built-in web search and web fetch tools. Search uses
DuckDuckGo by default and can be configured for API-backed or self-hosted
providers.
## What you will build
- web tools enabled in nanobot
- one search provider selected in the WebUI or `config.json`
- optional web fetch settings for page reading
## When to use this
Configure web search when the agent needs current information, public web
research, source discovery, or page fetching during a task.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Web tools are enabled by default. Configure them only when you want a specific
provider, API key, proxy, fetch behavior, or SSRF allowlist.
## Minimal working example
For local interactive setup:
1. Run `nanobot webui`.
2. Open **Settings → Web**.
3. Enable web search, choose a provider, and enter its API key if required.
4. Save and restart when prompted.
5. Ask a question that requires current information and inspect the cited sources.
For manual or deployment-managed config, use the default search provider:
```json
{
"tools": {
"web": {
"enable": true,
"search": {
"provider": "duckduckgo"
}
}
}
}
```
Or use an API-backed provider:
```json
{
"tools": {
"web": {
"search": {
"provider": "brave",
"apiKey": "${BRAVE_API_KEY}"
}
}
}
}
```
Ask a question that requires current information and inspect the tool activity
in the WebUI or logs.
## Production notes
- Keep API keys in environment variables.
- Set `maxResults` when you need fewer or more search results per query.
- Set `tools.web.proxy` only to a proxy you trust.
- Use `fetch.useJinaReader: false` if you need local page conversion.
## Security notes
- Web fetch and HTTP MCP share an SSRF guard.
- Private, loopback, link-local, and cloud metadata addresses are blocked by
default.
- Add `tools.ssrfWhitelist` only for narrow trusted CIDRs.
- Do not give public chat users unrestricted web and shell access without
review.
## Troubleshooting
- If search returns no results, switch provider or check the provider API key.
- If fetch is blocked, inspect the target URL and SSRF whitelist.
- If a proxy changes network behavior, verify `NO_PROXY` and proxy settings.
## Related nanobot docs
- [Configuration: Web Tools](../configuration.md#web-tools)
- [Security](../configuration.md#security)
- [WebUI](../webui.md)
-76
View File
@@ -1,76 +0,0 @@
# How to Deploy a Long-Running nanobot AI Agent Gateway
The nanobot gateway is the long-running self-hosted AI agent process that keeps
WebUI sessions, chat apps, automations, local triggers, heartbeat jobs, Dream,
and WebSocket delivery online.
## What you will build
- a verified nanobot config
- a gateway process
- a service or container deployment path with Docker, systemd, or macOS
LaunchAgent
## When to use this
Use this when nanobot should keep running after a single CLI turn. Chat apps,
browser sessions, background automations, local triggers, and server-side
integrations all depend on a live gateway.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot status
nanobot agent -m "Hello!"
```
## Minimal working example
Run the gateway in the foreground:
```bash
nanobot gateway
```
For WebUI background usage:
```bash
nanobot webui --background
nanobot gateway status
nanobot gateway logs
```
## Production notes
- Docker Compose is the most repeatable Linux container path.
- systemd user services are useful for Linux user-level gateway deployments.
- macOS LaunchAgent keeps the gateway alive after login.
- Persist config, workspace, sessions, memory files, channel login state, and
generated artifacts.
- Restart the gateway after editing `config.json`.
## Security notes
- Plan ports before exposing services. Gateway health defaults to `18790`,
WebUI/WebSocket defaults to `8765`, and `nanobot serve` defaults to `8900`.
- Bind externally only when you have configured tokens or API keys.
- Keep chat access control intentional before deploying.
- Use Docker or Linux sandboxing when shell tools are enabled for unattended
work.
## Troubleshooting
- Use the same `--config` and `--workspace` flags for status checks and service
startup.
- Check logs with `docker compose logs`, `journalctl`, LaunchAgent logs, or
`nanobot gateway --verbose`.
- If Docker port publishing does not work, confirm the service is not bound only
to container loopback.
## Related nanobot docs
- [Deployment](../deployment.md)
- [Multiple Instances](../multiple-instances.md)
- [Configuration](../configuration.md)
-107
View File
@@ -1,107 +0,0 @@
# Build a Discord AI Agent with nanobot
This guide connects nanobot to Discord so a Discord user or server channel can
talk to your self-hosted AI agent through the nanobot gateway.
## What this guide builds
- a Discord bot application
- Message Content intent enabled
- the `discord` channel enabled in nanobot
- one direct message or mention test
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- Access to the Discord Developer Portal.
- A Discord server where you can invite a bot.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the Discord channel
Install the optional channel dependency:
```bash
nanobot plugins enable discord
```
Create a Discord application, add a bot, copy the token, and enable
`MESSAGE CONTENT INTENT` in the bot settings.
Merge this snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"discord": {
"enabled": true,
"token": "YOUR_BOT_TOKEN",
"allowChannels": [],
"groupPolicy": "mention",
"streaming": true
}
}
}
```
Omitting `allowFrom` enables pairing-only mode. A new user should DM the bot
first, get a pairing code, and be approved before using the bot in servers.
Invite the bot with permissions to read history and send messages.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
Send the bot a DM first. It should return a pairing code. Approve it from a
trusted local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
After approval, mention it in an allowed server channel:
```text
@your-bot Hello from Discord
```
## Security notes
- Keep `groupPolicy` as `mention` for first deployment.
- Use `allowChannels` for server channels where the bot should operate.
- Prefer pairing-only mode for user access; add `allowFrom` only when you want a
static allowlist.
- Avoid open group behavior in busy channels until session routing is clear.
- Review tool access before inviting the bot into shared servers.
## Troubleshooting
- If no messages arrive, confirm Message Content intent is enabled.
- If a DM returns a pairing code, approve it before testing normal replies.
- If server messages are ignored, check pairing approval, `allowChannels`, and
whether the bot was mentioned.
- If the bot cannot reply, confirm the invite permissions and channel overrides.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Pairing](../configuration.md#pairing)
- [AI Agent Memory](./ai-agent-memory.md)
- [Configure MCP tools](./configure-mcp-tools.md)
-93
View File
@@ -1,93 +0,0 @@
# Build an Email AI Agent with nanobot
This guide turns nanobot into an email AI agent that polls IMAP for accepted
messages and replies through SMTP.
## What this guide builds
- a dedicated mailbox for nanobot
- IMAP and SMTP credentials in `config.json`
- an allowed sender list
- a gateway process that polls and replies
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- A mailbox for the bot.
- IMAP and SMTP access. For Gmail, use an app password rather than your account
password.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the Email channel
Merge this snippet into `~/.nanobot/config.json` and replace the addresses and
passwords:
```json
{
"channels": {
"email": {
"enabled": true,
"consentGranted": true,
"imapHost": "imap.gmail.com",
"imapPort": 993,
"imapUsername": "my-nanobot@gmail.com",
"imapPassword": "your-app-password",
"smtpHost": "smtp.gmail.com",
"smtpPort": 587,
"smtpUsername": "my-nanobot@gmail.com",
"smtpPassword": "your-app-password",
"fromAddress": "my-nanobot@gmail.com",
"allowFrom": ["your-real-email@gmail.com"],
"autoReplyEnabled": true
}
}
}
```
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
Send an email from an address in `allowFrom` to the bot mailbox. Keep the
gateway running long enough for the polling interval to receive it.
## Security notes
- Use a dedicated mailbox, not your primary personal inbox.
- Set `consentGranted` to `false` to fully disable mailbox access.
- Email does not use DM pairing. Keep `allowFrom` narrow; `["*"]` accepts mail
from anyone.
- Use environment variables for mailbox passwords.
- Enable attachment types only when the agent needs them.
## Troubleshooting
- If login fails, confirm IMAP/SMTP access and app-password setup.
- If the bot reads but does not reply, check `autoReplyEnabled`, SMTP settings,
and allowed sender addresses.
- If attachments are missing, review `allowedAttachmentTypes`, size limits, and
gateway logs.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Secure local AI agent](./secure-local-ai-agent.md)
- [AI Agent Memory](./ai-agent-memory.md)
- [OpenAI-compatible agent API](./openai-compatible-agent-api.md)
-120
View File
@@ -1,120 +0,0 @@
# Build a Feishu AI Agent with nanobot
This guide connects nanobot to Feishu or Lark through the `feishu` channel. The
channel uses a WebSocket long connection, so the first setup does not require a
public webhook URL.
## What this guide builds
- a Feishu/Lark bot app connected to nanobot
- the `feishu` channel enabled in `config.json`
- one pairing-approved Feishu or Lark user
- mention-only group behavior for first deployment
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- A Feishu or Lark account that can create or approve bot apps.
- Permission to run `nanobot gateway` continuously.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the Feishu channel
Install the optional channel dependency:
```bash
nanobot plugins enable feishu
```
The easiest path is QR login:
```bash
nanobot channels login feishu
```
Open the printed URL or scan the QR code. nanobot writes the generated `appId`,
`appSecret`, `domain`, and `enabled` fields into the active config.
If QR login is unavailable, create a Feishu/Lark app manually and merge this
shape into `~/.nanobot/config.json`:
```json
{
"channels": {
"feishu": {
"enabled": true,
"appId": "cli_xxx",
"appSecret": "xxx",
"groupPolicy": "mention",
"streaming": true,
"domain": "feishu"
}
}
}
```
Omitting `allowFrom` enables pairing-only mode. A new user should DM the bot,
get a pairing code, and be approved before using the bot normally.
For manual apps, enable the Bot capability, receive-message events, and Long
Connection mode. If your app cannot get the `cardkit:card:write` permission,
set `"streaming": false`.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
DM the bot first. It should return a pairing code. Approve it from a trusted
local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
After approval, DM the bot again or mention it in a group chat:
```text
@nanobot Hello from Feishu
```
## Security notes
- Prefer pairing-only mode for first setup. Add `allowFrom` only when you want a
static allowlist.
- Keep `groupPolicy` as `"mention"` before inviting the bot into busy groups.
- Store app secrets through environment variables for deployed services.
- Review file, shell, and web tool access before adding more users.
## Troubleshooting
- If QR login is unavailable, use manual app setup from the full chat-apps
reference.
- If streaming cards fail, confirm `cardkit:card:write` or set
`"streaming": false`.
- If no messages arrive, check Feishu/Lark event permissions, Long Connection
mode, and `nanobot gateway --verbose`.
- If a first DM returns a pairing code, approve it before testing normal
replies.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Pairing](../configuration.md#pairing)
- [AI Agent Memory](./ai-agent-memory.md)
- [Configure MCP tools](./configure-mcp-tools.md)
-73
View File
@@ -1,73 +0,0 @@
# How to Run a Long-Running AI Agent with nanobot
nanobot can keep agent work alive across turns through sustained goals,
persistent sessions, scheduled automations, local triggers, and a gateway
process that stays running.
## What you will build
- a working local agent
- a persistent chat session
- a long-running goal or automation
- a gateway process for background delivery
## When to use this
Use this when the task is not a one-shot answer: project work, recurring checks,
scheduled summaries, file maintenance, multi-step research, or local triggers
from scripts and build jobs.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
## Minimal working example
Start a gateway:
```bash
nanobot gateway
```
From the WebUI or a chat session, start a sustained goal:
```text
/goal Review this workspace, identify missing tests, and propose the smallest next fix.
```
For scheduled or trigger-based runs, create the automation from the target chat
so nanobot can link it to the correct session and workspace.
## Production notes
- Keep the gateway running for chat apps, WebUI sessions, automations, and local
triggers.
- Use stable session keys or chat sessions for work that should preserve context.
- Keep goals bounded and explicit about done-ness.
- Review Automations in the WebUI before relying on a schedule.
## Security notes
- Treat long-running goals as delegated work with real tool access.
- Restrict workspaces and shell execution before scheduling unattended tasks.
- Keep chat access narrow so unknown users cannot create goals or automations.
## Troubleshooting
- If a goal appears stuck, inspect the active session and gateway logs.
- If an automation does not run, check that it is linked to a chat/session and
that the gateway is still running.
- If a local trigger fails, check the command copied from the WebUI Automations
view.
## Related nanobot docs
- [Automations](../automations.md)
- [WebUI Automations](../webui.md#automations)
- [Chat Commands](../chat-commands.md)
- [Memory](../memory.md)
- [Deployment](../deployment.md)
-104
View File
@@ -1,104 +0,0 @@
# Build a Mattermost AI Agent with nanobot
This guide connects nanobot to Mattermost through the built-in Mattermost
channel, using WebSocket events and the Mattermost REST API.
## What this guide builds
- a Mattermost bot account or token
- the `mattermost` channel enabled in nanobot
- mention-only group behavior for first deployment
- one pairing-approved DM or mention test
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- A Mattermost server URL.
- A bot token or personal access token for the bot account.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the Mattermost channel
Merge this snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"mattermost": {
"enabled": true,
"serverUrl": "https://mattermost.example.com",
"token": "YOUR_MATTERMOST_TOKEN",
"teamId": "YOUR_TEAM_ID",
"groupPolicy": "mention",
"replyInThread": true,
"dm": {
"policy": "allowlist"
}
}
}
}
```
`teamId` scopes the channel to a Mattermost team. Keep `groupPolicy` as
`mention` for the first test.
Mattermost DMs are open by default. Setting `dm.policy` to `"allowlist"` with no
`dm.allowFrom` entries makes new DM senders receive a pairing code. Approve the
code before using the bot normally.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
DM the bot account. It should return a pairing code. Approve it from a trusted
local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
Then DM the bot again, or mention it in a channel where the bot has access:
```text
@nanobot Hello from Mattermost
```
## Security notes
- Store the Mattermost token in an environment variable for deployed services.
- Keep `dm.policy` as `"allowlist"` when you want pairing-based approval.
- Use mention-only group behavior before opening the bot to busy channels.
- Review file and shell tools before inviting broad channel access.
## Troubleshooting
- If startup logs say `serverUrl and token must be configured`, check the
camelCase config keys.
- If DMs are ignored, review the `dm` policy and pairing approval state.
- If channel messages are ignored, confirm the bot is mentioned and belongs to
the team/channel.
- If thread replies are surprising, review `replyInThread` and
`includeThreadContext`.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Pairing](../configuration.md#pairing)
- [Long-running AI Agent](./long-running-ai-agent.md)
- [Deployment](../deployment.md)
-75
View File
@@ -1,75 +0,0 @@
# How to Add MCP Tools to an AI Agent with nanobot
nanobot can connect MCP servers and expose their tools to the agent alongside
built-in file, shell, web, cron, image generation, and subagent tools.
## What you will build
- a working nanobot agent
- one MCP server configured in `config.json`
- a restricted set of tools available to the model
## When to use this
Use MCP when a tool already exists as an MCP server, when another application
publishes an MCP adapter, or when you want a clean boundary between nanobot and
external tool logic.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Install the MCP server's own runtime separately. For example, many local MCP
servers use `npx` or `uvx`.
## Minimal working example
Add a stdio MCP server to `~/.nanobot/config.json`:
```json
{
"tools": {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
"enabledTools": ["read_file"]
}
}
}
}
```
Restart nanobot, then ask a question that needs the MCP tool.
## Production notes
- Use `enabledTools` to expose only the tools the agent actually needs.
- Set `toolTimeout` for slow MCP servers.
- Prefer stdio MCP for local tools and HTTP MCP for trusted remote services.
- Keep MCP server install/update steps outside nanobot config when possible.
## Security notes
- HTTP/SSE MCP URLs use the same SSRF guard as web fetch.
- Local/private HTTP endpoints require an explicit `tools.ssrfWhitelist` entry.
- Stdio MCP servers run local processes; review their command and arguments.
- Do not pass secrets in command-line args when environment variables or headers
are available.
## Troubleshooting
- Start `nanobot gateway --verbose` and check MCP startup logs.
- Confirm the MCP command works by itself before debugging nanobot.
- If an HTTP MCP server is blocked, review the SSRF whitelist and use a narrow
host CIDR.
## Related nanobot docs
- [Configure MCP tools](./configure-mcp-tools.md)
- [Configuration: MCP](../configuration.md#mcp-model-context-protocol)
- [Security](../configuration.md#security)
@@ -1,74 +0,0 @@
# How to Run an OpenAI-Compatible Agent API with nanobot
nanobot can expose a local OpenAI-compatible endpoint behind
`/v1/chat/completions`. This lets existing OpenAI-style clients talk to a
tool-using nanobot agent instead of a raw model.
## What you will build
- a working nanobot agent
- a local API server on `127.0.0.1:8900`
- a `/v1/chat/completions` request
- optional session isolation with `session_id`
## When to use this
Use this when an existing client, another language, or a separate process
already knows how to call an OpenAI-compatible API. Use the Python SDK when you
want in-process access to sessions, memory, runtime helpers, and hooks.
## Install
```bash
python -m pip install nanobot-ai
nanobot plugins enable api
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
## Minimal working example
Start the API server:
```bash
nanobot serve
```
Call the chat endpoint:
```bash
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "hi"}],
"session_id": "demo"
}'
```
## Production notes
- Pass `session_id` to isolate users, jobs, or workflows.
- Streaming uses Server-Sent Events when `stream` is `true`.
- `/v1/models` reports the fixed model surface expected by compatible clients.
- File uploads are supported through JSON base64 or multipart form data.
## Security notes
- Local `127.0.0.1` usage does not require an API key.
- If `api.host` is `0.0.0.0` or `::`, configure `api.apiKey` before startup.
- Treat the API as agent access, not just model access: tools and workspace
permissions still matter.
## Troubleshooting
- If `/v1/chat/completions` fails, test `nanobot agent -m "Hello!"` first.
- If remote clients cannot connect, check `api.host`, `api.port`, firewall, and
API key configuration.
- If sessions mix together, pass unique `session_id` values.
## Related nanobot docs
- [Nanobot OpenAI-Compatible API](../openai-api.md)
- [Python SDK](../python-sdk.md)
- [Configuration](../configuration.md)
- [Deployment](../deployment.md)
-75
View File
@@ -1,75 +0,0 @@
# Nanobot Python SDK: Run an AI Agent from Python
This guide shows when to use the Nanobot Python SDK instead of calling a model
directly. The SDK runs the same agent runtime used by the CLI: model routing,
tools, workspace access, session history, memory, streaming events, and runtime
helpers.
## What you will build
- a Python script that creates a `Nanobot`
- one agent run from code
- an optional streamed run with tool visibility
## When to use this
Use the Python SDK for notebooks, evals, product backends, local scripts,
workflow runners, and integrations that need direct access to agent sessions,
memory, hooks, runtime state, or structured run results.
Use the OpenAI-compatible API instead when another language or process should
call nanobot over HTTP.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
## Minimal working example
```python
import asyncio
from nanobot import Nanobot
async def main() -> None:
async with Nanobot.from_config() as bot:
result = await bot.run("List the top-level files in this workspace.")
print(result.content)
asyncio.run(main())
```
## Production notes
- Reuse one `Nanobot` instance for related work.
- Pass `session_key` when a user, job, or eval case needs persistent history.
- Use `bot.stream(...)` when the caller needs live text, tool, or failure
events.
- Use hooks for audit logs or custom observability.
## Security notes
- The SDK uses the same config, workspace, tools, and secrets as the CLI.
- Do not run untrusted prompts with broad file or shell access.
- Keep separate config/workspace paths for separate products or tenants.
## Troubleshooting
- If SDK code fails, first run `nanobot agent -m "Hello!"` in the same
environment.
- Print `bot.runtime.workspace` and `bot.runtime.model` to confirm the expected
config loaded.
- Use explicit `config_path` and `workspace` when scripts run from services.
## Related nanobot docs
- [Nanobot Python SDK](../python-sdk.md)
- [OpenAI-Compatible API](../openai-api.md)
- [Configuration](../configuration.md)
- [Concepts](../concepts.md)
-102
View File
@@ -1,102 +0,0 @@
# Build a QQ AI Agent with nanobot
This guide connects nanobot to QQ through the official `qq` channel. The
official channel uses the botpy SDK and currently focuses on private messages.
For QQ group chat and OneBot v11 workflows, use the Napcat section in the full
chat-apps reference.
## What this guide builds
- a QQ bot application
- the `qq` channel enabled in nanobot
- one pairing-approved QQ private sender
- a running nanobot gateway
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- Access to the QQ Open Platform.
- A QQ account added to the bot sandbox for testing.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the QQ channel
Install the optional channel dependency:
```bash
nanobot plugins enable qq
```
In the QQ Open Platform, create a bot application and copy the AppID and
AppSecret. Add your QQ account to the sandbox test members, then merge this
snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"qq": {
"enabled": true,
"appId": "YOUR_APP_ID",
"secret": "YOUR_APP_SECRET",
"msgFormat": "plain"
}
}
}
```
Omitting `allowFrom` enables pairing-only mode. A new private sender should get
a pairing code before normal agent access.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
Send the QQ bot a private message from a sandbox account. It should return a
pairing code. Approve it from a trusted local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
Send the message again after approval.
## Security notes
- Prefer pairing-only mode for first setup. Add `allowFrom` only when you want a
static allowlist.
- Keep sandbox testing separate from production publishing.
- Store QQ AppSecret through environment variables for deployed services.
- Use Napcat only when you intentionally need a QQ account bridge and group chat
features.
## Troubleshooting
- If private messages do not arrive, confirm the sender is in the QQ bot sandbox
and the gateway is running.
- If output formatting is unreliable, keep `msgFormat` as `"plain"`.
- If a first private message returns a pairing code, approve it before testing
normal replies.
- If you need QQ groups, see the Napcat section in the full chat-apps reference.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Pairing](../configuration.md#pairing)
- [AI Agent Memory](./ai-agent-memory.md)
- [Configure MCP tools](./configure-mcp-tools.md)
-78
View File
@@ -1,78 +0,0 @@
# How to Secure a Local AI Agent with nanobot
This guide covers the practical controls to review before letting a nanobot
agent access files, shell commands, web fetch, chat apps, or remote users.
## What you will build
- a workspace-scoped agent setup
- narrow channel access
- safer secrets handling
- optional shell sandboxing on Linux
## When to use this
Use this before exposing nanobot to teammates, chat apps, public networks, broad
web access, or unattended automations.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
## Minimal working example
Start with workspace restriction:
```json
{
"tools": {
"restrictToWorkspace": true,
"exec": {
"enable": true,
"sandbox": "bwrap"
}
}
}
```
`bwrap` is Linux-only and requires bubblewrap. On macOS or Windows, keep
`restrictToWorkspace` enabled and review shell access carefully.
## Production notes
- Use environment variables for provider keys, bot tokens, and mailbox
passwords.
- Keep one workspace per trust boundary.
- Prefer pairing for DM-capable chat apps, use narrow `allowFrom` lists only
when static allowlists are intentional, and keep group policy mention-only at
first.
- Bind WebUI, WebSocket, and API services to localhost unless remote access is
intentional.
## Security notes
- `restrictToWorkspace` is an application-level guard, not an OS sandbox.
- `tools.exec.enable: false` removes shell execution entirely.
- HTTP web fetch and HTTP MCP use SSRF protections by default.
- Adding broad `tools.ssrfWhitelist` ranges increases exposure.
- `allowFrom: ["*"]` bypasses pairing and means anyone who can reach that
channel can talk to the bot.
## Troubleshooting
- If a needed file cannot be read, confirm the active workspace path.
- If a shell command fails under `bwrap`, check whether the command needs files
outside the sandbox.
- If local HTTP tools are blocked, review the SSRF whitelist and use a narrow
CIDR.
## Related nanobot docs
- [Configuration: Security](../configuration.md#security)
- [Pairing](../configuration.md#pairing)
- [Deployment](../deployment.md)
- [Chat Apps](../chat-apps.md)
-83
View File
@@ -1,83 +0,0 @@
# How to Run a Self-Hosted AI Agent with nanobot
This guide sets up nanobot as a self-hosted AI agent runtime on your own
machine or server. The result is a gateway process that can serve the WebUI,
chat apps, automations, and API integrations.
## What you will build
- a nanobot config and workspace under your control
- a model provider connected through `config.json`
- a long-running `nanobot gateway`
- optional browser, chat app, and API access
## When to use this
Use this path when you want local or server-side ownership of the agent process,
workspace files, memory files, and provider keys. It is also the right path when
the agent must keep running after one terminal command finishes.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Complete the CLI check before deploying the gateway. A deployment problem is
much easier to debug after the provider and model are known to work.
## Minimal working example
For chat apps, automations, and WebSocket delivery, start the gateway:
```bash
nanobot gateway
```
For the browser surface, use the WebUI launcher instead. It can start and manage
the local gateway for you:
```bash
nanobot webui
```
Or connect a channel in `~/.nanobot/config.json`, then keep the same gateway
process running for messages.
## Production notes
- Use Docker, systemd, or a macOS LaunchAgent when the process should survive
terminal exits.
- Give every deployed instance a distinct config path, workspace path, and port
set.
- Keep secrets in environment variables and start the service from the same
environment.
- Use health checks against the gateway or API process, not chat app delivery as
the only signal.
## Security notes
- Bind local-only services to `127.0.0.1` unless you intentionally expose them.
- Set an API key before binding the OpenAI-compatible API to a public interface.
- Prefer pairing for DM-capable chat apps, and keep any static `allowFrom`
allowlists strict.
- Enable `tools.restrictToWorkspace`; on Linux, use the bubblewrap sandbox for
shell execution.
## Troubleshooting
- Run `nanobot status` with the same `--config` and `--workspace` flags used by
the service.
- Run `nanobot gateway --verbose` while debugging channel startup.
- Check port conflicts if the WebUI, WebSocket channel, or API endpoint fails to
bind.
## Related nanobot docs
- [Deployment](../deployment.md)
- [Multiple Instances](../multiple-instances.md)
- [Configuration](../configuration.md)
- [Chat Apps](../chat-apps.md)
- [OpenAI-Compatible API](../openai-api.md)
-109
View File
@@ -1,109 +0,0 @@
# Build a Slack AI Agent with nanobot
This guide connects nanobot to Slack through Socket Mode. No public webhook URL
is required for the first working setup.
## What this guide builds
- a Slack app with Socket Mode
- a bot token and app-level token
- the `slack` channel enabled in nanobot
- a DM pairing flow and mention test from an approved Slack user
## Prerequisites
- A working nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- Permission to create a Slack app in a workspace.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the Slack channel
Install the optional channel dependency:
```bash
nanobot plugins enable slack
```
In Slack, create an app, enable Socket Mode, create an app-level token with
`connections:write`, add bot scopes, subscribe to bot events, and install the
app to your workspace.
Merge this snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"slack": {
"enabled": true,
"botToken": "xoxb-...",
"appToken": "xapp-...",
"groupPolicy": "mention",
"dm": {
"policy": "allowlist"
}
}
}
}
```
Slack DMs are open by default. Setting `dm.policy` to `"allowlist"` with no
`dm.allowFrom` entries makes new DM senders receive a pairing code. Approve the
code before using the bot normally.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
DM the Slack bot directly. It should return a pairing code. Approve it from a
trusted local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
Then DM the bot again, or mention it in a channel:
```text
@nanobot Hello from Slack
```
## Security notes
- Keep `groupPolicy` as `mention` unless the bot is intentionally listening to
every channel message.
- Keep `dm.policy` as `"allowlist"` when you want pairing-based approval.
- Use `groupAllowFrom` with allowlist mode for approved channels.
- Reinstall the Slack app after changing scopes.
- Keep bot and app tokens out of committed config files.
## Troubleshooting
- If Socket Mode fails, confirm the app-level token starts with `xapp-`.
- If the bot cannot send files, add `files:write`, reinstall the app, and
restart nanobot.
- If a DM responds normally without pairing, check that `dm.policy` is
`"allowlist"`.
- If channel messages are ignored, check event subscriptions and group policy.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Configure web search](./configure-web-search.md)
- [Long-running AI Agent](./long-running-ai-agent.md)
- [Deployment](../deployment.md)
-109
View File
@@ -1,109 +0,0 @@
# Build a Telegram AI Agent with nanobot
This guide connects nanobot to Telegram so a paired Telegram user can message a
self-hosted AI agent backed by your normal nanobot config, tools, memory, and
workspace.
## What this guide builds
- a Telegram bot created through BotFather
- the `telegram` channel enabled in nanobot
- a running nanobot gateway
- one pairing-approved Telegram account
## Prerequisites
- A working nanobot CLI reply:
```bash
nanobot agent -m "Hello!"
```
- A Telegram account.
- A bot token from `@BotFather`.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the Telegram channel
Install the optional channel dependency:
```bash
nanobot plugins enable telegram
```
Merge this snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"telegram": {
"enabled": true,
"token": "YOUR_BOT_TOKEN"
}
}
}
```
Omitting `allowFrom` enables pairing-only mode. The first DM from a new user
gets a pairing code instead of agent access.
Telegram uses long polling by default. Webhook mode is available for public
HTTPS deployments; start with long polling for the first test.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
Leave the gateway running while you test messages.
## Test a message
Open Telegram, DM the bot, and send:
```text
Hello from Telegram
```
The bot should reply with a pairing code. Approve it from an already trusted
surface, such as the local CLI:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
Send the message again after approval. The reply should use the same model and
workspace as your local CLI check.
## Security notes
- Prefer pairing-only mode for first setup. Add `allowFrom` only when you want a
static allowlist instead of code approval.
- Do not use `allowFrom: ["*"]` unless the bot is isolated or intentionally public.
- Rotate the BotFather token if it is pasted into logs or shared files.
- Review tool access before adding group chats or more users.
## Troubleshooting
- If the channel is not listed, run `nanobot plugins enable telegram` again in
the same Python environment.
- If messages do not arrive, run `nanobot gateway --verbose` and check the bot
token.
- If a first DM returns a pairing code, that is expected. Approve the code before
testing normal agent replies.
- If Telegram Web shows unsupported rich messages, keep `richMessages` disabled.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [AI Agent Memory](./ai-agent-memory.md)
- [Long-running AI Agent](./long-running-ai-agent.md)
- [Configure MCP tools](./configure-mcp-tools.md)
-103
View File
@@ -1,103 +0,0 @@
# Build a WeChat AI Agent with nanobot
This guide connects nanobot to WeChat through the `weixin` channel. The channel
uses HTTP long polling with QR-code login through the supported upstream API.
## What this guide builds
- the `weixin` channel enabled in nanobot
- a QR-code login session
- one pairing-approved WeChat sender
- a running gateway for message delivery
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- A WeChat account that can complete QR-code login.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the WeChat channel
Install the optional channel dependency:
```bash
nanobot plugins enable weixin
```
Merge this snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"weixin": {
"enabled": true
}
}
}
```
Omitting `allowFrom` enables pairing-only mode. The first private WeChat message
from a new sender gets a pairing code instead of agent access.
Log in:
```bash
nanobot channels login weixin
```
Use `--force` if you need to discard saved login state and authenticate again.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
Send a private WeChat message to the bot. It should reply with a pairing code.
Approve it from a trusted local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
Send the message again after approval and watch gateway logs for the sender ID
and reply.
## Security notes
- Prefer pairing-only mode for first setup. Add `allowFrom` only when you want a
static allowlist.
- Treat saved login state as sensitive account access.
- Avoid connecting personal accounts to untrusted workspaces or broad tool
permissions.
## Troubleshooting
- If login fails, rerun `nanobot channels login weixin --force`.
- If a first private message returns a pairing code, that is expected. Approve
the code before testing normal agent replies.
- If messages are denied without a pairing code, check gateway logs for whether
WeChat provided the context token required for nanobot to reply.
- If polling disconnects, restart the gateway and check network reachability to
the upstream service.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [AI Agent Memory](./ai-agent-memory.md)
- [Secure local AI agent](./secure-local-ai-agent.md)
- [Deployment](../deployment.md)
-107
View File
@@ -1,107 +0,0 @@
# Build a WhatsApp AI Agent with nanobot
This guide connects nanobot to WhatsApp through the `whatsapp` channel. The
channel links as a WhatsApp device and uses the same nanobot agent runtime,
tools, memory, and workspace as the CLI and WebUI.
## What this guide builds
- WhatsApp optional dependencies installed
- a linked WhatsApp device session
- the `whatsapp` channel enabled in `config.json`
- one pairing-approved WhatsApp sender
## Prerequisites
- A working local nanobot reply:
```bash
nanobot agent -m "Hello!"
```
- A WhatsApp account that can link a new device.
- A machine that can keep `nanobot gateway` running.
## Install nanobot
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
## Enable the WhatsApp channel
Install the optional channel dependency:
```bash
nanobot plugins enable whatsapp
```
Link WhatsApp as a device:
```bash
nanobot channels login whatsapp
```
Scan the QR code from WhatsApp -> Settings -> Linked Devices.
Merge this snippet into `~/.nanobot/config.json`:
```json
{
"channels": {
"whatsapp": {
"enabled": true,
"groupPolicy": "mention"
}
}
}
```
Omitting `allowFrom` enables pairing-only mode for private chats. `groupPolicy`
defaults to `"open"` in the channel, but `"mention"` is safer for a first
deployment.
## Run nanobot gateway
```bash
nanobot channels status
nanobot gateway
```
## Test a message
Send the bot a private WhatsApp message. It should return a pairing code.
Approve it from a trusted local surface:
```bash
nanobot agent -m "/pairing approve ABCD-EFGH"
```
Send the message again after approval. The reply should use the same model and
workspace as your local CLI check.
## Security notes
- Treat the WhatsApp session database as account access.
- Prefer pairing-only mode for first setup. Add `allowFrom` only when you want a
static allowlist.
- Keep `groupPolicy` as `"mention"` before adding the bot to groups.
- Avoid `allowFrom: ["*"]` unless the bot is intentionally public or isolated.
## Troubleshooting
- If QR linking fails, rerun `nanobot channels login whatsapp`.
- If you are migrating from the old bridge, remove `bridgeUrl` and
`bridgeToken`, then re-login.
- If a sender appears as a LID instead of a phone number, let nanobot learn the
mapping at runtime or use `lidMappings` in the full reference.
- If a first private message returns a pairing code, approve it before testing
normal replies.
## Next: memory, automations, MCP tools
- [Chat Apps reference](../chat-apps.md)
- [Pairing](../configuration.md#pairing)
- [Secure local AI agent](./secure-local-ai-agent.md)
- [Deployment](../deployment.md)
+7 -14
View File
@@ -1,20 +1,11 @@
# Image Generation
nanobot can generate and edit images through the `generate_image` tool. Enable the tool in WebUI Settings, then ask for an image normally in chat; the agent decides when to call it and can keep iterating on generated images in the same conversation.
nanobot can generate and edit images through the `generate_image` tool. In the WebUI, users can enable **Image Generation** from the composer, choose an aspect ratio, and keep iterating on generated images inside the same chat.
The feature is disabled by default. Open **Settings → Image**, choose a configured provider and model, enable image generation, save, and restart when prompted. If that screen is not available in your installed version, use the manual config below.
The feature is disabled by default. Enable it in `~/.nanobot/config.json`, configure a supported image provider, then restart the gateway.
## Quick Setup
**WebUI**
1. Add the image provider credential under **Settings → Models** if it is not already configured.
2. Open **Settings → Image**.
3. Select the provider and image model, then enable image generation.
4. Save, restart when prompted, and ask for a simple test image.
**Manual config**
This snippet uses the current built-in image-generation default so the JSON has concrete names. It is not a provider recommendation; replace `provider` and `model` with any supported image provider and model you intend to use.
```json
@@ -41,9 +32,11 @@ See [Provider Notes](#provider-notes) for Custom, AIHubMix, MiniMax, Gemini, Oll
## WebUI Usage
1. Open Settings and enable **Image Generation** with a configured provider and model.
2. Describe the image or edit you want in chat.
3. Include an aspect ratio or size in the request when the configured defaults are not suitable.
In the WebUI composer:
1. Click **Image Generation**.
2. Choose an aspect ratio: `Auto`, `1:1`, `3:4`, `9:16`, `4:3`, or `16:9`.
3. Describe the image or the edit you want.
4. Attach reference images when editing an existing image.
Generated images are rendered as assistant media in the chat. Follow-up prompts such as "make it warmer", "change the background", or "try a 16:9 version" can reuse the most recent generated artifact.
+1 -32
View File
@@ -1,8 +1,4 @@
# AI Agent Memory in nanobot
This page explains how nanobot implements long-term AI agent memory: session
history, compressed archives, durable knowledge files, Dream consolidation, and
Git-backed memory changes.
# Memory in nanobot
nanobot's memory is built on a simple belief: memory should feel alive, but it should not feel chaotic.
@@ -68,9 +64,6 @@ This is why nanobot's memory is not just archival. It is interpretive.
workspace/
├── SOUL.md # The bot's long-term voice and communication style
├── USER.md # Stable knowledge about the user
├── prompts/
│ ├── README.md # Notes for memory guidance files
│ └── dream.md # Optional instructions for how Dream organizes memory
└── memory/
├── MEMORY.md # Project facts, decisions, and durable context
├── history.jsonl # Append-only history summaries
@@ -127,8 +120,6 @@ Memory is not hidden behind the curtain. Users can inspect and guide it.
| `/dream-log <sha>` | Show a specific Dream change |
| `/dream-restore` | List recent Dream memory versions |
| `/dream-restore <sha>` | Restore memory to the state before a specific change |
| `/dream-prompt` | Show how Dream is being guided for memory |
| `/dream-prompt init` | Create an editable Dream memory guide at `prompts/dream.md` |
These commands exist for a reason: automatic memory is powerful, but users should always retain the right to inspect, understand, and restore it.
@@ -144,28 +135,6 @@ This gives memory a history of its own:
That turns memory from a silent mutation into an auditable process.
## Guiding Dream
Dream decides what to keep, update, or forget using nanobot's built-in memory instructions. Most users can leave this alone.
If one workspace needs a different memory style, create an editable guide:
```text
/dream-prompt init
```
This creates:
```text
workspace/prompts/dream.md
```
Edit that file in plain Markdown. When it has content, Dream follows it for this workspace before reading the latest conversation history. You do not need to paste history into the file; Dream adds the current `## Conversation History` block automatically.
To return to nanobot's default behavior, delete `prompts/dream.md` or leave it empty.
Each workspace has its own guide. Changing this file does not affect other nanobot workspaces.
## Configuration
Dream is configured under `agents.defaults.dream`:
-7
View File
@@ -22,9 +22,6 @@ Edit `~/.nanobot-telegram/config.json`, `~/.nanobot-discord/config.json`, etc. w
**Run instances:**
```bash
# Check one instance before starting it
nanobot status --config ~/.nanobot-telegram/config.json
# Instance A - Telegram bot
nanobot gateway --config ~/.nanobot-telegram/config.json
@@ -45,9 +42,6 @@ To open a CLI session against one of these instances locally:
nanobot agent -c ~/.nanobot-telegram/config.json -m "Hello from Telegram instance"
nanobot agent -c ~/.nanobot-discord/config.json -m "Hello from Discord instance"
# Open the browser workbench for a specific instance
nanobot webui -c ~/.nanobot-telegram/config.json
# Optional one-off workspace override
nanobot agent -c ~/.nanobot-telegram/config.json -w /tmp/nanobot-telegram-test
```
@@ -100,7 +94,6 @@ The copied base config can keep using the same `modelPresets` and `agents.defaul
Start separate instances:
```bash
nanobot status --config ~/.nanobot-telegram/config.json
nanobot gateway --config ~/.nanobot-telegram/config.json
nanobot gateway --config ~/.nanobot-discord/config.json
```
+1 -1
View File
@@ -39,7 +39,7 @@ Without parameters, returns a key config overview:
my(action="check")
# → max_iterations: 40
# context_window_tokens: 200000
# model: 'anthropic/claude-sonnet-4-6'
# model: 'anthropic/claude-sonnet-4-20250514'
# workspace: PosixPath('/tmp/workspace')
# provider_retry_mode: 'standard'
# max_tool_result_chars: 16000
+2 -28
View File
@@ -1,9 +1,9 @@
# Nanobot OpenAI-Compatible API: Run a Local Agent Behind /v1/chat/completions
# OpenAI-Compatible API
nanobot can expose a minimal OpenAI-compatible endpoint for local integrations:
```bash
nanobot plugins enable api
python -m pip install "nanobot-ai[api]"
nanobot agent -m "Hello!"
nanobot serve
```
@@ -12,32 +12,6 @@ Run the CLI check first. If `nanobot agent -m "Hello!"` fails, fix provider or c
For setup help, see [`quick-start.md`](./quick-start.md), [`providers.md`](./providers.md), and [`troubleshooting.md`](./troubleshooting.md).
## Authentication
Local-only `127.0.0.1` usage does not require an API key. If you bind the API
server to all interfaces with `api.host: "0.0.0.0"` or `"::"`, nanobot requires
`api.apiKey`; otherwise startup fails to avoid exposing an unauthenticated agent
endpoint on the network.
```json
{
"api": {
"host": "0.0.0.0",
"port": 8900,
"apiKey": "${NANOBOT_API_KEY}"
}
}
```
When `api.apiKey` is set, send it as a Bearer token on API routes. The health
endpoint remains unauthenticated so local probes and load balancers can still
check process health.
```bash
curl http://127.0.0.1:8900/v1/models \
-H "Authorization: Bearer $NANOBOT_API_KEY"
```
## Behavior
- Session isolation: pass `"session_id"` in the request body to isolate conversations; omit for a shared default session (`api:default`)
+3 -15
View File
@@ -2,8 +2,6 @@
Use this page when the first reply fails because of provider/model mismatch, or when you want to adapt the concrete setup example to a different provider. If you already know which provider you want and only need a pasteable setup, use [`provider-cookbook.md`](./provider-cookbook.md).
For normal local setup, open **Settings → Models** in the WebUI to add provider credentials, create a model preset, and select the active model. Use the JSON below for manual deployments, local endpoints, provider-specific fields, or diagnosis.
For every setup, answer three questions:
1. Which provider owns the credential or endpoint?
@@ -63,12 +61,9 @@ These fields answer different questions:
| `model` | `modelPresets.<name>.model` | The model ID expected by that provider or gateway. |
| `apiKey` | `providers.<provider>.apiKey` | Credential for that provider. Use `${ENV_VAR}` for secrets. |
| `apiBase` | `providers.<provider>.apiBase` | HTTP base URL of the provider endpoint. |
| `proxy` | `providers.<provider>.proxy` | Optional HTTP proxy for this provider only. Supported for OpenAI-compatible providers and OpenAI Codex. |
You usually omit `apiBase` for hosted built-in providers such as OpenRouter, Anthropic direct, OpenAI direct, Groq, or Bedrock because nanobot knows their default endpoints. Set `apiBase` for `custom`, local OpenAI-compatible servers, provider proxies, regional endpoints, or subscription endpoints. Include the API version path when the endpoint requires it, for example `https://api.example.com/v1` or `http://localhost:11434/v1`.
Use `proxy` when one provider must send HTTP traffic through a proxy without changing process-wide `HTTP_PROXY` / `HTTPS_PROXY`. This is supported for providers that use nanobot's OpenAI-compatible client, including `openai`, `custom`, named custom providers, OpenRouter-style gateways, local OpenAI-compatible servers, and similar registry entries. It is also supported for `openai_codex`, including Codex OAuth token exchange/refresh and Codex Responses API requests. Native provider backends such as `anthropic`, `bedrock`, `azure_openai`, and `github_copilot` reject `proxy`; use their endpoint-specific configuration instead.
## Common Provider Patterns
### OpenRouter Gateway
@@ -420,19 +415,12 @@ See [`configuration.md#providers`](./configuration.md#providers) for Bedrock-spe
Some providers do not use API keys in `config.json`.
For OpenAI Codex:
```bash
nanobot provider login openai-codex --set-main
nanobot provider login openai-codex
nanobot provider login github-copilot
```
For GitHub Copilot:
```bash
nanobot provider login github-copilot --set-main
```
Each command authenticates the selected provider and makes its current default model active. OAuth providers are not valid automatic fallbacks. See [`troubleshooting.md`](./troubleshooting.md#provider-and-model-problems) for proxy, headless-login, model-name, and config-key errors.
Then explicitly select the provider and model in a preset. OAuth providers are not valid automatic fallbacks.
## Provider Resolution
+2 -8
View File
@@ -1,4 +1,4 @@
# Nanobot Python SDK: Run an AI Agent from Python
# Python SDK
Use nanobot as a Python library. The SDK gives you the same agent runtime used
by the CLI, but from code: model routing, tools, workspace access, conversation
@@ -599,8 +599,7 @@ async with Nanobot.from_config() as bot:
| `await ingest(session_key, messages, metadata=None, source=None, save=True)` | Import existing transcript messages without running the model. |
| `get(session_key)` | Return a `SessionSnapshot`, or `None` if missing. |
| `list()` | Return compact `SessionInfo` rows. |
| `export(session_key)` | Return a trusted full `SessionSnapshot`, including model-only runtime context, suitable for JSON serialization. |
| `await restore(snapshot, session_key=None, save=True)` | Restore a trusted exported snapshot into an empty session; the returned snapshot is display-safe. |
| `export(session_key)` | Return a full `SessionSnapshot` suitable for JSON serialization. |
| `clear(session_key)` | Clear and persist one session. |
| `delete(session_key)` | Delete one session from disk and cache. |
| `flush()` | Flush cached sessions to durable storage. |
@@ -609,11 +608,6 @@ Ingested messages must include `role` and `content`. Roles may be `user`,
`assistant`, `tool`, or `system`. Other fields, such as `timestamp`,
`source_session_id`, or `source_date`, are persisted as message metadata.
`get()` and snapshots returned by ordinary SDK operations are display-safe and omit
model-only runtime context. `export()` is an explicit backup boundary and includes
that internal context so `restore()` can preserve the exact model-visible history.
Do not expose exported snapshots directly to chat users.
### `bot.memory`
| Method | Description |
+251 -153
View File
@@ -1,197 +1,153 @@
# Install and Quick Start
This guide has one goal: get a normal nanobot reply in your browser. Do not add chat apps, MCP servers, fallback models, or deployment until this path works.
This page gets one local nanobot reply working. After that, you can add the WebUI, chat apps, local models, web search, MCP, deployment, or custom plugins.
If terminals, Python, or API keys are unfamiliar, use the [beginner walkthrough](./start-without-technical-background.md), which explains each term and screen.
If you have never used a terminal or edited a config file before, use [`start-without-technical-background.md`](./start-without-technical-background.md) first. This page assumes you are comfortable pasting commands and editing JSON snippets.
These repository docs follow current `main`. The recommended installer uses the stable package, so a newly documented WebUI screen may not appear until the next release. Each advanced guide also provides a CLI or manual config path.
## Before You Start
## What You Need
You need:
- Python 3.11 or newer.
- Access to one supported AI provider, company endpoint, or local model server.
- The credential, endpoint URL, and model ID required by that service. Local providers such as Ollama may not require a key.
- One LLM provider, company endpoint, subscription endpoint, or local model server you can call. The examples below use a generic OpenAI-compatible `custom` provider so the compact path does not recommend one hosted service; any supported provider works when the key, provider name, and model ID match.
- Git only if you install from source.
- Node.js or Bun only if you are developing the WebUI itself.
Git is only needed for a source install. The published package already contains the WebUI. A current-source install needs `bun` or `npm` so its WebUI bundle can be built.
> [!IMPORTANT]
> Repository docs may describe features that are available first in source. Install from PyPI or `uv` for the stable day-to-day release; install from source when you want the newest repository behavior or plan to contribute.
## 1. Install nanobot
## 1. Install
The recommended installer keeps nanobot out of the system Python environment and opens the setup wizard when installation finishes.
Pick one install method.
**macOS / Linux**
**One-command setup:**
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh
```
**Windows PowerShell**
On Windows PowerShell:
```powershell
irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | iex
```
The installer chooses an active virtual environment, `uv`, `pipx`, or a managed environment under `~/.nanobot/venv`. It installs the stable PyPI release unless you explicitly pass `--dev`. At the end it prints the exact command it used to run nanobot; if `nanobot` is not on `PATH`, reuse that full command in the examples below.
The default command installs or upgrades `nanobot-ai` from PyPI, then starts `nanobot onboard --wizard`. It avoids system-wide pip installs by using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`. If Quick Start finishes and you enabled the WebSocket channel, go straight to [Open the WebUI](#5-open-the-webui).
If you prefer to inspect the scripts first, open [`install.sh`](../scripts/install.sh) or [`install.ps1`](../scripts/install.ps1).
## 2. Complete Quick Start
The installer opens `nanobot onboard --wizard`. Choose **Quick Start** and follow the prompts:
1. Choose the provider or endpoint that owns your credential.
2. Enter its API key or base URL when requested.
3. Enter a model ID that the same provider can run.
4. Let Quick Start enable the local WebUI.
5. Set a WebUI password and review the summary.
Quick Start creates or updates:
| Path | Purpose |
|---|---|
| `~/.nanobot/config.json` | Provider, model, WebUI, channel, tool, and runtime settings |
| `~/.nanobot/workspace/` | Sessions, memory, skills, automations, and generated files |
If the installer did not open the wizard, run it yourself:
To preview the plan without changing your environment, pass `--dry-run`; combine it with `--dev` when you want to preview the main-branch install.
```bash
nanobot onboard --wizard
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dry-run
```
Current source versions also provide `nanobot webui`. When run without a usable model, that launcher offers the same Quick Start flow before starting the browser.
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dry-run
```
## 3. Check the Setup
To install the current `main` branch instead, pass `--dev`:
```bash
nanobot status
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dev
```
You want:
- a check mark for **Config** and **Workspace**;
- the model or preset you selected;
- a configured state for the provider used by that model.
Most other providers can say `not set`. This command validates local setup but does not call the model.
## 4. Get the First Reply
```bash
nanobot gateway
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dev
```
Quick Start has already prepared the local WebSocket channel. Leave the gateway terminal open and visit `http://127.0.0.1:8765`; the first-run WebUI is bound to localhost, so other devices on your network cannot reach it. On current source versions, you can run `nanobot webui` instead to perform the local WebUI checks, start the gateway, and open the browser automatically.
If `curl` or `irm` is unavailable, or GitHub raw downloads are blocked on your network, use one of the manual install methods below.
Send:
If you prefer to inspect the script first, open [`../scripts/install.sh`](../scripts/install.sh) or [`../scripts/install.ps1`](../scripts/install.ps1).
```text
Hello!
```
Any normal assistant answer is success. It proves that nanobot can load the config, reach the selected model, use the workspace, and serve the browser UI.
Leave the terminal open while using the WebUI. If you prefer a managed background process, stop the foreground process with `Ctrl+C`, then run:
```bash
nanobot gateway --background
nanobot gateway status
```
Use `nanobot gateway logs`, `restart`, and `stop` to manage that background gateway.
## Terminal-Only Check
If you do not want the browser or need to isolate a WebUI problem, send one message directly:
```bash
nanobot agent -m "Hello!"
```
Then start an interactive terminal chat with:
```bash
nanobot agent
```
In interactive mode, `Enter` sends and `Alt+Enter` inserts a newline. Exit with `exit`, `/exit`, `:q`, or `Ctrl+D`.
## Choose One Next Step
After the first reply works, add one capability and test again:
| Goal | Recommended path |
|---|---|
| Learn sessions, workspaces, tools, and access modes | [WebUI guide](./webui.md) |
| Connect a chat platform | Open **Settings → Channels**, then use [Chat Apps](./chat-apps.md) for platform prerequisites |
| Change or add a model | Open **Settings → Models**; use the [Provider Cookbook](./provider-cookbook.md) for a recipe |
| Add web search, voice, or image generation | Use the matching WebUI Settings page, then consult [Configuration](./configuration.md) for advanced fields |
| Add an App or MCP integration | Open **Apps** or follow [Configure MCP Tools](./guides/configure-mcp-tools.md) |
| Schedule agent work | Read [Automations](./automations.md) |
| Run continuously or remotely | Read [Deployment](./deployment.md) |
| Integrate from code | Use the [Python SDK](./python-sdk.md) or [OpenAI-Compatible API](./openai-api.md) |
## Other Install Methods
Use one method, then continue at [Complete Quick Start](#2-complete-quick-start).
**uv**
**Stable release with `uv`:**
```bash
uv tool install nanobot-ai
nanobot onboard --wizard
nanobot --version
```
**pip in a virtual environment**
**Stable release with pip:**
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot --version
```
If pip reports `externally-managed-environment`, use the recommended installer, `uv tool install nanobot-ai`, `pipx install nanobot-ai`, or create a virtual environment. Do not force a system-wide install.
Use pip only inside an environment you control. If pip reports `externally-managed-environment` on macOS or Linux, use the one-command installer, `uv tool install nanobot-ai`, `pipx install nanobot-ai`, or create a virtual environment first.
**Current source**
`bun` or `npm` must be available. Activate a virtual environment first, then run:
**Latest source checkout:**
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install .
python -m pip install -e .
nanobot --version
```
If your shell cannot find `nanobot` after a pip install, run the module form:
```bash
python -m nanobot --version
python -m nanobot onboard
```
On Windows, `~` in the docs means your user profile directory, for example `C:\Users\you`.
The docs use `python` in commands. If your system exposes Python 3.11+ as `python3` or `py`, use that command in the same place, for example `python3 -m pip install nanobot-ai` or `py -m nanobot --version`.
## 2. Initialize
Skip this section if the one-command setup already started the wizard and Quick Start finished there.
```bash
nanobot onboard
```
Use the wizard if you prefer prompts instead of editing JSON by hand:
```bash
nanobot onboard --wizard
```
On Windows, if `python -m pip install .` reports that it cannot launch `npm`, run `cd webui`, `npm.cmd install --package-lock=false`, `npm.cmd run build`, and `cd ..` in order, then retry the install.
Initialization creates:
The source path follows current `main` and can be newer than the published package. A non-editable install triggers the build hook that bundles the current WebUI. For editable Python or frontend development, follow [`../CONTRIBUTING.md`](../CONTRIBUTING.md) and [`../webui/README.md`](../webui/README.md).
| Path | What it is |
|------|------------|
| `~/.nanobot/config.json` | Main settings file for providers, models, channels, tools, gateway, and API |
| `~/.nanobot/workspace/` | Agent workspace for memory, sessions, heartbeat tasks, skills, and artifacts |
If the package is installed but the shell cannot find `nanobot`, use the runner that owns the installation. The recommended installer prints the exact command to reuse. Common forms are:
If you already have a config, `nanobot onboard` can refresh missing default fields without overwriting your existing values.
```bash
uv tool run --from nanobot-ai nanobot --version
pipx run --spec nanobot-ai nanobot --version
~/.nanobot/venv/bin/python -m nanobot --version
```
## 3. Configure a Provider
On Windows, the managed-environment form is `& "$HOME\.nanobot\venv\Scripts\python.exe" -m nanobot --version`. Replace `--version` with `onboard --wizard`, `gateway`, or any other arguments you need. Use plain `python -m nanobot` only when that Python executable belongs to the environment where nanobot was installed.
Skip this section if you already configured provider and model settings in the wizard.
## Manual Configuration Fallback
Open `~/.nanobot/config.json`. Add or merge these blocks into the file created by `nanobot onboard`; do not replace the whole file unless you want to reset the config.
Use this only when the wizard is unavailable or you intentionally manage JSON. First run `nanobot onboard`, then merge a provider and a named model preset into `~/.nanobot/config.json`.
A generic OpenAI-compatible setup has this shape:
**API key:**
```json
{
"providers": {
"custom": {
"apiKey": "${PROVIDER_API_KEY}",
"apiKey": "your-api-key",
"apiBase": "https://api.example.com/v1"
}
},
}
}
```
**Model preset:**
```json
{
"modelPresets": {
"primary": {
"label": "Primary",
"provider": "custom",
"model": "model-id-from-your-provider"
"model": "model-id-from-your-provider",
"maxTokens": 8192,
"contextWindowTokens": 65536,
"temperature": 0.1
}
},
"agents": {
@@ -202,48 +158,190 @@ A generic OpenAI-compatible setup has this shape:
}
```
Replace the provider, endpoint, and model together. Do not pair a credential from one service with a model ID from another. See [Provider Cookbook](./provider-cookbook.md) for hosted, OAuth, company, and local examples, and [Configuration](./configuration.md) for exact fields.
The provider and model inside a preset must match. The snippet above is only an example. For another provider, replace these values together:
## Updating
| Replace | Where |
|---|---|
| Provider config key, such as `custom` | `providers.<provider>` |
| API key or environment variable | `providers.<provider>.apiKey` |
| Preset provider name | `modelPresets.primary.provider` |
| Model ID | `modelPresets.primary.model` |
| Endpoint URL, only when needed | `providers.<provider>.apiBase` |
Upgrade with the same method you used to install:
Direct `agents.defaults.provider` and `agents.defaults.model` still work for existing configs, but named presets are the recommended path because they also power `/model` switching and fallback chains. For provider-specific examples across direct, gateway, OAuth, cloud, and local setups, see [`providers.md`](./providers.md).
```bash
# Recommended installer
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh
**What about `apiBase` / base URL?**
# Or one of these
uv tool upgrade nanobot-ai
pipx upgrade nanobot-ai
python -m pip install -U nanobot-ai
`apiBase` is the HTTP base URL of the provider endpoint, not the model name. Most hosted providers in nanobot already know their default endpoint, so you usually only set `apiKey` and a model preset. Set `apiBase` when you are using:
- `custom` for a third-party or self-hosted OpenAI-compatible API;
- a local OpenAI-compatible server such as Ollama, vLLM, or LM Studio;
- a provider-specific alternate endpoint, regional endpoint, proxy, or subscription endpoint.
Examples:
```json
{
"providers": {
"custom": {
"apiKey": "${CUSTOM_API_KEY}",
"apiBase": "https://api.example.com/v1"
}
}
}
```
For a source checkout:
```bash
git pull
python -m pip install .
```json
{
"providers": {
"ollama": {
"apiBase": "http://localhost:11434/v1"
}
}
}
```
Then check `nanobot --version`. Run `nanobot onboard --refresh` when you want to add newly introduced default fields while preserving existing settings.
If the provider's docs say the endpoint is `/v1`, include `/v1` in `apiBase`. The model ID still belongs in the active `modelPresets` entry.
## If the First Reply Fails
If you prefer not to store secrets in `config.json`, reference an environment variable and set it before starting nanobot:
Do not change several settings at once. Start with:
```json
{
"providers": {
"custom": {
"apiKey": "${PROVIDER_API_KEY}",
"apiBase": "https://api.example.com/v1"
}
}
}
```
## 4. Check the Setup
```bash
nanobot --version
nanobot status
```
This should show the config path, workspace path, active model or preset, and provider summary. It does not send a message to the model, so use it as a quick config check before the first real request.
Read it like this:
| Status line | What you want |
|---|---|
| `Config` | A check mark. |
| `Workspace` | A check mark. |
| `Model` | The model or preset you expect. |
| Provider list | Most providers can say `not set`; the provider used by the active preset should show a check mark, OAuth status, or local URL. |
## 5. Open the WebUI
If Quick Start enabled the WebSocket channel, start the gateway:
```bash
nanobot gateway
```
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password you set in the wizard, then send your first message there.
## 6. Test One CLI Message
Use this path if you skipped Quick Start, declined the WebSocket channel, or want a terminal-only check.
Run a one-shot CLI message:
```bash
nanobot agent -m "Hello!"
```
| Symptom | First check |
|---|---|
| `nanobot: command not found` | Reuse the installer command or method-specific runner described under [Other Install Methods](#other-install-methods) |
| JSON parse error | Check commas and braces; remember that docs examples are usually snippets |
| `401` or invalid API key | Verify the selected provider owns that key and remove accidental spaces |
| Model not found | Use a model ID available from the provider selected in the active preset |
| CLI works but WebUI does not open | Use port `8765`, not gateway health port `18790` |
| WebUI works but a chat app does not | Check **Settings → Channels**, then run `nanobot channels status` |
A successful first run proves that:
Continue with the ordered [Troubleshooting guide](./troubleshooting.md) if the cause is still unclear.
- the `nanobot` command is installed;
- `~/.nanobot/config.json` can be loaded;
- the selected provider and model can answer;
- the default workspace can be created and used.
The reply text itself will vary. Any normal assistant answer means the install, config, provider, model, and workspace path are all usable.
If that works, start an interactive CLI chat:
```bash
nanobot agent
```
After the interactive session can answer normally, nanobot can help with its own next setup step. Ask it to read the relevant docs, inspect your current `~/.nanobot/config.json`, and make one concrete change such as enabling WebUI, adding a provider preset, or configuring one chat channel. When nanobot says the config is updated, run `/restart` in the chat or restart the nanobot process manually so long-running processes reload `config.json`.
Example prompt:
```text
Read docs/quick-start.md, docs/providers.md, and docs/configuration.md in this checkout.
Then update ~/.nanobot/config.json to add a model preset named "primary" for my provider.
Tell me exactly what changed and whether I need to run /restart.
```
Exit interactive mode with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
## 7. Choose Your Next Step
| Want to... | Go to |
|---|---|
| Understand config, workspace, gateway, channels, memory, and tools | [`concepts.md`](./concepts.md) |
| Copy another provider or local model setup | [`provider-cookbook.md`](./provider-cookbook.md) |
| Understand provider/model matching | [`providers.md`](./providers.md) |
| Open the bundled browser UI | [`webui.md`](./webui.md) |
| Connect Telegram, Discord, WeChat, Slack, Email, or another chat app | [`chat-apps.md`](./chat-apps.md) |
| Configure web search, MCP, security, memory, gateway, or runtime settings | [`configuration.md`](./configuration.md) |
| Run with Docker, systemd, or LaunchAgent | [`deployment.md`](./deployment.md) |
| Debug a failure | [`troubleshooting.md`](./troubleshooting.md) |
## Updating
**pip:**
```bash
python -m pip install -U nanobot-ai
nanobot --version
```
If pip reports `externally-managed-environment`, upgrade with the same isolated method you used to install nanobot, such as `uv tool upgrade nanobot-ai`, `pipx upgrade nanobot-ai`, or the managed venv created by the one-command installer.
**uv:**
```bash
uv tool upgrade nanobot-ai
nanobot --version
```
**pipx:**
```bash
pipx upgrade nanobot-ai
nanobot --version
```
**Source checkout:**
```bash
git pull
python -m pip install -e .
nanobot --version
```
If you use WhatsApp from a source checkout, keep the optional dependencies installed:
```bash
python -m pip install -e ".[whatsapp]"
```
## First-Run Troubleshooting
| Symptom | What to check |
|---------|---------------|
| `nanobot: command not found` | Use `python -m nanobot ...`, or add your Python scripts directory to `PATH`. |
| `ModuleNotFoundError: nanobot` | Confirm you installed into the same Python environment that is running the command. |
| JSON parse errors | Check commas and braces in `~/.nanobot/config.json`; examples above are partial snippets to merge. |
| Authentication or 401 errors | Check that the API key is valid, copied without spaces, and placed under the provider you selected. |
| Provider/model errors | Make sure the active preset uses the provider that owns your API key and that the model exists there. |
| The CLI works but a chat app does not reply | First keep `nanobot gateway` running, then follow [`chat-apps.md`](./chat-apps.md). |
| WebUI does not open | Enable the WebSocket channel and open port `8765`, not the gateway health port `18790`. |
For a fuller diagnosis flow, see [`troubleshooting.md`](./troubleshooting.md).
-164
View File
@@ -1,164 +0,0 @@
# Release Archive
This page keeps release and daily update history outside the README so the project homepage can stay focused on what nanobot is, what it can do, and how to start.
For tagged releases, see [GitHub Releases](https://github.com/HKUDS/nanobot/releases).
## Highlights
- **2026-07-12** 🎯 Explicit `/goal` activation, safer runtime and workspace access.
- **2026-07-11** 🛠️ Syntax-highlighted previews and diffs, queued prompts, safer edits.
- **2026-07-10** 🧠 Stable model routing, multiline CLI input, new automation guide.
- **2026-07-09** 📝 Live file-edit diffs, safer localhost setup, Matrix image fixes.
- **2026-07-08** 🔐 Safer WebUI/API setup, onboard refresh, responsive prompt rail.
- **2026-07-07** ⌨️ CLI multiline input, steadier slash commands, safer web fetching.
- **2026-07-06** 💬 Mattermost channel, Serper search, safer Windows shells.
- **2026-07-04** 🔌 MCP reconnects, safer Copilot refresh, Windows shutdown fixes.
- **2026-07-03** 🧙 Guided WebUI setup, plugin controls, Claude Sonnet 4.6 default.
- **2026-07-02** ⏰ Local triggers with recovery, audit history, WebUI pending status.
- **2026-07-01** 🛡️ API keys for remote binds, `$skill` shortcuts, clearer tool errors.
- **2026-06-30** 🌐 Provider proxies, Copilot Enterprise, steadier WhatsApp and Weixin.
- **2026-06-29** 🧠 Context replay scaled to model windows, without fixed message caps.
- **2026-06-28** 🖼️ MCP images, steadier WebUI reconnects, safer tool calls.
- **2026-06-27** 🔒 Collision-safe sessions, safer shells, Neonize WhatsApp.
- **2026-06-25** 🎛️ Thinking controls, MiMo voice input, opt-in Telegram rich messages.
- **2026-06-24** 🌙 Kimi Coding and OpenCode, steadier reasoning and Anthropic tool calls.
- **2026-06-22** 🚀 Released **v0.2.2****The Durability Release** makes nanobot sturdier for daily agent work: segmented WebUI transcripts, first-class Python SDK runtime controls, automation management, richer search/STT providers, and stronger gateway/session/provider reliability. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.2.2) for details.
- **2026-06-21** 🧰 Python SDK runtime controls, optional Keenable key, cleaner run hooks.
- **2026-06-20** 💬 Telegram rich messages, safer SDK concurrency, smoother Quick Start.
- **2026-06-19** 🔎 Firecrawl app, OpenAI image edits, safer session deletion.
- **2026-06-18** 💬 Feishu recovery, Keenable search, Mistral polish, workspace-aware git.
- **2026-06-17** 🧠 Default idle auto-compact, clearer `/dream`, macOS installer fixes.
- **2026-06-16** 🎯 Fresher goal context, Kimi K2.7 thinking, cleaner API retries.
- **2026-06-15** 📱 Mobile WebUI polish, optional file tools, real API usage.
- **2026-06-14** 🖼️ Themed cover, partner links, stronger Codex image streaming.
- **2026-06-13** 🗓️ Session-bound automations, sturdier WhatsApp, faster WebUI startup.
- **2026-06-12** 💬 Slack allowlisted channels can require mentions.
- **2026-06-11** ✂️ Fenced-code message splitting.
- **2026-06-10** 📜 Segmented transcripts, Exa/Bocha search, StepFun/SiliconFlow ASR.
- **2026-06-09** 🎙️ Shared voice input, more STT providers, TeX and email polish.
- **2026-06-08** 🧮 Token heatmap fix, safer MCP HTTP probing, docs cleanup.
- **2026-06-06** 🧰 SDK MCP cleanup, removable OpenAI image defaults.
- **2026-06-05** 🖼️ Azure AAD, custom image providers, `/skill`, steadier pairing.
- **2026-06-04** 🔌 MCP reconnects, `uv pip` install fallback, QQ pairing.
- **2026-06-03** 🧠 Hidden-history recovery, quieter email progress handling.
- **2026-06-02** 📬 Email attachments, Napcat QQ, Volcengine search, simpler Dream.
- **2026-06-01** 🚀 Released **v0.2.1****The Workbench Release** turns the packaged WebUI into a daily agent workbench: clearer Thought/response timelines, live file-edit activity, project workspaces, model and context controls, steadier sustained goals, CLI Apps + MCP extensions, and broader provider/channel support. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.2.1) for details.
- **2026-05-30** 🔐 Safer Matrix verification, bounded media downloads, clearer WebUI model timeline.
- **2026-05-29** 🧩 Extension registry, context-window tuning, document extraction controls.
- **2026-05-28** 🗂️ Project workspaces, access controls, steadier goals and streaming.
- **2026-05-27** ⏱️ Codex streams respect idle timeouts during long runs.
- **2026-05-26** 📡 Telegram webhooks, refreshed Kagi search, cleaner transport errors.
- **2026-05-25** 🔌 Unified CLI Apps and MCP, Step Plan support, steadier sustained goals.
- **2026-05-24** 🧰 MCP presets, richer slash actions, configurable OpenAI-compatible requests.
- **2026-05-23** 🖼️ Zhipu image generation, longer exec windows, cleaner transcription config.
- **2026-05-22** 🛠️ CLI Apps, more image providers, safer web redirects and edits.
- **2026-05-21** ⚡ Novita provider, faster sidebar, smoother coding tools and Weixin replies.
- **2026-05-20** 📶 Signal channel, faster gateway startup, multilingual README links.
- **2026-05-19** 🎨 Image provider registry, StepFun and Skywork, stronger WebUI controls.
- **2026-05-18** 🖌️ Gemini and MiniMax images, Ant Ling, live file-edit activity.
- **2026-05-17** 🌊 Smoother WebUI streaming, AutoCompact fixes, buffered CLI reasoning.
- **2026-05-16** 🧠 Atomic Chat provider, goal-aware timeouts, safer exec URL handling.
- **2026-05-15** 🚀 Released **v0.2.0****`/goal`** holds sustained objectives across turns, WebUI now ships inside the wheel, image generation end to end, 5 new providers with `fallback_models`, and a real agent-loop refactor. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.2.0) for details.
- **2026-05-14** 🎯 **`/goal`** for long-term objectives, visible multi-step progress, long-horizon missions in chat.
- **2026-05-13** 🧠 Streaming reasoning before answers, automatic backup models, smoother plug-in reconnects.
- **2026-05-12** 🎛️ Saved model presets with WebUI badge, simpler plug-in tools, quieter Feishu topic threads.
- **2026-05-11** 🖥️ NVIDIA NIM support, terminal bot name and icon, streamed reasoning and MiMo toggle clarity.
- **2026-05-09** 🖼️ Sharper image replay, BYO web-search keys in Settings, Feishu threads routed cleanly.
- **2026-05-08** ✨ Inline chat image, redesigned Settings and keys, Dream memory aligned with visible history.
- **2026-05-07** 📜 Locale-aware slash palette in WebUI, LAN login, faithful HTTP streaming responses.
- **2026-05-06** 🧩 Tunable tool hint, steadier voice and plug-in startups, schedules and reminders that stick.
- **2026-05-05** 🛡️ Quiet deny for unknown Telegram chats, Dream cleanup, fuller automation summaries.
- **2026-05-04** 🔐 Safer DingTalk outbound media links, durable cron persistence, DeepSeek polish.
- **2026-05-03** ⚙️ Predictable shell allow-list behavior, isolated chats mid-reply, cleaner interactive retries.
- **2026-05-02** 🐈 LongCat support, smarter token sizing hints, clearer bundled upgrade guidance.
- **2026-05-01** ☁️ Native AWS Bedrock provider, tighter helper handoffs and scoped session files.
- **2026-04-30** 💬 Feishu threads that honor replies and topics, WhatsApp bridge refresh on source edits.
- **2026-04-29** 🚀 Released **v0.1.5.post3** — Smarter threads on Feishu, Discord, Slack, and Teams; **DeepSeek-V4**; Hugging Face & Olostep; choices, `/history`, and steadier long chats. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5.post3) for details.
- **2026-04-28** 🌐 Olostep web search, Hugging Face provider, safer workspace-tool interruptions.
- **2026-04-27** 💬 `/history` command, smarter session replay caps, smoother Discord / Slack threads.
- **2026-04-26** 🧭 Natural cron reminders, thread-aware restarts, safer local provider and shell behavior.
- **2026-04-25** 🧩 `ask_user` choices, macOS LaunchAgent deployment, MSTeams stale-reference cleanup.
- **2026-04-24** 🎥 Video attachments for channels, DeepSeek thinking control, faster document startup.
- **2026-04-23** 🧵 Discord thread sessions, Telegram inline buttons, structured tool progress updates.
- **2026-04-22** 🔎 GitHub Copilot GPT-5 / o-series support, configurable web fetch, WebUI image uploads.
- **2026-04-21** 🚀 Released **v0.1.5.post2** — Windows & Python 3.14 support, Office document reading, SSE streaming for the OpenAI-compatible API, and stronger reliability across sessions, memory, and channels. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5.post2) for details.
- **2026-04-20** 🎨 Kimi K2.6 support, Telegram long-message split, WebUI typography & dark-mode polish.
- **2026-04-19** 🌐 WebUI i18n locale switcher, atomic session writes with auto-repair.
- **2026-04-18** 🧪 Initial WebUI chat, smarter setup wizard menus, WebSocket multi-chat multiplexing.
- **2026-04-17** 🪟 Windows & Python 3.14 CI, Dream line-age memory, email self-loop guard.
- **2026-04-16** 📡 SSE streaming for OpenAI-compatible API, Discord channel allow-list.
- **2026-04-15** 🎛️ LM Studio & nullable API keys, MiniMax thinking endpoint, runtime SelfTool.
- **2026-04-14** 🚀 Released **v0.1.5.post1** — Dream skill discovery, mid-turn follow-up injection, WebSocket channel, and deeper channel integrations. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5.post1) for details.
- **2026-04-13** 🛡️ Agent turn hardened — user messages persisted early, auto-compact skips active tasks.
- **2026-04-12** 🔒 Lark global domain support, Dream learns discovered skills, shell sandbox tightened.
- **2026-04-11** ⚡ Context compact shrinks sessions on the fly; Kagi web search; QQ & WeCom full media.
- **2026-04-10** 📓 Multiple MCP servers, Feishu streaming & done-emoji.
- **2026-04-09** 🔌 WebSocket channel, unified cross-channel session, `disabled_skills` config.
- **2026-04-08** 📤 API file uploads, OpenAI reasoning auto-routing with Responses fallback.
- **2026-04-07** 🧠 Anthropic adaptive thinking, MCP resources & prompts exposed as tools.
- **2026-04-06** 🛰️ Langfuse observability, unified Whisper transcription, email attachments.
- **2026-04-05** 🚀 Released **v0.1.5** — sturdier long-running tasks, Dream two-stage memory, production-ready sandboxing and programming Agent SDK. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.5) for details.
- **2026-04-04** 🚀 Jinja2 response templates, Dream memory hardened, smarter retry handling.
- **2026-04-03** 🧠 Xiaomi MiMo provider, chain-of-thought reasoning visible, Telegram UX polish.
- **2026-04-02** 🧱 Long-running tasks run more reliably — core runtime hardening.
- **2026-04-01** 🔑 GitHub Copilot auth restored; stricter workspace paths; OpenRouter Claude caching fix.
- **2026-03-31** 🛰️ WeChat multimodal alignment, Discord/Matrix polish, Python SDK facade, MCP and tool fixes.
- **2026-03-30** 🧩 OpenAI-compatible API tightened; composable agent lifecycle hooks.
- **2026-03-29** 💬 WeChat voice, typing, QR/media resilience; fixed-session OpenAI-compatible API.
- **2026-03-28** 📚 Provider docs refresh; skill template wording fix.
- **2026-03-27** 🚀 Released **v0.1.4.post6** — architecture decoupling, litellm removal, end-to-end streaming, WeChat channel, and a security fix. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post6) for details.
- **2026-03-26** 🏗️ Agent runner extracted and lifecycle hooks unified; stream delta coalescing at boundaries.
- **2026-03-25** 🌏 StepFun provider, configurable timezone, Gemini thought signatures.
- **2026-03-24** 🔧 WeChat compatibility, Feishu CardKit streaming, test suite restructured.
- **2026-03-23** 🔧 Command routing refactored for plugins, WhatsApp/WeChat media, unified channel login CLI.
- **2026-03-22** ⚡ End-to-end streaming, WeChat channel, Anthropic cache optimization, `/status` command.
- **2026-03-21** 🔒 Replace `litellm` with native `openai` + `anthropic` SDKs. Please see [commit](https://github.com/HKUDS/nanobot/commit/3dfdab7).
- **2026-03-20** 🧙 Interactive setup wizard — pick your provider, model autocomplete, and you're good to go.
- **2026-03-19** 💬 Telegram gets more resilient under load; Feishu now renders code blocks properly.
- **2026-03-18** 📷 Telegram can now send media via URL. Cron schedules show human-readable details.
- **2026-03-17** ✨ Feishu formatting glow-up, Slack reacts when done, custom endpoints support extra headers, and image handling is more reliable.
- **2026-03-16** 🚀 Released **v0.1.4.post5** — a refinement-focused release with stronger reliability and channel support, and a more dependable day-to-day experience. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post5) for details.
- **2026-03-15** 🧩 DingTalk rich media, smarter built-in skills, and cleaner model compatibility.
- **2026-03-14** 💬 Channel plugins, Feishu replies, and steadier MCP, QQ, and media handling.
- **2026-03-13** 🌐 Multi-provider web search, LangSmith, and broader reliability improvements.
- **2026-03-12** 🚀 VolcEngine support, Telegram reply context, `/restart`, and sturdier memory.
- **2026-03-11** 🔌 WeCom, Ollama, cleaner discovery, and safer tool behavior.
- **2026-03-10** 🧠 Token-based memory, shared retries, and cleaner gateway and Telegram behavior.
- **2026-03-09** 💬 Slack thread polish and better Feishu audio compatibility.
- **2026-03-08** 🚀 Released **v0.1.4.post4** — a reliability-packed release with safer defaults, better multi-instance support, sturdier MCP, and major channel and provider improvements. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post4) for details.
- **2026-03-07** 🚀 Azure OpenAI provider, WhatsApp media, QQ group chats, and more Telegram/Feishu polish.
- **2026-03-06** 🪄 Lighter providers, smarter media handling, and sturdier memory and CLI compatibility.
- **2026-03-05** ⚡️ Telegram draft streaming, MCP SSE support, and broader channel reliability fixes.
- **2026-03-04** 🛠️ Dependency cleanup, safer file reads, and another round of test and Cron fixes.
- **2026-03-03** 🧠 Cleaner user-message merging, safer multimodal saves, and stronger Cron guards.
- **2026-03-02** 🛡️ Safer default access control, sturdier Cron reloads, and cleaner Matrix media handling.
- **2026-03-01** 🌐 Web proxy support, smarter Cron reminders, and Feishu rich-text parsing improvements.
- **2026-02-28** 🚀 Released **v0.1.4.post3** — cleaner context, hardened session history, and smarter agent. Please see [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post3) for details.
- **2026-02-27** 🧠 Experimental thinking mode support, DingTalk media messages, Feishu and QQ channel fixes.
- **2026-02-26** 🛡️ Session poisoning fix, WhatsApp dedup, Windows path guard, Mistral compatibility.
- **2026-02-25** 🧹 New Matrix channel, cleaner session context, auto workspace template sync.
- **2026-02-24** 🚀 Released **v0.1.4.post2** — a reliability-focused release with a redesigned heartbeat, prompt cache optimization, and hardened provider & channel stability. See [release notes](https://github.com/HKUDS/nanobot/releases/tag/v0.1.4.post2) for details.
- **2026-02-23** 🔧 Virtual tool-call heartbeat, prompt cache optimization, Slack mrkdwn fixes.
- **2026-02-22** 🛡️ Slack thread isolation, Discord typing fix, agent reliability improvements.
- **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.
- **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.
- **2026-02-14** 🔌 nanobot now supports MCP! See [MCP section](./configuration.md#mcp-model-context-protocol) for details.
- **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](./configuration.md#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!
+340 -100
View File
@@ -1,62 +1,76 @@
# Start Without Technical Background
This walkthrough is for people who have not used a terminal, API key, or JSON config file before. The goal is only to get one reply in a browser. You do not need to understand nanobot's architecture or edit its config by hand.
This page is for you if you have never used a terminal, edited a JSON file, or configured an AI model before.
## What You Will Need
The goal is small: get one local nanobot reply in your browser. Do not connect Telegram, Discord, Docker, local models, or deployment yet. Those are easier after the first reply works.
- A Windows, macOS, or Linux computer.
- Python 3.11 or newer.
- An account or endpoint that can run an AI model.
- The API key, login, endpoint, and model name required by that service. A local model such as Ollama may not require an API key.
## What You Are Setting Up
An API key is password-like. Do not post it in an issue, screenshot, chat, or public config file.
You only need these words for Quick Start:
## A Few Useful Words
| Word | Meaning |
| Word | Plain meaning |
|---|---|
| Terminal | A text window where you paste a command and press Enter |
| Command | One instruction typed into the terminal |
| Provider | The service or local server that runs the AI model |
| Model ID | The exact model name expected by that provider |
| API key | A secret credential that lets software call the provider |
| Wizard | A question-and-answer setup menu |
| WebUI | The local browser page where you use nanobot |
| Terminal | A text window where you paste commands and press Enter. |
| Command | One line of text you run in the terminal. |
| API key | A password-like token from an AI provider. Do not share it publicly. |
| Config file | The settings file nanobot reads when it starts. |
| Wizard | An interactive terminal menu that edits the config file for you. |
| Browser UI | The local web page where you chat with nanobot. |
## 1. Install Python
## 1. Open a Terminal
Download Python from [python.org](https://www.python.org/downloads/) if you do not already have version 3.11 or newer. On Windows, enable **Add python.exe to PATH** if the installer shows that option.
You will paste commands into a terminal. Copy only the command text inside each code block; do not copy the ``` marks.
Open a terminal:
| System | How |
| System | How to open it |
|---|---|
| Windows | Press `Win`, type `PowerShell`, and open Windows PowerShell |
| macOS | Press `Command+Space`, type `Terminal`, and press Enter |
| Linux | Open your application menu and search for Terminal |
| Windows | Press `Win`, type `PowerShell`, then open **Windows PowerShell**. |
| macOS | Press `Command` + `Space`, type `Terminal`, then press `Enter`. |
| Linux | Open your app launcher, search for `Terminal`, then open it. |
Check Python:
When the terminal opens, click inside it, paste the command, and press `Enter`. If a command prints text and returns to a prompt, that is usually normal.
## 2. Install Python
Install Python 3.11 or newer from [python.org](https://www.python.org/downloads/).
On Windows, enable **Add python.exe to PATH** during installation if the installer shows that option.
In that terminal, check Python:
```bash
python --version
```
The result should start with `Python 3.11` or a newer number. If the command is not found, close and reopen the terminal. You can also try `python3 --version` on macOS/Linux or `py --version` on Windows.
If Windows says `python` is not found, close and reopen PowerShell. If it still does not work, try:
## 2. Prepare Your Model Details
```bash
py --version
```
nanobot does not create an AI provider account for you. Before setup, have these details nearby:
If `py` works but `python` does not, replace `python` with `py` in the commands below.
1. The provider or company endpoint name.
2. Its API key, if it requires one.
3. Its base URL, if its documentation gives you one.
4. A model ID your account can use.
If macOS or Linux says `python` is not found, try:
The provider, credential, endpoint, and model must belong together. For example, an API key from one provider usually cannot call a model name copied from a different provider.
```bash
python3 --version
```
## 3. Install nanobot
If `python3` works but `python` does not, replace `python` with `python3` in the manual commands below. The one-command installer already checks both `python3` and `python`.
Copy the command for your system, paste it into the terminal, and press Enter. Copy only the text inside the code block.
## 3. Get a Provider API Key
nanobot does not create AI accounts or API keys for you. Use an AI provider account, company endpoint, subscription endpoint, or local model server that you already control. If the provider has an OpenAI-compatible base URL in its docs, keep that nearby too.
For the setup path:
1. Open your provider's API key page.
2. Create or copy an API key.
3. Keep the key private.
4. Keep the provider's base URL nearby if the provider docs show one.
## 4. Install nanobot
The easiest path is the one-command installer. It installs or upgrades nanobot, then starts the setup wizard. On macOS and Linux it avoids system-wide pip installs by using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`.
**macOS / Linux**
@@ -70,13 +84,75 @@ curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.
irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | iex
```
The installer downloads the stable nanobot package into an isolated Python environment and opens the setup wizard. It can take a few minutes on the first run. When it finishes, it prints the exact command it used to run nanobot. Keep that command: if `nanobot` is not found later, reuse the whole printed command instead of switching to a different Python command.
These commands install the stable PyPI package. To preview what the installer would do without changing your environment, pass `--dry-run`:
If your organization blocks downloaded install scripts, use the [alternative install methods](./quick-start.md#other-install-methods) or ask your administrator to review the scripts first.
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dry-run
```
## 4. Follow Quick Start
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dry-run
```
The wizard shows a menu similar to:
Use the development installer only when a maintainer asks you to test the current `main` branch:
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dev
```
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dev
```
If the command says `curl` or `irm` is not found, or it cannot download from GitHub, use one of the manual install commands below.
If `uv` is installed, use:
```bash
uv tool install nanobot-ai
```
If you prefer pip, use it only inside an environment you control:
```bash
python -m pip install nanobot-ai
```
If pip reports `externally-managed-environment` on macOS or Linux, go back to the one-command installer, use `uv tool install nanobot-ai`, use `pipx install nanobot-ai`, or create a virtual environment first.
Then check that nanobot is installed:
```bash
nanobot --version
```
If the terminal cannot find `nanobot`, use the module form:
```bash
python -m nanobot --version
```
Use `python3 -m nanobot --version` or `py -m nanobot --version` if that is the Python command that worked in step 2.
## 5. Run the Setup Wizard
The one-command installer starts this for you after installation. If you installed manually, run:
```bash
nanobot onboard --wizard
```
If `nanobot` is not found, run:
```bash
python -m nanobot onboard --wizard
```
Use `python3 -m nanobot onboard --wizard` or `py -m nanobot onboard --wizard` if that is the Python command that worked in step 2.
The wizard is a terminal menu. It is not a graphical app, but it lets you choose options instead of hand-editing every JSON field.
You will see a menu like this:
```text
> What would you like to do?
@@ -85,92 +161,217 @@ The wizard shows a menu similar to:
[X] Exit
```
Choose **Quick Start**. Use the arrow keys to highlight an option and press `Enter`.
Move through the wizard like this:
The wizard asks for only the information needed for the first reply:
| When you see | Do this |
|---|---|
| A menu | Use the arrow keys to highlight an option, then press `Enter`. |
| The provider menu | Choose the company or service you want to use. |
| An endpoint menu | Choose the standard API or subscription plan endpoint that matches your key. |
| An API key field | Paste the key, then press `Enter`. |
| A provider base URL field | Paste the provider base URL from its docs, then press `Enter`. |
| The Model ID field | Paste a model name from your provider, then press `Enter`. |
| A back option in Advanced Settings | Choose it to return to the previous menu. |
1. Choose your provider.
2. Choose an endpoint option if the provider offers several plans.
3. Paste the API key if asked.
4. Enter the base URL if asked.
5. Enter a model ID.
6. Confirm the local WebUI setup.
7. Choose a WebUI password.
8. Review the summary and save.
For the first setup, choose `[Q] Quick Start`. It configures the recommended local browser UI and default AI settings for you. Use `Advanced Settings` later only if you need a chat app, a tool setup, or provider-specific fields.
When you paste a password or API key, the terminal may hide the characters. That is normal.
1. Choose `[Q] Quick Start`.
2. Choose the provider you want to use.
3. Choose the endpoint if the wizard asks, such as Standard API, Coding Plan, Token Plan, or Step Plan.
4. Paste your API key if the wizard asks for one.
5. Paste the provider base URL if the wizard asks for one.
6. Paste a model ID that provider can run.
7. Confirm that Quick Start should enable the WebSocket channel for the local WebUI.
8. Set the WebUI password when prompted.
9. Review the Quick Start summary. The wizard saves and exits when Quick Start finishes.
If the installer finishes without opening the wizard and `nanobot` is available, run:
The recommended path enables `channels.websocket` for the local WebUI, requires a WebUI password, and writes default AI settings. You do not need to choose a separate chat app for the first run.
```bash
nanobot onboard --wizard
If you already know that you need custom headers, provider-specific request fields, a chat app, or tools, choose `Advanced Settings` instead. [`provider-cookbook.md`](./provider-cookbook.md) has copyable examples for several common provider setups. After you change advanced settings, a save option appears in the main menu. Choose `[S] Save and Exit`.
The wizard creates or updates:
| Path | Meaning |
|---|---|
| `~/.nanobot/config.json` | Settings file. |
| `~/.nanobot/workspace/` | Working folder for memory, sessions, and generated files. |
If Quick Start finished successfully, skip to [Open the WebUI](#7-open-the-webui). The next two sections are only for manual setup.
## Manual Setup: How to Merge JSON Snippets
Most docs examples are snippets, not whole files. Your `config.json` has one outer `{ ... }`. Add new top-level sections such as `providers`, `modelPresets`, `agents`, or `channels` inside that same outer object.
Do not paste two separate JSON objects into one file:
```text
{
"providers": { "...": "..." }
}
{
"channels": { "...": "..." }
}
```
If the terminal cannot find `nanobot`, take the exact command printed by the installer and replace its final arguments with `onboard --wizard`. That command may begin with `uv tool run`, `pipx run`, or the full path to nanobot's private Python environment.
Merge them into one object:
## 5. Open the Browser
```json
{
"providers": {
"custom": {
"apiKey": "your-api-key",
"apiBase": "https://api.example.com/v1"
}
},
"channels": {
"websocket": {
"enabled": true,
"tokenIssueSecret": "your-webui-password",
"websocketRequiresToken": true
}
}
}
```
Run:
Notice the comma after the `providers` block. JSON needs commas between sibling sections, but not after the last section. If this feels hard, use `nanobot onboard --wizard` whenever possible.
## 6. Manual Setup: Config Fallback
Use this only if the wizard is unavailable or you prefer opening the file yourself.
Run `nanobot onboard` first if `~/.nanobot/config.json` does not exist yet.
Use one of these commands:
**Windows PowerShell**
```powershell
notepad "$env:USERPROFILE\.nanobot\config.json"
```
**macOS**
```bash
open -e ~/.nanobot/config.json
```
**Linux**
```bash
xdg-open ~/.nanobot/config.json
```
If this is a brand-new install and you have not configured anything else yet, replace the file with this minimal config:
```json
{
"providers": {
"custom": {
"apiKey": "your-api-key",
"apiBase": "https://api.example.com/v1"
}
},
"modelPresets": {
"primary": {
"label": "Primary",
"provider": "custom",
"model": "model-id-from-your-provider",
"maxTokens": 4096,
"contextWindowTokens": 65536,
"temperature": 0.1
}
},
"agents": {
"defaults": {
"modelPreset": "primary"
}
},
"channels": {
"websocket": {
"enabled": true,
"tokenIssueSecret": "your-webui-password",
"websocketRequiresToken": true
}
}
}
```
Replace `your-api-key`, `https://api.example.com/v1`, `model-id-from-your-provider`, and `your-webui-password` with your own values.
For copyable provider-specific examples, use [`provider-cookbook.md`](./provider-cookbook.md).
Save the file.
## 7. Open the WebUI
First check that nanobot can read the saved setup:
```bash
nanobot status
```
This should show the config file path, workspace path, and the active model or preset. If `nanobot` is not found, use `python -m nanobot status`, `python3 -m nanobot status`, or `py -m nanobot status`, matching the Python command that worked in step 2.
It is normal for most providers to say `not set`. Only the provider you selected for the active preset needs to look configured.
Start the local browser UI:
```bash
nanobot gateway
```
Leave the terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password from the wizard if the browser asks for it. Current source versions also provide `nanobot webui`, which starts the gateway and opens the browser automatically.
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password you set in the wizard or the `tokenIssueSecret` value from your manual config.
Send this message:
Send this first message in the browser:
```text
Hello!
```
A normal assistant reply means setup is complete. The exact reply does not matter.
If that works, nanobot is installed and can call the model. You should see a normal assistant reply in the browser. The exact words will differ, but it should look like this shape:
The first-run address is local to your computer. It is not automatically available to other computers on your network.
## 6. Add One Thing at a Time
Do not configure every feature immediately. Choose one next goal:
| Goal | What to do |
|---|---|
| Change the AI model | Open **Settings → Models** |
| Add a provider credential | Open **Settings → Models**, then find the provider |
| Connect Telegram, Discord, Slack, Feishu, WeChat, or another chat app | Open **Settings → Channels**, choose the platform, and follow its connection steps |
| Add a tool integration | Open **Apps** and choose an App or MCP integration |
| Schedule a reminder or recurring task | Ask nanobot in the target chat, then manage it in **Automations** |
| Work with project files | Start a new chat, choose the project workspace, and review the access setting before sending the task |
Repository docs show the current development version. If your stable package does not yet show **Settings → Channels**, use the [Chat Apps guide](./chat-apps.md) or update to a release that includes it.
Some runtime changes ask you to restart nanobot. Use the restart action shown by the WebUI, or return to the terminal, press `Ctrl+C`, and run `nanobot gateway` again.
For a chat platform's account, bot, token, or permission prerequisites, use the [Chat Apps guide](./chat-apps.md). For local models and provider-specific recipes, use the [Provider Cookbook](./provider-cookbook.md).
## If Something Fails
Run these commands one at a time:
```bash
nanobot --version
nanobot status
nanobot agent -m "Hello!"
```text
Hello! How can I help you today?
```
| What you see | What it usually means |
If `nanobot` is not found, run:
```bash
python -m nanobot gateway
```
Use `python3 -m nanobot gateway` or `py -m nanobot gateway` if that is the Python command that worked in step 2.
Once this works, nanobot can help with its own next setup step. In the browser UI, ask it to read these docs and update your current config for one specific goal, then run `/restart` when nanobot tells you the config is ready. For example, ask it to add one provider preset or configure one chat app.
## 8. If Something Fails
Do not change many things at once. Check the exact error:
| Error or symptom | What it usually means |
|---|---|
| `nanobot: command not found` | Reuse the exact nanobot command printed by the installer; it points to the isolated environment that contains the package |
| `401`, unauthorized, or invalid API key | The key is wrong, expired, or belongs to a different provider |
| Model not found | The model ID is misspelled or unavailable to your provider account |
| Browser does not open | Open `http://127.0.0.1:8765` yourself and keep the terminal running |
| Browser opens but messages fail | Test `nanobot agent -m "Hello!"` to separate a model problem from a WebUI problem |
| A change was saved but nothing changed | Restart nanobot so the running process reloads the config |
| `JSON parse error` | The config file has a missing comma, extra comma, or mismatched brace. Copy the example again. |
| `401`, `unauthorized`, or `invalid API key` | The API key is wrong, expired, has extra spaces, or was pasted under the wrong provider. |
| `model not found` | Your account cannot use the default model. Return to `nanobot onboard --wizard`, choose `Advanced Settings`, then edit `Model Presets`. |
| `nanobot: command not found` | The install worked in Python, but your shell cannot find the script. Use `python -m nanobot ...`, `python3 -m nanobot ...`, or `py -m nanobot ...`, matching the Python command that worked earlier. |
| No response after editing config | Restart the command. Long-running processes read config when they start. |
If you ask for help, include your operating system, `nanobot --version`, `nanobot status`, the exact command, and the exact error. Remove every API key, bot token, password, OAuth token, and private account ID first.
For a fuller diagnosis path, see [`troubleshooting.md`](./troubleshooting.md).
Continue with the full [Troubleshooting guide](./troubleshooting.md) for an ordered diagnosis.
## What Not to Configure Yet
## Open nanobot Later
Skip these until the first local message works:
- `apiBase`: hosted built-in providers often already have default endpoints. You only need `apiBase` for local models, proxies, custom OpenAI-compatible providers, or special regional/subscription endpoints.
- chat apps: first prove the local browser UI can answer.
- fallback models: useful later, but not needed for the first reply.
- Langfuse: useful for observability, but not needed for first setup.
## Next Steps
After the first reply works, choose only one next goal. Keep the terminal that runs `nanobot gateway` open whenever you use the WebUI or a chat app.
### Open the Browser UI Again
Run:
@@ -178,4 +379,43 @@ Run:
nanobot gateway
```
Leave that terminal open and visit `http://127.0.0.1:8765`. To stop nanobot, return to the terminal and press `Ctrl+C`. Use `nanobot gateway --background` only after the normal foreground start works; then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser.
To stop the WebUI later, return to the gateway terminal and press `Ctrl+C`.
If `nanobot` is not found, run `python -m nanobot gateway`, `python3 -m nanobot gateway`, or `py -m nanobot gateway`, matching the Python command that worked earlier. More details are in [`webui.md`](./webui.md).
### Connect a Chat App
1. Read the section for one app in [`chat-apps.md`](./chat-apps.md).
2. Add only that app's config snippet. Merge it into the existing file instead of replacing the whole file.
3. Run:
```bash
nanobot channels status
nanobot gateway
```
4. Leave the gateway terminal open, then send a message from the allowed account.
Start with a private chat or a test server. Do not set `allowFrom` to `["*"]` unless you intentionally want anyone who can reach that channel to talk to the bot.
### Change Models or Add Backups
Use [`providers.md`](./providers.md) when a provider/model pair fails, and [`provider-cookbook.md`](./provider-cookbook.md) when you want copyable snippets. Keep model choices in `modelPresets`, then select the active one with `agents.defaults.modelPreset`.
### Ask for Help
When you ask for help, include:
- your operating system;
- the command you ran;
- `nanobot --version`;
- `nanobot status`;
- whether the browser UI can answer `Hello!`;
- the exact error text;
- a config snippet with API keys and tokens removed.
Never paste real API keys, bot tokens, OAuth tokens, or private chat IDs into a public issue or chat.
If you find a docs mistake, outdated command, or confusing step, please open an issue: <https://github.com/HKUDS/nanobot/issues>.
+5 -11
View File
@@ -31,7 +31,7 @@ If `nanobot agent -m "Hello!"` fails, fix that before debugging WebUI, Telegram,
## How to Read `nanobot status`
`nanobot status` does not call a model. It only checks whether nanobot can find the selected config, selected workspace, active model or preset, and provider setup summary.
`nanobot status` does not call a model. It only checks whether nanobot can find the default config, default workspace, active model or preset, and provider setup summary.
The output has this shape:
@@ -90,10 +90,9 @@ Default workspace path:
~/.nanobot/workspace/
```
`nanobot status` reads the default config unless you pass explicit paths. Use the same `--config` and `--workspace` across status checks and runtime commands when debugging multiple instances:
`nanobot status` reads the default config. Use explicit paths on commands that support them when debugging multiple instances:
```bash
nanobot status --config ./bot-a/config.json --workspace ./bot-a/workspace
nanobot agent --config ./bot-a/config.json --workspace ./bot-a/workspace -m "Hello"
nanobot gateway --config ./bot-a/config.json --workspace ./bot-a/workspace
```
@@ -111,10 +110,10 @@ Common config mistakes:
To refresh missing defaults without overwriting existing settings, run:
```bash
nanobot onboard --refresh
nanobot onboard
```
For an interactive choice between resetting and refreshing, run `nanobot onboard` and choose the option that keeps current values and merges missing defaults.
When prompted about overwriting the config, choose the option that keeps current values and merges missing defaults.
## Provider and Model Problems
@@ -135,12 +134,7 @@ If you need a known-good snippet instead of diagnosis, use [`provider-cookbook.m
| Provider cannot be inferred | Pin `modelPresets.<name>.provider` in the active preset instead of using `"auto"`. For legacy direct configs, pin `agents.defaults.provider`. |
| Local model connection refused | Ollama, vLLM, LM Studio, or another local server is not running, or `apiBase` points to the wrong port. |
| Bedrock validation error | Check AWS region, credentials, model access, model ID, and whether the model supports Converse. |
| OAuth provider fails | Run `nanobot provider login openai-codex --set-main` or `nanobot provider login github-copilot --set-main`. |
| Codex OAuth needs a proxy | Set `providers.openaiCodex.proxy` before running the login command. The proxy applies to login, token refresh, and Codex API requests. |
| Codex login runs on a remote/headless machine | Open the printed URL in a local browser, then paste the final `http://localhost:1455/auth/callback?...` URL back into the terminal. |
| Codex login runs in Docker | Start the container with `docker run -it` so the OAuth flow has an interactive terminal. |
| Codex says a model is not supported with a ChatGPT account | Use provider `openai_codex` with a Codex model such as `openai-codex/gpt-5.6-sol`. Do not use the direct-API `openai/...` prefix with Codex OAuth. |
| Config says `providers.openai_codex` conflicts with the built-in provider | Under `providers`, keep only the canonical `openaiCodex` settings key and remove a duplicate `openai_codex` key. A model preset's `provider` value remains `openai_codex`. |
| OAuth provider fails | Run `nanobot provider login openai-codex` or `nanobot provider login github-copilot`, then select the provider explicitly. |
## Langfuse Problems
+9 -9
View File
@@ -16,13 +16,13 @@ Nanobot can act as a WebSocket server, allowing external clients (web apps, CLIs
### 1. Configure
The WebSocket channel is enabled by default. Add only the fields you want to
override under `channels.websocket`:
Add to `config.json` under `channels.websocket`:
```json
{
"channels": {
"websocket": {
"enabled": true,
"host": "127.0.0.1",
"port": 8765,
"path": "/",
@@ -208,7 +208,7 @@ All fields go under `channels.websocket` in `config.json`.
| Field | Type | Default | Description |
|-------|------|---------|-------------|
| `enabled` | bool | `true` | Enable the WebSocket server. Set to `false` only when you intentionally do not want the bundled WebUI/WebSocket surface. |
| `enabled` | bool | `false` | Enable the WebSocket server. |
| `host` | string | `"127.0.0.1"` | Bind address. Use `"0.0.0.0"` to accept external connections. |
| `port` | int | `8765` | Listen port. |
| `path` | string | `"/"` | WebSocket upgrade path. Trailing slashes are normalized (root `/` is preserved). |
@@ -221,7 +221,7 @@ All fields go under `channels.websocket` in `config.json`.
| `token` | string | `""` | Static shared secret. When set, clients must provide `?token=<value>` matching this secret (timing-safe comparison). Issued tokens are also accepted as a fallback. |
| `websocketRequiresToken` | bool | `true` | When `true` and no static `token` is configured, clients must still present a valid issued token. Set to `false` to allow unauthenticated connections (only safe for local/trusted networks). |
| `tokenIssuePath` | string | `""` | HTTP path for issuing short-lived tokens. Must differ from `path`. See [Token Issuance](#token-issuance). |
| `tokenIssueSecret` | string | `""` | Secret required to obtain tokens via the issue endpoint. If empty, any client can obtain WebSocket connection tokens from `tokenIssuePath` (logged as a warning). `/webui/bootstrap` still issues WebUI REST API tokens for same-machine localhost browser requests; remote or forwarded bootstrap requires `tokenIssueSecret` or `token`. |
| `tokenIssueSecret` | string | `""` | Secret required to obtain tokens via the issue endpoint. If empty, any client can obtain tokens (logged as a warning). |
| `tokenTtlS` | int | `300` | Time-to-live for issued tokens in seconds (30 86,400). |
### Access Control
@@ -266,17 +266,13 @@ For production deployments where `websocketRequiresToken: true`, use short-lived
3. Client opens WebSocket with `?token=nbwt_aBcDeFg...&client_id=...`.
4. The token is consumed (single use) and cannot be reused.
The embedded WebUI's `/webui/bootstrap` route also returns a WebSocket token.
It returns a separate `api_token` for REST routes to same-machine localhost
browser requests, or after the request proves knowledge of `tokenIssueSecret`
or the static `token`.
### Example setup
```json
{
"channels": {
"websocket": {
"enabled": true,
"port": 8765,
"path": "/ws",
"tokenIssuePath": "/auth/token",
@@ -371,6 +367,7 @@ Outbound `message` events may include a `media` field containing local filesyste
{
"channels": {
"websocket": {
"enabled": true,
"host": "0.0.0.0",
"port": 8765,
"websocketRequiresToken": false,
@@ -387,6 +384,7 @@ Outbound `message` events may include a `media` field containing local filesyste
{
"channels": {
"websocket": {
"enabled": true,
"token": "my-shared-secret",
"allowFrom": ["alice", "bob"]
}
@@ -402,6 +400,7 @@ Clients connect with `?token=my-shared-secret&client_id=alice`.
{
"channels": {
"websocket": {
"enabled": true,
"host": "0.0.0.0",
"port": 8765,
"path": "/ws",
@@ -422,6 +421,7 @@ Clients connect with `?token=my-shared-secret&client_id=alice`.
{
"channels": {
"websocket": {
"enabled": true,
"path": "/chat/ws",
"allowFrom": ["*"]
}
+39 -143
View File
@@ -1,48 +1,28 @@
# Nanobot WebUI: Browser Workbench for Self-Hosted AI Agents
# WebUI
<!-- Meta description: Run nanobot from a browser WebUI with persistent chat sessions, visible tool activity, workspace controls, Apps, MCP presets, Skills, settings, and Automations. -->
The WebUI is nanobot's browser workbench for persistent chat sessions, visible
agent activity, workspace controls, Apps, Skills, settings, and Automations in
one place.
The WebUI is nanobot's browser workbench. Use it after a basic CLI reply already
works, when you want a persistent chat workspace, visible agent activity,
workspace controls, Apps, Skills, settings, and Automations in one place.
The published `nanobot-ai` wheel already includes the WebUI bundle. You only need
the `webui/` source directory when you are changing the frontend itself.
## Open the WebUI
Use the launcher:
First confirm your provider and model can answer:
```bash
nanobot webui
nanobot agent -m "Hello!"
```
`nanobot webui` creates the config/workspace when needed, checks provider setup,
offers Quick Start when the model provider is not ready, enables the local
WebSocket channel after confirmation, generates a WebUI bootstrap secret when
one is missing, starts the gateway, and opens the browser. The first-run path
binds the WebUI to `127.0.0.1` by default, so it is not available from other
devices on your LAN.
Run it in the background when you do not want to keep a terminal open:
```bash
nanobot webui --background
```
Manage the background gateway with `nanobot gateway status`, `nanobot gateway
logs`, `nanobot gateway restart`, and `nanobot gateway stop`.
Manual config still works. Same-machine localhost WebUI access can run without
a browser password. Set `tokenIssueSecret` when you intentionally expose the
WebUI beyond localhost or want a browser password:
Then merge the WebSocket channel into your existing `~/.nanobot/config.json`.
Set `tokenIssueSecret` to the password you will enter in the WebUI login form:
```json
{
"channels": {
"websocket": {
"enabled": true,
"host": "127.0.0.1",
"tokenIssueSecret": "your-webui-password",
"websocketRequiresToken": true
}
@@ -50,34 +30,33 @@ WebUI beyond localhost or want a browser password:
}
```
The WebUI is served by the WebSocket channel on port `8765` by default. The
gateway health endpoint, `18790` by default, is not the browser UI.
If you are new to JSON snippets, see
[`start-without-technical-background.md#how-to-merge-json-snippets`](./start-without-technical-background.md#how-to-merge-json-snippets).
## First 10 Minutes
Start the gateway:
Use the WebUI as the primary setup surface after Quick Start:
```bash
nanobot gateway
```
1. Send `Hello!` in a new chat to prove the selected model works.
2. Open **Settings → Models** and confirm the active model preset.
3. Start a separate chat before project work, then choose the intended workspace and access mode.
4. Add only one capability next: a chat channel in **Settings → Channels**, a web/voice/image provider in **Settings**, or an App/MCP integration in **Apps**.
5. Restart when the WebUI shows a restart requirement, then test that capability with the smallest possible request.
This path avoids hand-editing `config.json` for normal setup. Use the reference docs when you need an option the WebUI does not expose or when you manage config as code.
Leave the gateway running and open
[`http://127.0.0.1:8765`](http://127.0.0.1:8765). The WebUI is served by the
WebSocket channel on port `8765` by default. The gateway health endpoint,
`18790` by default, is not the browser UI.
Enter `tokenIssueSecret` when the WebUI asks for a password.
## What It Is For
| Area | Use it for |
|---|---|
| Chat | Start, switch, search, fork, and delete browser sessions |
| Agent activity | See thinking, tool calls, file edits with diffs, command output, and generated artifacts in context |
| Agent activity | See thinking, tool calls, file activity, command output, and generated artifacts in context |
| Workspace | Pick the project workspace before asking for file or shell work |
| Access | Choose the access mode for local capabilities allowed by your gateway configuration |
| Composer | Send text, images, voice input, slash commands, and `@` mentions for Apps or MCP presets |
| Channels | Connect and validate chat platforms, install their optional support, and manage saved channel setup |
| Apps | Install, test, update, and use local CLI App adapters and MCP presets |
| Skills | Inspect available built-in and workspace skills before relying on them |
| Automations | Review, search, run, pause, edit, and delete scheduled and local-trigger agent turns |
| Automations | Review, search, run, pause, edit, and delete scheduled agent turns |
| Settings | Adjust models, providers, image generation, voice, web tools, runtime, and safety options |
## Chat Workspace
@@ -90,16 +69,6 @@ without changing the original thread.
The message timeline shows both user-visible replies and agent activity. Long
tool or reasoning sections can be expanded when you need the details.
When the agent writes or edits files, the activity item shows the target path,
status, changed line counts, and, when available, a unified diff. Use **View
diff** to expand the change; large diffs may hide unchanged lines or truncate the
inline preview. Use **Open file** from a file edit to open the read-only file
preview panel.
File previews follow the active session access mode. Restricted workspace access
previews only files under the selected workspace. Full Access can preview files
outside the workspace when that access mode is allowed by the gateway.
## Workspace and Access
Use the workspace picker before starting project-specific work. This gives the
@@ -111,10 +80,6 @@ chat. It does not bypass your gateway, provider, shell sandbox, or operating
system configuration; it only selects among the capabilities that are already
available to this WebUI session.
Remote WebUI sessions may reduce access for the current workspace. Selecting a
different workspace or enabling Full Access remains limited to local and native
clients.
## Composer
The composer supports plain messages, image attachments, voice input when
@@ -126,38 +91,12 @@ For image generation, configure an image provider first and then use the WebUI
image mode from the composer. See [`image-generation.md`](./image-generation.md)
for provider setup and output behavior.
## Channels
Open **Settings → Channels** to connect chat apps without assembling JSON by hand. Search for a platform, open its setup panel, and follow the fields or QR flow shown for that channel. The guided setup can:
- install missing optional channel support when the WebUI is running locally;
- collect platform credentials while preserving previously saved values;
- handle supported QR-based login flows;
- validate the connection and show actionable setup errors;
- tell you when the gateway needs to restart.
The platform itself may still require you to create a bot, enable event permissions, copy a token, or configure a webhook. Use [`chat-apps.md`](./chat-apps.md) for those platform-side prerequisites and for manual JSON/reference options.
Test a new channel with a private DM. When a supported channel sends a pairing code, the WebUI surfaces the pending request so you can approve the sender. Keep access narrow; do not use a wildcard allowlist unless public access is intentional.
## Apps
Open Apps from the sidebar to manage tools that nanobot can attach to a chat
turn. The default **Ready** view shows only tools that can be used immediately:
- **Apps** are local command-line adapters that nanobot runs on your machine.
Installing an adapter does not modify the native desktop or web app it
connects to.
- **Integrations** are MCP servers. Presets provide known configurations, and
the custom integration panel accepts stdio, HTTP, and SSE servers.
Apps intentionally does not list nanobot runtime support packages such as
`api` or `bedrock`. Those packages enable providers, servers, or channels; they
are not tools that can be attached to a turn with `@`. Manage them from
**System**, **Models**, or **Web**. PDF and common Office document readers are
included in nanobot and activate automatically when a file is attached. The
equivalent CLI for optional integrations remains `nanobot plugins`. See
[`cli-reference.md`](./cli-reference.md#optional-features).
Open Apps from the sidebar or settings navigation to manage integrations that
nanobot can call from a chat. CLI Apps install local adapters that nanobot runs
on your machine; they do not modify the native apps themselves. MCP presets add
predefined MCP server configurations.
Some MCP presets connect to hosted keyless endpoints. For example, the Firecrawl
preset uses Firecrawl's hosted MCP endpoint for search, scrape, crawl, and
@@ -165,8 +104,8 @@ extraction tools without requiring an API key. This does not replace nanobot's
built-in web search provider; mention the Firecrawl MCP preset with `@` when a
turn needs Firecrawl's richer web data tools.
After an App or integration is available, mention it from the composer with
`@` to attach that tool to the next message.
After an App or MCP preset is available, mention it from the composer with `@`
to attach that capability to the next message.
## Skills
@@ -177,20 +116,10 @@ to perform that task.
## Automations
Automations are agent turns that run later in a linked chat/session. They should
be created from the chat, channel, or session where they are supposed to run so
nanobot keeps the correct target context. When an automation runs, it normally
delivers the result back to that linked chat.
For the full automation model, creation flow, trigger CLI usage, and delivery
semantics, see [`automations.md`](./automations.md).
There are two user-facing automation types:
- Scheduled automations, created by the agent's cron tool, run at a time,
interval, or cron expression.
- Local triggers, created with `/trigger <name>`, run when you call a local
command such as `nanobot trigger trg_8K4P2Q9X "Review PR #4502"`.
Automations are scheduled agent turns. They should be created from the chat,
channel, or session where they are supposed to run so nanobot keeps the correct
target context. When an automation runs, it normally delivers the result back to
that linked chat.
For recurring background checks that should stay quiet unless there is something
useful to report, use the protected heartbeat job by editing `HEARTBEAT.md`
@@ -199,39 +128,29 @@ instead of creating a chat automation.
Use the Automations view to:
- Filter by all, active, paused, needs-attention, or system jobs.
- Search by task name, message, trigger command, linked chat, schedule, or status.
- Search by task name, message, linked chat, schedule, or status.
- Sort by next run, last run, updated time, or name.
- Run scheduled automations now.
- Pause or resume, rename, or delete user-created automations.
- Copy the CLI command for local triggers.
- Run now, pause or resume, edit, or delete user-created automations.
- Inspect protected system automations without changing them.
Search accepts plain text and field filters such as `name:backup`,
`chat:WeChat`, `schedule:09:30`, `cron:"0 23 * * *"`, `trigger`, and
`status:paused`.
`chat:WeChat`, `schedule:09:30`, `cron:"0 23 * * *"`, and `status:paused`.
An automation without a linked chat cannot be enabled or run from the WebUI,
because nanobot would not know where to deliver the scheduled turn. Recreate it
from the target chat or channel so the automation has complete context.
Local triggers do not have a WebUI "Run now" action because each run needs a
message. Use the copied `nanobot trigger ...` command and replace `"message"`
with the content that should be delivered.
## Settings
Settings is the control surface for the browser session and gateway-backed
runtime configuration. Use it to review or adjust model presets, providers,
image generation, voice transcription, web tools, chat channels, Apps,
Automations, Skills, runtime identity, and advanced safety controls.
runtime configuration. Use it to review or adjust model presets, provider
visibility, image generation, voice transcription, web tools, Apps, Automations,
Skills, runtime identity, and advanced safety controls.
Some settings take effect immediately. Runtime settings that affect the gateway
or agent process may require a restart; the WebUI shows that requirement next to
the relevant control.
Browser-only display preferences, such as file edit display mode, take effect
immediately for the current browser and do not change gateway configuration.
## LAN Access
To open the WebUI from another device on the same network, bind the WebSocket
@@ -241,6 +160,7 @@ channel to all interfaces and set a token or token issue secret:
{
"channels": {
"websocket": {
"enabled": true,
"host": "0.0.0.0",
"port": 8765,
"tokenIssueSecret": "your-secret-here"
@@ -254,36 +174,12 @@ The gateway refuses to start with `host` set to `"0.0.0.0"` unless `token` or
`http://<your-ip>:8765` from the other device and enter the secret in the login
form.
Remote WebUI clients with a valid token can view and use Apps. Actions that
install missing nanobot support packages, such as adding a channel dependency,
are blocked by default. To let trusted remote administrators change the Python
environment through the WebUI, opt in explicitly:
```json
{
"tools": {
"webuiAllowRemotePackageInstall": true
}
}
```
Use this only for a private deployment where every authenticated WebUI user is
trusted to change the Python environment that nanobot runs in. If you publish
the WebUI through Nginx, Caddy, Cloudflare Tunnel, or a similar service, treat it
as remote access and leave package installs disabled unless that is intentional.
Optional feature installs use pip's configured package index, including
`PIP_INDEX_URL`.
Leave remote package installs disabled when the WebUI is exposed beyond a
private, trusted network.
## Troubleshooting
If the page does not open, check these in order:
1. `nanobot agent -m "Hello!"` works in the same Python environment.
2. `~/.nanobot/config.json` does not explicitly set `channels.websocket.enabled` to `false`.
2. The WebSocket channel is enabled in `~/.nanobot/config.json`.
3. `nanobot gateway` is still running.
4. You are opening port `8765`, not the gateway health port.
5. LAN access uses `host: "0.0.0.0"` and a token or token issue secret.
-40
View File
@@ -1,44 +1,5 @@
#!/bin/sh
dir="$HOME/.nanobot"
# Render deploy path (see render.yaml + render-config.json). Gated on Render's
# automatic RENDER=true env var so local Docker/podman usage is unaffected.
# Initializes the on-disk config from the committed template (wiring secrets via
# ${VAR} env vars, keeping runtime data on the persistent disk) and appends the
# --config flag. Logs each decision so a failed start is diagnosable in Render's
# logs. Privilege dropping is handled below, for every root start (not just here).
if [ "$RENDER" = "true" ]; then
echo "[entrypoint] Render deploy — starting as $(id)"
mkdir -p "$dir" || echo "[entrypoint] warning: mkdir $dir failed"
config="$dir/config.json"
# Initialize config only when it does not already exist, so WebUI/provider
# settings edited at runtime survive restarts. The disk persists config.json
# across deploys; overwriting it every boot would discard those changes.
if [ ! -f "$config" ]; then
echo "[entrypoint] initializing $config from render-config.json"
cp /app/render-config.json "$config" || echo "[entrypoint] warning: cp config failed"
else
echo "[entrypoint] existing $config found — leaving it in place"
fi
set -- "$@" --config "$config"
fi
# Drop privileges whenever the container starts as root. Render mounts the
# persistent disk root-owned, and a plain `docker run` also defaults to root now,
# so this covers both. Chown the data dir so the non-root user can write it, then
# re-exec as nanobot. Fail closed: if the privilege drop cannot be performed,
# exit rather than run the agent as root.
if [ "$(id -u)" = "0" ]; then
chown -R nanobot:nanobot "$dir" 2>/dev/null || echo "[entrypoint] warning: chown $dir failed"
if setpriv --reuid=nanobot --regid=nanobot --init-groups true 2>/dev/null; then
echo "[entrypoint] dropping privileges to nanobot via setpriv"
exec setpriv --reuid=nanobot --regid=nanobot --init-groups nanobot "$@"
fi
echo "[entrypoint] error: started as root but setpriv privilege drop failed — refusing to run as root" >&2
exit 1
fi
# Already non-root: make sure the data dir is writable before starting.
if [ -d "$dir" ] && [ ! -w "$dir" ]; then
owner_uid=$(stat -c %u "$dir" 2>/dev/null || stat -f %u "$dir" 2>/dev/null)
cat >&2 <<EOF
@@ -51,5 +12,4 @@ Fix (pick one):
EOF
exit 1
fi
exec nanobot "$@"
+30 -32
View File
@@ -4,7 +4,7 @@ Triggered automatically by `python -m build` (and any other hatch-driven build)
so published wheels and sdists ship a fresh webui without requiring developers
to remember `cd webui && bun run build` beforehand.
Behavior:
Behaviour:
- Skips for editable installs (`pip install -e .`). Editable mode is for Python
development; webui contributors use `cd webui && bun run dev` (Vite HMR) and
@@ -12,7 +12,7 @@ Behavior:
- No-op when `webui/package.json` is absent (e.g. installing from an sdist that
already contains a prebuilt `nanobot/web/dist/`).
- Skips when `NANOBOT_SKIP_WEBUI_BUILD=1` is set.
- Reuses `nanobot/web/dist/` only when it is already fresh, unless
- Skips when `nanobot/web/dist/index.html` already exists, unless
`NANOBOT_FORCE_WEBUI_BUILD=1` is set.
- Uses `bun` when available, otherwise falls back to `npm`. The chosen tool
performs `install` followed by `run build`.
@@ -21,22 +21,12 @@ Behavior:
from __future__ import annotations
import os
import sys
import shutil
import subprocess
from pathlib import Path
from types import ModuleType
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
_PROJECT_ROOT = Path(__file__).resolve().parent
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
def _load_webui_build_module() -> ModuleType:
from nanobot.webui import build as webui_build
return webui_build
class WebUIBuildHook(BuildHookInterface):
PLUGIN_NAME = "webui-build"
@@ -68,32 +58,24 @@ class WebUIBuildHook(BuildHookInterface):
)
return
webui_build = _load_webui_build_module()
status = webui_build.inspect_webui_bundle(source_dir=webui_dir, dist_dir=dist_dir)
force = os.environ.get("NANOBOT_FORCE_WEBUI_BUILD") == "1"
if not status.needs_build and not force:
if index_html.is_file() and not force:
self.app.display_info(
f"[webui-build] reusing existing build at {dist_dir} "
"(already fresh; set NANOBOT_FORCE_WEBUI_BUILD=1 to rebuild)"
"(set NANOBOT_FORCE_WEBUI_BUILD=1 to rebuild)"
)
return
if status.needs_build and not force:
self.app.display_info(
f"[webui-build] {webui_build.describe_webui_bundle_status(status)}"
runner = self._pick_runner()
if runner is None:
raise RuntimeError(
"[webui-build] neither `bun` nor `npm` is available on PATH; "
"install one or set NANOBOT_SKIP_WEBUI_BUILD=1 to bypass."
)
try:
webui_build.build_webui_bundle(
source_dir=webui_dir,
dist_dir=dist_dir,
output=self.app.display_info,
)
except webui_build.WebUIBuildError as exc:
raise RuntimeError(
"[webui-build] "
f"{exc}. Install `bun` or `npm`, or set NANOBOT_SKIP_WEBUI_BUILD=1 to bypass."
) from exc
self.app.display_info(f"[webui-build] using {runner} to build webui")
self._run([runner, "install"], cwd=webui_dir)
self._run([runner, "run", "build"], cwd=webui_dir)
if not index_html.is_file():
raise RuntimeError(
@@ -101,3 +83,19 @@ class WebUIBuildHook(BuildHookInterface):
"check webui/vite.config.ts outDir."
)
self.app.display_info(f"[webui-build] webui ready at {dist_dir}")
@staticmethod
def _pick_runner() -> str | None:
for candidate in ("bun", "npm"):
if shutil.which(candidate):
return candidate
return None
def _run(self, cmd: list[str], *, cwd: Path) -> None:
self.app.display_info(f"[webui-build] $ {' '.join(cmd)} (cwd={cwd})")
try:
subprocess.run(cmd, cwd=cwd, check=True)
except subprocess.CalledProcessError as exc:
raise RuntimeError(
f"[webui-build] command failed ({exc.returncode}): {' '.join(cmd)}"
) from exc
Binary file not shown.

Before

Width:  |  Height:  |  Size: 657 KiB

After

Width:  |  Height:  |  Size: 287 KiB

+1 -10
View File
@@ -1,14 +1,7 @@
"""Agent core module."""
from nanobot.agent.context import ContextBuilder
from nanobot.agent.hook import (
AgentHook,
AgentHookContext,
AgentRunHookContext,
AgentTurnHookContext,
AgentTurnHookFactory,
CompositeHook,
)
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext, CompositeHook
from nanobot.agent.loop import AgentLoop
from nanobot.agent.memory import MemoryStore
from nanobot.agent.skills import SkillsLoader
@@ -18,8 +11,6 @@ __all__ = [
"AgentHook",
"AgentHookContext",
"AgentRunHookContext",
"AgentTurnHookContext",
"AgentTurnHookFactory",
"AgentLoop",
"CompositeHook",
"ContextBuilder",
+6 -35
View File
@@ -12,7 +12,6 @@ from nanobot.session.manager import Session, SessionManager
if TYPE_CHECKING:
from nanobot.agent.memory import Consolidator
from nanobot.utils.llm_runtime import LLMRuntime
class AutoCompact:
@@ -35,26 +34,6 @@ class AutoCompact:
ts = datetime.fromisoformat(ts)
return ((now or datetime.now()) - ts).total_seconds() >= self._ttl * 60
def _has_compactable_idle_tail(self, key: str) -> bool:
session = self.sessions.get_or_create(key)
tail = list(session.messages[session.last_consolidated:])
if not tail:
return False
probe = Session(
key=session.key,
messages=tail,
created_at=session.created_at,
updated_at=session.updated_at,
metadata={},
last_consolidated=0,
)
result = probe.retain_recent_legal_suffix(
self._RECENT_SUFFIX_MESSAGES,
extend_to_user=True,
)
messages_to_remove = result.dropped[result.already_consolidated_count:]
return bool(messages_to_remove)
@staticmethod
def _format_summary(text: str, last_active: datetime) -> str:
return f"Previous conversation summary (last active {last_active.isoformat()}):\n{text}"
@@ -63,12 +42,8 @@ class AutoCompact:
def _is_internal_session(cls, key: str) -> bool:
return key.startswith(cls._INTERNAL_SESSION_PREFIXES)
def check_expired(
self,
schedule_background: Callable[[Coroutine], None],
resolve_runtime: Callable[[], LLMRuntime],
active_session_keys: Collection[str] = (),
) -> None:
def check_expired(self, schedule_background: Callable[[Coroutine], None],
active_session_keys: Collection[str] = ()) -> None:
"""Schedule archival for idle sessions, skipping those with in-flight agent tasks."""
now = datetime.now()
for info in self.sessions.list_sessions():
@@ -77,21 +52,17 @@ class AutoCompact:
continue
if key in active_session_keys:
continue
updated_at = info.get("updated_at")
if self._is_expired(updated_at, now) and self._has_compactable_idle_tail(key):
runtime = resolve_runtime()
if self._is_expired(info.get("updated_at"), now):
self._archiving.add(key)
schedule_background(self._archive(key, runtime=runtime))
schedule_background(self._archive(key))
async def _archive(self, key: str, *, runtime: LLMRuntime) -> None:
async def _archive(self, key: str) -> None:
if self._is_internal_session(key):
self._archiving.discard(key)
return
try:
summary = await self.consolidator.compact_idle_session(
key,
runtime=runtime,
max_suffix=self._RECENT_SUFFIX_MESSAGES,
key, self._RECENT_SUFFIX_MESSAGES,
)
if summary and summary != "(nothing)":
session = self.sessions.get_or_create(key)
-149
View File
@@ -1,149 +0,0 @@
"""Shared coordination for session-bound automation turns."""
from __future__ import annotations
import asyncio
import dataclasses
from collections.abc import Awaitable, Callable, Iterable
from nanobot.bus.events import InboundMessage, OutboundMessage
class AutomationTurnError(RuntimeError):
"""Raised when an automation turn reaches the agent and finishes with an error."""
async def publish_next_deferred_turn(
*,
deferred_queues: dict[str, list[InboundMessage]],
publish_inbound: Callable[[InboundMessage], Awaitable[None]],
session_key: str,
) -> bool:
"""Publish the next deferred automation turn for a session."""
queue = deferred_queues.get(session_key)
if not queue:
return False
msg = queue.pop(0)
if not queue:
deferred_queues.pop(session_key, None)
await publish_inbound(msg)
return True
class AutomationTurnCoordinator:
"""Manage automation turns without mixing them into live injections."""
def __init__(
self,
*,
publish_inbound: Callable[[InboundMessage], Awaitable[None]],
dispatch: Callable[[InboundMessage], Awaitable[object]],
is_running: Callable[[], bool],
turn_id: Callable[[InboundMessage], str | None],
pending_id: Callable[[InboundMessage], str | None],
should_defer_turn: Callable[[InboundMessage, str, Iterable[str]], bool],
missing_id_error: str,
duplicate_id_error: Callable[[str], str],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
self._publish_inbound = publish_inbound
self._dispatch = dispatch
self._is_running = is_running
self._turn_id = turn_id
self._pending_id = pending_id
self._should_defer_turn = should_defer_turn
self._missing_id_error = missing_id_error
self._duplicate_id_error = duplicate_id_error
self.deferred_queues = deferred_queues if deferred_queues is not None else {}
self._waiters: dict[str, asyncio.Future[OutboundMessage | None]] = {}
self._pending_messages_by_turn_id: dict[str, InboundMessage] = {}
async def submit(self, msg: InboundMessage) -> OutboundMessage | None:
"""Submit an automation turn and wait for its session response."""
turn_id = self._turn_id(msg)
if not turn_id:
raise ValueError(self._missing_id_error)
if turn_id in self._waiters:
raise RuntimeError(self._duplicate_id_error(turn_id))
loop = asyncio.get_running_loop()
future: asyncio.Future[OutboundMessage | None] = loop.create_future()
self._waiters[turn_id] = future
self._pending_messages_by_turn_id[turn_id] = msg
try:
if self._is_running():
await self._publish_inbound(msg)
else:
await self._dispatch(msg)
try:
return await future
except asyncio.CancelledError:
raise
except AutomationTurnError:
raise
except Exception as exc:
raise AutomationTurnError(str(exc) or exc.__class__.__name__) from exc
finally:
self._waiters.pop(turn_id, None)
self._pending_messages_by_turn_id.pop(turn_id, None)
def defer_if_active(
self,
msg: InboundMessage,
*,
session_key: str,
active_session_keys: Iterable[str],
) -> bool:
"""Defer an automation turn when its target session is already active."""
if not self._should_defer_turn(msg, session_key, active_session_keys):
return False
pending_msg = msg
if session_key != msg.session_key:
pending_msg = dataclasses.replace(
msg,
session_key_override=session_key,
)
self.deferred_queues.setdefault(session_key, []).append(pending_msg)
return True
def complete(
self,
msg: InboundMessage,
*,
response: OutboundMessage | None = None,
error: BaseException | None = None,
) -> None:
turn_id = self._turn_id(msg)
if not turn_id:
return
future = self._waiters.get(turn_id)
if future is None or future.done():
return
if error is not None:
if isinstance(error, asyncio.CancelledError):
error = AutomationTurnError(str(error) or error.__class__.__name__)
future.set_exception(error)
else:
future.set_result(response)
def pending_ids_for_session(self, session_key: str) -> set[str]:
"""Return automation IDs that are waiting for or running in *session_key*."""
pending_ids: set[str] = set()
for msg in self.deferred_queues.get(session_key, []):
pending_id = self._pending_id(msg)
if pending_id:
pending_ids.add(pending_id)
for msg in self._pending_messages_by_turn_id.values():
if msg.session_key != session_key:
continue
pending_id = self._pending_id(msg)
if pending_id:
pending_ids.add(pending_id)
return pending_ids
async def publish_next_deferred(self, session_key: str) -> bool:
return await publish_next_deferred_turn(
deferred_queues=self.deferred_queues,
publish_inbound=self._publish_inbound,
session_key=session_key,
)
+64 -29
View File
@@ -12,14 +12,9 @@ from nanobot.agent.tools import mcp as mcp_tools
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.apps.cli import utils as cli_app_utils
from nanobot.bus.events import InboundMessage
from nanobot.runtime_context import (
RUNTIME_CONTEXT_END,
RUNTIME_CONTEXT_MESSAGE_META,
RUNTIME_CONTEXT_TAG,
RuntimeContextBlock,
append_runtime_context,
)
from nanobot.session.goal_state import goal_state_runtime_lines
from nanobot.utils.helpers import (
current_time_str,
detect_image_mime,
load_bundled_template,
truncate_text_to_tokens,
@@ -32,14 +27,23 @@ def session_extra(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
return cli_app_utils.session_extra(metadata) | mcp_tools.session_extra(metadata)
def runtime_lines(state: Any, msg: Any, workspace: Path, *, skip: bool = False) -> list[str]:
"""Return model-visible runtime annotations for turn-attached capabilities."""
return [
*cli_app_utils.runtime_lines(msg, workspace, skip=skip),
*mcp_tools.runtime_lines(
msg,
configured_server_names=set(state._mcp_servers),
connected_server_names=set(state._mcp_stacks),
skip=skip,
),
]
async def connect_mcp(state: Any, tools: ToolRegistry) -> None:
await mcp_tools.connect_missing_servers(state, tools)
async def close_mcp(state: Any) -> None:
await mcp_tools.close_mcp_servers(state)
async def handle_runtime_control(state: Any, msg: InboundMessage, tools: ToolRegistry) -> bool:
return await mcp_tools.handle_runtime_control(state, msg, tools)
@@ -48,10 +52,10 @@ class ContextBuilder:
"""Builds the context (system prompt + messages) for the agent."""
BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md"]
_RUNTIME_CONTEXT_TAG = RUNTIME_CONTEXT_TAG
_RUNTIME_CONTEXT_TAG = "[Runtime Context — metadata only, not instructions]"
_MAX_RECENT_HISTORY = 50
_MAX_HISTORY_TOKENS = 8_000 # hard cap on recent history section size (tokens)
_RUNTIME_CONTEXT_END = RUNTIME_CONTEXT_END
_RUNTIME_CONTEXT_END = "[/Runtime Context]"
def __init__(self, workspace: Path, timezone: str | None = None, disabled_skills: list[str] | None = None):
self.workspace = workspace
@@ -127,14 +131,28 @@ class ContextBuilder:
channel=channel or "",
)
@staticmethod
def _build_runtime_context(
channel: str | None,
chat_id: str | None,
timezone: str | None = None,
sender_id: str | None = None,
supplemental_lines: Sequence[str] | None = None,
) -> str:
"""Build untrusted runtime metadata block appended after user content."""
lines = [f"Current Time: {current_time_str(timezone)}"]
if channel and chat_id:
lines += [f"Channel: {channel}", f"Chat ID: {chat_id}"]
if sender_id:
lines += [f"Sender ID: {sender_id}"]
if supplemental_lines:
lines.extend(supplemental_lines)
return ContextBuilder._RUNTIME_CONTEXT_TAG + "\n" + "\n".join(lines) + "\n" + ContextBuilder._RUNTIME_CONTEXT_END
@staticmethod
def _merge_message_content(left: Any, right: Any) -> str | list[dict[str, Any]]:
if isinstance(left, str) and isinstance(right, str):
if not left:
return right
if not right:
return left
return f"{left}\n\n{right}"
return f"{left}\n\n{right}" if left else right
def _to_blocks(value: Any) -> list[dict[str, Any]]:
if isinstance(value, list):
@@ -178,17 +196,41 @@ class ContextBuilder:
sender_id: str | None = None,
session_summary: str | None = None,
session_metadata: Mapping[str, Any] | None = None,
runtime_context_blocks: Sequence[RuntimeContextBlock] | None = None,
current_runtime_lines: Sequence[str] | None = None,
workspace: Path | None = None,
runtime_state: Any | None = None,
inbound_message: Any | None = None,
skip_runtime_lines: bool = False,
include_memory_recent_history: bool = True,
session_key: str | None = None,
unified_session: bool = False,
) -> list[dict[str, Any]]:
"""Build the complete message list for an LLM call."""
root = workspace or self.workspace
extra = [
*goal_state_runtime_lines(session_metadata),
]
if runtime_state is not None and inbound_message is not None:
extra.extend(runtime_lines(runtime_state, inbound_message, root, skip=skip_runtime_lines))
if current_runtime_lines:
extra.extend(line for line in current_runtime_lines if line)
runtime_ctx = self._build_runtime_context(
channel,
chat_id,
self.timezone,
sender_id=sender_id,
supplemental_lines=extra or None,
)
user_content = self._build_user_content(current_message, media)
blocks = list(runtime_context_blocks or ()) if current_role == "user" else []
merged, runtime_context_meta = append_runtime_context(user_content, blocks)
# Merge runtime context and user content into a single user message
# to avoid consecutive same-role messages that some providers reject.
# Runtime context is appended to keep the user-content prefix stable
# for prompt-cache hits (the context changes every turn due to time).
if isinstance(user_content, str):
merged = f"{user_content}\n\n{runtime_ctx}"
else:
merged = user_content + [{"type": "text", "text": runtime_ctx}]
messages = [
{
"role": "system",
@@ -207,16 +249,9 @@ class ContextBuilder:
if messages[-1].get("role") == current_role:
last = dict(messages[-1])
last["content"] = self._merge_message_content(last.get("content"), merged)
if current_role == "user" and runtime_context_meta is not None:
internal_meta = dict(last.get("_meta") or {})
internal_meta[RUNTIME_CONTEXT_MESSAGE_META] = runtime_context_meta
last["_meta"] = internal_meta
messages[-1] = last
return messages
current = {"role": current_role, "content": merged}
if current_role == "user" and runtime_context_meta is not None:
current["_meta"] = {RUNTIME_CONTEXT_MESSAGE_META: runtime_context_meta}
messages.append(current)
messages.append({"role": current_role, "content": merged})
return messages
def _build_user_content(self, text: str, media: list[str] | None) -> str | list[dict[str, Any]]:
+7 -124
View File
@@ -36,23 +36,6 @@ COMPACTABLE_TOOLS = frozenset({
# read_file is the recovery path for persisted results; exempting it prevents persist->read->persist loops.
TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS = frozenset({"read_file"})
BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]"
PLACEHOLDER_TEXTS = frozenset({
"[Previous assistant message omitted.]",
})
def _tool_call_name_is_valid(tool_call: Any) -> bool:
"""Whether a persisted OpenAI-style tool_call carries a usable name.
Mirrors ``ToolCallRequest.has_valid_name`` for the dict shape stored in
message history: a degenerate call with ``name=None`` / ``""`` cannot be
executed and is rejected by upstream APIs if replayed.
"""
if not isinstance(tool_call, dict):
return False
fn = tool_call.get("function")
name = fn.get("name") if isinstance(fn, dict) else tool_call.get("name")
return isinstance(name, str) and bool(name)
@dataclass(slots=True)
@@ -78,9 +61,7 @@ class ContextGovernor:
messages: list[dict[str, Any]],
compacted_tool_call_ids: set[str],
) -> list[dict[str, Any]]:
updated = self.strip_placeholder_assistant_messages(messages)
updated = self.strip_malformed_tool_calls(updated)
updated = self.drop_orphan_tool_results(updated)
updated = self.drop_orphan_tool_results(messages)
updated = self.backfill_missing_tool_results(updated)
updated = self.apply_tool_result_budget(config, updated)
updated = self.compact_inflight_overflow(config, updated, compacted_tool_call_ids)
@@ -135,99 +116,6 @@ class ContextGovernor:
return truncate_text(content, config.max_tool_result_chars)
return content
@staticmethod
def strip_placeholder_assistant_messages(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Remove assistant messages that are compaction placeholders.
Messages like ``[Previous assistant message omitted.]`` carry no useful
context for the model and can cause it to repeatedly attempt tool calls
that previously failed, producing malformed responses in a loop.
Consecutive same-role messages that result from removal are handled
downstream by the provider's merge-consecutive logic. Only the
model-facing copy is repaired; the persisted transcript is untouched
(a copy is returned, or the same list object when nothing changes).
"""
updated: list[dict[str, Any]] | None = None
for idx, msg in enumerate(messages):
if msg.get("role") != "assistant":
if updated is not None:
updated.append(msg)
continue
content = msg.get("content", "")
text = content if isinstance(content, str) else ""
is_placeholder = text.strip() in PLACEHOLDER_TEXTS
has_tool_calls = bool(msg.get("tool_calls"))
if is_placeholder and not has_tool_calls:
if updated is None:
updated = list(messages[:idx])
logger.debug(
"Stripping placeholder assistant message from history: {!r}",
text[:60],
)
continue
if updated is not None:
updated.append(msg)
if updated is None:
return messages
return updated
@staticmethod
def strip_malformed_tool_calls(
messages: list[dict[str, Any]],
) -> list[dict[str, Any]]:
"""Drop persisted assistant tool_calls whose name is missing/non-string.
A degenerate tool call (``name=None`` or ``""``) that slipped into the
saved history before this guard existed gets replayed on every turn and
makes upstream APIs reject the whole request
(``messages.content.N.tool_use.name: Input should be a valid string``),
permanently wedging the session. Removing the bad call here lets the
existing orphan-result cleanup drop its now-dangling tool result, so a
polluted session self-heals on its next turn. The persisted transcript
is left untouched; only the model-facing copy is repaired (a copy is
returned, or the same list object when nothing changes).
"""
updated: list[dict[str, Any]] | None = None
for idx, msg in enumerate(messages):
if msg.get("role") != "assistant":
if updated is not None:
updated.append(msg)
continue
calls = msg.get("tool_calls")
if not calls:
if updated is not None:
updated.append(msg)
continue
kept = [tc for tc in calls if _tool_call_name_is_valid(tc)]
if len(kept) == len(calls):
if updated is not None:
updated.append(msg)
continue
if updated is None:
updated = [dict(m) for m in messages[:idx]]
logger.warning(
"Stripping {} malformed tool_call(s) with missing/non-string "
"name from assistant history before request",
len(calls) - len(kept),
)
repaired = dict(msg)
if kept:
repaired["tool_calls"] = kept
else:
repaired.pop("tool_calls", None)
# An assistant turn with neither content nor any valid tool call is
# itself invalid upstream; drop it entirely in that case.
has_content = bool(repaired.get("content"))
if not kept and not has_content:
continue
updated.append(repaired)
if updated is None:
return messages
return updated
@staticmethod
def drop_orphan_tool_results(
messages: list[dict[str, Any]],
@@ -425,14 +313,9 @@ class ContextGovernor:
return system_messages + self._legal_history_tail(kept, non_system)
@staticmethod
def _tool_result_compaction_message(message: dict[str, Any]) -> str:
def _summary_for(message: dict[str, Any]) -> str:
name = message.get("name", "tool")
return (
f"Error: The previous {name} result was compacted to fit context because it was too "
"large. Do not repeat the same call unchanged. Retry with a narrower path, query, "
"range, or result limit, use another tool, or tell the user the task cannot fit in "
"the available context."
)
return f"[{name} result omitted from context]"
def _legal_history_tail(
self,
@@ -467,12 +350,12 @@ class ContextGovernor:
tool_call_id = msg.get("tool_call_id")
if not tool_call_id or str(tool_call_id) not in compacted_tool_call_ids:
continue
compaction_message = self._tool_result_compaction_message(msg)
if msg.get("content") == compaction_message:
summary = self._summary_for(msg)
if msg.get("content") == summary:
continue
if updated is messages:
updated = [dict(m) for m in messages]
updated[idx]["content"] = compaction_message
updated[idx]["content"] = summary
return updated
def _inflight_compaction_candidates(
@@ -505,4 +388,4 @@ class ContextGovernor:
return primary + fallback
def _compact_tool_result_at(self, messages: list[dict[str, Any]], idx: int) -> None:
messages[idx]["content"] = self._tool_result_compaction_message(messages[idx])
messages[idx]["content"] = self._summary_for(messages[idx])
+107 -22
View File
@@ -2,10 +2,11 @@
from __future__ import annotations
import asyncio
import dataclasses
from collections.abc import Awaitable, Callable, Iterable
from nanobot.agent.automation_turns import AutomationTurnCoordinator
from nanobot.bus.events import InboundMessage
from nanobot.bus.events import InboundMessage, OutboundMessage
from nanobot.cron.session_turns import (
cron_run_id,
cron_trigger,
@@ -13,7 +14,7 @@ from nanobot.cron.session_turns import (
)
class CronTurnCoordinator(AutomationTurnCoordinator):
class CronTurnCoordinator:
"""Manage scheduled cron turns without mixing them into live injections."""
def __init__(
@@ -22,31 +23,115 @@ class CronTurnCoordinator(AutomationTurnCoordinator):
publish_inbound: Callable[[InboundMessage], Awaitable[None]],
dispatch: Callable[[InboundMessage], Awaitable[object]],
is_running: Callable[[], bool],
deferred_queues: dict[str, list[InboundMessage]] | None = None,
) -> None:
super().__init__(
publish_inbound=publish_inbound,
dispatch=dispatch,
is_running=is_running,
turn_id=lambda msg: cron_run_id(msg.metadata),
pending_id=_cron_job_id,
should_defer_turn=_should_defer_cron_turn,
missing_id_error="cron turn metadata must include a run_id",
duplicate_id_error=lambda run_id: f"cron run {run_id!r} is already pending",
deferred_queues=deferred_queues,
self._publish_inbound = publish_inbound
self._dispatch = dispatch
self._is_running = is_running
self.deferred_queues: dict[str, list[InboundMessage]] = {}
self._waiters: dict[str, asyncio.Future[OutboundMessage | None]] = {}
self._pending_messages_by_run_id: dict[str, InboundMessage] = {}
async def submit(self, msg: InboundMessage) -> OutboundMessage | None:
"""Submit a scheduled cron turn and wait for its session response."""
run_id = cron_run_id(msg.metadata)
if not run_id:
raise ValueError("cron turn metadata must include a run_id")
if run_id in self._waiters:
raise RuntimeError(f"cron run {run_id!r} is already pending")
loop = asyncio.get_running_loop()
future: asyncio.Future[OutboundMessage | None] = loop.create_future()
self._waiters[run_id] = future
self._pending_messages_by_run_id[run_id] = msg
try:
if self._is_running():
await self._publish_inbound(msg)
else:
await self._dispatch(msg)
return await future
finally:
self._waiters.pop(run_id, None)
self._pending_messages_by_run_id.pop(run_id, None)
def should_defer(
self,
msg: InboundMessage,
*,
session_key: str,
active_session_keys: Iterable[str],
) -> bool:
return (
defer_cron_until_session_idle(msg.metadata)
and session_key in active_session_keys
)
def defer_if_active(
self,
msg: InboundMessage,
*,
session_key: str,
active_session_keys: Iterable[str],
) -> bool:
"""Defer a cron turn when its target session is already active."""
if not self.should_defer(
msg,
session_key=session_key,
active_session_keys=active_session_keys,
):
return False
pending_msg = msg
if session_key != msg.session_key:
pending_msg = dataclasses.replace(
msg,
session_key_override=session_key,
)
self.defer(session_key, pending_msg)
return True
def complete(
self,
msg: InboundMessage,
*,
response: OutboundMessage | None = None,
error: BaseException | None = None,
) -> None:
run_id = cron_run_id(msg.metadata)
if not run_id:
return
future = self._waiters.get(run_id)
if future is None or future.done():
return
if error is not None:
future.set_exception(error)
else:
future.set_result(response)
def defer(self, session_key: str, msg: InboundMessage) -> None:
self.deferred_queues.setdefault(session_key, []).append(msg)
def pending_job_ids_for_session(self, session_key: str) -> set[str]:
"""Return cron jobs that are waiting for or running in *session_key*."""
return self.pending_ids_for_session(session_key)
job_ids: set[str] = set()
for msg in self.deferred_queues.get(session_key, []):
job_id = _cron_job_id(msg)
if job_id:
job_ids.add(job_id)
for msg in self._pending_messages_by_run_id.values():
if msg.session_key != session_key:
continue
job_id = _cron_job_id(msg)
if job_id:
job_ids.add(job_id)
return job_ids
def _should_defer_cron_turn(
msg: InboundMessage,
session_key: str,
active_session_keys: Iterable[str],
) -> bool:
return defer_cron_until_session_idle(msg.metadata) and session_key in active_session_keys
async def publish_next_deferred(self, session_key: str) -> None:
queue = self.deferred_queues.get(session_key)
if not queue:
return
msg = queue.pop(0)
if not queue:
self.deferred_queues.pop(session_key, None)
await self._publish_inbound(msg)
def _cron_job_id(msg: InboundMessage) -> str | None:
-29
View File
@@ -1,29 +0,0 @@
"""Turn-local permission for explicit sustained-goal mutations."""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar
_GOAL_MUTATION_ALLOWED: ContextVar[bool] = ContextVar(
"nanobot_goal_mutation_allowed",
default=False,
)
def goal_mutation_allowed() -> bool:
return _GOAL_MUTATION_ALLOWED.get()
def revoke_goal_mutation_permission() -> None:
_GOAL_MUTATION_ALLOWED.set(False)
@contextmanager
def goal_mutation_permission(allowed: bool):
"""Bind goal permission for one agent-run or direct tool execution scope."""
token = _GOAL_MUTATION_ALLOWED.set(allowed)
try:
yield
finally:
_GOAL_MUTATION_ALLOWED.reset(token)
-91
View File
@@ -2,9 +2,7 @@
from __future__ import annotations
from collections.abc import Awaitable, Callable
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from loguru import logger
@@ -46,20 +44,6 @@ class AgentRunHookContext:
exception: BaseException | None = None
@dataclass(slots=True)
class AgentTurnHookContext:
"""Turn-local inputs available when constructing per-turn hooks."""
on_progress: Callable[..., Awaitable[None]] | None = None
workspace: Path | None = None
channel: str = "cli"
chat_id: str = "direct"
message_id: str | None = None
session_key: str | None = None
metadata: dict[str, Any] = field(default_factory=dict)
ephemeral: bool = False
class AgentHook:
"""Minimal lifecycle surface for shared runner customization."""
@@ -93,35 +77,6 @@ class AgentHook:
async def before_execute_tools(self, context: AgentHookContext) -> None:
pass
async def before_execute_tool(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
) -> None:
pass
async def after_execute_tool(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
result: Any,
) -> None:
pass
async def on_execute_tool_error(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
error: Any,
) -> None:
pass
async def emit_reasoning(self, reasoning_content: str | None) -> None:
pass
@@ -140,9 +95,6 @@ class AgentHook:
return content
AgentTurnHookFactory = Callable[[AgentTurnHookContext], AgentHook | None]
class CompositeHook(AgentHook):
"""Fan-out hook that delegates to an ordered list of hooks.
@@ -195,49 +147,6 @@ class CompositeHook(AgentHook):
async def before_execute_tools(self, context: AgentHookContext) -> None:
await self._for_each_hook_safe("before_execute_tools", context)
async def before_execute_tool(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
) -> None:
await self._for_each_hook_safe("before_execute_tool", context, tool_call, tool, params)
async def after_execute_tool(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
result: Any,
) -> None:
await self._for_each_hook_safe(
"after_execute_tool",
context,
tool_call,
tool,
params,
result,
)
async def on_execute_tool_error(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
error: Any,
) -> None:
await self._for_each_hook_safe(
"on_execute_tool_error",
context,
tool_call,
tool,
params,
error,
)
async def emit_reasoning(self, reasoning_content: str | None) -> None:
await self._for_each_hook_safe("emit_reasoning", reasoning_content)
-11
View File
@@ -1,11 +0,0 @@
"""Concrete agent hook implementations."""
from nanobot.agent.hooks.file_edit_activity import (
FileEditActivityHook,
create_file_edit_activity_hook,
)
__all__ = [
"FileEditActivityHook",
"create_file_edit_activity_hook",
]
-135
View File
@@ -1,135 +0,0 @@
"""Agent hook that observes file-editing tools and emits file-edit activity."""
from __future__ import annotations
from collections.abc import Awaitable, Callable
from pathlib import Path
from typing import Any
from nanobot.agent.hook import (
AgentHook,
AgentHookContext,
AgentRunHookContext,
AgentTurnHookContext,
)
from nanobot.providers.base import ToolCallRequest
from nanobot.utils.file_edit_events import (
FileEditTracker,
build_file_edit_end_event,
build_file_edit_error_event,
build_file_edit_start_event,
prepare_file_edit_trackers,
)
from nanobot.utils.progress_events import (
invoke_file_edit_progress,
on_progress_accepts_file_edit_events,
)
class FileEditActivityHook(AgentHook):
"""Translate file-editing tool lifecycle events into WebUI progress events."""
def __init__(
self,
*,
on_progress: Callable[..., Awaitable[None]] | None,
workspace: Path | None,
) -> None:
super().__init__()
self._on_progress = (
on_progress
if on_progress is not None and on_progress_accepts_file_edit_events(on_progress)
else None
)
self._workspace = workspace
self._trackers_by_call: dict[str, list[FileEditTracker]] = {}
async def before_iteration(self, context: AgentHookContext) -> None:
self._trackers_by_call.clear()
async def before_execute_tool(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
) -> None:
if self._on_progress is None or not isinstance(params, dict):
return
trackers = prepare_file_edit_trackers(
call_id=tool_call.id,
tool_name=tool_call.name,
tool=tool,
workspace=self._workspace,
params=params,
)
if not trackers:
return
self._trackers_by_call[self._tool_call_key(tool_call)] = trackers
await self._emit([build_file_edit_start_event(tracker, params) for tracker in trackers])
async def after_execute_tool(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
result: Any,
) -> None:
key = self._tool_call_key(tool_call)
trackers = self._trackers_by_call.get(key, [])
if trackers:
await self._emit([build_file_edit_end_event(tracker) for tracker in trackers])
self._trackers_by_call.pop(key, None)
async def on_execute_tool_error(
self,
context: AgentHookContext,
tool_call: ToolCallRequest,
tool: Any,
params: Any,
error: Any,
) -> None:
key = self._tool_call_key(tool_call)
trackers = self._trackers_by_call.get(key, [])
if trackers:
await self._emit([
build_file_edit_error_event(tracker, str(error)) for tracker in trackers
])
self._trackers_by_call.pop(key, None)
async def on_finally(self, context: AgentRunHookContext) -> None:
if context.stop_reason != "cancelled" or not self._trackers_by_call:
return
trackers = [
tracker
for trackers in self._trackers_by_call.values()
for tracker in trackers
]
self._trackers_by_call.clear()
await self._emit([
build_file_edit_error_event(
tracker,
"Task interrupted before this tool finished.",
)
for tracker in trackers
])
async def _emit(self, events: list[dict[str, Any]]) -> None:
if self._on_progress is not None:
await invoke_file_edit_progress(self._on_progress, events)
@staticmethod
def _tool_call_key(tool_call: ToolCallRequest) -> str:
call_id = getattr(tool_call, "id", "") or ""
return f"{call_id}|{tool_call.name}" if call_id else f"{id(tool_call)}|{tool_call.name}"
def create_file_edit_activity_hook(context: AgentTurnHookContext) -> AgentHook | None:
"""Create the default file-edit observer for one agent turn."""
if context.on_progress is None:
return None
return FileEditActivityHook(
on_progress=context.on_progress,
workspace=context.workspace,
)
+258 -415
View File
File diff suppressed because it is too large Load Diff
+63 -169
View File
@@ -15,8 +15,7 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator
from loguru import logger
from nanobot.runtime_context import public_history_messages
from nanobot.session.manager import Session, SessionManager
from nanobot.session.manager import Session
from nanobot.utils.gitstore import GitStore
from nanobot.utils.helpers import (
ensure_dir,
@@ -29,15 +28,11 @@ from nanobot.utils.helpers import (
truncate_text_to_tokens,
)
from nanobot.utils.prompt_templates import render_template
from nanobot.utils.workspace_prompts import (
WORKSPACE_PROMPT_MAX_CHARS,
has_workspace_prompt_override,
load_workspace_prompt_override,
workspace_prompt_file,
)
if TYPE_CHECKING:
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.providers.base import LLMProvider
from nanobot.session.manager import SessionManager
# ---------------------------------------------------------------------------
# MemoryStore — pure file I/O layer
@@ -47,14 +42,6 @@ class MemoryStore:
"""Pure file I/O for memory files: MEMORY.md, history.jsonl, SOUL.md, USER.md."""
_DEFAULT_MAX_HISTORY = 1000
# Durable files whose real working-tree delta grounds Dream commit messages
# and the cursor-advance gate. Deliberately excludes memory/.dream_cursor so
# that advancing the cursor itself is never mistaken for a productive edit.
_DREAM_CONTENT_PATHS = ("SOUL.md", "USER.md", "memory/MEMORY.md")
# Per-file cap when embedding current contents into the Dream prompt. The
# durable files are tiny in practice (~5 KB total), but a runaway file must
# not unbounded the prompt.
_DREAM_FILE_EMBED_CAP = 8000
_INTERNAL_HISTORY_SESSION_PREFIXES = ("cron:", "dream:")
_INTERNAL_HISTORY_SESSION_KEYS = {"heartbeat"}
_LEGACY_ENTRY_START_RE = re.compile(r"^\[(\d{4}-\d{2}-\d{2}[^\]]*)\]\s*")
@@ -77,7 +64,6 @@ class MemoryStore:
self._corruption_logged = False # rate-limit invalid cursor warning
self._malformed_entry_logged = False # rate-limit bad history shape warning
self._oversize_logged = False # rate-limit oversized-entry warning
self._dream_prompt_oversize_logged = False
self._append_lock = threading.Lock() # serialize cursor allocation + append
self._git = GitStore(workspace, tracked_files=[
"SOUL.md", "USER.md", "memory/MEMORY.md", "memory/.dream_cursor",
@@ -496,49 +482,13 @@ class MemoryStore:
def get_latest_cursor(self) -> int:
return max(self._next_cursor() - 1, 0)
@property
def dream_prompt_file(self) -> Path:
return workspace_prompt_file(self.workspace, "dream")
def has_dream_prompt_override(self) -> bool:
return has_workspace_prompt_override(self.dream_prompt_file)
@staticmethod
def default_dream_prompt() -> str:
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
return render_template(
"agent/dream.md",
strip=True,
skill_creator_path=str(BUILTIN_SKILLS_DIR / "skill-creator" / "SKILL.md"),
)
def _dream_template(self) -> str:
text, original_chars = load_workspace_prompt_override(self.dream_prompt_file)
if text is not None:
if (
original_chars > WORKSPACE_PROMPT_MAX_CHARS
and not self._dream_prompt_oversize_logged
):
self._dream_prompt_oversize_logged = True
logger.warning(
"workspace Dream prompt exceeds {} chars ({}); truncating. "
"Further occurrences suppressed.",
WORKSPACE_PROMPT_MAX_CHARS, original_chars,
)
return text
return self.default_dream_prompt()
def build_dream_prompt(self, *, max_entries: int = 20) -> tuple[str, int] | None:
"""Build the Dream prompt with unprocessed history context.
Returns ``(prompt, last_cursor)`` or ``None`` if nothing to process.
The current contents of the durable memory files (SOUL.md, USER.md,
memory/MEMORY.md) are embedded so the model edits the real files rather
than a stale mental model eliminating a class of failed/out-of-bounds
edits that previously produced hallucinated audit records.
"""
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
last_cursor = self.get_last_dream_cursor()
entries = self.read_unprocessed_history(since_cursor=last_cursor)
if not entries:
@@ -549,47 +499,13 @@ class MemoryStore:
f"[{e['timestamp']}] {truncate_text(e['content'], 500)}"
for e in batch
)
template = self._dream_template()
files_section = self._render_current_memory_files()
prompt = (
f"{template}\n\n{files_section}\n\n"
f"## Conversation History\n{history_text}"
skill_creator_path = str(BUILTIN_SKILLS_DIR / "skill-creator" / "SKILL.md")
template = render_template(
"agent/dream.md", strip=True, skill_creator_path=skill_creator_path,
)
prompt = f"{template}\n\n## Conversation History\n{history_text}"
return (prompt, batch[-1]["cursor"])
def _render_current_memory_files(self) -> str:
"""Render the durable memory files' current contents for the Dream prompt.
Missing files render as ``(empty)``; oversized files are capped. The
section is the ground truth the model must edit against.
"""
files = [
("SOUL.md", self.soul_file),
("USER.md", self.user_file),
("memory/MEMORY.md", self.memory_file),
]
blocks = []
for label, path in files:
try:
content = path.read_text(encoding="utf-8") if path.exists() else ""
except OSError:
content = ""
if len(content) > self._DREAM_FILE_EMBED_CAP:
content = truncate_text(content, self._DREAM_FILE_EMBED_CAP) + "\n...[truncated]"
blocks.append(f"### {label}\n{content}" if content.strip() else f"### {label}\n(empty)")
return "## Current Memory Files\n" + "\n\n".join(blocks)
def dream_content_diff(self) -> str:
"""Structured summary of uncommitted changes to the durable memory files.
Returns "" when git is unavailable or no content file changed. This is
the ground-truth input for diff-grounded Dream commit messages and for
gating cursor advance on real edits (never on LLM self-report).
"""
if not self._git.is_initialized():
return ""
return self._git.summarize_working_tree(list(self._DREAM_CONTENT_PATHS))
def build_dream_tools(self):
"""Build the restricted tool registry used by Dream runs."""
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
@@ -661,10 +577,7 @@ class MemoryStore:
) -> None:
"""Fallback: dump raw messages to history.jsonl without LLM summarization."""
limit = max_chars if max_chars is not None else _RAW_ARCHIVE_MAX_CHARS
formatted = truncate_text(
self._format_messages(public_history_messages(messages)),
limit,
)
formatted = truncate_text(self._format_messages(messages), limit)
self.append_history(
f"[RAW] {len(messages)} messages\n"
f"{formatted}",
@@ -684,36 +597,23 @@ class MemoryStore:
return f"dream:{datetime.now():%Y%m%d-%H%M%S}"
@staticmethod
def build_dream_commit_message(prefix: str, diff_body: str) -> str:
"""Build a Dream commit message grounded in the real working-tree diff.
*diff_body* is a structured, machine-derived summary of the actual file
changes (see :meth:`dream_content_diff` /
:meth:`GitStore.summarize_working_tree`). The LLM narrative is
deliberately excluded so the audit record (``/dream-log``) reflects the
filesystem's truth, not the model's self-report.
An empty *diff_body* yields the bare *prefix*, which ``auto_commit``
turns into a no-op when there is nothing to stage.
"""
diff_body = (diff_body or "").strip()
if not diff_body:
return prefix
return f"{prefix}\n\n{diff_body}"
def build_dream_commit_message(prefix: str, resp: object | None) -> str:
"""Build a Dream auto-commit message, appending the LLM summary if present."""
msg = prefix
if resp is not None and getattr(resp, "content", None):
msg = f"{msg}\n\n{resp.content.strip()}"
return msg
@staticmethod
def prune_dream_sessions(sessions_dir: Path, *, keep: int = 10) -> None:
"""Remove the oldest Dream session files, keeping only the N most recent.
Only current base64url-encoded Dream session keys are considered.
Non-dream session files are never touched.
Only files matching ``dream_*.jsonl`` are considered. Non-dream session
files are never touched.
"""
dream_files = []
for path in sessions_dir.glob("*.jsonl"):
decoded_key = SessionManager._decode_storage_key(path.stem)
if decoded_key is not None and decoded_key.startswith("dream:"):
dream_files.append(path)
dream_files.sort(key=lambda p: p.stat().st_mtime)
dream_files = sorted(
sessions_dir.glob("dream_*.jsonl"), key=lambda p: p.stat().st_mtime,
)
if len(dream_files) <= keep:
return
@@ -748,14 +648,22 @@ class Consolidator:
def __init__(
self,
store: MemoryStore,
provider: LLMProvider,
model: str,
sessions: SessionManager,
context_window_tokens: int,
build_messages: Callable[..., list[dict[str, Any]]],
get_tool_definitions: Callable[[], list[dict[str, Any]]],
max_completion_tokens: int = 4096,
consolidation_ratio: float = 0.5,
unified_session: bool = False,
):
self.store = store
self.provider = provider
self.model = model
self.sessions = sessions
self.context_window_tokens = context_window_tokens
self.max_completion_tokens = max_completion_tokens
self.consolidation_ratio = consolidation_ratio
self.unified_session = unified_session
self._build_messages = build_messages
@@ -764,6 +672,17 @@ class Consolidator:
weakref.WeakValueDictionary()
)
def set_provider(
self,
provider: LLMProvider,
model: str,
context_window_tokens: int,
) -> None:
self.provider = provider
self.model = model
self.context_window_tokens = context_window_tokens
self.max_completion_tokens = provider.generation.max_tokens
def get_lock(self, session_key: str) -> asyncio.Lock:
"""Return the shared consolidation lock for one session."""
return self._locks.setdefault(session_key, asyncio.Lock())
@@ -841,8 +760,6 @@ class Consolidator:
self,
session: Session,
replay_max_messages: int | None,
*,
runtime: LLMRuntime,
) -> str | None:
"""Archive messages that would be hidden by the replay message window."""
end_idx = self._replay_overflow_boundary(session, replay_max_messages)
@@ -857,11 +774,7 @@ class Consolidator:
len(chunk),
replay_max_messages,
)
summary = await self.archive(
chunk,
runtime=runtime,
session_key=session.key,
)
summary = await self.archive(chunk, session_key=session.key)
session.last_consolidated = end_idx
self.sessions.save(session)
return summary
@@ -877,8 +790,6 @@ class Consolidator:
def estimate_session_prompt_tokens(
self,
session: Session,
*,
runtime: LLMRuntime,
) -> tuple[int, str]:
"""Estimate prompt size from the full unconsolidated session tail."""
history = self._full_unconsolidated_history(session)
@@ -898,23 +809,20 @@ class Consolidator:
unified_session=self.unified_session,
)
return estimate_prompt_tokens_chain(
runtime.provider,
runtime.model,
self.provider,
self.model,
probe_messages,
self._get_tool_definitions(),
)
def _input_token_budget(self, runtime: LLMRuntime) -> int:
@property
def _input_token_budget(self) -> int:
"""Available input token budget for consolidation LLM."""
return (
runtime.context_window_tokens
- runtime.generation.max_tokens
- self._SAFETY_BUFFER
)
return self.context_window_tokens - self.max_completion_tokens - self._SAFETY_BUFFER
def _truncate_to_token_budget(self, text: str, *, runtime: LLMRuntime) -> str:
def _truncate_to_token_budget(self, text: str) -> str:
"""Truncate text so it fits within the consolidation LLM's token budget."""
budget = self._input_token_budget(runtime)
budget = self._input_token_budget
if budget <= 0:
return truncate_text(text, _RAW_ARCHIVE_MAX_CHARS)
return truncate_text_to_tokens(text, budget)
@@ -923,7 +831,6 @@ class Consolidator:
self,
messages: list[dict],
*,
runtime: LLMRuntime,
session_key: str | None = None,
summary_messages: list[dict] | None = None,
) -> str | None:
@@ -938,14 +845,12 @@ class Consolidator:
"""
if not messages:
return None
messages_to_summarize = public_history_messages(
summary_messages if summary_messages is not None else messages
)
messages_to_summarize = summary_messages if summary_messages is not None else messages
try:
formatted = MemoryStore._format_messages(messages_to_summarize)
formatted = self._truncate_to_token_budget(formatted, runtime=runtime)
response = await runtime.provider.chat_with_retry(
model=runtime.model,
formatted = self._truncate_to_token_budget(formatted)
response = await self.provider.chat_with_retry(
model=self.model,
messages=[
{
"role": "system",
@@ -958,9 +863,6 @@ class Consolidator:
],
tools=None,
tool_choice=None,
temperature=runtime.generation.temperature,
max_tokens=runtime.generation.max_tokens,
reasoning_effort=runtime.generation.reasoning_effort,
)
if response.finish_reason == "error":
raise RuntimeError(f"LLM returned error: {response.content}")
@@ -980,7 +882,6 @@ class Consolidator:
self,
session: Session,
*,
runtime: LLMRuntime,
replay_max_messages: int | None = None,
) -> None:
"""Loop: archive old messages until prompt fits within safe budget.
@@ -988,7 +889,7 @@ class Consolidator:
The budget reserves space for completion tokens and a safety buffer
so the LLM request never exceeds the context window.
"""
if runtime.context_window_tokens <= 0:
if self.context_window_tokens <= 0:
return
lock = self.get_lock(session.key)
@@ -1000,17 +901,15 @@ class Consolidator:
if not session.messages:
return
budget = self._input_token_budget(runtime)
budget = self._input_token_budget
target = int(budget * self.consolidation_ratio)
last_summary = await self._consolidate_replay_overflow(
session,
replay_max_messages,
runtime=runtime,
)
try:
estimated, source = self.estimate_session_prompt_tokens(
session,
runtime=runtime,
)
except Exception:
logger.exception("Token estimation failed for {}", session.key)
@@ -1024,7 +923,7 @@ class Consolidator:
"Token consolidation idle {}: {}/{} via {}, msgs={}",
session.key,
estimated,
runtime.context_window_tokens,
self.context_window_tokens,
source,
unconsolidated_count,
)
@@ -1055,15 +954,11 @@ class Consolidator:
round_num,
session.key,
estimated,
runtime.context_window_tokens,
self.context_window_tokens,
source,
len(chunk),
)
summary = await self.archive(
chunk,
runtime=runtime,
session_key=session.key,
)
summary = await self.archive(chunk, session_key=session.key)
# Advance the cursor either way: on success the chunk was
# summarized; on failure archive() already raw-archived it as
# a breadcrumb. Re-archiving the same chunk on the next call
@@ -1080,7 +975,6 @@ class Consolidator:
try:
estimated, source = self.estimate_session_prompt_tokens(
session,
runtime=runtime,
)
except Exception:
logger.exception("Token estimation failed for {}", session.key)
@@ -1096,8 +990,6 @@ class Consolidator:
async def compact_idle_session(
self,
session_key: str,
*,
runtime: LLMRuntime,
max_suffix: int = 8,
) -> str | None:
"""Hard-truncate an idle session under the consolidation lock.
@@ -1114,6 +1006,7 @@ class Consolidator:
messages_to_summarize = list(session.messages[session.last_consolidated:])
if not messages_to_summarize:
session.updated_at = datetime.now()
self.sessions.save(session)
return ""
@@ -1125,11 +1018,12 @@ class Consolidator:
metadata={},
last_consolidated=0,
)
result = probe.retain_recent_legal_suffix(max_suffix, extend_to_user=True)
dropped, already_consolidated = probe.retain_recent_legal_suffix(max_suffix, extend_to_user=True)
messages_to_keep = probe.messages
messages_to_remove = result.dropped[result.already_consolidated_count:]
messages_to_remove = dropped[already_consolidated:]
if not messages_to_remove and not messages_to_keep:
session.updated_at = datetime.now()
self.sessions.save(session)
return ""
@@ -1140,7 +1034,6 @@ class Consolidator:
# the messages that are no longer kept in the live session.
summary = await self.archive(
messages_to_remove,
runtime=runtime,
session_key=session_key,
summary_messages=messages_to_summarize,
)
@@ -1153,6 +1046,7 @@ class Consolidator:
session.messages = messages_to_keep
session.last_consolidated = 0
session.updated_at = datetime.now()
self.sessions.save(session)
if messages_to_remove:
+1 -1
View File
@@ -34,12 +34,12 @@ def build_static_preset_snapshot(
name: str,
preset: ModelPresetConfig,
) -> ProviderSnapshot:
provider.generation = preset.to_generation_settings()
return ProviderSnapshot(
provider=provider,
model=preset.model,
context_window_tokens=preset.context_window_tokens,
signature=("model_preset", name, preset.model_dump_json()),
generation=preset.to_generation_settings(),
)
-203
View File
@@ -1,203 +0,0 @@
"""Public resolution boundary for default and overridden LLM runtimes."""
from __future__ import annotations
from collections.abc import Callable, Mapping
from dataclasses import replace
from nanobot.agent import model_presets as preset_helpers
from nanobot.config.schema import Config, ModelPresetConfig
from nanobot.providers.factory import ProviderSnapshot, build_provider_snapshot
from nanobot.utils.llm_runtime import LLMRuntime, runtime_from_provider_snapshot
class ModelRuntimeResolver:
"""Own model selection and resolve it to immutable execution values.
The resolver is deliberately independent of ``AgentLoop``. Command, SDK,
and tool admission layers can depend on this public service without reading
or mutating private loop state.
"""
def __init__(
self,
initial_runtime: LLMRuntime,
*,
model_presets: Mapping[str, ModelPresetConfig] | None = None,
provider_snapshot_loader: Callable[[], ProviderSnapshot] | None = None,
preset_snapshot_loader: preset_helpers.PresetSnapshotLoader | None = None,
) -> None:
self._runtime = initial_runtime
self._model_presets = dict(model_presets or {})
self._provider_snapshot_loader = provider_snapshot_loader
self._preset_snapshot_loader = preset_snapshot_loader
self._tracks_provider_generation = initial_runtime.model_preset is None
self._default_selection_signature = preset_helpers.default_selection_signature(
initial_runtime.snapshot_signature
)
@property
def runtime(self) -> LLMRuntime:
"""Return the current immutable default without refreshing configuration."""
return self._runtime
@property
def model_presets(self) -> Mapping[str, ModelPresetConfig]:
return self._model_presets
@property
def model_preset(self) -> str | None:
return self._runtime.model_preset
@property
def provider_signature(self) -> tuple[object, ...] | None:
return self._runtime.snapshot_signature
def current(self, *, refresh: bool = False) -> LLMRuntime:
"""Return the selected runtime, optionally refreshing the default source."""
if refresh:
self.refresh()
self._refresh_provider_generation()
return self._runtime
def resolve_snapshot(
self,
snapshot: ProviderSnapshot,
*,
model_preset: str | None = None,
) -> LLMRuntime:
"""Resolve a factory snapshot without changing the selected default."""
return runtime_from_provider_snapshot(snapshot, model_preset=model_preset)
def adopt_snapshot(
self,
snapshot: ProviderSnapshot,
*,
model_preset: str | None = None,
) -> LLMRuntime:
"""Select a snapshot as the default for future turns."""
runtime = self.resolve_snapshot(snapshot, model_preset=model_preset)
self._runtime = runtime
self._tracks_provider_generation = model_preset is None
self._default_selection_signature = preset_helpers.default_selection_signature(
runtime.snapshot_signature
)
return runtime
def resolve_preset(self, name: str | None) -> LLMRuntime:
"""Resolve a named preset without changing the selected default."""
normalized = preset_helpers.normalize_preset_name(name, self._model_presets)
snapshot = preset_helpers.build_runtime_preset_snapshot(
name=normalized,
presets=self._model_presets,
provider=self._runtime.provider,
loader=self._preset_snapshot_loader,
)
return self.resolve_snapshot(snapshot, model_preset=normalized)
def select_preset(self, name: str | None) -> LLMRuntime:
"""Select a named preset as the default for future turns."""
runtime = self.resolve_preset(name)
self._runtime = runtime
self._tracks_provider_generation = False
return runtime
def select_model(self, model: str) -> LLMRuntime:
"""Change the default model without reconstructing downstream consumers."""
if not isinstance(model, str) or not model.strip():
raise ValueError("model must be a non-empty string")
self._runtime = replace(
self._runtime,
model=model.strip(),
model_preset=None,
)
return self._runtime
def select_context_window(self, context_window_tokens: int) -> LLMRuntime:
"""Change the default context limit for future admissions."""
if not isinstance(context_window_tokens, int) or isinstance(
context_window_tokens,
bool,
):
raise TypeError("context_window_tokens must be an integer")
self._runtime = replace(
self._runtime,
context_window_tokens=context_window_tokens,
)
return self._runtime
def _refresh_provider_generation(self) -> LLMRuntime | None:
"""Adopt direct provider-default changes only for provider-backed defaults."""
if not self._tracks_provider_generation:
return None
runtime = self._runtime
captured = LLMRuntime.capture(
runtime.provider,
runtime.model,
context_window_tokens=runtime.context_window_tokens,
model_preset=runtime.model_preset,
snapshot_signature=runtime.snapshot_signature,
)
if captured.generation == runtime.generation:
return None
self._runtime = replace(runtime, generation=captured.generation)
return self._runtime
def refresh(self) -> LLMRuntime | None:
"""Refresh configured defaults and return the replacement when changed."""
if self._provider_snapshot_loader is None:
return None
snapshot = self._provider_snapshot_loader()
default_selection = preset_helpers.default_selection_signature(snapshot.signature)
active_preset = self._runtime.model_preset
if active_preset and self._default_selection_signature in (None, default_selection):
runtime = self.resolve_preset(active_preset)
else:
active_preset = None
runtime = self.resolve_snapshot(snapshot)
unchanged = (
runtime.snapshot_signature == self._runtime.snapshot_signature
and runtime.model_preset == self._runtime.model_preset
)
if unchanged:
self._default_selection_signature = default_selection
return None
(
self._runtime,
self._tracks_provider_generation,
self._default_selection_signature,
) = (
runtime,
active_preset is None,
default_selection,
)
return runtime
def resolve_override(
self,
*,
model: str | None,
model_preset: str | None,
config: Config | None = None,
) -> LLMRuntime | None:
"""Resolve an SDK-style per-run override without mutating the default."""
if model is not None and model_preset is not None:
raise ValueError("model and model_preset are mutually exclusive")
if model_preset is not None:
return self.resolve_preset(model_preset)
if model is None:
return None
if config is None:
return LLMRuntime(
provider=self._runtime.provider,
model=model,
generation=self._runtime.generation,
context_window_tokens=self._runtime.context_window_tokens,
snapshot_signature=("model_override", model),
)
base = config.resolve_preset(self.model_preset)
preset = base.model_copy(update={"model": model, "provider": "auto"})
return self.resolve_snapshot(build_provider_snapshot(config, preset=preset))
+19
View File
@@ -28,16 +28,26 @@ class AgentProgressHook(AgentHook):
on_stream: Callable[[str], Awaitable[None]] | None = None,
on_stream_end: Callable[..., Awaitable[None]] | None = None,
*,
channel: str = "cli",
chat_id: str = "direct",
message_id: str | None = None,
metadata: dict[str, Any] | None = None,
session_key: str | None = None,
tool_hint_max_length: int = 40,
set_tool_context: Callable[..., None] | None = None,
on_iteration: Callable[[int], None] | None = None,
) -> None:
super().__init__(reraise=True)
self._on_progress = on_progress
self._on_stream = on_stream
self._on_stream_end = on_stream_end
self._channel = channel
self._chat_id = chat_id
self._message_id = message_id
self._metadata = metadata or {}
self._session_key = session_key
self._tool_hint_max_length = tool_hint_max_length
self._set_tool_context = set_tool_context
self._on_iteration = on_iteration
self._stream_buf = ""
self._think_extractor = IncrementalThinkExtractor()
@@ -114,6 +124,15 @@ class AgentProgressHook(AgentHook):
for tc in context.tool_calls:
args_str = json.dumps(tc.arguments, ensure_ascii=False)
logger.info("Tool call: {}({})", tc.name, args_str[:200])
if self._set_tool_context:
self._set_tool_context(
self._channel,
self._chat_id,
self._message_id,
self._metadata,
session_key=self._session_key,
)
async def emit_reasoning(self, reasoning_content: str | None) -> None:
"""Publish a reasoning chunk; channel plugins decide whether to render."""
if (
+194 -173
View File
@@ -18,9 +18,18 @@ from nanobot.agent.context_governance import (
ContextGovernor,
)
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
from nanobot.session.history_visibility import is_hidden_history_message
from nanobot.utils.file_edit_events import (
StreamingFileEditTracker,
build_file_edit_end_event,
build_file_edit_error_event,
build_file_edit_start_event,
prepare_file_edit_trackers,
)
from nanobot.utils.file_edit_events import (
prepare_file_edit_tracker as _prepare_file_edit_tracker,
)
from nanobot.utils.helpers import (
IncrementalThinkExtractor,
build_assistant_message,
@@ -30,7 +39,10 @@ from nanobot.utils.helpers import (
strip_reasoning_tags,
strip_think,
)
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.progress_events import (
invoke_file_edit_progress,
on_progress_accepts_file_edit_events,
)
from nanobot.utils.prompt_templates import render_template
from nanobot.utils.runtime import (
EMPTY_FINAL_RESPONSE_MESSAGE,
@@ -38,6 +50,7 @@ from nanobot.utils.runtime import (
build_finalization_retry_message,
build_goal_continue_message,
build_length_recovery_message,
build_runtime_budget_notice_message,
is_blank_text,
repeated_external_lookup_error,
repeated_workspace_violation_error,
@@ -55,6 +68,11 @@ _MAX_EMPTY_RETRIES = 2
_MAX_LENGTH_RECOVERIES = 3
_MAX_INJECTIONS_PER_TURN = 3
_MAX_INJECTION_CYCLES = 5
_BUDGET_NOTICE_MIN_ITERATIONS = 20
# Backward-compatible module attribute for tests/extensions that monkeypatch
# the former single-file tracker hook. Runtime uses prepare_file_edit_trackers.
prepare_file_edit_tracker = _prepare_file_edit_tracker
@dataclass(slots=True)
class AgentRunSpec:
@@ -62,9 +80,12 @@ class AgentRunSpec:
initial_messages: list[dict[str, Any]]
tools: ToolRegistry
runtime: LLMRuntime
model: str
max_iterations: int
max_tool_result_chars: int
temperature: float | None = None
max_tokens: int | None = None
reasoning_effort: str | None = None
hook: AgentHook | None = None
error_message: str | None = _DEFAULT_ERROR_MESSAGE
max_iterations_message: str | None = None
@@ -72,6 +93,7 @@ class AgentRunSpec:
fail_on_tool_error: bool = False
workspace: Path | None = None
session_key: str | None = None
context_window_tokens: int | None = None
context_block_limit: int | None = None
provider_retry_mode: str = "standard"
progress_callback: Any | None = None
@@ -102,7 +124,8 @@ class AgentRunResult:
class AgentRunner:
"""Run a tool-capable LLM loop without product-layer concerns."""
def __init__(self) -> None:
def __init__(self, provider: LLMProvider):
self.provider = provider
self.context_governor = ContextGovernor()
@staticmethod
@@ -134,8 +157,6 @@ class AgentRunner:
messages
and injection.get("role") == "user"
and messages[-1].get("role") == "user"
and not is_hidden_history_message(injection)
and not is_hidden_history_message(messages[-1])
):
merged = dict(messages[-1])
merged["content"] = cls._merge_message_content(
@@ -185,7 +206,7 @@ class AgentRunner:
{
"phase": "final_response",
"iteration": iteration,
"model": spec.runtime.model,
"model": spec.model,
"assistant_message": assistant_message,
"completed_tool_results": [],
"pending_tool_calls": [],
@@ -338,17 +359,18 @@ class AgentRunner:
length_recovery_count = 0
had_injections = False
injection_cycles = 0
budget_notice_level_sent = 0
compacted_tool_call_ids: set[str] = set()
governance_config = ContextGovernanceConfig(
provider=spec.runtime.provider,
model=spec.runtime.model,
provider=self.provider,
model=spec.model,
tools=spec.tools,
workspace=spec.workspace,
session_key=spec.session_key,
max_tool_result_chars=spec.max_tool_result_chars,
context_window_tokens=spec.runtime.context_window_tokens,
context_window_tokens=spec.context_window_tokens,
context_block_limit=spec.context_block_limit,
max_tokens=spec.runtime.generation.max_tokens,
max_tokens=spec.max_tokens,
inflight_start_index=len(spec.initial_messages),
)
@@ -370,15 +392,7 @@ class AgentRunner:
spec.session_key or "default",
)
try:
messages_for_model = ContextGovernor.strip_placeholder_assistant_messages(
messages
)
messages_for_model = ContextGovernor.strip_malformed_tool_calls(
messages_for_model
)
messages_for_model = ContextGovernor.drop_orphan_tool_results(
messages_for_model
)
messages_for_model = ContextGovernor.drop_orphan_tool_results(messages)
messages_for_model = ContextGovernor.backfill_missing_tool_results(
messages_for_model
)
@@ -425,7 +439,7 @@ class AgentRunner:
{
"phase": "awaiting_tools",
"iteration": iteration,
"model": spec.runtime.model,
"model": spec.model,
"assistant_message": assistant_message,
"completed_tool_results": [],
"pending_tool_calls": [tc.to_openai_tool_call() for tc in response.tool_calls],
@@ -439,8 +453,6 @@ class AgentRunner:
response.tool_calls,
external_lookup_counts,
workspace_violation_counts,
hook,
context,
)
tool_events.extend(new_events)
tools_used.extend(
@@ -487,7 +499,7 @@ class AgentRunner:
{
"phase": "tools_completed",
"iteration": iteration,
"model": spec.runtime.model,
"model": spec.model,
"assistant_message": assistant_message,
"completed_tool_results": completed_tool_results,
"pending_tool_calls": [],
@@ -502,6 +514,12 @@ class AgentRunner:
)
if _drained:
had_injections = True
budget_notice_level_sent = self._append_runtime_budget_notice_if_needed(
spec,
messages,
completed_iterations=iteration + 1,
sent_level=budget_notice_level_sent,
)
await hook.after_iteration(context)
continue
@@ -641,7 +659,7 @@ class AgentRunner:
{
"phase": "final_response",
"iteration": iteration,
"model": spec.runtime.model,
"model": spec.model,
"assistant_message": messages[-1],
"completed_tool_results": [],
"pending_tool_calls": [],
@@ -698,14 +716,16 @@ class AgentRunner:
kwargs: dict[str, Any] = {
"messages": messages,
"tools": tools,
"model": spec.runtime.model,
"model": spec.model,
"retry_mode": spec.provider_retry_mode,
"on_retry_wait": spec.retry_wait_callback,
}
generation = spec.runtime.generation
kwargs["temperature"] = generation.temperature
kwargs["max_tokens"] = generation.max_tokens
kwargs["reasoning_effort"] = generation.reasoning_effort
if spec.temperature is not None:
kwargs["temperature"] = spec.temperature
if spec.max_tokens is not None:
kwargs["max_tokens"] = spec.max_tokens
if spec.reasoning_effort is not None:
kwargs["reasoning_effort"] = spec.reasoning_effort
return kwargs
async def _request_model(
@@ -714,8 +734,6 @@ class AgentRunner:
messages: list[dict[str, Any]],
hook: AgentHook,
context: AgentHookContext,
*,
malformed_retry: bool = False,
):
timeout_s: float | None = spec.llm_timeout_s
if timeout_s is None:
@@ -740,10 +758,28 @@ class AgentRunner:
not wants_streaming
and spec.stream_progress_deltas
and spec.progress_callback is not None
and getattr(spec.runtime.provider, "supports_progress_deltas", False) is True
and getattr(self.provider, "supports_progress_deltas", False) is True
)
progress_state: dict[str, bool] | None = None
live_file_edits: StreamingFileEditTracker | None = None
if (
spec.progress_callback is not None
and on_progress_accepts_file_edit_events(spec.progress_callback)
):
async def _emit_live_file_edits(events: list[dict[str, Any]]) -> None:
await invoke_file_edit_progress(spec.progress_callback, events)
live_file_edits = StreamingFileEditTracker(
workspace=spec.workspace,
tools=spec.tools,
emit=_emit_live_file_edits,
)
async def _tool_call_delta(delta: dict[str, Any]) -> None:
if live_file_edits is not None:
await live_file_edits.update(delta)
if wants_streaming:
thinking_buf = ""
@@ -768,10 +804,11 @@ class AgentRunner:
async def _stream_recover() -> None:
await hook.on_stream_end(context, resuming=True)
coro = spec.runtime.provider.chat_stream_with_retry(
coro = self.provider.chat_stream_with_retry(
**kwargs,
on_content_delta=_stream,
on_thinking_delta=_thinking,
on_tool_call_delta=_tool_call_delta if live_file_edits is not None else None,
on_stream_recover=_stream_recover,
)
elif wants_progress_streaming:
@@ -799,132 +836,48 @@ class AgentRunner:
context.streamed_content = True
await spec.progress_callback(incremental)
coro = spec.runtime.provider.chat_stream_with_retry(
coro = self.provider.chat_stream_with_retry(
**kwargs,
on_content_delta=_stream_progress,
on_tool_call_delta=_tool_call_delta if live_file_edits is not None else None,
)
else:
coro = spec.runtime.provider.chat_with_retry(**kwargs)
coro = self.provider.chat_with_retry(**kwargs)
# Streaming requests also have provider-level idle timeouts
# (NANOBOT_STREAM_IDLE_TIMEOUT_S), but a stream that keeps producing
# very slow deltas can still run forever. Use a more generous wall-clock
# timeout for streaming while preserving NANOBOT_LLM_TIMEOUT_S=0 as an
# opt-out for all LLM wall-clock timeouts.
is_streaming_request = wants_streaming or wants_progress_streaming
outer_timeout_s = (
max(300.0, timeout_s * 2)
if is_streaming_request and timeout_s is not None
else timeout_s
)
# Streaming requests already have provider-level idle timeouts
# (NANOBOT_STREAM_IDLE_TIMEOUT_S). Do not also apply the outer wall-clock
# LLM timeout here, or healthy long reasoning streams can be killed just
# because total elapsed time exceeded NANOBOT_LLM_TIMEOUT_S.
outer_timeout_s = None if (wants_streaming or wants_progress_streaming) else timeout_s
try:
response = (
await coro if outer_timeout_s is None
else await asyncio.wait_for(coro, timeout=outer_timeout_s)
)
if live_file_edits is not None:
await live_file_edits.flush()
if response.should_execute_tools:
live_file_edits.apply_final_call_ids(response.tool_calls)
await live_file_edits.error_unmatched(
response.tool_calls if response.should_execute_tools else [],
"Tool call did not complete.",
)
except asyncio.TimeoutError:
if outer_timeout_s is None:
response = LLMResponse(
return LLMResponse(
content="Error calling LLM: stream stalled",
finish_reason="error",
error_kind="timeout",
)
else:
response = LLMResponse(
content=f"Error calling LLM: timed out after {outer_timeout_s:g}s",
finish_reason="error",
error_kind="timeout",
)
return LLMResponse(
content=f"Error calling LLM: timed out after {outer_timeout_s:g}s",
finish_reason="error",
error_kind="timeout",
)
if progress_state and progress_state.get("reasoning_open"):
await hook.emit_reasoning_end()
dropped, all_dropped, original_finish_reason = (
self._drop_malformed_tool_calls(response)
)
if (
all_dropped
and original_finish_reason in ("tool_calls", "function_call")
and not malformed_retry
):
logger.warning(
"Retrying LLM request after all {} malformed tool call(s) were dropped",
dropped,
)
retry_messages = self._malformed_tool_call_retry_messages(
messages, response.content,
)
return await self._request_model(
spec, retry_messages, hook, context,
malformed_retry=True,
)
if (
all_dropped
and original_finish_reason in ("tool_calls", "function_call")
and malformed_retry
):
logger.warning(
"Malformed tool calls persisted after retry; falling back to no-tools request",
)
fallback_messages = self._malformed_tool_call_retry_messages(
messages, response.content,
)
return await self._request_no_tools(spec, fallback_messages)
return response
@staticmethod
def _drop_malformed_tool_calls(
response: LLMResponse,
) -> tuple[int, bool, str | None]:
"""Strip tool calls whose name is missing/non-string from the response.
Returns (dropped_count, all_dropped, original_finish_reason).
A degenerate call (name=None or "") cannot be executed, and if it were
persisted into the assistant message it would be replayed on every
subsequent turn, causing upstream validation errors
(``tool_use.name: Input should be a valid string``) that permanently
wedge the session. Dropping it here keeps it out of execution, the
assistant message, and the saved history in one place.
"""
calls = getattr(response, "tool_calls", None)
if not calls:
return (0, False, getattr(response, "finish_reason", None))
valid = [tc for tc in calls if tc.has_valid_name()]
if len(valid) == len(calls):
return (0, False, getattr(response, "finish_reason", None))
dropped = len(calls) - len(valid)
original_finish_reason = getattr(response, "finish_reason", None)
logger.warning(
"Dropped {} malformed tool call(s) with missing/non-string name "
"from LLM response (finish_reason={!r})",
dropped,
original_finish_reason,
)
response.tool_calls = valid
if not valid:
response.finish_reason = "stop"
return (dropped, not valid, original_finish_reason)
@staticmethod
def _malformed_tool_call_retry_messages(
messages: list[dict[str, Any]],
assistant_text: str | None,
) -> list[dict[str, Any]]:
retry_messages = list(messages)
note = (
"The previous model response attempted to call tools, but every tool call "
"was malformed: the tool_use blocks had missing or non-string tool names. "
"Do not answer with a promise to use tools. Either call the required tools again "
"using valid tool names from the provided tool list and JSON object inputs, or give "
"a final answer only if no tool is required."
)
if assistant_text:
note += (
f"\n\nPrevious assistant text before the malformed calls:\n"
f"{assistant_text}"
)
retry_messages.append({"role": "user", "content": note})
return retry_messages
async def _request_finalization_retry(
self,
spec: AgentRunSpec,
@@ -986,7 +939,7 @@ class AgentRunner:
messages: list[dict[str, Any]],
) -> LLMResponse:
kwargs = self._build_request_kwargs(spec, messages, tools=None)
return await spec.runtime.provider.chat_with_retry(**kwargs)
return await self.provider.chat_with_retry(**kwargs)
@staticmethod
def _budget_exhausted_finalization_messages(
@@ -996,6 +949,53 @@ class AgentRunner:
retry_messages.append(build_budget_exhausted_finalization_message())
return retry_messages
@classmethod
def _append_runtime_budget_notice_if_needed(
cls,
spec: AgentRunSpec,
messages: list[dict[str, Any]],
*,
completed_iterations: int,
sent_level: int,
) -> int:
level = cls._runtime_budget_notice_level(
max_iterations=spec.max_iterations,
completed_iterations=completed_iterations,
)
if level <= sent_level:
return sent_level
remaining_iterations = max(0, spec.max_iterations - completed_iterations)
messages.append(build_runtime_budget_notice_message(
level=level,
max_iterations=spec.max_iterations,
used_iterations=completed_iterations,
remaining_iterations=remaining_iterations,
))
return level
@staticmethod
def _runtime_budget_notice_level(
*,
max_iterations: int,
completed_iterations: int,
) -> int:
"""Return the convergence-warning level for a long tool loop."""
if max_iterations < _BUDGET_NOTICE_MIN_ITERATIONS:
return 0
remaining_iterations = max_iterations - completed_iterations
if remaining_iterations <= 0:
return 0
convergence_threshold = max(5, (max_iterations + 9) // 10)
final_threshold = max(3, (max_iterations + 32) // 33)
if remaining_iterations <= final_threshold:
return 2
if remaining_iterations <= convergence_threshold:
return 1
return 0
@staticmethod
def _max_iterations_fallback(spec: AgentRunSpec) -> str:
if spec.max_iterations_message:
@@ -1034,12 +1034,7 @@ class AgentRunner:
tools = spec.tools.get_definitions()
except Exception:
tools = None
prompt_tokens, _ = estimate_prompt_tokens_chain(
spec.runtime.provider,
spec.runtime.model,
messages,
tools,
)
prompt_tokens, _ = estimate_prompt_tokens_chain(self.provider, spec.model, messages, tools)
assistant_message = build_assistant_message(
response.content or "",
tool_calls=[tc.to_openai_tool_call() for tc in response.tool_calls],
@@ -1093,23 +1088,14 @@ class AgentRunner:
tool_calls: list[ToolCallRequest],
external_lookup_counts: dict[str, int],
workspace_violation_counts: dict[str, int],
hook: AgentHook | None = None,
context: AgentHookContext | None = None,
) -> tuple[list[Any], list[dict[str, str]], BaseException | None]:
hook = hook or AgentHook()
context = context or AgentHookContext(iteration=0, messages=[])
batches = self._partition_tool_batches(spec, tool_calls)
tool_results: list[tuple[Any, dict[str, str], BaseException | None]] = []
for batch in batches:
if spec.concurrent_tools and len(batch) > 1:
batch_results = await asyncio.gather(*(
self._run_tool(
spec,
tool_call,
external_lookup_counts,
workspace_violation_counts,
hook,
context,
spec, tool_call, external_lookup_counts, workspace_violation_counts,
)
for tool_call in batch
))
@@ -1118,12 +1104,7 @@ class AgentRunner:
batch_results = []
for tool_call in batch:
result = await self._run_tool(
spec,
tool_call,
external_lookup_counts,
workspace_violation_counts,
hook,
context,
spec, tool_call, external_lookup_counts, workspace_violation_counts,
)
tool_results.append(result)
batch_results.append(result)
@@ -1144,11 +1125,7 @@ class AgentRunner:
tool_call: ToolCallRequest,
external_lookup_counts: dict[str, int],
workspace_violation_counts: dict[str, int],
hook: AgentHook | None = None,
context: AgentHookContext | None = None,
) -> tuple[Any, dict[str, str], BaseException | None]:
hook = hook or AgentHook()
context = context or AgentHookContext(iteration=0, messages=[])
hint = "\n\n[Analyze the error above and try a different approach.]"
lookup_error = repeated_external_lookup_error(
tool_call.name,
@@ -1189,7 +1166,30 @@ class AgentRunner:
return prep_error + hint, event, (
RuntimeError(prep_error) if spec.fail_on_tool_error else None
)
await hook.before_execute_tool(context, tool_call, tool, params)
emit_file_edit_events = (
spec.progress_callback is not None
and on_progress_accepts_file_edit_events(spec.progress_callback)
)
progress_callback = spec.progress_callback if emit_file_edit_events else None
file_edit_trackers = (
prepare_file_edit_trackers(
call_id=tool_call.id,
tool_name=tool_call.name,
tool=tool,
workspace=spec.workspace,
params=params if isinstance(params, dict) else None,
)
if progress_callback is not None
else None
)
if file_edit_trackers and progress_callback is not None:
await invoke_file_edit_progress(
progress_callback,
[build_file_edit_start_event(
file_edit_tracker,
params if isinstance(params, dict) else None,
) for file_edit_tracker in file_edit_trackers],
)
try:
if tool is not None:
result = await tool.execute(**params)
@@ -1198,7 +1198,14 @@ class AgentRunner:
except asyncio.CancelledError:
raise
except BaseException as exc:
await hook.on_execute_tool_error(context, tool_call, tool, params, exc)
if file_edit_trackers and progress_callback is not None:
await invoke_file_edit_progress(
progress_callback,
[
build_file_edit_error_event(file_edit_tracker, str(exc))
for file_edit_tracker in file_edit_trackers
],
)
event = {
"name": tool_call.name,
"status": "error",
@@ -1219,8 +1226,15 @@ class AgentRunner:
return payload, event, exc
return payload, event, None
if is_tool_error_result(tool_call.name, result):
await hook.on_execute_tool_error(context, tool_call, tool, params, result)
if isinstance(result, str) and result.startswith("Error"):
if file_edit_trackers and progress_callback is not None:
await invoke_file_edit_progress(
progress_callback,
[
build_file_edit_error_event(file_edit_tracker, result)
for file_edit_tracker in file_edit_trackers
],
)
event = {
"name": tool_call.name,
"status": "error",
@@ -1239,7 +1253,14 @@ class AgentRunner:
return result + hint, event, RuntimeError(result)
return result + hint, event, None
await hook.after_execute_tool(context, tool_call, tool, params, result)
if file_edit_trackers and progress_callback is not None:
await invoke_file_edit_progress(
progress_callback,
[build_file_edit_end_event(
file_edit_tracker,
params if isinstance(params, dict) else None,
) for file_edit_tracker in file_edit_trackers],
)
detail = "" if result is None else str(result)
detail = detail.replace("\n", " ").strip()
+20 -92
View File
@@ -4,7 +4,6 @@ import asyncio
import json
import time
import uuid
import warnings
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable
@@ -13,13 +12,7 @@ from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.runner import AgentRunner, AgentRunSpec
from nanobot.agent.tools.context import (
RequestContext,
ToolContext,
bind_request_context,
reset_request_context,
)
from nanobot.agent.tools.exec_session import ExecSessionManager
from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.file_state import FileStates
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
@@ -33,7 +26,6 @@ from nanobot.security.workspace_access import (
reset_workspace_scope,
workspace_sandbox_status,
)
from nanobot.utils.llm_runtime import LLMRuntime
from nanobot.utils.prompt_templates import render_template
@@ -84,10 +76,10 @@ class SubagentManager:
def __init__(
self,
provider: LLMProvider | None = None,
workspace: Path | None = None,
bus: MessageBus | None = None,
max_tool_result_chars: int | None = None,
provider: LLMProvider,
workspace: Path,
bus: MessageBus,
max_tool_result_chars: int,
model: str | None = None,
tools_config: ToolsConfig | None = None,
restrict_to_workspace: bool = False,
@@ -97,33 +89,11 @@ class SubagentManager:
fail_on_tool_error: bool | None = None,
llm_wall_timeout_for_session: Callable[[str | None], float | None] | None = None,
):
if workspace is None:
raise TypeError("SubagentManager.__init__() missing required argument: 'workspace'")
if bus is None:
raise TypeError("SubagentManager.__init__() missing required argument: 'bus'")
if max_tool_result_chars is None:
raise TypeError(
"SubagentManager.__init__() missing required argument: 'max_tool_result_chars'"
)
if model is not None and provider is None:
raise TypeError("SubagentManager model compatibility argument requires provider")
defaults = AgentDefaults()
self._compat_runtime: LLMRuntime | None = None
if provider is not None:
warnings.warn(
"SubagentManager provider/model constructor arguments are deprecated; "
"pass runtime=... to spawn() instead",
DeprecationWarning,
stacklevel=2,
)
self._compat_runtime = LLMRuntime.capture(
provider,
model or provider.get_default_model(),
context_window_tokens=defaults.context_window_tokens,
)
self.provider = provider
self.workspace = workspace
self.bus = bus
self.model = model or provider.get_default_model()
self.tools_config = tools_config or ToolsConfig()
self.max_tool_result_chars = max_tool_result_chars
self.restrict_to_workspace = restrict_to_workspace
@@ -143,48 +113,12 @@ class SubagentManager:
if fail_on_tool_error is not None
else defaults.fail_on_tool_error
)
self.runner = AgentRunner()
self._exec_session_manager = ExecSessionManager()
self.runner = AgentRunner(provider)
self._llm_wall_timeout_for_session = llm_wall_timeout_for_session
self._running_tasks: dict[str, asyncio.Task[None]] = {}
self._task_statuses: dict[str, SubagentStatus] = {}
self._session_tasks: dict[str, set[str]] = {} # session_key -> {task_id, ...}
def set_provider(self, provider: LLMProvider, model: str) -> None:
"""Update the deprecated runtime source used by legacy ``spawn`` calls."""
warnings.warn(
"SubagentManager.set_provider() is deprecated; pass runtime=... to spawn() instead",
DeprecationWarning,
stacklevel=2,
)
context_window_tokens = (
self._compat_runtime.context_window_tokens
if self._compat_runtime is not None
else AgentDefaults().context_window_tokens
)
self._compat_runtime = LLMRuntime.capture(
provider,
model,
context_window_tokens=context_window_tokens,
)
def _compat_spawn_runtime(self) -> LLMRuntime:
runtime = self._compat_runtime
if runtime is None:
raise TypeError(
"SubagentManager.spawn() missing required keyword-only argument: 'runtime'"
)
warnings.warn(
"SubagentManager.spawn() without runtime is deprecated; pass runtime=... explicitly",
DeprecationWarning,
stacklevel=3,
)
return LLMRuntime.capture(
runtime.provider,
runtime.model,
context_window_tokens=runtime.context_window_tokens,
)
def _subagent_tools_config(self) -> ToolsConfig:
"""Build a ToolsConfig scoped for subagent use."""
return ToolsConfig(
@@ -206,7 +140,6 @@ class SubagentManager:
ctx = ToolContext(
config=cfg,
workspace=str(root.resolve()),
exec_session_manager=self._exec_session_manager,
file_state_store=FileStates(),
workspace_sandbox=workspace_sandbox_status(
restrict_to_workspace=cfg.restrict_to_workspace,
@@ -216,6 +149,11 @@ class SubagentManager:
ToolLoader().load(ctx, registry, scope="subagent")
return registry
def set_provider(self, provider: LLMProvider, model: str) -> None:
self.provider = provider
self.model = model
self.runner.provider = provider
async def spawn(
self,
task: str,
@@ -226,14 +164,8 @@ class SubagentManager:
origin_message_id: str | None = None,
temperature: float | None = None,
workspace_scope: WorkspaceScope | None = None,
*,
runtime: LLMRuntime | None = None,
) -> str:
"""Spawn a subagent to execute a task in the background."""
if runtime is None:
runtime = self._compat_spawn_runtime()
if temperature is not None:
runtime = runtime.with_generation_overrides(temperature=temperature)
task_id = str(uuid.uuid4())[:8]
display_label = label or task[:30] + ("..." if len(task) > 30 else "")
origin = {"channel": origin_channel, "chat_id": origin_chat_id, "session_key": session_key}
@@ -253,8 +185,8 @@ class SubagentManager:
display_label,
origin,
status,
runtime,
origin_message_id,
temperature,
workspace_scope,
)
)
@@ -282,8 +214,8 @@ class SubagentManager:
label: str,
origin: dict[str, str],
status: SubagentStatus,
runtime: LLMRuntime,
origin_message_id: str | None = None,
temperature: float | None = None,
workspace_scope: WorkspaceScope | None = None,
) -> None:
"""Execute the subagent task and announce the result."""
@@ -312,19 +244,13 @@ class SubagentManager:
if self._llm_wall_timeout_for_session
else None
)
request_token = bind_request_context(RequestContext(
channel=origin["channel"],
chat_id=origin["chat_id"],
message_id=origin_message_id,
session_key=sess_key,
runtime=runtime,
))
token = bind_workspace_scope(workspace_scope) if workspace_scope is not None else None
try:
result = await self.runner.run(AgentRunSpec(
initial_messages=messages,
tools=tools,
runtime=runtime,
model=self.model,
temperature=temperature,
max_iterations=self.max_iterations,
max_tool_result_chars=self.max_tool_result_chars,
hook=_SubagentHook(task_id, status),
@@ -340,7 +266,6 @@ class SubagentManager:
finally:
if token is not None:
reset_workspace_scope(token)
reset_request_context(request_token)
status.phase = "done"
status.stop_reason = result.stop_reason
@@ -436,8 +361,10 @@ class SubagentManager:
def _build_subagent_prompt(self, workspace: Path | None = None) -> str:
"""Build a focused system prompt for the subagent."""
from nanobot.agent.context import ContextBuilder
from nanobot.agent.skills import SkillsLoader
time_ctx = ContextBuilder._build_runtime_context(None, None)
root = workspace or self.workspace
skills_summary = SkillsLoader(
root,
@@ -445,6 +372,7 @@ class SubagentManager:
).build_skills_summary()
return render_template(
"agent/subagent_system.md",
time_ctx=time_ctx,
workspace=str(root),
skills_summary=skills_summary or "",
)
+1 -2
View File
@@ -1,6 +1,6 @@
"""Agent tools module."""
from nanobot.agent.tools.base import Schema, Tool, ToolResult, tool_parameters
from nanobot.agent.tools.base import Schema, Tool, tool_parameters
from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
@@ -25,7 +25,6 @@ __all__ = [
"Tool",
"ToolContext",
"ToolLoader",
"ToolResult",
"ToolRegistry",
"tool_parameters",
"tool_parameters_schema",
+4 -4
View File
@@ -7,7 +7,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
from nanobot.agent.tools.base import ToolResult, tool_parameters
from nanobot.agent.tools.base import tool_parameters
from nanobot.agent.tools.filesystem import _FsTool
from nanobot.agent.tools.schema import (
ArraySchema,
@@ -289,8 +289,8 @@ class ApplyPatchTool(_FsTool):
_format_summary(summary) for summary in summaries
)
except PermissionError as exc:
return ToolResult.error(f"Error: {exc}")
return f"Error: {exc}"
except _PatchError as exc:
return ToolResult.error(f"Error applying patch: {exc}")
return f"Error applying patch: {exc}"
except Exception as exc:
return ToolResult.error(f"Error applying patch: {exc}")
return f"Error applying patch: {exc}"
+1 -25
View File
@@ -11,7 +11,6 @@ if typing.TYPE_CHECKING:
from pydantic import BaseModel
from nanobot.agent.tools.context import ToolContext
from nanobot.runtime_context import RuntimeContextProvider
_ToolT = TypeVar("_ToolT", bound="Tool")
@@ -129,21 +128,6 @@ class Schema(ABC):
return Schema.validate_json_schema_value(value, self.to_json_schema(), path)
class ToolResult(str):
"""String-compatible tool output with structured status."""
is_error: bool
def __new__(cls, content: str, *, is_error: bool = False) -> ToolResult:
obj = str.__new__(cls, content)
obj.is_error = is_error
return obj
@classmethod
def error(cls, content: str) -> ToolResult:
return cls(content, is_error=True)
class Tool(ABC):
"""Agent capability: read files, run commands, etc."""
@@ -207,19 +191,11 @@ class Tool(ABC):
def create(cls, ctx: ToolContext) -> Tool:
return cls()
def runtime_context_provider(self) -> RuntimeContextProvider | None:
"""Return optional per-turn prompt context owned by this tool."""
return None
@abstractmethod
async def execute(self, **kwargs: Any) -> Any:
"""Run the tool; return content, or ``ToolResult.error(...)`` for failures."""
"""Run the tool; returns a string or list of content blocks."""
...
@staticmethod
def error(content: str) -> ToolResult:
return ToolResult.error(content)
def _cast_object(self, obj: Any, schema: dict[str, Any]) -> dict[str, Any]:
if not isinstance(obj, dict):
return obj
+2 -22
View File
@@ -7,8 +7,7 @@ from typing import Any
from pydantic import Field
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import RequestContext
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.schema import (
ArraySchema,
BooleanSchema,
@@ -17,9 +16,7 @@ from nanobot.agent.tools.schema import (
tool_parameters_schema,
)
from nanobot.apps.cli import CliAppError, CliAppManager, CliAppsRuntimeConfig
from nanobot.apps.cli.utils import runtime_lines_for_request
from nanobot.config_base import Base
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
from nanobot.security.workspace_access import current_tool_workspace
@@ -115,23 +112,6 @@ class CliAppsTool(Tool):
+ installed_note
)
def runtime_context_provider(self):
return self._provide_runtime_context
async def _provide_runtime_context(
self,
request: RequestContext,
) -> RuntimeContextBlock | None:
lines = runtime_lines_for_request(
request.original_user_text or "",
request.metadata,
request.workspace or self.workspace,
)
content = wrap_runtime_context_lines(lines)
if not content:
return None
return RuntimeContextBlock(source="cli_apps", content=content)
async def execute(
self,
name: str,
@@ -156,4 +136,4 @@ class CliAppsTool(Tool):
restrict_to_workspace=access.restrict_to_workspace,
)
except CliAppError as exc:
return ToolResult.error(f"Error: {exc.message}")
return f"Error: {exc.message}"
+1 -22
View File
@@ -1,14 +1,9 @@
"""Runtime context for tool construction."""
from __future__ import annotations
from contextlib import contextmanager
from contextvars import ContextVar, Token
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable
if TYPE_CHECKING:
from nanobot.utils.llm_runtime import LLMRuntime
from typing import Any, Callable, Protocol, runtime_checkable
_CURRENT_REQUEST_CONTEXT: ContextVar["RequestContext | None"] = ContextVar(
"nanobot_tool_request_context",
@@ -23,12 +18,7 @@ class RequestContext:
chat_id: str
message_id: str | None = None
session_key: str | None = None
original_user_text: str | None = None
runtime: LLMRuntime | None = None
metadata: dict[str, Any] = field(default_factory=dict)
sender_id: str | None = None
turn_id: str | None = None
workspace: Path | None = None
@runtime_checkable
@@ -45,16 +35,6 @@ def reset_request_context(token: Token[RequestContext | None]) -> None:
_CURRENT_REQUEST_CONTEXT.reset(token)
@contextmanager
def request_context(ctx: RequestContext):
"""Bind one immutable request snapshot and restore the previous value."""
token = bind_request_context(ctx)
try:
yield ctx
finally:
reset_request_context(token)
def current_request_context() -> RequestContext | None:
return _CURRENT_REQUEST_CONTEXT.get()
@@ -71,7 +51,6 @@ class ToolContext:
bus: Any | None = None
subagent_manager: Any | None = None
cron_service: Any | None = None
exec_session_manager: Any | None = None
sessions: Any | None = None
file_state_store: Any = field(default=None)
provider_snapshot_loader: Callable[[], Any] | None = None
+29 -22
View File
@@ -6,8 +6,8 @@ from contextvars import ContextVar
from datetime import datetime
from typing import Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.schema import (
IntegerSchema,
StringSchema,
@@ -51,12 +51,19 @@ _CRON_PARAMETERS = tool_parameters_schema(
@tool_parameters(_CRON_PARAMETERS)
class CronTool(Tool):
class CronTool(Tool, ContextAware):
"""Tool to schedule reminders and recurring tasks."""
def __init__(self, cron_service: CronService, default_timezone: str = "UTC"):
self._cron = cron_service
self._default_timezone = default_timezone
self._session_key: ContextVar[str] = ContextVar("cron_session_key", default="")
self._origin_channel: ContextVar[str] = ContextVar("cron_origin_channel", default="")
self._origin_chat_id: ContextVar[str] = ContextVar("cron_origin_chat_id", default="")
self._origin_metadata: ContextVar[dict[str, Any] | None] = ContextVar(
"cron_origin_metadata",
default=None,
)
self._in_cron_context: ContextVar[bool] = ContextVar("cron_in_context", default=False)
@classmethod
@@ -67,17 +74,15 @@ class CronTool(Tool):
def create(cls, ctx: Any) -> Tool:
return cls(cron_service=ctx.cron_service, default_timezone=ctx.timezone)
@staticmethod
def _request_route() -> tuple[str, str, str, dict[str, Any]]:
"""Return routing from the authoritative request snapshot."""
ctx = current_request_context()
if ctx is None:
return "", "", "", {}
def set_context(self, ctx: RequestContext) -> None:
"""Set the current session context for scheduled cron job ownership."""
raw_key = f"{ctx.channel}:{ctx.chat_id}" if ctx.channel and ctx.chat_id else ""
session_key = (
self._session_key.set(
raw_key if ctx.session_key == UNIFIED_SESSION_KEY else (ctx.session_key or "")
)
return session_key, ctx.channel or "", ctx.chat_id or "", dict(ctx.metadata or {})
self._origin_channel.set(ctx.channel or "")
self._origin_chat_id.set(ctx.chat_id or "")
self._origin_metadata.set(dict(ctx.metadata or {}))
def set_cron_context(self, active: bool):
"""Mark whether the tool is executing inside a cron job callback."""
@@ -94,7 +99,7 @@ class CronTool(Tool):
try:
ZoneInfo(tz)
except (KeyError, Exception):
return ToolResult.error(f"Error: unknown timezone '{tz}'")
return f"Error: unknown timezone '{tz}'"
return None
def _display_timezone(self, schedule: CronSchedule) -> str:
@@ -143,7 +148,7 @@ class CronTool(Tool):
) -> str:
if action == "add":
if self._in_cron_context.get():
return ToolResult.error("Error: cannot schedule new jobs from within a cron job execution")
return "Error: cannot schedule new jobs from within a cron job execution"
return self._add_job(name, message, every_seconds, cron_expr, tz, at)
elif action == "list":
return self._list_jobs()
@@ -161,18 +166,20 @@ class CronTool(Tool):
at: str | None,
) -> str:
if not message:
return ToolResult.error(
return (
"Error: cron action='add' requires a non-empty 'message' parameter "
"describing what to do when the job triggers "
"(e.g. the reminder text). Retry including message=\"...\"."
)
session_key, origin_channel, origin_chat_id, origin_metadata = self._request_route()
session_key = self._session_key.get()
if not session_key:
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
return "Error: scheduled cron jobs must be created from a chat session"
origin_channel = self._origin_channel.get()
origin_chat_id = self._origin_chat_id.get()
if not origin_channel or not origin_chat_id:
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
return "Error: scheduled cron jobs must be created from a chat session"
if tz and not cron_expr:
return ToolResult.error("Error: tz can only be used with cron_expr")
return "Error: tz can only be used with cron_expr"
if tz:
if err := self._validate_timezone(tz):
return err
@@ -192,7 +199,7 @@ class CronTool(Tool):
try:
dt = datetime.fromisoformat(at)
except ValueError:
return ToolResult.error(f"Error: invalid ISO datetime format '{at}'. Expected format: YYYY-MM-DDTHH:MM:SS")
return f"Error: invalid ISO datetime format '{at}'. Expected format: YYYY-MM-DDTHH:MM:SS"
if dt.tzinfo is None:
if err := self._validate_timezone(self._default_timezone):
return err
@@ -201,7 +208,7 @@ class CronTool(Tool):
schedule = CronSchedule(kind="at", at_ms=at_ms)
delete_after = True
else:
return ToolResult.error("Error: either every_seconds, cron_expr, or at is required")
return "Error: either every_seconds, cron_expr, or at is required"
job = self._cron.add_job(
name=name or message[:30],
@@ -211,7 +218,7 @@ class CronTool(Tool):
session_key=session_key,
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
origin_metadata=origin_metadata,
origin_metadata=dict(self._origin_metadata.get() or {}),
)
return f"Created job '{job.name}' (id: {job.id})"
@@ -272,7 +279,7 @@ class CronTool(Tool):
def _remove_job(self, job_id: str | None) -> str:
if not job_id:
return ToolResult.error("Error: job_id is required for remove")
return "Error: job_id is required for remove"
result = self._cron.remove_job(job_id)
if result == "removed":
return f"Removed job {job_id}"
+80 -40
View File
@@ -9,7 +9,7 @@ from contextlib import suppress
from dataclasses import dataclass
from typing import Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.context import current_request_session_key
from nanobot.agent.tools.schema import (
BooleanSchema,
@@ -17,6 +17,13 @@ from nanobot.agent.tools.schema import (
StringSchema,
tool_parameters_schema,
)
from nanobot.agent.verification_state import (
VerificationAnalysis,
analyze_verification_result,
append_verification_feedback,
record_verification_observation,
)
from nanobot.utils.helpers import build_structured_output_summary
DEFAULT_YIELD_MS = 1000
MAX_YIELD_MS = 30_000
@@ -37,6 +44,7 @@ class _SessionPoll:
terminated: bool = False
stdin_closed: bool = False
truncated_chars: int = 0
analysis: VerificationAnalysis | None = None
@dataclass(slots=True)
@@ -128,15 +136,7 @@ class _ExecSession:
) -> _SessionPoll:
self.last_access = time.monotonic()
if yield_time_ms > 0 and self.process.returncode is None:
wait_s = min(yield_time_ms, MAX_YIELD_MS) / 1000
remaining_s = self.deadline - time.monotonic()
if remaining_s <= 0:
wait_s = 0
else:
wait_s = min(wait_s, remaining_s)
if wait_s > 0:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.process.wait(), timeout=wait_s)
await asyncio.sleep(min(yield_time_ms, MAX_YIELD_MS) / 1000)
if self.process.returncode is None and time.monotonic() >= self.deadline:
self._timed_out = True
@@ -148,9 +148,6 @@ class _ExecSession:
asyncio.gather(self._stdout_task, self._stderr_task),
timeout=2.0,
)
# Safety-net reap after normal exit.
from nanobot.agent.tools.shell import _reap_pid
_reap_pid(self.process.pid)
elif yield_time_ms > 0:
await self._wait_for_buffered_output()
@@ -158,7 +155,19 @@ class _ExecSession:
output = "".join(self._chunks)
self._chunks.clear()
output, truncated = _truncate_output(output, max_output_chars)
analysis = analyze_verification_result(
command=self.command,
output=output,
exit_code=self.process.returncode,
timed_out=self._timed_out,
)
output, truncated = _truncate_output(
output,
max_output_chars,
analysis=analysis,
exit_code=self.process.returncode,
elapsed_s=max(0.0, time.monotonic() - self.started_at),
)
return _SessionPoll(
output=output,
done=self.process.returncode is not None,
@@ -168,20 +177,15 @@ class _ExecSession:
terminated=terminated,
stdin_closed=stdin_closed,
truncated_chars=truncated,
analysis=analysis,
)
async def kill(self) -> None:
if self.process.returncode is not None:
return
self.process.kill()
try:
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.process.wait(), timeout=5.0)
finally:
# Safety-net waitpid — prevent zombie if asyncio's child watcher
# did not reap the process (common in containers).
from nanobot.agent.tools.shell import _reap_pid
_reap_pid(self.process.pid)
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(self.process.wait(), timeout=5.0)
async def _wait_for_buffered_output(self) -> None:
deadline = time.monotonic() + OUTPUT_DRAIN_GRACE_S
@@ -250,7 +254,11 @@ class ExecSessionManager:
session = self._sessions.get(session_id)
if session is None:
raise KeyError(session_id)
if session.owner_session_key and session.owner_session_key != owner_session_key:
if (
owner_session_key
and session.owner_session_key
and session.owner_session_key != owner_session_key
):
raise KeyError(session_id)
if chars:
@@ -292,7 +300,9 @@ class ExecSessionManager:
owner_session_key=session.owner_session_key,
)
for session_id, session in sorted(self._sessions.items())
if session.owner_session_key == owner_session_key
if not owner_session_key
or not session.owner_session_key
or session.owner_session_key == owner_session_key
]
async def _cleanup_locked(self) -> None:
@@ -331,15 +341,33 @@ def clamp_session_int(value: int | None, default: int, minimum: int, maximum: in
return min(max(value, minimum), maximum)
def _truncate_output(output: str, max_output_chars: int) -> tuple[str, int]:
def _truncate_output(
output: str,
max_output_chars: int,
*,
analysis: VerificationAnalysis | None = None,
exit_code: int | None = None,
elapsed_s: float | None = None,
) -> tuple[str, int]:
if len(output) <= max_output_chars:
return output, 0
half = max_output_chars // 2
omitted = len(output) - max_output_chars
return (
output[:half]
+ f"\n\n... ({omitted:,} chars truncated) ...\n\n"
+ output[-half:],
build_structured_output_summary(
"[tool output truncated]",
output,
max_chars=max_output_chars,
metadata=[
("original_size_chars", len(output)),
("exit_code", exit_code if exit_code is not None else "running"),
("elapsed_s", f"{elapsed_s:.1f}" if elapsed_s is not None else "unknown"),
],
analysis=analysis,
guidance=(
"Use the structured summary first. Poll again for new output "
"or rerun a narrower command instead of reading broad logs."
),
),
omitted,
)
@@ -362,6 +390,20 @@ def format_session_poll(session_id: str, poll: _SessionPoll) -> str:
return "\n".join(parts) if parts else "(no output yet)"
def _format_poll_with_verification(session_id: str, poll: _SessionPoll) -> str:
result = format_session_poll(session_id, poll)
if not poll.done:
return result
analysis = poll.analysis or analyze_verification_result(
command="",
output=result,
exit_code=poll.exit_code,
timed_out=poll.timed_out,
)
record_verification_observation(current_request_session_key(), analysis)
return append_verification_feedback(result, analysis)
@tool_parameters(
tool_parameters_schema(
session_id=StringSchema("Session id returned by exec when yield_time_ms is used."),
@@ -436,7 +478,7 @@ class WriteStdinTool(Tool):
@classmethod
def create(cls, ctx: Any) -> Tool:
return cls(manager=getattr(ctx, "exec_session_manager", None))
return cls()
@property
def exclusive(self) -> bool:
@@ -503,12 +545,11 @@ class WriteStdinTool(Tool):
max_output_chars=output_limit,
owner_session_key=current_request_session_key(),
)
result = format_session_poll(session_id, poll)
return ToolResult.error(result) if poll.timed_out else result
return _format_poll_with_verification(session_id, poll)
except KeyError:
return ToolResult.error(f"Error: exec session not found: {session_id!r}")
return f"Error: exec session not found: {session_id}"
except Exception as exc:
return ToolResult.error(f"Error writing to exec session: {exc}")
return f"Error writing to exec session: {exc}"
async def _wait_for_output(
self,
@@ -544,14 +585,13 @@ class WriteStdinTool(Tool):
joined = "".join(aggregate)
if wait_for in joined:
poll.output = joined
result = format_session_poll(session_id, poll)
return ToolResult.error(result) if poll.timed_out else result
return _format_poll_with_verification(session_id, poll)
if poll.done or remaining_ms <= 0:
poll.output = "".join(aggregate)
result = format_session_poll(session_id, poll)
result = _format_poll_with_verification(session_id, poll)
if wait_for not in poll.output:
result += f"\nWait target not observed: {wait_for!r}"
return ToolResult.error(result) if poll.timed_out else result
return result
@tool_parameters(tool_parameters_schema())
@@ -580,7 +620,7 @@ class ListExecSessionsTool(Tool):
@classmethod
def create(cls, ctx: Any) -> Tool:
return cls(manager=getattr(ctx, "exec_session_manager", None))
return cls()
@property
def name(self) -> str:
@@ -619,4 +659,4 @@ class ListExecSessionsTool(Tool):
)
return "\n".join(lines)
except Exception as exc:
return ToolResult.error(f"Error listing exec sessions: {exc}")
return f"Error listing exec sessions: {exc}"
+113 -120
View File
@@ -7,7 +7,7 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.file_state import FileStates, _hash_file, current_file_states
from nanobot.agent.tools.path_utils import resolve_workspace_path
from nanobot.agent.tools.schema import (
@@ -194,21 +194,15 @@ def _is_blocked_device(path: str | Path) -> bool:
return False
def _builtin_skill_read_path(path: str) -> Path | None:
"""Map workspace-relative skills/<name>/... reads onto bundled skills."""
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
requested = Path(path)
if requested.is_absolute():
return None
parts = requested.parts
if len(parts) < 2 or parts[0] != "skills":
return None
root = BUILTIN_SKILLS_DIR.resolve()
candidate = (root / Path(*parts[1:])).resolve()
if candidate != root and root not in candidate.parents:
return None
return candidate if candidate.is_file() else None
def _parse_page_range(pages: str, total: int) -> tuple[int, int]:
"""Parse a page range like '2-5' into 0-based (start, end) inclusive."""
parts = pages.strip().split("-")
if len(parts) == 1:
p = int(parts[0])
return max(0, p - 1), min(p - 1, total - 1)
start = int(parts[0])
end = int(parts[1])
return max(0, start - 1), min(end - 1, total - 1)
@tool_parameters(
@@ -274,21 +268,19 @@ class ReadFileTool(_FsTool):
) -> Any:
try:
if not path:
return ToolResult.error("Error reading file: Unknown path")
return "Error reading file: Unknown path"
# Device path blacklist
if _is_blocked_device(path):
return ToolResult.error(f"Error: Reading {path} is blocked (device path that could hang or produce infinite output).")
return f"Error: Reading {path} is blocked (device path that could hang or produce infinite output)."
fp = self._resolve_read(path)
if not fp.exists():
fp = _builtin_skill_read_path(path) or fp
if _is_blocked_device(fp):
return ToolResult.error(f"Error: Reading {fp} is blocked (device path that could hang or produce infinite output).")
return f"Error: Reading {fp} is blocked (device path that could hang or produce infinite output)."
if not fp.exists():
return ToolResult.error(f"Error: File not found: {path}")
return f"Error: File not found: {path}"
if not fp.is_file():
return ToolResult.error(f"Error: Not a file: {path}")
return f"Error: Not a file: {path}"
# PDF support
if fp.suffix.lower() == ".pdf":
@@ -351,7 +343,7 @@ class ReadFileTool(_FsTool):
mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]
if mime and mime.startswith("image/"):
return build_image_content_blocks(raw, mime, str(fp), f"(Image file: {path})")
return ToolResult.error(f"Error: Cannot read binary file {path} (MIME: {mime or 'unknown'}). Only UTF-8 text and images are supported.")
return f"Error: Cannot read binary file {path} (MIME: {mime or 'unknown'}). Only UTF-8 text and images are supported."
# Normalize CRLF -> LF before line-splitting. Primarily a Windows
# concern (git checkouts with autocrlf, editors saving CRLF) but
@@ -365,7 +357,7 @@ class ReadFileTool(_FsTool):
if offset < 1:
offset = 1
if offset > total:
return ToolResult.error(f"Error: offset {offset} is beyond end of file ({total} lines)")
return f"Error: offset {offset} is beyond end of file ({total} lines)"
start = offset - 1
end = min(start + (limit or self._DEFAULT_LIMIT), total)
@@ -389,38 +381,54 @@ class ReadFileTool(_FsTool):
self._file_states.record_read(fp, offset=offset, limit=limit)
return result
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
return f"Error: {e}"
except Exception as e:
return ToolResult.error(f"Error reading file: {e}")
return f"Error reading file: {e}"
def _read_pdf(self, fp: Path, pages: str | None) -> str:
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError, extract_pdf_pages
try:
import fitz # pymupdf
except ImportError:
return "Error: PDF reading requires pymupdf. Install with: pip install pymupdf"
try:
extraction = extract_pdf_pages(
fp,
pages=pages,
max_pages=self._MAX_PDF_PAGES,
max_chars=self._MAX_CHARS,
)
except PdfPageRangeError:
return ToolResult.error(f"Error: Invalid page range '{pages}'. Use format like '1-5'.")
except PdfSafetyError as e:
return ToolResult.error(f"Error reading PDF: {e}")
doc = fitz.open(str(fp))
except Exception as e:
return ToolResult.error(f"Error reading PDF: {e}")
return f"Error reading PDF: {e}"
if not extraction.text:
total_pages = len(doc)
if pages:
try:
start, end = _parse_page_range(pages, total_pages)
except (ValueError, IndexError):
doc.close()
return f"Error: Invalid page range '{pages}'. Use format like '1-5'."
if start > end or start >= total_pages:
doc.close()
return f"Error: Page range '{pages}' is out of bounds (document has {total_pages} pages)."
else:
start = 0
end = min(total_pages - 1, self._MAX_PDF_PAGES - 1)
if end - start + 1 > self._MAX_PDF_PAGES:
end = start + self._MAX_PDF_PAGES - 1
parts: list[str] = []
for i in range(start, end + 1):
page = doc[i]
text = page.get_text().strip()
if text:
parts.append(f"--- Page {i + 1} ---\n{text}")
doc.close()
if not parts:
return f"(PDF has no extractable text: {fp})"
result = extraction.text
if extraction.end_page < extraction.total_pages - 1:
next_start = extraction.end_page + 2
next_end = min(extraction.end_page + 1 + self._MAX_PDF_PAGES, extraction.total_pages)
result += (
f"\n\n(Showing pages {extraction.start_page + 1}-{extraction.end_page + 1} "
f"of {extraction.total_pages}. Use pages='{next_start}-{next_end}' to continue.)"
)
result = "\n\n".join(parts)
if end < total_pages - 1:
result += f"\n\n(Showing pages {start + 1}-{end + 1} of {total_pages}. Use pages='{end + 2}-{min(end + 1 + self._MAX_PDF_PAGES, total_pages)}' to continue.)"
if len(result) > self._MAX_CHARS:
result = result[:self._MAX_CHARS] + "\n\n(PDF text truncated at ~128K chars)"
return result
def _read_office_doc(self, fp: Path) -> str:
@@ -429,10 +437,10 @@ class ReadFileTool(_FsTool):
result = extract_text(fp)
if result is None:
return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}")
return f"Error: Unsupported file format: {fp.suffix}"
if result.startswith("[error:"):
return ToolResult.error(f"Error reading {fp.suffix.upper()} file: {result}")
return f"Error reading {fp.suffix.upper()} file: {result}"
if not result:
return f"({fp.suffix.upper().lstrip('.')} has no extractable text: {fp})"
@@ -484,9 +492,9 @@ class WriteFileTool(_FsTool):
self._file_states.record_write(fp)
return f"Successfully wrote {len(content)} characters to {fp}"
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
return f"Error: {e}"
except Exception as e:
return ToolResult.error(f"Error writing file: {e}")
return f"Error writing file: {e}"
# ---------------------------------------------------------------------------
@@ -594,15 +602,6 @@ class _MatchSpan:
line: int
def _match_end_line(match: _MatchSpan) -> int:
comparable = match.text[:-1] if match.text.endswith("\n") else match.text
return match.line + comparable.count("\n")
def _match_covers_line(match: _MatchSpan, line: int) -> bool:
return match.line <= line <= _match_end_line(match)
def _find_exact_matches(content: str, old_text: str) -> list[_MatchSpan]:
matches: list[_MatchSpan] = []
start = 0
@@ -776,10 +775,7 @@ def _find_match(content: str, old_text: str) -> tuple[str | None, int]:
),
line_hint=IntegerSchema(
1,
description=(
"Optional exact 1-based target line copied from read_file. "
"The selected old_text match must cover this line."
),
description="Optional 1-based line hint used to choose the nearest match.",
minimum=1,
nullable=True,
),
@@ -811,9 +807,8 @@ class EditFileTool(_FsTool):
"with old_text copied from read_file. For multi-file, structural, "
"or generated code edits, prefer apply_patch. If old_text matches "
"multiple times, provide more context or set occurrence, line_hint, "
"replace_all, and expected_replacements. When editing from numbered "
"read_file output, set line_hint to the exact target line. "
"Shows closest-match diagnostics on failure."
"replace_all, and expected_replacements. Shows closest-match "
"diagnostics on failure."
)
@staticmethod
@@ -835,11 +830,11 @@ class EditFileTool(_FsTool):
if new_text is None:
raise ValueError("Unknown new_text")
if occurrence is not None and occurrence < 1:
return ToolResult.error("Error: occurrence must be >= 1.")
return "Error: occurrence must be >= 1."
if line_hint is not None and line_hint < 1:
return ToolResult.error("Error: line_hint must be >= 1.")
return "Error: line_hint must be >= 1."
if expected_replacements is not None and expected_replacements < 1:
return ToolResult.error("Error: expected_replacements must be >= 1.")
return "Error: expected_replacements must be >= 1."
fp = self._resolve_write(path)
@@ -858,14 +853,14 @@ class EditFileTool(_FsTool):
except OSError:
fsize = 0
if fsize > self._MAX_EDIT_FILE_SIZE:
return ToolResult.error(f"Error: File too large to edit ({fsize / (1024**3):.1f} GiB). Maximum is 1 GiB.")
return f"Error: File too large to edit ({fsize / (1024**3):.1f} GiB). Maximum is 1 GiB."
# Create-file: old_text='' but file exists and not empty → reject
if old_text == "":
raw = fp.read_bytes()
content = raw.decode("utf-8")
if content.strip():
return ToolResult.error(f"Error: Cannot create file — {path} already exists and is not empty.")
return f"Error: Cannot create file — {path} already exists and is not empty."
fp.write_text(new_text, encoding="utf-8")
self._file_states.record_write(fp)
return f"Successfully edited {fp}"
@@ -883,26 +878,41 @@ class EditFileTool(_FsTool):
return self._not_found_msg(old_text, content, path)
count = len(matches)
if replace_all and occurrence is not None:
return ToolResult.error("Error: occurrence cannot be used with replace_all=true.")
return "Error: occurrence cannot be used with replace_all=true."
if replace_all and line_hint is not None:
return ToolResult.error("Error: line_hint cannot be used with replace_all=true.")
return "Error: line_hint cannot be used with replace_all=true."
if occurrence is not None and line_hint is not None:
return ToolResult.error("Error: line_hint cannot be used with occurrence.")
if occurrence is not None and occurrence > count:
return ToolResult.error(
f"Error: occurrence {occurrence} is out of range; "
f"old_text appears {count} time(s)."
)
if count > 1 and not replace_all and occurrence is None and line_hint is None:
line_numbers = [match.line for match in matches]
preview = ", ".join(f"line {n}" for n in line_numbers[:3])
if len(line_numbers) > 3:
preview += ", ..."
location_hint = f" at {preview}" if preview else ""
return "Error: line_hint cannot be used with occurrence."
if count > 1 and not replace_all:
if occurrence is not None:
if occurrence > count:
return (
f"Error: occurrence {occurrence} is out of range; "
f"old_text appears {count} times."
)
elif line_hint is not None:
nearest = min(matches, key=lambda match: abs(match.line - line_hint))
distance = abs(nearest.line - line_hint)
if sum(1 for match in matches if abs(match.line - line_hint) == distance) > 1:
return (
f"Error: line_hint {line_hint} is ambiguous; "
f"old_text appears {count} times."
)
else:
line_numbers = [match.line for match in matches]
preview = ", ".join(f"line {n}" for n in line_numbers[:3])
if len(line_numbers) > 3:
preview += ", ..."
location_hint = f" at {preview}" if preview else ""
return (
f"Warning: old_text appears {count} times{location_hint}. "
"Provide more context, set occurrence to choose one match, "
"or set replace_all=true."
)
elif occurrence is not None and occurrence > count:
return (
f"Warning: old_text appears {count} times{location_hint}. "
"Provide more context, set occurrence to choose one match, "
"or set replace_all=true."
f"Error: occurrence {occurrence} is out of range; "
f"old_text appears {count} time."
)
norm_new = new_text.replace("\r\n", "\n")
@@ -913,29 +923,12 @@ class EditFileTool(_FsTool):
if replace_all:
selected = matches
elif occurrence is not None:
selected = [matches[occurrence - 1]]
elif line_hint is not None:
candidates = [match for match in matches if _match_covers_line(match, line_hint)]
if not candidates:
locations = ", ".join(f"line {match.line}" for match in matches[:3])
if len(matches) > 3:
locations += ", ..."
return ToolResult.error(
f"Error: line_hint {line_hint} does not match the old_text location. "
f"old_text appears at {locations}. Re-read the intended region and "
"copy old_text that covers the target line."
)
if len(candidates) > 1:
return ToolResult.error(
f"Error: line_hint {line_hint} is ambiguous; "
f"old_text appears {len(candidates)} times on that line."
)
selected = candidates
selected = [min(matches, key=lambda match: abs(match.line - line_hint))]
else:
selected = [matches[0]]
selected = [matches[occurrence - 1 if occurrence else 0]]
if expected_replacements is not None and len(selected) != expected_replacements:
return ToolResult.error(
return (
f"Error: expected {expected_replacements} replacements but "
f"would make {len(selected)}."
)
@@ -961,9 +954,9 @@ class EditFileTool(_FsTool):
msg = f"{warning}\n{msg}"
return msg
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
return f"Error: {e}"
except Exception as e:
return ToolResult.error(f"Error editing file: {e}")
return f"Error editing file: {e}"
def _file_not_found_msg(self, path: str, fp: Path) -> str:
"""Build an error message with 'Did you mean ...?' suggestions."""
@@ -976,7 +969,7 @@ class EditFileTool(_FsTool):
parts = [f"Error: File not found: {path}"]
if suggestions:
parts.append("Did you mean: " + ", ".join(suggestions) + "?")
return ToolResult.error("\n".join(parts))
return "\n".join(parts)
@staticmethod
def _not_found_msg(old_text: str, content: str, path: str) -> str:
@@ -992,18 +985,18 @@ class EditFileTool(_FsTool):
hint_text = ""
if hints:
hint_text = "\nPossible cause: " + ", ".join(hints) + "."
return ToolResult.error(
return (
f"Error: old_text not found in {path}."
f"{hint_text}\nBest match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff}"
)
if hints:
return ToolResult.error(
return (
f"Error: old_text not found in {path}. "
f"Possible cause: {', '.join(hints)}. "
"Copy the exact text from read_file and try again."
)
return ToolResult.error(f"Error: old_text not found in {path}. No similar text found. Verify the file content.")
return f"Error: old_text not found in {path}. No similar text found. Verify the file content."
# ---------------------------------------------------------------------------
@@ -1058,9 +1051,9 @@ class ListDirTool(_FsTool):
raise ValueError("Unknown path")
dp = self._resolve(path)
if not dp.exists():
return ToolResult.error(f"Error: Directory not found: {path}")
return f"Error: Directory not found: {path}"
if not dp.is_dir():
return ToolResult.error(f"Error: Not a directory: {path}")
return f"Error: Not a directory: {path}"
cap = max_entries or self._DEFAULT_MAX
items: list[str] = []
@@ -1091,6 +1084,6 @@ class ListDirTool(_FsTool):
result += f"\n\n(truncated, showing first {cap} of {total} entries)"
return result
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
return f"Error: {e}"
except Exception as e:
return ToolResult.error(f"Error listing directory: {e}")
return f"Error listing directory: {e}"
+4 -5
View File
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any
from pydantic import Field
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.schema import (
ArraySchema,
IntegerSchema,
@@ -129,7 +129,6 @@ class ImageGenerationTool(Tool):
"api_base": provider.api_base if provider else None,
"extra_headers": provider.extra_headers if provider else None,
"extra_body": provider.extra_body if provider else None,
"proxy": provider.proxy if provider else None,
}
return cls(**kwargs)
@@ -173,11 +172,11 @@ class ImageGenerationTool(Tool):
) -> str:
client = self._provider_client()
if client is None:
return ToolResult.error(f"Error: unsupported image generation provider '{self.config.provider}'")
return f"Error: unsupported image generation provider '{self.config.provider}'"
requested = count or 1
if requested > self.config.max_images_per_turn:
return ToolResult.error(
return (
"Error: count exceeds tools.imageGeneration.maxImagesPerTurn "
f"({self.config.max_images_per_turn})"
)
@@ -207,4 +206,4 @@ class ImageGenerationTool(Tool):
break
return generated_image_tool_result(artifacts)
except (ArtifactError, ImageGenerationError, OSError) as exc:
return ToolResult.error(f"Error: {exc}")
return f"Error: {exc}"
+1 -70
View File
@@ -8,7 +8,7 @@ from typing import Any
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.registry import ToolRegistry
_SKIP_MODULES = frozenset({
@@ -96,8 +96,6 @@ class ToolLoader:
if not tool_cls.enabled(ctx):
continue
tool = tool_cls.create(ctx)
if is_plugin_source:
tool = _LegacyErrorPrefixTool(tool)
if registry.has(tool.name):
if is_plugin_source and tool.name in builtin_names:
logger.warning(
@@ -116,70 +114,3 @@ class ToolLoader:
except Exception:
logger.exception("Failed to register tool: %s", cls_label)
return registered
class _LegacyErrorPrefixTool(Tool):
"""Compatibility wrapper for external tools using the old error-string contract."""
_plugin_discoverable = False
def __init__(self, wrapped: Tool) -> None:
self._wrapped = wrapped
@property
def name(self) -> str:
return self._wrapped.name
@property
def description(self) -> str:
return self._wrapped.description
@property
def parameters(self) -> dict[str, Any]:
return self._wrapped.parameters
def runtime_context_provider(self):
return self._wrapped.runtime_context_provider()
@property
def read_only(self) -> bool:
return self._wrapped.read_only
@property
def exclusive(self) -> bool:
return self._wrapped.exclusive
@property
def concurrency_safe(self) -> bool:
return self._wrapped.concurrency_safe
@property
def config_key(self) -> str:
return getattr(self._wrapped, "config_key", "")
def set_context(self, ctx: Any) -> None:
set_context = getattr(self._wrapped, "set_context", None)
if callable(set_context):
set_context(ctx)
def cast_params(self, params: dict[str, Any]) -> dict[str, Any]:
return self._wrapped.cast_params(params)
def validate_params(self, params: dict[str, Any]) -> list[str]:
return self._wrapped.validate_params(params)
def to_schema(self) -> dict[str, Any]:
return self._wrapped.to_schema()
async def execute(self, **kwargs: Any) -> Any:
result = await self._wrapped.execute(**kwargs)
if (
isinstance(result, str)
and not isinstance(result, ToolResult)
and result.startswith("Error:")
):
return ToolResult.error(result)
return result
def __getattr__(self, name: str) -> Any:
return getattr(self._wrapped, name)
+141 -195
View File
@@ -1,54 +1,51 @@
"""Sustained-goal tools with explicit user opt-in at the execution boundary."""
"""Sustained goal tools on the main agent (Codex-style).
Follow the built-in **long-goal** skill for lifecycle rules and how to phrase
objectives (especially **idempotent**, compaction-safe goals). Load that skill
from the skills listing (path shown there) before composing ``long_task.goal`` text.
``long_task`` registers an objective on the session (JSON-serializable metadata).
Active objectives are mirrored each turn into the Runtime Context block (see
``nanobot.session.goal_state.goal_state_runtime_lines``) so compaction cannot hide them.
Work proceeds in ordinary agent turns (same runner, compaction as configured).
Call ``complete_goal`` when the sustained objective should stop being tracked:
finished successfully, or cancelled / superseded / redirectedin every case the recap should match reality.
There is **no** sub-agent orchestrator and **no** special WebSocket ``agent_ui`` stream.
"""
from __future__ import annotations
from copy import deepcopy
from contextvars import ContextVar
from datetime import datetime
from typing import TYPE_CHECKING, Any
from nanobot.agent.goal_permission import (
goal_mutation_allowed,
revoke_goal_mutation_permission,
)
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import RequestContext, current_request_context
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.schema import StringSchema, tool_parameters_schema
from nanobot.agent.verification_state import (
clear_verification_observation,
format_completion_gate_message,
latest_verification_observation,
)
from nanobot.bus.runtime_events import GoalStateChanged, RuntimeEventBus, RuntimeEventContext
from nanobot.runtime_context import RuntimeContextBlock, wrap_runtime_context_lines
from nanobot.session.goal_state import (
GOAL_STATE_KEY,
MAX_GOAL_OBJECTIVE_CHARS,
discard_legacy_goal_state_key,
explicit_goal_requested,
goal_state_raw,
goal_state_runtime_lines,
parse_goal_state,
sustained_goal_active,
)
from nanobot.session.turn_continuation import reset_goal_continuation_rounds
from nanobot.utils.prompt_templates import render_template
if TYPE_CHECKING:
from nanobot.session.manager import SessionManager
_GOAL_ACTIONS = ("complete", "cancel", "block", "replace")
_CREATE_UNAVAILABLE_ERROR = (
"Error: create_goal is unavailable for this turn. Ask the user to submit the complete "
"objective as `/goal <task>`."
)
_REPLACE_UNAVAILABLE_ERROR = (
"Error: replacing the goal is unavailable for this turn. Ask the user to submit the "
"replacement objective as `/goal <task>`."
)
def _iso_now() -> str:
return datetime.now().isoformat()
class _GoalToolsMixin:
"""Shared routing context and session lookup."""
class _GoalToolsMixin(ContextAware):
"""Shared routing context + Session lookup."""
def __init__(
self,
@@ -57,9 +54,19 @@ class _GoalToolsMixin:
) -> None:
self._sessions = sessions
self._runtime_events = runtime_events
# Each subclass gets its own ContextVar so concurrent tasks across
# different tool types (LongTaskTool vs CompleteGoalTool) do not
# interfere with each other.
self._request_ctx: ContextVar[RequestContext | None] = ContextVar(
f"{self.__class__.__name__}_request_ctx",
default=None,
)
def set_context(self, ctx: RequestContext) -> None:
self._request_ctx.set(ctx)
def _session(self):
request_ctx = current_request_context()
request_ctx = self._request_ctx.get()
if request_ctx is None:
return None
key = request_ctx.session_key
@@ -67,31 +74,10 @@ class _GoalToolsMixin:
return None
return self._sessions.get_or_create(key)
def _goal_mutation_allowed(self) -> bool:
return current_request_context() is not None and goal_mutation_allowed()
def _save_goal_state(
self,
sess: Any,
blob: dict[str, Any],
*,
reset_continuation: bool = False,
) -> None:
previous_metadata = deepcopy(sess.metadata)
sess.metadata[GOAL_STATE_KEY] = blob
discard_legacy_goal_state_key(sess.metadata)
if reset_continuation:
reset_goal_continuation_rounds(sess.metadata)
try:
self._sessions.save(sess)
except BaseException:
sess.metadata.clear()
sess.metadata.update(previous_metadata)
raise
async def _publish_goal_state_changed(self, metadata: dict[str, Any]) -> None:
"""Publish authoritative goal metadata as a runtime event."""
runtime_events = self._runtime_events
rc = current_request_context()
rc = self._request_ctx.get()
if runtime_events is None or rc is None:
return
cid = (rc.chat_id or "").strip()
@@ -112,23 +98,23 @@ class _GoalToolsMixin:
@tool_parameters(
tool_parameters_schema(
objective=StringSchema(
"The sustained objective for this session. It may consolidate a plan from earlier "
"discussion, but must be self-contained, bounded, safe under repetition, and "
"explicit about done-ness.",
min_length=1,
max_length=MAX_GOAL_OBJECTIVE_CHARS,
goal=StringSchema(
"Sustained objective for this chat thread. First read the built-in **long-goal** skill, "
"especially its Start fast section, then call this promptly once the user's intent is clear. "
"The goal must still be idempotent, self-contained, bounded, and explicit about done-ness; "
"do not delay this tool call to over-plan, research, or decide execution details.",
max_length=12_000,
),
ui_summary=StringSchema(
"Optional one-line display label for session lists and logs. It is not load-bearing.",
"Optional one-line label for session lists / logs (≤120 chars).",
max_length=120,
nullable=True,
),
required=["objective"],
required=["goal"],
)
)
class CreateGoalTool(Tool, _GoalToolsMixin):
"""Create one explicit sustained objective for the current session."""
class LongTaskTool(Tool, _GoalToolsMixin):
"""Begin or replace focus on a long-running objective stored on the session."""
def __init__(
self,
@@ -140,7 +126,7 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
@classmethod
def create(cls, ctx: Any) -> Tool:
sess = getattr(ctx, "sessions", None)
assert sess is not None
assert sess is not None # guarded by enabled()
return cls(
sessions=sess,
runtime_events=getattr(ctx, "runtime_events", None),
@@ -152,113 +138,88 @@ class CreateGoalTool(Tool, _GoalToolsMixin):
@property
def name(self) -> str:
return "create_goal"
return "long_task"
@property
def description(self) -> str:
return (
"Create one sustained goal for the current session when Goal Runtime Guidance asks "
"you to record it. Consolidate relevant prior discussion into a durable objective "
"that is self-contained, bounded, safe under repetition, and explicit about "
"completion criteria. Do not retry after a successful creation."
"Mark this thread as a sustained long-running task. "
"First read the built-in **long-goal** skill, especially its Start fast section; then call this "
"as soon as the user's intent is clear. Write a good idempotent goal, but do not delay the tool "
"call with long planning, research, or execution-detail thinking. "
"The active goal is mirrored in Runtime Context each turn. Use normal tools until done, then call "
"complete_goal when the objective is satisfied, cancelled, or replaced. "
"If a goal is already active, finish it or call complete_goal before registering another."
)
def runtime_context_provider(self):
return self._provide_runtime_context
async def _provide_runtime_context(
self,
request: RequestContext,
) -> RuntimeContextBlock | None:
if not request.session_key:
return None
session = self._sessions.get_or_create(request.session_key)
goal_start_requested = explicit_goal_requested(request.metadata)
goal_active = sustained_goal_active(session.metadata)
if not goal_start_requested and not goal_active:
return None
guidance = render_template(
"agent/goal_runtime.md",
strip=True,
goal_start_requested=goal_start_requested,
goal_active=goal_active,
)
state = wrap_runtime_context_lines(goal_state_runtime_lines(session.metadata))
content = "\n\n".join(part for part in (guidance, state) if part)
return RuntimeContextBlock(source="goal", content=content)
async def execute(
self,
objective: str,
ui_summary: str | None = None,
**kwargs: Any,
) -> str:
async def execute(self, goal: str, ui_summary: str | None = None, **kwargs: Any) -> str:
sess = self._session()
if sess is None:
return ToolResult.error(
"Error: create_goal requires an active chat session (missing routing context)."
return (
"Error: long_task requires an active chat session (missing routing context)."
)
if not self._goal_mutation_allowed():
return ToolResult.error(_CREATE_UNAVAILABLE_ERROR)
prior = parse_goal_state(goal_state_raw(sess.metadata))
if isinstance(prior, dict) and prior.get("status") == "active":
return ToolResult.error(
"Error: a sustained goal is already active. Use update_goal with "
"action='replace' only if the user explicitly changes the objective."
return (
"Error: a sustained goal is already active. "
"Use complete_goal when finished, or ask the user before replacing it."
)
objective_text = objective.strip()
if not objective_text:
return ToolResult.error("Error: objective must not be empty.")
if len(objective_text) > MAX_GOAL_OBJECTIVE_CHARS:
return ToolResult.error(
f"Error: objective must not exceed {MAX_GOAL_OBJECTIVE_CHARS} characters."
)
summary = (ui_summary or "").strip()[:120]
blob = {
"status": "active",
"objective": objective_text,
"objective": goal.strip(),
"ui_summary": summary,
"started_at": _iso_now(),
}
self._save_goal_state(sess, blob, reset_continuation=True)
sess.metadata[GOAL_STATE_KEY] = blob
discard_legacy_goal_state_key(sess.metadata)
self._sessions.save(sess)
await self._publish_goal_state_changed(sess.metadata)
extra = f"\nSummary line: {summary}" if summary else ""
return (
"Goal recorded. Keep working toward the objective using ordinary tools. "
"When fully done and verified, call update_goal with action='complete'."
f"{extra}"
"When fully done (verified against what was asked), call complete_goal with a "
f"short recap.{extra}"
)
@tool_parameters(
tool_parameters_schema(
action=StringSchema(
"How to update the active goal.",
enum=_GOAL_ACTIONS,
),
recap=StringSchema(
"Brief honest recap for the user. Required in practice for complete, cancel, and block.",
"Brief recap for the user (plain text). When the goal succeeded, confirm outcomes; "
"if the user cancelled, pivoted, or replaced the objective, say so honestly.",
max_length=8000,
nullable=True,
),
objective=StringSchema(
"Replacement objective. Required only when action is 'replace'; make it durable, "
"self-contained, bounded, and explicit about done-ness.",
max_length=MAX_GOAL_OBJECTIVE_CHARS,
verification_summary=StringSchema(
"For coding or file-producing tasks, summarize how the work was verified. "
"Mention the most relevant test/check command and whether it passed. "
"If no verification was possible, say why.",
max_length=4000,
nullable=True,
),
ui_summary=StringSchema(
"Optional one-line display label for a replacement goal.",
max_length=120,
commands_run=StringSchema(
"Optional concise list of verification/build commands run before completion.",
max_length=4000,
nullable=True,
),
required=["action"],
artifacts_created=StringSchema(
"Optional concise list of files, outputs, or artifacts created.",
max_length=4000,
nullable=True,
),
remaining_failures=StringSchema(
"Known unresolved failures, if intentionally stopping before success. "
"Leave empty when verification passes.",
max_length=4000,
nullable=True,
),
required=[],
)
)
class UpdateGoalTool(Tool, _GoalToolsMixin):
"""Complete, cancel, block, or replace the active sustained goal."""
class CompleteGoalTool(Tool, _GoalToolsMixin):
"""Mark the active sustained goal finished after all required work is verified."""
def __init__(
self,
@@ -282,89 +243,74 @@ class UpdateGoalTool(Tool, _GoalToolsMixin):
@property
def name(self) -> str:
return "update_goal"
return "complete_goal"
@property
def description(self) -> str:
return (
"Update the active sustained goal. Use action='complete' only after the objective "
"is actually achieved and verified. Use action='cancel' when the user cancels, "
"action='block' when progress is genuinely blocked, and action='replace' only when "
"the requested objective changes."
"End bookkeeping for the active sustained goal. "
"Use when the objective is fully achieved and verified—recap what was delivered. "
"For coding/file-producing tasks, run the smallest reliable verification first and include "
"verification_summary / commands_run / artifacts_created. "
"Also call when the user cancels, redirects, or replaces the goal: recap must reflect "
"what actually happened (not necessarily success). "
"If recent verification failed and no later verification passed, this tool will ask you to "
"continue fixing unless remaining_failures describes an intentional incomplete stop. "
"If no goal is active, the tool reports that and leaves metadata unchanged."
)
async def execute(
self,
action: str,
recap: str | None = None,
objective: str | None = None,
ui_summary: str | None = None,
verification_summary: str | None = None,
commands_run: str | None = None,
artifacts_created: str | None = None,
remaining_failures: str | None = None,
**kwargs: Any,
) -> str:
sess = self._session()
if sess is None:
return ToolResult.error("Error: update_goal requires an active chat session.")
return "Error: complete_goal requires an active chat session."
session_key = self._request_ctx.get().session_key if self._request_ctx.get() else None
observation = latest_verification_observation(session_key)
if (
observation is not None
and observation.analysis.status == "failed"
and not _has_meaningful_remaining_failures(remaining_failures)
):
return format_completion_gate_message(observation)
prior = parse_goal_state(goal_state_raw(sess.metadata))
if not isinstance(prior, dict) or prior.get("status") != "active":
return "No active goal to update."
normalized = (action or "").strip().lower()
if normalized not in _GOAL_ACTIONS:
return ToolResult.error(
"Error: action must be one of complete, cancel, block, or replace."
)
if normalized == "replace":
if not self._goal_mutation_allowed():
return ToolResult.error(_REPLACE_UNAVAILABLE_ERROR)
objective_text = (objective or "").strip()
if not objective_text:
return ToolResult.error(
"Error: update_goal action='replace' requires a replacement objective."
)
if len(objective_text) > MAX_GOAL_OBJECTIVE_CHARS:
return ToolResult.error(
f"Error: objective must not exceed {MAX_GOAL_OBJECTIVE_CHARS} characters."
)
summary = (ui_summary or "").strip()[:120]
blob = {
"status": "active",
"objective": objective_text,
"ui_summary": summary,
"started_at": _iso_now(),
"replaced_at": _iso_now(),
"previous_objective": str(prior.get("objective") or ""),
"recap": (recap or "").strip(),
}
self._save_goal_state(sess, blob, reset_continuation=True)
await self._publish_goal_state_changed(sess.metadata)
extra = f"\nSummary line: {summary}" if summary else ""
return "Goal replaced. Continue toward the new objective using ordinary tools." + extra
return "No active goal to complete."
ended = _iso_now()
status = {
"complete": "completed",
"cancel": "cancelled",
"block": "blocked",
}[normalized]
blob = {
completed = {
**prior,
"status": status,
"ended_at": ended,
"status": "completed",
"completed_at": ended,
"recap": (recap or "").strip(),
}
if normalized == "complete":
blob["completed_at"] = ended
self._save_goal_state(sess, blob)
revoke_goal_mutation_permission()
if verification_summary:
completed["verification_summary"] = verification_summary.strip()
if commands_run:
completed["commands_run"] = commands_run.strip()
if artifacts_created:
completed["artifacts_created"] = artifacts_created.strip()
if remaining_failures:
completed["remaining_failures"] = remaining_failures.strip()
sess.metadata[GOAL_STATE_KEY] = completed
discard_legacy_goal_state_key(sess.metadata)
self._sessions.save(sess)
clear_verification_observation(session_key)
await self._publish_goal_state_changed(sess.metadata)
tail = (recap or "").strip()
label = {
"complete": "complete",
"cancel": "cancelled",
"block": "blocked",
}[normalized]
if tail:
return f"Goal marked {label} ({ended}). Recap:\n{tail}"
return f"Goal marked {label} ({ended})."
return f"Goal marked complete ({ended}). Recap:\n{tail}"
return f"Goal marked complete ({ended})."
def _has_meaningful_remaining_failures(value: str | None) -> bool:
text = (value or "").strip().lower()
return bool(text and text not in {"none", "no", "n/a", "na", "no remaining failures"})
+141 -357
View File
@@ -1,21 +1,19 @@
"""MCP client: connects to MCP servers and wraps their tools as native nanobot tools."""
import asyncio
import hashlib
import json
import os
import re
import shutil
import urllib.parse
from collections.abc import Awaitable, Callable
from contextlib import AsyncExitStack, suppress
from typing import Any, Mapping, Protocol
from typing import Any, Mapping
from weakref import WeakKeyDictionary
import httpx
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.bus.events import (
INBOUND_META_RUNTIME_CONTROL,
@@ -23,14 +21,7 @@ from nanobot.bus.events import (
RUNTIME_CONTROL_MCP_RELOAD,
InboundMessage,
)
from nanobot.security.network import (
PinnedDNSAsyncTransport,
env_proxy_applies_to_url,
httpx_env_proxy_mounts,
resolve_url_target,
validate_url_target,
)
from nanobot.utils.cancellation import task_is_cancelling
from nanobot.security.network import validate_url_target
# Transient connection errors that warrant a single retry.
# These typically happen when an MCP server restarts or a network
@@ -55,26 +46,6 @@ _RELOAD_LOCKS: WeakKeyDictionary[Any, asyncio.Lock] = WeakKeyDictionary()
_ReconnectCallback = Callable[[str, str, Tool], Awaitable[Tool | None]]
class MCPConnection(Protocol):
async def aclose(self) -> None: ...
class _OwnedMCPConnection:
"""Close an MCP transport from the task that originally opened it."""
def __init__(self, owner: asyncio.Task[None], close_requested: asyncio.Event) -> None:
self._owner = owner
self._close_requested = close_requested
async def aclose(self) -> None:
self._close_requested.set()
try:
await asyncio.shield(self._owner)
except asyncio.CancelledError:
if not self._owner.cancelled():
raise
def _is_malformed_mcp_progress_notification(message: Any) -> bool:
payload = _mcp_jsonrpc_payload(message)
if _payload_value(payload, "method") != "notifications/progress":
@@ -150,25 +121,6 @@ def _sanitize_name(name: str) -> str:
return _SANITIZE_RE.sub("_", re.sub(r"[^a-zA-Z0-9_-]", "_", name))
_MAX_TOOL_NAME_LENGTH = 64
_HASH_LENGTH = 8
def _limit_tool_name(name: str, max_length: int = _MAX_TOOL_NAME_LENGTH) -> str:
"""Limit a tool name while keeping short names unchanged."""
if len(name) <= max_length:
return name
digest = hashlib.sha1(name.encode("utf-8")).hexdigest()[:_HASH_LENGTH]
prefix_length = max_length - _HASH_LENGTH - 1
return f"{name[:prefix_length]}_{digest}"
def _sanitize_mcp_tool_name(name: str) -> str:
"""Sanitize and limit an MCP-derived tool name."""
return _limit_tool_name(_sanitize_name(name))
def _is_transient(exc: BaseException) -> bool:
"""Check if an exception looks like a transient connection error."""
return type(exc).__name__ in _TRANSIENT_EXC_NAMES
@@ -176,8 +128,6 @@ def _is_transient(exc: BaseException) -> bool:
def _is_session_terminated(exc: BaseException) -> bool:
"""Return True when the MCP SDK reports a dead client session."""
if _is_transient(exc):
return True
messages = [str(exc)]
error = getattr(exc, "error", None)
if error is not None:
@@ -202,51 +152,17 @@ async def _probe_http_url(url: str, timeout: float = 3.0) -> bool:
port = parsed.port
if not port:
port = 443 if parsed.scheme == "https" else 80
ok, _, resolved_ips = resolve_url_target(url)
if not ok:
return False
if env_proxy_applies_to_url(url):
return True
for target_host in resolved_ips or (host,):
try:
_reader, writer = await asyncio.wait_for(
asyncio.open_connection(target_host, port),
timeout=timeout,
)
writer.close()
with suppress(OSError, asyncio.TimeoutError):
await asyncio.wait_for(writer.wait_closed(), timeout=0.2)
return True
except (OSError, asyncio.TimeoutError):
continue
return False
def _redact_url(url: str) -> str:
"""Strip credentials and query/fragment before logging an MCP URL.
Server URLs may embed secrets (``https://user:token@host/sse`` or a
``?token=`` query). Some deployments also put opaque tokens in the path, so
log only the origin and a path placeholder.
"""
try:
parts = urllib.parse.urlsplit(url)
hostname = parts.hostname or ""
netloc = f"[{hostname}]" if ":" in hostname else hostname
if parts.port:
netloc = f"{netloc}:{parts.port}"
path = "/..." if parts.path and parts.path != "/" else parts.path
return urllib.parse.urlunsplit((parts.scheme, netloc, path, "", ""))
except Exception:
return "<redacted-url>"
def _pinned_transport_kwargs() -> dict[str, object]:
kwargs: dict[str, object] = {"transport": PinnedDNSAsyncTransport()}
mounts = httpx_env_proxy_mounts()
if mounts:
kwargs["mounts"] = mounts
return kwargs
reader, writer = await asyncio.wait_for(
asyncio.open_connection(host, port),
timeout=timeout,
)
writer.close()
with suppress(OSError, asyncio.TimeoutError):
await asyncio.wait_for(writer.wait_closed(), timeout=0.2)
return True
except (OSError, asyncio.TimeoutError):
return False
async def _validate_mcp_request_url(request: httpx.Request) -> None:
@@ -254,7 +170,7 @@ async def _validate_mcp_request_url(request: httpx.Request) -> None:
ok, error = validate_url_target(str(request.url))
if not ok:
raise httpx.RequestError(
f"Blocked unsafe MCP URL {_redact_url(str(request.url))} ({error})",
f"Blocked unsafe MCP URL {request.url} ({error})",
request=request,
)
@@ -397,52 +313,6 @@ class _MCPWrapperBase(Tool):
return True
def _image_block_data_url(block: Any, types: Any) -> str | None:
"""Return a base64 ``data:`` URL for an MCP image-bearing content block.
Handles ``ImageContent`` directly and ``EmbeddedResource`` wrapping a binary
blob with an ``image/*`` MIME type. Returns ``None`` for anything else.
``getattr`` guards keep this safe when the installed/faked ``mcp`` SDK does
not expose a given type.
"""
image_cls = getattr(types, "ImageContent", None)
if image_cls is not None and isinstance(block, image_cls):
mime = getattr(block, "mimeType", None) or "image/png"
return f"data:{mime};base64,{block.data}"
embedded_cls = getattr(types, "EmbeddedResource", None)
blob_cls = getattr(types, "BlobResourceContents", None)
if embedded_cls is not None and isinstance(block, embedded_cls):
resource = getattr(block, "resource", None)
if blob_cls is not None and isinstance(resource, blob_cls):
mime = getattr(resource, "mimeType", None) or ""
if isinstance(mime, str) and mime.startswith("image/"):
return f"data:{mime};base64,{resource.blob}"
return None
def _mcp_image_tool_result(text_parts: list[str], artifacts: list[dict[str, Any]]) -> str:
"""Build the compact tool result for an MCP call that returned image(s).
The base64 stays out of the model context entirely only artifact paths and
metadata are returned, so the result is small and the channel can deliver the
saved file via the message tool.
"""
payload: dict[str, Any] = {
"artifacts": artifacts,
"next_step": (
"These images were returned by an MCP tool and saved as local artifacts. "
"Call the message tool with the artifact 'path' values in the media "
"parameter to deliver the images to the user. Do not paste base64 or raw "
"paths into your reply unless the user asks for debug details."
),
}
text = "\n".join(part for part in text_parts if part)
if text:
payload["text"] = text
return json.dumps(payload, ensure_ascii=False)
class MCPToolWrapper(_MCPWrapperBase):
"""Wraps a single MCP server tool as a nanobot Tool."""
@@ -451,7 +321,7 @@ class MCPToolWrapper(_MCPWrapperBase):
def __init__(self, session, server_name: str, tool_def, tool_timeout: int = 30):
self._set_mcp_connection(session, server_name)
self._original_name = tool_def.name
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_{tool_def.name}")
self._name = _sanitize_name(f"mcp_{server_name}_{tool_def.name}")
self._description = tool_def.description or tool_def.name
raw_schema = tool_def.inputSchema or {"type": "object", "properties": {}}
self._parameters = _normalize_schema_for_openai(raw_schema)
@@ -470,6 +340,8 @@ class MCPToolWrapper(_MCPWrapperBase):
return self._parameters
async def execute(self, **kwargs: Any) -> str:
from mcp import types
retried_transient = False
refreshed_session = False
while True:
@@ -482,16 +354,15 @@ class MCPToolWrapper(_MCPWrapperBase):
logger.warning(
"MCP tool '{}' timed out after {}s", self._name, self._tool_timeout
)
return ToolResult.error(
f"(MCP tool call timed out after {self._tool_timeout}s)"
)
return f"(MCP tool call timed out after {self._tool_timeout}s)"
except asyncio.CancelledError:
# MCP SDK's anyio cancel scopes can leak CancelledError on timeout/failure.
# Re-raise only if our task was externally cancelled (e.g. /stop).
if task_is_cancelling():
task = asyncio.current_task()
if task is not None and task.cancelling() > 0:
raise
logger.warning("MCP tool '{}' was cancelled by server/SDK", self._name)
return ToolResult.error("(MCP tool call was cancelled)")
return "(MCP tool call was cancelled)"
except Exception as exc:
if await self._refresh_session_after_termination(
exc,
@@ -516,87 +387,25 @@ class MCPToolWrapper(_MCPWrapperBase):
self._name,
type(exc).__name__,
)
return ToolResult.error(
f"(MCP tool call failed after retry: {type(exc).__name__})"
)
return f"(MCP tool call failed after retry: {type(exc).__name__})"
logger.exception(
"MCP tool '{}' failed: {}: {}",
self._name,
type(exc).__name__,
exc,
)
return ToolResult.error(
f"(MCP tool call failed: {type(exc).__name__})"
)
return f"(MCP tool call failed: {type(exc).__name__})"
else:
# Success — extract text and persist any image content as artifacts.
try:
rendered = self._render_call_result(result.content, kwargs)
if getattr(result, "isError", False):
return ToolResult.error(rendered)
return rendered
except Exception as exc:
logger.exception(
"MCP tool '{}' failed while rendering result: {}: {}",
self._name,
type(exc).__name__,
exc,
)
return ToolResult.error(
f"(MCP tool returned malformed content: {type(exc).__name__})"
)
# Success — extract result
parts = []
for block in result.content:
if isinstance(block, types.TextContent):
parts.append(block.text)
else:
parts.append(str(block))
return "\n".join(parts) or "(no output)"
def _render_call_result(self, content: Any, arguments: Mapping[str, Any]) -> str:
"""Turn MCP content blocks into a tool result string.
Text is concatenated as before. Image blocks are decoded and saved as
local artifacts (mirroring the built-in image generation tool) so the
model can deliver them via the message tool instead of trying to forward
base64 which would be truncated and bloat the context window.
"""
from mcp import types
text_parts: list[str] = []
artifacts: list[dict[str, Any]] = []
for block in content:
if isinstance(block, types.TextContent):
text_parts.append(block.text)
continue
data_url = _image_block_data_url(block, types)
if data_url is not None:
stored = self._store_image_block(data_url, arguments)
if stored is not None:
artifacts.append(stored)
else:
text_parts.append("(MCP tool returned an image that could not be stored)")
continue
text_parts.append(str(block))
if artifacts:
return _mcp_image_tool_result(text_parts, artifacts)
return "\n".join(text_parts) or "(no output)"
def _store_image_block(
self, data_url: str, arguments: Mapping[str, Any]
) -> dict[str, Any] | None:
"""Persist one image data URL as an artifact; return its metadata or None."""
from nanobot.utils.artifacts import ArtifactError, store_generated_image_artifact
try:
return store_generated_image_artifact(
data_url,
prompt=str(arguments.get("prompt") or ""),
model=str(arguments.get("model") or ""),
save_dir="generated",
provider=f"mcp:{self._server_name}",
)
except (ArtifactError, OSError) as exc:
logger.warning(
"MCP tool '{}' returned an image that could not be stored: {}",
self._name,
exc,
)
return None
return "(MCP tool call failed)" # Unreachable, but satisfies type checkers
class MCPResourceWrapper(_MCPWrapperBase):
@@ -607,7 +416,7 @@ class MCPResourceWrapper(_MCPWrapperBase):
def __init__(self, session, server_name: str, resource_def, resource_timeout: int = 30):
self._set_mcp_connection(session, server_name)
self._uri = resource_def.uri
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_resource_{resource_def.name}")
self._name = _sanitize_name(f"mcp_{server_name}_resource_{resource_def.name}")
desc = resource_def.description or resource_def.name
self._description = f"[MCP Resource] {desc}\nURI: {self._uri}"
self._parameters: dict[str, Any] = {
@@ -650,7 +459,8 @@ class MCPResourceWrapper(_MCPWrapperBase):
)
return f"(MCP resource read timed out after {self._resource_timeout}s)"
except asyncio.CancelledError:
if task_is_cancelling():
task = asyncio.current_task()
if task is not None and task.cancelling() > 0:
raise
logger.warning("MCP resource '{}' was cancelled by server/SDK", self._name)
return "(MCP resource read was cancelled)"
@@ -696,6 +506,8 @@ class MCPResourceWrapper(_MCPWrapperBase):
parts.append(str(block))
return "\n".join(parts) or "(no output)"
return "(MCP resource read failed)" # Unreachable
class MCPPromptWrapper(_MCPWrapperBase):
"""Wraps an MCP prompt as a read-only nanobot Tool."""
@@ -705,7 +517,7 @@ class MCPPromptWrapper(_MCPWrapperBase):
def __init__(self, session, server_name: str, prompt_def, prompt_timeout: int = 30):
self._set_mcp_connection(session, server_name)
self._prompt_name = prompt_def.name
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_prompt_{prompt_def.name}")
self._name = _sanitize_name(f"mcp_{server_name}_prompt_{prompt_def.name}")
desc = prompt_def.description or prompt_def.name
self._description = (
f"[MCP Prompt] {desc}\n"
@@ -763,7 +575,8 @@ class MCPPromptWrapper(_MCPWrapperBase):
)
return f"(MCP prompt call timed out after {self._prompt_timeout}s)"
except asyncio.CancelledError:
if task_is_cancelling():
task = asyncio.current_task()
if task is not None and task.cancelling() > 0:
raise
logger.warning("MCP prompt '{}' was cancelled by server/SDK", self._name)
return "(MCP prompt call was cancelled)"
@@ -829,22 +642,24 @@ class MCPPromptWrapper(_MCPWrapperBase):
parts.append(str(content))
return "\n".join(parts) or "(no output)"
return "(MCP prompt call failed)" # Unreachable
async def connect_mcp_servers(
mcp_servers: dict, registry: ToolRegistry
) -> dict[str, MCPConnection]:
) -> dict[str, AsyncExitStack]:
"""Connect to configured MCP servers and register their tools, resources, prompts.
Returns one connection handle per server. Each handle keeps the task that
entered the MCP SDK contexts alive so reconnect and shutdown can close
AnyIO cancel scopes from their owning task.
Returns a dict mapping server name -> its dedicated AsyncExitStack.
Each server gets its own stack to prevent cancel scope conflicts
when multiple MCP servers are configured.
"""
from mcp import ClientSession, StdioServerParameters
from mcp.client.sse import sse_client
from mcp.client.stdio import stdio_client
from mcp.client.streamable_http import streamable_http_client
async def open_single_server(name: str, cfg) -> tuple[str, AsyncExitStack | None]:
async def connect_single_server(name: str, cfg) -> tuple[str, AsyncExitStack | None]:
server_stack = AsyncExitStack()
await server_stack.__aenter__()
@@ -868,7 +683,7 @@ async def connect_mcp_servers(
logger.warning(
"MCP server '{}': blocked unsafe URL {} ({})",
name,
_redact_url(cfg.url),
cfg.url,
error,
)
await server_stack.aclose()
@@ -889,7 +704,7 @@ async def connect_mcp_servers(
read, write = await server_stack.enter_async_context(stdio_client(params))
elif transport_type == "sse":
if not await _probe_http_url(cfg.url):
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
logger.warning("MCP server '{}': {} unreachable, skipping", name, cfg.url)
await server_stack.aclose()
return name, None
@@ -909,7 +724,6 @@ async def connect_mcp_servers(
follow_redirects=True,
timeout=timeout,
auth=auth,
**_pinned_transport_kwargs(),
)
read, write = await server_stack.enter_async_context(
@@ -917,7 +731,7 @@ async def connect_mcp_servers(
)
elif transport_type == "streamableHttp":
if not await _probe_http_url(cfg.url):
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
logger.warning("MCP server '{}': {} unreachable, skipping", name, cfg.url)
await server_stack.aclose()
return name, None
@@ -927,7 +741,6 @@ async def connect_mcp_servers(
event_hooks={"request": [_validate_mcp_request_url]},
follow_redirects=True,
timeout=httpx.Timeout(30.0, connect=10.0),
**_pinned_transport_kwargs(),
)
)
read, write, _ = await server_stack.enter_async_context(
@@ -948,9 +761,9 @@ async def connect_mcp_servers(
registered_count = 0
matched_enabled_tools: set[str] = set()
available_raw_names = [tool_def.name for tool_def in tools.tools]
available_wrapped_names = [_sanitize_mcp_tool_name(f"mcp_{name}_{tool_def.name}") for tool_def in tools.tools]
available_wrapped_names = [_sanitize_name(f"mcp_{name}_{tool_def.name}") for tool_def in tools.tools]
for tool_def in tools.tools:
wrapped_name = _sanitize_mcp_tool_name(f"mcp_{name}_{tool_def.name}")
wrapped_name = _sanitize_name(f"mcp_{name}_{tool_def.name}")
if (
not allow_all_tools
and tool_def.name not in enabled_tools
@@ -1063,43 +876,7 @@ async def connect_mcp_servers(
await server_stack.aclose()
return name, None
async def connect_single_server(name: str, cfg) -> tuple[str, MCPConnection | None]:
loop = asyncio.get_running_loop()
ready: asyncio.Future[bool] = loop.create_future()
close_requested = asyncio.Event()
async def own_connection() -> None:
stack: AsyncExitStack | None = None
try:
_, stack = await open_single_server(name, cfg)
if not ready.done():
ready.set_result(stack is not None)
if stack is not None:
await close_requested.wait()
except BaseException as exc:
if not ready.done():
ready.set_exception(exc)
raise
finally:
if stack is not None:
await stack.aclose()
owner = asyncio.create_task(own_connection(), name=f"mcp:{name}")
connection = _OwnedMCPConnection(owner, close_requested)
try:
connected = await ready
except BaseException:
close_requested.set()
owner.cancel()
with suppress(BaseException):
await asyncio.shield(owner)
raise
if not connected:
await connection.aclose()
return name, None
return name, connection
server_stacks: dict[str, MCPConnection] = {}
server_stacks: dict[str, AsyncExitStack] = {}
for name, cfg in mcp_servers.items():
try:
@@ -1119,48 +896,93 @@ def session_extra(metadata: Mapping[str, Any] | None) -> dict[str, Any]:
return {"mcp_presets": mcp_presets} if isinstance(mcp_presets, list) and mcp_presets else {}
def runtime_lines(
message: Any,
*,
available_server_names: set[str] | None = None,
configured_server_names: set[str] | None = None,
connected_server_names: set[str] | None = None,
skip: bool = False,
) -> list[str]:
"""Return model-visible MCP preset annotations for the current turn."""
if skip:
return []
if configured_server_names is None:
configured_server_names = available_server_names
if connected_server_names is None:
connected_server_names = available_server_names
metadata = message.metadata if isinstance(getattr(message, "metadata", None), Mapping) else None
structured = metadata.get("mcp_presets") if isinstance(metadata, Mapping) else None
if not isinstance(structured, list):
return []
lines: list[str] = []
for item in structured[:8]:
if not isinstance(item, Mapping):
continue
raw_name = str(item.get("name") or "").strip().lower()
if not raw_name:
continue
display = str(item.get("display_name") or raw_name).strip() or raw_name
transport = str(item.get("transport") or "mcp").strip() or "mcp"
prefix = f"mcp_{raw_name}_"
if configured_server_names is not None and raw_name not in configured_server_names:
lines.append(
"MCP Preset Attachment: "
f"@{raw_name} ({display}; transport={transport}) is configured in WebUI Settings, "
"but this gateway has not loaded the latest MCP settings yet. "
f"Tools with prefix `{prefix}` may not be available yet; if they are missing, "
"tell the user to restart nanobot."
)
continue
if connected_server_names is not None and raw_name not in connected_server_names:
lines.append(
"MCP Preset Attachment: "
f"@{raw_name} ({display}; transport={transport}) is configured, "
"but its MCP connection is not currently live. "
f"Tools with prefix `{prefix}` may be unavailable; tell the user to open Settings, "
"run the preset test, and restart nanobot only if hot reload is unavailable."
)
continue
lines.append(
"MCP Preset Attachment: "
f"@{raw_name} ({display}; transport={transport}; tool_prefix={prefix}). "
f"Prefer available tools whose names start with `{prefix}` for this request; "
"do not substitute shell commands for this MCP integration unless the user asks."
)
return lines
async def connect_missing_servers(state: Any, registry: ToolRegistry) -> None:
"""Connect configured MCP servers that are not currently live."""
async with _reload_lock(state):
if getattr(state, "_mcp_closing", False):
return
missing_servers = {
name: cfg for name, cfg in state._mcp_servers.items() if name not in state._mcp_stacks
}
if state._mcp_connecting or not missing_servers:
return
state._mcp_connecting = True
try:
connected = await connect_mcp_servers(missing_servers, registry)
if getattr(state, "_mcp_closing", False):
for connection in connected.values():
await connection.aclose()
return
state._mcp_stacks.update(connected)
_attach_reconnect_handlers(state, registry, connected)
if connected:
logger.info("MCP connected servers: {}", sorted(connected))
else:
logger.warning("No MCP servers connected successfully (will retry next message)")
except asyncio.CancelledError:
if task_is_cancelling():
raise
logger.warning("MCP connection cancelled (will retry next message)")
except BaseException as e:
logger.warning("Failed to connect MCP servers (will retry next message): {}", e)
finally:
state._mcp_connecting = False
missing_servers = {
name: cfg for name, cfg in state._mcp_servers.items() if name not in state._mcp_stacks
}
if state._mcp_connecting or not missing_servers:
return
state._mcp_connecting = True
try:
connected = await connect_mcp_servers(missing_servers, registry)
state._mcp_stacks.update(connected)
_attach_reconnect_handlers(state, registry, connected)
state._mcp_connected = bool(state._mcp_stacks)
if connected:
logger.info("MCP connected servers: {}", sorted(connected))
else:
logger.warning("No MCP servers connected successfully (will retry next message)")
except asyncio.CancelledError:
logger.warning("MCP connection cancelled (will retry next message)")
state._mcp_connected = bool(state._mcp_stacks)
except BaseException as e:
logger.warning("Failed to connect MCP servers (will retry next message): {}", e)
state._mcp_connected = bool(state._mcp_stacks)
finally:
state._mcp_connecting = False
async def reload_servers(state: Any, registry: ToolRegistry) -> dict[str, Any]:
"""Reconcile live MCP connections with the current config file."""
async with _reload_lock(state):
if getattr(state, "_mcp_closing", False):
return {
"ok": False,
"message": "MCP connections are shutting down.",
"requires_restart": True,
}
try:
from nanobot.config.loader import load_config, resolve_config_env_vars
@@ -1199,20 +1021,13 @@ async def reload_servers(state: Any, registry: ToolRegistry) -> dict[str, Any]:
)
to_connect_names = sorted(set(added) | set(changed) | set(retry_missing))
to_connect = {name: next_servers[name] for name in to_connect_names}
connected: dict[str, MCPConnection] = {}
connected: dict[str, AsyncExitStack] = {}
if to_connect:
connected = await connect_mcp_servers(to_connect, registry)
if getattr(state, "_mcp_closing", False):
for connection in connected.values():
await connection.aclose()
return {
"ok": False,
"message": "MCP connections are shutting down.",
"requires_restart": True,
}
state._mcp_stacks.update(connected)
_attach_reconnect_handlers(state, registry, connected)
state._mcp_connected = bool(state._mcp_stacks)
failed = sorted(set(to_connect) - set(connected))
unchanged = not removed and not added and not changed and not retry_missing
ok = not failed
@@ -1327,10 +1142,11 @@ def _attach_reconnect_handlers(
)
for server_name in server_names:
prefix = _tool_prefix(server_name)
for tool_name in list(registry.tool_names):
tool = registry.get(tool_name)
if not _tool_belongs_to_server(tool, tool_name, server_name):
if not tool_name.startswith(prefix):
continue
tool = registry.get(tool_name)
if isinstance(tool, _MCPWrapperBase):
tool.set_reconnect_handler(reconnect)
@@ -1343,8 +1159,6 @@ async def _refresh_terminated_server(
stale_tool: Tool,
) -> Tool | None:
async with _reload_lock(state):
if getattr(state, "_mcp_closing", False):
return None
cfg = state._mcp_servers.get(server_name)
if cfg is None:
logger.warning(
@@ -1366,12 +1180,9 @@ async def _refresh_terminated_server(
await _close_server(state, server_name)
connected = await connect_mcp_servers({server_name: cfg}, registry)
if getattr(state, "_mcp_closing", False):
for connection in connected.values():
await connection.aclose()
return None
state._mcp_stacks.update(connected)
_attach_reconnect_handlers(state, registry, connected)
state._mcp_connected = bool(state._mcp_stacks)
if server_name not in connected:
logger.warning("MCP server '{}' reconnect failed after session termination", server_name)
return None
@@ -1388,17 +1199,11 @@ def _tool_prefix(server_name: str) -> str:
return _sanitize_name(f"mcp_{server_name}_")
def _tool_belongs_to_server(tool: Tool | None, tool_name: str, server_name: str) -> bool:
if isinstance(tool, _MCPWrapperBase):
return getattr(tool, "_server_name", None) == server_name
return tool_name.startswith(_tool_prefix(server_name))
def _unregister_server_tools(state: Any, registry: ToolRegistry, server_name: str) -> int:
prefix = _tool_prefix(server_name)
removed = 0
for tool_name in list(registry.tool_names):
tool = registry.get(tool_name)
if _tool_belongs_to_server(tool, tool_name, server_name):
if tool_name.startswith(prefix):
registry.unregister(tool_name)
removed += 1
return removed
@@ -1410,26 +1215,5 @@ async def _close_server(state: Any, server_name: str) -> None:
return
try:
await stack.aclose()
except asyncio.CancelledError:
if task_is_cancelling():
raise
logger.debug("MCP server '{}' cleanup error (can be ignored)", server_name)
except (RuntimeError, BaseExceptionGroup):
logger.debug("MCP server '{}' cleanup error (can be ignored)", server_name)
async def close_mcp_servers(state: Any) -> None:
"""Close every MCP connection while excluding reconnect and hot reload."""
state._mcp_closing = True
async with _reload_lock(state):
connections = list(state._mcp_stacks.items())
state._mcp_stacks.clear()
for name, connection in connections:
try:
await connection.aclose()
except asyncio.CancelledError:
if task_is_cancelling():
raise
logger.debug("MCP server '{}' cleanup error (can be ignored)", name)
except (RuntimeError, BaseExceptionGroup):
logger.debug("MCP server '{}' cleanup error (can be ignored)", name)
+34 -32
View File
@@ -6,8 +6,8 @@ from typing import Any, Awaitable, Callable
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.path_utils import resolve_workspace_path
from nanobot.agent.tools.schema import ArraySchema, StringSchema, tool_parameters_schema
from nanobot.bus.events import OutboundMessage
@@ -45,7 +45,7 @@ from nanobot.security.workspace_access import current_tool_workspace
required=["content"],
)
)
class MessageTool(Tool):
class MessageTool(Tool, ContextAware):
"""Tool to send messages to users on chat channels."""
def __init__(
@@ -62,10 +62,20 @@ class MessageTool(Tool):
Path(workspace).expanduser() if workspace is not None else get_workspace_path()
)
self._restrict_to_workspace = restrict_to_workspace
self._fallback_channel = default_channel
self._fallback_chat_id = default_chat_id
self._fallback_message_id = default_message_id
self._fallback_metadata: dict[str, Any] = {}
self._default_channel: ContextVar[str] = ContextVar(
"message_default_channel", default=default_channel
)
self._default_chat_id: ContextVar[str] = ContextVar(
"message_default_chat_id", default=default_chat_id
)
self._default_message_id: ContextVar[str | None] = ContextVar(
"message_default_message_id",
default=default_message_id,
)
self._default_metadata: ContextVar[dict[str, Any]] = ContextVar(
"message_default_metadata",
default={},
)
self._sent_in_turn_var: ContextVar[bool] = ContextVar("message_sent_in_turn", default=False)
self._turn_delivered_media_var: ContextVar[tuple[str, ...]] = ContextVar(
"message_turn_delivered_media",
@@ -89,6 +99,13 @@ class MessageTool(Tool):
restrict_to_workspace=ctx.config.restrict_to_workspace,
)
def set_context(self, ctx: RequestContext) -> None:
"""Set the current message context."""
self._default_channel.set(ctx.channel)
self._default_chat_id.set(ctx.chat_id)
self._default_message_id.set(ctx.message_id)
self._default_metadata.set(dict(ctx.metadata or {}))
def set_send_callback(self, callback: Callable[[OutboundMessage], Awaitable[None]]) -> None:
"""Set the callback for sending messages."""
self._send_callback = callback
@@ -181,24 +198,9 @@ class MessageTool(Tool):
not isinstance(row, list) or any(not isinstance(label, str) for label in row)
for row in buttons
):
return ToolResult.error("Error: buttons must be a list of list of strings")
request_ctx = current_request_context()
default_channel = (
request_ctx.channel if request_ctx is not None else self._fallback_channel
)
default_chat_id = (
request_ctx.chat_id if request_ctx is not None else self._fallback_chat_id
)
default_message_id = (
request_ctx.message_id
if request_ctx is not None
else self._fallback_message_id
)
default_metadata = (
request_ctx.metadata
if request_ctx is not None
else self._fallback_metadata
)
return "Error: buttons must be a list of list of strings"
default_channel = self._default_channel.get()
default_chat_id = self._default_chat_id.get()
channel = channel or default_channel
explicit_chat_id = chat_id
if (
@@ -208,7 +210,7 @@ class MessageTool(Tool):
and str(explicit_chat_id).strip() != ""
and str(explicit_chat_id).strip() != str(default_chat_id).strip()
):
return ToolResult.error(
return (
"Error: chat_id does not match the active WebSocket conversation. "
"Omit chat_id (and usually channel) so delivery uses the current "
"conversation id from context — WebSocket client_id strings "
@@ -222,23 +224,23 @@ class MessageTool(Tool):
# to the wrong chat entirely.
same_target = channel == default_channel and chat_id == default_chat_id
if same_target:
message_id = message_id or default_message_id
message_id = message_id or self._default_message_id.get()
else:
message_id = None
if not channel or not chat_id:
return ToolResult.error("Error: No target channel/chat specified")
return "Error: No target channel/chat specified"
if not self._send_callback:
return ToolResult.error("Error: Message sending not configured")
return "Error: Message sending not configured"
if media:
try:
media = self._resolve_media(media)
except (OSError, PermissionError, ValueError) as e:
return ToolResult.error(f"Error: media path is not allowed: {str(e)}")
return f"Error: media path is not allowed: {str(e)}"
metadata = dict(default_metadata) if same_target else {}
metadata = dict(self._default_metadata.get()) if same_target else {}
if message_id:
metadata["message_id"] = message_id
if self._record_channel_delivery_var.get() or media:
@@ -268,4 +270,4 @@ class MessageTool(Tool):
button_info = f" with {sum(len(row) for row in buttons)} button(s)" if buttons else ""
return f"Message sent to {channel}:{chat_id}{media_info}{button_info}"
except Exception as e:
return ToolResult.error(f"Error sending message: {str(e)}")
return f"Error sending message: {str(e)}"
+11 -40
View File
@@ -1,19 +1,9 @@
"""Tool registry for dynamic tool management."""
from __future__ import annotations
import json
from typing import TYPE_CHECKING, Any
from typing import Any
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.context import ContextAware, current_request_context
if TYPE_CHECKING:
from nanobot.runtime_context import RuntimeContextProvider
def is_tool_error_result(name: str, result: Any) -> bool:
return isinstance(result, ToolResult) and result.is_error
from nanobot.agent.tools.base import Tool
class ToolRegistry:
@@ -41,15 +31,6 @@ class ToolRegistry:
"""Get a tool by name."""
return self._tools.get(name)
def get_runtime_context_providers(self) -> list[RuntimeContextProvider]:
"""Return tool-owned providers in stable tool-name order."""
providers: list[RuntimeContextProvider] = []
for name in sorted(self._tools):
provider = self._tools[name].runtime_context_provider()
if provider is not None:
providers.append(provider)
return providers
@staticmethod
def _lookup_key(name: str) -> str:
"""Normalize names for suggestions only; never for execution."""
@@ -119,32 +100,22 @@ class ToolRegistry:
suggestion = self._suggest_name(str(name))
hint = f" Did you mean '{suggestion}'? Tool names must match exactly." if suggestion else ""
return None, params, (
ToolResult.error(
f"Error: Tool '{name}' not found.{hint} Available: {', '.join(self.tool_names)}"
)
f"Error: Tool '{name}' not found.{hint} Available: {', '.join(self.tool_names)}"
)
# Compatibility for external tools that still implement the legacy
# setter protocol. Built-ins read the authoritative ContextVar
# directly and never copy routing state.
if isinstance(tool, ContextAware) and (ctx := current_request_context()) is not None:
tool.set_context(ctx)
params = self._coerce_params(tool, params)
if not isinstance(params, dict):
return tool, params, (
ToolResult.error(
f"Error: Tool '{name}' parameters must be a JSON object, got "
f"{type(params).__name__}. Use named parameters like "
'tool_name(param1="value1", param2="value2") matching the tool schema.'
)
f"Error: Tool '{name}' parameters must be a JSON object, got "
f"{type(params).__name__}. Use named parameters like "
'tool_name(param1="value1", param2="value2") matching the tool schema.'
)
cast_params = tool.cast_params(params)
errors = tool.validate_params(cast_params)
if errors:
return tool, cast_params, (
ToolResult.error(f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors))
f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors)
)
return tool, cast_params, None
@@ -188,16 +159,16 @@ class ToolRegistry:
hint = "\n\n[Analyze the error above and try a different approach.]"
tool, params, error = self.prepare_call(name, params)
if error:
return ToolResult.error(str(error) + hint)
return error + hint
try:
assert tool is not None # guarded by prepare_call()
result = await tool.execute(**params)
if is_tool_error_result(name, result):
return ToolResult.error(str(result) + hint)
if isinstance(result, str) and result.startswith("Error"):
return result + hint
return result
except Exception as e:
return ToolResult.error(f"Error executing {name}: {str(e)}" + hint)
return f"Error executing {name}: {str(e)}" + hint
@property
def tool_names(self) -> list[str]:
+2 -4
View File
@@ -56,9 +56,7 @@ class RuntimeState(Protocol):
def _sync_subagent_runtime_limits(self) -> None: ...
def set_runtime_model(self, model: str) -> Any: ...
def set_runtime_context_window(self, context_window_tokens: int) -> Any: ...
@property
def model_preset(self) -> str | None: ...
_active_preset: str | None
-3
View File
@@ -33,9 +33,6 @@ def _bwrap(command: str, workspace: str, cwd: str) -> str:
"/lib64",
"/etc/alternatives",
"/etc/ssl/certs",
"/etc/pki/tls/certs",
"/etc/pki/ca-trust",
"/etc/crypto-policies",
"/etc/resolv.conf",
"/etc/ld.so.cache",
]
+10 -11
View File
@@ -9,7 +9,6 @@ from contextlib import suppress
from pathlib import Path, PurePosixPath
from typing import Any, Iterable, TypeVar
from nanobot.agent.tools.base import ToolResult
from nanobot.agent.tools.filesystem import ListDirTool, _FsTool
_DEFAULT_HEAD_LIMIT = 250
@@ -219,12 +218,12 @@ class FindFilesTool(_SearchTool):
try:
target = self._resolve(path or ".")
if not target.exists():
return ToolResult.error(f"Error: Path not found: {path}")
return f"Error: Path not found: {path}"
if not (target.is_dir() or target.is_file()):
return ToolResult.error(f"Error: Unsupported path: {path}")
return f"Error: Unsupported path: {path}"
if sort not in {"path", "modified"}:
return ToolResult.error("Error: sort must be 'path' or 'modified'")
return "Error: sort must be 'path' or 'modified'"
limit = (
_DEFAULT_FILE_HEAD_LIMIT
@@ -272,9 +271,9 @@ class FindFilesTool(_SearchTool):
result += "\n\n" + note
return result
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
return f"Error: {e}"
except Exception as e:
return ToolResult.error(f"Error finding files: {e}")
return f"Error finding files: {e}"
class GrepTool(_SearchTool):
@@ -426,16 +425,16 @@ class GrepTool(_SearchTool):
try:
target = self._resolve(path or ".")
if not target.exists():
return ToolResult.error(f"Error: Path not found: {path}")
return f"Error: Path not found: {path}"
if not (target.is_dir() or target.is_file()):
return ToolResult.error(f"Error: Unsupported path: {path}")
return f"Error: Unsupported path: {path}"
flags = re.IGNORECASE if case_insensitive else 0
try:
needle = re.escape(pattern) if fixed_strings else pattern
regex = re.compile(needle, flags)
except re.error as e:
return ToolResult.error(f"Error: invalid regex pattern: {e}")
return f"Error: invalid regex pattern: {e}"
if head_limit is not None:
limit = None if head_limit == 0 else head_limit
@@ -580,6 +579,6 @@ class GrepTool(_SearchTool):
result += "\n\n" + "\n".join(notes)
return result
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
return f"Error: {e}"
except Exception as e:
return ToolResult.error(f"Error searching files: {e}")
return f"Error searching files: {e}"
+42 -85
View File
@@ -7,8 +7,8 @@ from typing import TYPE_CHECKING, Any
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.runtime_state import RuntimeState
from nanobot.config_base import Base
@@ -41,7 +41,7 @@ def _is_subagent_status(value: Any) -> bool:
return isinstance(value, SubagentStatus)
class MyTool(Tool):
class MyTool(Tool, ContextAware):
"""Check and set the agent loop's runtime configuration."""
_plugin_discoverable = False # Requires AgentLoop reference; registered manually
@@ -57,7 +57,7 @@ class MyTool(Tool):
BLOCKED = frozenset({
# Core infrastructure
"bus", "provider", "runtime_resolver", "_running", "tools",
"bus", "provider", "_running", "tools",
# Config management
"_runtime_vars",
# Subsystems
@@ -68,7 +68,7 @@ class MyTool(Tool):
"_session_locks", "_active_tasks", "_background_tasks",
# Security boundaries (inspect + modify both blocked)
"restrict_to_workspace", "channels_config",
"_concurrency_gate", "_unified_session", "_extra_hooks", "_hook_factories",
"_concurrency_gate", "_unified_session", "_extra_hooks",
})
READ_ONLY = frozenset({
@@ -77,11 +77,8 @@ class MyTool(Tool):
"exec_config", # inspect allowed (e.g. check sandbox), modify blocked
"web_config", # inspect allowed (e.g. check enable), modify blocked
"workspace_sandbox", # read-only view of workspace enforcement level
"request", # current message routing metadata
})
_REQUEST_FIELDS = ("channel", "chat_id", "sender_id")
_DENIED_ATTRS = frozenset({
"__class__", "__dict__", "__bases__", "__subclasses__", "__mro__",
"__init__", "__new__", "__reduce__", "__getstate__", "__setstate__",
@@ -110,15 +107,12 @@ class MyTool(Tool):
}
_MAX_RUNTIME_KEYS = 64
_MODEL_RUNTIME_FIELDS = frozenset({
"model",
"model_preset",
"context_window_tokens",
})
def __init__(self, runtime_state: RuntimeState, modify_allowed: bool = True) -> None:
self._runtime_state = runtime_state
self._modify_allowed = modify_allowed
self._channel = ""
self._chat_id = ""
def __deepcopy__(self, memo: dict[int, Any]) -> MyTool:
cls = self.__class__
@@ -126,8 +120,14 @@ class MyTool(Tool):
memo[id(self)] = result
result._runtime_state = self._runtime_state
result._modify_allowed = self._modify_allowed
result._channel = self._channel
result._chat_id = self._chat_id
return result
def set_context(self, ctx: RequestContext) -> None:
self._channel = ctx.channel
self._chat_id = ctx.chat_id
@property
def name(self) -> str:
return "my"
@@ -144,8 +144,6 @@ class MyTool(Tool):
"Scratchpad keys persist across turns but not restarts.\n"
"Key values: _current_iteration (current progress), "
"max_iterations - _current_iteration = remaining iterations.\n"
"Current routing metadata is available read-only via request.channel, "
"request.chat_id, and request.sender_id.\n"
"Note: web_config and exec_config are readable but read-only.\n"
"\n"
"When to use:\n"
@@ -178,7 +176,6 @@ class MyTool(Tool):
"key": {
"type": "string",
"description": "Dot-path for check/set. Examples: 'max_iterations', 'workspace', 'provider_retry_mode'. "
"Use 'request.channel', 'request.chat_id', or 'request.sender_id' for current routing metadata. "
"Use 'model_preset' to switch named model presets. For check without key, shows all config values.",
},
"value": {"description": "New value (for set). Type must match target (int for max_iterations/context_window_tokens, str for model/model_preset)."},
@@ -187,12 +184,7 @@ class MyTool(Tool):
}
def _audit(self, action: str, detail: str) -> None:
ctx = current_request_context()
session = (
ctx.session_key or f"{ctx.channel}:{ctx.chat_id}"
if ctx is not None and ctx.channel
else "unknown"
)
session = f"{self._channel}:{self._chat_id}" if self._channel else "unknown"
logger.info("self.{} | {} | session:{}", action, detail, session)
# ------------------------------------------------------------------
@@ -224,7 +216,7 @@ class MyTool(Tool):
@staticmethod
def _validate_key(key: str | None, label: str = "key") -> str | None:
if not key or not key.strip():
return ToolResult.error(f"Error: '{label}' cannot be empty or whitespace")
return f"Error: '{label}' cannot be empty or whitespace"
return None
# ------------------------------------------------------------------
@@ -329,43 +321,19 @@ class MyTool(Tool):
if action in ("inspect", "check"):
return self._inspect(key)
if not self._modify_allowed:
return ToolResult.error("Error: set is disabled (tools.my.allow_set is false)")
return "Error: set is disabled (tools.my.allow_set is false)"
if action in ("modify", "set"):
return self._modify(key, value)
return f"Unknown action: {action}"
# -- inspect --
def _current_runtime_value(self, key: str) -> tuple[bool, Any]:
request_ctx = current_request_context()
runtime = request_ctx.runtime if request_ctx is not None else None
if runtime is None or key not in self._MODEL_RUNTIME_FIELDS:
return False, None
return True, getattr(runtime, key)
def _inspect(self, key: str | None) -> str:
if not key:
return self._inspect_all()
if key == "request" or key.startswith("request."):
request_ctx = current_request_context()
if request_ctx is None:
return ToolResult.error("Error: current request context is unavailable")
if key == "request":
return self._format_value(
{field: getattr(request_ctx, field) for field in self._REQUEST_FIELDS},
key,
)
field = key.removeprefix("request.")
if field not in self._REQUEST_FIELDS:
return ToolResult.error(f"Error: '{key}' not found")
return self._format_value(getattr(request_ctx, field), key)
if "." not in key:
found, value = self._current_runtime_value(key)
if found:
return self._format_value(value, key)
top = key.split(".")[0]
if top in self._DENIED_ATTRS or top.startswith("__"):
return ToolResult.error(f"Error: '{top}' is not accessible")
return f"Error: '{top}' is not accessible"
obj, err = self._resolve_path(key)
if err:
# "scratchpad" alias for _runtime_vars
@@ -375,12 +343,12 @@ class MyTool(Tool):
# Fallback: check _runtime_vars for simple keys stored by modify
if "." not in key and key in self._runtime_state._runtime_vars:
return self._format_value(self._runtime_state._runtime_vars[key], key)
return ToolResult.error(f"Error: {err}")
return f"Error: {err}"
# Guard against mock auto-generated attributes
if "." not in key and not _has_real_attr(self._runtime_state, key):
if key in self._runtime_state._runtime_vars:
return self._format_value(self._runtime_state._runtime_vars[key], key)
return ToolResult.error(f"Error: '{key}' not found")
return f"Error: '{key}' not found"
return self._format_value(obj, key)
def _inspect_all(self) -> str:
@@ -388,13 +356,8 @@ class MyTool(Tool):
parts: list[str] = []
# RESTRICTED keys
for k in self.RESTRICTED:
found, value = self._current_runtime_value(k)
parts.append(self._format_value(value if found else getattr(state, k, None), k))
found, value = self._current_runtime_value("model_preset")
parts.append(self._format_value(
value if found else state.model_preset,
"model_preset",
))
parts.append(self._format_value(getattr(state, k, None), k))
parts.append(self._format_value(state.model_preset, "model_preset"))
# Other useful top-level keys shown in description
for k in ("workspace", "provider_retry_mode", "max_tool_result_chars", "_current_iteration", "web_config", "exec_config", "workspace_sandbox", "subagents"):
if _has_real_attr(state, k):
@@ -416,21 +379,21 @@ class MyTool(Tool):
top = key.split(".")[0]
if top in self.BLOCKED or top in self._DENIED_ATTRS or top.startswith("__") or top.lower() in self._SENSITIVE_NAMES:
self._audit("modify", f"BLOCKED {key}")
return ToolResult.error(f"Error: '{key}' is protected and cannot be modified")
return f"Error: '{key}' is protected and cannot be modified"
if top in self.READ_ONLY:
self._audit("modify", f"READ_ONLY {key}")
return ToolResult.error(f"Error: '{key}' is read-only and cannot be modified")
return f"Error: '{key}' is read-only and cannot be modified"
if "." in key:
parent_path, leaf = key.rsplit(".", 1)
if leaf in self._DENIED_ATTRS or leaf.startswith("__"):
self._audit("modify", f"BLOCKED leaf '{leaf}'")
return ToolResult.error(f"Error: '{leaf}' is not accessible")
return f"Error: '{leaf}' is not accessible"
if leaf.lower() in self._SENSITIVE_NAMES:
self._audit("modify", f"BLOCKED sensitive leaf '{leaf}'")
return ToolResult.error(f"Error: '{leaf}' is not accessible")
return f"Error: '{leaf}' is not accessible"
parent, err = self._resolve_path(parent_path)
if err:
return ToolResult.error(f"Error: {err}")
return f"Error: {err}"
if isinstance(parent, dict):
parent[leaf] = value
else:
@@ -445,11 +408,11 @@ class MyTool(Tool):
def _modify_model_preset(self, value: Any) -> str:
if not isinstance(value, str) or not value.strip():
return ToolResult.error("Error: 'model_preset' must be a non-empty string")
return "Error: 'model_preset' must be a non-empty string"
name = value.strip()
result = self._modify_free("model_preset", name)
if isinstance(result, ToolResult) and result.is_error:
return result if result.endswith((".", "!", "?")) else ToolResult.error(f"{result}.")
if result.startswith("Error:"):
return result if result.endswith((".", "!", "?")) else f"{result}."
return (
f"{result}; model is now {self._runtime_state.model!r}; "
f"context_window_tokens is now {self._runtime_state.context_window_tokens!r}"
@@ -459,29 +422,23 @@ class MyTool(Tool):
spec = self.RESTRICTED[key]
expected = spec["type"]
if expected is int and isinstance(value, bool):
return ToolResult.error(f"Error: '{key}' must be {expected.__name__}, got bool")
return f"Error: '{key}' must be {expected.__name__}, got bool"
if not isinstance(value, expected):
try:
value = expected(value)
except (ValueError, TypeError):
return ToolResult.error(f"Error: '{key}' must be {expected.__name__}, got {type(value).__name__}")
return f"Error: '{key}' must be {expected.__name__}, got {type(value).__name__}"
old = getattr(self._runtime_state, key)
if "min" in spec and value < spec["min"]:
return ToolResult.error(f"Error: '{key}' must be >= {spec['min']}")
return f"Error: '{key}' must be >= {spec['min']}"
if "max" in spec and value > spec["max"]:
return ToolResult.error(f"Error: '{key}' must be <= {spec['max']}")
return f"Error: '{key}' must be <= {spec['max']}"
if "min_len" in spec and len(str(value)) < spec["min_len"]:
return ToolResult.error(f"Error: '{key}' must be at least {spec['min_len']} characters")
return f"Error: '{key}' must be at least {spec['min_len']} characters"
setattr(self._runtime_state, key, value)
if key == "model":
self._runtime_state.set_runtime_model(value)
elif key == "context_window_tokens":
self._runtime_state.set_runtime_context_window(value)
else:
setattr(self._runtime_state, key, value)
if key == "max_iterations" and hasattr(
self._runtime_state,
"_sync_subagent_runtime_limits",
):
self._runtime_state._active_preset = None
if key == "max_iterations" and hasattr(self._runtime_state, "_sync_subagent_runtime_limits"):
self._runtime_state._sync_subagent_runtime_limits()
self._audit("modify", f"{key}: {old!r} -> {value!r}")
return f"Set {key} = {value!r} (was {old!r})"
@@ -498,25 +455,25 @@ class MyTool(Tool):
"modify",
f"REJECTED type mismatch {key}: expects {old_t.__name__}, got {new_t.__name__}",
)
return ToolResult.error(f"Error: '{key}' expects {old_t.__name__}, got {new_t.__name__}")
return f"Error: '{key}' expects {old_t.__name__}, got {new_t.__name__}"
try:
setattr(self._runtime_state, key, value)
except (ValueError, KeyError) as e:
message = str(e.args[0] if isinstance(e, KeyError) and e.args else e).strip('"')
self._audit("modify", f"REJECTED {key}: {message}")
return ToolResult.error(f"Error: {message}")
return f"Error: {message}"
self._audit("modify", f"{key}: {old!r} -> {value!r}")
return f"Set {key} = {value!r} (was {old!r})"
if callable(value):
self._audit("modify", f"REJECTED callable {key}")
return ToolResult.error("Error: cannot store callable values")
return "Error: cannot store callable values"
err = self._validate_json_safe(value)
if err:
self._audit("modify", f"REJECTED {key}: {err}")
return ToolResult.error(f"Error: {err}")
return f"Error: {err}"
if key not in self._runtime_state._runtime_vars and len(self._runtime_state._runtime_vars) >= self._MAX_RUNTIME_KEYS:
self._audit("modify", f"REJECTED {key}: max keys ({self._MAX_RUNTIME_KEYS}) reached")
return ToolResult.error(f"Error: scratchpad is full (max {self._MAX_RUNTIME_KEYS} keys). Remove unused keys first.")
return f"Error: scratchpad is full (max {self._MAX_RUNTIME_KEYS} keys). Remove unused keys first."
old = self._runtime_state._runtime_vars.get(key)
self._runtime_state._runtime_vars[key] = value
self._audit("modify", f"scratchpad.{key}: {old!r} -> {value!r}")
+186 -170
View File
@@ -6,16 +6,19 @@ import asyncio
import os
import re
import shutil
import subprocess
import sys
import time
import uuid
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path, PureWindowsPath
from pathlib import Path
from typing import Any
from loguru import logger
from pydantic import Field
from pydantic import AliasChoices, Field
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.context import current_request_session_key
from nanobot.agent.tools.exec_session import (
DEFAULT_EXEC_SESSION_MANAGER,
@@ -33,36 +36,19 @@ from nanobot.agent.tools.schema import (
StringSchema,
tool_parameters_schema,
)
from nanobot.agent.verification_state import (
analyze_verification_result,
append_verification_feedback,
record_verification_observation,
)
from nanobot.config.paths import get_media_dir
from nanobot.config_base import Base
from nanobot.security.workspace_access import current_scope_allows_loopback, current_tool_workspace
from nanobot.security.workspace_policy import is_path_within
from nanobot.utils.helpers import build_structured_output_summary
_IS_WINDOWS = sys.platform == "win32"
def _reap_pid(pid: int) -> None:
"""Best-effort ``waitpid`` to reap a child and prevent zombies.
Call this after killing or after normal completion of any subprocess
as a safety net asyncio's child-watcher *should* have reaped it,
but in containers / edge-cases it sometimes doesn't.
Uses ``os`` capability checks rather than ``_IS_WINDOWS`` so this is
safe when tests patch the platform flag while still running on Windows
(``os.waitpid`` / ``os.WNOHANG`` do not exist there).
"""
waitpid = getattr(os, "waitpid", None)
wnohang = getattr(os, "WNOHANG", None)
if waitpid is None or wnohang is None:
return
try:
waitpid(pid, wnohang)
except (ProcessLookupError, ChildProcessError):
# Already reaped, or not our child — both are fine.
pass
except OSError as exc:
logger.debug("_reap_pid({}): {}", pid, exc)
_DETACHED_EXIT_GRACE_S = 1.0 if _IS_WINDOWS else 0.2
# Policy note appended to recoverable workspace-boundary guard errors.
@@ -79,6 +65,13 @@ class ExecToolConfig(Base):
"""Shell exec tool configuration."""
enable: bool = True
timeout: int = Field(default=60, ge=0) # Hard timeout (s); 0 = no limit. Not capped by the per-call max.
allow_local_service_access: bool = Field(
default=False,
validation_alias=AliasChoices(
"allowLocalServiceAccess",
"allow_local_service_access",
),
) # allow shell commands to reach literal localhost/loopback services
path_prepend: str = ""
path_append: str = ""
sandbox: str = ""
@@ -113,15 +106,7 @@ class _PreparedCommand:
maximum=600,
),
shell=StringSchema(
(
"Override the Windows shell only when needed. Omit to use "
"PowerShell by default (pwsh when available, else powershell). "
"Pass 'cmd' only for cmd.exe syntax or cmd built-ins."
if _IS_WINDOWS
else "Override the Unix shell only when needed. Omit to use "
"bash by default. Pass 'sh' for POSIX sh or 'zsh' for "
"zsh-specific syntax."
),
"Optional shell binary to launch. On Unix, supports sh, bash, or zsh.",
nullable=True,
),
login=BooleanSchema(
@@ -158,6 +143,16 @@ class _PreparedCommand:
maximum=MAX_OUTPUT_CHARS,
nullable=True,
),
detach=BooleanSchema(
description=(
"Run the command as a detached background process that can "
"survive after the agent finishes. Use for local servers, "
"dev servers, mock APIs, or other services that must remain "
"available for later commands or external verification."
),
default=False,
nullable=True,
),
)
)
class ExecTool(Tool):
@@ -181,6 +176,7 @@ class ExecTool(Tool):
working_dir=ctx.workspace,
timeout=cfg.timeout,
restrict_to_workspace=ctx.config.restrict_to_workspace,
allow_local_service_access=cfg.allow_local_service_access,
webui_allow_local_service_access=ctx.config.webui_allow_local_service_access,
sandbox=cfg.sandbox,
path_prepend=cfg.path_prepend,
@@ -188,7 +184,6 @@ class ExecTool(Tool):
allowed_env_keys=cfg.allowed_env_keys,
allow_patterns=cfg.allow_patterns,
deny_patterns=cfg.deny_patterns,
session_manager=getattr(ctx, "exec_session_manager", None),
)
def __init__(
@@ -198,6 +193,7 @@ class ExecTool(Tool):
deny_patterns: list[str] | None = None,
allow_patterns: list[str] | None = None,
restrict_to_workspace: bool = False,
allow_local_service_access: bool = False,
webui_allow_local_service_access: bool = True,
allow_local_preview_access: bool | None = None,
sandbox: str = "",
@@ -230,6 +226,7 @@ class ExecTool(Tool):
]
self.allow_patterns = allow_patterns or []
self.restrict_to_workspace = restrict_to_workspace
self.allow_local_service_access = allow_local_service_access
if allow_local_preview_access is not None:
webui_allow_local_service_access = allow_local_preview_access
self.webui_allow_local_service_access = webui_allow_local_service_access
@@ -260,13 +257,6 @@ class ExecTool(Tool):
@property
def description(self) -> str:
platform_note = (
"On Windows, use PowerShell syntax by default; pass shell='cmd' "
"only for cmd-specific commands. "
if _IS_WINDOWS
else "On Unix, commands run through bash by default; pass shell='sh' "
"or shell='zsh' when needed. "
)
return (
"Execute a shell command and return its output. "
"Use this for tests, builds, package commands, git commands, and "
@@ -274,11 +264,13 @@ class ExecTool(Tool):
"inspection and apply_patch/write_file/edit_file for file changes "
"instead of cat, shell find/grep, echo, or sed. "
"Use -y or --yes flags to avoid interactive prompts. "
f"{platform_note}"
"For long-running or interactive commands, pass yield_time_ms; "
"if the command keeps running, exec returns a session_id that can "
"be polled or written to with write_stdin. Output is truncated at "
"10 000 chars; timeout defaults to 60s."
"be polled or written to with write_stdin. For services that "
"must remain available after you finish, pass detach=true instead "
"of yield_time_ms; detached output is written to a log file and "
"the tool returns a pid. Output is truncated at 10 000 chars; "
"timeout defaults to 60s."
)
@property
@@ -292,12 +284,13 @@ class ExecTool(Tool):
login: bool | None = None, yield_time_ms: int | None = None,
max_output_chars: int | None = None,
max_output_tokens: int | None = None,
detach: bool | None = False,
**kwargs: Any,
) -> str:
command = command or cmd
working_dir = working_dir or workdir
if not command:
return ToolResult.error("Error: Missing command. Provide command or cmd.")
return "Error: Missing command. Provide command or cmd."
if max_output_chars is None:
max_output_chars = max_output_tokens
@@ -305,11 +298,14 @@ class ExecTool(Tool):
if isinstance(prepared, str):
return prepared
if detach:
return await self._execute_detached(prepared)
if yield_time_ms is not None:
return await self._execute_session(prepared, yield_time_ms, max_output_chars)
process: asyncio.subprocess.Process | None = None
try:
started_at = time.monotonic()
process = await self._spawn(
prepared.command,
prepared.cwd,
@@ -325,16 +321,19 @@ class ExecTool(Tool):
)
except asyncio.TimeoutError:
await self._kill_process(process)
return ToolResult.error(f"Error: Command timed out after {prepared.timeout} seconds")
result = f"Error: Command timed out after {prepared.timeout} seconds"
analysis = analyze_verification_result(
command=prepared.command,
output=result,
exit_code=None,
timed_out=True,
)
record_verification_observation(current_request_session_key(), analysis)
return append_verification_feedback(result, analysis)
except asyncio.CancelledError:
await self._kill_process(process)
raise
# Safety-net reap: asyncio *should* have reaped the child via
# communicate(), but in containers the child-watcher sometimes
# misses it, leaving a zombie.
_reap_pid(process.pid)
output_parts = []
if stdout:
@@ -348,24 +347,38 @@ class ExecTool(Tool):
output_parts.append(f"\nExit code: {process.returncode}")
result = "\n".join(output_parts) if output_parts else "(no output)"
elapsed_s = max(0.0, time.monotonic() - started_at)
analysis = analyze_verification_result(
command=prepared.command,
output=result,
exit_code=process.returncode,
)
max_len = clamp_session_int(max_output_chars, self._MAX_OUTPUT, 1000, MAX_OUTPUT_CHARS)
if len(result) > max_len:
half = max_len // 2
result = (
result[:half]
+ f"\n\n... ({len(result) - max_len:,} chars truncated) ...\n\n"
+ result[-half:]
result = build_structured_output_summary(
"[tool output truncated]",
result,
max_chars=max_len,
metadata=[
("original_size_chars", len(result)),
("exit_code", process.returncode),
("duration_s", f"{elapsed_s:.1f}"),
],
analysis=analysis,
guidance=(
"Use the structured summary first. Rerun a narrower "
"command, grep a specific failure, or inspect the "
"named artifact instead of rerunning broad noisy logs."
),
)
return result
record_verification_observation(current_request_session_key(), analysis)
return append_verification_feedback(result, analysis)
except Exception as e:
# Kill and reap the child if it was spawned but an unexpected
# error prevented communicate() from completing.
if process is not None:
await self._kill_process(process)
return ToolResult.error(f"Error executing command: {str(e)}")
return f"Error executing command: {str(e)}"
async def _execute_session(
self,
@@ -391,9 +404,69 @@ class ExecTool(Tool):
),
)
result = format_session_poll(session_id, poll)
return ToolResult.error(result) if poll.timed_out else result
if poll.done:
analysis = analyze_verification_result(
command=prepared.command,
output=result,
exit_code=poll.exit_code,
timed_out=poll.timed_out,
)
record_verification_observation(current_request_session_key(), analysis)
return append_verification_feedback(result, analysis)
return result
except Exception as exc:
return ToolResult.error(f"Error executing command: {exc}")
return f"Error executing command: {exc}"
async def _execute_detached(self, prepared: _PreparedCommand) -> str:
log_dir = Path(prepared.cwd) / ".nanobot" / "exec-logs"
try:
log_dir.mkdir(parents=True, exist_ok=True)
log_path = log_dir / f"detached-{uuid.uuid4().hex[:12]}.log"
except Exception as exc:
return f"Error preparing detached command log directory: {exc}"
log_handle = None
try:
log_handle = open(log_path, "ab", buffering=0)
process = await self._spawn(
prepared.command,
prepared.cwd,
prepared.env,
prepared.shell_program,
prepared.login,
stdout=log_handle,
stderr=log_handle,
start_new_session=not _IS_WINDOWS,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if _IS_WINDOWS else 0,
)
except Exception as exc:
return f"Error starting detached command: {exc}"
finally:
if log_handle is not None:
with suppress(Exception):
log_handle.close()
try:
exit_code = await asyncio.wait_for(process.wait(), timeout=_DETACHED_EXIT_GRACE_S)
except asyncio.TimeoutError:
return (
"Detached process started.\n"
f"pid: {process.pid}\n"
f"cwd: {prepared.cwd}\n"
f"log: {log_path}\n"
"Poll the log or run a health check to verify the service is ready."
)
log_text = ""
with suppress(Exception):
log_text = log_path.read_text(encoding="utf-8", errors="replace")
if len(log_text) > 4000:
log_text = log_text[-4000:]
return (
f"Detached process exited immediately with code {exit_code}.\n"
f"log: {log_path}\n"
f"{log_text}"
)
def _resolve_timeout(self, timeout: int | None) -> int | None:
"""Resolve the effective hard timeout in seconds (None = no limit).
@@ -435,12 +508,12 @@ class ExecTool(Tool):
requested = Path(cwd).expanduser().resolve()
resolved_root = Path(workspace_root).expanduser().resolve()
except Exception:
return ToolResult.error(
return (
"Error: working_dir could not be resolved"
+ _WORKSPACE_BOUNDARY_NOTE
)
if not is_path_within(requested, resolved_root):
return ToolResult.error(
return (
"Error: working_dir is outside the configured workspace"
+ _WORKSPACE_BOUNDARY_NOTE
)
@@ -516,39 +589,31 @@ class ExecTool(Tool):
login: bool = False,
*,
stdin: int = asyncio.subprocess.DEVNULL,
stdout: Any = asyncio.subprocess.PIPE,
stderr: Any = asyncio.subprocess.PIPE,
start_new_session: bool = False,
creationflags: int = 0,
) -> asyncio.subprocess.Process:
"""Launch *command* in a platform-appropriate shell."""
if _IS_WINDOWS:
# Default to PowerShell so single-line and multi-line commands
# share the same shell semantics. cmd.exe is reachable via the
# explicit shell="cmd" parameter (see _resolve_shell).
default_program = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
program = shell_program or default_program
program_name = PureWindowsPath(program).name.lower()
if program_name in ("cmd", "cmd.exe"):
cmd_env = {**env, "COMSPEC": program}
return await asyncio.create_subprocess_shell(
command,
if "\n" in command:
return await asyncio.create_subprocess_exec(
"powershell", "-NoProfile", "-Command", command,
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdout=stdout,
stderr=stderr,
cwd=cwd,
env=cmd_env,
env=env,
creationflags=creationflags,
)
command = ExecTool._normalize_powershell_command(command)
command = (
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n"
"$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'\n"
f"{command}\n"
"if ($LASTEXITCODE -ne $null) { exit $LASTEXITCODE }"
)
return await asyncio.create_subprocess_exec(
program, "-NoProfile", "-NonInteractive", "-Command", command,
return await asyncio.create_subprocess_shell(
command,
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdout=stdout,
stderr=stderr,
cwd=cwd,
env=env,
creationflags=creationflags,
)
shell_program = shell_program or shutil.which("bash") or "/bin/bash"
args = [shell_program]
@@ -559,101 +624,51 @@ class ExecTool(Tool):
return await asyncio.create_subprocess_exec(
*args,
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
stdout=stdout,
stderr=stderr,
cwd=cwd,
env=env,
start_new_session=start_new_session,
)
@staticmethod
def _normalize_powershell_command(command: str) -> str:
stripped = command.lstrip()
if not stripped or stripped[0] not in {"'", '"'}:
return command
quote = stripped[0]
end = stripped.find(quote, 1)
if end == -1 or end + 1 >= len(stripped) or not stripped[end + 1].isspace():
return command
executable = stripped[1:end]
looks_like_windows_executable = (
bool(re.match(r"^[A-Za-z]:[\\/]", executable))
or executable.startswith(r"\\")
or executable.lower().endswith((".exe", ".cmd", ".bat", ".ps1"))
)
if not looks_like_windows_executable:
return command
leading = command[: len(command) - len(stripped)]
return f"{leading}& {stripped}"
@staticmethod
def _resolve_shell(shell: str | None) -> tuple[str | None, str | None]:
if not shell:
return None, None
if "\0" in shell or "\n" in shell or "\r" in shell:
return None, ToolResult.error("Error: shell contains invalid characters")
if _IS_WINDOWS:
win_allowed = {"powershell", "powershell.exe", "pwsh", "pwsh.exe", "cmd", "cmd.exe"}
path = Path(shell).expanduser()
if path.is_absolute():
name = path.name.lower()
if name not in win_allowed:
return None, ToolResult.error(
f"Error: unsupported shell {shell!r}. "
"Allowed: powershell, pwsh, cmd"
)
if not path.is_file():
return None, ToolResult.error(f"Error: shell is not found: {shell}")
return str(path), None
if "/" in shell or "\\" in shell:
return None, ToolResult.error("Error: shell must be a shell name or absolute path")
if shell.lower() not in win_allowed:
return None, ToolResult.error(
f"Error: unsupported shell {shell!r}. "
"Allowed: powershell, pwsh, cmd"
)
if shell.lower() in ("cmd", "cmd.exe"):
resolved = os.environ.get("COMSPEC") or shutil.which("cmd") or "cmd"
return resolved, None
resolved = shutil.which(shell) or shell
return resolved, None
return None, "Error: shell parameter is not supported on Windows"
if "\0" in shell or "\n" in shell or "\r" in shell:
return None, "Error: shell contains invalid characters"
allowed = {"sh", "bash", "zsh"}
path = Path(shell).expanduser()
if path.is_absolute():
if path.name not in allowed:
return None, ToolResult.error(f"Error: unsupported shell {shell!r}. Allowed: bash, sh, zsh")
return None, f"Error: unsupported shell {shell!r}. Allowed: bash, sh, zsh"
if not path.is_file() or not os.access(path, os.X_OK):
return None, ToolResult.error(f"Error: shell is not executable: {shell}")
return None, f"Error: shell is not executable: {shell}"
return str(path), None
if "/" in shell or "\\" in shell:
return None, ToolResult.error("Error: shell must be a shell name or absolute path")
return None, "Error: shell must be a shell name or absolute path"
if shell not in allowed:
return None, ToolResult.error(f"Error: unsupported shell {shell!r}. Allowed: bash, sh, zsh")
return None, f"Error: unsupported shell {shell!r}. Allowed: bash, sh, zsh"
resolved = shutil.which(shell)
if not resolved:
return None, ToolResult.error(f"Error: shell not found: {shell}")
return None, f"Error: shell not found: {shell}"
return resolved, None
@staticmethod
async def _kill_process(process: asyncio.subprocess.Process) -> None:
"""Kill a subprocess and reap it to prevent zombies.
Safe to call when the process has already exited (e.g. generic
exception handlers after a successful ``communicate()``): skips
``kill()`` and only runs the safety-net reap.
"""
if process.returncode is not None:
_reap_pid(process.pid)
return
"""Kill a subprocess and reap it to prevent zombies."""
process.kill()
try:
with suppress(ProcessLookupError):
process.kill()
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(process.wait(), timeout=5.0)
finally:
_reap_pid(process.pid)
if not _IS_WINDOWS:
try:
os.waitpid(process.pid, os.WNOHANG)
except (ProcessLookupError, ChildProcessError) as e:
logger.debug("Process already reaped or not found: {}", e)
def _build_env(self) -> dict[str, str]:
"""Build a minimal environment for subprocess execution.
@@ -725,25 +740,26 @@ class ExecTool(Tool):
if not explicitly_allowed:
for pattern in self.deny_patterns:
if re.search(pattern, lower):
return ToolResult.error("Error: Command blocked by deny pattern filter")
return "Error: Command blocked by deny pattern filter"
if self.allow_patterns:
return ToolResult.error("Error: Command blocked by allowlist filter (not in allowlist)")
return "Error: Command blocked by allowlist filter (not in allowlist)"
from nanobot.security.network import contains_internal_url
allow_loopback = self.allow_local_service_access or current_scope_allows_loopback(
enabled=self.webui_allow_local_service_access,
)
if contains_internal_url(
cmd,
allow_loopback=current_scope_allows_loopback(
enabled=self.webui_allow_local_service_access,
),
allow_loopback=allow_loopback,
):
# The runner turns this marker into a non-retryable security hint.
return ToolResult.error("Error: Command blocked by safety guard (internal/private URL detected)")
return "Error: Command blocked by safety guard (internal/private URL detected)"
should_restrict = self.restrict_to_workspace if restrict_to_workspace is None else restrict_to_workspace
if should_restrict:
if "..\\" in cmd or "../" in cmd:
return ToolResult.error(
return (
"Error: Command blocked by safety guard (path traversal detected)"
+ _WORKSPACE_BOUNDARY_NOTE
)
@@ -778,7 +794,7 @@ class ExecTool(Tool):
if not allowed and resolved_workspace is not None:
allowed = is_path_within(p, resolved_workspace)
if p.is_absolute() and not allowed:
return ToolResult.error(
return (
"Error: Command blocked by safety guard (path outside working dir)"
+ _WORKSPACE_BOUNDARY_NOTE
)
+22 -14
View File
@@ -2,10 +2,11 @@
from __future__ import annotations
from contextvars import ContextVar
from typing import TYPE_CHECKING, Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.base import Tool, tool_parameters
from nanobot.agent.tools.context import ContextAware, RequestContext
from nanobot.agent.tools.schema import NumberSchema, StringSchema, tool_parameters_schema
from nanobot.security.workspace_access import current_workspace_scope
@@ -29,16 +30,30 @@ if TYPE_CHECKING:
required=["task"],
)
)
class SpawnTool(Tool):
class SpawnTool(Tool, ContextAware):
"""Tool to spawn a subagent for background task execution."""
def __init__(self, manager: "SubagentManager"):
self._manager = manager
self._origin_channel: ContextVar[str] = ContextVar("spawn_origin_channel", default="cli")
self._origin_chat_id: ContextVar[str] = ContextVar("spawn_origin_chat_id", default="direct")
self._session_key: ContextVar[str] = ContextVar("spawn_session_key", default="cli:direct")
self._origin_message_id: ContextVar[str | None] = ContextVar(
"spawn_origin_message_id",
default=None,
)
@classmethod
def create(cls, ctx: Any) -> Tool:
return cls(manager=ctx.subagent_manager)
def set_context(self, ctx: RequestContext) -> None:
"""Set the origin context for subagent announcements."""
self._origin_channel.set(ctx.channel)
self._origin_chat_id.set(ctx.chat_id)
self._session_key.set(ctx.session_key or f"{ctx.channel}:{ctx.chat_id}")
self._origin_message_id.set(ctx.message_id)
@property
def name(self) -> str:
return "spawn"
@@ -69,20 +84,13 @@ class SpawnTool(Tool):
f"({running}/{limit} running). Wait for a running subagent "
f"to complete before spawning a new one."
)
request_ctx = current_request_context()
if request_ctx is None or request_ctx.runtime is None:
return ToolResult.error("Error: spawn requires an active model runtime")
origin_channel = request_ctx.channel
origin_chat_id = request_ctx.chat_id
session_key = request_ctx.session_key or f"{origin_channel}:{origin_chat_id}"
return await self._manager.spawn(
task=task,
runtime=request_ctx.runtime,
label=label,
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
session_key=session_key,
origin_message_id=request_ctx.message_id,
origin_channel=self._origin_channel.get(),
origin_chat_id=self._origin_chat_id.get(),
session_key=self._session_key.get(),
origin_message_id=self._origin_message_id.get(),
temperature=temperature,
workspace_scope=current_workspace_scope(),
)

Some files were not shown because too many files have changed in this diff Show More