mirror of
https://github.com/HKUDS/nanobot.git
synced 2026-08-08 21:38:40 +03:00
Compare commits
307
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e065cfffe | ||
|
|
27f7549c84 | ||
|
|
f5371a6c5a | ||
|
|
f19efcd990 | ||
|
|
6e462e62a6 | ||
|
|
ed47cf1562 | ||
|
|
6b5820ea89 | ||
|
|
1e7518a207 | ||
|
|
4a3818e03c | ||
|
|
276cbd947f | ||
|
|
234e895e5a | ||
|
|
8c9110fee3 | ||
|
|
e864fba522 | ||
|
|
a65a6f334c | ||
|
|
3824206ab2 | ||
|
|
2c78976728 | ||
|
|
fe0717b385 | ||
|
|
791c7fd505 | ||
|
|
6d406d93c9 | ||
|
|
053722a2a2 | ||
|
|
45d1caba1d | ||
|
|
89acea6fe1 | ||
|
|
01e4f3762a | ||
|
|
c339ce8bba | ||
|
|
12b88d3872 | ||
|
|
8ccb2a451b | ||
|
|
20748bc4e3 | ||
|
|
93de413432 | ||
|
|
d349b65713 | ||
|
|
54b250430d | ||
|
|
5794d481c3 | ||
|
|
e206ee4e70 | ||
|
|
2eb7398f34 | ||
|
|
f75d3519db | ||
|
|
7f8c3453e1 | ||
|
|
edf78e7054 | ||
|
|
bd0dd85f44 | ||
|
|
469d004773 | ||
|
|
f3d1b9ca2d | ||
|
|
c111aaa7ee | ||
|
|
9adcd3d923 | ||
|
|
0a1c98c142 | ||
|
|
7675364eae | ||
|
|
052fdc132d | ||
|
|
47d498bab0 | ||
|
|
04328f8129 | ||
|
|
137fbf875e | ||
|
|
1ee4349a08 | ||
|
|
9a1d1e64c7 | ||
|
|
a1fbfd9f7b | ||
|
|
bda0c099ab | ||
|
|
ef14d1ea92 | ||
|
|
c9e014fdea | ||
|
|
d32f8961b1 | ||
|
|
45a6466c2c | ||
|
|
99e04c2da2 | ||
|
|
87602a74ea | ||
|
|
ad55f3ce37 | ||
|
|
e284592649 | ||
|
|
2154dc51d0 | ||
|
|
fe7d94359b | ||
|
|
10930f3902 | ||
|
|
6b7470646f | ||
|
|
21f58cbabf | ||
|
|
c9d3e74342 | ||
|
|
5bd3d1e0af | ||
|
|
af85c356b8 | ||
|
|
198fd9f869 | ||
|
|
45ace23580 | ||
|
|
b4f069800e | ||
|
|
3f8170e835 | ||
|
|
cb03d2c748 | ||
|
|
bd94fefd1a | ||
|
|
42d7ad34a4 | ||
|
|
bb3b449e09 | ||
|
|
55317094b6 | ||
|
|
6313ae9f4f | ||
|
|
4137be62a1 | ||
|
|
0b9ca744c2 | ||
|
|
7685a89dcc | ||
|
|
bbd4f4054b | ||
|
|
0ae28571e7 | ||
|
|
6851a6ebd4 | ||
|
|
7768672c5b | ||
|
|
207813d3b5 | ||
|
|
e0c2d28f90 | ||
|
|
8559458258 | ||
|
|
04dbf17426 | ||
|
|
a52a88455b | ||
|
|
3ab09075c5 | ||
|
|
4ddd639e67 | ||
|
|
444f488563 | ||
|
|
88143a8bf0 | ||
|
|
7204d88a4c | ||
|
|
1a21542d11 | ||
|
|
f531f1ce38 | ||
|
|
941a2541eb | ||
|
|
be8ac1e484 | ||
|
|
f074aa7d80 | ||
|
|
ea7f4679f1 | ||
|
|
c188e96f4e | ||
|
|
815f15993c | ||
|
|
4333d6f103 | ||
|
|
65d32ffd6c | ||
|
|
379785d365 | ||
|
|
883776358e | ||
|
|
28141ce20b | ||
|
|
460c62c0b0 | ||
|
|
e86133c434 | ||
|
|
6c59332a8a | ||
|
|
a7b8a9ed46 | ||
|
|
7e135b45f3 | ||
|
|
fa73448f6f | ||
|
|
8a231b6e4d | ||
|
|
ef5318ebdc | ||
|
|
8f68040f05 | ||
|
|
0f88927364 | ||
|
|
3f33ff3143 | ||
|
|
29e99d3742 | ||
|
|
01a0f5aaf3 | ||
|
|
77a6003255 | ||
|
|
25a477050d | ||
|
|
ea0516e655 | ||
|
|
18a230de75 | ||
|
|
c5e053f83b | ||
|
|
b68ae4f9bc | ||
|
|
97e3b360c2 | ||
|
|
4353f4680b | ||
|
|
73bf299a59 | ||
|
|
d04ad1a5b4 | ||
|
|
67b56cba74 | ||
|
|
105230cc34 | ||
|
|
dd014b50a7 | ||
|
|
595d789c6f | ||
|
|
cf35238834 | ||
|
|
ef9780719d | ||
|
|
cc70a2a79f | ||
|
|
f9806cc60f | ||
|
|
76877036f7 | ||
|
|
a710a7d6f7 | ||
|
|
fff38f11a7 | ||
|
|
5e51c5014f | ||
|
|
937f04ac86 | ||
|
|
9eade9be5f | ||
|
|
400369f0b0 | ||
|
|
f0c989ba2d | ||
|
|
70505bd1fc | ||
|
|
162b6ee5bd | ||
|
|
b1d29ede7d | ||
|
|
800d51ecac | ||
|
|
3f9fb63d4c | ||
|
|
1cfa48ad4a | ||
|
|
8a42a9c73a | ||
|
|
72c8a47ac9 | ||
|
|
122cf4213b | ||
|
|
8c4a74ee3c | ||
|
|
4ec111c1a9 | ||
|
|
8222f3c85f | ||
|
|
d76493a63a | ||
|
|
220de320fb | ||
|
|
33b1c6f601 | ||
|
|
10b52cfb3a | ||
|
|
5d034dc79c | ||
|
|
b8d7708171 | ||
|
|
e725649146 | ||
|
|
6a95877196 | ||
|
|
83e4bae7db | ||
|
|
58b5bb9204 | ||
|
|
c579551bb1 | ||
|
|
8b645135bc | ||
|
|
28011413bc | ||
|
|
614ea86a81 | ||
|
|
6d28db3248 | ||
|
|
0d1221bece | ||
|
|
8b9f93d7d1 | ||
|
|
a119c35b1e | ||
|
|
067e0c4a40 | ||
|
|
5283ceae85 | ||
|
|
00cc0da530 | ||
|
|
b19a744110 | ||
|
|
c9c69e4316 | ||
|
|
8a79eb1aaa | ||
|
|
979f038ded | ||
|
|
f38fd7d5d3 | ||
|
|
5af22042ec | ||
|
|
aecb5fbc33 | ||
|
|
34535b4e7c | ||
|
|
5abe06f808 | ||
|
|
64c7ff5fdc | ||
|
|
54bcdb5a62 | ||
|
|
ffdf05a603 | ||
|
|
fd9e57703c | ||
|
|
661ab00656 | ||
|
|
b941233138 | ||
|
|
acb0e853ff | ||
|
|
afef27dd6c | ||
|
|
f32007c83f | ||
|
|
09bde468eb | ||
|
|
2ebf5c4972 | ||
|
|
1ed2c9a213 | ||
|
|
55b550ee01 | ||
|
|
b690a48336 | ||
|
|
7178ea3f13 | ||
|
|
2a0cd19a74 | ||
|
|
c78421cf16 | ||
|
|
03be51ade5 | ||
|
|
c757c5466c | ||
|
|
5f4cfbcb16 | ||
|
|
f6d1dba32a | ||
|
|
2ec4044217 | ||
|
|
a6d5e4f3b5 | ||
|
|
ed48325346 | ||
|
|
56443ac6e2 | ||
|
|
21aa900d64 | ||
|
|
b0258e8b20 | ||
|
|
8493560976 | ||
|
|
8d2c31eb6a | ||
|
|
a6a489e0fa | ||
|
|
840ba5af33 | ||
|
|
3403b87641 | ||
|
|
bfbae5a7b3 | ||
|
|
58cce14a07 | ||
|
|
f9b02496c8 | ||
|
|
bfc2a74e4f | ||
|
|
780093d037 | ||
|
|
1873e948c3 | ||
|
|
735a243849 | ||
|
|
edada598c8 | ||
|
|
2527ce5de9 | ||
|
|
44a5ed1bc0 | ||
|
|
4c0e9b9f46 | ||
|
|
839d1ecfb1 | ||
|
|
593b328dbb | ||
|
|
4beca25ceb | ||
|
|
82ffce1474 | ||
|
|
4726ca0478 | ||
|
|
d979597361 | ||
|
|
070aed8ade | ||
|
|
8df100203c | ||
|
|
8fa9eed6a8 | ||
|
|
5692f7a68a | ||
|
|
57f0c859fc | ||
|
|
40282e3b74 | ||
|
|
dacc699293 | ||
|
|
c8638dee46 | ||
|
|
7dc45ff94e | ||
|
|
8248d075db | ||
|
|
d7152cdbdd | ||
|
|
89dc34df88 | ||
|
|
67ce6822ca | ||
|
|
194e9d5f5f | ||
|
|
5005bca353 | ||
|
|
e5dbb15c34 | ||
|
|
c90e433057 | ||
|
|
3ce77633c0 | ||
|
|
00a907c493 | ||
|
|
cf2f589615 | ||
|
|
463f536750 | ||
|
|
00a7de0171 | ||
|
|
efb792ff24 | ||
|
|
d8601478db | ||
|
|
66fc54421c | ||
|
|
6a27c26257 | ||
|
|
3ca82ea880 | ||
|
|
47dcc61e9b | ||
|
|
2bf111f456 | ||
|
|
aa6c1bf300 | ||
|
|
5281e67222 | ||
|
|
dbb53109f4 | ||
|
|
b015515f30 | ||
|
|
be88e14424 | ||
|
|
9e490ef473 | ||
|
|
bfb4246659 | ||
|
|
fbf96a3502 | ||
|
|
2a9e288dfe | ||
|
|
3460ca3cb9 | ||
|
|
9b45fc1172 | ||
|
|
8656549129 | ||
|
|
4c1f127549 | ||
|
|
13c951aa41 | ||
|
|
cd1fb61eb5 | ||
|
|
e79cb816e3 | ||
|
|
64901be67f | ||
|
|
9ce9d2235a | ||
|
|
06d5495b60 | ||
|
|
851a0ff50c | ||
|
|
3596ccf828 | ||
|
|
d1ae73a8a8 | ||
|
|
c661012754 | ||
|
|
0e19ea3062 | ||
|
|
ceae6d7b61 | ||
|
|
34f776b48b | ||
|
|
f7b027a295 | ||
|
|
6c880a6691 | ||
|
|
4636c78100 | ||
|
|
28c8c89a42 | ||
|
|
7899857201 | ||
|
|
9354b80a6e | ||
|
|
638af123ba | ||
|
|
42aa37cfc0 | ||
|
|
03302c751f | ||
|
|
246ea8ef61 | ||
|
|
f60b3c7920 | ||
|
|
e92899607a | ||
|
|
c930aa3713 | ||
|
|
4378944459 | ||
|
|
123384975e |
@@ -27,3 +27,9 @@ A bugfix should make the protected invariant clear, change the smallest surface
|
||||
## Explicit over magical
|
||||
|
||||
Configuration must be declared explicitly in `config/schema.py` Pydantic models. Error handling should raise clear exceptions rather than silently correcting bad input. Provider auto-detection exists, but every resolution path must be traceable from the factory to the concrete provider class.
|
||||
|
||||
## Configuration has an explicit owner
|
||||
|
||||
`FileConfigRepository` owns config-file reads, validation, revisions, and atomic writes. Process entry points may use the explicit functions in `config/loader.py`; components with an explicit config path should keep their own repository instance instead of importing a mutable global config object.
|
||||
|
||||
Persisted and runtime views are separate: `load_raw_config()` / `load_raw()` preserve `${VAR}` references for editing, while `load_effective_config()` / `load_effective()` return an isolated snapshot with references resolved. Read-modify-write flows must use `update()` / `update_config()` so a stale object cannot silently overwrite a newer change. Loading config is side-effect free; process-wide policies are applied explicitly during runtime startup.
|
||||
|
||||
+2
-2
@@ -6,7 +6,7 @@
|
||||
|
||||
## Config `${VAR}` References
|
||||
|
||||
`config/loader.py` resolves `${VAR}` patterns in `config.json` at load time. This is **not** a shell-like default-value syntax. If the environment variable is missing, `load_config` raises `ValueError` and the agent falls back to default configuration.
|
||||
`load_raw_config()` and `FileConfigRepository.load_raw()` preserve `${VAR}` patterns so Settings can safely edit and save the persisted representation. Runtime entry points use `load_effective_config()` / `load_effective()` to resolve them in an isolated snapshot. This is **not** a shell-like default-value syntax. If a referenced variable is missing, effective loading raises `ValueError`.
|
||||
|
||||
Example valid usage:
|
||||
```json
|
||||
@@ -16,7 +16,7 @@ Example valid usage:
|
||||
## Windows Compatibility
|
||||
|
||||
nanobot explicitly supports Windows. Key differences to keep in mind:
|
||||
- `ExecTool` uses `cmd /c` on Windows instead of `sh -c` (`shell.py`).
|
||||
- `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`).
|
||||
- `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.
|
||||
|
||||
+1
-1
@@ -16,7 +16,7 @@ Shell execution (`ExecTool`, `agent/tools/shell.py`) also respects `restrict_to_
|
||||
|
||||
All outbound HTTP requests from agent tools must pass through `validate_url_target` (`security/network.py`). By default it blocks loopback, RFC1918 private addresses, CGNAT ranges, link-local ranges, and cloud metadata endpoints (including `169.254.169.254`).
|
||||
|
||||
The only escape hatch is `configure_ssrf_whitelist(cidrs)`, which reads from `config.tools.ssrf_whitelist` at load time.
|
||||
The only escape hatch is `configure_ssrf_whitelist(cidrs)`. Runtime entry points explicitly apply `config.tools.ssrf_whitelist` after loading the effective config; ordinary config reads must not mutate this process-wide policy.
|
||||
|
||||
HTTP/SSE MCP transports are part of this boundary: validate configured MCP URLs before probing or constructing clients, and validate each outgoing HTTP request before redirects are followed. Local/private HTTP MCP endpoints are allowed only through the explicit SSRF whitelist. Stdio MCP servers are not part of the HTTP SSRF path.
|
||||
|
||||
|
||||
@@ -44,10 +44,38 @@ jobs:
|
||||
run: sudo apt-get update && sudo apt-get install -y libolm-dev build-essential
|
||||
|
||||
- name: Install dependencies
|
||||
run: uv sync --all-extras
|
||||
run: uv sync --all-extras --dev
|
||||
|
||||
- name: Lint with ruff
|
||||
run: uv run ruff check nanobot --select F
|
||||
|
||||
- name: Run tests
|
||||
run: uv run pytest tests/
|
||||
run: uv run python -m pytest tests/ --cov=nanobot --cov-report=term-missing:skip-covered
|
||||
|
||||
webui:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.6
|
||||
|
||||
- name: Install WebUI dependencies
|
||||
working-directory: webui
|
||||
run: bun install
|
||||
|
||||
- name: Lint WebUI
|
||||
working-directory: webui
|
||||
run: bun run lint
|
||||
|
||||
- name: Test WebUI
|
||||
working-directory: webui
|
||||
run: bun run test
|
||||
|
||||
- name: Build WebUI
|
||||
working-directory: webui
|
||||
run: bun run build
|
||||
|
||||
@@ -36,18 +36,17 @@ 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). `manager.py` discovers and coordinates them. Channels are auto-discovered via `pkgutil` scan + entry-point plugins.
|
||||
- **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 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`).
|
||||
- **Config** (`nanobot/config/schema.py`, `loader.py`): Pydantic-based configuration loaded from `~/.nanobot/config.json`. Supports camelCase aliases for JSON compatibility.
|
||||
- **Bridge** (`bridge/`): TypeScript services (e.g. WhatsApp bridge) bundled into the wheel via `pyproject.toml` `force-include`.
|
||||
- **WebUI** (`webui/`): Vite-based React SPA that talks to the gateway over a WebSocket multiplex protocol. The dev server proxies `/api`, `/webui`, `/auth`, and WebSocket traffic to the gateway.
|
||||
- **API Server** (`nanobot/api/server.py`): OpenAI-compatible HTTP API (`/v1/chat/completions`, `/v1/models`) for programmatic access.
|
||||
- **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 (long-goal, cron, github, image-generation, etc.) loaded into agent context.
|
||||
- **Skills** (`nanobot/skills/`): Built-in skill definitions (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
|
||||
|
||||
+16
-22
@@ -1,38 +1,32 @@
|
||||
FROM node:24-bookworm-slim AS webui-builder
|
||||
|
||||
WORKDIR /app
|
||||
COPY webui/package.json webui/package-lock.json ./webui/
|
||||
WORKDIR /app/webui
|
||||
RUN npm ci
|
||||
COPY webui/ ./
|
||||
RUN mkdir -p /app/nanobot/web && npm run build
|
||||
|
||||
FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim
|
||||
|
||||
# Install Node.js for the WhatsApp bridge
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends curl ca-certificates gnupg git bubblewrap openssh-client && \
|
||||
mkdir -p /etc/apt/keyrings && \
|
||||
curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key | gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg && \
|
||||
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_24.x nodistro main" > /etc/apt/sources.list.d/nodesource.list && \
|
||||
apt-get update && \
|
||||
apt-get install -y --no-install-recommends nodejs && \
|
||||
apt-get purge -y gnupg && \
|
||||
apt-get autoremove -y && \
|
||||
apt-get install -y --no-install-recommends ca-certificates git bubblewrap openssh-client libmagic1 && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
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 bridge && touch nanobot/__init__.py && \
|
||||
uv pip install --system --no-cache . && \
|
||||
rm -rf nanobot bridge
|
||||
RUN mkdir -p nanobot && touch nanobot/__init__.py && \
|
||||
NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[$NANOBOT_EXTRAS]" && \
|
||||
rm -rf nanobot
|
||||
|
||||
# Copy the full source and install
|
||||
COPY nanobot/ nanobot/
|
||||
COPY bridge/ bridge/
|
||||
COPY webui/ webui/
|
||||
RUN NANOBOT_FORCE_WEBUI_BUILD=1 uv pip install --system --no-cache .
|
||||
|
||||
# Build the WhatsApp bridge
|
||||
WORKDIR /app/bridge
|
||||
RUN git config --global --add url."https://github.com/".insteadOf ssh://git@github.com/ && \
|
||||
git config --global --add url."https://github.com/".insteadOf git@github.com: && \
|
||||
npm install && npm run build
|
||||
WORKDIR /app
|
||||
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]"
|
||||
|
||||
# Create non-root user and config directory
|
||||
RUN useradd -m -u 1000 -s /bin/bash nanobot && \
|
||||
|
||||
@@ -42,11 +42,37 @@
|
||||
|---|---|
|
||||
| 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 after the CLI works | [WebUI](#-webui) |
|
||||
| Connect Telegram, Discord, WeChat, Slack, Email, or another chat app | [Chat Apps](./docs/chat-apps.md) |
|
||||
| Open the bundled browser UI | [WebUI](#-webui) |
|
||||
| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, 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) |
|
||||
|
||||
## 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
|
||||
|
||||
<p align="center">
|
||||
@@ -54,158 +80,20 @@
|
||||
<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>
|
||||
|
||||
## 📢 News
|
||||
## Recent Updates
|
||||
|
||||
- **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>
|
||||
- **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.
|
||||
|
||||
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, and email.
|
||||
- **Chat-native reach**: WebUI, API, Telegram, Feishu, Slack, Discord, Teams, email, and Mattermost.
|
||||
- **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.
|
||||
@@ -237,7 +125,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 and you enabled the WebSocket channel, skip the manual initialize/configure steps below and go straight to **Open the WebUI**.
|
||||
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**.
|
||||
|
||||
To preview the plan without changing your environment, pass `--dry-run`; combine it with `--dev` when you want to preview the main-branch install.
|
||||
|
||||
@@ -358,14 +246,13 @@ For another provider, the same config shape still applies:
|
||||
|
||||
**3. Open the WebUI**
|
||||
|
||||
If Quick Start enabled the WebSocket channel, start the gateway:
|
||||
Start the browser workbench:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
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`.
|
||||
`nanobot webui` prepares the local WebSocket channel if needed, starts the gateway, and opens `http://127.0.0.1:8765`. It binds the first-run WebUI to `127.0.0.1` by default, so it is not exposed to your LAN. Prefer not to keep a terminal open? Use `nanobot webui --background`, then manage the gateway with `nanobot gateway status`, `logs`, `restart`, and `stop`.
|
||||
|
||||
For manual or terminal-only setup, test one CLI message:
|
||||
|
||||
@@ -399,33 +286,13 @@ 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>
|
||||
|
||||
**1. Enable the WebSocket channel in `~/.nanobot/config.json`**
|
||||
|
||||
Merge this block into your existing config:
|
||||
|
||||
```json
|
||||
{
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"tokenIssueSecret": "your-webui-password",
|
||||
"websocketRequiresToken": true
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**2. Start the gateway**
|
||||
**Open it**
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
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 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). 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.
|
||||
|
||||
@@ -467,6 +334,7 @@ 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)
|
||||
@@ -474,7 +342,8 @@ 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 Apps](./docs/chat-apps.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)
|
||||
- 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)
|
||||
@@ -505,19 +374,6 @@ This project was started by [Xubin Ren](https://github.com/re-bin) as a personal
|
||||
<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">
|
||||
|
||||
+8
-16
@@ -48,7 +48,7 @@ chmod 600 ~/.nanobot/config.json
|
||||
},
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"allowFrom": ["+1234567890"]
|
||||
"allowFrom": ["1234567890"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,7 @@ chmod 600 ~/.nanobot/config.json
|
||||
**Security Notes:**
|
||||
- In `v0.1.4.post3` and earlier, an empty `allowFrom` allowed all users. Since `v0.1.4.post4`, empty `allowFrom` denies all access by default — set `["*"]` to explicitly allow everyone.
|
||||
- Get your Telegram user ID from `@userinfobot`
|
||||
- Use full phone numbers with country code for WhatsApp
|
||||
- Use WhatsApp sender IDs as full phone numbers with country code and no leading `+`
|
||||
- Review access logs regularly for unauthorized access attempts
|
||||
|
||||
### 3. Shell Command Execution
|
||||
@@ -107,12 +107,12 @@ 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 Bridge:**
|
||||
- The bridge binds to `127.0.0.1:3001` (localhost only, not accessible from external network)
|
||||
- Set `bridgeToken` in config to enable shared-secret authentication between Python and Node.js
|
||||
- Keep authentication data in `~/.nanobot/whatsapp-auth` secure (mode 0700)
|
||||
**WhatsApp:**
|
||||
- Keep the neonize session database under `~/.nanobot/whatsapp-auth` secure (mode 0700).
|
||||
- Use `nanobot channels login whatsapp --force` to remove and recreate the local session database when rotating linked devices.
|
||||
|
||||
### 6. Dependency Security
|
||||
|
||||
@@ -127,17 +127,9 @@ pip-audit
|
||||
pip install --upgrade nanobot-ai
|
||||
```
|
||||
|
||||
For Node.js dependencies (WhatsApp bridge):
|
||||
```bash
|
||||
cd bridge
|
||||
npm audit
|
||||
npm audit fix
|
||||
```
|
||||
|
||||
**Important Notes:**
|
||||
- Keep `litellm` updated to the latest version for security fixes
|
||||
- We've updated `ws` to `>=8.17.1` to fix DoS vulnerability
|
||||
- Run `pip-audit` or `npm audit` regularly
|
||||
- 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
|
||||
@@ -238,7 +230,7 @@ If you suspect a security breach:
|
||||
✅ **Secure Communication**
|
||||
- HTTPS for all external API calls
|
||||
- TLS for Telegram API
|
||||
- WhatsApp bridge: localhost-only binding + optional token auth
|
||||
- WhatsApp session secrets stay in the local session database
|
||||
|
||||
## Known Limitations
|
||||
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "nanobot-whatsapp-bridge",
|
||||
"version": "0.1.0",
|
||||
"description": "WhatsApp bridge for nanobot using Baileys",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"start": "node dist/index.js",
|
||||
"dev": "tsc && node dist/index.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"@whiskeysockets/baileys": "7.0.0-rc.9",
|
||||
"ws": "^8.17.1",
|
||||
"qrcode-terminal": "^0.12.0",
|
||||
"pino": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/ws": "^8.5.10",
|
||||
"typescript": "^5.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* nanobot WhatsApp Bridge
|
||||
*
|
||||
* This bridge connects WhatsApp Web to nanobot's Python backend
|
||||
* via WebSocket. It handles authentication, message forwarding,
|
||||
* and reconnection logic.
|
||||
*
|
||||
* Usage:
|
||||
* npm run build && npm start
|
||||
*
|
||||
* Or with custom settings:
|
||||
* BRIDGE_PORT=3001 AUTH_DIR=~/.nanobot/whatsapp npm start
|
||||
*/
|
||||
|
||||
// Polyfill crypto for Baileys in ESM
|
||||
import { webcrypto } from 'crypto';
|
||||
if (!globalThis.crypto) {
|
||||
(globalThis as any).crypto = webcrypto;
|
||||
}
|
||||
|
||||
import { BridgeServer } from './server.js';
|
||||
import { homedir } from 'os';
|
||||
import { join } from 'path';
|
||||
|
||||
const PORT = parseInt(process.env.BRIDGE_PORT || '3001', 10);
|
||||
const AUTH_DIR = process.env.AUTH_DIR || join(homedir(), '.nanobot', 'whatsapp-auth');
|
||||
const TOKEN = process.env.BRIDGE_TOKEN?.trim();
|
||||
|
||||
if (!TOKEN) {
|
||||
console.error('BRIDGE_TOKEN is required. Start the bridge via nanobot so it can provision a local secret automatically.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
console.log('🐈 nanobot WhatsApp Bridge');
|
||||
console.log('========================\n');
|
||||
|
||||
const server = new BridgeServer(PORT, AUTH_DIR, TOKEN);
|
||||
|
||||
// Handle graceful shutdown
|
||||
process.on('SIGINT', async () => {
|
||||
console.log('\n\nShutting down...');
|
||||
await server.stop();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
process.on('SIGTERM', async () => {
|
||||
await server.stop();
|
||||
process.exit(0);
|
||||
});
|
||||
|
||||
// Start the server
|
||||
server.start().catch((error) => {
|
||||
console.error('Failed to start bridge:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,155 +0,0 @@
|
||||
/**
|
||||
* WebSocket server for Python-Node.js bridge communication.
|
||||
* Security: binds to 127.0.0.1 only; requires BRIDGE_TOKEN auth; rejects browser Origin headers.
|
||||
*/
|
||||
|
||||
import { WebSocketServer, WebSocket } from 'ws';
|
||||
import { WhatsAppClient, InboundMessage } from './whatsapp.js';
|
||||
|
||||
interface SendCommand {
|
||||
type: 'send';
|
||||
to: string;
|
||||
text: string;
|
||||
}
|
||||
|
||||
interface SendMediaCommand {
|
||||
type: 'send_media';
|
||||
to: string;
|
||||
filePath: string;
|
||||
mimetype: string;
|
||||
caption?: string;
|
||||
fileName?: string;
|
||||
}
|
||||
|
||||
type BridgeCommand = SendCommand | SendMediaCommand;
|
||||
|
||||
interface BridgeMessage {
|
||||
type: 'message' | 'status' | 'qr' | 'error';
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export class BridgeServer {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private wa: WhatsAppClient | null = null;
|
||||
private clients: Set<WebSocket> = new Set();
|
||||
|
||||
constructor(private port: number, private authDir: string, private token: string) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (!this.token.trim()) {
|
||||
throw new Error('BRIDGE_TOKEN is required');
|
||||
}
|
||||
|
||||
// Bind to localhost only — never expose to external network
|
||||
this.wss = new WebSocketServer({
|
||||
host: '127.0.0.1',
|
||||
port: this.port,
|
||||
verifyClient: (info, done) => {
|
||||
const origin = info.origin || info.req.headers.origin;
|
||||
if (origin) {
|
||||
console.warn(`Rejected WebSocket connection with Origin header: ${origin}`);
|
||||
done(false, 403, 'Browser-originated WebSocket connections are not allowed');
|
||||
return;
|
||||
}
|
||||
done(true);
|
||||
},
|
||||
});
|
||||
console.log(`🌉 Bridge server listening on ws://127.0.0.1:${this.port}`);
|
||||
console.log('🔒 Token authentication enabled');
|
||||
|
||||
// Initialize WhatsApp client
|
||||
this.wa = new WhatsAppClient({
|
||||
authDir: this.authDir,
|
||||
onMessage: (msg) => this.broadcast({ type: 'message', ...msg }),
|
||||
onQR: (qr) => this.broadcast({ type: 'qr', qr }),
|
||||
onStatus: (status) => this.broadcast({ type: 'status', status }),
|
||||
});
|
||||
|
||||
// Handle WebSocket connections
|
||||
this.wss.on('connection', (ws) => {
|
||||
// Require auth handshake as first message
|
||||
const timeout = setTimeout(() => ws.close(4001, 'Auth timeout'), 5000);
|
||||
ws.once('message', (data) => {
|
||||
clearTimeout(timeout);
|
||||
try {
|
||||
const msg = JSON.parse(data.toString());
|
||||
if (msg.type === 'auth' && msg.token === this.token) {
|
||||
console.log('🔗 Python client authenticated');
|
||||
this.setupClient(ws);
|
||||
} else {
|
||||
ws.close(4003, 'Invalid token');
|
||||
}
|
||||
} catch {
|
||||
ws.close(4003, 'Invalid auth message');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Connect to WhatsApp
|
||||
await this.wa.connect();
|
||||
}
|
||||
|
||||
private setupClient(ws: WebSocket): void {
|
||||
this.clients.add(ws);
|
||||
|
||||
ws.on('message', async (data) => {
|
||||
try {
|
||||
const cmd = JSON.parse(data.toString()) as BridgeCommand;
|
||||
await this.handleCommand(cmd);
|
||||
ws.send(JSON.stringify({ type: 'sent', to: cmd.to }));
|
||||
} catch (error) {
|
||||
console.error('Error handling command:', error);
|
||||
ws.send(JSON.stringify({ type: 'error', error: String(error) }));
|
||||
}
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
console.log('🔌 Python client disconnected');
|
||||
this.clients.delete(ws);
|
||||
});
|
||||
|
||||
ws.on('error', (error) => {
|
||||
console.error('WebSocket error:', error);
|
||||
this.clients.delete(ws);
|
||||
});
|
||||
}
|
||||
|
||||
private async handleCommand(cmd: BridgeCommand): Promise<void> {
|
||||
if (!this.wa) return;
|
||||
|
||||
if (cmd.type === 'send') {
|
||||
await this.wa.sendMessage(cmd.to, cmd.text);
|
||||
} else if (cmd.type === 'send_media') {
|
||||
await this.wa.sendMedia(cmd.to, cmd.filePath, cmd.mimetype, cmd.caption, cmd.fileName);
|
||||
}
|
||||
}
|
||||
|
||||
private broadcast(msg: BridgeMessage): void {
|
||||
const data = JSON.stringify(msg);
|
||||
for (const client of this.clients) {
|
||||
if (client.readyState === WebSocket.OPEN) {
|
||||
client.send(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
// Close all client connections
|
||||
for (const client of this.clients) {
|
||||
client.close();
|
||||
}
|
||||
this.clients.clear();
|
||||
|
||||
// Close WebSocket server
|
||||
if (this.wss) {
|
||||
this.wss.close();
|
||||
this.wss = null;
|
||||
}
|
||||
|
||||
// Disconnect WhatsApp
|
||||
if (this.wa) {
|
||||
await this.wa.disconnect();
|
||||
this.wa = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
declare module 'qrcode-terminal' {
|
||||
export function generate(text: string, options?: { small?: boolean }): void;
|
||||
}
|
||||
@@ -1,360 +0,0 @@
|
||||
/**
|
||||
* WhatsApp client wrapper using Baileys.
|
||||
* Based on OpenClaw's working implementation.
|
||||
*/
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import makeWASocket, {
|
||||
DisconnectReason,
|
||||
useMultiFileAuthState,
|
||||
fetchLatestBaileysVersion,
|
||||
makeCacheableSignalKeyStore,
|
||||
downloadMediaMessage,
|
||||
extractMessageContent as baileysExtractMessageContent,
|
||||
} from '@whiskeysockets/baileys';
|
||||
|
||||
import { Boom } from '@hapi/boom';
|
||||
import qrcode from 'qrcode-terminal';
|
||||
import pino from 'pino';
|
||||
import { readFile, writeFile, mkdir } from 'fs/promises';
|
||||
import { join, basename, resolve, sep } from 'path';
|
||||
import { randomBytes } from 'crypto';
|
||||
|
||||
const VERSION = '0.1.0';
|
||||
|
||||
export interface InboundMessage {
|
||||
id: string;
|
||||
sender: string;
|
||||
pn: string;
|
||||
participant?: string;
|
||||
content: string;
|
||||
timestamp: number;
|
||||
isGroup: boolean;
|
||||
isForwarded?: boolean;
|
||||
wasMentioned?: boolean;
|
||||
isReplyToBot?: boolean;
|
||||
media?: string[];
|
||||
}
|
||||
|
||||
export interface WhatsAppClientOptions {
|
||||
authDir: string;
|
||||
onMessage: (msg: InboundMessage) => void;
|
||||
onQR: (qr: string) => void;
|
||||
onStatus: (status: string) => void;
|
||||
}
|
||||
|
||||
export class WhatsAppClient {
|
||||
private sock: any = null;
|
||||
private options: WhatsAppClientOptions;
|
||||
private reconnecting = false;
|
||||
|
||||
constructor(options: WhatsAppClientOptions) {
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
private normalizeJid(jid: string | undefined | null): string {
|
||||
return (jid || '').trim().toLowerCase().replace(/:\d+(?=@)/g, '');
|
||||
}
|
||||
|
||||
private selfJids(): Set<string> {
|
||||
return new Set(
|
||||
[this.sock?.user?.id, this.sock?.user?.lid, this.sock?.user?.jid]
|
||||
.map((jid) => this.normalizeJid(jid))
|
||||
.filter(Boolean),
|
||||
);
|
||||
}
|
||||
|
||||
private messageContextInfos(msg: any): any[] {
|
||||
const unwrapped = baileysExtractMessageContent(msg?.message);
|
||||
const containers = [msg?.message, unwrapped];
|
||||
const infos = containers.flatMap((message) => [
|
||||
message?.extendedTextMessage?.contextInfo,
|
||||
message?.imageMessage?.contextInfo,
|
||||
message?.videoMessage?.contextInfo,
|
||||
message?.documentMessage?.contextInfo,
|
||||
message?.audioMessage?.contextInfo,
|
||||
]);
|
||||
return infos.filter(Boolean);
|
||||
}
|
||||
|
||||
private botAddressing(msg: any): { wasMentioned: boolean; isReplyToBot: boolean } {
|
||||
if (!msg?.key?.remoteJid?.endsWith('@g.us')) {
|
||||
return { wasMentioned: false, isReplyToBot: false };
|
||||
}
|
||||
|
||||
const selfIds = this.selfJids();
|
||||
const contextInfos = this.messageContextInfos(msg);
|
||||
|
||||
const mentioned = contextInfos.flatMap((info) => (
|
||||
Array.isArray(info?.mentionedJid) ? info.mentionedJid : []
|
||||
));
|
||||
const wasMentioned = mentioned.some((jid: string) => selfIds.has(this.normalizeJid(jid)));
|
||||
|
||||
const isReplyToBot = contextInfos.some((info) => {
|
||||
const quotedParticipant = this.normalizeJid(info?.participant);
|
||||
return Boolean(info?.stanzaId && quotedParticipant && selfIds.has(quotedParticipant));
|
||||
});
|
||||
|
||||
return { wasMentioned, isReplyToBot };
|
||||
}
|
||||
|
||||
private isForwarded(msg: any): boolean {
|
||||
return this.messageContextInfos(msg).some((info) => Boolean(info?.isForwarded));
|
||||
}
|
||||
|
||||
async connect(): Promise<void> {
|
||||
const logger = pino({ level: 'silent' });
|
||||
const { state, saveCreds } = await useMultiFileAuthState(this.options.authDir);
|
||||
const { version } = await fetchLatestBaileysVersion();
|
||||
|
||||
console.log(`Using Baileys version: ${version.join('.')}`);
|
||||
|
||||
// Record startup time — messages older than this will be ignored
|
||||
// to avoid replaying history on reconnect
|
||||
const startupTimestamp = Math.floor(Date.now() / 1000);
|
||||
|
||||
// Create socket following OpenClaw's pattern
|
||||
this.sock = makeWASocket({
|
||||
auth: {
|
||||
creds: state.creds,
|
||||
keys: makeCacheableSignalKeyStore(state.keys, logger),
|
||||
},
|
||||
version,
|
||||
logger,
|
||||
printQRInTerminal: false,
|
||||
browser: ['nanobot', 'cli', VERSION],
|
||||
syncFullHistory: false,
|
||||
markOnlineOnConnect: false,
|
||||
});
|
||||
|
||||
// Handle WebSocket errors
|
||||
if (this.sock.ws && typeof this.sock.ws.on === 'function') {
|
||||
this.sock.ws.on('error', (err: Error) => {
|
||||
console.error('WebSocket error:', err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Handle connection updates
|
||||
this.sock.ev.on('connection.update', async (update: any) => {
|
||||
const { connection, lastDisconnect, qr } = update;
|
||||
|
||||
if (qr) {
|
||||
// Display QR code in terminal
|
||||
console.log('\n📱 Scan this QR code with WhatsApp (Linked Devices):\n');
|
||||
qrcode.generate(qr, { small: true });
|
||||
this.options.onQR(qr);
|
||||
}
|
||||
|
||||
if (connection === 'close') {
|
||||
const statusCode = (lastDisconnect?.error as Boom)?.output?.statusCode;
|
||||
const shouldReconnect = statusCode !== DisconnectReason.loggedOut;
|
||||
|
||||
console.log(`Connection closed. Status: ${statusCode}, Will reconnect: ${shouldReconnect}`);
|
||||
this.options.onStatus('disconnected');
|
||||
|
||||
if (shouldReconnect && !this.reconnecting) {
|
||||
this.reconnecting = true;
|
||||
console.log('Reconnecting in 5 seconds...');
|
||||
setTimeout(() => {
|
||||
this.reconnecting = false;
|
||||
this.connect();
|
||||
}, 5000);
|
||||
}
|
||||
} else if (connection === 'open') {
|
||||
console.log('✅ Connected to WhatsApp');
|
||||
this.options.onStatus('connected');
|
||||
}
|
||||
});
|
||||
|
||||
// Save credentials on update
|
||||
this.sock.ev.on('creds.update', saveCreds);
|
||||
|
||||
// Handle incoming messages
|
||||
this.sock.ev.on('messages.upsert', async ({ messages, type }: { messages: any[]; type: string }) => {
|
||||
if (type !== 'notify') return;
|
||||
|
||||
for (const msg of messages) {
|
||||
if (msg.key.fromMe) continue;
|
||||
if (msg.key.remoteJid === 'status@broadcast') continue;
|
||||
|
||||
// Drop messages older than startup time (avoid replaying history on reconnect)
|
||||
const msgTimestamp = msg.messageTimestamp as number;
|
||||
if (msgTimestamp && msgTimestamp < startupTimestamp) continue;
|
||||
|
||||
// Send read receipt (blue check) immediately
|
||||
try {
|
||||
await this.sock!.readMessages([msg.key]);
|
||||
} catch (e) {
|
||||
// Non-fatal: log but don't block message processing
|
||||
console.error('Failed to send read receipt:', (e as Error).message);
|
||||
}
|
||||
|
||||
const unwrapped = baileysExtractMessageContent(msg.message);
|
||||
if (!unwrapped) continue;
|
||||
|
||||
const content = this.getTextContent(unwrapped);
|
||||
let fallbackContent: string | null = null;
|
||||
const mediaPaths: string[] = [];
|
||||
|
||||
if (unwrapped.imageMessage) {
|
||||
fallbackContent = '[Image]';
|
||||
const path = await this.downloadMedia(msg, unwrapped.imageMessage.mimetype ?? undefined);
|
||||
if (path) mediaPaths.push(path);
|
||||
} else if (unwrapped.documentMessage) {
|
||||
fallbackContent = '[Document]';
|
||||
const path = await this.downloadMedia(msg, unwrapped.documentMessage.mimetype ?? undefined,
|
||||
unwrapped.documentMessage.fileName ?? undefined);
|
||||
if (path) mediaPaths.push(path);
|
||||
} else if (unwrapped.videoMessage) {
|
||||
fallbackContent = '[Video]';
|
||||
const path = await this.downloadMedia(msg, unwrapped.videoMessage.mimetype ?? undefined);
|
||||
if (path) mediaPaths.push(path);
|
||||
} else if (unwrapped.audioMessage) {
|
||||
fallbackContent = '[Voice Message]';
|
||||
const path = await this.downloadMedia(msg, unwrapped.audioMessage.mimetype ?? undefined);
|
||||
if (path) mediaPaths.push(path);
|
||||
} else if (unwrapped.contactMessage) {
|
||||
// Single shared contact
|
||||
const displayName = unwrapped.contactMessage.displayName || '';
|
||||
const vcard = unwrapped.contactMessage.vcard || '';
|
||||
fallbackContent = `[Contact: ${displayName}]\n${vcard}`;
|
||||
} else if (unwrapped.contactsArrayMessage) {
|
||||
// Multiple shared contacts
|
||||
const vcards = unwrapped.contactsArrayMessage.contacts || [];
|
||||
const parts = vcards.map((c: any) => {
|
||||
const name = c.displayName || '';
|
||||
const vc = c.vcard || '';
|
||||
return `[Contact: ${name}]\n${vc}`;
|
||||
});
|
||||
fallbackContent = parts.join('\n\n');
|
||||
}
|
||||
|
||||
const isForwarded = this.isForwarded(msg);
|
||||
|
||||
const finalContent = content || (mediaPaths.length === 0 ? fallbackContent : '') || '';
|
||||
if (!finalContent && mediaPaths.length === 0) continue;
|
||||
|
||||
const isGroup = msg.key.remoteJid?.endsWith('@g.us') || false;
|
||||
const { wasMentioned, isReplyToBot } = this.botAddressing(msg);
|
||||
|
||||
this.options.onMessage({
|
||||
id: msg.key.id || '',
|
||||
sender: msg.key.remoteJid || '',
|
||||
pn: msg.key.remoteJidAlt || '',
|
||||
...(isGroup && msg.key.participant ? { participant: msg.key.participant } : {}),
|
||||
content: finalContent,
|
||||
timestamp: msg.messageTimestamp as number,
|
||||
isGroup,
|
||||
...(isForwarded ? { isForwarded } : {}),
|
||||
...(isGroup ? { wasMentioned: wasMentioned || isReplyToBot, isReplyToBot } : {}),
|
||||
...(mediaPaths.length > 0 ? { media: mediaPaths } : {}),
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private async downloadMedia(msg: any, mimetype?: string, fileName?: string): Promise<string | null> {
|
||||
try {
|
||||
const mediaDir = join(this.options.authDir, '..', 'media');
|
||||
await mkdir(mediaDir, { recursive: true });
|
||||
|
||||
const buffer = await downloadMediaMessage(msg, 'buffer', {}) as Buffer;
|
||||
|
||||
let outFilename: string;
|
||||
if (fileName) {
|
||||
const safeName = basename(fileName).replace(/[^a-zA-Z0-9._-]/g, '_');
|
||||
outFilename = `wa_${Date.now()}_${randomBytes(4).toString('hex')}_${safeName}`;
|
||||
} else {
|
||||
const mime = mimetype || 'application/octet-stream';
|
||||
const ext = '.' + (mime.split('/').pop()?.split(';')[0] || 'bin');
|
||||
outFilename = `wa_${Date.now()}_${randomBytes(4).toString('hex')}${ext}`;
|
||||
}
|
||||
|
||||
const filepath = resolve(mediaDir, outFilename);
|
||||
if (!filepath.startsWith(resolve(mediaDir) + sep)) {
|
||||
throw new Error(`Path traversal blocked: ${outFilename}`);
|
||||
}
|
||||
await writeFile(filepath, buffer);
|
||||
|
||||
return filepath;
|
||||
} catch (err) {
|
||||
console.error('Failed to download media:', err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private getTextContent(message: any): string | null {
|
||||
// Text message
|
||||
if (message.conversation) {
|
||||
return message.conversation;
|
||||
}
|
||||
|
||||
// Extended text (reply, link preview)
|
||||
if (message.extendedTextMessage?.text) {
|
||||
return message.extendedTextMessage.text;
|
||||
}
|
||||
|
||||
// Image with optional caption
|
||||
if (message.imageMessage) {
|
||||
return message.imageMessage.caption || '';
|
||||
}
|
||||
|
||||
// Video with optional caption
|
||||
if (message.videoMessage) {
|
||||
return message.videoMessage.caption || '';
|
||||
}
|
||||
|
||||
// Document with optional caption
|
||||
if (message.documentMessage) {
|
||||
return message.documentMessage.caption || '';
|
||||
}
|
||||
|
||||
// Voice/Audio message
|
||||
if (message.audioMessage) {
|
||||
return `[Voice Message]`;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async sendMessage(to: string, text: string): Promise<void> {
|
||||
if (!this.sock) {
|
||||
throw new Error('Not connected');
|
||||
}
|
||||
|
||||
await this.sock.sendMessage(to, { text });
|
||||
}
|
||||
|
||||
async sendMedia(
|
||||
to: string,
|
||||
filePath: string,
|
||||
mimetype: string,
|
||||
caption?: string,
|
||||
fileName?: string,
|
||||
): Promise<void> {
|
||||
if (!this.sock) {
|
||||
throw new Error('Not connected');
|
||||
}
|
||||
|
||||
const buffer = await readFile(filePath);
|
||||
const category = mimetype.split('/')[0];
|
||||
|
||||
if (category === 'image') {
|
||||
await this.sock.sendMessage(to, { image: buffer, caption: caption || undefined, mimetype });
|
||||
} else if (category === 'video') {
|
||||
await this.sock.sendMessage(to, { video: buffer, caption: caption || undefined, mimetype });
|
||||
} else if (category === 'audio') {
|
||||
await this.sock.sendMessage(to, { audio: buffer, mimetype });
|
||||
} else {
|
||||
const name = fileName || basename(filePath);
|
||||
await this.sock.sendMessage(to, { document: buffer, mimetype, fileName: name });
|
||||
}
|
||||
}
|
||||
|
||||
async disconnect(): Promise<void> {
|
||||
if (this.sock) {
|
||||
this.sock.end(undefined);
|
||||
this.sock = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "node",
|
||||
"esModuleInterop": true,
|
||||
"strict": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"declaration": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
+1
-1
@@ -19,7 +19,7 @@ services:
|
||||
command: ["gateway"]
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- 18790:18790
|
||||
- 127.0.0.1:18790:18790
|
||||
- 8765:8765
|
||||
deploy:
|
||||
resources:
|
||||
|
||||
+47
-5
@@ -2,7 +2,7 @@
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
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), open the browser workbench with `nanobot webui`, and use terminal checks when you need lower-level diagnosis.
|
||||
|
||||
Most JSON examples in these docs are snippets to merge into `~/.nanobot/config.json`, not full replacement files.
|
||||
|
||||
@@ -30,6 +30,45 @@ If you find a docs mistake, outdated command, or confusing step, please open an
|
||||
| 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 |
|
||||
|
||||
## Task Guides
|
||||
|
||||
Use these pages when you know the workflow you want and do not want to scan the
|
||||
full reference first.
|
||||
|
||||
| Goal | Guide |
|
||||
|---|---|
|
||||
| Build a personal AI agent | [`guides/build-a-personal-ai-agent.md`](./guides/build-a-personal-ai-agent.md) |
|
||||
| Run a self-hosted AI agent | [`guides/self-hosted-ai-agent.md`](./guides/self-hosted-ai-agent.md) |
|
||||
| Use a browser AI agent WebUI | [`guides/ai-agent-webui.md`](./guides/ai-agent-webui.md) |
|
||||
| Connect an AI agent to chat apps | [`guides/chat-app-ai-agent.md`](./guides/chat-app-ai-agent.md) |
|
||||
| Run long-running agent tasks | [`guides/long-running-ai-agent.md`](./guides/long-running-ai-agent.md) |
|
||||
| Schedule or trigger agent turns | [`automations.md`](./automations.md) |
|
||||
| Add long-term agent memory | [`guides/ai-agent-memory.md`](./guides/ai-agent-memory.md) |
|
||||
| Add MCP tools to an agent | [`guides/mcp-tools-for-ai-agents.md`](./guides/mcp-tools-for-ai-agents.md) |
|
||||
| Run an agent from Python | [`guides/python-ai-agent-sdk.md`](./guides/python-ai-agent-sdk.md) |
|
||||
| Expose an OpenAI-compatible agent API | [`guides/openai-compatible-agent-api.md`](./guides/openai-compatible-agent-api.md) |
|
||||
| Deploy a long-running agent gateway | [`guides/deploy-nanobot-gateway.md`](./guides/deploy-nanobot-gateway.md) |
|
||||
|
||||
Platform-specific chat guides:
|
||||
[`Telegram`](./guides/telegram-ai-agent.md),
|
||||
[`Discord`](./guides/discord-ai-agent.md),
|
||||
[`Slack`](./guides/slack-ai-agent.md),
|
||||
[`Feishu`](./guides/feishu-ai-agent.md),
|
||||
[`WhatsApp`](./guides/whatsapp-ai-agent.md),
|
||||
[`WeChat`](./guides/wechat-ai-agent.md),
|
||||
[`QQ`](./guides/qq-ai-agent.md),
|
||||
[`Email`](./guides/email-ai-agent.md), and
|
||||
[`Mattermost`](./guides/mattermost-ai-agent.md).
|
||||
|
||||
Configuration guides:
|
||||
[`MCP tools`](./guides/configure-mcp-tools.md),
|
||||
[`web search`](./guides/configure-web-search.md),
|
||||
[`model fallback`](./guides/configure-model-fallback.md),
|
||||
[`OpenAI-compatible providers`](./guides/configure-openai-compatible-provider.md),
|
||||
[`Langfuse`](./guides/configure-langfuse-observability.md),
|
||||
[`local security`](./guides/secure-local-ai-agent.md), and
|
||||
[`gateway deployment`](./guides/deploy-nanobot-gateway.md).
|
||||
|
||||
## After the First Reply Works
|
||||
|
||||
Do not configure everything at once. Pick one next surface:
|
||||
@@ -38,7 +77,7 @@ If a local `nanobot agent` session can already answer normally, you can also ask
|
||||
|
||||
| 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` |
|
||||
| Use nanobot in a browser | [`webui.md`](./webui.md) | Run `nanobot webui` and open the local browser workbench |
|
||||
| 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 |
|
||||
@@ -49,9 +88,10 @@ If a local `nanobot agent` session can already answer normally, you can also ask
|
||||
|
||||
| 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 |
|
||||
| Open the bundled browser UI | [`webui.md`](./webui.md) | `nanobot webui`, chat workspace, Apps, Skills, Automations, and settings |
|
||||
| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, or another chat app | [`chat-apps.md`](./chat-apps.md) | A gateway-backed chat channel with access control |
|
||||
| Use automations | [`automations.md`](./automations.md) | Scheduled automations, local triggers, heartbeat, WebUI management, and delivery behavior |
|
||||
| Use slash commands | [`chat-commands.md`](./chat-commands.md) | Pairing, model presets, local triggers, 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 |
|
||||
@@ -64,6 +104,7 @@ If a local `nanobot agent` session can already answer normally, you can also ask
|
||||
| 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 |
|
||||
| Release archive | [`release-archive.md`](./release-archive.md) | Older release and daily update highlights moved out of the README |
|
||||
| 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 |
|
||||
@@ -82,6 +123,7 @@ If a local `nanobot agent` session can already answer normally, you can also ask
|
||||
| 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) |
|
||||
| Scheduled automations and local triggers | [`automations.md`](./automations.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) |
|
||||
|
||||
@@ -1,10 +1,99 @@
|
||||
# Agent Social Network
|
||||
|
||||
🐈 nanobot is capable of linking to the agent social network (agent community). **Just send one message and your nanobot joins automatically!**
|
||||
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.
|
||||
|
||||
| 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` |
|
||||
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.
|
||||
|
||||
Simply send the command above to your nanobot (via CLI or any chat channel), and it will handle the rest.
|
||||
## 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)
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
# 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
|
||||
@@ -103,7 +103,8 @@ class WebhookChannel(BaseChannel):
|
||||
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
|
||||
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.
|
||||
@@ -154,7 +155,7 @@ The key (`webhook`) becomes the config section name. The value points to your `B
|
||||
|
||||
```bash
|
||||
python -m pip install -e .
|
||||
nanobot plugins list # verify "Webhook" shows as "plugin"
|
||||
nanobot plugins list # verify the installed example plugin appears as "webhook"
|
||||
nanobot onboard # auto-adds default config for detected plugins
|
||||
```
|
||||
|
||||
@@ -238,15 +239,15 @@ nanobot channels login <channel_name> --force # re-authenticate
|
||||
| `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_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 (streaming)
|
||||
|
||||
| Method | Description |
|
||||
|--------|-------------|
|
||||
| `async send_delta(chat_id, delta, metadata?)` | Override to receive streaming chunks. See [Streaming Support](#streaming-support) for details. |
|
||||
| `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
|
||||
|
||||
@@ -257,10 +258,12 @@ class OutboundMessage:
|
||||
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
|
||||
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.
|
||||
@@ -279,10 +282,18 @@ If either is missing, the agent falls back to the normal one-shot `send()` path.
|
||||
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"):
|
||||
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
|
||||
|
||||
@@ -290,12 +301,7 @@ async def send_delta(self, chat_id: str, delta: str, metadata: dict[str, Any] |
|
||||
# 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) |
|
||||
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
|
||||
|
||||
@@ -310,18 +316,27 @@ class WebhookChannel(BaseChannel):
|
||||
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, "")
|
||||
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(chat_id, "")
|
||||
self._buffers[chat_id] += delta
|
||||
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[chat_id], final=False)
|
||||
await self._deliver(chat_id, self._buffers[buffer_key], final=False)
|
||||
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
# Non-streaming path — unchanged
|
||||
@@ -350,7 +365,7 @@ When `streaming` is `false` (default) or omitted, only `send()` is called — no
|
||||
|
||||
| Method / Property | Description |
|
||||
|-------------------|-------------|
|
||||
| `async send_delta(chat_id, delta, metadata?)` | Override to handle streaming chunks. No-op by default. |
|
||||
| `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
|
||||
@@ -359,18 +374,20 @@ Besides normal assistant text, nanobot can emit low-emphasis trace blocks. These
|
||||
|
||||
### Progress and Tool Hints
|
||||
|
||||
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.metadata` before rendering:
|
||||
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.event` before rendering:
|
||||
|
||||
```python
|
||||
async def send(self, msg: OutboundMessage) -> None:
|
||||
meta = msg.metadata or {}
|
||||
from nanobot.bus.outbound_events import ProgressEvent
|
||||
|
||||
if meta.get("_tool_hint"):
|
||||
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 meta.get("_progress"):
|
||||
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
|
||||
@@ -412,32 +429,33 @@ class WebhookChannel(BaseChannel):
|
||||
chat_id: str,
|
||||
delta: str,
|
||||
metadata: dict[str, Any] | None = None,
|
||||
*,
|
||||
stream_id: str | 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)
|
||||
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:
|
||||
meta = metadata or {}
|
||||
stream_id = str(meta.get("_stream_id") or chat_id)
|
||||
text = self._reasoning_buffers.pop(stream_id, "")
|
||||
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 metadata flags:**
|
||||
**Reasoning arguments:**
|
||||
|
||||
| Flag | Meaning |
|
||||
| Argument | 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`. |
|
||||
| `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:
|
||||
|
||||
@@ -534,7 +552,7 @@ If not overridden, the base class returns `{"enabled": false}`.
|
||||
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 plugins list # should show the installed example plugin as "webhook"
|
||||
nanobot gateway # test end-to-end
|
||||
```
|
||||
|
||||
@@ -543,8 +561,8 @@ nanobot gateway # test end-to-end
|
||||
```bash
|
||||
$ nanobot plugins list
|
||||
|
||||
Name Source Enabled
|
||||
telegram builtin yes
|
||||
discord builtin no
|
||||
webhook plugin yes
|
||||
Name Type Enabled
|
||||
discord channel no
|
||||
telegram channel yes
|
||||
webhook channel yes
|
||||
```
|
||||
|
||||
+124
-32
@@ -1,6 +1,22 @@
|
||||
# Chat Apps
|
||||
# Chat Apps for Self-Hosted AI Agents
|
||||
|
||||
Connect nanobot to your favorite chat platform. Want to build your own? See the [Channel Plugin Guide](./channel-plugin-guide.md).
|
||||
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 Plugin Guide](./channel-plugin-guide.md).
|
||||
|
||||
Before configuring a chat app, make sure the local CLI path works:
|
||||
|
||||
@@ -10,7 +26,26 @@ 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.
|
||||
|
||||
Most examples below are snippets to merge into `~/.nanobot/config.json`.
|
||||
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.
|
||||
|
||||
> [!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.
|
||||
|
||||
## Common Setup Pattern
|
||||
|
||||
@@ -19,24 +54,25 @@ 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. Keep access control narrow at first with `allowFrom` or the platform-specific allow list.
|
||||
5. Check that nanobot can see the configured channel:
|
||||
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:
|
||||
|
||||
```bash
|
||||
nanobot channels status
|
||||
```
|
||||
|
||||
6. Start the gateway and leave that terminal running:
|
||||
7. Start the gateway and leave that terminal running:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
> `["*"]` 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.
|
||||
> `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.
|
||||
|
||||
| Channel | What you need |
|
||||
|---------|---------------|
|
||||
@@ -59,6 +95,12 @@ 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
|
||||
@@ -79,6 +121,8 @@ If `nanobot channels status` does not show the channel as enabled, the config sn
|
||||
```
|
||||
|
||||
> You can find your **User ID** in Telegram settings. It is shown as `@yourUserId`. Copy this value **without the `@` symbol** and paste it into the config file.
|
||||
>
|
||||
> `richMessages` defaults to `false`. Set it to `true` only if your Telegram client supports Bot API 10.1 rich messages and you want richer markdown rendering; keep it disabled for Telegram Web, which may show unsupported-message errors for rich messages.
|
||||
|
||||
|
||||
**3. Run**
|
||||
@@ -121,6 +165,14 @@ 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):
|
||||
@@ -231,14 +283,14 @@ nanobot gateway
|
||||
<details>
|
||||
<summary><b>Matrix (Element)</b></summary>
|
||||
|
||||
Install Matrix dependencies first:
|
||||
Enable Matrix support first:
|
||||
|
||||
```bash
|
||||
python -m pip install "nanobot-ai[matrix]"
|
||||
nanobot plugins enable matrix
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> 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.
|
||||
> 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.
|
||||
|
||||
**1. Create/choose a Matrix account**
|
||||
|
||||
@@ -301,9 +353,13 @@ nanobot gateway
|
||||
<details>
|
||||
<summary><b>WhatsApp</b></summary>
|
||||
|
||||
Requires **Node.js ≥18**.
|
||||
Requires the WhatsApp optional dependencies:
|
||||
|
||||
**1. Link device**
|
||||
```bash
|
||||
nanobot plugins enable whatsapp
|
||||
```
|
||||
|
||||
**1. Link device with QR**
|
||||
|
||||
```bash
|
||||
nanobot channels login whatsapp
|
||||
@@ -317,30 +373,41 @@ nanobot channels login whatsapp
|
||||
"channels": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"allowFrom": ["+1234567890"]
|
||||
"allowFrom": ["1234567890"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**3. Run** (two terminals)
|
||||
Optional session database path:
|
||||
|
||||
```bash
|
||||
# Terminal 1
|
||||
nanobot channels login whatsapp
|
||||
|
||||
# Terminal 2
|
||||
nanobot gateway
|
||||
```json
|
||||
{
|
||||
"channels": {
|
||||
"whatsapp": {
|
||||
"databasePath": "~/.nanobot/whatsapp-auth/neonize.db"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> WhatsApp bridge updates are not applied automatically for existing installations. After upgrading nanobot, rebuild the local bridge with:
|
||||
> `rm -rf ~/.nanobot/bridge && nanobot channels login whatsapp`
|
||||
**Migrating from the old bridge**
|
||||
|
||||
- Remove `bridgeUrl` and `bridgeToken`; WhatsApp no longer runs a local Node.js bridge.
|
||||
- Re-run `nanobot channels login whatsapp`; old Baileys bridge auth data is not reused by neonize.
|
||||
- Update `allowFrom` entries to the WhatsApp sender ID without a leading `+`.
|
||||
|
||||
**3. Run**
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
```
|
||||
|
||||
**Optional: static LID mappings**
|
||||
|
||||
Modern WhatsApp can deliver a sender's LID instead of their phone number. nanobot
|
||||
learns the LID→phone mapping at runtime (and reuses the ones the bridge persists on
|
||||
disk), but you can also seed mappings up front so the phone number resolves from the
|
||||
learns LID to phone mappings at runtime when both identifiers are present, but you
|
||||
can also seed mappings up front so the phone number resolves from the
|
||||
very first message:
|
||||
|
||||
```json
|
||||
@@ -348,7 +415,7 @@ very first message:
|
||||
"channels": {
|
||||
"whatsapp": {
|
||||
"enabled": true,
|
||||
"allowFrom": ["+1234567890"],
|
||||
"allowFrom": ["1234567890"],
|
||||
"lidMappings": { "123456789012345": "1234567890" }
|
||||
}
|
||||
}
|
||||
@@ -365,6 +432,7 @@ 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
|
||||
```
|
||||
@@ -435,6 +503,12 @@ 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
|
||||
@@ -487,6 +561,12 @@ 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
|
||||
@@ -524,6 +604,12 @@ Connects to a [Napcat](https://github.com/NapNeko/NapCatQQ) instance over its **
|
||||
|
||||
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
|
||||
@@ -566,6 +652,12 @@ 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
|
||||
@@ -676,10 +768,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. Install with WeChat support**
|
||||
**1. Enable WeChat support**
|
||||
|
||||
```bash
|
||||
python -m pip install "nanobot-ai[weixin]"
|
||||
nanobot plugins enable weixin
|
||||
```
|
||||
|
||||
**2. Configure**
|
||||
@@ -728,10 +820,10 @@ nanobot gateway
|
||||
>
|
||||
> Uses **WebSocket** long connection — no public IP required.
|
||||
|
||||
**1. Install the optional dependency**
|
||||
**1. Enable WeCom support**
|
||||
|
||||
```bash
|
||||
python -m pip install "nanobot-ai[wecom]"
|
||||
nanobot plugins enable wecom
|
||||
```
|
||||
|
||||
**2. Create a WeCom AI Bot**
|
||||
@@ -767,10 +859,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. Install the optional dependency**
|
||||
**1. Enable Microsoft Teams support**
|
||||
|
||||
```bash
|
||||
python -m pip install "nanobot-ai[msteams]"
|
||||
nanobot plugins enable msteams
|
||||
```
|
||||
|
||||
**2. Create a Teams / Azure bot app registration**
|
||||
|
||||
+72
-4
@@ -15,7 +15,11 @@ 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 |
|
||||
@@ -55,20 +59,84 @@ 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 tasks 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 results to your most recently active chat channel. If there are no active tasks, the heartbeat is skipped silently.
|
||||
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.
|
||||
|
||||
Use heartbeat for recurring checks that should usually stay quiet. User-created cron jobs are different: they run as scheduled turns in the chat/session where they were created and normally deliver the result back to that channel.
|
||||
|
||||
**Setup:** edit `~/.nanobot/workspace/HEARTBEAT.md` (created automatically by `nanobot onboard`):
|
||||
|
||||
```markdown
|
||||
## Active Tasks
|
||||
|
||||
- Check weather forecast and send a summary
|
||||
- Scan inbox for urgent emails
|
||||
- Check weather forecast and notify me only if storms are expected
|
||||
- Scan inbox for urgent emails and notify me if any are found
|
||||
```
|
||||
|
||||
The agent can also manage this file itself — ask it to "add a periodic task" and it will update `HEARTBEAT.md` for you. Completed tasks should be deleted from the file, not moved to another section.
|
||||
The agent can also manage this file itself - ask it to "add a periodic background check" or "check this periodically but only notify me if something changes" and it will update `HEARTBEAT.md` for you. Completed tasks should be deleted from the file, not moved to another section.
|
||||
|
||||
You can change the interval or disable the built-in heartbeat in `~/.nanobot/config.json`:
|
||||
|
||||
|
||||
+118
-6
@@ -8,13 +8,17 @@ 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 |
|
||||
| Check config without calling a model | `nanobot status` | Reads the default config and summarizes the active model/provider |
|
||||
| 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 |
|
||||
| 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` |
|
||||
| Use WebUI or chat apps | `nanobot gateway` | Keep this terminal running, or use `nanobot gateway --background` |
|
||||
| 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 |
|
||||
| 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 |
|
||||
|
||||
@@ -55,6 +59,7 @@ 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 |
|
||||
|
||||
@@ -77,11 +82,26 @@ 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. 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. 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.
|
||||
|
||||
| Command | Description |
|
||||
|---|---|
|
||||
@@ -122,6 +142,55 @@ 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 |
|
||||
@@ -140,6 +209,8 @@ 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
|
||||
@@ -148,7 +219,13 @@ See [`openai-api.md`](./openai-api.md) for request examples.
|
||||
nanobot status
|
||||
```
|
||||
|
||||
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.
|
||||
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 |
|
||||
|
||||
## Channels
|
||||
|
||||
@@ -159,6 +236,7 @@ Shows the default config path, workspace path, active model, and provider summar
|
||||
| `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:
|
||||
|
||||
@@ -170,12 +248,46 @@ 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` | Authenticate OpenAI Codex provider |
|
||||
| `nanobot provider login github-copilot` | Authenticate GitHub Copilot provider |
|
||||
| `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 logout openai-codex` | Remove OpenAI Codex OAuth state |
|
||||
| `nanobot provider logout github-copilot` | Remove GitHub Copilot OAuth state |
|
||||
|
||||
|
||||
+20
-5
@@ -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, and others |
|
||||
| Channels | User-facing transports such as CLI, WebUI/WebSocket, Telegram, Discord, Slack, Feishu, WeChat, Email, Mattermost, 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 |
|
||||
@@ -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 and heartbeat tasks;
|
||||
- cron reminders, local triggers, and heartbeat tasks;
|
||||
- image generation;
|
||||
- subagents and runtime self-inspection.
|
||||
|
||||
@@ -131,14 +131,29 @@ Security-sensitive controls live in [`configuration.md#security`](./configuratio
|
||||
|
||||
## Background Jobs
|
||||
|
||||
When `nanobot gateway` starts, it creates workspace-scoped cron storage at `<workspace>/cron/jobs.json` and registers system jobs:
|
||||
When `nanobot gateway` starts, it runs workspace-scoped automations 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 useful results to the most recently active chat target.
|
||||
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.
|
||||
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.
|
||||
|
||||
## Where to Go Next
|
||||
|
||||
|
||||
+184
-144
@@ -13,6 +13,61 @@ For setup and runtime failures, follow the diagnosis order in [`troubleshooting.
|
||||
> [!NOTE]
|
||||
> 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.
|
||||
|
||||
## Python Configuration API
|
||||
|
||||
> [!WARNING]
|
||||
> `nanobot.config.load_config` and `nanobot.config.loader.load_config` have been
|
||||
> removed. There is intentionally no compatibility alias because the old name
|
||||
> did not distinguish the persisted representation from the runtime view.
|
||||
|
||||
Python embedders and plugins must choose the view they need explicitly:
|
||||
|
||||
```python
|
||||
from pathlib import Path
|
||||
|
||||
from nanobot.config import (
|
||||
apply_config_runtime_policies,
|
||||
load_effective_config,
|
||||
load_raw_config,
|
||||
)
|
||||
|
||||
path = Path.home() / ".nanobot" / "config.json"
|
||||
|
||||
# For settings editors and persistence flows: preserves ${VAR} placeholders.
|
||||
persisted = load_raw_config(path)
|
||||
|
||||
# For agents, providers, channels, and tools: resolves ${VAR} placeholders.
|
||||
runtime = load_effective_config(path)
|
||||
apply_config_runtime_policies(runtime)
|
||||
```
|
||||
|
||||
Use this migration mapping:
|
||||
|
||||
| Previous call | Replacement |
|
||||
|---|---|
|
||||
| `load_config(path)` used to inspect or edit persisted values | `load_raw_config(path)` |
|
||||
| `resolve_config_env_vars(load_config(path))` used at runtime | `load_effective_config(path)` |
|
||||
| Loading followed by implicit process-policy setup | `load_effective_config(path)`, then `apply_config_runtime_policies(config)` at the runtime boundary |
|
||||
|
||||
This is a Python API breaking change for embedders and plugins that import the
|
||||
old function. The `config.json` format is unchanged, and the bundled CLI,
|
||||
gateway, and WebUI already use the explicit APIs.
|
||||
|
||||
## 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) |
|
||||
|
||||
## Quick Jump
|
||||
|
||||
| Need | Section |
|
||||
@@ -41,16 +96,15 @@ If you are not sure where a setting belongs, start from the task you are trying
|
||||
| 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 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) |
|
||||
| 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) |
|
||||
| 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) |
|
||||
| Accept incoming webhooks | `webhooks.routes.<name>` with `secret`, `to`, and optional `prompt` | `nanobot gateway`, then POST to `gateway.port` | [Webhooks](#webhooks) |
|
||||
| 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 | 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) |
|
||||
| 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) |
|
||||
| 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
|
||||
@@ -199,7 +253,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
|
||||
python -m pip install langfuse
|
||||
nanobot plugins enable langfuse
|
||||
```
|
||||
|
||||
Set Langfuse credentials before starting `nanobot agent`, `nanobot gateway`, or `nanobot serve`:
|
||||
@@ -233,7 +287,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.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.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.
|
||||
> - **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`.
|
||||
@@ -241,12 +295,14 @@ 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_zen` | LLM gateway (OpenCode Zen coding-agent models) | [opencode.ai/docs/zen](https://opencode.ai/docs/zen/) |
|
||||
| `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_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) |
|
||||
@@ -282,7 +338,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` |
|
||||
| `openai_codex` | LLM (Codex, OAuth) | `nanobot provider login openai-codex --set-main` |
|
||||
| `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) |
|
||||
|
||||
@@ -380,7 +436,7 @@ Omit `apiKey` (or leave it empty / unset). The provider falls back to [`DefaultA
|
||||
Install the optional dependency:
|
||||
|
||||
```bash
|
||||
python -m pip install 'nanobot-ai[azure]'
|
||||
nanobot plugins enable azure
|
||||
```
|
||||
|
||||
`DefaultAzureCredential` walks this chain in order and uses the first identity that succeeds:
|
||||
@@ -395,7 +451,7 @@ python -m pip install 'nanobot-ai[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 `python -m pip install 'nanobot-ai[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 `nanobot plugins enable azure`.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -439,6 +495,17 @@ 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:
|
||||
@@ -633,42 +700,19 @@ nanobot agent -m "Reply with one short sentence."
|
||||
<details>
|
||||
<summary><b>OpenAI Codex (OAuth)</b></summary>
|
||||
|
||||
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.
|
||||
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:
|
||||
|
||||
**1. Login:**
|
||||
```bash
|
||||
nanobot provider login openai-codex
|
||||
nanobot provider login openai-codex --set-main
|
||||
```
|
||||
|
||||
**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"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
Then run:
|
||||
|
||||
**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!"
|
||||
```
|
||||
|
||||
> Docker users: use `docker run -it` for interactive OAuth login.
|
||||
For proxy, remote/headless login, model-name, or config-key errors, see [`troubleshooting.md`](./troubleshooting.md#provider-and-model-problems).
|
||||
|
||||
</details>
|
||||
|
||||
@@ -676,7 +720,17 @@ nanobot agent -c ~/.nanobot-telegram/config.json -w /tmp/nanobot-telegram-test -
|
||||
<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.githubCopilot` block is needed in `config.json`; `nanobot provider login` stores the OAuth session outside config.
|
||||
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"
|
||||
```
|
||||
|
||||
**1. Login:**
|
||||
```bash
|
||||
@@ -724,6 +778,7 @@ 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>` |
|
||||
|
||||
@@ -732,13 +787,13 @@ OpenCode Zen:
|
||||
```json
|
||||
{
|
||||
"providers": {
|
||||
"opencodeZen": {
|
||||
"opencode": {
|
||||
"apiKey": "${OPENCODE_API_KEY}"
|
||||
}
|
||||
},
|
||||
"modelPresets": {
|
||||
"opencodeZen": {
|
||||
"provider": "opencode_zen",
|
||||
"provider": "opencode",
|
||||
"model": "opencode/deepseek-v4-pro"
|
||||
}
|
||||
},
|
||||
@@ -750,6 +805,8 @@ OpenCode Zen:
|
||||
}
|
||||
```
|
||||
|
||||
`providers.opencodeZen` / `provider: "opencode_zen"` still work as compatibility aliases for existing configs.
|
||||
|
||||
OpenCode Go:
|
||||
|
||||
```json
|
||||
@@ -986,6 +1043,29 @@ Some OpenAI-compatible gateways expose request-body extensions such as vLLM guid
|
||||
}
|
||||
```
|
||||
|
||||
If a custom OpenAI-compatible endpoint exposes a provider-specific thinking toggle, set `thinkingStyle` so nanobot can translate `reasoningEffort` into the right request body. Supported styles are `thinking_type` (`{"thinking":{"type":"enabled"}}`), `enable_thinking` (`{"enable_thinking": true}`), and `reasoning_split` (`{"reasoning_split": true}`):
|
||||
|
||||
```json
|
||||
{
|
||||
"providers": {
|
||||
"companyProxy": {
|
||||
"apiKey": "${COMPANY_PROXY_API_KEY}",
|
||||
"apiBase": "https://api.your-provider.com/v1",
|
||||
"thinkingStyle": "enable_thinking"
|
||||
}
|
||||
},
|
||||
"modelPresets": {
|
||||
"company": {
|
||||
"provider": "companyProxy",
|
||||
"model": "served-model-name",
|
||||
"reasoningEffort": "high"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Leave `thinkingStyle` unset unless the endpoint explicitly documents one of those wire formats. `extraBody` is still applied last, so advanced users can override the generated value.
|
||||
|
||||
</details>
|
||||
|
||||
<a id="local-providers"></a>
|
||||
@@ -1458,8 +1538,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 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. |
|
||||
| `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. |
|
||||
| `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`.
|
||||
@@ -1483,6 +1563,8 @@ Global settings that apply to all channels. Configure under the `channels` secti
|
||||
}
|
||||
```
|
||||
|
||||
Telegram `richMessages` defaults to `false`. Enable it only to opt in to Bot API 10.1 `sendRichMessage` rendering; leave it disabled for Telegram Web clients that show unsupported-message errors for rich messages.
|
||||
|
||||
### Retry Behavior
|
||||
|
||||
Retry is intentionally simple.
|
||||
@@ -1531,18 +1613,21 @@ 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 all web requests (search + fetch) through a proxy:
|
||||
> Use `proxy` in `tools.web` to route web requests 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 all web requests, for example `http://127.0.0.1:7890` |
|
||||
| `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. |
|
||||
| `userAgent` | string or null | `null` | User-Agent header for all web requests. If null, a browser one will be used |
|
||||
|
||||
### Web Search
|
||||
@@ -1685,6 +1770,22 @@ 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
|
||||
{
|
||||
@@ -1716,7 +1817,7 @@ Keenable search works out of the box with no account, via its token-less public
|
||||
|
||||
| Option | Type | Default | Description |
|
||||
|--------|------|---------|-------------|
|
||||
| `provider` | string | `"duckduckgo"` | Search backend: `brave`, `tavily`, `jina`, `kagi`, `olostep`, `bocha`, `volcengine`, `keenable`, `searxng`, `duckduckgo` |
|
||||
| `provider` | string | `"duckduckgo"` | Search backend: `brave`, `tavily`, `jina`, `kagi`, `olostep`, `bocha`, `volcengine`, `keenable`, `serper`, `searxng`, `duckduckgo` |
|
||||
| `apiKey` | string | `""` | API key for API-backed search providers |
|
||||
| `baseUrl` | string | `""` | Base URL for SearXNG |
|
||||
| `maxResults` | integer | `5` | Results per search (1–10) |
|
||||
@@ -1828,9 +1929,9 @@ Use `enabledTools` to register only a subset of tools from an MCP server:
|
||||
|
||||
`enabledTools` accepts either the raw MCP tool name (for example `read_file`) or the wrapped nanobot tool name (for example `mcp_filesystem_write_file`).
|
||||
|
||||
- Omit `enabledTools`, or set it to `["*"]`, to register all tools.
|
||||
- Set `enabledTools` to `[]` to register no tools from that server.
|
||||
- Set `enabledTools` to a non-empty list of names to register only that subset.
|
||||
- Omit `enabledTools`, or set it to `["*"]`, to register all capabilities (tools, resources, and prompts).
|
||||
- Set `enabledTools` to `[]` to register no tools from that server. Resources and prompts are also skipped, since they have no per-name filter.
|
||||
- Set `enabledTools` to a non-empty list of names to register only those tools — resources and prompts are not registered.
|
||||
|
||||
MCP tools are automatically discovered and registered on startup. The LLM can use them alongside built-in tools — no extra configuration needed.
|
||||
|
||||
@@ -1852,6 +1953,7 @@ 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. |
|
||||
|
||||
@@ -1864,7 +1966,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 any channel (Telegram, Discord, Slack, etc.) where they aren't yet approved.
|
||||
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`.
|
||||
2. The bot replies with a pairing code (like `ABCD-EFGH`) and tells them to forward it to you.
|
||||
3. You approve the code:
|
||||
|
||||
@@ -1878,7 +1980,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`, 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:
|
||||
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:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -1890,6 +1992,21 @@ By default, if you don't set `allowFrom`, anyone who isn't approved yet will get
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
@@ -1923,99 +2040,6 @@ nanobot agent -m "/pairing approve ABCD-EFGH"
|
||||
```
|
||||
|
||||
|
||||
## Webhooks
|
||||
|
||||
Webhooks let external systems start a nanobot turn by sending an authenticated HTTP `POST` to the gateway health port. They are event sources, not chat channels: the HTTP caller gets an immediate JSON acceptance response, and the agent's actual reply is delivered to the configured chat target.
|
||||
|
||||
`nanobot gateway` serves webhook routes on `gateway.host:gateway.port`, the same small HTTP listener that serves `/health`. If the gateway is behind a tunnel or reverse proxy, terminate TLS and public host policy there, then forward only the route paths you need.
|
||||
|
||||
### Generic route
|
||||
|
||||
```json
|
||||
{
|
||||
"webhooks": {
|
||||
"enabled": true,
|
||||
"routes": {
|
||||
"deploy": {
|
||||
"secret": "${NANOBOT_DEPLOY_WEBHOOK_SECRET}",
|
||||
"to": "telegram:123456789",
|
||||
"prompt": "Deployment event for {{ event.service }}: {{ event.status }}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The default route path is `/webhooks/<route-name>`, so the example above listens on `/webhooks/deploy`. Set `path` only when the external platform requires a different URL.
|
||||
|
||||
For generic webhooks with `auth: "secret"` (the default), send one of these:
|
||||
|
||||
```text
|
||||
Authorization: Bearer <secret>
|
||||
X-Nanobot-Auth: <secret>
|
||||
X-Nanobot-Signature-256: sha256=<hmac_sha256(raw_body, secret)>
|
||||
```
|
||||
|
||||
Use the HMAC header when the sender supports request signing. Bearer-style headers are simpler for systems that only support static secret headers. `auth: "none"` is available for trusted local-only integrations, but do not expose unauthenticated routes to the public internet.
|
||||
|
||||
### GitHub route
|
||||
|
||||
```json
|
||||
{
|
||||
"webhooks": {
|
||||
"routes": {
|
||||
"github": {
|
||||
"provider": "github",
|
||||
"secret": "${GITHUB_WEBHOOK_SECRET}",
|
||||
"to": "discord:repo-events",
|
||||
"events": ["pull_request"],
|
||||
"actions": ["opened", "synchronize", "reopened", "ready_for_review"],
|
||||
"thread": "github:{{ github.repository_full_name }}:{{ github.pull_request.number or github.issue.number or github.ref }}",
|
||||
"prompt": "Review {{ github.repository_full_name }} PR #{{ github.pull_request.number }} after {{ github.action }}.\n\n{{ body }}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
For `provider: "github"`, nanobot validates GitHub's `X-Hub-Signature-256` HMAC header and deduplicates deliveries by `X-GitHub-Delivery` for `dedupeTtlS` seconds.
|
||||
Use `events` and `actions` to keep setup pings, issue events, or unrelated PR actions from starting an agent turn.
|
||||
|
||||
### Template data
|
||||
|
||||
`prompt` and `thread` are Jinja templates. If `prompt` is empty, nanobot builds a generic event summary and includes a warning that webhook payloads are untrusted external data.
|
||||
|
||||
Common template variables:
|
||||
|
||||
| Variable | Description |
|
||||
|----------|-------------|
|
||||
| `event` / `payload` / `json` | Parsed JSON body for JSON requests. |
|
||||
| `body` | Raw UTF-8 request body. |
|
||||
| `headers` | Request headers with secrets redacted. |
|
||||
| `event_name` | Generic event header or GitHub event name. |
|
||||
| `delivery_id` | Delivery ID used for deduplication when present. |
|
||||
| `github.*` | GitHub-specific fields such as `event`, `action`, `repository_full_name`, `sender_login`, `issue_title`, and `pull_request_title`. |
|
||||
|
||||
`to` is required for enabled routes and uses `channel:chat` format, for example `telegram:123456789`, `discord:repo-events`, or `websocket:webhooks`. It decides where the agent answer is sent. `thread` is optional; when omitted, the session key defaults to the same `channel:chat` value.
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `webhooks.enabled` | `true` | Enables the webhook subsystem. |
|
||||
| `webhooks.routes.<name>.enabled` | `true` | Enables one route. Route names may contain letters, numbers, `_`, `.`, and `-`. |
|
||||
| `webhooks.routes.<name>.path` | `/webhooks/<name>` | HTTP path served by the gateway. `/health` is reserved. |
|
||||
| `webhooks.routes.<name>.provider` | `generic` | Registered webhook provider. Built-ins are `generic` and `github`; provider controls signature and context handling. |
|
||||
| `webhooks.routes.<name>.auth` | `secret` | `secret` or `none`. |
|
||||
| `webhooks.routes.<name>.secret` | empty | Shared secret or signing secret. Use `${ENV_VAR}` placeholders for real deployments. |
|
||||
| `webhooks.routes.<name>.to` | empty | Required target address in `channel:chat` format. |
|
||||
| `webhooks.routes.<name>.events` | `[]` | Optional provider event-name allowlist. For GitHub this matches `X-GitHub-Event`, such as `pull_request`. |
|
||||
| `webhooks.routes.<name>.actions` | `[]` | Optional JSON payload `action` allowlist, such as `opened` or `synchronize`. |
|
||||
| `webhooks.routes.<name>.thread` | empty | Optional Jinja template for the session key. Defaults to `to`; rendered values are capped at 512 characters. |
|
||||
| `webhooks.routes.<name>.prompt` | empty | Optional Jinja template for the inbound agent message. |
|
||||
| `webhooks.routes.<name>.sender` | `webhook` | Sender ID placed on the inbound message. |
|
||||
| `webhooks.routes.<name>.maxBodyBytes` | `1048576` | Maximum request body size, from 1 KiB to 10 MiB. |
|
||||
| `webhooks.routes.<name>.dedupeTtlS` | `3600` | In-memory duplicate delivery TTL. Set `0` to disable dedupe. |
|
||||
|
||||
|
||||
## Gateway Heartbeat
|
||||
|
||||
The gateway can run a protected heartbeat cron job that periodically checks `HEARTBEAT.md` in the active workspace. This is enabled by default when you run `nanobot gateway`.
|
||||
@@ -2032,7 +2056,9 @@ The gateway can run a protected heartbeat cron job that periodically checks `HEA
|
||||
}
|
||||
```
|
||||
|
||||
If `HEARTBEAT.md` has tasks under `## Active Tasks`, the agent executes them and delivers useful results to the most recently active chat target. If the file has no active tasks, the heartbeat is skipped silently.
|
||||
If `HEARTBEAT.md` has tasks under `## Active Tasks`, the agent executes them and sends only useful/actionable results to the most recently active chat target. If the file has no active tasks, or the result is routine with nothing useful to report, the heartbeat is skipped silently.
|
||||
|
||||
This is intentionally different from user-created cron jobs. A cron job created with the `cron` tool runs as a scheduled turn in its origin chat/session and normally delivers the result back to that channel. Use `HEARTBEAT.md` for recurring background checks that should not notify the user on every run.
|
||||
|
||||
The heartbeat job is backed by the same cron service as user-created reminders. It is stored under the active workspace (`<workspace>/cron/jobs.json`) and shows up in `cron(action="list")` as `heartbeat`, but it is system-managed and cannot be removed with the `cron` tool. Disable it through config and restart the gateway if you do not want periodic heartbeat checks.
|
||||
|
||||
@@ -2041,6 +2067,7 @@ 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. |
|
||||
|
||||
|
||||
## Subagent Concurrency
|
||||
@@ -2057,9 +2084,22 @@ By default, nanobot only allows one spawned subagent at a time. When the limit i
|
||||
}
|
||||
```
|
||||
|
||||
Subagents also stop immediately when one of their tools returns an execution error. That default keeps failures visible to the parent agent. If your subagent workflows use tools that can fail transiently and should be retried or worked around by the model, disable hard-stop behavior:
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": {
|
||||
"defaults": {
|
||||
"failOnToolError": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
| Option | Default | Description |
|
||||
|--------|---------|-------------|
|
||||
| `agents.defaults.maxConcurrentSubagents` | `1` | Maximum number of spawned subagents that may run at the same time. Attempts to spawn beyond this limit return an error. |
|
||||
| `agents.defaults.failOnToolError` | `true` | Stop a spawned subagent when a tool execution fails. Set to `false` to return tool errors to the subagent model so it can recover within the same run. |
|
||||
|
||||
|
||||
## Auto Compact
|
||||
|
||||
+8
-4
@@ -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 `18790`; WebUI/WebSocket defaults to `8765`; `nanobot serve` defaults to `8900` |
|
||||
| Ports are planned | Gateway health defaults to local-only `127.0.0.1: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,14 +38,13 @@ 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, enable the WebSocket channel 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, bind the WebSocket channel externally 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"
|
||||
@@ -55,6 +54,11 @@ 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
|
||||
|
||||
@@ -94,7 +98,7 @@ docker run \
|
||||
--security-opt apparmor=unconfined \
|
||||
--security-opt seccomp=unconfined \
|
||||
-v ~/.nanobot:/home/nanobot/.nanobot \
|
||||
-p 18790:18790 -p 8765:8765 \
|
||||
-p 127.0.0.1:18790:18790 -p 8765:8765 \
|
||||
nanobot gateway
|
||||
|
||||
# Or run a single command
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# nanobot Guides
|
||||
|
||||
These guides are short task entry points. Use them when you know what you want
|
||||
to build, then follow the linked reference docs for complete option tables and
|
||||
edge cases.
|
||||
|
||||
## Build and operate
|
||||
|
||||
| Goal | Guide |
|
||||
|---|---|
|
||||
| Build a personal AI agent | [Build a personal AI agent](./build-a-personal-ai-agent.md) |
|
||||
| Run a self-hosted AI agent | [Self-hosted AI agent](./self-hosted-ai-agent.md) |
|
||||
| Use the browser workbench | [AI agent WebUI](./ai-agent-webui.md) |
|
||||
| Run long-running tasks | [Long-running AI agent](./long-running-ai-agent.md) |
|
||||
| Add memory | [AI agent memory](./ai-agent-memory.md) |
|
||||
| Deploy a gateway | [Deploy a long-running nanobot AI agent gateway](./deploy-nanobot-gateway.md) |
|
||||
|
||||
## Connect and integrate
|
||||
|
||||
| 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) |
|
||||
| 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
|
||||
|
||||
| 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) |
|
||||
@@ -0,0 +1,72 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,73 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,83 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,94 @@
|
||||
# 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 agent -m "Hello!"
|
||||
```
|
||||
|
||||
Then choose one platform guide:
|
||||
|
||||
- [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
|
||||
|
||||
Every channel follows the same pattern:
|
||||
|
||||
1. Get the platform token, login state, webhook, or mailbox credentials.
|
||||
2. Merge the channel snippet into `~/.nanobot/config.json`.
|
||||
3. Prefer pairing for DM-capable channels: omit `allowFrom`, then approve the
|
||||
first DM's pairing code.
|
||||
4. For channels without pairing, such as Email, keep access narrow with
|
||||
`allowFrom` or platform-specific allow lists.
|
||||
5. Check status:
|
||||
|
||||
```bash
|
||||
nanobot channels status
|
||||
```
|
||||
|
||||
6. Start the gateway:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
```
|
||||
|
||||
7. Send a test DM, approve the pairing code when prompted, then send the test
|
||||
message again.
|
||||
|
||||
## 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 it with
|
||||
`/pairing approve <code>` before expecting normal replies.
|
||||
- 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)
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,74 @@
|
||||
# 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 server entry in `~/.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
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,93 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,93 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,90 @@
|
||||
# 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 `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
|
||||
|
||||
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)
|
||||
@@ -0,0 +1,76 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,107 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,93 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,120 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,73 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,104 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,74 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,75 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,102 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,78 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,83 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,109 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,109 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,103 @@
|
||||
# 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)
|
||||
@@ -0,0 +1,107 @@
|
||||
# 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)
|
||||
@@ -1,6 +1,6 @@
|
||||
# Image Generation
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
The feature is disabled by default. Enable it in `~/.nanobot/config.json`, configure a supported image provider, then restart the gateway.
|
||||
|
||||
@@ -32,11 +32,9 @@ See [Provider Notes](#provider-notes) for Custom, AIHubMix, MiniMax, Gemini, Oll
|
||||
|
||||
## WebUI Usage
|
||||
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
|
||||
+32
-1
@@ -1,4 +1,8 @@
|
||||
# Memory in nanobot
|
||||
# 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.
|
||||
|
||||
nanobot's memory is built on a simple belief: memory should feel alive, but it should not feel chaotic.
|
||||
|
||||
@@ -64,6 +68,9 @@ 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
|
||||
@@ -120,6 +127,8 @@ 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.
|
||||
|
||||
@@ -135,6 +144,28 @@ 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`:
|
||||
|
||||
@@ -22,6 +22,9 @@ 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
|
||||
|
||||
@@ -42,6 +45,9 @@ 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
|
||||
```
|
||||
@@ -94,6 +100,7 @@ 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
@@ -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-20250514'
|
||||
# model: 'anthropic/claude-sonnet-4-6'
|
||||
# workspace: PosixPath('/tmp/workspace')
|
||||
# provider_retry_mode: 'standard'
|
||||
# max_tool_result_chars: 16000
|
||||
|
||||
+28
-2
@@ -1,9 +1,9 @@
|
||||
# OpenAI-Compatible API
|
||||
# Nanobot OpenAI-Compatible API: Run a Local Agent Behind /v1/chat/completions
|
||||
|
||||
nanobot can expose a minimal OpenAI-compatible endpoint for local integrations:
|
||||
|
||||
```bash
|
||||
python -m pip install "nanobot-ai[api]"
|
||||
nanobot plugins enable api
|
||||
nanobot agent -m "Hello!"
|
||||
nanobot serve
|
||||
```
|
||||
@@ -12,6 +12,32 @@ 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`)
|
||||
|
||||
+15
-3
@@ -61,9 +61,12 @@ 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
|
||||
@@ -293,6 +296,8 @@ If you have more than one custom OpenAI-compatible endpoint, give each endpoint
|
||||
|
||||
Custom provider keys are treated as direct OpenAI-compatible providers. `apiBase` is required because nanobot cannot know the endpoint URL. `apiKey` is optional for local servers or private proxies that do not require one. Choose a name that does not conflict with a built-in provider name or alias, such as `openai`, `openai-codex`, `github-copilot`, or `lm-studio`. Do not set `apiType` on custom provider keys; `apiType` is only for `providers.openai`.
|
||||
|
||||
If your custom endpoint documents a nonstandard thinking toggle, set `providers.<name>.thinkingStyle` to `thinking_type`, `enable_thinking`, or `reasoning_split`; nanobot then maps `reasoningEffort` onto that provider-specific request body. Leave it unset for ordinary OpenAI-compatible endpoints.
|
||||
|
||||
This named custom provider path is not for Anthropic-compatible endpoints. For Anthropic-compatible proxies, use `providers.anthropic.apiBase` and set the preset provider to `anthropic`.
|
||||
|
||||
### Ollama
|
||||
@@ -413,12 +418,19 @@ 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
|
||||
nanobot provider login github-copilot
|
||||
nanobot provider login openai-codex --set-main
|
||||
```
|
||||
|
||||
Then explicitly select the provider and model in a preset. OAuth providers are not valid automatic fallbacks.
|
||||
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.
|
||||
|
||||
## Provider Resolution
|
||||
|
||||
|
||||
+8
-2
@@ -1,4 +1,4 @@
|
||||
# Python SDK
|
||||
# Nanobot Python SDK: Run an AI Agent from Python
|
||||
|
||||
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,7 +599,8 @@ 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 full `SessionSnapshot` suitable for JSON serialization. |
|
||||
| `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. |
|
||||
| `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. |
|
||||
@@ -608,6 +609,11 @@ 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 |
|
||||
|
||||
+11
-10
@@ -32,7 +32,7 @@ On 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 and you enabled the WebSocket channel, go straight to [Open the WebUI](#5-open-the-webui).
|
||||
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, go straight to [Open the WebUI](#5-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.
|
||||
|
||||
@@ -115,7 +115,7 @@ Initialization creates:
|
||||
| `~/.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 you already have a config, `nanobot onboard` can refresh missing default fields without overwriting your existing values.
|
||||
If you already have a config, `nanobot onboard` can refresh missing default fields without overwriting your existing values. Use `nanobot onboard --refresh` to do the same refresh without an interactive prompt.
|
||||
|
||||
## 3. Configure a Provider
|
||||
|
||||
@@ -235,13 +235,13 @@ Read it like this:
|
||||
|
||||
## 5. Open the WebUI
|
||||
|
||||
If Quick Start enabled the WebSocket channel, start the gateway:
|
||||
Start the browser workbench:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
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.
|
||||
`nanobot webui` prepares the local WebSocket channel and WebUI bootstrap secret if needed, starts the gateway, and opens `http://127.0.0.1:8765`. First-run WebUI setup binds to `127.0.0.1` by default, so it is not exposed to your LAN. Use `nanobot webui --background` when you want the gateway to keep running without an open terminal.
|
||||
|
||||
## 6. Test One CLI Message
|
||||
|
||||
@@ -278,6 +278,8 @@ Then update ~/.nanobot/config.json to add a model preset named "primary" for my
|
||||
Tell me exactly what changed and whether I need to run /restart.
|
||||
```
|
||||
|
||||
In interactive mode, `Enter` sends the current message. Press `Alt+Enter` to add a newline before sending.
|
||||
|
||||
Exit interactive mode with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
|
||||
|
||||
## 7. Choose Your Next Step
|
||||
@@ -288,7 +290,7 @@ Exit interactive mode with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
|
||||
| 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) |
|
||||
| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, 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) |
|
||||
@@ -326,11 +328,10 @@ python -m pip install -e .
|
||||
nanobot --version
|
||||
```
|
||||
|
||||
If you use WhatsApp, rebuild the local bridge after upgrading:
|
||||
If you use WhatsApp from a source checkout, keep the optional dependencies installed:
|
||||
|
||||
```bash
|
||||
rm -rf ~/.nanobot/bridge
|
||||
nanobot channels login whatsapp
|
||||
nanobot plugins enable whatsapp
|
||||
```
|
||||
|
||||
## First-Run Troubleshooting
|
||||
@@ -343,6 +344,6 @@ nanobot channels login whatsapp
|
||||
| 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`. |
|
||||
| WebUI does not open | Run `nanobot webui`; the browser UI uses port `8765`, not the gateway health port `18790`. |
|
||||
|
||||
For a fuller diagnosis flow, see [`troubleshooting.md`](./troubleshooting.md).
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
# 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!
|
||||
@@ -181,11 +181,11 @@ For the first setup, choose `[Q] Quick Start`. It configures the recommended loc
|
||||
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.
|
||||
7. Confirm that Quick Start should configure 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.
|
||||
|
||||
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.
|
||||
The recommended path configures 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.
|
||||
|
||||
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`.
|
||||
|
||||
@@ -225,7 +225,6 @@ Merge them into one object:
|
||||
},
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"tokenIssueSecret": "your-webui-password",
|
||||
"websocketRequiresToken": true
|
||||
}
|
||||
@@ -288,7 +287,6 @@ If this is a brand-new install and you have not configured anything else yet, re
|
||||
},
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"tokenIssueSecret": "your-webui-password",
|
||||
"websocketRequiresToken": true
|
||||
}
|
||||
@@ -317,10 +315,10 @@ It is normal for most providers to say `not set`. Only the provider you selected
|
||||
Start the local browser UI:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
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.
|
||||
This starts nanobot and opens `http://127.0.0.1:8765` in your browser. Leave the terminal open while you use the WebUI. Enter the WebUI password you set in the wizard if the browser asks for one.
|
||||
|
||||
Send this first message in the browser:
|
||||
|
||||
@@ -337,10 +335,10 @@ Hello! How can I help you today?
|
||||
If `nanobot` is not found, run:
|
||||
|
||||
```bash
|
||||
python -m nanobot gateway
|
||||
python -m nanobot webui
|
||||
```
|
||||
|
||||
Use `python3 -m nanobot gateway` or `py -m nanobot gateway` if that is the Python command that worked in step 2.
|
||||
Use `python3 -m nanobot webui` or `py -m nanobot webui` 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.
|
||||
|
||||
@@ -369,21 +367,21 @@ Skip these until the first local message works:
|
||||
|
||||
## 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.
|
||||
After the first reply works, choose only one next goal. Keep the terminal that runs `nanobot webui` open whenever you use the WebUI. Chat apps use the same gateway service underneath.
|
||||
|
||||
### Open the Browser UI Again
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser.
|
||||
Leave that terminal open; the browser should open automatically.
|
||||
|
||||
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).
|
||||
If `nanobot` is not found, run `python -m nanobot webui`, `python3 -m nanobot webui`, or `py -m nanobot webui`, matching the Python command that worked earlier. More details are in [`webui.md`](./webui.md).
|
||||
|
||||
### Connect a Chat App
|
||||
|
||||
|
||||
+11
-5
@@ -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 default config, default workspace, active model or preset, and provider setup summary.
|
||||
`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.
|
||||
|
||||
The output has this shape:
|
||||
|
||||
@@ -90,9 +90,10 @@ Default workspace path:
|
||||
~/.nanobot/workspace/
|
||||
```
|
||||
|
||||
`nanobot status` reads the default config. Use explicit paths on commands that support them when debugging multiple instances:
|
||||
`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:
|
||||
|
||||
```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
|
||||
```
|
||||
@@ -110,10 +111,10 @@ Common config mistakes:
|
||||
To refresh missing defaults without overwriting existing settings, run:
|
||||
|
||||
```bash
|
||||
nanobot onboard
|
||||
nanobot onboard --refresh
|
||||
```
|
||||
|
||||
When prompted about overwriting the config, choose the option that keeps current values and merges missing defaults.
|
||||
For an interactive choice between resetting and refreshing, run `nanobot onboard` and choose the option that keeps current values and merges missing defaults.
|
||||
|
||||
## Provider and Model Problems
|
||||
|
||||
@@ -134,7 +135,12 @@ 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` or `nanobot provider login github-copilot`, then select the provider explicitly. |
|
||||
| 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`. |
|
||||
|
||||
## Langfuse Problems
|
||||
|
||||
|
||||
+9
-9
@@ -16,13 +16,13 @@ Nanobot can act as a WebSocket server, allowing external clients (web apps, CLIs
|
||||
|
||||
### 1. Configure
|
||||
|
||||
Add to `config.json` under `channels.websocket`:
|
||||
The WebSocket channel is enabled by default. Add only the fields you want to
|
||||
override 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 | `false` | Enable the WebSocket server. |
|
||||
| `enabled` | bool | `true` | Enable the WebSocket server. Set to `false` only when you intentionally do not want the bundled WebUI/WebSocket surface. |
|
||||
| `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 tokens (logged as a warning). |
|
||||
| `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`. |
|
||||
| `tokenTtlS` | int | `300` | Time-to-live for issued tokens in seconds (30 – 86,400). |
|
||||
|
||||
### Access Control
|
||||
@@ -266,13 +266,17 @@ 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",
|
||||
@@ -367,7 +371,6 @@ Outbound `message` events may include a `media` field containing local filesyste
|
||||
{
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"host": "0.0.0.0",
|
||||
"port": 8765,
|
||||
"websocketRequiresToken": false,
|
||||
@@ -384,7 +387,6 @@ Outbound `message` events may include a `media` field containing local filesyste
|
||||
{
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"token": "my-shared-secret",
|
||||
"allowFrom": ["alice", "bob"]
|
||||
}
|
||||
@@ -400,7 +402,6 @@ Clients connect with `?token=my-shared-secret&client_id=alice`.
|
||||
{
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"host": "0.0.0.0",
|
||||
"port": 8765,
|
||||
"path": "/ws",
|
||||
@@ -421,7 +422,6 @@ Clients connect with `?token=my-shared-secret&client_id=alice`.
|
||||
{
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"path": "/chat/ws",
|
||||
"allowFrom": ["*"]
|
||||
}
|
||||
|
||||
+120
-38
@@ -1,28 +1,48 @@
|
||||
# WebUI
|
||||
# Nanobot WebUI: Browser Workbench for Self-Hosted AI Agents
|
||||
|
||||
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.
|
||||
<!-- 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 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
|
||||
|
||||
First confirm your provider and model can answer:
|
||||
Use the launcher:
|
||||
|
||||
```bash
|
||||
nanobot agent -m "Hello!"
|
||||
nanobot webui
|
||||
```
|
||||
|
||||
Then merge the WebSocket channel into your existing `~/.nanobot/config.json`.
|
||||
Set `tokenIssueSecret` to the password you will enter in the WebUI login form:
|
||||
`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:
|
||||
|
||||
```json
|
||||
{
|
||||
"channels": {
|
||||
"websocket": {
|
||||
"enabled": true,
|
||||
"host": "127.0.0.1",
|
||||
"tokenIssueSecret": "your-webui-password",
|
||||
"websocketRequiresToken": true
|
||||
}
|
||||
@@ -30,33 +50,21 @@ Set `tokenIssueSecret` to the password you will enter in the WebUI login form:
|
||||
}
|
||||
```
|
||||
|
||||
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).
|
||||
|
||||
Start the gateway:
|
||||
|
||||
```bash
|
||||
nanobot gateway
|
||||
```
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## What It Is For
|
||||
|
||||
| Area | Use it for |
|
||||
|---|---|
|
||||
| Chat | Start, switch, search, fork, and delete browser sessions |
|
||||
| Agent activity | See thinking, tool calls, file activity, command output, and generated artifacts in context |
|
||||
| Agent activity | See thinking, tool calls, file edits with diffs, 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 |
|
||||
| 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 agent turns |
|
||||
| Automations | Review, search, run, pause, edit, and delete scheduled and local-trigger agent turns |
|
||||
| Settings | Adjust models, providers, image generation, voice, web tools, runtime, and safety options |
|
||||
|
||||
## Chat Workspace
|
||||
@@ -69,6 +77,16 @@ 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
|
||||
@@ -80,6 +98,10 @@ 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
|
||||
@@ -93,10 +115,22 @@ for provider setup and output behavior.
|
||||
|
||||
## Apps
|
||||
|
||||
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.
|
||||
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).
|
||||
|
||||
Some MCP presets connect to hosted keyless endpoints. For example, the Firecrawl
|
||||
preset uses Firecrawl's hosted MCP endpoint for search, scrape, crawl, and
|
||||
@@ -104,8 +138,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 MCP preset is available, mention it from the composer with `@`
|
||||
to attach that capability to the next message.
|
||||
After an App or integration is available, mention it from the composer with
|
||||
`@` to attach that tool to the next message.
|
||||
|
||||
## Skills
|
||||
|
||||
@@ -116,25 +150,47 @@ to perform that task.
|
||||
|
||||
## Automations
|
||||
|
||||
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.
|
||||
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"`.
|
||||
|
||||
For recurring background checks that should stay quiet unless there is something
|
||||
useful to report, use the protected heartbeat job by editing `HEARTBEAT.md`
|
||||
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, linked chat, schedule, or status.
|
||||
- Search by task name, message, trigger command, linked chat, schedule, or status.
|
||||
- Sort by next run, last run, updated time, or name.
|
||||
- Run now, pause or resume, edit, or delete user-created automations.
|
||||
- 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.
|
||||
|
||||
Search accepts plain text and field filters such as `name:backup`,
|
||||
`chat:WeChat`, `schedule:09:30`, `cron:"0 23 * * *"`, and `status:paused`.
|
||||
`chat:WeChat`, `schedule:09:30`, `cron:"0 23 * * *"`, `trigger`, 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
|
||||
@@ -146,6 +202,9 @@ 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
|
||||
@@ -155,7 +214,6 @@ 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"
|
||||
@@ -169,12 +227,36 @@ 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. The WebSocket channel is enabled in `~/.nanobot/config.json`.
|
||||
2. `~/.nanobot/config.json` does not explicitly set `channels.websocket.enabled` to `false`.
|
||||
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.
|
||||
|
||||
+32
-30
@@ -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.
|
||||
|
||||
Behaviour:
|
||||
Behavior:
|
||||
|
||||
- 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 @@ Behaviour:
|
||||
- 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.
|
||||
- Skips when `nanobot/web/dist/index.html` already exists, unless
|
||||
- Reuses `nanobot/web/dist/` only when it is already fresh, 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,12 +21,22 @@ Behaviour:
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
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"
|
||||
@@ -58,24 +68,32 @@ 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 index_html.is_file() and not force:
|
||||
if not status.needs_build and not force:
|
||||
self.app.display_info(
|
||||
f"[webui-build] reusing existing build at {dist_dir} "
|
||||
"(set NANOBOT_FORCE_WEBUI_BUILD=1 to rebuild)"
|
||||
"(already fresh; set NANOBOT_FORCE_WEBUI_BUILD=1 to rebuild)"
|
||||
)
|
||||
return
|
||||
|
||||
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."
|
||||
if status.needs_build and not force:
|
||||
self.app.display_info(
|
||||
f"[webui-build] {webui_build.describe_webui_bundle_status(status)}"
|
||||
)
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
if not index_html.is_file():
|
||||
raise RuntimeError(
|
||||
@@ -83,19 +101,3 @@ 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
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
"""Agent core module."""
|
||||
|
||||
from nanobot.agent.context import ContextBuilder
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext, CompositeHook
|
||||
from nanobot.agent.hook import (
|
||||
AgentHook,
|
||||
AgentHookContext,
|
||||
AgentRunHookContext,
|
||||
AgentTurnHookContext,
|
||||
AgentTurnHookFactory,
|
||||
CompositeHook,
|
||||
)
|
||||
from nanobot.agent.loop import AgentLoop
|
||||
from nanobot.agent.memory import MemoryStore
|
||||
from nanobot.agent.skills import SkillsLoader
|
||||
@@ -11,6 +18,8 @@ __all__ = [
|
||||
"AgentHook",
|
||||
"AgentHookContext",
|
||||
"AgentRunHookContext",
|
||||
"AgentTurnHookContext",
|
||||
"AgentTurnHookFactory",
|
||||
"AgentLoop",
|
||||
"CompositeHook",
|
||||
"ContextBuilder",
|
||||
|
||||
@@ -12,6 +12,7 @@ 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:
|
||||
@@ -34,6 +35,26 @@ 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}"
|
||||
@@ -42,8 +63,12 @@ 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],
|
||||
active_session_keys: Collection[str] = ()) -> None:
|
||||
def check_expired(
|
||||
self,
|
||||
schedule_background: Callable[[Coroutine], None],
|
||||
resolve_runtime: Callable[[], LLMRuntime],
|
||||
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():
|
||||
@@ -52,17 +77,21 @@ class AutoCompact:
|
||||
continue
|
||||
if key in active_session_keys:
|
||||
continue
|
||||
if self._is_expired(info.get("updated_at"), now):
|
||||
updated_at = info.get("updated_at")
|
||||
if self._is_expired(updated_at, now) and self._has_compactable_idle_tail(key):
|
||||
runtime = resolve_runtime()
|
||||
self._archiving.add(key)
|
||||
schedule_background(self._archive(key))
|
||||
schedule_background(self._archive(key, runtime=runtime))
|
||||
|
||||
async def _archive(self, key: str) -> None:
|
||||
async def _archive(self, key: str, *, runtime: LLMRuntime) -> None:
|
||||
if self._is_internal_session(key):
|
||||
self._archiving.discard(key)
|
||||
return
|
||||
try:
|
||||
summary = await self.consolidator.compact_idle_session(
|
||||
key, self._RECENT_SUFFIX_MESSAGES,
|
||||
key,
|
||||
runtime=runtime,
|
||||
max_suffix=self._RECENT_SUFFIX_MESSAGES,
|
||||
)
|
||||
if summary and summary != "(nothing)":
|
||||
session = self.sessions.get_or_create(key)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""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,
|
||||
)
|
||||
+29
-64
@@ -12,9 +12,14 @@ 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.session.goal_state import goal_state_runtime_lines
|
||||
from nanobot.runtime_context import (
|
||||
RUNTIME_CONTEXT_END,
|
||||
RUNTIME_CONTEXT_MESSAGE_META,
|
||||
RUNTIME_CONTEXT_TAG,
|
||||
RuntimeContextBlock,
|
||||
append_runtime_context,
|
||||
)
|
||||
from nanobot.utils.helpers import (
|
||||
current_time_str,
|
||||
detect_image_mime,
|
||||
load_bundled_template,
|
||||
truncate_text_to_tokens,
|
||||
@@ -27,23 +32,14 @@ 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)
|
||||
|
||||
@@ -52,10 +48,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 — metadata only, not instructions]"
|
||||
_RUNTIME_CONTEXT_TAG = RUNTIME_CONTEXT_TAG
|
||||
_MAX_RECENT_HISTORY = 50
|
||||
_MAX_HISTORY_TOKENS = 8_000 # hard cap on recent history section size (tokens)
|
||||
_RUNTIME_CONTEXT_END = "[/Runtime Context]"
|
||||
_RUNTIME_CONTEXT_END = RUNTIME_CONTEXT_END
|
||||
|
||||
def __init__(self, workspace: Path, timezone: str | None = None, disabled_skills: list[str] | None = None):
|
||||
self.workspace = workspace
|
||||
@@ -131,28 +127,14 @@ 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):
|
||||
return f"{left}\n\n{right}" if left else right
|
||||
if not left:
|
||||
return right
|
||||
if not right:
|
||||
return left
|
||||
return f"{left}\n\n{right}"
|
||||
|
||||
def _to_blocks(value: Any) -> list[dict[str, Any]]:
|
||||
if isinstance(value, list):
|
||||
@@ -196,41 +178,17 @@ class ContextBuilder:
|
||||
sender_id: str | None = None,
|
||||
session_summary: str | None = None,
|
||||
session_metadata: Mapping[str, Any] | None = None,
|
||||
current_runtime_lines: Sequence[str] | None = None,
|
||||
runtime_context_blocks: Sequence[RuntimeContextBlock] | 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)
|
||||
|
||||
# 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}]
|
||||
blocks = list(runtime_context_blocks or ()) if current_role == "user" else []
|
||||
merged, runtime_context_meta = append_runtime_context(user_content, blocks)
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
@@ -249,9 +207,16 @@ 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
|
||||
messages.append({"role": current_role, "content": merged})
|
||||
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)
|
||||
return messages
|
||||
|
||||
def _build_user_content(self, text: str, media: list[str] | None) -> str | list[dict[str, Any]]:
|
||||
|
||||
@@ -0,0 +1,503 @@
|
||||
"""Model-message governance for agent runner requests.
|
||||
|
||||
This module owns model-facing message shaping and tool-result content normalization.
|
||||
It may return copied messages or persisted-result placeholders, but it must not
|
||||
mutate an existing session history list in place.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.utils.helpers import (
|
||||
estimate_message_tokens,
|
||||
estimate_prompt_tokens_chain,
|
||||
find_legal_message_start,
|
||||
maybe_persist_tool_result,
|
||||
truncate_text,
|
||||
)
|
||||
from nanobot.utils.runtime import ensure_nonempty_tool_result
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.providers.base import LLMProvider
|
||||
|
||||
SNIP_SAFETY_BUFFER = 1024
|
||||
MICROCOMPACT_KEEP_RECENT = 10
|
||||
MICROCOMPACT_MIN_CHARS = 500
|
||||
INFLIGHT_COMPACT_TARGET_RATIO = 0.85
|
||||
COMPACTABLE_TOOLS = frozenset({
|
||||
"read_file", "exec", "grep", "find_files",
|
||||
"web_search", "web_fetch", "list_dir", "list_exec_sessions",
|
||||
})
|
||||
# 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)
|
||||
class ContextGovernanceConfig:
|
||||
provider: LLMProvider
|
||||
model: str
|
||||
tools: Any
|
||||
workspace: Path | None
|
||||
session_key: str | None
|
||||
max_tool_result_chars: int
|
||||
context_window_tokens: int | None = None
|
||||
context_block_limit: int | None = None
|
||||
max_tokens: int | None = None
|
||||
inflight_start_index: int = 0
|
||||
|
||||
|
||||
class ContextGovernor:
|
||||
"""Prepare model-copy messages while preserving persisted history."""
|
||||
|
||||
def prepare_for_model(
|
||||
self,
|
||||
config: ContextGovernanceConfig,
|
||||
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.backfill_missing_tool_results(updated)
|
||||
updated = self.apply_tool_result_budget(config, updated)
|
||||
updated = self.compact_inflight_overflow(config, updated, compacted_tool_call_ids)
|
||||
updated = self.snip_history(config, updated)
|
||||
updated = self.drop_orphan_tool_results(updated)
|
||||
return self.backfill_missing_tool_results(updated)
|
||||
|
||||
@staticmethod
|
||||
def input_budget(config: ContextGovernanceConfig) -> int:
|
||||
if not config.context_window_tokens:
|
||||
return 0
|
||||
|
||||
provider_max_tokens = getattr(
|
||||
getattr(config.provider, "generation", None),
|
||||
"max_tokens",
|
||||
4096,
|
||||
)
|
||||
max_output = config.max_tokens if isinstance(config.max_tokens, int) else (
|
||||
provider_max_tokens if isinstance(provider_max_tokens, int) else 4096
|
||||
)
|
||||
budget = config.context_block_limit or (
|
||||
config.context_window_tokens - max_output - SNIP_SAFETY_BUFFER
|
||||
)
|
||||
return budget if budget > 0 else 0
|
||||
|
||||
@staticmethod
|
||||
def normalize_tool_result(
|
||||
config: ContextGovernanceConfig,
|
||||
tool_call_id: str,
|
||||
tool_name: str,
|
||||
result: Any,
|
||||
) -> Any:
|
||||
result = ensure_nonempty_tool_result(tool_name, result)
|
||||
if tool_name in TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS:
|
||||
return result
|
||||
try:
|
||||
content = maybe_persist_tool_result(
|
||||
config.workspace,
|
||||
config.session_key,
|
||||
tool_call_id,
|
||||
result,
|
||||
max_chars=config.max_tool_result_chars,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Tool result persist failed for {} in {}; using raw result",
|
||||
tool_call_id,
|
||||
config.session_key or "default",
|
||||
)
|
||||
content = result
|
||||
if isinstance(content, str) and len(content) > config.max_tool_result_chars:
|
||||
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]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Drop tool results that have no matching assistant tool_call earlier in history."""
|
||||
declared: set[str] = set()
|
||||
updated: list[dict[str, Any]] | None = None
|
||||
for idx, msg in enumerate(messages):
|
||||
role = msg.get("role")
|
||||
if role == "assistant":
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if isinstance(tc, dict) and tc.get("id"):
|
||||
declared.add(str(tc["id"]))
|
||||
if role == "tool":
|
||||
tid = msg.get("tool_call_id")
|
||||
if tid and str(tid) not in declared:
|
||||
if updated is None:
|
||||
updated = [dict(m) for m in messages[:idx]]
|
||||
continue
|
||||
if updated is not None:
|
||||
updated.append(dict(msg))
|
||||
|
||||
if updated is None:
|
||||
return messages
|
||||
return updated
|
||||
|
||||
@staticmethod
|
||||
def backfill_missing_tool_results(
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Insert synthetic error results for assistant tool_calls with missing tool outputs."""
|
||||
declared: list[tuple[int, str, str]] = []
|
||||
fulfilled: set[str] = set()
|
||||
for idx, msg in enumerate(messages):
|
||||
role = msg.get("role")
|
||||
if role == "assistant":
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if isinstance(tc, dict) and tc.get("id"):
|
||||
name = ""
|
||||
func = tc.get("function")
|
||||
if isinstance(func, dict):
|
||||
name = func.get("name", "")
|
||||
declared.append((idx, str(tc["id"]), name))
|
||||
elif role == "tool":
|
||||
tid = msg.get("tool_call_id")
|
||||
if tid:
|
||||
fulfilled.add(str(tid))
|
||||
|
||||
missing = [(ai, cid, name) for ai, cid, name in declared if cid not in fulfilled]
|
||||
if not missing:
|
||||
return messages
|
||||
|
||||
updated = list(messages)
|
||||
offset = 0
|
||||
for assistant_idx, call_id, name in missing:
|
||||
insert_at = assistant_idx + 1 + offset
|
||||
while insert_at < len(updated) and updated[insert_at].get("role") == "tool":
|
||||
insert_at += 1
|
||||
updated.insert(insert_at, {
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"name": name,
|
||||
"content": BACKFILL_CONTENT,
|
||||
})
|
||||
offset += 1
|
||||
return updated
|
||||
|
||||
def apply_tool_result_budget(
|
||||
self,
|
||||
config: ContextGovernanceConfig,
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
updated = messages
|
||||
for idx, message in enumerate(messages):
|
||||
if message.get("role") != "tool":
|
||||
continue
|
||||
normalized = self.normalize_tool_result(
|
||||
config,
|
||||
str(message.get("tool_call_id") or f"tool_{idx}"),
|
||||
str(message.get("name") or "tool"),
|
||||
message.get("content"),
|
||||
)
|
||||
if normalized != message.get("content"):
|
||||
if updated is messages:
|
||||
updated = [dict(m) for m in messages]
|
||||
updated[idx]["content"] = normalized
|
||||
return updated
|
||||
|
||||
def compact_inflight_overflow(
|
||||
self,
|
||||
config: ContextGovernanceConfig,
|
||||
messages: list[dict[str, Any]],
|
||||
compacted_tool_call_ids: set[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Compact in-flight tool results only when the request would overflow."""
|
||||
budget = self.input_budget(config)
|
||||
if budget <= 0:
|
||||
return messages
|
||||
|
||||
tools = config.tools.get_definitions()
|
||||
updated = self._apply_recorded_compactions(messages, compacted_tool_call_ids)
|
||||
estimate, source = estimate_prompt_tokens_chain(
|
||||
config.provider,
|
||||
config.model,
|
||||
updated,
|
||||
tools,
|
||||
)
|
||||
if estimate <= budget:
|
||||
return updated
|
||||
|
||||
target = int(budget * INFLIGHT_COMPACT_TARGET_RATIO)
|
||||
candidates = self._inflight_compaction_candidates(
|
||||
config,
|
||||
updated,
|
||||
compacted_tool_call_ids,
|
||||
)
|
||||
if not candidates:
|
||||
return updated
|
||||
|
||||
for candidate_idx, (idx, tool_call_id) in enumerate(candidates):
|
||||
is_newest_candidate = candidate_idx == len(candidates) - 1
|
||||
if is_newest_candidate and estimate <= budget:
|
||||
break
|
||||
if tool_call_id in compacted_tool_call_ids:
|
||||
continue
|
||||
if updated is messages:
|
||||
updated = [dict(m) for m in messages]
|
||||
compacted_tool_call_ids.add(tool_call_id)
|
||||
self._compact_tool_result_at(updated, idx)
|
||||
estimate, source = estimate_prompt_tokens_chain(
|
||||
config.provider,
|
||||
config.model,
|
||||
updated,
|
||||
tools,
|
||||
)
|
||||
if estimate <= target:
|
||||
break
|
||||
|
||||
logger.debug(
|
||||
"In-flight context compaction for {}: prompt={} budget={} target={} via {}, ids={}",
|
||||
config.session_key or "default",
|
||||
estimate,
|
||||
budget,
|
||||
target,
|
||||
source,
|
||||
len(compacted_tool_call_ids),
|
||||
)
|
||||
return updated
|
||||
|
||||
def snip_history(
|
||||
self,
|
||||
config: ContextGovernanceConfig,
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
if not messages or not config.context_window_tokens:
|
||||
return messages
|
||||
|
||||
budget = self.input_budget(config)
|
||||
if budget <= 0:
|
||||
return messages
|
||||
|
||||
tools = config.tools.get_definitions()
|
||||
estimate, _ = estimate_prompt_tokens_chain(
|
||||
config.provider,
|
||||
config.model,
|
||||
messages,
|
||||
tools,
|
||||
)
|
||||
if estimate <= budget:
|
||||
return messages
|
||||
|
||||
system_messages = [dict(msg) for msg in messages if msg.get("role") == "system"]
|
||||
non_system = [dict(msg) for msg in messages if msg.get("role") != "system"]
|
||||
if not non_system:
|
||||
return messages
|
||||
|
||||
system_tokens = sum(estimate_message_tokens(msg) for msg in system_messages)
|
||||
fixed_tokens, _ = estimate_prompt_tokens_chain(
|
||||
config.provider,
|
||||
config.model,
|
||||
system_messages,
|
||||
tools,
|
||||
)
|
||||
remaining_budget = max(0, budget - max(system_tokens, fixed_tokens))
|
||||
kept: list[dict[str, Any]] = []
|
||||
kept_tokens = 0
|
||||
for message in reversed(non_system):
|
||||
msg_tokens = estimate_message_tokens(message)
|
||||
if kept and kept_tokens + msg_tokens > remaining_budget:
|
||||
break
|
||||
kept.append(message)
|
||||
kept_tokens += msg_tokens
|
||||
kept.reverse()
|
||||
|
||||
return system_messages + self._legal_history_tail(kept, non_system)
|
||||
|
||||
@staticmethod
|
||||
def _summary_for(message: dict[str, Any]) -> str:
|
||||
name = message.get("name", "tool")
|
||||
return f"[Prior {name} result compacted to fit context; the tool call already completed.]"
|
||||
|
||||
def _legal_history_tail(
|
||||
self,
|
||||
kept: list[dict[str, Any]],
|
||||
non_system: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
fallback = kept if kept else (non_system[-1:] if non_system else [])
|
||||
kept = self._user_tail(kept) or self._user_tail(non_system, last=True) or fallback
|
||||
|
||||
start = find_legal_message_start(kept)
|
||||
return kept[start:] if start else kept
|
||||
|
||||
@staticmethod
|
||||
def _user_tail(messages: list[dict[str, Any]], *, last: bool = False) -> list[dict[str, Any]]:
|
||||
indexes = range(len(messages) - 1, -1, -1) if last else range(len(messages))
|
||||
for idx in indexes:
|
||||
if messages[idx].get("role") == "user":
|
||||
return messages[idx:]
|
||||
return []
|
||||
|
||||
def _apply_recorded_compactions(
|
||||
self,
|
||||
messages: list[dict[str, Any]],
|
||||
compacted_tool_call_ids: set[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
if not compacted_tool_call_ids:
|
||||
return messages
|
||||
updated = messages
|
||||
for idx, msg in enumerate(messages):
|
||||
if msg.get("role") != "tool":
|
||||
continue
|
||||
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
|
||||
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"] = summary
|
||||
return updated
|
||||
|
||||
def _inflight_compaction_candidates(
|
||||
self,
|
||||
config: ContextGovernanceConfig,
|
||||
messages: list[dict[str, Any]],
|
||||
compacted_tool_call_ids: set[str],
|
||||
) -> list[tuple[int, str]]:
|
||||
compactable: list[tuple[int, str]] = []
|
||||
for idx, msg in enumerate(messages):
|
||||
if idx < config.inflight_start_index:
|
||||
continue
|
||||
if msg.get("role") != "tool" or msg.get("name") not in COMPACTABLE_TOOLS:
|
||||
continue
|
||||
tool_call_id = msg.get("tool_call_id")
|
||||
if not tool_call_id or str(tool_call_id) in compacted_tool_call_ids:
|
||||
continue
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, str) or len(content) < MICROCOMPACT_MIN_CHARS:
|
||||
continue
|
||||
compactable.append((idx, str(tool_call_id)))
|
||||
|
||||
if not compactable:
|
||||
return []
|
||||
primary_count = max(0, len(compactable) - MICROCOMPACT_KEEP_RECENT)
|
||||
primary = compactable[:primary_count]
|
||||
# Hard overflow beats the keep-recent preference. Return recent results
|
||||
# after stale ones so the newest result is naturally last.
|
||||
fallback = compactable[primary_count:]
|
||||
return primary + fallback
|
||||
|
||||
def _compact_tool_result_at(self, messages: list[dict[str, Any]], idx: int) -> None:
|
||||
messages[idx]["content"] = self._summary_for(messages[idx])
|
||||
+22
-107
@@ -2,11 +2,10 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import dataclasses
|
||||
from collections.abc import Awaitable, Callable, Iterable
|
||||
|
||||
from nanobot.bus.events import InboundMessage, OutboundMessage
|
||||
from nanobot.agent.automation_turns import AutomationTurnCoordinator
|
||||
from nanobot.bus.events import InboundMessage
|
||||
from nanobot.cron.session_turns import (
|
||||
cron_run_id,
|
||||
cron_trigger,
|
||||
@@ -14,7 +13,7 @@ from nanobot.cron.session_turns import (
|
||||
)
|
||||
|
||||
|
||||
class CronTurnCoordinator:
|
||||
class CronTurnCoordinator(AutomationTurnCoordinator):
|
||||
"""Manage scheduled cron turns without mixing them into live injections."""
|
||||
|
||||
def __init__(
|
||||
@@ -23,115 +22,31 @@ class CronTurnCoordinator:
|
||||
publish_inbound: Callable[[InboundMessage], Awaitable[None]],
|
||||
dispatch: Callable[[InboundMessage], Awaitable[object]],
|
||||
is_running: Callable[[], bool],
|
||||
deferred_queues: dict[str, list[InboundMessage]] | None = None,
|
||||
) -> None:
|
||||
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
|
||||
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,
|
||||
)
|
||||
|
||||
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*."""
|
||||
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
|
||||
return self.pending_ids_for_session(session_key)
|
||||
|
||||
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 _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
|
||||
|
||||
|
||||
def _cron_job_id(msg: InboundMessage) -> str | None:
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"""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)
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
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
|
||||
@@ -44,6 +46,20 @@ 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."""
|
||||
|
||||
@@ -77,6 +93,35 @@ 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
|
||||
|
||||
@@ -95,6 +140,9 @@ class AgentHook:
|
||||
return content
|
||||
|
||||
|
||||
AgentTurnHookFactory = Callable[[AgentTurnHookContext], AgentHook | None]
|
||||
|
||||
|
||||
class CompositeHook(AgentHook):
|
||||
"""Fan-out hook that delegates to an ordered list of hooks.
|
||||
|
||||
@@ -147,6 +195,49 @@ 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)
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
"""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",
|
||||
]
|
||||
@@ -0,0 +1,135 @@
|
||||
"""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,
|
||||
)
|
||||
+410
-259
File diff suppressed because it is too large
Load Diff
+174
-70
@@ -15,7 +15,8 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.session.manager import Session
|
||||
from nanobot.runtime_context import public_history_messages
|
||||
from nanobot.session.manager import Session, SessionManager
|
||||
from nanobot.utils.gitstore import GitStore
|
||||
from nanobot.utils.helpers import (
|
||||
ensure_dir,
|
||||
@@ -30,9 +31,7 @@ from nanobot.utils.helpers import (
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.providers.base import LLMProvider
|
||||
from nanobot.session.manager import SessionManager
|
||||
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MemoryStore — pure file I/O layer
|
||||
@@ -42,6 +41,14 @@ 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*")
|
||||
@@ -64,6 +71,7 @@ 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",
|
||||
@@ -479,13 +487,57 @@ class MemoryStore:
|
||||
def set_last_dream_cursor(self, cursor: int) -> None:
|
||||
self._dream_cursor_file.write_text(str(cursor), encoding="utf-8")
|
||||
|
||||
def get_latest_cursor(self) -> int:
|
||||
return max(self._next_cursor() - 1, 0)
|
||||
|
||||
@property
|
||||
def dream_prompt_file(self) -> Path:
|
||||
return self.workspace / "prompts" / "dream.md"
|
||||
|
||||
def has_dream_prompt_override(self) -> bool:
|
||||
with suppress(OSError):
|
||||
return self.dream_prompt_file.is_file() and bool(
|
||||
self.dream_prompt_file.read_text(encoding="utf-8").strip()
|
||||
)
|
||||
return False
|
||||
|
||||
@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:
|
||||
with suppress(OSError):
|
||||
text = self.dream_prompt_file.read_text(encoding="utf-8")
|
||||
if text.strip():
|
||||
text = text.rstrip()
|
||||
if len(text) > _DREAM_PROMPT_MAX_CHARS:
|
||||
if not self._dream_prompt_oversize_logged:
|
||||
self._dream_prompt_oversize_logged = True
|
||||
logger.warning(
|
||||
"workspace Dream prompt exceeds {} chars ({}); truncating. "
|
||||
"Further occurrences suppressed.",
|
||||
_DREAM_PROMPT_MAX_CHARS, len(text),
|
||||
)
|
||||
return truncate_text(text, _DREAM_PROMPT_MAX_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.
|
||||
"""
|
||||
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
|
||||
|
||||
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.
|
||||
"""
|
||||
last_cursor = self.get_last_dream_cursor()
|
||||
entries = self.read_unprocessed_history(since_cursor=last_cursor)
|
||||
if not entries:
|
||||
@@ -496,13 +548,47 @@ class MemoryStore:
|
||||
f"[{e['timestamp']}] {truncate_text(e['content'], 500)}"
|
||||
for e in batch
|
||||
)
|
||||
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,
|
||||
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}"
|
||||
)
|
||||
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
|
||||
@@ -574,7 +660,10 @@ 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(messages), limit)
|
||||
formatted = truncate_text(
|
||||
self._format_messages(public_history_messages(messages)),
|
||||
limit,
|
||||
)
|
||||
self.append_history(
|
||||
f"[RAW] {len(messages)} messages\n"
|
||||
f"{formatted}",
|
||||
@@ -594,23 +683,36 @@ class MemoryStore:
|
||||
return f"dream:{datetime.now():%Y%m%d-%H%M%S}"
|
||||
|
||||
@staticmethod
|
||||
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
|
||||
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}"
|
||||
|
||||
@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 files matching ``dream_*.jsonl`` are considered. Non-dream session
|
||||
files are never touched.
|
||||
Only current base64url-encoded Dream session keys are considered.
|
||||
Non-dream session files are never touched.
|
||||
"""
|
||||
dream_files = sorted(
|
||||
sessions_dir.glob("dream_*.jsonl"), key=lambda p: p.stat().st_mtime,
|
||||
)
|
||||
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)
|
||||
if len(dream_files) <= keep:
|
||||
return
|
||||
|
||||
@@ -632,6 +734,7 @@ class MemoryStore:
|
||||
# that catches any new caller that forgot to set its own cap.
|
||||
_RAW_ARCHIVE_MAX_CHARS = 16_000 # fallback dump (LLM failed)
|
||||
_ARCHIVE_SUMMARY_MAX_CHARS = 8_000 # LLM-produced consolidation summary
|
||||
_DREAM_PROMPT_MAX_CHARS = 32_000 # workspace-local Dream prompt override
|
||||
_HISTORY_ENTRY_HARD_CAP = 64_000 # emergency cap in append_history
|
||||
|
||||
|
||||
@@ -645,22 +748,14 @@ 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
|
||||
@@ -669,17 +764,6 @@ 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())
|
||||
@@ -709,17 +793,12 @@ class Consolidator:
|
||||
@staticmethod
|
||||
def _full_unconsolidated_history(
|
||||
session: Session,
|
||||
*,
|
||||
include_timestamps: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Return the whole unconsolidated tail for consolidation decisions."""
|
||||
unconsolidated_count = len(session.messages) - session.last_consolidated
|
||||
if unconsolidated_count <= 0:
|
||||
return []
|
||||
return session.get_history(
|
||||
max_messages=unconsolidated_count,
|
||||
include_timestamps=include_timestamps,
|
||||
)
|
||||
return session.get_history(max_messages=unconsolidated_count)
|
||||
|
||||
@staticmethod
|
||||
def _replay_overflow_boundary(
|
||||
@@ -762,6 +841,8 @@ 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)
|
||||
@@ -776,7 +857,11 @@ class Consolidator:
|
||||
len(chunk),
|
||||
replay_max_messages,
|
||||
)
|
||||
summary = await self.archive(chunk, session_key=session.key)
|
||||
summary = await self.archive(
|
||||
chunk,
|
||||
runtime=runtime,
|
||||
session_key=session.key,
|
||||
)
|
||||
session.last_consolidated = end_idx
|
||||
self.sessions.save(session)
|
||||
return summary
|
||||
@@ -792,9 +877,11 @@ 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, include_timestamps=True)
|
||||
history = self._full_unconsolidated_history(session)
|
||||
channel, chat_id = (session.key.split(":", 1) if ":" in session.key else (None, None))
|
||||
# Include archived summary in estimation so the budget accounts for it.
|
||||
meta = session.metadata.get("_last_summary")
|
||||
@@ -811,20 +898,23 @@ class Consolidator:
|
||||
unified_session=self.unified_session,
|
||||
)
|
||||
return estimate_prompt_tokens_chain(
|
||||
self.provider,
|
||||
self.model,
|
||||
runtime.provider,
|
||||
runtime.model,
|
||||
probe_messages,
|
||||
self._get_tool_definitions(),
|
||||
)
|
||||
|
||||
@property
|
||||
def _input_token_budget(self) -> int:
|
||||
def _input_token_budget(self, runtime: LLMRuntime) -> int:
|
||||
"""Available input token budget for consolidation LLM."""
|
||||
return self.context_window_tokens - self.max_completion_tokens - self._SAFETY_BUFFER
|
||||
return (
|
||||
runtime.context_window_tokens
|
||||
- runtime.generation.max_tokens
|
||||
- self._SAFETY_BUFFER
|
||||
)
|
||||
|
||||
def _truncate_to_token_budget(self, text: str) -> str:
|
||||
def _truncate_to_token_budget(self, text: str, *, runtime: LLMRuntime) -> str:
|
||||
"""Truncate text so it fits within the consolidation LLM's token budget."""
|
||||
budget = self._input_token_budget
|
||||
budget = self._input_token_budget(runtime)
|
||||
if budget <= 0:
|
||||
return truncate_text(text, _RAW_ARCHIVE_MAX_CHARS)
|
||||
return truncate_text_to_tokens(text, budget)
|
||||
@@ -833,6 +923,7 @@ class Consolidator:
|
||||
self,
|
||||
messages: list[dict],
|
||||
*,
|
||||
runtime: LLMRuntime,
|
||||
session_key: str | None = None,
|
||||
summary_messages: list[dict] | None = None,
|
||||
) -> str | None:
|
||||
@@ -847,12 +938,14 @@ class Consolidator:
|
||||
"""
|
||||
if not messages:
|
||||
return None
|
||||
messages_to_summarize = summary_messages if summary_messages is not None else messages
|
||||
messages_to_summarize = public_history_messages(
|
||||
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)
|
||||
response = await self.provider.chat_with_retry(
|
||||
model=self.model,
|
||||
formatted = self._truncate_to_token_budget(formatted, runtime=runtime)
|
||||
response = await runtime.provider.chat_with_retry(
|
||||
model=runtime.model,
|
||||
messages=[
|
||||
{
|
||||
"role": "system",
|
||||
@@ -865,6 +958,9 @@ 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}")
|
||||
@@ -884,6 +980,7 @@ class Consolidator:
|
||||
self,
|
||||
session: Session,
|
||||
*,
|
||||
runtime: LLMRuntime,
|
||||
replay_max_messages: int | None = None,
|
||||
) -> None:
|
||||
"""Loop: archive old messages until prompt fits within safe budget.
|
||||
@@ -891,7 +988,7 @@ class Consolidator:
|
||||
The budget reserves space for completion tokens and a safety buffer
|
||||
so the LLM request never exceeds the context window.
|
||||
"""
|
||||
if self.context_window_tokens <= 0:
|
||||
if runtime.context_window_tokens <= 0:
|
||||
return
|
||||
|
||||
lock = self.get_lock(session.key)
|
||||
@@ -903,15 +1000,17 @@ class Consolidator:
|
||||
if not session.messages:
|
||||
return
|
||||
|
||||
budget = self._input_token_budget
|
||||
budget = self._input_token_budget(runtime)
|
||||
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)
|
||||
@@ -925,7 +1024,7 @@ class Consolidator:
|
||||
"Token consolidation idle {}: {}/{} via {}, msgs={}",
|
||||
session.key,
|
||||
estimated,
|
||||
self.context_window_tokens,
|
||||
runtime.context_window_tokens,
|
||||
source,
|
||||
unconsolidated_count,
|
||||
)
|
||||
@@ -956,11 +1055,15 @@ class Consolidator:
|
||||
round_num,
|
||||
session.key,
|
||||
estimated,
|
||||
self.context_window_tokens,
|
||||
runtime.context_window_tokens,
|
||||
source,
|
||||
len(chunk),
|
||||
)
|
||||
summary = await self.archive(chunk, session_key=session.key)
|
||||
summary = await self.archive(
|
||||
chunk,
|
||||
runtime=runtime,
|
||||
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
|
||||
@@ -977,6 +1080,7 @@ class Consolidator:
|
||||
try:
|
||||
estimated, source = self.estimate_session_prompt_tokens(
|
||||
session,
|
||||
runtime=runtime,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception("Token estimation failed for {}", session.key)
|
||||
@@ -992,6 +1096,8 @@ 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.
|
||||
@@ -1008,7 +1114,6 @@ 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 ""
|
||||
|
||||
@@ -1020,12 +1125,11 @@ class Consolidator:
|
||||
metadata={},
|
||||
last_consolidated=0,
|
||||
)
|
||||
dropped, already_consolidated = probe.retain_recent_legal_suffix(max_suffix, extend_to_user=True)
|
||||
result = probe.retain_recent_legal_suffix(max_suffix, extend_to_user=True)
|
||||
messages_to_keep = probe.messages
|
||||
messages_to_remove = dropped[already_consolidated:]
|
||||
messages_to_remove = result.dropped[result.already_consolidated_count:]
|
||||
|
||||
if not messages_to_remove and not messages_to_keep:
|
||||
session.updated_at = datetime.now()
|
||||
self.sessions.save(session)
|
||||
return ""
|
||||
|
||||
@@ -1036,6 +1140,7 @@ 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,
|
||||
)
|
||||
@@ -1048,7 +1153,6 @@ class Consolidator:
|
||||
|
||||
session.messages = messages_to_keep
|
||||
session.last_consolidated = 0
|
||||
session.updated_at = datetime.now()
|
||||
self.sessions.save(session)
|
||||
|
||||
if messages_to_remove:
|
||||
|
||||
@@ -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(),
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
"""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))
|
||||
@@ -28,26 +28,16 @@ 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()
|
||||
@@ -124,15 +114,6 @@ 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 (
|
||||
|
||||
+179
-368
@@ -13,35 +13,24 @@ from typing import Any, Callable
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.context_governance import (
|
||||
ContextGovernanceConfig,
|
||||
ContextGovernor,
|
||||
)
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result
|
||||
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
|
||||
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.session.history_visibility import is_hidden_history_message
|
||||
from nanobot.utils.helpers import (
|
||||
IncrementalThinkExtractor,
|
||||
build_assistant_message,
|
||||
estimate_message_tokens,
|
||||
estimate_prompt_tokens_chain,
|
||||
extract_reasoning,
|
||||
find_legal_message_start,
|
||||
maybe_persist_tool_result,
|
||||
strip_reasoning_tags,
|
||||
strip_think,
|
||||
truncate_text,
|
||||
)
|
||||
from nanobot.utils.progress_events import (
|
||||
invoke_file_edit_progress,
|
||||
on_progress_accepts_file_edit_events,
|
||||
)
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
from nanobot.utils.prompt_templates import render_template
|
||||
from nanobot.utils.runtime import (
|
||||
EMPTY_FINAL_RESPONSE_MESSAGE,
|
||||
@@ -49,7 +38,6 @@ from nanobot.utils.runtime import (
|
||||
build_finalization_retry_message,
|
||||
build_goal_continue_message,
|
||||
build_length_recovery_message,
|
||||
ensure_nonempty_tool_result,
|
||||
is_blank_text,
|
||||
repeated_external_lookup_error,
|
||||
repeated_workspace_violation_error,
|
||||
@@ -67,21 +55,6 @@ _MAX_EMPTY_RETRIES = 2
|
||||
_MAX_LENGTH_RECOVERIES = 3
|
||||
_MAX_INJECTIONS_PER_TURN = 3
|
||||
_MAX_INJECTION_CYCLES = 5
|
||||
_SNIP_SAFETY_BUFFER = 1024
|
||||
_MICROCOMPACT_KEEP_RECENT = 10
|
||||
_MICROCOMPACT_MIN_CHARS = 500
|
||||
_COMPACTABLE_TOOLS = frozenset({
|
||||
"read_file", "exec", "grep", "find_files",
|
||||
"web_search", "web_fetch", "list_dir", "list_exec_sessions",
|
||||
})
|
||||
# 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]"
|
||||
|
||||
# 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:
|
||||
@@ -89,12 +62,9 @@ class AgentRunSpec:
|
||||
|
||||
initial_messages: list[dict[str, Any]]
|
||||
tools: ToolRegistry
|
||||
model: str
|
||||
runtime: LLMRuntime
|
||||
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
|
||||
@@ -102,7 +72,6 @@ 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
|
||||
@@ -133,8 +102,8 @@ class AgentRunResult:
|
||||
class AgentRunner:
|
||||
"""Run a tool-capable LLM loop without product-layer concerns."""
|
||||
|
||||
def __init__(self, provider: LLMProvider):
|
||||
self.provider = provider
|
||||
def __init__(self) -> None:
|
||||
self.context_governor = ContextGovernor()
|
||||
|
||||
@staticmethod
|
||||
def _merge_message_content(left: Any, right: Any) -> str | list[dict[str, Any]]:
|
||||
@@ -165,6 +134,8 @@ 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(
|
||||
@@ -214,7 +185,7 @@ class AgentRunner:
|
||||
{
|
||||
"phase": "final_response",
|
||||
"iteration": iteration,
|
||||
"model": spec.model,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": assistant_message,
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
@@ -367,6 +338,19 @@ class AgentRunner:
|
||||
length_recovery_count = 0
|
||||
had_injections = False
|
||||
injection_cycles = 0
|
||||
compacted_tool_call_ids: set[str] = set()
|
||||
governance_config = ContextGovernanceConfig(
|
||||
provider=spec.runtime.provider,
|
||||
model=spec.runtime.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_block_limit=spec.context_block_limit,
|
||||
max_tokens=spec.runtime.generation.max_tokens,
|
||||
inflight_start_index=len(spec.initial_messages),
|
||||
)
|
||||
|
||||
for iteration in range(spec.max_iterations):
|
||||
try:
|
||||
@@ -374,14 +358,11 @@ class AgentRunner:
|
||||
# may repair or compact historical messages for the model, but
|
||||
# those synthetic edits must not shift the append boundary used
|
||||
# later when the caller saves only the new turn.
|
||||
messages_for_model = self._drop_orphan_tool_results(messages)
|
||||
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
|
||||
messages_for_model = self._microcompact(messages_for_model)
|
||||
messages_for_model = self._apply_tool_result_budget(spec, messages_for_model)
|
||||
messages_for_model = self._snip_history(spec, messages_for_model)
|
||||
# Snipping may have created new orphans; clean them up.
|
||||
messages_for_model = self._drop_orphan_tool_results(messages_for_model)
|
||||
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
|
||||
messages_for_model = self.context_governor.prepare_for_model(
|
||||
governance_config,
|
||||
messages,
|
||||
compacted_tool_call_ids,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Context governance failed on turn {} for {}; applying minimal repair",
|
||||
@@ -389,8 +370,18 @@ class AgentRunner:
|
||||
spec.session_key or "default",
|
||||
)
|
||||
try:
|
||||
messages_for_model = self._drop_orphan_tool_results(messages)
|
||||
messages_for_model = self._backfill_missing_tool_results(messages_for_model)
|
||||
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.backfill_missing_tool_results(
|
||||
messages_for_model
|
||||
)
|
||||
except Exception:
|
||||
messages_for_model = messages
|
||||
context = AgentHookContext(
|
||||
@@ -434,7 +425,7 @@ class AgentRunner:
|
||||
{
|
||||
"phase": "awaiting_tools",
|
||||
"iteration": iteration,
|
||||
"model": spec.model,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": assistant_message,
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [tc.to_openai_tool_call() for tc in response.tool_calls],
|
||||
@@ -448,6 +439,8 @@ class AgentRunner:
|
||||
response.tool_calls,
|
||||
external_lookup_counts,
|
||||
workspace_violation_counts,
|
||||
hook,
|
||||
context,
|
||||
)
|
||||
tool_events.extend(new_events)
|
||||
tools_used.extend(
|
||||
@@ -463,8 +456,8 @@ class AgentRunner:
|
||||
"role": "tool",
|
||||
"tool_call_id": tool_call.id,
|
||||
"name": tool_call.name,
|
||||
"content": self._normalize_tool_result(
|
||||
spec,
|
||||
"content": self.context_governor.normalize_tool_result(
|
||||
governance_config,
|
||||
tool_call.id,
|
||||
tool_call.name,
|
||||
result,
|
||||
@@ -494,7 +487,7 @@ class AgentRunner:
|
||||
{
|
||||
"phase": "tools_completed",
|
||||
"iteration": iteration,
|
||||
"model": spec.model,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": assistant_message,
|
||||
"completed_tool_results": completed_tool_results,
|
||||
"pending_tool_calls": [],
|
||||
@@ -648,7 +641,7 @@ class AgentRunner:
|
||||
{
|
||||
"phase": "final_response",
|
||||
"iteration": iteration,
|
||||
"model": spec.model,
|
||||
"model": spec.runtime.model,
|
||||
"assistant_message": messages[-1],
|
||||
"completed_tool_results": [],
|
||||
"pending_tool_calls": [],
|
||||
@@ -705,16 +698,14 @@ class AgentRunner:
|
||||
kwargs: dict[str, Any] = {
|
||||
"messages": messages,
|
||||
"tools": tools,
|
||||
"model": spec.model,
|
||||
"model": spec.runtime.model,
|
||||
"retry_mode": spec.provider_retry_mode,
|
||||
"on_retry_wait": spec.retry_wait_callback,
|
||||
}
|
||||
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
|
||||
generation = spec.runtime.generation
|
||||
kwargs["temperature"] = generation.temperature
|
||||
kwargs["max_tokens"] = generation.max_tokens
|
||||
kwargs["reasoning_effort"] = generation.reasoning_effort
|
||||
return kwargs
|
||||
|
||||
async def _request_model(
|
||||
@@ -723,6 +714,8 @@ 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:
|
||||
@@ -747,28 +740,10 @@ class AgentRunner:
|
||||
not wants_streaming
|
||||
and spec.stream_progress_deltas
|
||||
and spec.progress_callback is not None
|
||||
and getattr(self.provider, "supports_progress_deltas", False) is True
|
||||
and getattr(spec.runtime.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 = ""
|
||||
@@ -793,11 +768,10 @@ class AgentRunner:
|
||||
async def _stream_recover() -> None:
|
||||
await hook.on_stream_end(context, resuming=True)
|
||||
|
||||
coro = self.provider.chat_stream_with_retry(
|
||||
coro = spec.runtime.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:
|
||||
@@ -825,13 +799,12 @@ class AgentRunner:
|
||||
context.streamed_content = True
|
||||
await spec.progress_callback(incremental)
|
||||
|
||||
coro = self.provider.chat_stream_with_retry(
|
||||
coro = spec.runtime.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 = self.provider.chat_with_retry(**kwargs)
|
||||
coro = spec.runtime.provider.chat_with_retry(**kwargs)
|
||||
|
||||
# Streaming requests already have provider-level idle timeouts
|
||||
# (NANOBOT_STREAM_IDLE_TIMEOUT_S). Do not also apply the outer wall-clock
|
||||
@@ -843,14 +816,6 @@ class AgentRunner:
|
||||
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:
|
||||
return LLMResponse(
|
||||
@@ -865,8 +830,94 @@ class AgentRunner:
|
||||
)
|
||||
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,
|
||||
@@ -928,7 +979,7 @@ class AgentRunner:
|
||||
messages: list[dict[str, Any]],
|
||||
) -> LLMResponse:
|
||||
kwargs = self._build_request_kwargs(spec, messages, tools=None)
|
||||
return await self.provider.chat_with_retry(**kwargs)
|
||||
return await spec.runtime.provider.chat_with_retry(**kwargs)
|
||||
|
||||
@staticmethod
|
||||
def _budget_exhausted_finalization_messages(
|
||||
@@ -976,7 +1027,12 @@ class AgentRunner:
|
||||
tools = spec.tools.get_definitions()
|
||||
except Exception:
|
||||
tools = None
|
||||
prompt_tokens, _ = estimate_prompt_tokens_chain(self.provider, spec.model, messages, tools)
|
||||
prompt_tokens, _ = estimate_prompt_tokens_chain(
|
||||
spec.runtime.provider,
|
||||
spec.runtime.model,
|
||||
messages,
|
||||
tools,
|
||||
)
|
||||
assistant_message = build_assistant_message(
|
||||
response.content or "",
|
||||
tool_calls=[tc.to_openai_tool_call() for tc in response.tool_calls],
|
||||
@@ -1030,14 +1086,23 @@ 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,
|
||||
spec,
|
||||
tool_call,
|
||||
external_lookup_counts,
|
||||
workspace_violation_counts,
|
||||
hook,
|
||||
context,
|
||||
)
|
||||
for tool_call in batch
|
||||
))
|
||||
@@ -1046,7 +1111,12 @@ class AgentRunner:
|
||||
batch_results = []
|
||||
for tool_call in batch:
|
||||
result = await self._run_tool(
|
||||
spec, tool_call, external_lookup_counts, workspace_violation_counts,
|
||||
spec,
|
||||
tool_call,
|
||||
external_lookup_counts,
|
||||
workspace_violation_counts,
|
||||
hook,
|
||||
context,
|
||||
)
|
||||
tool_results.append(result)
|
||||
batch_results.append(result)
|
||||
@@ -1067,7 +1137,11 @@ 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,
|
||||
@@ -1108,30 +1182,7 @@ class AgentRunner:
|
||||
return prep_error + hint, event, (
|
||||
RuntimeError(prep_error) if spec.fail_on_tool_error else None
|
||||
)
|
||||
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],
|
||||
)
|
||||
await hook.before_execute_tool(context, tool_call, tool, params)
|
||||
try:
|
||||
if tool is not None:
|
||||
result = await tool.execute(**params)
|
||||
@@ -1140,14 +1191,7 @@ class AgentRunner:
|
||||
except asyncio.CancelledError:
|
||||
raise
|
||||
except BaseException as 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
|
||||
],
|
||||
)
|
||||
await hook.on_execute_tool_error(context, tool_call, tool, params, exc)
|
||||
event = {
|
||||
"name": tool_call.name,
|
||||
"status": "error",
|
||||
@@ -1168,15 +1212,8 @@ class AgentRunner:
|
||||
return payload, event, exc
|
||||
return payload, event, None
|
||||
|
||||
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
|
||||
],
|
||||
)
|
||||
if is_tool_error_result(tool_call.name, result):
|
||||
await hook.on_execute_tool_error(context, tool_call, tool, params, result)
|
||||
event = {
|
||||
"name": tool_call.name,
|
||||
"status": "error",
|
||||
@@ -1195,14 +1232,7 @@ class AgentRunner:
|
||||
return result + hint, event, RuntimeError(result)
|
||||
return result + hint, event, None
|
||||
|
||||
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],
|
||||
)
|
||||
await hook.after_execute_tool(context, tool_call, tool, params, result)
|
||||
|
||||
detail = "" if result is None else str(result)
|
||||
detail = detail.replace("\n", " ").strip()
|
||||
@@ -1334,225 +1364,6 @@ class AgentRunner:
|
||||
return
|
||||
messages.append(build_assistant_message(_PERSISTED_MODEL_ERROR_PLACEHOLDER))
|
||||
|
||||
def _normalize_tool_result(
|
||||
self,
|
||||
spec: AgentRunSpec,
|
||||
tool_call_id: str,
|
||||
tool_name: str,
|
||||
result: Any,
|
||||
) -> Any:
|
||||
result = ensure_nonempty_tool_result(tool_name, result)
|
||||
if tool_name in _TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS:
|
||||
# Exempt tools bound their own output; skip generic offload and truncation.
|
||||
return result
|
||||
try:
|
||||
content = maybe_persist_tool_result(
|
||||
spec.workspace,
|
||||
spec.session_key,
|
||||
tool_call_id,
|
||||
result,
|
||||
max_chars=spec.max_tool_result_chars,
|
||||
)
|
||||
except Exception:
|
||||
logger.exception(
|
||||
"Tool result persist failed for {} in {}; using raw result",
|
||||
tool_call_id,
|
||||
spec.session_key or "default",
|
||||
)
|
||||
content = result
|
||||
if isinstance(content, str) and len(content) > spec.max_tool_result_chars:
|
||||
return truncate_text(content, spec.max_tool_result_chars)
|
||||
return content
|
||||
|
||||
@staticmethod
|
||||
def _drop_orphan_tool_results(
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Drop tool results that have no matching assistant tool_call earlier in the history."""
|
||||
declared: set[str] = set()
|
||||
updated: list[dict[str, Any]] | None = None
|
||||
for idx, msg in enumerate(messages):
|
||||
role = msg.get("role")
|
||||
if role == "assistant":
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if isinstance(tc, dict) and tc.get("id"):
|
||||
declared.add(str(tc["id"]))
|
||||
if role == "tool":
|
||||
tid = msg.get("tool_call_id")
|
||||
if tid and str(tid) not in declared:
|
||||
if updated is None:
|
||||
updated = [dict(m) for m in messages[:idx]]
|
||||
continue
|
||||
if updated is not None:
|
||||
updated.append(dict(msg))
|
||||
|
||||
if updated is None:
|
||||
return messages
|
||||
return updated
|
||||
|
||||
@staticmethod
|
||||
def _backfill_missing_tool_results(
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Insert synthetic error results for orphaned tool_use blocks."""
|
||||
declared: list[tuple[int, str, str]] = [] # (assistant_idx, call_id, name)
|
||||
fulfilled: set[str] = set()
|
||||
for idx, msg in enumerate(messages):
|
||||
role = msg.get("role")
|
||||
if role == "assistant":
|
||||
for tc in msg.get("tool_calls") or []:
|
||||
if isinstance(tc, dict) and tc.get("id"):
|
||||
name = ""
|
||||
func = tc.get("function")
|
||||
if isinstance(func, dict):
|
||||
name = func.get("name", "")
|
||||
declared.append((idx, str(tc["id"]), name))
|
||||
elif role == "tool":
|
||||
tid = msg.get("tool_call_id")
|
||||
if tid:
|
||||
fulfilled.add(str(tid))
|
||||
|
||||
missing = [(ai, cid, name) for ai, cid, name in declared if cid not in fulfilled]
|
||||
if not missing:
|
||||
return messages
|
||||
|
||||
updated = list(messages)
|
||||
offset = 0
|
||||
for assistant_idx, call_id, name in missing:
|
||||
insert_at = assistant_idx + 1 + offset
|
||||
while insert_at < len(updated) and updated[insert_at].get("role") == "tool":
|
||||
insert_at += 1
|
||||
updated.insert(insert_at, {
|
||||
"role": "tool",
|
||||
"tool_call_id": call_id,
|
||||
"name": name,
|
||||
"content": _BACKFILL_CONTENT,
|
||||
})
|
||||
offset += 1
|
||||
return updated
|
||||
|
||||
@staticmethod
|
||||
def _microcompact(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Replace old compactable tool results with one-line summaries."""
|
||||
compactable_indices: list[int] = []
|
||||
for idx, msg in enumerate(messages):
|
||||
if msg.get("role") == "tool" and msg.get("name") in _COMPACTABLE_TOOLS:
|
||||
compactable_indices.append(idx)
|
||||
|
||||
if len(compactable_indices) <= _MICROCOMPACT_KEEP_RECENT:
|
||||
return messages
|
||||
|
||||
stale = compactable_indices[: len(compactable_indices) - _MICROCOMPACT_KEEP_RECENT]
|
||||
updated: list[dict[str, Any]] | None = None
|
||||
for idx in stale:
|
||||
msg = messages[idx]
|
||||
content = msg.get("content")
|
||||
if not isinstance(content, str) or len(content) < _MICROCOMPACT_MIN_CHARS:
|
||||
continue
|
||||
name = msg.get("name", "tool")
|
||||
summary = f"[{name} result omitted from context]"
|
||||
if updated is None:
|
||||
updated = [dict(m) for m in messages]
|
||||
updated[idx]["content"] = summary
|
||||
|
||||
return updated if updated is not None else messages
|
||||
|
||||
def _apply_tool_result_budget(
|
||||
self,
|
||||
spec: AgentRunSpec,
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
updated = messages
|
||||
for idx, message in enumerate(messages):
|
||||
if message.get("role") != "tool":
|
||||
continue
|
||||
normalized = self._normalize_tool_result(
|
||||
spec,
|
||||
str(message.get("tool_call_id") or f"tool_{idx}"),
|
||||
str(message.get("name") or "tool"),
|
||||
message.get("content"),
|
||||
)
|
||||
if normalized != message.get("content"):
|
||||
if updated is messages:
|
||||
updated = [dict(m) for m in messages]
|
||||
updated[idx]["content"] = normalized
|
||||
return updated
|
||||
|
||||
def _snip_history(
|
||||
self,
|
||||
spec: AgentRunSpec,
|
||||
messages: list[dict[str, Any]],
|
||||
) -> list[dict[str, Any]]:
|
||||
if not messages or not spec.context_window_tokens:
|
||||
return messages
|
||||
|
||||
provider_max_tokens = getattr(getattr(self.provider, "generation", None), "max_tokens", 4096)
|
||||
max_output = spec.max_tokens if isinstance(spec.max_tokens, int) else (
|
||||
provider_max_tokens if isinstance(provider_max_tokens, int) else 4096
|
||||
)
|
||||
budget = spec.context_block_limit or (
|
||||
spec.context_window_tokens - max_output - _SNIP_SAFETY_BUFFER
|
||||
)
|
||||
if budget <= 0:
|
||||
return messages
|
||||
|
||||
estimate, _ = estimate_prompt_tokens_chain(
|
||||
self.provider,
|
||||
spec.model,
|
||||
messages,
|
||||
spec.tools.get_definitions(),
|
||||
)
|
||||
if estimate <= budget:
|
||||
return messages
|
||||
|
||||
system_messages = [dict(msg) for msg in messages if msg.get("role") == "system"]
|
||||
non_system = [dict(msg) for msg in messages if msg.get("role") != "system"]
|
||||
if not non_system:
|
||||
return messages
|
||||
|
||||
system_tokens = sum(estimate_message_tokens(msg) for msg in system_messages)
|
||||
fixed_tokens, _ = estimate_prompt_tokens_chain(
|
||||
self.provider,
|
||||
spec.model,
|
||||
system_messages,
|
||||
spec.tools.get_definitions(),
|
||||
)
|
||||
remaining_budget = max(0, budget - max(system_tokens, fixed_tokens))
|
||||
kept: list[dict[str, Any]] = []
|
||||
kept_tokens = 0
|
||||
for message in reversed(non_system):
|
||||
msg_tokens = estimate_message_tokens(message)
|
||||
if kept and kept_tokens + msg_tokens > remaining_budget:
|
||||
break
|
||||
kept.append(message)
|
||||
kept_tokens += msg_tokens
|
||||
kept.reverse()
|
||||
|
||||
if kept:
|
||||
for i, message in enumerate(kept):
|
||||
if message.get("role") == "user":
|
||||
kept = kept[i:]
|
||||
break
|
||||
else:
|
||||
# Recover nearest user message from outside the kept window;
|
||||
# GLM rejects system→assistant (error 1214). Budget is
|
||||
# intentionally exceeded — oversized beats invalid.
|
||||
for idx in range(len(non_system) - 1, -1, -1):
|
||||
if non_system[idx].get("role") == "user":
|
||||
kept = non_system[idx:]
|
||||
break
|
||||
# If no user exists at all, _enforce_role_alternation
|
||||
# will insert a synthetic one as a safety net.
|
||||
start = find_legal_message_start(kept)
|
||||
if start:
|
||||
kept = kept[start:]
|
||||
if not kept:
|
||||
kept = non_system[-min(len(non_system), 4) :]
|
||||
start = find_legal_message_start(kept)
|
||||
if start:
|
||||
kept = kept[start:]
|
||||
return system_messages + kept
|
||||
|
||||
def _partition_tool_batches(
|
||||
self,
|
||||
spec: AgentRunSpec,
|
||||
|
||||
+96
-21
@@ -4,6 +4,7 @@ import asyncio
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
import warnings
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
@@ -12,7 +13,12 @@ from loguru import logger
|
||||
|
||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||
from nanobot.agent.runner import AgentRunner, AgentRunSpec
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.context import (
|
||||
RequestContext,
|
||||
ToolContext,
|
||||
bind_request_context,
|
||||
reset_request_context,
|
||||
)
|
||||
from nanobot.agent.tools.file_state import FileStates
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
@@ -26,6 +32,7 @@ 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
|
||||
|
||||
|
||||
@@ -76,23 +83,46 @@ class SubagentManager:
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
provider: LLMProvider,
|
||||
workspace: Path,
|
||||
bus: MessageBus,
|
||||
max_tool_result_chars: int,
|
||||
provider: LLMProvider | None = None,
|
||||
workspace: Path | None = None,
|
||||
bus: MessageBus | None = None,
|
||||
max_tool_result_chars: int | None = None,
|
||||
model: str | None = None,
|
||||
tools_config: ToolsConfig | None = None,
|
||||
restrict_to_workspace: bool = False,
|
||||
disabled_skills: list[str] | None = None,
|
||||
max_iterations: int | None = None,
|
||||
max_concurrent_subagents: int | None = None,
|
||||
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.provider = provider
|
||||
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.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
|
||||
@@ -107,12 +137,52 @@ class SubagentManager:
|
||||
if max_concurrent_subagents is not None
|
||||
else defaults.max_concurrent_subagents
|
||||
)
|
||||
self.runner = AgentRunner(provider)
|
||||
self.fail_on_tool_error = (
|
||||
fail_on_tool_error
|
||||
if fail_on_tool_error is not None
|
||||
else defaults.fail_on_tool_error
|
||||
)
|
||||
self.runner = AgentRunner()
|
||||
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(
|
||||
@@ -143,11 +213,6 @@ 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,
|
||||
@@ -158,8 +223,14 @@ 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}
|
||||
@@ -179,8 +250,8 @@ class SubagentManager:
|
||||
display_label,
|
||||
origin,
|
||||
status,
|
||||
runtime,
|
||||
origin_message_id,
|
||||
temperature,
|
||||
workspace_scope,
|
||||
)
|
||||
)
|
||||
@@ -208,8 +279,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."""
|
||||
@@ -238,20 +309,26 @@ 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,
|
||||
model=self.model,
|
||||
temperature=temperature,
|
||||
runtime=runtime,
|
||||
max_iterations=self.max_iterations,
|
||||
max_tool_result_chars=self.max_tool_result_chars,
|
||||
hook=_SubagentHook(task_id, status),
|
||||
max_iterations_message="Task completed but no final response was generated.",
|
||||
finalize_on_max_iterations=False,
|
||||
error_message=None,
|
||||
fail_on_tool_error=True,
|
||||
fail_on_tool_error=self.fail_on_tool_error,
|
||||
checkpoint_callback=_on_checkpoint,
|
||||
session_key=sess_key,
|
||||
workspace=root,
|
||||
@@ -260,6 +337,7 @@ 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
|
||||
|
||||
@@ -355,10 +433,8 @@ 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,
|
||||
@@ -366,7 +442,6 @@ 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,6 +1,6 @@
|
||||
"""Agent tools module."""
|
||||
|
||||
from nanobot.agent.tools.base import Schema, Tool, tool_parameters
|
||||
from nanobot.agent.tools.base import Schema, Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import ToolContext
|
||||
from nanobot.agent.tools.loader import ToolLoader
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
@@ -25,6 +25,7 @@ __all__ = [
|
||||
"Tool",
|
||||
"ToolContext",
|
||||
"ToolLoader",
|
||||
"ToolResult",
|
||||
"ToolRegistry",
|
||||
"tool_parameters",
|
||||
"tool_parameters_schema",
|
||||
|
||||
@@ -7,7 +7,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.base import tool_parameters
|
||||
from nanobot.agent.tools.base import ToolResult, 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 f"Error: {exc}"
|
||||
return ToolResult.error(f"Error: {exc}")
|
||||
except _PatchError as exc:
|
||||
return f"Error applying patch: {exc}"
|
||||
return ToolResult.error(f"Error applying patch: {exc}")
|
||||
except Exception as exc:
|
||||
return f"Error applying patch: {exc}"
|
||||
return ToolResult.error(f"Error applying patch: {exc}")
|
||||
|
||||
@@ -11,6 +11,7 @@ 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")
|
||||
|
||||
@@ -128,6 +129,21 @@ 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."""
|
||||
|
||||
@@ -191,11 +207,19 @@ 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; returns a string or list of content blocks."""
|
||||
"""Run the tool; return content, or ``ToolResult.error(...)`` for failures."""
|
||||
...
|
||||
|
||||
@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
|
||||
|
||||
@@ -7,7 +7,8 @@ from typing import Any
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import RequestContext
|
||||
from nanobot.agent.tools.schema import (
|
||||
ArraySchema,
|
||||
BooleanSchema,
|
||||
@@ -16,7 +17,9 @@ 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
|
||||
|
||||
|
||||
@@ -112,6 +115,23 @@ 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,
|
||||
@@ -136,4 +156,4 @@ class CliAppsTool(Tool):
|
||||
restrict_to_workspace=access.restrict_to_workspace,
|
||||
)
|
||||
except CliAppError as exc:
|
||||
return f"Error: {exc.message}"
|
||||
return ToolResult.error(f"Error: {exc.message}")
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
"""Runtime context for tool construction."""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import contextmanager
|
||||
from contextvars import ContextVar, Token
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Callable, Protocol, runtime_checkable
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, Any, Callable, Protocol, runtime_checkable
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from nanobot.utils.llm_runtime import LLMRuntime
|
||||
|
||||
_CURRENT_REQUEST_CONTEXT: ContextVar["RequestContext | None"] = ContextVar(
|
||||
"nanobot_tool_request_context",
|
||||
@@ -18,7 +23,12 @@ 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
|
||||
@@ -35,6 +45,16 @@ 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()
|
||||
|
||||
|
||||
+22
-29
@@ -6,8 +6,8 @@ from contextvars import ContextVar
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
from nanobot.agent.tools.schema import (
|
||||
IntegerSchema,
|
||||
StringSchema,
|
||||
@@ -51,19 +51,12 @@ _CRON_PARAMETERS = tool_parameters_schema(
|
||||
|
||||
|
||||
@tool_parameters(_CRON_PARAMETERS)
|
||||
class CronTool(Tool, ContextAware):
|
||||
class CronTool(Tool):
|
||||
"""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
|
||||
@@ -74,15 +67,17 @@ class CronTool(Tool, ContextAware):
|
||||
def create(cls, ctx: Any) -> Tool:
|
||||
return cls(cron_service=ctx.cron_service, default_timezone=ctx.timezone)
|
||||
|
||||
def set_context(self, ctx: RequestContext) -> None:
|
||||
"""Set the current session context for scheduled cron job ownership."""
|
||||
@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 "", "", "", {}
|
||||
raw_key = f"{ctx.channel}:{ctx.chat_id}" if ctx.channel and ctx.chat_id else ""
|
||||
self._session_key.set(
|
||||
session_key = (
|
||||
raw_key if ctx.session_key == UNIFIED_SESSION_KEY else (ctx.session_key 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 {}))
|
||||
return session_key, ctx.channel or "", ctx.chat_id or "", dict(ctx.metadata or {})
|
||||
|
||||
def set_cron_context(self, active: bool):
|
||||
"""Mark whether the tool is executing inside a cron job callback."""
|
||||
@@ -99,7 +94,7 @@ class CronTool(Tool, ContextAware):
|
||||
try:
|
||||
ZoneInfo(tz)
|
||||
except (KeyError, Exception):
|
||||
return f"Error: unknown timezone '{tz}'"
|
||||
return ToolResult.error(f"Error: unknown timezone '{tz}'")
|
||||
return None
|
||||
|
||||
def _display_timezone(self, schedule: CronSchedule) -> str:
|
||||
@@ -148,7 +143,7 @@ class CronTool(Tool, ContextAware):
|
||||
) -> str:
|
||||
if action == "add":
|
||||
if self._in_cron_context.get():
|
||||
return "Error: cannot schedule new jobs from within a cron job execution"
|
||||
return ToolResult.error("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()
|
||||
@@ -166,20 +161,18 @@ class CronTool(Tool, ContextAware):
|
||||
at: str | None,
|
||||
) -> str:
|
||||
if not message:
|
||||
return (
|
||||
return ToolResult.error(
|
||||
"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 = self._session_key.get()
|
||||
session_key, origin_channel, origin_chat_id, origin_metadata = self._request_route()
|
||||
if not session_key:
|
||||
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()
|
||||
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
|
||||
if not origin_channel or not origin_chat_id:
|
||||
return "Error: scheduled cron jobs must be created from a chat session"
|
||||
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
|
||||
if tz and not cron_expr:
|
||||
return "Error: tz can only be used with cron_expr"
|
||||
return ToolResult.error("Error: tz can only be used with cron_expr")
|
||||
if tz:
|
||||
if err := self._validate_timezone(tz):
|
||||
return err
|
||||
@@ -199,7 +192,7 @@ class CronTool(Tool, ContextAware):
|
||||
try:
|
||||
dt = datetime.fromisoformat(at)
|
||||
except ValueError:
|
||||
return f"Error: invalid ISO datetime format '{at}'. Expected format: YYYY-MM-DDTHH:MM:SS"
|
||||
return ToolResult.error(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
|
||||
@@ -208,7 +201,7 @@ class CronTool(Tool, ContextAware):
|
||||
schedule = CronSchedule(kind="at", at_ms=at_ms)
|
||||
delete_after = True
|
||||
else:
|
||||
return "Error: either every_seconds, cron_expr, or at is required"
|
||||
return ToolResult.error("Error: either every_seconds, cron_expr, or at is required")
|
||||
|
||||
job = self._cron.add_job(
|
||||
name=name or message[:30],
|
||||
@@ -218,7 +211,7 @@ class CronTool(Tool, ContextAware):
|
||||
session_key=session_key,
|
||||
origin_channel=origin_channel,
|
||||
origin_chat_id=origin_chat_id,
|
||||
origin_metadata=dict(self._origin_metadata.get() or {}),
|
||||
origin_metadata=origin_metadata,
|
||||
)
|
||||
return f"Created job '{job.name}' (id: {job.id})"
|
||||
|
||||
@@ -279,7 +272,7 @@ class CronTool(Tool, ContextAware):
|
||||
|
||||
def _remove_job(self, job_id: str | None) -> str:
|
||||
if not job_id:
|
||||
return "Error: job_id is required for remove"
|
||||
return ToolResult.error("Error: job_id is required for remove")
|
||||
result = self._cron.remove_job(job_id)
|
||||
if result == "removed":
|
||||
return f"Removed job {job_id}"
|
||||
|
||||
@@ -9,7 +9,7 @@ from contextlib import suppress
|
||||
from dataclasses import dataclass
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import current_request_session_key
|
||||
from nanobot.agent.tools.schema import (
|
||||
BooleanSchema,
|
||||
@@ -128,7 +128,15 @@ class _ExecSession:
|
||||
) -> _SessionPoll:
|
||||
self.last_access = time.monotonic()
|
||||
if yield_time_ms > 0 and self.process.returncode is None:
|
||||
await asyncio.sleep(min(yield_time_ms, MAX_YIELD_MS) / 1000)
|
||||
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)
|
||||
|
||||
if self.process.returncode is None and time.monotonic() >= self.deadline:
|
||||
self._timed_out = True
|
||||
@@ -140,6 +148,9 @@ 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()
|
||||
|
||||
@@ -163,8 +174,14 @@ class _ExecSession:
|
||||
if self.process.returncode is not None:
|
||||
return
|
||||
self.process.kill()
|
||||
with suppress(asyncio.TimeoutError):
|
||||
await asyncio.wait_for(self.process.wait(), timeout=5.0)
|
||||
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)
|
||||
|
||||
async def _wait_for_buffered_output(self) -> None:
|
||||
deadline = time.monotonic() + OUTPUT_DRAIN_GRACE_S
|
||||
@@ -492,11 +509,12 @@ class WriteStdinTool(Tool):
|
||||
max_output_chars=output_limit,
|
||||
owner_session_key=current_request_session_key(),
|
||||
)
|
||||
return format_session_poll(session_id, poll)
|
||||
result = format_session_poll(session_id, poll)
|
||||
return ToolResult.error(result) if poll.timed_out else result
|
||||
except KeyError:
|
||||
return f"Error: exec session not found: {session_id}"
|
||||
return ToolResult.error(f"Error: exec session not found: {session_id!r}")
|
||||
except Exception as exc:
|
||||
return f"Error writing to exec session: {exc}"
|
||||
return ToolResult.error(f"Error writing to exec session: {exc}")
|
||||
|
||||
async def _wait_for_output(
|
||||
self,
|
||||
@@ -532,13 +550,14 @@ class WriteStdinTool(Tool):
|
||||
joined = "".join(aggregate)
|
||||
if wait_for in joined:
|
||||
poll.output = joined
|
||||
return format_session_poll(session_id, poll)
|
||||
result = format_session_poll(session_id, poll)
|
||||
return ToolResult.error(result) if poll.timed_out else result
|
||||
if poll.done or remaining_ms <= 0:
|
||||
poll.output = "".join(aggregate)
|
||||
result = format_session_poll(session_id, poll)
|
||||
if wait_for not in poll.output:
|
||||
result += f"\nWait target not observed: {wait_for!r}"
|
||||
return result
|
||||
return ToolResult.error(result) if poll.timed_out else result
|
||||
|
||||
|
||||
@tool_parameters(tool_parameters_schema())
|
||||
@@ -606,4 +625,4 @@ class ListExecSessionsTool(Tool):
|
||||
)
|
||||
return "\n".join(lines)
|
||||
except Exception as exc:
|
||||
return f"Error listing exec sessions: {exc}"
|
||||
return ToolResult.error(f"Error listing exec sessions: {exc}")
|
||||
|
||||
+121
-114
@@ -7,7 +7,7 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, 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,15 +194,21 @@ def _is_blocked_device(path: str | Path) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
@tool_parameters(
|
||||
@@ -268,19 +274,21 @@ class ReadFileTool(_FsTool):
|
||||
) -> Any:
|
||||
try:
|
||||
if not path:
|
||||
return "Error reading file: Unknown path"
|
||||
return ToolResult.error("Error reading file: Unknown path")
|
||||
|
||||
# Device path blacklist
|
||||
if _is_blocked_device(path):
|
||||
return f"Error: Reading {path} is blocked (device path that could hang or produce infinite output)."
|
||||
return ToolResult.error(f"Error: Reading {path} is blocked (device path that could hang or produce infinite output).")
|
||||
|
||||
fp = self._resolve_read(path)
|
||||
if _is_blocked_device(fp):
|
||||
return f"Error: Reading {fp} is blocked (device path that could hang or produce infinite output)."
|
||||
if not fp.exists():
|
||||
return f"Error: File not found: {path}"
|
||||
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).")
|
||||
if not fp.exists():
|
||||
return ToolResult.error(f"Error: File not found: {path}")
|
||||
if not fp.is_file():
|
||||
return f"Error: Not a file: {path}"
|
||||
return ToolResult.error(f"Error: Not a file: {path}")
|
||||
|
||||
# PDF support
|
||||
if fp.suffix.lower() == ".pdf":
|
||||
@@ -343,7 +351,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 f"Error: Cannot read binary file {path} (MIME: {mime or 'unknown'}). Only UTF-8 text and images are supported."
|
||||
return ToolResult.error(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
|
||||
@@ -357,7 +365,7 @@ class ReadFileTool(_FsTool):
|
||||
if offset < 1:
|
||||
offset = 1
|
||||
if offset > total:
|
||||
return f"Error: offset {offset} is beyond end of file ({total} lines)"
|
||||
return ToolResult.error(f"Error: offset {offset} is beyond end of file ({total} lines)")
|
||||
|
||||
start = offset - 1
|
||||
end = min(start + (limit or self._DEFAULT_LIMIT), total)
|
||||
@@ -381,54 +389,38 @@ class ReadFileTool(_FsTool):
|
||||
self._file_states.record_read(fp, offset=offset, limit=limit)
|
||||
return result
|
||||
except PermissionError as e:
|
||||
return f"Error: {e}"
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
return f"Error reading file: {e}"
|
||||
return ToolResult.error(f"Error reading file: {e}")
|
||||
|
||||
def _read_pdf(self, fp: Path, pages: str | None) -> str:
|
||||
try:
|
||||
import fitz # pymupdf
|
||||
except ImportError:
|
||||
return "Error: PDF reading requires pymupdf. Install with: pip install pymupdf"
|
||||
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError, extract_pdf_pages
|
||||
|
||||
try:
|
||||
doc = fitz.open(str(fp))
|
||||
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}")
|
||||
except Exception as e:
|
||||
return f"Error reading PDF: {e}"
|
||||
return ToolResult.error(f"Error reading PDF: {e}")
|
||||
|
||||
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:
|
||||
if not extraction.text:
|
||||
return f"(PDF has no extractable text: {fp})"
|
||||
|
||||
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)"
|
||||
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.)"
|
||||
)
|
||||
return result
|
||||
|
||||
def _read_office_doc(self, fp: Path) -> str:
|
||||
@@ -437,10 +429,10 @@ class ReadFileTool(_FsTool):
|
||||
result = extract_text(fp)
|
||||
|
||||
if result is None:
|
||||
return f"Error: Unsupported file format: {fp.suffix}"
|
||||
return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}")
|
||||
|
||||
if result.startswith("[error:"):
|
||||
return f"Error reading {fp.suffix.upper()} file: {result}"
|
||||
return ToolResult.error(f"Error reading {fp.suffix.upper()} file: {result}")
|
||||
|
||||
if not result:
|
||||
return f"({fp.suffix.upper().lstrip('.')} has no extractable text: {fp})"
|
||||
@@ -492,9 +484,9 @@ class WriteFileTool(_FsTool):
|
||||
self._file_states.record_write(fp)
|
||||
return f"Successfully wrote {len(content)} characters to {fp}"
|
||||
except PermissionError as e:
|
||||
return f"Error: {e}"
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
return f"Error writing file: {e}"
|
||||
return ToolResult.error(f"Error writing file: {e}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -602,6 +594,15 @@ 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
|
||||
@@ -775,7 +776,10 @@ def _find_match(content: str, old_text: str) -> tuple[str | None, int]:
|
||||
),
|
||||
line_hint=IntegerSchema(
|
||||
1,
|
||||
description="Optional 1-based line hint used to choose the nearest match.",
|
||||
description=(
|
||||
"Optional exact 1-based target line copied from read_file. "
|
||||
"The selected old_text match must cover this line."
|
||||
),
|
||||
minimum=1,
|
||||
nullable=True,
|
||||
),
|
||||
@@ -807,8 +811,9 @@ 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. Shows closest-match "
|
||||
"diagnostics on failure."
|
||||
"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."
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
@@ -830,11 +835,11 @@ class EditFileTool(_FsTool):
|
||||
if new_text is None:
|
||||
raise ValueError("Unknown new_text")
|
||||
if occurrence is not None and occurrence < 1:
|
||||
return "Error: occurrence must be >= 1."
|
||||
return ToolResult.error("Error: occurrence must be >= 1.")
|
||||
if line_hint is not None and line_hint < 1:
|
||||
return "Error: line_hint must be >= 1."
|
||||
return ToolResult.error("Error: line_hint must be >= 1.")
|
||||
if expected_replacements is not None and expected_replacements < 1:
|
||||
return "Error: expected_replacements must be >= 1."
|
||||
return ToolResult.error("Error: expected_replacements must be >= 1.")
|
||||
|
||||
fp = self._resolve_write(path)
|
||||
|
||||
@@ -853,14 +858,14 @@ class EditFileTool(_FsTool):
|
||||
except OSError:
|
||||
fsize = 0
|
||||
if fsize > self._MAX_EDIT_FILE_SIZE:
|
||||
return f"Error: File too large to edit ({fsize / (1024**3):.1f} GiB). Maximum is 1 GiB."
|
||||
return ToolResult.error(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 f"Error: Cannot create file — {path} already exists and is not empty."
|
||||
return ToolResult.error(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}"
|
||||
@@ -878,41 +883,26 @@ class EditFileTool(_FsTool):
|
||||
return self._not_found_msg(old_text, content, path)
|
||||
count = len(matches)
|
||||
if replace_all and occurrence is not None:
|
||||
return "Error: occurrence cannot be used with replace_all=true."
|
||||
return ToolResult.error("Error: occurrence cannot be used with replace_all=true.")
|
||||
if replace_all and line_hint is not None:
|
||||
return "Error: line_hint cannot be used with replace_all=true."
|
||||
return ToolResult.error("Error: line_hint cannot be used with replace_all=true.")
|
||||
if occurrence is not None and line_hint is not None:
|
||||
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 (
|
||||
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."
|
||||
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 (
|
||||
f"Warning: old_text appears {count} times{location_hint}. "
|
||||
"Provide more context, set occurrence to choose one match, "
|
||||
"or set replace_all=true."
|
||||
)
|
||||
|
||||
norm_new = new_text.replace("\r\n", "\n")
|
||||
@@ -923,12 +913,29 @@ class EditFileTool(_FsTool):
|
||||
|
||||
if replace_all:
|
||||
selected = matches
|
||||
elif occurrence is not None:
|
||||
selected = [matches[occurrence - 1]]
|
||||
elif line_hint is not None:
|
||||
selected = [min(matches, key=lambda match: abs(match.line - line_hint))]
|
||||
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
|
||||
else:
|
||||
selected = [matches[occurrence - 1 if occurrence else 0]]
|
||||
selected = [matches[0]]
|
||||
if expected_replacements is not None and len(selected) != expected_replacements:
|
||||
return (
|
||||
return ToolResult.error(
|
||||
f"Error: expected {expected_replacements} replacements but "
|
||||
f"would make {len(selected)}."
|
||||
)
|
||||
@@ -954,9 +961,9 @@ class EditFileTool(_FsTool):
|
||||
msg = f"{warning}\n{msg}"
|
||||
return msg
|
||||
except PermissionError as e:
|
||||
return f"Error: {e}"
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
return f"Error editing file: {e}"
|
||||
return ToolResult.error(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."""
|
||||
@@ -969,7 +976,7 @@ class EditFileTool(_FsTool):
|
||||
parts = [f"Error: File not found: {path}"]
|
||||
if suggestions:
|
||||
parts.append("Did you mean: " + ", ".join(suggestions) + "?")
|
||||
return "\n".join(parts)
|
||||
return ToolResult.error("\n".join(parts))
|
||||
|
||||
@staticmethod
|
||||
def _not_found_msg(old_text: str, content: str, path: str) -> str:
|
||||
@@ -985,18 +992,18 @@ class EditFileTool(_FsTool):
|
||||
hint_text = ""
|
||||
if hints:
|
||||
hint_text = "\nPossible cause: " + ", ".join(hints) + "."
|
||||
return (
|
||||
return ToolResult.error(
|
||||
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 (
|
||||
return ToolResult.error(
|
||||
f"Error: old_text not found in {path}. "
|
||||
f"Possible cause: {', '.join(hints)}. "
|
||||
"Copy the exact text from read_file and try again."
|
||||
)
|
||||
return f"Error: old_text not found in {path}. No similar text found. Verify the file content."
|
||||
return ToolResult.error(f"Error: old_text not found in {path}. No similar text found. Verify the file content.")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1051,9 +1058,9 @@ class ListDirTool(_FsTool):
|
||||
raise ValueError("Unknown path")
|
||||
dp = self._resolve(path)
|
||||
if not dp.exists():
|
||||
return f"Error: Directory not found: {path}"
|
||||
return ToolResult.error(f"Error: Directory not found: {path}")
|
||||
if not dp.is_dir():
|
||||
return f"Error: Not a directory: {path}"
|
||||
return ToolResult.error(f"Error: Not a directory: {path}")
|
||||
|
||||
cap = max_entries or self._DEFAULT_MAX
|
||||
items: list[str] = []
|
||||
@@ -1084,6 +1091,6 @@ class ListDirTool(_FsTool):
|
||||
result += f"\n\n(truncated, showing first {cap} of {total} entries)"
|
||||
return result
|
||||
except PermissionError as e:
|
||||
return f"Error: {e}"
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
return f"Error listing directory: {e}"
|
||||
return ToolResult.error(f"Error listing directory: {e}")
|
||||
|
||||
@@ -7,7 +7,7 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
from pydantic import Field
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.schema import (
|
||||
ArraySchema,
|
||||
IntegerSchema,
|
||||
@@ -172,11 +172,11 @@ class ImageGenerationTool(Tool):
|
||||
) -> str:
|
||||
client = self._provider_client()
|
||||
if client is None:
|
||||
return f"Error: unsupported image generation provider '{self.config.provider}'"
|
||||
return ToolResult.error(f"Error: unsupported image generation provider '{self.config.provider}'")
|
||||
|
||||
requested = count or 1
|
||||
if requested > self.config.max_images_per_turn:
|
||||
return (
|
||||
return ToolResult.error(
|
||||
"Error: count exceeds tools.imageGeneration.maxImagesPerTurn "
|
||||
f"({self.config.max_images_per_turn})"
|
||||
)
|
||||
@@ -206,4 +206,4 @@ class ImageGenerationTool(Tool):
|
||||
break
|
||||
return generated_image_tool_result(artifacts)
|
||||
except (ArtifactError, ImageGenerationError, OSError) as exc:
|
||||
return f"Error: {exc}"
|
||||
return ToolResult.error(f"Error: {exc}")
|
||||
|
||||
@@ -8,7 +8,7 @@ from typing import Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.base import Tool, ToolResult
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
|
||||
_SKIP_MODULES = frozenset({
|
||||
@@ -96,6 +96,8 @@ 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(
|
||||
@@ -114,3 +116,70 @@ 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)
|
||||
|
||||
+260
-141
@@ -1,46 +1,54 @@
|
||||
"""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 / redirected—in every case the recap should match reality.
|
||||
|
||||
There is **no** sub-agent orchestrator and **no** special WebSocket ``agent_ui`` stream.
|
||||
"""
|
||||
"""Sustained-goal tools with explicit user opt-in at the execution boundary."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from contextvars import ContextVar
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
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.schema import StringSchema, tool_parameters_schema
|
||||
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(ContextAware):
|
||||
"""Shared routing context + Session lookup."""
|
||||
class _GoalToolsMixin:
|
||||
"""Shared routing context and session lookup."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -49,19 +57,9 @@ class _GoalToolsMixin(ContextAware):
|
||||
) -> 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 = self._request_ctx.get()
|
||||
request_ctx = current_request_context()
|
||||
if request_ctx is None:
|
||||
return None
|
||||
key = request_ctx.session_key
|
||||
@@ -69,10 +67,31 @@ class _GoalToolsMixin(ContextAware):
|
||||
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 = self._request_ctx.get()
|
||||
rc = current_request_context()
|
||||
if runtime_events is None or rc is None:
|
||||
return
|
||||
cid = (rc.chat_id or "").strip()
|
||||
@@ -93,105 +112,23 @@ class _GoalToolsMixin(ContextAware):
|
||||
|
||||
@tool_parameters(
|
||||
tool_parameters_schema(
|
||||
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,
|
||||
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,
|
||||
),
|
||||
ui_summary=StringSchema(
|
||||
"Optional one-line label for session lists / logs (≤120 chars).",
|
||||
"Optional one-line display label for session lists and logs. It is not load-bearing.",
|
||||
max_length=120,
|
||||
nullable=True,
|
||||
),
|
||||
required=["goal"],
|
||||
required=["objective"],
|
||||
)
|
||||
)
|
||||
class LongTaskTool(Tool, _GoalToolsMixin):
|
||||
"""Begin or replace focus on a long-running objective stored on the session."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sessions: Any,
|
||||
runtime_events: RuntimeEventBus | None = None,
|
||||
) -> None:
|
||||
_GoalToolsMixin.__init__(self, sessions, runtime_events)
|
||||
|
||||
@classmethod
|
||||
def create(cls, ctx: Any) -> Tool:
|
||||
sess = getattr(ctx, "sessions", None)
|
||||
assert sess is not None # guarded by enabled()
|
||||
return cls(
|
||||
sessions=sess,
|
||||
runtime_events=getattr(ctx, "runtime_events", None),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def enabled(cls, ctx: Any) -> bool:
|
||||
return getattr(ctx, "sessions", None) is not None
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "long_task"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"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."
|
||||
)
|
||||
|
||||
async def execute(self, goal: str, ui_summary: str | None = None, **kwargs: Any) -> str:
|
||||
sess = self._session()
|
||||
if sess is None:
|
||||
return (
|
||||
"Error: long_task requires an active chat session (missing routing context)."
|
||||
)
|
||||
prior = parse_goal_state(goal_state_raw(sess.metadata))
|
||||
if isinstance(prior, dict) and prior.get("status") == "active":
|
||||
return (
|
||||
"Error: a sustained goal is already active. "
|
||||
"Use complete_goal when finished, or ask the user before replacing it."
|
||||
)
|
||||
|
||||
summary = (ui_summary or "").strip()[:120]
|
||||
blob = {
|
||||
"status": "active",
|
||||
"objective": goal.strip(),
|
||||
"ui_summary": summary,
|
||||
"started_at": _iso_now(),
|
||||
}
|
||||
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 (verified against what was asked), call complete_goal with a "
|
||||
f"short recap.{extra}"
|
||||
)
|
||||
|
||||
|
||||
@tool_parameters(
|
||||
tool_parameters_schema(
|
||||
recap=StringSchema(
|
||||
"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,
|
||||
),
|
||||
required=[],
|
||||
)
|
||||
)
|
||||
class CompleteGoalTool(Tool, _GoalToolsMixin):
|
||||
"""Mark the active sustained goal finished after all required work is verified."""
|
||||
class CreateGoalTool(Tool, _GoalToolsMixin):
|
||||
"""Create one explicit sustained objective for the current session."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -215,37 +152,219 @@ class CompleteGoalTool(Tool, _GoalToolsMixin):
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "complete_goal"
|
||||
return "create_goal"
|
||||
|
||||
@property
|
||||
def description(self) -> str:
|
||||
return (
|
||||
"End bookkeeping for the active sustained goal. "
|
||||
"Use when the objective is fully achieved and verified—recap what was delivered. "
|
||||
"Also call when the user cancels, redirects, or replaces the goal: recap must reflect "
|
||||
"what actually happened (not necessarily success). "
|
||||
"If no goal is active, the tool reports that and leaves metadata unchanged."
|
||||
"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."
|
||||
)
|
||||
|
||||
async def execute(self, recap: str | None = None, **kwargs: Any) -> str:
|
||||
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:
|
||||
sess = self._session()
|
||||
if sess is None:
|
||||
return "Error: complete_goal requires an active chat session."
|
||||
return ToolResult.error(
|
||||
"Error: create_goal 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."
|
||||
)
|
||||
|
||||
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,
|
||||
"ui_summary": summary,
|
||||
"started_at": _iso_now(),
|
||||
}
|
||||
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 recorded. Keep working toward the objective using ordinary tools. "
|
||||
"When fully done and verified, call update_goal with action='complete'."
|
||||
f"{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.",
|
||||
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,
|
||||
nullable=True,
|
||||
),
|
||||
ui_summary=StringSchema(
|
||||
"Optional one-line display label for a replacement goal.",
|
||||
max_length=120,
|
||||
nullable=True,
|
||||
),
|
||||
required=["action"],
|
||||
)
|
||||
)
|
||||
class UpdateGoalTool(Tool, _GoalToolsMixin):
|
||||
"""Complete, cancel, block, or replace the active sustained goal."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
sessions: Any,
|
||||
runtime_events: RuntimeEventBus | None = None,
|
||||
) -> None:
|
||||
_GoalToolsMixin.__init__(self, sessions, runtime_events)
|
||||
|
||||
@classmethod
|
||||
def create(cls, ctx: Any) -> Tool:
|
||||
sess = getattr(ctx, "sessions", None)
|
||||
assert sess is not None
|
||||
return cls(
|
||||
sessions=sess,
|
||||
runtime_events=getattr(ctx, "runtime_events", None),
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def enabled(cls, ctx: Any) -> bool:
|
||||
return getattr(ctx, "sessions", None) is not None
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
return "update_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."
|
||||
)
|
||||
|
||||
async def execute(
|
||||
self,
|
||||
action: str,
|
||||
recap: str | None = None,
|
||||
objective: str | None = None,
|
||||
ui_summary: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> str:
|
||||
sess = self._session()
|
||||
if sess is None:
|
||||
return ToolResult.error("Error: update_goal requires an active chat session.")
|
||||
prior = parse_goal_state(goal_state_raw(sess.metadata))
|
||||
if not isinstance(prior, dict) or prior.get("status") != "active":
|
||||
return "No active goal to complete."
|
||||
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
|
||||
|
||||
ended = _iso_now()
|
||||
sess.metadata[GOAL_STATE_KEY] = {
|
||||
status = {
|
||||
"complete": "completed",
|
||||
"cancel": "cancelled",
|
||||
"block": "blocked",
|
||||
}[normalized]
|
||||
blob = {
|
||||
**prior,
|
||||
"status": "completed",
|
||||
"completed_at": ended,
|
||||
"status": status,
|
||||
"ended_at": ended,
|
||||
"recap": (recap or "").strip(),
|
||||
}
|
||||
discard_legacy_goal_state_key(sess.metadata)
|
||||
self._sessions.save(sess)
|
||||
if normalized == "complete":
|
||||
blob["completed_at"] = ended
|
||||
self._save_goal_state(sess, blob)
|
||||
revoke_goal_mutation_permission()
|
||||
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 complete ({ended}). Recap:\n{tail}"
|
||||
return f"Goal marked complete ({ended})."
|
||||
return f"Goal marked {label} ({ended}). Recap:\n{tail}"
|
||||
return f"Goal marked {label} ({ended})."
|
||||
|
||||
+392
-158
@@ -1,19 +1,21 @@
|
||||
"""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
|
||||
from typing import Any, Mapping, Protocol
|
||||
from weakref import WeakKeyDictionary
|
||||
|
||||
import httpx
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.base import Tool, ToolResult
|
||||
from nanobot.agent.tools.registry import ToolRegistry
|
||||
from nanobot.bus.events import (
|
||||
INBOUND_META_RUNTIME_CONTROL,
|
||||
@@ -21,7 +23,13 @@ from nanobot.bus.events import (
|
||||
RUNTIME_CONTROL_MCP_RELOAD,
|
||||
InboundMessage,
|
||||
)
|
||||
from nanobot.security.network import validate_url_target
|
||||
from nanobot.security.network import (
|
||||
PinnedDNSAsyncTransport,
|
||||
env_proxy_applies_to_url,
|
||||
httpx_env_proxy_mounts,
|
||||
resolve_url_target,
|
||||
validate_url_target,
|
||||
)
|
||||
|
||||
# Transient connection errors that warrant a single retry.
|
||||
# These typically happen when an MCP server restarts or a network
|
||||
@@ -46,6 +54,26 @@ _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":
|
||||
@@ -121,6 +149,25 @@ 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
|
||||
@@ -128,6 +175,8 @@ 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:
|
||||
@@ -152,17 +201,51 @@ 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
|
||||
try:
|
||||
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):
|
||||
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
|
||||
|
||||
|
||||
async def _validate_mcp_request_url(request: httpx.Request) -> None:
|
||||
@@ -170,7 +253,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 {request.url} ({error})",
|
||||
f"Blocked unsafe MCP URL {_redact_url(str(request.url))} ({error})",
|
||||
request=request,
|
||||
)
|
||||
|
||||
@@ -313,6 +396,52 @@ 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."""
|
||||
|
||||
@@ -321,7 +450,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_name(f"mcp_{server_name}_{tool_def.name}")
|
||||
self._name = _sanitize_mcp_tool_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)
|
||||
@@ -340,8 +469,6 @@ 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:
|
||||
@@ -354,7 +481,9 @@ class MCPToolWrapper(_MCPWrapperBase):
|
||||
logger.warning(
|
||||
"MCP tool '{}' timed out after {}s", self._name, self._tool_timeout
|
||||
)
|
||||
return f"(MCP tool call timed out after {self._tool_timeout}s)"
|
||||
return ToolResult.error(
|
||||
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).
|
||||
@@ -362,7 +491,7 @@ class MCPToolWrapper(_MCPWrapperBase):
|
||||
if task is not None and task.cancelling() > 0:
|
||||
raise
|
||||
logger.warning("MCP tool '{}' was cancelled by server/SDK", self._name)
|
||||
return "(MCP tool call was cancelled)"
|
||||
return ToolResult.error("(MCP tool call was cancelled)")
|
||||
except Exception as exc:
|
||||
if await self._refresh_session_after_termination(
|
||||
exc,
|
||||
@@ -387,25 +516,87 @@ class MCPToolWrapper(_MCPWrapperBase):
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
)
|
||||
return f"(MCP tool call failed after retry: {type(exc).__name__})"
|
||||
return ToolResult.error(
|
||||
f"(MCP tool call failed after retry: {type(exc).__name__})"
|
||||
)
|
||||
logger.exception(
|
||||
"MCP tool '{}' failed: {}: {}",
|
||||
self._name,
|
||||
type(exc).__name__,
|
||||
exc,
|
||||
)
|
||||
return f"(MCP tool call failed: {type(exc).__name__})"
|
||||
return ToolResult.error(
|
||||
f"(MCP tool call failed: {type(exc).__name__})"
|
||||
)
|
||||
else:
|
||||
# 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)"
|
||||
# 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__})"
|
||||
)
|
||||
|
||||
return "(MCP tool call failed)" # Unreachable, but satisfies type checkers
|
||||
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
|
||||
|
||||
|
||||
class MCPResourceWrapper(_MCPWrapperBase):
|
||||
@@ -416,7 +607,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_name(f"mcp_{server_name}_resource_{resource_def.name}")
|
||||
self._name = _sanitize_mcp_tool_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] = {
|
||||
@@ -506,8 +697,6 @@ 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."""
|
||||
@@ -517,7 +706,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_name(f"mcp_{server_name}_prompt_{prompt_def.name}")
|
||||
self._name = _sanitize_mcp_tool_name(f"mcp_{server_name}_prompt_{prompt_def.name}")
|
||||
desc = prompt_def.description or prompt_def.name
|
||||
self._description = (
|
||||
f"[MCP Prompt] {desc}\n"
|
||||
@@ -642,24 +831,22 @@ 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, AsyncExitStack]:
|
||||
) -> dict[str, MCPConnection]:
|
||||
"""Connect to configured MCP servers and register their tools, resources, prompts.
|
||||
|
||||
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.
|
||||
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.
|
||||
"""
|
||||
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 connect_single_server(name: str, cfg) -> tuple[str, AsyncExitStack | None]:
|
||||
async def open_single_server(name: str, cfg) -> tuple[str, AsyncExitStack | None]:
|
||||
server_stack = AsyncExitStack()
|
||||
await server_stack.__aenter__()
|
||||
|
||||
@@ -683,7 +870,7 @@ async def connect_mcp_servers(
|
||||
logger.warning(
|
||||
"MCP server '{}': blocked unsafe URL {} ({})",
|
||||
name,
|
||||
cfg.url,
|
||||
_redact_url(cfg.url),
|
||||
error,
|
||||
)
|
||||
await server_stack.aclose()
|
||||
@@ -704,7 +891,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, cfg.url)
|
||||
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
|
||||
await server_stack.aclose()
|
||||
return name, None
|
||||
|
||||
@@ -724,6 +911,7 @@ async def connect_mcp_servers(
|
||||
follow_redirects=True,
|
||||
timeout=timeout,
|
||||
auth=auth,
|
||||
**_pinned_transport_kwargs(),
|
||||
)
|
||||
|
||||
read, write = await server_stack.enter_async_context(
|
||||
@@ -731,7 +919,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, cfg.url)
|
||||
logger.warning("MCP server '{}': {} unreachable, skipping", name, _redact_url(cfg.url))
|
||||
await server_stack.aclose()
|
||||
return name, None
|
||||
|
||||
@@ -741,6 +929,7 @@ 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(
|
||||
@@ -761,9 +950,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_name(f"mcp_{name}_{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]
|
||||
for tool_def in tools.tools:
|
||||
wrapped_name = _sanitize_name(f"mcp_{name}_{tool_def.name}")
|
||||
wrapped_name = _sanitize_mcp_tool_name(f"mcp_{name}_{tool_def.name}")
|
||||
if (
|
||||
not allow_all_tools
|
||||
and tool_def.name not in enabled_tools
|
||||
@@ -797,31 +986,57 @@ async def connect_mcp_servers(
|
||||
", ".join(available_wrapped_names) or "(none)",
|
||||
)
|
||||
|
||||
try:
|
||||
resources_result = await session.list_resources()
|
||||
for resource in resources_result.resources:
|
||||
wrapper = MCPResourceWrapper(
|
||||
session, name, resource, resource_timeout=cfg.tool_timeout
|
||||
)
|
||||
registry.register(wrapper)
|
||||
registered_count += 1
|
||||
# Only register resources and prompts when no tool restriction is
|
||||
# active. enabledTools is a per-*tool* allowlist; resources and
|
||||
# prompts have no equivalent name filter, so they must be skipped
|
||||
# whenever the operator specified a tool subset. An empty list
|
||||
# (deny-all) or a list of specific tool names both indicate that
|
||||
# the operator intended to restrict capabilities — registering
|
||||
# unrestricted resource/prompt wrappers would violate that intent.
|
||||
# The default ["*"] (allow-all) means no restriction was intended.
|
||||
register_extras = allow_all_tools
|
||||
if register_extras:
|
||||
try:
|
||||
resources_result = await session.list_resources()
|
||||
for resource in resources_result.resources:
|
||||
wrapper = MCPResourceWrapper(
|
||||
session, name, resource, resource_timeout=cfg.tool_timeout
|
||||
)
|
||||
registry.register(wrapper)
|
||||
registered_count += 1
|
||||
logger.debug(
|
||||
"MCP: registered resource '{}' from server '{}'",
|
||||
wrapper.name,
|
||||
name,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug(
|
||||
"MCP: registered resource '{}' from server '{}'", wrapper.name, name
|
||||
"MCP server '{}': resources not supported or failed: {}", name, e
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug("MCP server '{}': resources not supported or failed: {}", name, e)
|
||||
|
||||
try:
|
||||
prompts_result = await session.list_prompts()
|
||||
for prompt in prompts_result.prompts:
|
||||
wrapper = MCPPromptWrapper(
|
||||
session, name, prompt, prompt_timeout=cfg.tool_timeout
|
||||
try:
|
||||
prompts_result = await session.list_prompts()
|
||||
for prompt in prompts_result.prompts:
|
||||
wrapper = MCPPromptWrapper(
|
||||
session, name, prompt, prompt_timeout=cfg.tool_timeout
|
||||
)
|
||||
registry.register(wrapper)
|
||||
registered_count += 1
|
||||
logger.debug(
|
||||
"MCP: registered prompt '{}' from server '{}'",
|
||||
wrapper.name,
|
||||
name,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.debug(
|
||||
"MCP server '{}': prompts not supported or failed: {}", name, e
|
||||
)
|
||||
registry.register(wrapper)
|
||||
registered_count += 1
|
||||
logger.debug("MCP: registered prompt '{}' from server '{}'", wrapper.name, name)
|
||||
except Exception as e:
|
||||
logger.debug("MCP server '{}': prompts not supported or failed: {}", name, e)
|
||||
else:
|
||||
logger.info(
|
||||
"MCP server '{}': skipping resource/prompt registration "
|
||||
"(enabledTools does not include '*' — only tools allowed)",
|
||||
name,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
"MCP server '{}': connected, {} capabilities registered", name, registered_count
|
||||
@@ -850,7 +1065,43 @@ async def connect_mcp_servers(
|
||||
await server_stack.aclose()
|
||||
return name, None
|
||||
|
||||
server_stacks: dict[str, AsyncExitStack] = {}
|
||||
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] = {}
|
||||
|
||||
for name, cfg in mcp_servers.items():
|
||||
try:
|
||||
@@ -870,97 +1121,50 @@ 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."""
|
||||
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 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:
|
||||
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
|
||||
|
||||
|
||||
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
|
||||
from nanobot.config.loader import load_effective_config
|
||||
|
||||
config = resolve_config_env_vars(load_config())
|
||||
config = load_effective_config()
|
||||
next_servers = dict(config.tools.mcp_servers)
|
||||
except Exception as exc:
|
||||
logger.warning("MCP hot reload could not read config: {}", exc)
|
||||
@@ -995,13 +1199,20 @@ 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, AsyncExitStack] = {}
|
||||
connected: dict[str, MCPConnection] = {}
|
||||
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
|
||||
@@ -1116,11 +1327,10 @@ def _attach_reconnect_handlers(
|
||||
)
|
||||
|
||||
for server_name in server_names:
|
||||
prefix = _tool_prefix(server_name)
|
||||
for tool_name in list(registry.tool_names):
|
||||
if not tool_name.startswith(prefix):
|
||||
continue
|
||||
tool = registry.get(tool_name)
|
||||
if not _tool_belongs_to_server(tool, tool_name, server_name):
|
||||
continue
|
||||
if isinstance(tool, _MCPWrapperBase):
|
||||
tool.set_reconnect_handler(reconnect)
|
||||
|
||||
@@ -1133,6 +1343,8 @@ 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(
|
||||
@@ -1154,9 +1366,12 @@ 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
|
||||
@@ -1173,11 +1388,17 @@ 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):
|
||||
if tool_name.startswith(prefix):
|
||||
tool = registry.get(tool_name)
|
||||
if _tool_belongs_to_server(tool, tool_name, server_name):
|
||||
registry.unregister(tool_name)
|
||||
removed += 1
|
||||
return removed
|
||||
@@ -1191,3 +1412,16 @@ async def _close_server(state: Any, server_name: str) -> None:
|
||||
await stack.aclose()
|
||||
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 (RuntimeError, BaseExceptionGroup):
|
||||
logger.debug("MCP server '{}' cleanup error (can be ignored)", name)
|
||||
|
||||
@@ -6,8 +6,8 @@ from typing import Any, Awaitable, Callable
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.tools.base import Tool, tool_parameters
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
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, ContextAware):
|
||||
class MessageTool(Tool):
|
||||
"""Tool to send messages to users on chat channels."""
|
||||
|
||||
def __init__(
|
||||
@@ -62,20 +62,10 @@ class MessageTool(Tool, ContextAware):
|
||||
Path(workspace).expanduser() if workspace is not None else get_workspace_path()
|
||||
)
|
||||
self._restrict_to_workspace = restrict_to_workspace
|
||||
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._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._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",
|
||||
@@ -99,13 +89,6 @@ class MessageTool(Tool, ContextAware):
|
||||
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
|
||||
@@ -198,9 +181,24 @@ class MessageTool(Tool, ContextAware):
|
||||
not isinstance(row, list) or any(not isinstance(label, str) for label in row)
|
||||
for row in buttons
|
||||
):
|
||||
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()
|
||||
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
|
||||
)
|
||||
channel = channel or default_channel
|
||||
explicit_chat_id = chat_id
|
||||
if (
|
||||
@@ -210,7 +208,7 @@ class MessageTool(Tool, ContextAware):
|
||||
and str(explicit_chat_id).strip() != ""
|
||||
and str(explicit_chat_id).strip() != str(default_chat_id).strip()
|
||||
):
|
||||
return (
|
||||
return ToolResult.error(
|
||||
"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 "
|
||||
@@ -224,23 +222,23 @@ class MessageTool(Tool, ContextAware):
|
||||
# to the wrong chat entirely.
|
||||
same_target = channel == default_channel and chat_id == default_chat_id
|
||||
if same_target:
|
||||
message_id = message_id or self._default_message_id.get()
|
||||
message_id = message_id or default_message_id
|
||||
else:
|
||||
message_id = None
|
||||
|
||||
if not channel or not chat_id:
|
||||
return "Error: No target channel/chat specified"
|
||||
return ToolResult.error("Error: No target channel/chat specified")
|
||||
|
||||
if not self._send_callback:
|
||||
return "Error: Message sending not configured"
|
||||
return ToolResult.error("Error: Message sending not configured")
|
||||
|
||||
if media:
|
||||
try:
|
||||
media = self._resolve_media(media)
|
||||
except (OSError, PermissionError, ValueError) as e:
|
||||
return f"Error: media path is not allowed: {str(e)}"
|
||||
return ToolResult.error(f"Error: media path is not allowed: {str(e)}")
|
||||
|
||||
metadata = dict(self._default_metadata.get()) if same_target else {}
|
||||
metadata = dict(default_metadata) if same_target else {}
|
||||
if message_id:
|
||||
metadata["message_id"] = message_id
|
||||
if self._record_channel_delivery_var.get() or media:
|
||||
@@ -270,4 +268,4 @@ class MessageTool(Tool, ContextAware):
|
||||
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 f"Error sending message: {str(e)}"
|
||||
return ToolResult.error(f"Error sending message: {str(e)}")
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
"""Tool registry for dynamic tool management."""
|
||||
|
||||
import json
|
||||
from typing import Any
|
||||
from __future__ import annotations
|
||||
|
||||
from nanobot.agent.tools.base import Tool
|
||||
import json
|
||||
from typing import TYPE_CHECKING, 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
|
||||
|
||||
|
||||
class ToolRegistry:
|
||||
@@ -31,6 +41,15 @@ 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."""
|
||||
@@ -100,22 +119,32 @@ 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, (
|
||||
f"Error: Tool '{name}' not found.{hint} Available: {', '.join(self.tool_names)}"
|
||||
ToolResult.error(
|
||||
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, (
|
||||
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.'
|
||||
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.'
|
||||
)
|
||||
)
|
||||
|
||||
cast_params = tool.cast_params(params)
|
||||
errors = tool.validate_params(cast_params)
|
||||
if errors:
|
||||
return tool, cast_params, (
|
||||
f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors)
|
||||
ToolResult.error(f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors))
|
||||
)
|
||||
return tool, cast_params, None
|
||||
|
||||
@@ -159,16 +188,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 error + hint
|
||||
return ToolResult.error(str(error) + hint)
|
||||
|
||||
try:
|
||||
assert tool is not None # guarded by prepare_call()
|
||||
result = await tool.execute(**params)
|
||||
if isinstance(result, str) and result.startswith("Error"):
|
||||
return result + hint
|
||||
if is_tool_error_result(name, result):
|
||||
return ToolResult.error(str(result) + hint)
|
||||
return result
|
||||
except Exception as e:
|
||||
return f"Error executing {name}: {str(e)}" + hint
|
||||
return ToolResult.error(f"Error executing {name}: {str(e)}" + hint)
|
||||
|
||||
@property
|
||||
def tool_names(self) -> list[str]:
|
||||
|
||||
@@ -56,7 +56,9 @@ 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
|
||||
|
||||
@@ -33,6 +33,9 @@ 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",
|
||||
]
|
||||
|
||||
@@ -9,6 +9,7 @@ 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
|
||||
@@ -218,12 +219,12 @@ class FindFilesTool(_SearchTool):
|
||||
try:
|
||||
target = self._resolve(path or ".")
|
||||
if not target.exists():
|
||||
return f"Error: Path not found: {path}"
|
||||
return ToolResult.error(f"Error: Path not found: {path}")
|
||||
if not (target.is_dir() or target.is_file()):
|
||||
return f"Error: Unsupported path: {path}"
|
||||
return ToolResult.error(f"Error: Unsupported path: {path}")
|
||||
|
||||
if sort not in {"path", "modified"}:
|
||||
return "Error: sort must be 'path' or 'modified'"
|
||||
return ToolResult.error("Error: sort must be 'path' or 'modified'")
|
||||
|
||||
limit = (
|
||||
_DEFAULT_FILE_HEAD_LIMIT
|
||||
@@ -271,9 +272,9 @@ class FindFilesTool(_SearchTool):
|
||||
result += "\n\n" + note
|
||||
return result
|
||||
except PermissionError as e:
|
||||
return f"Error: {e}"
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
return f"Error finding files: {e}"
|
||||
return ToolResult.error(f"Error finding files: {e}")
|
||||
|
||||
|
||||
class GrepTool(_SearchTool):
|
||||
@@ -425,16 +426,16 @@ class GrepTool(_SearchTool):
|
||||
try:
|
||||
target = self._resolve(path or ".")
|
||||
if not target.exists():
|
||||
return f"Error: Path not found: {path}"
|
||||
return ToolResult.error(f"Error: Path not found: {path}")
|
||||
if not (target.is_dir() or target.is_file()):
|
||||
return f"Error: Unsupported path: {path}"
|
||||
return ToolResult.error(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 f"Error: invalid regex pattern: {e}"
|
||||
return ToolResult.error(f"Error: invalid regex pattern: {e}")
|
||||
|
||||
if head_limit is not None:
|
||||
limit = None if head_limit == 0 else head_limit
|
||||
@@ -579,6 +580,6 @@ class GrepTool(_SearchTool):
|
||||
result += "\n\n" + "\n".join(notes)
|
||||
return result
|
||||
except PermissionError as e:
|
||||
return f"Error: {e}"
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
return f"Error searching files: {e}"
|
||||
return ToolResult.error(f"Error searching files: {e}")
|
||||
|
||||
+85
-42
@@ -7,8 +7,8 @@ from typing import TYPE_CHECKING, Any
|
||||
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.agent.tools.base import Tool
|
||||
from nanobot.agent.tools.context import ContextAware, RequestContext
|
||||
from nanobot.agent.tools.base import Tool, ToolResult
|
||||
from nanobot.agent.tools.context import current_request_context
|
||||
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, ContextAware):
|
||||
class MyTool(Tool):
|
||||
"""Check and set the agent loop's runtime configuration."""
|
||||
|
||||
_plugin_discoverable = False # Requires AgentLoop reference; registered manually
|
||||
@@ -57,7 +57,7 @@ class MyTool(Tool, ContextAware):
|
||||
|
||||
BLOCKED = frozenset({
|
||||
# Core infrastructure
|
||||
"bus", "provider", "_running", "tools",
|
||||
"bus", "provider", "runtime_resolver", "_running", "tools",
|
||||
# Config management
|
||||
"_runtime_vars",
|
||||
# Subsystems
|
||||
@@ -68,7 +68,7 @@ class MyTool(Tool, ContextAware):
|
||||
"_session_locks", "_active_tasks", "_background_tasks",
|
||||
# Security boundaries (inspect + modify both blocked)
|
||||
"restrict_to_workspace", "channels_config",
|
||||
"_concurrency_gate", "_unified_session", "_extra_hooks",
|
||||
"_concurrency_gate", "_unified_session", "_extra_hooks", "_hook_factories",
|
||||
})
|
||||
|
||||
READ_ONLY = frozenset({
|
||||
@@ -77,8 +77,11 @@ class MyTool(Tool, ContextAware):
|
||||
"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__",
|
||||
@@ -107,12 +110,15 @@ class MyTool(Tool, ContextAware):
|
||||
}
|
||||
|
||||
_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__
|
||||
@@ -120,14 +126,8 @@ class MyTool(Tool, ContextAware):
|
||||
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,6 +144,8 @@ class MyTool(Tool, ContextAware):
|
||||
"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"
|
||||
@@ -176,6 +178,7 @@ class MyTool(Tool, ContextAware):
|
||||
"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)."},
|
||||
@@ -184,7 +187,12 @@ class MyTool(Tool, ContextAware):
|
||||
}
|
||||
|
||||
def _audit(self, action: str, detail: str) -> None:
|
||||
session = f"{self._channel}:{self._chat_id}" if self._channel else "unknown"
|
||||
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"
|
||||
)
|
||||
logger.info("self.{} | {} | session:{}", action, detail, session)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -216,7 +224,7 @@ class MyTool(Tool, ContextAware):
|
||||
@staticmethod
|
||||
def _validate_key(key: str | None, label: str = "key") -> str | None:
|
||||
if not key or not key.strip():
|
||||
return f"Error: '{label}' cannot be empty or whitespace"
|
||||
return ToolResult.error(f"Error: '{label}' cannot be empty or whitespace")
|
||||
return None
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -321,19 +329,43 @@ class MyTool(Tool, ContextAware):
|
||||
if action in ("inspect", "check"):
|
||||
return self._inspect(key)
|
||||
if not self._modify_allowed:
|
||||
return "Error: set is disabled (tools.my.allow_set is false)"
|
||||
return ToolResult.error("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 f"Error: '{top}' is not accessible"
|
||||
return ToolResult.error(f"Error: '{top}' is not accessible")
|
||||
obj, err = self._resolve_path(key)
|
||||
if err:
|
||||
# "scratchpad" alias for _runtime_vars
|
||||
@@ -343,12 +375,12 @@ class MyTool(Tool, ContextAware):
|
||||
# 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 f"Error: {err}"
|
||||
return ToolResult.error(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 f"Error: '{key}' not found"
|
||||
return ToolResult.error(f"Error: '{key}' not found")
|
||||
return self._format_value(obj, key)
|
||||
|
||||
def _inspect_all(self) -> str:
|
||||
@@ -356,8 +388,13 @@ class MyTool(Tool, ContextAware):
|
||||
parts: list[str] = []
|
||||
# RESTRICTED keys
|
||||
for k in self.RESTRICTED:
|
||||
parts.append(self._format_value(getattr(state, k, None), k))
|
||||
parts.append(self._format_value(state.model_preset, "model_preset"))
|
||||
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",
|
||||
))
|
||||
# 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):
|
||||
@@ -379,21 +416,21 @@ class MyTool(Tool, ContextAware):
|
||||
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 f"Error: '{key}' is protected and cannot be modified"
|
||||
return ToolResult.error(f"Error: '{key}' is protected and cannot be modified")
|
||||
if top in self.READ_ONLY:
|
||||
self._audit("modify", f"READ_ONLY {key}")
|
||||
return f"Error: '{key}' is read-only and cannot be modified"
|
||||
return ToolResult.error(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 f"Error: '{leaf}' is not accessible"
|
||||
return ToolResult.error(f"Error: '{leaf}' is not accessible")
|
||||
if leaf.lower() in self._SENSITIVE_NAMES:
|
||||
self._audit("modify", f"BLOCKED sensitive leaf '{leaf}'")
|
||||
return f"Error: '{leaf}' is not accessible"
|
||||
return ToolResult.error(f"Error: '{leaf}' is not accessible")
|
||||
parent, err = self._resolve_path(parent_path)
|
||||
if err:
|
||||
return f"Error: {err}"
|
||||
return ToolResult.error(f"Error: {err}")
|
||||
if isinstance(parent, dict):
|
||||
parent[leaf] = value
|
||||
else:
|
||||
@@ -408,11 +445,11 @@ class MyTool(Tool, ContextAware):
|
||||
|
||||
def _modify_model_preset(self, value: Any) -> str:
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
return "Error: 'model_preset' must be a non-empty string"
|
||||
return ToolResult.error("Error: 'model_preset' must be a non-empty string")
|
||||
name = value.strip()
|
||||
result = self._modify_free("model_preset", name)
|
||||
if result.startswith("Error:"):
|
||||
return result if result.endswith((".", "!", "?")) else f"{result}."
|
||||
if isinstance(result, ToolResult) and result.is_error:
|
||||
return result if result.endswith((".", "!", "?")) else ToolResult.error(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}"
|
||||
@@ -422,23 +459,29 @@ class MyTool(Tool, ContextAware):
|
||||
spec = self.RESTRICTED[key]
|
||||
expected = spec["type"]
|
||||
if expected is int and isinstance(value, bool):
|
||||
return f"Error: '{key}' must be {expected.__name__}, got bool"
|
||||
return ToolResult.error(f"Error: '{key}' must be {expected.__name__}, got bool")
|
||||
if not isinstance(value, expected):
|
||||
try:
|
||||
value = expected(value)
|
||||
except (ValueError, TypeError):
|
||||
return f"Error: '{key}' must be {expected.__name__}, got {type(value).__name__}"
|
||||
return ToolResult.error(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 f"Error: '{key}' must be >= {spec['min']}"
|
||||
return ToolResult.error(f"Error: '{key}' must be >= {spec['min']}")
|
||||
if "max" in spec and value > spec["max"]:
|
||||
return f"Error: '{key}' must be <= {spec['max']}"
|
||||
return ToolResult.error(f"Error: '{key}' must be <= {spec['max']}")
|
||||
if "min_len" in spec and len(str(value)) < spec["min_len"]:
|
||||
return f"Error: '{key}' must be at least {spec['min_len']} characters"
|
||||
setattr(self._runtime_state, key, value)
|
||||
return ToolResult.error(f"Error: '{key}' must be at least {spec['min_len']} characters")
|
||||
if key == "model":
|
||||
self._runtime_state._active_preset = None
|
||||
if key == "max_iterations" and hasattr(self._runtime_state, "_sync_subagent_runtime_limits"):
|
||||
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._sync_subagent_runtime_limits()
|
||||
self._audit("modify", f"{key}: {old!r} -> {value!r}")
|
||||
return f"Set {key} = {value!r} (was {old!r})"
|
||||
@@ -455,25 +498,25 @@ class MyTool(Tool, ContextAware):
|
||||
"modify",
|
||||
f"REJECTED type mismatch {key}: expects {old_t.__name__}, got {new_t.__name__}",
|
||||
)
|
||||
return f"Error: '{key}' expects {old_t.__name__}, got {new_t.__name__}"
|
||||
return ToolResult.error(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 f"Error: {message}"
|
||||
return ToolResult.error(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 "Error: cannot store callable values"
|
||||
return ToolResult.error("Error: cannot store callable values")
|
||||
err = self._validate_json_safe(value)
|
||||
if err:
|
||||
self._audit("modify", f"REJECTED {key}: {err}")
|
||||
return f"Error: {err}"
|
||||
return ToolResult.error(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 f"Error: scratchpad is full (max {self._MAX_RUNTIME_KEYS} keys). Remove unused keys first."
|
||||
return ToolResult.error(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}")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user