Compare commits

...
Author SHA1 Message Date
Xubin Ren ab8783758a feat(webui): add browser companion launch 2026-07-20 04:51:26 +08:00
chengyongruandchengyongru e3de01c9f6 fix(webui): resolve build runner executable 2026-07-19 23:59:34 +08:00
chengyongruandGitHub 462a0dfb0f refactor(channels): make built-in channels self-contained (#4908)
* refactor(channels): own setup and instance contracts

* refactor(channels): isolate management contracts

* refactor(channels): normalize activation contracts

* fix(channels): enforce management contracts

* refactor(channels): finish setup ownership migration

* fix(channels): harden management contracts

* fix(channels): enforce lazy loading and runtime ownership

* fix(feishu): make multi-instance startup idempotent

* fix(webui): render channel setup contracts cleanly

* fix(feishu): stop websocket clients cleanly

* fix(channels): enforce persistence and activation gates

* fix(channels): preserve global feature action scope

* fix(channels): apply defaults for single plugins

* fix(channels): enforce management contract boundaries

* refactor(feishu): remove identity helper indirection

* fix(channels): preserve management setup contracts

* refactor(channels): generalize instance settings UI

* refactor(channels): package channel plugins with web UI metadata

* refactor(channels): make built-ins self-contained packages

* test(channels): colocate tests with channel packages

* fix(dingtalk): use official brand icon

* feat(channels): colocate webui translations

* docs(channels): clarify plugin ownership

* test(exec): remove output wait race

* refactor(channels): unify plugin descriptors

* fix(channels): enforce descriptor-owned contracts

* refactor(channels): finish package-owned plugin setup

* refactor(channels): use repository-owned packages only

* fix(channels): self-describe dependencies and runtime state

* fix(channels): warn about legacy entry points
2026-07-19 23:30:49 +08:00
chengyongruandchengyongru 7aaac37bca fix(triggers): require channel enablement predicate 2026-07-19 22:33:29 +08:00
Pei Futongandchengyongru 91514ad0b1 fix(triggers): reject deliveries to disabled channels 2026-07-19 22:33:29 +08:00
chengyongruandGitHub a6b68178aa fix(whatsapp): allow group ids in allowFrom (#4834) 2026-07-19 19:16:37 +08:00
chengyongruandGitHub 2099cb009e fix(providers): fail over across provider failure domains 2026-07-19 17:37:55 +08:00
Pei Futongandchengyongru 39a952ecce fix(cli-apps): decode subprocess output as UTF-8 2026-07-19 16:05:26 +08:00
chengyongruandchengyongru b1232fdaf4 fix(gitstore): preserve staged symlinks 2026-07-19 16:01:11 +08:00
Pei Futongandchengyongru cea8617096 fix(gitstore): resolve staged paths relative to workspace 2026-07-19 16:01:11 +08:00
chengyongruandchengyongru ffb7ddfa1e refactor(triggers): clarify stored integer coercion 2026-07-19 15:46:00 +08:00
santhrealandchengyongru c2071594cf fix(triggers): rename coerce helper to _store_int
Match the cron store-load naming and cover null attempts on deliveries.
2026-07-19 15:46:00 +08:00
santhrealandchengyongru cf96c4d5e9 fix(triggers): coerce null ms fields when loading local triggers
Explicit JSON null for runAtMs/createdAtMs raised TypeError and could
quarantine triggers.json. Treat null/blank like a missing key (0).
2026-07-19 15:46:00 +08:00
chengyongruandchengyongru cf00f537bd fix(agent): guide recovery from oversized tool results
Use the existing in-flight context governor to replace tool output that cannot fit the next model request with a bounded, actionable instruction. The model can retry with narrower arguments, use another tool, or explain the context limit without a second recovery state machine.
2026-07-19 01:08:36 +08:00
cfa49c6e78 fix(render): issue short-lived WebUI tokens via tokenIssueSecret
Map NANOBOT_WEB_TOKEN to channels.websocket.tokenIssueSecret instead of
the static token, and remove the static token. The gateway now issues
short-lived WebSocket/API tokens rather than accepting a long-lived
credential directly at the handshake, matching the public-WebUI login
flow and documentation. Users still enter the same NANOBOT_WEB_TOKEN,
and websocketRequiresToken remains true.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:39:59 +08:00
c062e1af14 fix(webui): quiet non-WebSocket handshake noise on public port
The WebSocket channel also serves the WebUI over plain HTTP, so on a
public endpoint (e.g. a Render *.onrender.com service) the underlying
websockets library logs a full-traceback ERROR for every request that
isn't a valid GET handshake: HEAD probes ("unsupported HTTP method;
expected GET"), port scanners, uptime monitors, and TLS-to-plain-port
attempts. These are internet background noise, not server faults.

WebSocketHandshakeNoiseFilter already suppressed "opening handshake
failed" records caused by mid-handshake disconnects; widen it to also
suppress records whose exception chain contains websockets'
InvalidMessage, which covers both non-GET methods and malformed/empty
requests. Genuine server-side handshake errors still log.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:39:59 +08:00
Ho1yShifandXubin Ren c77379099b refactor(entrypoint): improve privilege dropping and config initialization
- Updated entrypoint.sh to initialize the on-disk config only if it does not already exist, preserving user edits across restarts.
- Enhanced privilege dropping logic to ensure the container does not run as root if the privilege drop fails.
- Clarified comments in Dockerfile and entrypoint.sh for better understanding of the privilege management process.
- Updated README.md to include a note about persistent disks requiring a paid service on Render.
- Adjusted render.yaml to clarify the Docker command behavior and added a note regarding auto-deploy settings.
2026-07-18 17:39:59 +08:00
Ho1yShifandXubin Ren ca873e4d17 fix(README): update Deploy to Render link to point to the correct GitHub repository 2026-07-18 17:39:59 +08:00
Ho1yShifandXubin Ren 63895fc101 fix: update Deploy to Render link in README
Changed the repository link for the one-click Deploy to Render button in the README.md file to point to the correct GitHub repository.
2026-07-18 17:39:59 +08:00
770d89b430 feat: add one-click Deploy to Render support
Adds a Render Blueprint (render.yaml) and supporting pieces so nanobot can
be deployed to Render in one click, with persistent memory across deploys.

- render.yaml: web service + 1GB persistent disk mounted at
  /home/nanobot/.nanobot. Prompts for ANTHROPIC_API_KEY and
  NANOBOT_WEB_TOKEN at deploy time (sync: false).
- render-config.json: committed gateway config that wires secrets via
  ${VAR} placeholders (resolved at runtime). Nothing secret is committed.
- entrypoint.sh: adds a branch gated on RENDER=true that copies the config
  onto the mounted disk, chowns the root-owned mount, and drops to the
  non-root nanobot user via setpriv. Local (non-Render) path is unchanged.
- Dockerfile: COPY render-config.json; USER nanobot -> USER root so the
  entrypoint can chown the freshly-mounted disk before dropping privileges;
  add PYTHONUNBUFFERED/PYTHONFAULTHANDLER for diagnosable crash output.
- README.md: Deploy to Render button + section.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-18 17:39:59 +08:00
santhrealandXubin Ren afed32b013 fix(cron): dual-case keys when loading jobs.json
jobs.json hand-edits and asdict-style snake_case for schedule intervals and
runHistory crashed or silently disabled cron. Deserialize via Cron* from_store_dict
and shared get_camel_snake (also used by local triggers).
2026-07-18 17:39:06 +08:00
bingqilinweimaotaiandXubin Ren 8c68c6fe1e feat: support Kimi K3 2026-07-18 17:38:32 +08:00
Yuxin LouandXubin Ren b76d54aae1 Harden default Docker Compose security 2026-07-18 17:37:41 +08:00
KDBandXubin Ren d35f99abfc fix(session): bound the in-memory session cache
Keep only 128 recently used sessions strongly cached while retaining weak references to evicted sessions still owned by active callers. This bounds idle memory growth without allowing duplicate live Session objects or skipping shutdown flushes.

Add LRU, lifecycle, SDK, and flush regression coverage.

Refs #4786
2026-07-18 17:37:07 +08:00
adabarbulescuandXubin Ren d4f5abe004 fix: preserve real cancellation in MCP paths 2026-07-18 17:36:35 +08:00
yu-xin-candXubin Ren 07ad0bafa8 test(exec): relax wait-for timing on Windows 2026-07-18 17:35:56 +08:00
yu-xin-candXubin Ren 995cc44e89 fix(exec): isolate exec session managers 2026-07-18 17:35:56 +08:00
santhrealandXubin Ren 7ac9a46978 fix(utils): avoid hang in split_message when max_len <= 0
When max_len is 0 or negative the cut pointer never advances, so the loop hangs. Return the content unsplit, matching truncate_text_to_tokens for non-positive budgets.
2026-07-18 17:24:12 +08:00
santhrealandXubin Ren fe0e65928d fix(utils): coerce Tavily usage counters to int
JSON APIs sometimes return numeric fields as strings; subtracting them raised TypeError and /status dropped the usage block.
2026-07-18 17:23:26 +08:00
santhrealandXubin Ren 85097aa143 fix(utils): handle empty commit messages in CommitInfo.format
Empty git commit messages made splitlines()[0] raise IndexError in format() and /dream-restore list rendering.
2026-07-18 17:22:16 +08:00
Peter Dave Helloandchengyongru 6de5a0c5ca Improve zh-TW Traditional Chinese locale 2026-07-18 00:59:05 +08:00
bingqilinweimaotaiandchengyongru 8a48af7c74 fix(providers): omit Kimi K2.5/K2.6 temperature 2026-07-17 22:39:33 +08:00
Xubin Ren b4adb29c2b feat(webui): support native folder picker bridges 2026-07-17 12:26:03 +08:00
Xubin Ren 6519737860 docs(readme): reflect community maintenance 2026-07-16 13:52:12 +08:00
chengyongruandchengyongru d4e0294734 fix(gateway): stop channels before draining tasks 2026-07-15 22:25:08 +08:00
chengyongruandchengyongru 681edfa6f3 fix(providers): honor Codex proxy config consistently 2026-07-15 20:01:48 +08:00
chengyongruandGitHub ba86dccc8d fix(webui): correct activity timer duration (#4649) 2026-07-15 16:46:05 +08:00
chengyongruandGitHub 5ed28a6744 fix(webui): validate inferred file paths before preview (#4935) 2026-07-15 10:45:40 +08:00
chengyongruandGitHub aa70aa48f9 fix(cli): point onboarding to the WebUI launcher (#4938) 2026-07-15 10:34:46 +08:00
chengyongruandchengyongru 0fd4d0ab29 fix(prompts): handle undecodable overrides 2026-07-15 01:19:48 +08:00
chengyongruandchengyongru c1fd76add3 refactor(prompts): share workspace override handling 2026-07-15 01:19:48 +08:00
chengyongruandchengyongru 63a6d5d07d fix(heartbeat): retain history after empty runs 2026-07-15 01:19:48 +08:00
Arthur K.andchengyongru dcb37259fa feat(heartbeat): custom evaluator prompt 2026-07-15 01:19:48 +08:00
chengyongruandGitHub 88c38e9b38 fix(restart): deliver completion after channel reconnects (#4931) 2026-07-15 01:08:39 +08:00
chengyongruandGitHub 37165b0db0 feat(webui): highlight slash commands and app mentions (#4933) 2026-07-15 00:34:22 +08:00
chengyongruandchengyongru 2116e32013 test: speed up CI and harden the suite 2026-07-15 00:18:37 +08:00
Olu Bandchengyongru 06f47fa540 fix: standardize --config help text across CLI commands 2026-07-14 23:51:39 +08:00
chengyongruandchengyongru 905da8e34a ci(webui): verify npm and bun lockfiles 2026-07-14 23:16:21 +08:00
5365bab088 fix(webui): sync package-lock.json for qrcode dependency
fe0717b3 ("feat(webui): add guided setup flows") added qrcode and
@types/qrcode to webui/package.json without regenerating the lockfile,
so `npm ci` fails in the Docker build with EUSAGE (Missing: qrcode,
@types/qrcode, dijkstrajs, pngjs, yargs, ...).

Regenerate the lockfile so it matches package.json again.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-14 23:16:21 +08:00
chengyongruandchengyongru f718c69b2d feat(webui): add copy action to user messages 2026-07-14 22:41:17 +08:00
chengyongruandGitHub 07f54c25e3 chore(codex): identify failing request stage (#4929) 2026-07-14 22:40:10 +08:00
chengyongruandchengyongru 1a1e666625 fix: install timezone data on Windows 2026-07-14 17:30:16 +08:00
chengyongruandchengyongru 297a9e5939 test: cover MCP cleanup cancellation paths 2026-07-14 16:17:35 +08:00
Brian Noahandchengyongru 86f6558707 fix: catch asyncio.CancelledError in close_mcp shutdown
When an MCP server (e.g. stdio browser-agent subprocess) does not
terminate within the AsyncExitStack.aclose() timeout, asyncio raises
CancelledError. The existing exception handler only caught RuntimeError
and BaseExceptionGroup, so CancelledError escaped the except block and
crashed nanobot with exit code 1 on every shutdown.

Add asyncio.CancelledError to the caught exception tuple so the error
is logged at debug level and shutdown completes cleanly.

Stack trace from the crash:

Traceback (most recent call last):
  File ".../nanobot/agent/loop.py", line 1194, in close_mcp
    await stack.aclose()
asyncio.exceptions.CancelledError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File ".../asyncio/__main__.py", line ?, in <module>
  File ".../nanobot/agent/loop.py", line ?, in close_mcp
    ...
RuntimeError: ... (or BaseExceptionGroup) not caught
SystemExit: 1
2026-07-14 16:17:35 +08:00
chengyongruandchengyongru 4916fc07ab fix(agent): close reasoning on stream timeout 2026-07-14 15:51:22 +08:00
WK Wongandchengyongru 11eb9d8cc8 fix(agent): add wall-clock timeout for streaming LLM requests 2026-07-14 15:51:22 +08:00
chengyongruandGitHub 6c9e3a2cc3 refactor(webui): centralize native runtime access (#4769) 2026-07-14 15:00:30 +08:00
chengyongruandGitHub b7048cf76a feat(webui): support document attachments with ingress safeguards (#4771)
* feat: support document attachments in webui

* fix(webui): normalize document attachment MIME

* refactor(webui): move attachment policy out of channel

* fix(webui): reject oversized attachments before send

* fix(webui): align Portuguese attachment errors

* refactor(webui): separate ingress and transport limits

* fix(webui): reject malformed attachment payloads
2026-07-14 14:47:42 +08:00
chengyongruandGitHub b2759e8a6b docs: reorganize documentation around user workflows (#4916) 2026-07-14 13:59:47 +08:00
chengyongruandchengyongru 1643aa7ef5 fix(shell): narrow PowerShell UTF-8 configuration
Avoid changing native pipeline input encoding and consolidate real PowerShell checks to reduce Windows runner startup flakiness.
2026-07-14 13:50:02 +08:00
chengyongruandchengyongru 9f8c2cb1bf test(shell): wait for Windows PowerShell sessions 2026-07-14 13:50:02 +08:00
chengyongruandchengyongru 61afbffc89 fix(shell): configure PowerShell UTF-8 output 2026-07-14 13:50:02 +08:00
adabarbulescuandchengyongru 9cdf17f5d5 Fix Windows exec UTF-16 output decoding 2026-07-14 13:50:02 +08:00
chengyongruandXubin Ren 3b14d59dcd fix(telegram): fall back on overflow HTML rejection 2026-07-14 12:25:28 +08:00
chengyongruandXubin Ren a335ce07db fix(telegram): bound streamed HTML overflow chunks 2026-07-14 12:25:28 +08:00
sanasif786kaandXubin Ren 87478b6e92 fix(telegram): keep raw markdown in overflow stream buffer tail
Send the overflow tail message with HTML parse_mode, but persist the
unrendered markdown chunk in buf.text so later deltas and stream_end
re-render correctly via _split_telegram_markdown_html().
2026-07-14 12:25:28 +08:00
sanasif786kaandXubin Ren 67648774e2 fix(telegram): preserve HTML formatting in stream overflow chunks
Apply parse_mode=HTML to overflow intermediate chunks so markdown
formatting is not lost when long streamed messages are split.

Fixes #4637
2026-07-14 12:25:28 +08:00
chengyongruandchengyongru 6e462e62a6 fix(dream): limit newline normalization to CRLF 2026-07-14 00:30:50 +08:00
bingqilinweimaotaiandchengyongru ed47cf1562 fix(dream): ignore line-ending-only memory diffs 2026-07-14 00:30:50 +08:00
chengyongruandchengyongru 6b5820ea89 fix(webui): sync localized preboot copy 2026-07-13 23:28:19 +08:00
bill-kopp-ai-devandchengyongru 1e7518a207 feat(webui): add Brazilian Portuguese (pt-BR) locale
Translate the WebUI common.json to pt-BR, register the locale in
config.ts (with normalizeLocale rules for "pt", "pt-BR", "pt-PT", ...)
and index.ts resources, and add a Brazilian Portuguese overview
assertion in i18n.test.tsx.

Notes:
- Generic "pt" and any "pt-*" variant resolve to pt-BR. A future
  pt-PT locale can be added without affecting existing users.
- Universally borrowed technical terms (nanobot, BYOK, MCP, JSON,
  URL, Web, Apps when used as a product name, Skills) are kept in
  English, matching the pattern used by es/fr/ja/ko/vi/id.
- Empty-thread greetings, quick-action prompts, and slash command
  descriptions are translated; quick-action prompts are intentionally
  phrased so the agent still receives a clear task spec.

Verified with bun run test (536 passing), bun run lint (clean), and
bun run build (7.18s).
2026-07-13 23:28:19 +08:00
chengyongruandGitHub 4a3818e03c docs: update recent changes through July 12 (#4913) 2026-07-13 22:50:22 +08:00
chengyongruandchengyongru 276cbd947f docs: remove broken Star History embed 2026-07-13 18:28:22 +08:00
chengyongruandGitHub 234e895e5a fix(codex): align OAuth defaults and setup docs (#4910)
* fix(codex): align OAuth defaults and setup docs

* docs(codex): clarify provider settings key

* docs(codex): simplify OAuth setup guidance
2026-07-13 17:04:33 +08:00
chengyongruandGitHub 8c9110fee3 fix(dream): filter non-Dream history commits (#4905)
* fix(dream): filter non-Dream history commits

* fix(dream): resolve filtered commit diffs
2026-07-13 17:04:12 +08:00
chengyongruandGitHub e864fba522 fix: align optional dependency contracts (#4907)
* fix: align optional dependency contracts

* ci: avoid duplicate test suite

* test: drop removed langsmith assertions

* test: rely on generic extra coverage

* test: restore existing plugin coverage
2026-07-13 16:58:19 +08:00
Xubin Ren a65a6f334c test(gateway): cover slow health clients 2026-07-13 15:16:51 +08:00
Xubin Ren 3824206ab2 fix(gateway): harden health endpoint exposure 2026-07-13 15:16:51 +08:00
Xubin RenandGitHub 2c78976728 fix(cli): restore enter before webui prompts 2026-07-13 13:32:29 +08:00
Xubin RenandGitHub fe0717b385 feat(webui): add guided setup flows
* feat(channels): add guided setup flows

* test(channels): preserve setup config values

* fix(channels): reflect saved setup state

* refactor(channels): simplify setup state metadata

* fix(channels): harden setup lifecycle

* refactor(channels): centralize setup contracts

* fix(channels): route setup actions through webui shim

* fix(channels): adapt settings for compact screens

* fix(models): preserve default preset display

* feat(models): add curated Codex catalog

* fix(webui): stop attached gateway on interrupt

* fix(webui): simplify apps catalog

* docs(webui): clarify apps and runtime features

* feat(settings): add guided capability setup

* fix(webui): harden setup and managed services

* test: keep managed runtime checks portable

* test: scope POSIX runtime coverage

* fix(webui): simplify file settings

* feat(files): bundle document reading

* fix(webui): harden setup request boundaries

* fix(webui): prevent channel setup status squeeze

* fix(settings): group provider compatibility aliases

* refactor(settings): remove redundant setup surfaces

* fix(webui): harden guided setup lifecycle

* fix(webui): preserve channel setup compatibility
2026-07-13 13:11:46 +08:00
chengyongruandXubin Ren 791c7fd505 fix(memory): prune encoded Dream sessions 2026-07-13 12:07:29 +08:00
chengyongruandXubin Ren 6d406d93c9 fix(discord): route unauthorized DMs to pairing 2026-07-13 12:05:04 +08:00
Arthur K.andXubin Ren 053722a2a2 fix(heartbeat): rewrite prompt to execute tasks instead of reporting 2026-07-13 12:02:37 +08:00
Xubin Ren 45d1caba1d fix(webui): prevent stale workspace scope restore 2026-07-12 22:08:27 +08:00
Xubin Ren 89acea6fe1 fix(webui): allow remote workspace access reduction 2026-07-12 22:08:27 +08:00
Xubin Ren 01e4f3762a fix(agent): keep runtime context within its lifecycle 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren c339ce8bba refactor(agent): remove obsolete MCP prompt annotations 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 12b88d3872 docs(agent): summarize full my tool capability 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 8ccb2a451b docs(agent): advertise request metadata in my skill 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 20748bc4e3 perf(agent): load my skill on demand 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 93de413432 feat(agent): expose request routing metadata through my 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren d349b65713 test(agent): remove obsolete runtime context assertions 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 54b250430d fix(session): stop synthesizing MCP preset prompt context 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 5794d481c3 refactor(agent): remove MCP runtime context provider 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren e206ee4e70 refactor(agent): remove legacy image mode prompt injection 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 2eb7398f34 fix(agent): close runtime context persistence gaps 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren f75d3519db feat(agent): add persistent runtime context providers 2026-07-12 00:35:17 +08:00
chengyongruandXubin Ren 7f8c3453e1 refactor(agent): gate sustained goals behind explicit /goal
Replace the legacy long-goal skill contract with command-scoped goal tools and runtime guidance. Keep goal state durable across continuations while restricting create and replace mutations to explicit user /goal turns.
2026-07-12 00:35:17 +08:00
Xubin Ren edf78e7054 fix(mcp): keep transport cleanup in owner tasks 2026-07-11 11:45:20 +08:00
chengyongruandXubin Ren bd0dd85f44 test: isolate MCP reconnect DNS transport
Maintainer edit: the real MCP reconnect regression test can bind the class-level PinnedDNSAsyncTransport lock to its pytest event loop. Patch the MCP module to use a test-local transport subclass so later async tests do not inherit that loop-bound lock.
2026-07-11 11:45:20 +08:00
469d004773 test: add MCP reconnect crash regression
maintainer edit: port the real streamable-http idle-timeout reproduction from #4764 so this PR carries regression coverage for #4302's gateway crash path.

Co-authored-by: tjc0726 <49085201+tjc0726@users.noreply.github.com>
2026-07-11 11:45:20 +08:00
flyzstuandXubin Ren f3d1b9ca2d fix(mcp): defer stale stack cleanup during reconnect 2026-07-11 11:45:20 +08:00
Xubin Ren c111aaa7ee fix(dream): gate periodic commits on content changes 2026-07-11 11:16:59 +08:00
Aleksander W. Oleszkiewicz (Alek)andXubin Ren 9adcd3d923 adding tests to prevent regression 2026-07-11 11:16:59 +08:00
Aleksander W. Oleszkiewicz (Alek)andXubin Ren 0a1c98c142 Dream jobs don't create git commits if there were no changes
fixes #4872
2026-07-11 11:16:59 +08:00
chengyongruandXubin Ren 7675364eae fix(tools): enforce edit_file line hints 2026-07-11 01:14:50 +08:00
chengyongruandXubin Ren 052fdc132d feat(tools): guard edit_file target lines 2026-07-11 01:14:50 +08:00
chengyongruandXubin Ren 47d498bab0 fix(webui): disarm queued prompt for voice shortcut 2026-07-11 01:02:14 +08:00
chengyongruandXubin Ren 04328f8129 feat(webui): guide queued prompt with second Enter 2026-07-11 01:02:14 +08:00
chengyongruandXubin Ren 137fbf875e fix(webui): keep syntax highlighting chunks acyclic 2026-07-11 00:57:37 +08:00
chengyongruandXubin Ren 1ee4349a08 feat(webui): highlight file previews and diffs 2026-07-11 00:57:37 +08:00
Eric YangandXubin Ren 9a1d1e64c7 fix(shell): harden kill path and add zombie reap tests
Skip process.kill() when returncode is already set so generic exception
handlers after a successful communicate() cannot raise ProcessLookupError.
Suppress race kill failures and still run the safety-net reap.

Add unit and integration coverage for owned-PID reaping on normal exit,
timeout, exception, and exec-session kill/poll paths.
2026-07-10 20:19:44 +08:00
Eric YangandXubin Ren a1fbfd9f7b fix(shell): drop gateway-wide waitpid(-1) zombie reaper
A global reaper can race asyncio's child watcher for just-exited
create_subprocess_exec children, causing Process returncode 255 instead
of the real command status. Keep only owned-PID reaps after wait/communicate
/kill paths in shell and exec_session.

Addresses review feedback on #4840.
2026-07-10 20:19:44 +08:00
Eric YangandXubin Ren bda0c099ab fix(shell): guard _reap_pid on os.waitpid availability
Windows CI runs Unix-path unit tests by patching _IS_WINDOWS=False while
still on win32, where os.WNOHANG/os.waitpid do not exist. Use capability
checks so reaping is a no-op on platforms without waitpid rather than
trusting the (mockable) platform flag.
2026-07-10 20:19:44 +08:00
Eric YangandXubin Ren ef14d1ea92 fix(shell): remove unused os import in exec_session
Ruff F401 failed CI on the zombie-reap PR; reaping uses shell._reap_pid
so os is not needed in this module.
2026-07-10 20:19:44 +08:00
Eric YangandXubin Ren c9e014fdea fix(shell): reap zombie processes on all subprocess exit paths
The previous fix (dbcc7cb5) only added os.waitpid() to _kill_process(),
covering the timeout/cancel path of one-shot exec. Zombies continued to
accumulate because several other exit paths never reaped children:

- _ExecSession.kill(): sent SIGKILL + process.wait(5s) but had no
  os.waitpid() fallback if the wait timed out
- ExecTool.execute() generic exception handler: leaked the subprocess
  if communicate() raised an unexpected error
- Normal completion paths: relied entirely on asyncio's child-watcher,
  which can miss exits inside Docker containers (pidfd/SIGCHLD gaps)

Changes:
- Extract _reap_pid() helper for consistent, safe os.waitpid(WNOHANG)
- Add _reap_pid() fallback to _ExecSession.kill() via try/finally
- Add _reap_pid() safety-net after normal process exit in both
  ExecTool.execute() and _ExecSession.poll()
- Kill + reap subprocess in the generic except Exception handler
- Add periodic zombie reaper background task (every 30s) in the
  gateway as a last line of defense
2026-07-10 20:19:44 +08:00
sidandXubin Ren d32f8961b1 fix(webui): bind landing first message to created chat 2026-07-10 20:19:10 +08:00
chengyongruandXubin Ren 45a6466c2c style: trim CSI-u shortcut comments
Maintainer edit: simplify the explanatory comments for the CSI-u shortcut while preserving the existing behavior and regression coverage.
2026-07-10 19:32:47 +08:00
99e04c2da2 fix(cli): handle CSI-u Shift+Enter instead of dumping raw escapes
Terminals speaking the CSI-u (kitty / fixterms) keyboard protocol -- kitty,
Ghostty, WezTerm, and terminal panes that default to it -- encode Shift+Enter
as the escape sequence "\x1b[13;2u". prompt_toolkit 3.0 has no support for
that protocol and no default mapping for the sequence, so its Vt100Parser
fails to recognise it and dumps the raw bytes ("^[[13;2u") straight into the
prompt buffer. The multiline-input work kept only Alt+Enter, so on these
terminals Shift+Enter now leaks visible escape garbage into the input.

Register "\x1b[13;2u" (absent from prompt_toolkit's default ANSI_SEQUENCES,
so setdefault() overrides nothing) and bind it to insert a newline, matching
the Alt+Enter behaviour. This is best-effort: prompt_toolkit cannot negotiate
the protocol, so we only react to a CSI-u sequence a terminal already emits;
terminals that collapse Shift+Enter into plain Enter fall back to Alt+Enter,
which stays the primary shortcut.

Add a real-PromptSession regression test asserting the sequence inserts a
newline rather than leaking raw escape bytes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 19:32:47 +08:00
NOKIAOandXubin Ren 87602a74ea narrower cert path 2026-07-10 19:32:23 +08:00
NOKIAOandXubin Ren ad55f3ce37 添加红帽系Linux的证书路径支持 2026-07-10 19:32:23 +08:00
Siddhant LondheandXubin Ren e284592649 fix(webui): sync package-lock.json to resolve docker build failure 2026-07-10 19:31:58 +08:00
chengyongruandXubin Ren 2154dc51d0 docs: add automation guide 2026-07-10 19:31:33 +08:00
chengyongruandXubin Ren fe7d94359b fix(agent): preserve runtime compatibility contracts 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 10930f3902 Revert "test(agent): probe runtime change amplification"
This reverts commit 85c73779f9.
2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 6b7470646f test(agent): probe runtime change amplification 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 21f58cbabf refactor(agent): make resolver sole runtime owner 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren c9d3e74342 refactor(agent): require runtime for consolidation 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 5bd3d1e0af refactor(agent): centralize runtime default mutations 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren af85c356b8 refactor(agent): capture subagent runtime before spawn 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 198fd9f869 refactor(agent): capture runtime at turn admission 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 45ace23580 test(agent): assert subagent runtime generation 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren b4f069800e refactor(agent): make runner consume required runtime 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 3f8170e835 test(agent): characterize active runner provider drift 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren cb03d2c748 refactor(agent): snapshot generation without provider mutation 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren bd94fefd1a refactor(agent): introduce immutable model runtime resolver 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 42d7ad34a4 refactor(agent): unify request context routing 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren bb3b449e09 refactor(agent): capture original user text per turn 2026-07-10 17:54:34 +08:00
chengyongruandXubin Ren 55317094b6 test(agent): characterize request context isolation 2026-07-10 17:54:34 +08:00
David JimenezandXubin Ren 6313ae9f4f add Dockerfile arg to override optional Python dependencies to install at build time 2026-07-09 23:58:59 +08:00
chengyongruandXubin Ren 4137be62a1 fix(matrix): preserve mxc markdown image sources 2026-07-09 23:58:26 +08:00
chengyongruandXubin Ren 0b9ca744c2 docs(webui): mention file edit previews in guide 2026-07-09 10:42:43 +08:00
chengyongruandXubin Ren 7685a89dcc docs(webui): describe file edit diffs 2026-07-09 10:42:43 +08:00
chengyongruandXubin Ren bbd4f4054b fix(webui): respect full access in file preview 2026-07-09 10:42:43 +08:00
chengyongruandXubin Ren 0ae28571e7 fix(agent): close file edit activity on cancellation 2026-07-09 10:42:43 +08:00
chengyongruandXubin Ren 6851a6ebd4 fix(webui): sync file edit display preference 2026-07-09 10:42:43 +08:00
chengyongruandXubin Ren 7768672c5b feat: add file edit diff progress view
Capture file edit snapshots through runner tool lifecycle hooks and render unified diffs in the WebUI with folding and truncation controls.
2026-07-09 10:42:43 +08:00
chengyongruandXubin Ren 207813d3b5 fix(webui): tighten localhost bootstrap check 2026-07-09 10:42:00 +08:00
chengyongruandXubin Ren e0c2d28f90 fix(webui): issue localhost bootstrap api tokens 2026-07-09 10:42:00 +08:00
chengyongruandXubin Ren 8559458258 refactor(agent): add turn hook factories 2026-07-08 21:02:12 +08:00
chengyongruandXubin Ren 04dbf17426 test(agent): cover turn hook ordering 2026-07-08 21:02:12 +08:00
chengyongruandXubin Ren a52a88455b refactor(agent): extract turn hook assembly 2026-07-08 21:02:12 +08:00
Xubin Ren 3ab09075c5 test(webui): tolerate wrapped bootstrap CLI output 2026-07-08 21:01:48 +08:00
chengyongruandXubin Ren 4ddd639e67 fix(webui): route missing API bootstrap tokens to auth
maintainer edit: handle review feedback by treating bootstrap responses without api_token as auth-required, and remove the obsolete issue_token(api_token=...) compatibility path now that API tokens are issued separately.
2026-07-08 21:01:48 +08:00
chengyongruandXubin Ren 444f488563 fix(webui): repair bootstrap secret launch paths 2026-07-08 21:01:48 +08:00
chengyongruandXubin Ren 88143a8bf0 fix(webui): gate bootstrap API token issuance 2026-07-08 21:01:48 +08:00
chengyongruandXubin Ren 7204d88a4c docs: add high-usage chat app guides 2026-07-08 20:56:27 +08:00
chengyongruandXubin Ren 1a21542d11 docs: address search entry review feedback 2026-07-08 20:56:27 +08:00
chengyongruandXubin Ren f531f1ce38 docs: improve search entry pages 2026-07-08 20:56:27 +08:00
chengyongruandXubin Ren 941a2541eb docs: document onboard refresh flag
maintainer edit: add CLI, quick start, and troubleshooting docs for the non-interactive config refresh flow introduced by this PR.
2026-07-08 20:56:06 +08:00
Aleksander W. Oleszkiewicz (Alek)andXubin Ren be8ac1e484 removed duplicated code 2026-07-08 20:56:06 +08:00
Aleksander W. Oleszkiewicz (Alek)andXubin Ren f074aa7d80 feat: add --refresh flag to onboard command for non-interactive config updates 2026-07-08 20:56:06 +08:00
chengyongruandXubin Ren ea7f4679f1 fix(webui): keep prompt rail at original gutter offset 2026-07-08 12:16:47 +08:00
chengyongruandXubin Ren c188e96f4e refactor(webui): use container query for prompt rail layout 2026-07-08 12:16:47 +08:00
chengyongruandXubin Ren 815f15993c test(webui): dedupe prompt rail viewport setup 2026-07-08 12:16:47 +08:00
chengyongruandXubin Ren 4333d6f103 fix(webui): keep prompt rail out of narrow chat columns 2026-07-08 12:16:47 +08:00
Aleksander W. Oleszkiewicz (auticon)andXubin Ren 65d32ffd6c Fix dependency assertions in tests
Added a new `aiohttp` dependency for Slack
2026-07-08 12:16:30 +08:00
Aleksander W. Oleszkiewicz (auticon)andXubin Ren 379785d365 Fix missing aiohttp slack dependency in pyproject.toml
Added `"aiohttp>=3.9.0,<4.0.0"` to the dependencies for **slack**
2026-07-08 12:16:30 +08:00
chengyongruandXubin Ren 883776358e fix: keep local api serve unauthenticated
maintainer edit: Align OpenAI-compatible API auth with the WebSocket channel boundary: loopback serve remains usable without a key, while wildcard binds still fail before agent initialization unless api.api_key is configured.
2026-07-08 12:16:12 +08:00
chengyongruandXubin Ren 28141ce20b docs: update serve api key requirement
maintainer edit: Align OpenAI-compatible API docs and examples with the new fail-closed api.api_key requirement while keeping /health documented as unauthenticated.
2026-07-08 12:16:12 +08:00
chengyongruandXubin Ren 460c62c0b0 fix: validate api key before serve setup
maintainer edit: Check api.api_key before template sync and AgentLoop construction so missing-key startup errors are not hidden by provider or workspace initialization failures.
2026-07-08 12:16:12 +08:00
hamb1yandXubin Ren e86133c434 fix: require api auth in server factory 2026-07-08 12:16:12 +08:00
hamb1yandXubin Ren 6c59332a8a fix: require api key for serve 2026-07-08 12:16:12 +08:00
chengyongruandXubin Ren a7b8a9ed46 fix(webui): clarify new chat command text 2026-07-07 15:42:04 +08:00
chengyongruandXubin Ren 7e135b45f3 docs(webui): document slash command lifecycles 2026-07-07 15:42:04 +08:00
chengyongruandXubin Ren fa73448f6f fix(webui): drive slash command routing from metadata 2026-07-07 15:42:04 +08:00
chengyongruandXubin Ren 8a231b6e4d fix(webui): finalize turn-ending slash commands
maintainer edit: keep /new and manually submitted /stop from leaving stale WebUI streaming state after they cancel or reset the active turn.
2026-07-07 15:42:04 +08:00
chengyongruandXubin Ren ef5318ebdc fix(webui): classify builtin slash commands without metadata
maintainer edit: keep builtin shortcut commands on the side-channel path before async command metadata loads, while preserving /goal task text as a normal agent turn.
2026-07-07 15:42:04 +08:00
chengyongruandXubin Ren 8f68040f05 fix(webui): keep slash commands out of streaming state 2026-07-07 15:42:04 +08:00
chengyongruandXubin Ren 0f88927364 fix(webui): show generic tool arguments in activity 2026-07-07 15:41:45 +08:00
chengyongruandXubin Ren 3f33ff3143 chore: remove unused dead code 2026-07-07 15:41:27 +08:00
chengyongruandXubin Ren 29e99d3742 docs: document Alt+Enter multiline input
maintainer edit: document the supported interactive CLI multiline shortcut and trim comments left after removing Shift+Enter support.
2026-07-07 15:41:08 +08:00
chengyongruandXubin Ren 01a0f5aaf3 fix: remove unreliable Shift+Enter shortcut
maintainer edit: keep Alt+Enter as the supported multiline input path and remove the terminal-dependent Shift+Enter ANSI sequence patch.
2026-07-07 15:41:08 +08:00
77a6003255 fix(cli): make Alt+Enter insert a newline on LF-as-Enter terminals
On terminals that send a bare LF for plain Enter (WSL is the case
prompt_toolkit itself calls out), Alt+Enter arrives as ESC + LF
("\x1b\x0a" = Escape + ControlJ), not the ESC + CR the existing
"escape","enter" binding matches. The Escape was swallowed and the bare
LF hit prompt_toolkit's default submit, so the documented "universally
supported" Alt+Enter newline fallback failed on exactly the terminal path
plain Enter is preserved for.

Bind ESC + ControlJ to insert a newline too, and add a real-PromptSession
regression test covering the WSL Alt+Enter path.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 15:41:08 +08:00
25a477050d fix(cli): make the xterm modifyOtherKeys Shift+Enter encoding insert a newline
"\x1b[27;2;13~" (the older xterm modifyOtherKeys / rxvt encoding of
Shift+Enter) is already registered by prompt_toolkit by default -- as
Keys.ControlM, i.e. plain Enter/submit. The previous `setdefault()` call was
therefore a silent no-op against it: this Shift+Enter variant kept behaving
like a submit instead of inserting a newline, even after the ControlJ/WSL
fix, since setdefault only sets missing keys.

Assign directly to override that default for both known Shift+Enter
sequences, since inserting a newline is the whole point of the binding.
Add a regression test driving a real PromptSession/parser with this exact
sequence, since a mocked-buffer test can't observe prompt_toolkit's default
ANSI_SEQUENCES entries taking priority.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 15:41:08 +08:00
ea0516e655 fix(cli): stop hijacking ControlJ for Shift+Enter, it breaks Enter on WSL
Keys.ControlJ is also the literal LF byte ("\x0a") that some terminals send
for a plain Enter keypress -- prompt_toolkit's own default bindings handle
this by re-feeding it as ControlM/submit, and calls out WSL by name as the
case that needs it. Binding our Shift+Enter handler to ControlJ shadowed
that default, so on any terminal sending LF for Enter, pressing Enter only
ever inserted a newline and the prompt could never be submitted.

Register the CSI-u Shift+Enter sequences against Keys.ControlF3 instead: an
enum member prompt_toolkit declares but never wires to a default ANSI
sequence or key binding, so it's only reachable through our own mapping.

Also add a regression test that drives a real PromptSession/Vt100Parser
with a raw LF byte -- the existing key-binding test invoked handlers
directly against a mocked buffer, which exercises the handler logic but not
prompt_toolkit's key-resolution precedence, so it couldn't have caught this.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-07 15:41:08 +08:00
wangjunweiandXubin Ren 18a230de75 feat(cli): support multiline input via Shift+Enter / Alt+Enter
The interactive prompt used a single-line buffer (multiline=False), so
there was no way to compose a multi-line message before submitting.

Switch to a multiline-capable buffer with custom key bindings: Enter still
submits (unchanged feel), Alt+Enter always inserts a newline, and
Shift+Enter inserts a newline on terminals that emit a distinguishable
CSI-u sequence for it (kitty, iTerm2 with the fixterms protocol) by mapping
those sequences onto the otherwise-unused ControlJ key.
2026-07-07 15:41:08 +08:00
chengyongruandXubin Ren c5e053f83b fix: pin validated DNS for SSRF-safe fetches
maintainer edit: keep MCP HTTP SSRF checks strict, pin validated DNS for direct web_fetch and HTTP/SSE MCP requests, preserve explicit and environment proxy compatibility, and cover the proxy/redirect/rebinding cases with tests.
2026-07-07 15:40:53 +08:00
hamb1yandXubin Ren b68ae4f9bc fix: reject proxied pinned web fetches 2026-07-07 15:40:53 +08:00
hamb1yandXubin Ren 97e3b360c2 fix: serialize pinned dns web fetches 2026-07-07 15:40:53 +08:00
hamb1yandXubin Ren 4353f4680b fix: allow local mcp urls with pinned dns 2026-07-07 15:40:53 +08:00
hamb1yandXubin Ren 73bf299a59 fix: pin validated dns for ssrf checks 2026-07-07 15:40:53 +08:00
Xubin Ren d04ad1a5b4 fix(gateway): resolve runtime config path for state refresh 2026-07-06 15:55:15 +08:00
dajiaohuangandXubin Ren 67b56cba74 @
fix(gateway): self-heal state file PID on server startup

After /restart on Windows, the gateway process gets a new PID (os.execv
creates a new process on Windows), but the state file at
run/gateway.<suffix>.json still contains the old PID from the initial
background spawn.  Nothing rewrites it, leaving state inconsistent.

Add GatewayRuntime.refresh_state_pid() — a classmethod that reads the
existing state file, updates the PID and identity to the current
process, and writes atomically.  Call it early in _run_gateway() so the
state file is always correct regardless of how the process was started
(initial spawn, os.execv, or subprocess.Popen).

On POSIX os.execv preserves the PID, so this is a no-op in normal
operation there, but still beneficial after any unusual restart path.

Fixes #4511
@
2026-07-06 15:29:11 +08:00
Kenneth ZhaoandXubin Ren 105230cc34 fix(cli): print response text when streaming fails in interactive mode 2026-07-06 15:28:10 +08:00
chengyongruandXubin Ren dd014b50a7 docs(mattermost): finish channel ordering cleanup
Maintainer edit: move remaining Mattermost documentation mentions to the end of named channel lists.
2026-07-06 12:14:57 +08:00
chengyongruandXubin Ren 595d789c6f docs(mattermost): list new channel last
Maintainer edit: keep Mattermost at the end of documented channel lists so existing channel order remains first-come-first-served.
2026-07-06 12:14:57 +08:00
chengyongruandXubin Ren cf35238834 fix(mattermost): harden channel lifecycle and streaming
Maintainer edit: keep the Mattermost adapter running under the gateway, fail closed when team filtering cannot verify the team, isolate new thread sessions immediately, and make buffered stream finalization retry-safe.
2026-07-06 12:14:57 +08:00
Kenneth ZhaoandXubin Ren ef9780719d style: fix import ordering in mattermost tests 2026-07-06 12:14:57 +08:00
Kenneth ZhaoandXubin Ren cc70a2a79f fix(mattermost): fix file download paths and mobile streaming
- Use Mattermost file metadata/download API paths that work with current servers
- Buffer streamed content and post the final reply once for mobile clients that ignore post edits
- Keep attachment upload behavior on the first split chunk
2026-07-06 12:14:57 +08:00
Kenneth ZhaoandXubin Ren f9806cc60f fix(mattermost): address second round of review feedback
- Send pairing code response (not empty message) for denied DMs
- Resolve actual channel type in action events before permission check
- Use word-boundary regex in _is_mentioned to avoid partial matches
- Use safe_filename for download path sanitization
- Add tests: denied DM pairing, denied action event, is_mentioned boundary
2026-07-06 12:14:57 +08:00
Kenneth ZhaoandXubin Ren 76877036f7 mattermost: remove unused _BOT_MENTION_RE 2026-07-06 12:14:57 +08:00
Kenneth ZhaoandXubin Ren a710a7d6f7 fix(mattermost): address review comments
- Attachments now only attached to first chunk when message is split
- Filename sanitized with Path(name).name to prevent path traversal
- Updated streaming tests to match buffer-and-post-at-end pattern
  (iOS compatibility)
2026-07-06 12:14:57 +08:00
Kenneth ZhaoandXubin Ren fff38f11a7 feat: add Mattermost channel support 2026-07-06 12:14:57 +08:00
chengyongruandXubin Ren 5e51c5014f feat(feishu): render new session divider
maintainer edit: remove out-of-scope reasoning panel changes and keep this PR focused on the /new session divider.
2026-07-06 12:14:54 +08:00
Xubin Ren 937f04ac86 docs(config): document canonical OpenCode provider 2026-07-06 12:13:00 +08:00
hamb1yandXubin Ren 9eade9be5f test: update quick start provider expectations 2026-07-06 12:13:00 +08:00
hamb1yandXubin Ren 400369f0b0 feat: support canonical opencode provider 2026-07-06 12:13:00 +08:00
Kenneth ZhaoandGitHub f0c989ba2d fix(dream): ground memory audit records in the real git diff (#4673)
* fix(dream): ground commit messages and cursor advance in the real git diff

Dream consolidation could emit a /dream-log audit record that did not match
the actual file changes: build_dream_commit_message appended the LLM's
unverified resp.content, dream_run_completed only checked the stop reason, and
file contents were deliberately omitted from the prompt. The combination let a
single-turn self-report become the durable audit record.

- gitstore: add summarize_working_tree() — a structured, machine-derived
  summary (per-file +N/-M, totals, capped unified diff) of working-tree
  changes vs HEAD. Pure filesystem/git ground truth, never LLM narrative.
- memory: build_dream_commit_message now takes the diff body instead of resp;
  dream_content_diff() exposes the real delta over SOUL/USER/MEMORY.md only
  (excludes .dream_cursor so cursor writes aren't mistaken for edits);
  build_dream_prompt embeds current file contents so the model edits reality,
  not a stale mental model.
- builtin/cli: both Dream paths now compute the diff, gate cursor advance on
  a non-empty delta (no-op runs no longer swallow history), and commit with
  the diff-grounded message. Non-git workspaces fall back to the completion
  check.
- dream.md: document that contents are embedded, and add a chain-of-
  verification guardrail so the model's summary cannot claim unmade edits.

A regression test proves a lying resp.content never reaches the audit log
while the real diff does.

* fix(dream): mark non-UTF-8 memory files as binary in diff summary

Address review feedback (Q1 on PR #4673): summarize_working_tree read
working-tree files with errors="replace", which would emit U+FFFD
replacement chars into the audit record if a memory file ever held
invalid UTF-8 — misrepresenting the diff it is meant to make truthful.

Switch to errors="strict" and catch UnicodeDecodeError: a non-UTF-8
(or binary/corrupt) file is now recorded as "{path}: binary or
non-UTF-8 file changed" and omitted from the unified diff, so the
audit record stays honest. An empty diff block is also suppressed when
all changes are binary.

Adds a defensive regression test asserting no replacement char leaks.
2026-07-06 12:12:55 +08:00
70505bd1fc fix(webui): finish mobile containment for inline code, tables, chips, user bubbles
57f9ec0 added a CSS containment safety net for .markdown-content, but
several rendering paths still overflowed or truncated on narrow viewports
because they bypass those rules or actively disable wrapping:

- Inline code longer than 120 chars renders as `block whitespace-pre`
  with no scroll container, so it bled past the viewport (white-space:pre
  defeats overflow-wrap). It now scrolls inside its own box via
  max-w-full overflow-x-auto.
- Wide markdown tables never actually scrolled: Tailwind Typography forces
  width:100% + table-layout:auto on .prose table, so they shrank to fit
  instead of overflowing. Switched to a wrapper-<div> pattern (a custom
  `table` component, the approach used by DeepSeek/others) with min-w-max
  so wide tables keep natural column widths and scroll inside the
  conversation column; the old display:block rule on .markdown-content
  table is removed.
- File-reference chips and inline link-preview cards used `truncate`, so
  long filenames/labels were ellipsized to one line. Now
  [overflow-wrap:anywhere] sm:truncate — wrap on mobile, truncate on
  desktop.
- User-authored message bubbles don't pass through .markdown-content, so
  a long URL in the user's own message still burst the screen: under flex
  min-width:auto, break-words cannot reduce the item's min-content width.
  Added max-w-full min-w-0 + [overflow-wrap:anywhere].

No JS/agent/provider behavior touched. Desktop layout is unchanged — the
new rules only engage when content would otherwise overflow.

Verified: bun run lint (clean), bun run test (438 passed), bun run build.

Refs #4693

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-06 12:11:43 +08:00
162b6ee5bd fix(webui): keep chat viewport and composer inside narrow viewports
On mobile-width browsers the conversation column and bottom composer could
be forced wider than 100vw: long markdown (URLs, branch names, file paths),
fenced code, and tables stretched the prose container, and the thread scroll
area let the overflow bleed horizontally (#4693).

Add a pure-CSS containment safety net in globals.css:
- .markdown-content gets min-width:0, max-width:100%, overflow-wrap:anywhere
  so long tokens wrap instead of stretching the column.
- long links and inline code break rather than overflow.
- fenced/pre blocks and markdown tables scroll inside their own box.
- the thread scroll column clips residual horizontal bleed (overflow-x:hidden)
  while vertical scroll and internal code-block scroll are unaffected.

No component, JS, or agent-loop behavior touched; desktop layout unchanged.

Fixes #4693

Co-Authored-By: Claude <noreply@anthropic.com>
2026-07-06 12:11:43 +08:00
Xubin Ren b1d29ede7d test(mcp): cover limited enabledTools names 2026-07-06 12:11:37 +08:00
ThomasZP YangandXubin Ren 800d51ecac fix: align MCP tool matching with limited names 2026-07-06 12:11:37 +08:00
ThomasZP YangandXubin Ren 3f9fb63d4c fix: limit long MCP-derived tool names 2026-07-06 12:11:37 +08:00
Xubin Ren 1cfa48ad4a fix(web-search): return structured Serper errors 2026-07-06 12:11:31 +08:00
franciscomaestreandXubin Ren 8a42a9c73a feat(web-search): add Serper.dev (Google Search API) provider
Add 'serper' as a web search backend, following the existing provider
pattern (keenable/exa): POST to https://google.serper.dev/search with the
X-API-KEY header, map the 'organic' results into the shared result format,
and fall back to DuckDuckGo when no key is configured.

- key resolved from config.api_key or SERPER_API_KEY env var
- 429 handled with a rate-limit message; other HTTP errors surfaced
- tests cover success, env-key, no-key fallback, HTTP error and rate limit
- docs: add Serper config example and list it in tools.web.search providers
2026-07-06 12:11:31 +08:00
chengyongruandXubin Ren 72c8a47ac9 docs: update Windows exec shell gotcha
Maintainer edit: document that Windows exec defaults to PowerShell and cmd.exe syntax now requires shell='cmd'.
2026-07-06 12:11:25 +08:00
chengyongruandXubin Ren 122cf4213b fix: harden Windows exec shell edge cases
Maintainer edit: preserve raw cmd.exe quoting for shell='cmd', propagate native exit codes through the default PowerShell path, and keep quoted Windows executable paths invokable under PowerShell.
2026-07-06 12:11:25 +08:00
chengyongruandXubin Ren 8c4a74ee3c fix: honor explicit Windows cmd shell path
Maintainer edit: launch explicit cmd shells as cmd.exe /c so COMSPEC or absolute cmd.exe paths are actually used.
2026-07-06 12:11:25 +08:00
chengyongruandXubin Ren 4ec111c1a9 docs: clarify exec shell override guidance
Maintainer edit: make the shell parameter description explain defaults and when to override instead of only listing shell names.
2026-07-06 12:11:25 +08:00
chengyongruandXubin Ren 8222f3c85f docs: tailor exec shell guidance by platform
Maintainer edit: keep Windows PowerShell guidance out of Unix tool descriptions and cover the exposed schema text.
2026-07-06 12:11:25 +08:00
chengyongruandXubin Ren d76493a63a docs: clarify Windows exec shell syntax
Maintainer edit: document that Windows exec commands use PowerShell syntax by default and shell='cmd' is the cmd-specific escape hatch.
2026-07-06 12:11:25 +08:00
chengyongruandXubin Ren 220de320fb fix: harden Windows exec shell default
Maintainer edit: prefer pwsh when available so single-line commands support modern PowerShell operators, add -NonInteractive, and parse explicit cmd.exe paths with Windows path semantics for cross-platform tests.
2026-07-06 12:11:25 +08:00
dajiaohuangandXubin Ren 33b1c6f601 @
fix(exec): default Windows commands to PowerShell and allow shell parameter

Single-line commands on Windows were routed through cmd.exe
(asyncio.create_subprocess_shell) while multi-line commands used
PowerShell. This caused cross-drive cd failures, missing $VAR expansion,
and inconsistent behavior depending on whether a command contained a
newline. The shell parameter was also rejected on Windows.

- Route all Windows commands through PowerShell by default so single-line
  and multi-line commands share the same shell semantics.
- Allow the shell parameter on Windows: accepts powershell, pwsh, or cmd.
- cmd.exe remains reachable via shell="cmd" as an explicit escape hatch.
- Update tests to cover the new default and shell-parameter paths.

Fixes #4544
@
2026-07-06 12:11:25 +08:00
hamb1yandXubin Ren 10b52cfb3a fix: resolve builtin skill reads 2026-07-06 12:11:20 +08:00
hamb1yandXubin Ren 5d034dc79c fix: isolate matrix stream buffers 2026-07-06 12:11:14 +08:00
hamb1yandXubin Ren b8d7708171 fix: normalize text tool call markup 2026-07-06 12:11:08 +08:00
Xubin Ren e725649146 test(webui): cover OAuth kit missing errors 2026-07-06 12:11:03 +08:00
axelray-devandXubin Ren 6a95877196 fix(providers): standardize oauth_cli_kit error messages across CLI and WebUI 2026-07-06 12:11:03 +08:00
Xubin Ren 83e4bae7db fix(gateway): skip ctrl-break wait when signal is rejected 2026-07-04 21:25:46 +08:00
xcaoandXubin Ren 58b5bb9204 fix(gateway): handle Windows stop fallback 2026-07-04 21:25:46 +08:00
chengyongruandXubin Ren c579551bb1 fix(dingtalk): stop stream task on shutdown 2026-07-04 21:19:25 +08:00
yorkhellenandXubin Ren 8b645135bc fix(pairing): restore durable atomic writes 2026-07-04 21:19:19 +08:00
axelray-devandXubin Ren 28011413bc fix(copilot): guard token refresh with asyncio.Lock to prevent race condition
_get_copilot_access_token had a check-then-act race: concurrent chat()
calls after token expiry both fetched new tokens and clobbered each other.
Add asyncio.Lock with double-checked locking so only one fetch happens
per expiry window.

Closes #4677
2026-07-04 21:19:12 +08:00
chengyongruandXubin Ren 614ea86a81 test: align MCP transient reconnect coverage
maintainer edit: update the existing transient retry tests for reconnect-first behavior and keep structured retry-failure coverage in the focused MCP transient suite.
2026-07-04 21:15:18 +08:00
chengyongruandXubin Ren 6d28db3248 fix: reconnect MCP sessions on transient stream failures
maintainer edit: treat transient MCP stream failures as dead sessions so the existing reconnect handler can refresh the session before retrying. Also cover retry failure as a structured tool error.
2026-07-04 21:15:18 +08:00
Yuxin LouandXubin Ren 0d1221bece fix(mcp): contain malformed tool results 2026-07-04 21:15:18 +08:00
Xubin Ren 8b9f93d7d1 test(config): lock model presets alias serialization 2026-07-04 11:44:28 +08:00
Yuxin LouandXubin Ren a119c35b1e fix(config): serialize model presets as camelCase 2026-07-04 11:44:28 +08:00
Xubin RenandGitHub 067e0c4a40 feat(cli): add safe WebUI first-run launcher (#4688) 2026-07-03 18:58:04 +08:00
5283ceae85 Add optional Nanobot plugin controls (#4396)
* feat: add optional nanobot features

* test: update azure install hint expectation

* fix: validate optional feature extras

maintainer edit: verify requested dependency extras before treating optional features as installed, propagate restart state from feature enablement, and align docs with the new plugins enable command.

* fix: bound optional feature installs

maintainer edit: make optional feature installs time out as a normal install failure instead of leaving the WebUI or CLI action waiting indefinitely.

* feat: slim optional channel dependencies

* fix: log optional install commands

* fix(webui): gate remote feature installs

* docs: clarify webhook plugin example

* fix(webui): harden optional feature installs

* fix: install optional deps without package fallback

* fix(cli): refine plugin feature controls

* fix(webui): count enabled nanobot features

* fix(webui): allow slow feature install routes

* fix(webui): allow disabling websocket channel

* fix(plugins): simplify optional feature controls

* fix(webui): polish apps catalog states

* fix(webui): confirm nanobot support installs

* fix(webui): polish nanobot install dialog

* fix(webui): suppress empty websocket handshakes

* fix(webui): clarify apps plugin summary

* fix(webui): localize workspace access copy

* fix(plugins): polish optional feature controls (#4691)

---------

Co-authored-by: Xubin Ren <52506698+Re-bin@users.noreply.github.com>
2026-07-03 18:17:52 +08:00
Hamb_yandGitHub 00cc0da530 fix(providers): omit temperature for sonnet 5
Add sonnet-5 to the Anthropic omit-temperature model families and cover adaptive, enabled, and non-thinking request paths.

Fixes #4683
2026-07-03 15:48:46 +08:00
LILACandGitHub b19a744110 fix(providers): update Anthropic default model to claude-sonnet-4-6
Update the Anthropic provider default model and matching docs/tests from claude-sonnet-4-20250514 to claude-sonnet-4-6.

Fixes #4675
2026-07-03 15:46:19 +08:00
Xubin Ren c9c69e4316 fix(memory): cap workspace Dream prompt overrides 2026-07-03 00:41:51 +08:00
chengyongruandXubin Ren 8a79eb1aaa fix(memory): clarify Dream prompt init UX 2026-07-03 00:41:51 +08:00
chengyongruandXubin Ren 979f038ded fix(channels): align Dream prompt Telegram copy 2026-07-03 00:41:51 +08:00
chengyongruandXubin Ren f38fd7d5d3 feat(memory): add workspace Dream prompt override 2026-07-03 00:41:51 +08:00
chengyongruandXubin Ren 5af22042ec fix(trigger): keep local worker alive on turn cancel 2026-07-03 00:36:29 +08:00
chengyongruandXubin Ren aecb5fbc33 fix(agent): avoid tool compaction echo loops 2026-07-03 00:36:22 +08:00
chengyongruandXubin Ren 34535b4e7c fix(webui): hide subagent backfill payloads 2026-07-02 14:36:23 +08:00
Stellar鱼andXubin Ren 5abe06f808 test: cover runner blocked tool-call finish reasons 2026-07-02 14:36:18 +08:00
yu-xin-candXubin Ren 64c7ff5fdc test(cron): cover stale instance mutation consistency 2026-07-02 14:36:12 +08:00
chengyongruandXubin Ren 54bcdb5a62 fix(exec): return early when session command exits 2026-07-02 14:36:06 +08:00
754 changed files with 59778 additions and 10041 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ Example valid usage:
## Windows Compatibility
nanobot explicitly supports Windows. Key differences to keep in mind:
- `ExecTool` 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.
+33 -7
View File
@@ -19,14 +19,25 @@ permissions:
jobs:
test:
name: Python (${{ matrix.name }})
runs-on: ${{ matrix.os }}
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
os: ${{ fromJSON('["ubuntu-latest","windows-latest"]') }}
# CI concentrates on newer runtimes (3.11/3.12 still supported per pyproject requires-python).
python-version: ${{ fromJSON('["3.13","3.14"]') }}
include:
- name: minimum, 3.11
os: ubuntu-latest
python-version: "3.11"
coverage: false
- name: latest, 3.14 + coverage
os: ubuntu-latest
python-version: "3.14"
coverage: true
- name: Windows, 3.14
os: windows-latest
python-version: "3.14"
coverage: false
steps:
- uses: actions/checkout@v4
@@ -47,10 +58,21 @@ jobs:
run: uv sync --all-extras --dev
- name: Lint with ruff
run: uv run ruff check nanobot --select F
if: matrix.coverage
run: uv run ruff check nanobot tests conftest.py
- name: Run tests
run: uv run python -m pytest tests/ --cov=nanobot --cov-report=term-missing:skip-covered
- name: Run tests with coverage
if: matrix.coverage
run: >-
uv run python -m pytest
--cov=nanobot --cov-report=term-missing:skip-covered
--durations=25 --durations-min=1.0
- name: Run compatibility tests
if: ${{ !matrix.coverage }}
run: >-
uv run python -m pytest
--durations=25 --durations-min=1.0
webui:
runs-on: ubuntu-latest
@@ -64,9 +86,13 @@ jobs:
with:
bun-version: 1.3.6
- name: Verify npm lockfile
working-directory: webui
run: npm ci --ignore-scripts --dry-run
- name: Install WebUI dependencies
working-directory: webui
run: bun install
run: bun install --frozen-lockfile
- name: Lint WebUI
working-directory: webui
+2 -2
View File
@@ -36,7 +36,7 @@ Messages flow through an async `MessageBus` (`nanobot/bus/queue.py`) that decoup
- **Agent Loop** (`nanobot/agent/loop.py`, `runner.py`): The core processing engine. `AgentLoop` manages session keys, hooks, and context building. `AgentRunner` executes the multi-turn LLM conversation with tool execution.
- **LLM Providers** (`nanobot/providers/`): Provider implementations (Anthropic, OpenAI-compatible, OpenAI Responses API, Azure, Bedrock, GitHub Copilot, OpenAI Codex, etc.) built on a common base (`base.py`). Includes image generation (`image_generation.py`) and audio transcription (`transcription.py`). `factory.py` and `registry.py` handle instantiation and model discovery.
- **Channels** (`nanobot/channels/`): Platform integrations (Telegram, Discord, Slack, Feishu, Matrix, WhatsApp, QQ, WeChat, WeCom, DingTalk, Email, MoChat, MS Teams, WebSocket). `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 self-contained packages auto-discovered via `pkgutil` scanning.
- **Tools** (`nanobot/agent/tools/`): Agent capabilities exposed to the LLM: filesystem (read/write/edit/list), shell execution (with sandbox backends), web search/fetch, MCP servers, cron, notebook editing, subagent spawning, long-running tasks / sustained goals (`long_task.py`), image generation, and self-modification. Tools are auto-discovered via `pkgutil` scan + entry-point plugins.
- **Memory** (`nanobot/agent/memory.py`): Session history persistence with Dream two-phase memory consolidation. Uses atomic writes with fsync for durability.
- **Session Management** (`nanobot/session/`): Per-session history, context compaction, TTL-based auto-compaction (`manager.py`), and sustained goal state tracking (`goal_state.py`).
@@ -46,7 +46,7 @@ Messages flow through an async `MessageBus` (`nanobot/bus/queue.py`) that decoup
- **Command Router** (`nanobot/command/`): Slash command routing and built-in command handlers.
- **Heartbeat** (`nanobot/templates/HEARTBEAT.md`): Periodic task list checked via `cron` jobs (legacy dedicated service removed).
- **Pairing** (`nanobot/pairing/`): DM sender approval store with persistent pairing codes per channel.
- **Skills** (`nanobot/skills/`): Built-in skill definitions (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
+18 -3
View File
@@ -17,15 +17,22 @@ WORKDIR /app
# Install Python dependencies first (cached layer). Hatch reads the custom build
# hook from hatch_build.py even for this metadata-only install.
ARG NANOBOT_EXTRAS=whatsapp
COPY pyproject.toml README.md LICENSE THIRD_PARTY_NOTICES.md hatch_build.py ./
RUN mkdir -p nanobot && touch nanobot/__init__.py && \
NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[whatsapp]" && \
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 --from=webui-builder /app/nanobot/web/dist/ nanobot/web/dist/
RUN NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[whatsapp]"
RUN NANOBOT_SKIP_WEBUI_BUILD=1 uv pip install --system --no-cache ".[$NANOBOT_EXTRAS]"
# Render deploy template (see render.yaml): committed gateway config that wires
# secrets through ${ANTHROPIC_API_KEY} / ${NANOBOT_WEB_TOKEN} env vars (resolved
# at startup). Lives in the code dir (/app), not the data dir, so a mounted disk
# won't shadow it. Only used when RENDER=true; ignored by local runs.
COPY render-config.json ./
# Create non-root user and config directory
RUN useradd -m -u 1000 -s /bin/bash nanobot && \
@@ -35,8 +42,16 @@ RUN useradd -m -u 1000 -s /bin/bash nanobot && \
COPY entrypoint.sh /usr/local/bin/entrypoint.sh
RUN sed -i 's/\r$//' /usr/local/bin/entrypoint.sh && chmod +x /usr/local/bin/entrypoint.sh
USER nanobot
# Start as root so the entrypoint can chown the data dir (on Render, the
# freshly-mounted root-owned persistent disk) before dropping to the non-root
# nanobot user via setpriv. The entrypoint drops privileges on every root start
# and fails closed if it cannot, so the agent never runs as root (see
# entrypoint.sh).
USER root
ENV HOME=/home/nanobot
# Ensure crash output reaches Render logs (app output is otherwise swallowed on
# non-graceful exit).
ENV PYTHONUNBUFFERED=1 PYTHONFAULTHANDLER=1
# Gateway health endpoint and optional WebUI/WebSocket channel ports
EXPOSE 18790 8765
+65 -194
View File
@@ -42,10 +42,45 @@
|---|---|
| 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) |
| Deploy to the cloud in one click | [Deploy to Render](#deploy-to-render) |
## Deploy to Render
Deploy nanobot's gateway and bundled WebUI as a single web service with persistent memory. Render reads [`render.yaml`](./render.yaml) and prompts for two secrets on deploy: `ANTHROPIC_API_KEY` and `NANOBOT_WEB_TOKEN` (the password that gates the public WebUI — generate a strong random value, e.g. `openssl rand -hex 32`).
> **Note:** The blueprint attaches a persistent disk so sessions, memory, and WebUI history survive restarts. Persistent disks require a paid service (they are not available on Render's free tier).
[![Deploy to Render](https://render.com/images/deploy-to-render-button.svg)](https://render.com/deploy?repo=https://github.com/HKUDS/nanobot)
## What can nanobot do?
nanobot is a self-hosted personal AI agent runtime. It can:
- run in a browser WebUI or terminal
- connect to Telegram, Discord, Slack, WeChat, Email, Mattermost, and other chat apps
- use tools such as files, shell, web search, web fetch, MCP, cron, image generation, and subagents
- keep session history and long-term memory through Dream
- run long-horizon goals and scheduled automations
- expose a Python SDK and OpenAI-compatible API for integrations
- deploy as a long-running local or server-side agent gateway
## Latest Release
**v0.2.2 - Durability Release**
Highlights:
- Segmented WebUI transcripts
- Python SDK runtime controls
- Automation management
- Search/STT provider improvements
- Gateway/session/provider reliability
[See full changelog](https://github.com/HKUDS/nanobot/releases/tag/v0.2.2)
## Open Source Partners
@@ -54,158 +89,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.
@@ -213,13 +110,13 @@
## 📦 Install
> [!IMPORTANT]
> If you want the newest features and experiments, install from source.
>
> If you want the newest features and experiments, install from source.
>
> If you want the most stable day-to-day experience, install from PyPI or with `uv`.
Pick **one** install method:
Prerequisites: Python 3.11 or newer. Git is only needed for a source install; Node.js/Bun are only needed if you are developing the WebUI itself.
Prerequisites: Python 3.11 or newer. Git is only needed for a source install. Published packages already include the WebUI; a current-source install needs `bun` or `npm` to build it.
If terminals, API keys, or config files are new to you, use the guided zero-background walkthrough in [Start Without Technical Background](./docs/start-without-technical-background.md) instead of this compact README path.
@@ -237,7 +134,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**. The installer also prints the exact command it used to run nanobot; reuse that full command below if `nanobot` is not on `PATH`.
To preview the plan without changing your environment, pass `--dry-run`; combine it with `--dev` when you want to preview the main-branch install.
@@ -277,18 +174,24 @@ If pip reports `externally-managed-environment` on macOS or Linux, use the one-c
**Install from source**
`bun` or `npm` must be available. From an activated virtual environment:
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install -e .
python -m pip install .
```
On Windows, if pip reports that it cannot launch `npm`, run `cd webui`, `npm.cmd install --package-lock=false`, `npm.cmd run build`, and `cd ..` in order, then retry the install. Contributors who need an editable checkout should follow [`CONTRIBUTING.md`](./CONTRIBUTING.md) and [`webui/README.md`](./webui/README.md).
Verify the install:
```bash
nanobot --version
```
If `nanobot` is not on `PATH`, invoke it through the method that installed it: reuse the recommended installer's command, use `uv tool run --from nanobot-ai nanobot ...` or `pipx run --spec nanobot-ai nanobot ...`, or use the Python executable from the environment where pip installed the package.
## 🚀 Quick Start
**1. Initialize**
@@ -358,14 +261,13 @@ For another provider, the same config shape still applies:
**3. Open the WebUI**
If Quick Start enabled the WebSocket channel, start the gateway:
The stable-compatible path is:
```bash
nanobot gateway
```
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password you set in the wizard, then send your first message there.
Prefer not to keep a terminal open? Use `nanobot gateway --background`, then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
Leave the terminal open and visit `http://127.0.0.1:8765`. Current source versions also provide `nanobot webui`, which prepares the local WebSocket channel if needed, starts the gateway, and opens the browser automatically. The first-run WebUI binds to `127.0.0.1` by default, so it is not exposed to your LAN. Prefer not to keep a terminal open? Use `nanobot gateway --background`, then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
For manual or terminal-only setup, test one CLI message:
@@ -399,33 +301,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).
On current source versions, the command enables the local WebSocket channel after confirmation, starts the gateway, and opens [`http://127.0.0.1:8765`](http://127.0.0.1:8765). If your installed stable release does not include `nanobot webui`, run `nanobot gateway` and open that address manually. To open it from another device on your LAN, see [WebUI docs -> LAN access](./docs/webui.md#lan-access).
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 +349,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 +357,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)
@@ -497,7 +381,7 @@ See [CONTRIBUTING.md](./CONTRIBUTING.md) for setup, review, and contribution gui
## Contact
This project was started by [Xubin Ren](https://github.com/re-bin) as a personal open-source project and continues to be maintained in an individual capacity using personal resources, with contributions from the open-source community. Feel free to contact [xubinrencs@gmail.com](mailto:xubinrencs@gmail.com) for questions, ideas, or collaboration.
Nanobot was started by [Xubin Ren](https://github.com/re-bin) as a personal open-source project and is now maintained collaboratively with contributors from the open-source community. Feel free to contact [xubinrencs@gmail.com](mailto:xubinrencs@gmail.com) for questions, ideas, or collaboration.
### Contributors
@@ -505,19 +389,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">
+1 -1
View File
@@ -129,7 +129,7 @@ pip install --upgrade nanobot-ai
**Important Notes:**
- Keep `litellm` updated to the latest version for security fixes
- Run `pip-audit` regularly, including optional channel dependencies such as `nanobot-ai[whatsapp]`
- Run `pip-audit` regularly after enabling the channels used in production; their manifest-declared dependencies are installed into the same environment
- Subscribe to security advisories for nanobot and its dependencies
### 7. Production Deployment
+51
View File
@@ -0,0 +1,51 @@
"""Cross-suite test infrastructure."""
from __future__ import annotations
import os
import ssl
import sys
from collections.abc import Iterator
import certifi
import pytest
@pytest.fixture(scope="session", autouse=True)
def _use_windows_system_ca_for_default_http_clients() -> Iterator[None]:
"""Avoid reparsing certifi's CA bundle for every offline HTTP client.
Loading certifi takes roughly 0.7 seconds per client on Windows. The test
suite constructs hundreds of clients while mocking their I/O. System roots
preserve certificate verification for accidental local requests; explicit
``cafile``, ``capath``, and ``cadata`` arguments still use the real loader.
"""
if sys.platform != "win32":
yield
return
original = ssl.create_default_context
certifi_path = os.path.normcase(os.path.abspath(certifi.where()))
def create_default_context(
purpose: ssl.Purpose = ssl.Purpose.SERVER_AUTH,
*,
cafile: str | None = None,
capath: str | None = None,
cadata: str | bytes | None = None,
) -> ssl.SSLContext:
requested_path = os.path.normcase(os.path.abspath(cafile)) if cafile else None
if requested_path == certifi_path and capath is None and cadata is None:
return original(purpose)
return original(
purpose,
cafile=cafile,
capath=capath,
cadata=cadata,
)
ssl.create_default_context = create_default_context
try:
yield
finally:
ssl.create_default_context = original
+16
View File
@@ -0,0 +1,16 @@
x-bwrap-security: &bwrap-security
cap_add:
- SYS_ADMIN
security_opt:
- apparmor=unconfined
- seccomp=unconfined
services:
nanobot-gateway:
<<: *bwrap-security
nanobot-api:
<<: *bwrap-security
nanobot-cli:
<<: *bwrap-security
+1 -6
View File
@@ -6,11 +6,6 @@ x-common-config: &common-config
- ~/.nanobot:/home/nanobot/.nanobot
cap_drop:
- ALL
cap_add:
- SYS_ADMIN
security_opt:
- apparmor=unconfined
- seccomp=unconfined
services:
nanobot-gateway:
@@ -19,7 +14,7 @@ services:
command: ["gateway"]
restart: unless-stopped
ports:
- 18790:18790
- 127.0.0.1:18790:18790
- 8765:8765
deploy:
resources:
+62 -86
View File
@@ -1,108 +1,84 @@
# nanobot Docs
# nanobot Documentation
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.
Use these docs to get a working agent first, then open a task guide only when you need the next capability. Source-level design and extension details are kept in the contributor section.
If you have never used a terminal or edited a config file before, start with [`start-without-technical-background.md`](./start-without-technical-background.md). Otherwise, start with [`quick-start.md`](./quick-start.md) and get one local `nanobot agent -m "Hello!"` reply working before connecting chat apps, WebUI, Docker, or custom tools.
Most JSON examples in these docs are snippets to merge into `~/.nanobot/config.json`, not full replacement files.
Provider examples are concrete walkthroughs, not rankings or endorsements. Use the provider whose key, endpoint, and model ID you actually control.
If you find a docs mistake, outdated command, or confusing step, please open an issue: <https://github.com/HKUDS/nanobot/issues>.
## Pick a Track
| You are | Start with | Then use |
|---|---|---|
| New to terminals and config files | [`start-without-technical-background.md`](./start-without-technical-background.md) | [`troubleshooting.md`](./troubleshooting.md) if the first reply fails |
| Comfortable pasting commands and JSON | [`quick-start.md`](./quick-start.md) | [`provider-cookbook.md`](./provider-cookbook.md) for pasteable provider setups |
| Operating a long-running bot | [`concepts.md`](./concepts.md) | [`chat-apps.md`](./chat-apps.md), [`webui.md`](./webui.md), and [`deployment.md`](./deployment.md) |
| Integrating or extending nanobot | [`architecture.md`](./architecture.md) | [`configuration.md`](./configuration.md), [`openai-api.md`](./openai-api.md), [`python-sdk.md`](./python-sdk.md), [`development.md`](./development.md), and [`channel-plugin-guide.md`](./channel-plugin-guide.md) |
Repository docs follow the current source tree and can be newer than the latest package release. For published release docs, visit [nanobot.wiki](https://nanobot.wiki/docs/latest/getting-started/nanobot-overview).
## Start Here
| Goal | Read | Outcome |
| Your situation | Read this | You are done when... |
|---|---|---|
| Start with no technical background | [`start-without-technical-background.md`](./start-without-technical-background.md) | One-command setup, terminal basics, config, API keys, and the first reply |
| Install and get the first reply | [`quick-start.md`](./quick-start.md) | A working CLI agent and a known-good config path |
| Understand how the pieces fit | [`concepts.md`](./concepts.md) | Mental model for config, workspace, gateway, channels, tools, memory, and sessions |
| Choose or change a model provider | [`providers.md`](./providers.md) | Correct provider/model pairing without reading the full config reference |
| Copy a provider setup recipe | [`provider-cookbook.md`](./provider-cookbook.md) | Pasteable OpenRouter, OpenAI, Anthropic, local model, fallback, and Langfuse setups |
| Fix a first-run or runtime problem | [`troubleshooting.md`](./troubleshooting.md) | A diagnosis order and targeted checks for common failures |
| Terminals, Python, or API keys are new to you | [Beginner walkthrough](./start-without-technical-background.md) | The browser can send `Hello!` and receive a reply |
| You are comfortable running commands | [Install and Quick Start](./quick-start.md) | `nanobot status` is healthy and the WebUI or CLI can get one reply |
| Something already failed | [Troubleshooting](./troubleshooting.md) | You have isolated the problem to install, config, model, gateway, channel, or tool access |
## After the First Reply Works
The recommended first-run path is:
Do not configure everything at once. Pick one next surface:
1. Install nanobot.
2. Choose **Quick Start** in `nanobot onboard --wizard`.
3. Run `nanobot gateway` and open `http://127.0.0.1:8765`.
4. Send `Hello!` before configuring anything else.
If a local `nanobot agent` session can already answer normally, you can also ask nanobot to help configure itself: have it read the relevant docs, inspect your current config, make one specific next change, and tell you when to run `/restart`.
Most people do not need to edit JSON for the first run. The wizard handles the initial provider, model, and local WebUI settings. Current source versions also provide `nanobot webui` to start the gateway and open the browser in one step. After the WebUI opens, use **Settings** for models and built-in capabilities, **Settings → Channels** for chat apps, and **Apps** for CLI App or MCP integrations.
| Next goal | Read | First check |
|---|---|---|
| Use nanobot in a browser | [`webui.md`](./webui.md) | Enable WebSocket, run `nanobot gateway`, open `http://127.0.0.1:8765` |
| Talk through a chat app | [`chat-apps.md`](./chat-apps.md) | Merge one channel snippet, run `nanobot channels status`, keep `nanobot gateway` running |
| Change provider or add fallbacks | [`provider-cookbook.md`](./provider-cookbook.md) | Keep `modelPresets` named and set `agents.defaults.modelPreset` |
| Call nanobot from Python | [`python-sdk.md`](./python-sdk.md) | Reuse the same config/workspace from code, then run or stream one agent turn |
| Understand before operating long-term | [`concepts.md`](./concepts.md) | Know what config, workspace, gateway, sessions, memory, and tools mean |
| Diagnose a new failure | [`troubleshooting.md`](./troubleshooting.md) | Start with `nanobot status`, then `nanobot agent -m "Hello!"` |
## Add One Capability
## Use nanobot
Pick the row that matches what you want to accomplish next:
| 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 automations | [`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 |
| Join agent communities | [`agent-social-network.md`](./agent-social-network.md) | External agent-community setup |
| Goal | Guide |
|---|---|
| Learn the browser workbench | [WebUI](./webui.md) |
| Connect Telegram, Discord, Slack, Feishu, WeChat, Email, or another chat app | [Chat Apps](./chat-apps.md) |
| Choose a hosted, OAuth, company, or local model | [Provider Cookbook](./provider-cookbook.md) |
| Add model fallbacks | [Configure Model Fallback](./guides/configure-model-fallback.md) |
| Enable web search | [Configure Web Search](./guides/configure-web-search.md) |
| Add an MCP tool server | [Configure MCP Tools](./guides/configure-mcp-tools.md) |
| Generate images | [Image Generation](./image-generation.md) |
| Schedule work or create a local trigger | [Automations](./automations.md) |
| Understand and manage long-term memory | [Memory](./memory.md) |
| Run nanobot continuously | [Deployment](./deployment.md) |
| Run separate bots or workspaces | [Multiple Instances](./multiple-instances.md) |
| Call nanobot from Python | [Python SDK](./python-sdk.md) |
| Expose an OpenAI-compatible endpoint | [OpenAI-Compatible API](./openai-api.md) |
For shorter, outcome-focused walkthroughs, browse the [task guide index](./guides/README.md).
## Operate nanobot
| Need | Read |
|---|---|
| Commands and flags | [CLI Reference](./cli-reference.md) |
| In-chat slash commands | [In-Chat Commands](./chat-commands.md) |
| Config, workspace, gateway, sessions, tools, and memory in plain language | [Concepts](./concepts.md) |
| Provider/model matching and selection | [Providers and Models](./providers.md) |
| Setup and runtime diagnosis | [Troubleshooting](./troubleshooting.md) |
| Older development highlights | [Release Archive](./release-archive.md) |
## Reference
| Area | Read | Best for |
|---|---|---|
| Full configuration schema | [`configuration.md`](./configuration.md) | Exact fields, defaults, provider tables, web tools, MCP, security, and runtime options |
| CLI commands | [`cli-reference.md`](./cli-reference.md) | Command names, common flags, and entrypoints |
| Architecture | [`architecture.md`](./architecture.md) | Source-level runtime map for core flow, providers, channels, tools, WebUI, memory, security, and extension points |
| Development | [`development.md`](./development.md) | Contributor notes for adding providers and transcription adapters |
| Memory | [`memory.md`](./memory.md) | Session history, Dream consolidation, memory files, and versioning |
| Observability | [`configuration.md#langfuse-observability`](./configuration.md#langfuse-observability) | Langfuse tracing setup and required environment variables |
| WebSocket protocol | [`websocket.md`](./websocket.md) | Custom clients, token issuance, multiplexed chats, media, and protocol events |
| OpenAI-compatible API | [`openai-api.md`](./openai-api.md) | `/v1/chat/completions`, `/v1/models`, file uploads, and SDK-compatible usage |
| Python SDK | [`python-sdk.md`](./python-sdk.md) | SDK 101, sessions, streaming, model overrides, runtime helpers, and hooks |
| Runtime self-inspection | [`my-tool.md`](./my-tool.md) | Inspecting and tuning the current agent run |
Use reference pages to look up an exact option after you know what you are trying to configure:
## Fast Lookup
| Need | Jump to |
| Area | Reference |
|---|---|
| Provider/model resolution order | [`providers.md#provider-resolution`](./providers.md#provider-resolution) |
| Model presets and fallback chains | [`providers.md#model-presets`](./providers.md#model-presets) and [`providers.md#fallback-models`](./providers.md#fallback-models) |
| Langfuse environment variables | [`configuration.md#langfuse-observability`](./configuration.md#langfuse-observability) |
| WebSocket/WebUI protocol details | [`websocket.md`](./websocket.md) |
| OpenAI-compatible API usage | [`openai-api.md`](./openai-api.md) |
| Python SDK usage | [`python-sdk.md`](./python-sdk.md) |
| Multiple configs, workspaces, and ports | [`multiple-instances.md`](./multiple-instances.md) |
| Security, sandboxing, and SSRF controls | [`configuration.md#security`](./configuration.md#security) |
| Channel plugin development | [`channel-plugin-guide.md`](./channel-plugin-guide.md) |
| Every configuration field and default | [Configuration](./configuration.md) |
| Provider and model behavior | [Providers and Models](./providers.md) |
| Chat channel prerequisites and manual JSON | [Chat Apps](./chat-apps.md) |
| WebSocket authentication and wire protocol | [WebSocket](./websocket.md) |
| Python SDK classes, events, sessions, and hooks | [Python SDK](./python-sdk.md) |
| OpenAI-compatible HTTP routes and payloads | [OpenAI-Compatible API](./openai-api.md) |
| Runtime self-inspection and tuning | [My Tool](./my-tool.md) |
## Extend nanobot
Configuration examples are usually snippets to merge into `~/.nanobot/config.json`, not complete replacement files. The docs use camelCase because nanobot writes config that way. Keep real API keys, bot tokens, and passwords out of issues and public logs.
| Goal | Read | Outcome |
|---|---|---|
| Add a provider or transcription adapter | [`development.md`](./development.md) | A registry/schema-aligned implementation path |
| Add a chat channel plugin | [`channel-plugin-guide.md`](./channel-plugin-guide.md) | A packaged channel discovered through entry points |
| Add custom MCP servers | [`configuration.md#mcp-model-context-protocol`](./configuration.md#mcp-model-context-protocol) | External tools exposed to the agent through MCP |
| Tune tool safety | [`configuration.md#security`](./configuration.md#security) | Shell sandboxing, workspace restriction, and SSRF policy |
## Extend or Contribute
## Reading Strategy
These pages explain implementation and extension points. You do not need them to install or operate nanobot.
Use the docs in this order when you are unsure where to go:
| Goal | Read |
|---|---|
| Understand source ownership and runtime flow | [Architecture](./architecture.md) |
| Set up a development environment | [Development](./development.md) and [CONTRIBUTING.md](../CONTRIBUTING.md) |
| Add a channel package | [Channel Package Guide](./channel-package-guide.md) |
| Build the WebUI source | [WebUI Development](../webui/README.md) |
1. If terminal commands or config files are new to you, [`start-without-technical-background.md`](./start-without-technical-background.md) explains the setup words and uses one concrete provider example so there is only one decision at a time.
2. [`quick-start.md`](./quick-start.md) proves installation, config loading, and provider access.
3. [`concepts.md`](./concepts.md) explains the runtime model so later pages are easier to scan.
4. [`provider-cookbook.md`](./provider-cookbook.md) gives pasteable provider, fallback, local model, and Langfuse recipes.
5. A task guide, such as [`chat-apps.md`](./chat-apps.md), [`image-generation.md`](./image-generation.md), or [`deployment.md`](./deployment.md), gets one workflow working.
6. [`configuration.md`](./configuration.md) is the source of truth when you need a specific field, default value, or advanced option.
7. [`troubleshooting.md`](./troubleshooting.md) helps isolate whether a failure is install, config, provider, gateway, channel, or tool related.
If a command or screen no longer matches these docs, please [open an issue](https://github.com/HKUDS/nanobot/issues) with your nanobot version, operating system, and the page that needs correction.
+95 -6
View File
@@ -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)
+4 -4
View File
@@ -81,11 +81,11 @@ Main files:
| Area | Files |
|---|---|
| Base channel contract | `nanobot/channels/base.py` |
| Built-in channels | `nanobot/channels/*.py` |
| Channel packages | `nanobot/channels/<channel>/` |
| Discovery and lifecycle | `nanobot/channels/manager.py` |
| WebSocket/WebUI channel | `nanobot/channels/websocket.py` |
| WebSocket/WebUI channel | `nanobot/channels/websocket/` |
Channels are discovered through built-in module scanning and plugin entry points. A custom channel should follow [`channel-plugin-guide.md`](./channel-plugin-guide.md).
Channels are discovered by scanning self-contained packages under `nanobot/channels/`. Add a channel by contributing one package that follows [`channel-package-guide.md`](./channel-package-guide.md).
## WebUI and Gateway
@@ -181,7 +181,7 @@ When changing tools, channels, file access, WebUI workspace behavior, or network
| Extension | How |
|---|---|
| Provider | Add `ProviderSpec` in `providers/registry.py`, add schema field in `config/schema.py`, implement provider only if the generic backend is not enough |
| Channel | Implement `BaseChannel`, expose an entry point, follow [`channel-plugin-guide.md`](./channel-plugin-guide.md) |
| Channel | Export a `ChannelPlugin` descriptor, keep its runtime and optional setup surfaces in one package, and follow [`channel-package-guide.md`](./channel-package-guide.md) |
| Tool | Implement a tool under `agent/tools/` or expose a plugin entry point |
| MCP | Add `tools.mcpServers` config |
| Skill | Add workspace skill files under `<workspace>/skills/` or built-in skills under `nanobot/skills/` |
+201
View File
@@ -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
+792
View File
@@ -0,0 +1,792 @@
# Channel Package Guide
Use this guide to add a self-contained channel package to the nanobot repository. A channel is part of nanobot when its package lives at `nanobot/channels/<channel>/`; there is no separate external channel-plugin path.
> **Breaking change:** nanobot no longer discovers the `nanobot.channels` Python entry-point group. Move an entry-point implementation into `nanobot/channels/<channel>/` with a package-owned manifest, runtime, tests, and optional WebUI contribution.
## How It Works
When `nanobot gateway` starts, nanobot scans the packages under `nanobot/channels/` and loads each dependency-free `ChannelPlugin` descriptor from `manifest.py`.
If a matching config section has `"enabled": true`, the channel is instantiated and started.
## Ownership and Sources of Truth
| Concern | Owner and source of truth |
|---------|---------------------------|
| Runtime behavior and platform SDK use | `runtime.py` and package-local helpers |
| Python package requirements | `ChannelPlugin.dependencies` in `manifest.py` |
| Writable settings fields, types, defaults, requirements, secret handling, and validation | `ChannelPlugin.setup` in `manifest.py` |
| Persisted config expansion, instance updates, and runtime naming | `ChannelPlugin.management` backed by a dependency-free module |
| Interactive setup connections and their short-lived state | `ChannelPlugin.connector` backed by package-local `connect.py` |
| Reusable local login-state detection | `ChannelPlugin.management.local_state_present` backed by package-local code |
| Discovery metadata and lazy runtime target | `PLUGIN` in `manifest.py` |
| WebUI structure, components, URLs, field keys, actions, and preset values | `webui/index.ts` or `webui/index.tsx` |
| Channel-specific user-facing copy | `webui/locales/<locale>.json` |
| Generic settings-shell copy shared by every channel | `webui/src/i18n/locales/<locale>/common.json` |
Keep one source of truth for each concern. In particular, the backend setup contract decides what may be written, the TypeScript contribution decides how those fields are presented, and locale JSON supplies the channel-specific words shown to users.
## Quick Start
We'll build a minimal webhook channel that receives messages via HTTP POST and sends replies back.
### Project Structure
```text
nanobot/channels/webhook/
├── __init__.py # lightweight package marker; do not import the runtime
├── manifest.py # dependency-free ChannelPlugin descriptor
├── runtime.py # channel implementation and optional SDK imports
├── tests/ # package-local tests
└── webui/ # optional settings UI and translations
```
### 1. Create Your Channel
```python
# nanobot/channels/webhook/__init__.py
"""Webhook channel package."""
```
```python
# nanobot/channels/webhook/manifest.py
from nanobot.channels.contracts import ChannelFieldSpec, ChannelSetupSpec
from nanobot.channels.plugin import ChannelPlugin
PLUGIN = ChannelPlugin(
name="webhook",
display_name="Webhook",
runtime=f"{__package__}.runtime:WebhookChannel",
dependencies=("aiohttp>=3.9.0,<4.0.0",),
setup=ChannelSetupSpec(
fields={
"port": ChannelFieldSpec(kind="int", default=9000),
"allowFrom": ChannelFieldSpec(kind="list"),
},
),
)
```
```python
# nanobot/channels/webhook/runtime.py
import asyncio
from typing import Any
from aiohttp import web
from loguru import logger
from pydantic import Field
from nanobot.channels.base import BaseChannel
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
@classmethod
def default_config(cls) -> dict[str, Any]:
return WebhookConfig().model_dump(by_alias=True)
async def start(self) -> None:
"""Start an HTTP server that listens for incoming messages.
IMPORTANT: start() must block forever (or until stop() is called).
If it returns, the channel is considered dead.
"""
self._running = True
port = self.config.port
app = web.Application()
app.router.add_post("/message", self._on_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", port)
await site.start()
logger.info("Webhook listening on :{}", port)
# Block until stopped
while self._running:
await asyncio.sleep(1)
await runner.cleanup()
async def stop(self) -> None:
self._running = False
async def send(self, msg: OutboundMessage) -> None:
"""Deliver an outbound message.
msg.content — markdown text (convert to platform format as needed)
msg.media — list of local file paths to attach
msg.chat_id — the recipient (same chat_id you passed to _handle_message)
msg.metadata — channel routing context such as message/thread ids
msg.event — typed runtime event for progress/status messages
"""
logger.info("[webhook] -> {}: {}", msg.chat_id, msg.content[:80])
# In a real plugin: POST to a callback URL, send via SDK, etc.
async def _on_request(self, request: web.Request) -> web.Response:
"""Handle an incoming HTTP POST."""
body = await request.json()
sender = body.get("sender", "unknown")
chat_id = body.get("chat_id", sender)
text = body.get("text", "")
media = body.get("media", []) # list of URLs
# This is the key call: validates allowFrom, then puts the
# message onto the bus for the agent to process.
await self._handle_message(
sender_id=sender,
chat_id=chat_id,
content=text,
media=media,
)
return web.json_response({"ok": True})
```
The package directory, `PLUGIN.name`, runtime class name, and config section must all use `webhook`. Channel names use a portable ASCII package identifier: they start with a letter and contain only letters, digits, or underscores.
Declare runtime requirements directly in `ChannelPlugin.dependencies`. Do not add channel requirements to the root `pyproject.toml`: the package manifest is the source of truth used by the CLI, WebUI, and gateway startup. Keep the manifest and anything it imports free of the optional SDK itself.
### 2. Configure
```bash
nanobot plugins list # verify the channel package appears as "webhook"
nanobot onboard # add default config for detected channels
```
Edit `~/.nanobot/config.json`:
```json
{
"channels": {
"webhook": {
"enabled": true,
"port": 9000,
"allowFrom": ["*"]
}
}
}
```
nanobot always loads the dependency-free descriptor during discovery. When the WebUI gateway starts, it installs missing requirements for enabled channels before importing their runtimes. It also installs them when a channel is enabled from the CLI or WebUI. Status, configuration, and disable operations do not need the runtime. Single-instance and multi-instance channels use the same activation rules.
### 3. Run & Test
```bash
nanobot gateway
```
In another terminal:
```bash
curl -X POST http://localhost:9000/message \
-H "Content-Type: application/json" \
-d '{"sender": "user1", "chat_id": "user1", "text": "Hello!"}'
```
The agent receives the message and processes it. Replies arrive in your `send()` method.
## Channel Package Requirements
Every channel is a self-contained package at `nanobot/channels/<channel>/`; channel-specific runtime code, setup metadata, tests, WebUI structure, components, and translations stay under that directory.
### Package Layout
```text
nanobot/channels/<channel>/
├── __init__.py # package marker only; no runtime or SDK imports
├── manifest.py # dependency-free ChannelPlugin and ChannelSetupSpec
├── config.py # optional dependency-free config model and defaults
├── connect.py # optional interactive setup connector
├── instances.py # optional dependency-free multi-instance management adapter
├── state.py # optional persisted login-state detection
├── validation.py # optional package-owned setup checks
├── runtime.py # BaseChannel implementation and platform SDK imports
├── tests/ # channel-specific Python tests
└── webui/ # optional, compiled into the shared WebUI
├── index.ts or index.tsx # structure and optional React components
└── locales/
├── en.json # canonical locale shape
└── <locale>.json # one file for every supported WebUI locale
```
Do not add a runtime module directly under `nanobot/channels/`, create a parallel manifest tree, or add a central per-channel UI catalog. If existing channel files move, use `git mv` so history remains traceable.
### Manifest and Runtime Boundary
`manifest.py` exports a typed `ChannelPlugin` whose `runtime` target is an absolute import target, such as `nanobot.channels.telegram.runtime:TelegramChannel`; using `f"{__package__}.runtime:TelegramChannel"` keeps it package-owned without repeating the package path. Discovery imports the manifest before it knows whether the optional platform dependency is installed, so `manifest.py` must not import `runtime.py` or any platform SDK. Import runtime symbols from `runtime.py` explicitly; `__init__.py` remains an inert package marker.
The manifest owns the channel name, display name, setup contract, management adapter, optional connector target, optional dependency extra, capabilities, default activation, and optional WebUI entry path. The management adapter alone decides whether a channel is single-instance or multi-instance.
Interactive browser setup uses one small connector contract. Set `connector=f"{__package__}.connect:MyConnectStore"`; the target is loaded only when `/api/settings/channels/<name>/connect/{start,poll,cancel}` is called. The store exposes one async `handle(action, query)` method and keeps platform-specific parsing, sessions, and errors inside the channel package. The shared settings router only authenticates, dispatches, and applies a successful connection.
Use the small constructors in [`nanobot/channels/_manifest.py`](../nanobot/channels/_manifest.py) for declarative field and requirement definitions. Use [`nanobot/channels/dingtalk/manifest.py`](../nanobot/channels/dingtalk/manifest.py) as a compact single-instance example and [`nanobot/channels/feishu/`](../nanobot/channels/feishu/) as a multi-instance example.
### Package-owned WebUI
Set `webui="webui/index.ts"` or `webui="webui/index.tsx"` in the channel manifest. Candidate modules are bundled from channel packages, but the settings UI activates only the exact path returned by the backend feature payload.
The entry module exports one default `ChannelUiContribution`. Channel identity comes from the package directory, so do not repeat a `channel` field in TypeScript. Keep only structure and executable UI data in this module: presentation metadata, icons or logo URLs, docs URLs, config field keys, action payloads, preset values, aliases, and optional `Panel` or `ConnectFlow` components.
Do not put static descriptions, setup steps, labels, placeholders, help text, action labels, or preset labels in TSX. Those strings belong in the channel's locale JSON. TSX remains appropriate for dynamic rendering, interpolation, conditions, and rich component composition.
### Channel-owned i18n
Create `webui/locales/<locale>.json` for every locale code declared in [`webui/src/i18n/config.ts`](../webui/src/i18n/config.ts). Treat `en.json` as the canonical shape; every other locale must contain the same message keys and the same interpolation variables. `displayName` may be omitted when the product name should remain unchanged.
```json
{
"description": "Use nanobot from Example chats.",
"requirements": "Example app credentials and gateway",
"setup": {
"docsLabel": "Open Example setup",
"officialLabel": "Open Example console",
"summary": "Example needs app credentials.",
"tryIt": "Send a test message.",
"steps": [
"Create an Example app.",
"Add the credentials.",
"Save, enable, and test the channel."
],
"fields": {
"clientId": {
"label": "Client ID",
"placeholder": "Example client ID",
"help": "Copy it from the Example console."
}
},
"actions": {
"copyManifest": "Copy manifest"
},
"presets": {
"default": "Default"
}
},
"custom": {
"connected": "{{name}} is connected."
}
}
```
Field messages are keyed by the config path after `channels.<channel>.`, with remaining punctuation converted to underscores. For example, `channels.signal.dm.allowFrom` maps to `setup.fields.dm_allowFrom`. Action and preset messages use the IDs declared in the TypeScript contribution.
Custom channel components should read dynamic copy with `channelTranslator(t, "<channel>")`; keep the English fallback adjacent to the call so an incomplete translation still renders useful text. Aliases reuse the owning channel's locale namespace rather than duplicating translations.
The dependency direction is intentional:
- [`webui/src/i18n/index.ts`](../webui/src/i18n/index.ts) imports the pure JSON [`channel-plugins/locale-registry.ts`](../webui/src/channel-plugins/locale-registry.ts).
- The locale registry discovers only `nanobot/channels/*/webui/locales/*.json` and must not import the UI registry, React, or TSX.
- Settings components may consume both the UI registry and locale registry.
- Channel UI code may use shared types and generic settings components, but core settings code must not add `if (feature.name === "...")` branches for individual channels.
This separation prevents i18n initialization from eagerly loading every channel React component and keeps channel-specific ownership below the channel package.
### Tests and Definition of Done
Put channel-specific Python tests in `nanobot/channels/<channel>/tests/`. Keep only shared registry, manager, base-class, and cross-channel contract tests in `tests/channels/`. Release builds exclude package-local tests while the repository test configuration discovers both trees.
For a focused channel change, run the smallest relevant set:
```bash
uv run pytest nanobot/channels/<channel>/tests -q
cd webui
bun run test -- src/tests/channel-locale-registry.test.ts src/tests/channel-ui-registry.test.ts src/tests/channel-identity.test.ts
bun run lint
bun run build
```
Before considering the change complete, verify all of the following:
- The manifest can be discovered without importing the runtime or optional platform SDK.
- `ChannelSetupSpec` contains every writable field and rejects unknown fields.
- The TypeScript field, action, and preset IDs have matching English locale messages.
- Every supported locale matches the English key shape and interpolation variables.
- Generic settings copy remains in core `common.json`; channel-specific copy remains inside the channel package.
- User-facing WebUI changes work through the built frontend served by a real gateway, including language switching and refresh persistence.
- Markdown prose paragraphs and individual list items remain on one source line; let the renderer handle visual wrapping.
## BaseChannel API
### Required (abstract)
| Method | Description |
|--------|-------------|
| `async start()` | **Must block forever.** Connect to platform, listen for messages, call `_handle_message()` on each. If this returns, the channel is dead. |
| `async stop()` | Set `self._running = False` and clean up. Called when gateway shuts down. |
| `async send(msg: OutboundMessage)` | Deliver an outbound message to the platform. Raise when the transport does not accept it. |
#### Outbound delivery contract
A normal return from `send()` means either the visible payload was accepted by the platform transport/API, or the channel deliberately had nothing to deliver, such as an empty progress event. Do not log and return when the client is disconnected, still starting, or the platform rejects the request. Raise an exception so `ChannelManager` can apply the shared retry policy.
`send()` may run as soon as `is_running` becomes true. If a channel sets `_running` before its transport is ready, it must keep raising until delivery can be attempted safely. Small platform-specific retries are fine, but the final failure must still reach the manager.
### Interactive Login
If your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:
```python
async def login(self, force: bool = False) -> bool:
"""
Perform channel-specific interactive login.
Args:
force: If True, ignore existing credentials and re-authenticate.
Returns True if already authenticated or login succeeds.
"""
# For QR-code-based login:
# 1. If force, clear saved credentials
# 2. Check if already authenticated (load from disk/state)
# 3. If not, show QR code and poll for confirmation
# 4. Save token on success
```
Channels that don't need interactive login (e.g. Telegram with bot token, Discord with bot token) inherit the default `login()` which just returns `True`.
Users trigger interactive login via:
```bash
nanobot channels login <channel_name>
nanobot channels login <channel_name> --force # re-authenticate
```
### Provided by Base
| Method / Property | Description |
|-------------------|-------------|
| `_handle_message(sender_id, chat_id, content, media?, metadata?, session_key?)` | **Call this when you receive a message.** Checks `is_allowed()`, then publishes to the bus. Automatically sets `_wants_stream` if `supports_streaming` is true. |
| `is_allowed(sender_id)` | Checks against `config.allow_from`; `"*"` allows all, `[]` denies all. |
| `default_config()` (classmethod) | Returns runtime-local defaults for callers that construct the class directly. Discovery and onboarding use the descriptor instead. |
| `refresh_feature_metadata(config_path, instance_id)` (classmethod) | Optionally refreshes saved display metadata after an explicit settings action. It is never called by a read-only feature GET. |
| `transcribe_audio(file_path)` | Transcribes audio via the shared top-level `transcription` config (if configured). |
| `supports_streaming` (property) | `True` when config has `"streaming": true` **and** subclass overrides `send_delta()`. |
| `is_running` | Returns `self._running`. |
| `login(force=False)` | Perform interactive login (e.g. QR code scan). Returns `True` if already authenticated or login succeeds. Override in subclasses that support interactive login. |
| `send_reasoning_delta(chat_id, delta, metadata?, *, stream_id?)` | Optional hook for streamed model reasoning/thinking content. Default is no-op. |
| `send_reasoning_end(chat_id, metadata?, *, stream_id?)` | Optional hook marking the end of a reasoning block. Default is no-op. |
| `send_reasoning(msg)` | Optional one-shot reasoning fallback. Default translates to `send_reasoning_delta()` + `send_reasoning_end()`. |
### Optional management contract
Persisted-state management belongs to `ChannelPlugin.management`, not `BaseChannel`. Keep the adapter and anything it imports free of optional platform SDKs so status, settings, and disable operations still work when the runtime cannot be imported. Runtime classes own network lifecycle, message delivery, interactive login, enable-time availability checks, and explicit runtime-only actions such as metadata refresh.
```python
from nanobot.channels.contracts import ChannelFieldSpec, ChannelSetupSpec, SetupRequirement
from nanobot.channels.plugin import ChannelPlugin
from .instances import MANAGEMENT
PLUGIN = ChannelPlugin(
name="webhook",
display_name="Webhook",
runtime=f"{__package__}.channel:WebhookChannel",
setup=ChannelSetupSpec(
fields={
"token": ChannelFieldSpec(kind="secret"),
"region": ChannelFieldSpec(
kind="enum",
choices=frozenset({"us", "eu"}),
default="us",
),
},
required=(SetupRequirement.field("token"),),
),
management=MANAGEMENT,
)
```
`instances.py` then exports the dependency-free adapter assembled from channel-owned callbacks:
```python
from typing import Any
from nanobot.channels.contracts import ChannelInstanceSpec, ChannelManagementSpec
from .config import default_config
def instance_specs(section: Any, *, enabled_only: bool = True) -> list[ChannelInstanceSpec]:
... # Expand the persisted channel-owned envelope.
def update_instance_config(
section: Any,
values: dict[str, Any],
*,
instance_id: str = "default",
) -> dict[str, Any]:
... # Update one instance without discarding sibling data.
MANAGEMENT = ChannelManagementSpec(
multi_instance=True,
default_config=default_config,
instance_specs=instance_specs,
update_instance_config=update_instance_config,
)
```
`ChannelSetupSpec` is authoritative for writable field names, field types, choices, defaults, required setup, secret redaction, and optional backend validation. The settings API rejects fields outside this contract. A validator receives `(values, context)`; use `context.allow_local_service_access` for host network policy instead of loading global config from the channel package.
The dependency-free `MANAGEMENT` value is a `ChannelManagementSpec`. Multi-instance plugins provide `instance_specs(section, enabled_only=True)` and `update_instance_config(section, values, instance_id=...)`; they may also provide `default_config`, `runtime_name`, presentation-only `feature_instances`, and `local_state_present`. Single-instance plugins normally derive onboarding defaults from `ChannelSetupSpec`; use `default_config` only when persisted defaults include fields that are not part of generic setup.
Multi-instance adapters return `ChannelInstanceSpec` objects and preserve their persisted envelope when updating one instance. Their descriptor sets `ChannelManagementSpec(multi_instance=True)`. The shared contract enforces these invariants:
- every `instance_id` is non-empty and unique;
- the management adapter's `runtime_name(channel_name, instance_id)` is the single source of routing names, and every derived name is unique and is either the channel name or starts with `<channel-name>.`;
- runtime names cannot overwrite a runtime already owned by another channel;
- settings instance summaries are generated from `instance_specs()` and `ChannelPlugin.setup`. They contain the authoritative `enabled` and `configured` state plus secret-safe `config_values` and `configured_fields` for the generic instance editor;
- the management adapter's `feature_instances()` may return `None` or presentation overrides containing an `id` plus `name`, `display_name`, or `avatar_url`. It cannot override runtime state or the configuration snapshot.
`ChannelInstanceSpec` contains only `instance_id` and the instance config; nanobot derives its runtime name through the adapter. Single-instance plugins keep ownership of their entire config, including a field named `instances`. Only plugins whose management spec sets `multi_instance=True` opt into instance expansion.
The package/config section name owns every runtime produced from that section. Class inheritance does not transfer runtime ownership to another package.
Return a concrete iterable or generator from the adapter's `instance_specs()`; nanobot materializes and validates it before constructing any runtime. Raise an exception for malformed persisted data rather than silently changing instance identity. Keep network-backed metadata refresh behind the runtime's `refresh_feature_metadata()` so feature GET requests remain dependency-free and read-only.
For package layout, WebUI ownership, and localization rules, see [Channel Package Requirements](#channel-package-requirements).
### Optional (streaming)
| Method | Description |
|--------|-------------|
| `async send_delta(chat_id, delta, metadata?, *, stream_id?, stream_end=False, resuming=False)` | Override to receive streaming chunks. See [Streaming Support](#streaming-support) for details. |
### Message Types
```python
@dataclass
class OutboundMessage:
channel: str # your channel name
chat_id: str # recipient (same value you passed to _handle_message)
content: str # markdown text — convert to platform format as needed
media: list[str] # local file paths to attach (images, audio, docs)
metadata: dict # channel routing context, e.g. "message_id" for threading
event: object | None # typed runtime/UI event; usually inspect with isinstance()
```
Runtime/UI semantics live on `msg.event`. Plugin-authored outbound messages should use typed events instead of legacy metadata flags such as `_progress`, `_stream_delta`, `_stream_end`, `_reasoning_delta`, `_turn_end`, or `_goal_status`. nanobot still accepts those old flags as a compatibility bridge for existing in-process extensions, but new plugin code should not add fresh dependencies on them.
## Streaming Support
Channels can opt into real-time streaming — the agent sends content token-by-token instead of one final message. This is entirely optional; channels work fine without it.
### How It Works
When **both** conditions are met, the agent streams content through your channel:
1. Config has `"streaming": true`
2. Your subclass overrides `send_delta()`
If either is missing, the agent falls back to the normal one-shot `send()` path.
### Implementing `send_delta`
Override `send_delta` to handle two types of calls:
```python
async def send_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
stream_end: bool = False,
resuming: bool = False,
) -> None:
buffer_key = stream_id or chat_id
if stream_end:
# Streaming finished — do final formatting, cleanup, etc.
return
# Regular delta — append text, update the message on screen
# delta contains a small chunk of text (a few tokens)
```
Streaming state is passed through keyword-only arguments, not `_stream_delta` or `_stream_end` metadata flags. Use `stream_id` to key any per-stream buffers; fall back to `chat_id` when it is missing.
### Example: Webhook with Streaming
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._buffers: dict[str, str] = {}
async def send_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
stream_end: bool = False,
resuming: bool = False,
) -> None:
buffer_key = stream_id or chat_id
if stream_end:
text = self._buffers.pop(buffer_key, "")
# Final delivery — format and send the complete message
await self._deliver(chat_id, text, final=True)
return
self._buffers.setdefault(buffer_key, "")
self._buffers[buffer_key] += delta
# Incremental update — push partial text to the client
await self._deliver(chat_id, self._buffers[buffer_key], final=False)
async def send(self, msg: OutboundMessage) -> None:
# Non-streaming path — unchanged
await self._deliver(msg.chat_id, msg.content, final=True)
```
### Config
Enable streaming per channel:
```json
{
"channels": {
"webhook": {
"enabled": true,
"streaming": true,
"allowFrom": ["*"]
}
}
}
```
When `streaming` is `false` (default) or omitted, only `send()` is called — no streaming overhead.
### BaseChannel Streaming API
| Method / Property | Description |
|-------------------|-------------|
| `async send_delta(chat_id, delta, metadata?, *, stream_id?, stream_end=False, resuming=False)` | Override to handle streaming chunks. No-op by default. |
| `supports_streaming` (property) | Returns `True` when config has `streaming: true` **and** subclass overrides `send_delta`. |
## Progress, Tool Hints, and Reasoning
Besides normal assistant text, nanobot can emit low-emphasis trace blocks. These are intended for UI affordances like status rows, collapsible "used tools" groups, or reasoning/thinking blocks. Platforms that do not have a good place for them can ignore them safely.
### Progress and Tool Hints
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.event` before rendering:
```python
from nanobot.bus.outbound_events import ProgressEvent
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, ProgressEvent) and event.tool_hint:
# A short tool breadcrumb, e.g. read_file("config.json")
await self._send_trace(msg.chat_id, msg.content, kind="tool")
return
if isinstance(event, ProgressEvent):
# Generic non-final status, e.g. "Thinking..." or "Running command..."
await self._send_trace(msg.chat_id, msg.content, kind="progress")
return
await self._send_message(msg.chat_id, msg.content, media=msg.media)
```
Tool hints are off by default for most channels. Users can enable them globally or per channel:
```json
{
"channels": {
"sendToolHints": true,
"webhook": {
"enabled": true,
"sendToolHints": true
}
}
}
```
### Reasoning Blocks
Reasoning is delivered through dedicated optional hooks, not `send()`. Override `send_reasoning_delta()` and `send_reasoning_end()` if your platform can show model reasoning as a subdued/collapsible block. The default implementation is a no-op, so unsupported channels simply drop reasoning content.
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._reasoning_buffers: dict[str, str] = {}
async def send_reasoning_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
) -> None:
buffer_key = stream_id or chat_id
self._reasoning_buffers[buffer_key] = self._reasoning_buffers.get(buffer_key, "") + delta
await self._update_reasoning_block(chat_id, self._reasoning_buffers[buffer_key], final=False)
async def send_reasoning_end(
self,
chat_id: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
) -> None:
buffer_key = stream_id or chat_id
text = self._reasoning_buffers.pop(buffer_key, "")
if text:
await self._update_reasoning_block(chat_id, text, final=True)
```
**Reasoning arguments:**
| Argument | Meaning |
|------|---------|
| `delta` | A reasoning/thinking chunk for `send_reasoning_delta()`. |
| `stream_id` | Stable id for this assistant turn/segment. Use it to key buffers instead of only `chat_id`. |
| `send_reasoning_end()` | The current reasoning block is complete. |
Reasoning visibility is controlled by `showReasoning` globally or per channel:
```json
{
"channels": {
"showReasoning": true,
"webhook": {
"enabled": true,
"showReasoning": true
}
}
}
```
Recommended rendering:
- Render tool hints and progress as trace/status UI, not as normal assistant replies.
- Render reasoning with lower visual emphasis and collapse it after completion when the platform supports that.
- Keep reasoning separate from final answer text. A final answer still arrives through `send()` or `send_delta()`.
## Config
### Why Pydantic model is required
`BaseChannel.is_allowed()` reads the permission list via `getattr(self.config, "allow_from", [])`. This works for Pydantic models where `allow_from` is a real Python attribute, but **fails silently for plain `dict`**`dict` has no `allow_from` attribute, so `getattr` always returns the default `[]`, causing all messages to be denied.
Channel runtimes use Pydantic config models by subclassing `Base` from `nanobot.config.schema`.
### Pattern
1. Define a Pydantic model inheriting from `nanobot.config.schema.Base`:
```python
from pydantic import Field
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
```
`Base` is configured with `alias_generator=to_camel` and `populate_by_name=True`, so JSON keys like `"allowFrom"` and `"allow_from"` are both accepted.
2. Convert `dict` → model in `__init__`:
```python
from typing import Any
from nanobot.bus.queue import MessageBus
class WebhookChannel(BaseChannel):
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
```
3. Access config as attributes (not `.get()`):
```python
async def start(self) -> None:
port = self.config.port
token = self.config.token
```
`allowFrom` is handled automatically by `_handle_message()` — you don't need to check it yourself.
`nanobot onboard` reads the descriptor without importing the runtime. Put writable defaults in `ChannelSetupSpec`:
```python
setup=ChannelSetupSpec(
fields={
"port": ChannelFieldSpec(kind="int", default=9000),
"allowFrom": ChannelFieldSpec(kind="list"),
},
)
```
String and secret fields default to `""`, list fields to `[]`, and boolean fields to `false` when no explicit default is declared. For non-setup or multi-instance persisted defaults, provide `ChannelManagementSpec.default_config` from a dependency-free package-local module.
## Naming Convention
| What | Format | Example |
|------|--------|---------|
| Package directory | `nanobot/channels/{name}` | `nanobot/channels/webhook` |
| Manifest name | `{name}` | `webhook` |
| Config section | `channels.{name}` | `channels.webhook` |
| Runtime import | `nanobot.channels.{name}.runtime` | `nanobot.channels.webhook.runtime` |
## Local Development
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install -e .
nanobot plugins list # should show the package as "webhook"
nanobot gateway # test end-to-end
```
## Verify
```bash
$ nanobot plugins list
Name Type Enabled
discord channel no
telegram channel yes
webhook channel yes
```
-568
View File
@@ -1,568 +0,0 @@
# Channel Plugin Guide
Build a custom nanobot channel in three steps: subclass, package, install.
> **Note:** We recommend developing channel plugins against a source checkout of nanobot (`python -m pip install -e .`) rather than a PyPI release, so you always have access to the latest base-channel features and APIs.
## How It Works
nanobot discovers channel plugins via Python [entry points](https://packaging.python.org/en/latest/specifications/entry-points/). When `nanobot gateway` starts, it scans:
1. Built-in channels in `nanobot/channels/`
2. External packages registered under the `nanobot.channels` entry point group
If a matching config section has `"enabled": true`, the channel is instantiated and started.
## Quick Start
We'll build a minimal webhook channel that receives messages via HTTP POST and sends replies back.
### Project Structure
```text
nanobot-channel-webhook/
├── nanobot_channel_webhook/
│ ├── __init__.py # re-export WebhookChannel
│ └── channel.py # channel implementation
└── pyproject.toml
```
### 1. Create Your Channel
```python
# nanobot_channel_webhook/__init__.py
from nanobot_channel_webhook.channel import WebhookChannel
__all__ = ["WebhookChannel"]
```
```python
# nanobot_channel_webhook/channel.py
import asyncio
from typing import Any
from aiohttp import web
from loguru import logger
from pydantic import Field
from nanobot.channels.base import BaseChannel
from nanobot.bus.events import OutboundMessage
from nanobot.bus.queue import MessageBus
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
@classmethod
def default_config(cls) -> dict[str, Any]:
return WebhookConfig().model_dump(by_alias=True)
async def start(self) -> None:
"""Start an HTTP server that listens for incoming messages.
IMPORTANT: start() must block forever (or until stop() is called).
If it returns, the channel is considered dead.
"""
self._running = True
port = self.config.port
app = web.Application()
app.router.add_post("/message", self._on_request)
runner = web.AppRunner(app)
await runner.setup()
site = web.TCPSite(runner, "0.0.0.0", port)
await site.start()
logger.info("Webhook listening on :{}", port)
# Block until stopped
while self._running:
await asyncio.sleep(1)
await runner.cleanup()
async def stop(self) -> None:
self._running = False
async def send(self, msg: OutboundMessage) -> None:
"""Deliver an outbound message.
msg.content — markdown text (convert to platform format as needed)
msg.media — list of local file paths to attach
msg.chat_id — the recipient (same chat_id you passed to _handle_message)
msg.metadata — channel routing context such as message/thread ids
msg.event — typed runtime event for progress/status messages
"""
logger.info("[webhook] -> {}: {}", msg.chat_id, msg.content[:80])
# In a real plugin: POST to a callback URL, send via SDK, etc.
async def _on_request(self, request: web.Request) -> web.Response:
"""Handle an incoming HTTP POST."""
body = await request.json()
sender = body.get("sender", "unknown")
chat_id = body.get("chat_id", sender)
text = body.get("text", "")
media = body.get("media", []) # list of URLs
# This is the key call: validates allowFrom, then puts the
# message onto the bus for the agent to process.
await self._handle_message(
sender_id=sender,
chat_id=chat_id,
content=text,
media=media,
)
return web.json_response({"ok": True})
```
### 2. Register the Entry Point
```toml
# pyproject.toml
[project]
name = "nanobot-channel-webhook"
version = "0.1.0"
dependencies = ["nanobot-ai", "aiohttp"]
[project.entry-points."nanobot.channels"]
webhook = "nanobot_channel_webhook:WebhookChannel"
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[tool.hatch.build.targets.wheel]
packages = ["nanobot_channel_webhook"]
```
The key (`webhook`) becomes the config section name. The value points to your `BaseChannel` subclass.
### 3. Install & Configure
```bash
python -m pip install -e .
nanobot plugins list # verify "Webhook" shows as "plugin"
nanobot onboard # auto-adds default config for detected plugins
```
Edit `~/.nanobot/config.json`:
```json
{
"channels": {
"webhook": {
"enabled": true,
"port": 9000,
"allowFrom": ["*"]
}
}
}
```
### 4. Run & Test
```bash
nanobot gateway
```
In another terminal:
```bash
curl -X POST http://localhost:9000/message \
-H "Content-Type: application/json" \
-d '{"sender": "user1", "chat_id": "user1", "text": "Hello!"}'
```
The agent receives the message and processes it. Replies arrive in your `send()` method.
## BaseChannel API
### Required (abstract)
| Method | Description |
|--------|-------------|
| `async start()` | **Must block forever.** Connect to platform, listen for messages, call `_handle_message()` on each. If this returns, the channel is dead. |
| `async stop()` | Set `self._running = False` and clean up. Called when gateway shuts down. |
| `async send(msg: OutboundMessage)` | Deliver an outbound message to the platform. |
### Interactive Login
If your channel requires interactive authentication (e.g. QR code scan), override `login(force=False)`:
```python
async def login(self, force: bool = False) -> bool:
"""
Perform channel-specific interactive login.
Args:
force: If True, ignore existing credentials and re-authenticate.
Returns True if already authenticated or login succeeds.
"""
# For QR-code-based login:
# 1. If force, clear saved credentials
# 2. Check if already authenticated (load from disk/state)
# 3. If not, show QR code and poll for confirmation
# 4. Save token on success
```
Channels that don't need interactive login (e.g. Telegram with bot token, Discord with bot token) inherit the default `login()` which just returns `True`.
Users trigger interactive login via:
```bash
nanobot channels login <channel_name>
nanobot channels login <channel_name> --force # re-authenticate
```
### Provided by Base
| Method / Property | Description |
|-------------------|-------------|
| `_handle_message(sender_id, chat_id, content, media?, metadata?, session_key?)` | **Call this when you receive a message.** Checks `is_allowed()`, then publishes to the bus. Automatically sets `_wants_stream` if `supports_streaming` is true. |
| `is_allowed(sender_id)` | Checks against `config.allow_from`; `"*"` allows all, `[]` denies all. |
| `default_config()` (classmethod) | Returns default config dict for `nanobot onboard`. Override to declare your fields. |
| `transcribe_audio(file_path)` | Transcribes audio via the shared top-level `transcription` config (if configured). |
| `supports_streaming` (property) | `True` when config has `"streaming": true` **and** subclass overrides `send_delta()`. |
| `is_running` | Returns `self._running`. |
| `login(force=False)` | Perform interactive login (e.g. QR code scan). Returns `True` if already authenticated or login succeeds. Override in subclasses that support interactive login. |
| `send_reasoning_delta(chat_id, delta, metadata?, *, 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?, *, stream_id?, stream_end=False, resuming=False)` | Override to receive streaming chunks. See [Streaming Support](#streaming-support) for details. |
### Message Types
```python
@dataclass
class OutboundMessage:
channel: str # your channel name
chat_id: str # recipient (same value you passed to _handle_message)
content: str # markdown text — convert to platform format as needed
media: list[str] # local file paths to attach (images, audio, docs)
metadata: dict # channel routing context, e.g. "message_id" for threading
event: object | None # typed runtime/UI event; usually inspect with isinstance()
```
Runtime/UI semantics live on `msg.event`. Plugin-authored outbound messages should use typed events instead of legacy metadata flags such as `_progress`, `_stream_delta`, `_stream_end`, `_reasoning_delta`, `_turn_end`, or `_goal_status`. nanobot still accepts those old flags as a compatibility bridge for existing in-process extensions, but new plugin code should not add fresh dependencies on them.
## Streaming Support
Channels can opt into real-time streaming — the agent sends content token-by-token instead of one final message. This is entirely optional; channels work fine without it.
### How It Works
When **both** conditions are met, the agent streams content through your channel:
1. Config has `"streaming": true`
2. Your subclass overrides `send_delta()`
If either is missing, the agent falls back to the normal one-shot `send()` path.
### Implementing `send_delta`
Override `send_delta` to handle two types of calls:
```python
async def send_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
stream_end: bool = False,
resuming: bool = False,
) -> None:
buffer_key = stream_id or chat_id
if stream_end:
# Streaming finished — do final formatting, cleanup, etc.
return
# Regular delta — append text, update the message on screen
# delta contains a small chunk of text (a few tokens)
```
Streaming state is passed through keyword-only arguments, not `_stream_delta` or `_stream_end` metadata flags. Use `stream_id` to key any per-stream buffers; fall back to `chat_id` when it is missing.
### Example: Webhook with Streaming
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._buffers: dict[str, str] = {}
async def send_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
stream_end: bool = False,
resuming: bool = False,
) -> None:
buffer_key = stream_id or chat_id
if stream_end:
text = self._buffers.pop(buffer_key, "")
# Final delivery — format and send the complete message
await self._deliver(chat_id, text, final=True)
return
self._buffers.setdefault(buffer_key, "")
self._buffers[buffer_key] += delta
# Incremental update — push partial text to the client
await self._deliver(chat_id, self._buffers[buffer_key], final=False)
async def send(self, msg: OutboundMessage) -> None:
# Non-streaming path — unchanged
await self._deliver(msg.chat_id, msg.content, final=True)
```
### Config
Enable streaming per channel:
```json
{
"channels": {
"webhook": {
"enabled": true,
"streaming": true,
"allowFrom": ["*"]
}
}
}
```
When `streaming` is `false` (default) or omitted, only `send()` is called — no streaming overhead.
### BaseChannel Streaming API
| Method / Property | Description |
|-------------------|-------------|
| `async send_delta(chat_id, delta, metadata?, *, stream_id?, stream_end=False, resuming=False)` | Override to handle streaming chunks. No-op by default. |
| `supports_streaming` (property) | Returns `True` when config has `streaming: true` **and** subclass overrides `send_delta`. |
## Progress, Tool Hints, and Reasoning
Besides normal assistant text, nanobot can emit low-emphasis trace blocks. These are intended for UI affordances like status rows, collapsible "used tools" groups, or reasoning/thinking blocks. Platforms that do not have a good place for them can ignore them safely.
### Progress and Tool Hints
Progress and tool hints arrive through the normal `send(msg)` path. Check `msg.event` before rendering:
```python
from nanobot.bus.outbound_events import ProgressEvent
async def send(self, msg: OutboundMessage) -> None:
event = msg.event
if isinstance(event, ProgressEvent) and event.tool_hint:
# A short tool breadcrumb, e.g. read_file("config.json")
await self._send_trace(msg.chat_id, msg.content, kind="tool")
return
if isinstance(event, ProgressEvent):
# Generic non-final status, e.g. "Thinking..." or "Running command..."
await self._send_trace(msg.chat_id, msg.content, kind="progress")
return
await self._send_message(msg.chat_id, msg.content, media=msg.media)
```
Tool hints are off by default for most channels. Users can enable them globally or per channel:
```json
{
"channels": {
"sendToolHints": true,
"webhook": {
"enabled": true,
"sendToolHints": true
}
}
}
```
### Reasoning Blocks
Reasoning is delivered through dedicated optional hooks, not `send()`. Override `send_reasoning_delta()` and `send_reasoning_end()` if your platform can show model reasoning as a subdued/collapsible block. The default implementation is a no-op, so unsupported channels simply drop reasoning content.
```python
class WebhookChannel(BaseChannel):
name = "webhook"
display_name = "Webhook"
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
self._reasoning_buffers: dict[str, str] = {}
async def send_reasoning_delta(
self,
chat_id: str,
delta: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
) -> None:
buffer_key = stream_id or chat_id
self._reasoning_buffers[buffer_key] = self._reasoning_buffers.get(buffer_key, "") + delta
await self._update_reasoning_block(chat_id, self._reasoning_buffers[buffer_key], final=False)
async def send_reasoning_end(
self,
chat_id: str,
metadata: dict[str, Any] | None = None,
*,
stream_id: str | None = None,
) -> None:
buffer_key = stream_id or chat_id
text = self._reasoning_buffers.pop(buffer_key, "")
if text:
await self._update_reasoning_block(chat_id, text, final=True)
```
**Reasoning arguments:**
| Argument | Meaning |
|------|---------|
| `delta` | A reasoning/thinking chunk for `send_reasoning_delta()`. |
| `stream_id` | Stable id for this assistant turn/segment. Use it to key buffers instead of only `chat_id`. |
| `send_reasoning_end()` | The current reasoning block is complete. |
Reasoning visibility is controlled by `showReasoning` globally or per channel:
```json
{
"channels": {
"showReasoning": true,
"webhook": {
"enabled": true,
"showReasoning": true
}
}
}
```
Recommended rendering:
- Render tool hints and progress as trace/status UI, not as normal assistant replies.
- Render reasoning with lower visual emphasis and collapse it after completion when the platform supports that.
- Keep reasoning separate from final answer text. A final answer still arrives through `send()` or `send_delta()`.
## Config
### Why Pydantic model is required
`BaseChannel.is_allowed()` reads the permission list via `getattr(self.config, "allow_from", [])`. This works for Pydantic models where `allow_from` is a real Python attribute, but **fails silently for plain `dict`**`dict` has no `allow_from` attribute, so `getattr` always returns the default `[]`, causing all messages to be denied.
Built-in channels use Pydantic config models (subclassing `Base` from `nanobot.config.schema`). Plugin channels **must do the same**.
### Pattern
1. Define a Pydantic model inheriting from `nanobot.config.schema.Base`:
```python
from pydantic import Field
from nanobot.config.schema import Base
class WebhookConfig(Base):
"""Webhook channel configuration."""
enabled: bool = False
port: int = 9000
allow_from: list[str] = Field(default_factory=list)
```
`Base` is configured with `alias_generator=to_camel` and `populate_by_name=True`, so JSON keys like `"allowFrom"` and `"allow_from"` are both accepted.
2. Convert `dict` → model in `__init__`:
```python
from typing import Any
from nanobot.bus.queue import MessageBus
class WebhookChannel(BaseChannel):
def __init__(self, config: Any, bus: MessageBus):
if isinstance(config, dict):
config = WebhookConfig(**config)
super().__init__(config, bus)
```
3. Access config as attributes (not `.get()`):
```python
async def start(self) -> None:
port = self.config.port
token = self.config.token
```
`allowFrom` is handled automatically by `_handle_message()` — you don't need to check it yourself.
Override `default_config()` so `nanobot onboard` auto-populates `config.json`:
```python
@classmethod
def default_config(cls) -> dict[str, Any]:
return WebhookConfig().model_dump(by_alias=True)
```
> **Note:** `default_config()` returns a plain `dict` (not a Pydantic model) because it's used to serialize into `config.json`. The recommended way is to instantiate your config model and call `model_dump(by_alias=True)` — this automatically uses camelCase keys (`allowFrom`) and keeps defaults in a single source of truth.
If not overridden, the base class returns `{"enabled": false}`.
## Naming Convention
| What | Format | Example |
|------|--------|---------|
| PyPI package | `nanobot-channel-{name}` | `nanobot-channel-webhook` |
| Entry point key | `{name}` | `webhook` |
| Config section | `channels.{name}` | `channels.webhook` |
| Python package | `nanobot_channel_{name}` | `nanobot_channel_webhook` |
## Local Development
```bash
git clone https://github.com/you/nanobot-channel-webhook
cd nanobot-channel-webhook
python -m pip install -e .
nanobot plugins list # should show "Webhook" as "plugin"
nanobot gateway # test end-to-end
```
## Verify
```bash
$ nanobot plugins list
Name Source Enabled
telegram builtin yes
discord builtin no
webhook plugin yes
```
+112 -21
View File
@@ -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 Package Guide](./channel-package-guide.md).
Before configuring a chat app, make sure the local CLI path works:
@@ -10,33 +26,67 @@ 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`.
## Recommended Setup in the WebUI
## Common Setup Pattern
For normal local setup, let the WebUI write and validate the channel config:
1. Run `nanobot webui`.
2. Open **Settings → Channels**.
3. Search for the platform and open its setup panel.
4. Follow the credential fields or QR flow. The screen tells you which platform-side token, permission, account, or URL it needs.
5. Let nanobot install the optional channel support when prompted.
6. Restart from the WebUI if it reports that a restart is required.
7. Send a private test message. If the channel returns a pairing code, approve the pending request in the WebUI and send the message again.
If your installed stable release does not show **Settings → Channels**, continue with the [manual setup pattern](#manual-setup-pattern) below or install current source.
Optional package installation is available to a same-machine WebUI by default. Remote browser clients cannot change the Python environment unless an administrator explicitly enables that capability. Run `nanobot plugins enable <channel>` locally when the guided install is unavailable.
The sections below explain what each chat platform requires and provide manual config for deployments that manage `config.json` directly.
> [!NOTE]
> If you are upgrading from a version where chat app SDKs were installed by default,
> install the channel extra in the same Python environment before enabling or
> restarting that channel:
>
> ```bash
> nanobot plugins enable <channel>
> ```
>
> Replace `<channel>` with names such as `telegram`, `slack`, `feishu`,
> `dingtalk`, `matrix`, `qq`, `napcat`, `weixin`, `wecom`, or `msteams`.
> To turn a channel off later, run `nanobot plugins disable <channel>`.
> nanobot keeps the saved settings, but stops loading that channel after the
> next restart.
## Manual Setup Pattern
Most examples below are snippets to merge into `~/.nanobot/config.json`. When a snippet includes `allowFrom`, it is showing a static allowlist. For pairing-based access on supported channels, omit `allowFrom`; Slack and Mattermost also need `dm.policy` set to `"allowlist"` for DMs to issue pairing codes.
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 +109,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
@@ -123,6 +179,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):
@@ -233,14 +297,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**
@@ -306,9 +370,7 @@ nanobot gateway
Requires the WhatsApp optional dependencies:
```bash
pip install "nanobot-ai[whatsapp]"
# Source checkout:
python -m pip install -e ".[whatsapp]"
nanobot plugins enable whatsapp
```
**1. Link device with QR**
@@ -331,6 +393,10 @@ nanobot channels login whatsapp
}
```
For groups, `allowFrom` can contain either a participant sender ID/LID or a
group JID/bare group ID. A participant entry allows that sender wherever the bot
can see them; a group entry allows replies in that group.
Optional session database path:
```json
@@ -384,6 +450,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
```
@@ -454,6 +521,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
@@ -506,6 +579,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
@@ -543,6 +622,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
@@ -585,6 +670,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
@@ -695,10 +786,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**
@@ -747,10 +838,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**
@@ -786,10 +877,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**
+5
View File
@@ -15,6 +15,8 @@ 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 |
@@ -116,6 +118,9 @@ Manage triggers from the WebUI Automations view. You can search, pause/resume,
rename, delete, and copy the trigger command there. A session may have multiple
triggers, just like it may have multiple scheduled automations.
See [Automations](./automations.md) for how local triggers fit with scheduled
automations, heartbeat, and gateway delivery.
## Periodic Tasks
Periodic background checks are driven by `HEARTBEAT.md` in your workspace (`~/.nanobot/workspace/HEARTBEAT.md`). When `nanobot gateway` starts, it registers a protected heartbeat cron job by default. Every 30 minutes, that job checks the file; if it finds tasks under `## Active Tasks`, the agent executes them and delivers only results that pass the notification gate to your most recently active chat channel. If there are no active tasks, or the result is routine with nothing useful to report, the heartbeat is skipped silently.
+71 -6
View File
@@ -8,14 +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 |
@@ -56,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 |
@@ -78,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 |
|---|---|
@@ -169,6 +188,9 @@ 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 |
@@ -187,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
@@ -195,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
@@ -206,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:
@@ -217,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 |
+3 -3
View File
@@ -12,7 +12,7 @@ nanobot has one small core loop and several ways to enter it:
|---|---|
| Agent loop | Builds context, selects the session, calls the provider, runs tools, and publishes replies |
| Providers | LLM backends such as OpenRouter, Anthropic, OpenAI, Bedrock, Ollama, vLLM, and other OpenAI-compatible APIs |
| Channels | User-facing transports such as CLI, WebUI/WebSocket, Telegram, Discord, Slack, Feishu, WeChat, Email, 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 |
@@ -64,9 +64,9 @@ That flow is the same whether the message starts in the CLI, WebUI, Telegram, Di
| CLI interactive | `nanobot agent` | Terminal chat with persistent session history |
| Gateway | `nanobot gateway` | Chat apps, WebUI, heartbeat, Dream, and long-running service mode |
| OpenAI-compatible API | `nanobot serve` | Programmatic access through `/v1/chat/completions` |
| WebUI | `nanobot gateway` plus WebSocket channel | Browser workbench served by the WebSocket channel on port `8765` |
| WebUI | `nanobot webui` | Prepare the local WebUI, start the gateway, and open the browser workbench |
The gateway health endpoint is on `gateway.port` (`18790` by default). The browser WebUI is served by the WebSocket channel (`8765` by default), not by the health endpoint.
The WebUI launcher is the normal browser entry point. Underneath, the gateway keeps the WebSocket channel and other long-running services alive. The gateway health endpoint is on `gateway.port` (`18790` by default); the browser WebUI is served on `8765` by default, not by the health endpoint.
## Provider and Model Selection
+98 -69
View File
@@ -4,6 +4,8 @@ Config file: `~/.nanobot/config.json`
This is the full reference. If this is your first install, start with [`quick-start.md`](./quick-start.md). If you are trying to choose a model or fix provider/model matching, use [`providers.md`](./providers.md) first and come back here for exact fields and advanced options.
For normal local use, prefer the WebUI before editing JSON: **Settings → Models** manages model choices and provider credentials, **Settings → Channels** guides chat-platform setup, other Settings pages cover built-in capabilities, and **Apps** manages CLI App and MCP integrations. Edit `config.json` directly when you need an advanced field, automate deployment, or intentionally manage configuration as code.
The JSON examples below are usually partial snippets to merge into your existing config, not full replacement files. For the mental model behind config, workspace, gateway, channels, sessions, tools, and memory, see [`concepts.md`](./concepts.md).
The generated `config.json` uses camelCase keys such as `apiKey` and `intervalS`. snake_case keys are also accepted for compatibility, but the docs prefer camelCase because that is what nanobot writes back to disk.
@@ -11,7 +13,22 @@ The generated `config.json` uses camelCase keys such as `apiKey` and `intervalS`
For setup and runtime failures, follow the diagnosis order in [`troubleshooting.md`](./troubleshooting.md) before changing multiple config areas at once.
> [!NOTE]
> If your config file is older than the current schema, 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.
> If your config file is older than the current schema, run `nanobot onboard --refresh`. nanobot adds missing default fields while preserving your existing values.
## Configuration Guides
This page is the complete configuration reference. For task-oriented setup, use
the focused guides first and come back here for exact fields and defaults.
| Task | Guide |
|---|---|
| Add MCP tools | [`guides/configure-mcp-tools.md`](./guides/configure-mcp-tools.md) |
| Enable web search and web fetch | [`guides/configure-web-search.md`](./guides/configure-web-search.md) |
| Configure model fallback | [`guides/configure-model-fallback.md`](./guides/configure-model-fallback.md) |
| Add an OpenAI-compatible provider | [`guides/configure-openai-compatible-provider.md`](./guides/configure-openai-compatible-provider.md) |
| Add Langfuse observability | [`guides/configure-langfuse-observability.md`](./guides/configure-langfuse-observability.md) |
| Secure a local AI agent | [`guides/secure-local-ai-agent.md`](./guides/secure-local-ai-agent.md) |
| Deploy the gateway | [`guides/deploy-nanobot-gateway.md`](./guides/deploy-nanobot-gateway.md) |
## Quick Jump
@@ -32,24 +49,24 @@ For setup and runtime failures, follow the diagnosis order in [`troubleshooting.
| Control access and pairing | [Pairing](#pairing) |
| Tune gateway jobs, sessions, and tools | [Gateway Heartbeat](#gateway-heartbeat), [Auto Compact](#auto-compact), [Unified Session](#unified-session), [Tool Hint Max Length](#tool-hint-max-length) |
## Where to Edit First
## Where a Setting Lives
If you are not sure where a setting belongs, start from the task you are trying to complete. Most changes touch one config section and one verification command.
If the WebUI does not expose the option you need, start from the task below. Most advanced changes touch one config section and one verification command.
| Task | First keys to check | Verify with | Deep dive |
|---|---|---|---|
| Make the first model reply work | `providers.<name>.apiKey`, optional `providers.<name>.apiBase`, `modelPresets.<preset>`, `agents.defaults.modelPreset` | `nanobot status`, then `nanobot agent -m "Hello!"` | [Providers](#providers), [Model Presets](#model-presets) |
| Add fallback models | `modelPresets.<fallback>`, `agents.defaults.fallbackModels` | `nanobot status`, then a normal agent run | [Model Fallbacks](#model-fallbacks) |
| Keep secrets out of the config file | `${ENV_VAR}` placeholders inside any string value | Start nanobot from the same environment that sets the variable | [Environment Variables for Secrets](#environment-variables-for-secrets) |
| Open the bundled WebUI | `channels.websocket.enabled`, optional `channels.websocket.port`, `channels.websocket.tokenIssueSecret` | `nanobot 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) |
| 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
@@ -170,7 +187,7 @@ These variables are process-level switches. Set them in the same terminal, servi
| Variable | Default | Description |
|----------|---------|-------------|
| `NANOBOT_MAX_CONCURRENT_REQUESTS` | `3` | Maximum concurrently running inbound agent requests. Must be an integer; set `0` or a negative value for unlimited. |
| `NANOBOT_LLM_TIMEOUT_S` | `300` | Wall-clock timeout, in seconds, around ordinary LLM requests. Set `0` to disable. Sustained-goal turns bypass this wall-clock cap. |
| `NANOBOT_LLM_TIMEOUT_S` | `300` | Wall-clock timeout, in seconds. Ordinary requests use this value; streaming requests use the greater of 300 seconds or twice this value. Set `0` to disable. Sustained-goal turns bypass this wall-clock cap. |
| `NANOBOT_STREAM_IDLE_TIMEOUT_S` | `90` | Streaming idle timeout, in seconds, used by streaming providers. Invalid or non-positive values are ignored; values above `3600` are clamped. |
| `NANOBOT_OPENAI_COMPAT_TIMEOUT_S` | `120` | HTTP request timeout, in seconds, for OpenAI-compatible providers. Invalid or non-positive values are ignored. |
| `NANOBOT_WORKSPACE_SANDBOX_ENFORCED` | unset | Marks that an external workspace sandbox is already enforced. Truthy values (`1`, `true`, `yes`, `on`, `enabled`) use `NANOBOT_WORKSPACE_SANDBOX_PROVIDER` as the label; any other non-false value is treated as the provider name. |
@@ -198,7 +215,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`:
@@ -232,7 +249,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`.
@@ -246,7 +263,8 @@ Tracing covers the providers that go through nanobot's OpenAI-compatible client
|----------|---------|-------------|
| `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 +300,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 +398,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 +413,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 +457,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,61 +662,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. `nanobot provider login` stores the OAuth session outside config. A `providers.openai_codex` block is optional and is only needed for provider-specific settings such as a proxy.
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
```
If the machine running nanobot cannot open a graphical browser, copy the printed URL into a real browser. For remote SSH login, open the URL locally, then paste the final `http://localhost:1455/auth/callback?...` redirect URL back into the terminal when prompted.
Then run:
**2. Optional proxy** (merge into `~/.nanobot/config.json` if Codex OAuth or Codex API traffic must use a proxy):
```json
{
"providers": {
"openai_codex": {
"proxy": "http://127.0.0.1:7890"
}
}
}
```
The proxy applies to Codex OAuth token refresh, interactive token exchange, and Codex Responses API requests. It does not affect other providers; configure `proxy` separately on each supported provider that needs it.
**3. Set model** (merge into `~/.nanobot/config.json`):
```json
{
"modelPresets": {
"codex": {
"provider": "openai_codex",
"model": "gpt-5.1-codex",
"reasoningEffort": "high"
}
},
"agents": {
"defaults": {
"modelPreset": "codex"
}
}
}
```
Use `reasoningEffort` in the preset to send a Codex reasoning effort such as `"low"`, `"medium"`, `"high"`, or another value supported by the selected model. When `provider` is explicitly `openai_codex`, the model name does not need the `openai-codex/` prefix.
**4. 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>
@@ -753,6 +740,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>` |
@@ -761,13 +749,13 @@ OpenCode Zen:
```json
{
"providers": {
"opencodeZen": {
"opencode": {
"apiKey": "${OPENCODE_API_KEY}"
}
},
"modelPresets": {
"opencodeZen": {
"provider": "opencode_zen",
"provider": "opencode",
"model": "opencode/deepseek-v4-pro"
}
},
@@ -779,6 +767,8 @@ OpenCode Zen:
}
```
`providers.opencodeZen` / `provider: "opencode_zen"` still work as compatibility aliases for existing configs.
OpenCode Go:
```json
@@ -1510,8 +1500,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`.
@@ -1585,18 +1575,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
@@ -1739,6 +1732,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
{
@@ -1770,7 +1779,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 (110) |
@@ -1906,10 +1915,11 @@ For API keys, tokens, and other secrets, see [Environment Variables for Secrets]
| `tools.exec.timeout` | `60` | Default hard timeout in seconds for shell commands. Config values may exceed the per-call tool cap; set `0` to disable the hard timeout for trusted long-running commands. |
| `tools.exec.pathPrepend` | `""` | Extra directories to prepend to `PATH` when running shell commands. Use this when configured tools should win executable lookup precedence, such as a Python virtual environment's `bin` or `Scripts` directory. |
| `tools.exec.pathAppend` | `""` | Extra directories to append to `PATH` when running shell commands (e.g. `/usr/sbin` for `ufw`). |
| `tools.webuiAllowRemotePackageInstall` | `false` | When `false`, the WebUI can install missing optional packages only from a browser opened on the same machine as nanobot. Set to `true` only when a trusted remote admin is allowed to install Python packages into this nanobot environment. |
| `tools.ssrfWhitelist` | `[]` | CIDR ranges exempted from the shared SSRF guard used by web fetches and HTTP/SSE MCP connections. Prefer exact host CIDRs such as `192.168.1.50/32`; broad ranges increase SSRF exposure. |
| `channels.*.allowFrom` | omitted | Access control per channel. Omit to use pairing-only mode; set `["*"]` to allow everyone; or list specific user IDs. See [Pairing](#pairing) for details. |
**Docker security**: The official Docker image runs as a non-root user (`nanobot`, UID 1000) with bubblewrap pre-installed. When using `docker-compose.yml`, the container drops all Linux capabilities except `SYS_ADMIN` (required for bwrap's namespace isolation).
**Docker security**: The official Docker image runs as a non-root user (`nanobot`, UID 1000) with bubblewrap pre-installed. The default `docker-compose.yml` drops all Linux capabilities and keeps Docker's default AppArmor/seccomp profiles enabled. If you enable `"tools.exec.sandbox": "bwrap"` inside Docker, start Compose with `docker-compose.bwrap.yml` as an additional override so bubblewrap can create nested namespaces.
## Pairing
@@ -1918,7 +1928,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:
@@ -1932,7 +1942,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
{
@@ -1944,6 +1954,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
@@ -2006,6 +2031,10 @@ The heartbeat job is backed by the same cron service as user-created reminders.
| `gateway.heartbeat.keepRecentMessages` | `8` | Number of recent heartbeat-session messages to retain after each run. |
| `gateway.restartMode` | `auto` | Restart strategy for `/restart`: `auto` uses `spawn` on Windows foreground runs and `exec` elsewhere. Use `exit` with Windows service wrappers such as WinSW or nssm so the service manager owns the restart. |
### Custom heartbeat evaluator prompt
The notification gate runs on a built-in system prompt. Advanced users can override it, but you rarely need to — it's strongly advised to first read the evaluator code and the default `evaluator.md`. To override, drop your prompt at `<workspace>/prompts/evaluator.md`. It must still instruct the model to call the `evaluate_notification` tool; otherwise the gate fails closed and stays silent.
## Subagent Concurrency
+33 -10
View File
@@ -13,7 +13,7 @@ Check these once before Docker, systemd, or LaunchAgent:
| Secrets are in environment variables or protected config files | API keys, bot tokens, OAuth state, and chat credentials should not be world-readable |
| `~/.nanobot/` or your custom config/workspace path is persistent | Sessions, memory, channel login state, generated artifacts, and cron jobs live there |
| Channel access control is intentional | Use `allowFrom`, pairing, WebSocket `token`/`tokenIssueSecret`, or private test channels before exposing the bot |
| Ports are planned | Gateway health defaults to `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
@@ -70,6 +74,20 @@ docker compose logs -f nanobot-gateway # view logs
docker compose down # stop
```
The default Compose file drops all Linux capabilities and keeps Docker's default
AppArmor/seccomp profiles enabled. If you explicitly set
`"tools.exec.sandbox": "bwrap"` in `~/.nanobot/config.json`, add the bwrap
override file when starting containers:
```bash
docker compose -f docker-compose.yml -f docker-compose.bwrap.yml up -d nanobot-gateway
docker compose -f docker-compose.yml -f docker-compose.bwrap.yml run --rm nanobot-cli agent -m "Hello!"
```
The override grants `CAP_SYS_ADMIN` and disables AppArmor/seccomp confinement for
the container so bubblewrap can create its nested namespaces. Use it only when the
bwrap sandbox is enabled.
### Docker
```bash
@@ -83,18 +101,23 @@ docker run -v ~/.nanobot:/home/nanobot/.nanobot --rm nanobot onboard
vim ~/.nanobot/config.json
# Run gateway (connects to enabled channels, e.g. Telegram/Discord/Mochat).
# Mirrors the security caps and port mappings declared in docker-compose.yml:
# - `--cap-drop ALL --cap-add SYS_ADMIN` + unconfined apparmor/seccomp are required
# when `tools.exec.sandbox: "bwrap"` is enabled (bwrap needs CAP_SYS_ADMIN for
# user namespaces). Without them, `bwrap` exits with `clone3: Operation not permitted`.
# - `-p 8765:8765` exposes the WebSocket channel / WebUI alongside the gateway health
# endpoint on 18790.
# `-p 8765:8765` exposes the WebSocket channel / WebUI alongside the gateway
# health endpoint on 18790.
docker run \
--cap-drop ALL \
-v ~/.nanobot:/home/nanobot/.nanobot \
-p 18790:18790 -p 8765:8765 \
nanobot gateway
# If `tools.exec.sandbox: "bwrap"` is enabled, run with the extra permissions
# bubblewrap needs for nested namespaces. Without them, `bwrap` may exit with
# `clone3: Operation not permitted`.
docker run \
--cap-drop ALL --cap-add SYS_ADMIN \
--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
+49
View File
@@ -0,0 +1,49 @@
# nanobot Task Guides
Start with [Install and Quick Start](../quick-start.md) and get one reply before using a guide below. Each guide targets one outcome; linked reference pages hold the complete option tables and edge cases.
## Start and Use
| Goal | Guide |
|---|---|
| Build a personal AI agent | [Build a personal AI agent](./build-a-personal-ai-agent.md) |
| Use the browser workbench | [AI agent WebUI](./ai-agent-webui.md) |
| Run a self-hosted AI agent | [Self-hosted AI agent](./self-hosted-ai-agent.md) |
| Run a sustained goal | [Long-running AI agent](./long-running-ai-agent.md) |
| Add long-term memory | [AI agent memory](./ai-agent-memory.md) |
## Connect a Chat App
Use **Settings → Channels** in the WebUI for guided setup. These guides explain the account, bot, token, permission, and test-message steps on each platform.
| Goal | Guide |
|---|---|
| Connect chat apps | [Chat app AI agent](./chat-app-ai-agent.md) |
| Connect Telegram | [Telegram AI agent](./telegram-ai-agent.md) |
| Connect Discord | [Discord AI agent](./discord-ai-agent.md) |
| Connect Slack | [Slack AI agent](./slack-ai-agent.md) |
| Connect Feishu | [Feishu AI agent](./feishu-ai-agent.md) |
| Connect WhatsApp | [WhatsApp AI agent](./whatsapp-ai-agent.md) |
| Connect WeChat | [WeChat AI agent](./wechat-ai-agent.md) |
| Connect QQ | [QQ AI agent](./qq-ai-agent.md) |
| Connect Email | [Email AI agent](./email-ai-agent.md) |
| Connect Mattermost | [Mattermost AI agent](./mattermost-ai-agent.md) |
## Integrate from Code
| Goal | Guide |
|---|---|
| Run from Python | [Python AI agent SDK](./python-ai-agent-sdk.md) |
| Expose `/v1/chat/completions` | [OpenAI-compatible agent API](./openai-compatible-agent-api.md) |
## Configure and Operate
| Goal | Guide |
|---|---|
| Add MCP tools | [Configure MCP tools](./configure-mcp-tools.md) |
| Enable web search | [Configure web search](./configure-web-search.md) |
| Add model fallback | [Configure model fallback](./configure-model-fallback.md) |
| Add an OpenAI-compatible provider | [Configure an OpenAI-compatible provider](./configure-openai-compatible-provider.md) |
| Add Langfuse tracing | [Configure Langfuse observability](./configure-langfuse-observability.md) |
| Secure local tools | [Secure a local AI agent](./secure-local-ai-agent.md) |
| Deploy the gateway | [Deploy nanobot gateway](./deploy-nanobot-gateway.md) |
+72
View File
@@ -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)
+73
View File
@@ -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)
+83
View File
@@ -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)
+96
View File
@@ -0,0 +1,96 @@
# How to Connect an AI Agent to Chat Apps with nanobot
nanobot can run as a self-hosted chatbot or AI agent in Telegram, Discord,
Slack, WeChat, Email, Mattermost, and other chat apps. The gateway receives chat
messages, runs the agent, and sends replies back to the same channel.
## What you will build
- a working local agent
- one enabled chat channel
- a running gateway
- a pairing-based approval flow or a narrow static allowlist
## When to use this
Use chat apps when the agent should live where users already communicate:
private DMs, team channels, group chats, email threads, or bot workspaces.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot webui
```
Send `Hello!` in the WebUI before adding a channel. Then choose one platform guide for the bot/account prerequisites:
- [Telegram AI agent](./telegram-ai-agent.md)
- [Discord AI agent](./discord-ai-agent.md)
- [Slack AI agent](./slack-ai-agent.md)
- [Feishu AI agent](./feishu-ai-agent.md)
- [WhatsApp AI agent](./whatsapp-ai-agent.md)
- [WeChat AI agent](./wechat-ai-agent.md)
- [QQ AI agent](./qq-ai-agent.md)
- [Email AI agent](./email-ai-agent.md)
- [Mattermost AI agent](./mattermost-ai-agent.md)
## Minimal working example
Use the guided channel setup:
1. Get the platform token, login state, webhook, or mailbox credentials.
2. Open **Settings → Channels** in the WebUI.
3. Choose the platform and open its setup panel.
4. Complete the credential or QR flow and install optional support if prompted.
5. Restart when the WebUI requests it.
6. Send a private test message.
7. Approve the pairing request in the WebUI when a DM-capable channel asks for one.
If your installed release does not show **Settings → Channels**, use the full [Chat Apps reference](../chat-apps.md#manual-setup-pattern) to configure the channel manually.
Check status from the terminal when you need a lower-level confirmation:
```bash
nanobot channels status
```
The `nanobot webui` command already runs the gateway. For a chat-only or server deployment, start it directly:
```bash
nanobot gateway
```
Use the full [Chat Apps reference](../chat-apps.md) when you manage `config.json` directly or need platform-specific advanced settings.
## Production notes
- Keep the gateway running as a service for always-on chat apps.
- Use mention-only group policies before opening a bot to busy channels.
- Use one channel at a time while debugging.
- Prefer DMs for first tests; pairing only works in DMs, and group chats add
permissions and routing behavior.
## Security notes
- Prefer pairing or explicit allowlists; do not use `allowFrom: ["*"]` outside
an intentional sandbox.
- Rotate bot tokens if they are pasted into logs or shared files.
- Review file, shell, and web tool access before inviting other users.
## Troubleshooting
- If `nanobot channels status` does not show the channel, the config key or
optional dependency is likely missing.
- If the first DM returns a pairing code, approve the pending request in the WebUI or use `/pairing approve <code>` from an authorized chat.
- If messages do not arrive, run `nanobot gateway --verbose` and compare
platform credentials, event permissions, and allow lists.
- If group replies are unexpected, review that channel's group policy.
## Related nanobot docs
- [Chat Apps](../chat-apps.md)
- [Configuration](../configuration.md#channel-settings)
- [Pairing](../configuration.md#pairing)
- [Deployment](../deployment.md)
@@ -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)
+82
View File
@@ -0,0 +1,82 @@
# How to Configure MCP Tools in nanobot
This guide adds an MCP server to nanobot so the agent can use external tools
through the Model Context Protocol.
## What you will build
- a working nanobot agent
- one MCP integration configured through Apps or `~/.nanobot/config.json`
- a restricted set of MCP tools exposed to the model
## When to use this
Use MCP when the capability you need already exists as an MCP server, or when
you want external tools to be managed outside nanobot core.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Install the MCP server runtime separately. Many examples use `npx`, `uvx`, or a
remote HTTP endpoint.
## Minimal working example
For local interactive setup:
1. Run `nanobot webui` and open **Apps**.
2. Choose a known integration preset, or add a custom stdio, HTTP, or SSE server.
3. Limit the enabled tools when the server exposes more than the task needs.
4. Save and restart when prompted.
5. Mention the integration with `@` in the next message and ask for a small test action.
For manual or deployment-managed config, add this to `~/.nanobot/config.json`:
```json
{
"tools": {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
"enabledTools": ["read_file"]
}
}
}
}
```
Restart nanobot and ask a question that requires the MCP tool.
## Production notes
- Prefer `enabledTools` over exposing every tool by default.
- Use `toolTimeout` for slow MCP operations.
- Use HTTP MCP only for endpoints you trust.
- Keep MCP server commands stable and versioned in deployment docs or scripts.
## Security notes
- Stdio MCP starts a local process; review the command before enabling it.
- HTTP/SSE MCP uses nanobot's SSRF guard.
- Allow private HTTP MCP hosts only with narrow `tools.ssrfWhitelist` CIDRs.
- Do not place secrets in command arguments when environment variables or
headers can be used.
## Troubleshooting
- Run the MCP command outside nanobot first.
- Start `nanobot gateway --verbose` and inspect tool registration logs.
- If an HTTP MCP URL is blocked, check whether it points to loopback or a
private address that needs explicit allowlisting.
## Related nanobot docs
- [MCP tools for AI agents](./mcp-tools-for-ai-agents.md)
- [Configuration: MCP](../configuration.md#mcp-model-context-protocol)
- [Security](../configuration.md#security)
+93
View File
@@ -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)
+98
View File
@@ -0,0 +1,98 @@
# How to Configure Web Search for a nanobot AI Agent
nanobot includes built-in web search and web fetch tools. Search uses
DuckDuckGo by default and can be configured for API-backed or self-hosted
providers.
## What you will build
- web tools enabled in nanobot
- one search provider selected in the WebUI or `config.json`
- optional web fetch settings for page reading
## When to use this
Configure web search when the agent needs current information, public web
research, source discovery, or page fetching during a task.
## Install
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
nanobot agent -m "Hello!"
```
Web tools are enabled by default. Configure them only when you want a specific
provider, API key, proxy, fetch behavior, or SSRF allowlist.
## Minimal working example
For local interactive setup:
1. Run `nanobot webui`.
2. Open **Settings → Web**.
3. Enable web search, choose a provider, and enter its API key if required.
4. Save and restart when prompted.
5. Ask a question that requires current information and inspect the cited sources.
For manual or deployment-managed config, use the default search provider:
```json
{
"tools": {
"web": {
"enable": true,
"search": {
"provider": "duckduckgo"
}
}
}
}
```
Or use an API-backed provider:
```json
{
"tools": {
"web": {
"search": {
"provider": "brave",
"apiKey": "${BRAVE_API_KEY}"
}
}
}
}
```
Ask a question that requires current information and inspect the tool activity
in the WebUI or logs.
## Production notes
- Keep API keys in environment variables.
- Set `maxResults` when you need fewer or more search results per query.
- Set `tools.web.proxy` only to a proxy you trust.
- Use `fetch.useJinaReader: false` if you need local page conversion.
## Security notes
- Web fetch and HTTP MCP share an SSRF guard.
- Private, loopback, link-local, and cloud metadata addresses are blocked by
default.
- Add `tools.ssrfWhitelist` only for narrow trusted CIDRs.
- Do not give public chat users unrestricted web and shell access without
review.
## Troubleshooting
- If search returns no results, switch provider or check the provider API key.
- If fetch is blocked, inspect the target URL and SSRF whitelist.
- If a proxy changes network behavior, verify `NO_PROXY` and proxy settings.
## Related nanobot docs
- [Configuration: Web Tools](../configuration.md#web-tools)
- [Security](../configuration.md#security)
- [WebUI](../webui.md)
+76
View File
@@ -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)
+107
View File
@@ -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)
+93
View File
@@ -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)
+120
View File
@@ -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)
+73
View File
@@ -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)
+104
View File
@@ -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)
+75
View File
@@ -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)
+75
View File
@@ -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)
+102
View File
@@ -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)
+78
View File
@@ -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)
+83
View File
@@ -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)
+109
View File
@@ -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)
+109
View File
@@ -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)
+103
View File
@@ -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)
+107
View File
@@ -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)
+14 -7
View File
@@ -1,11 +1,20 @@
# 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.
The feature is disabled by default. Open **Settings → Image**, choose a configured provider and model, enable image generation, save, and restart when prompted. If that screen is not available in your installed version, use the manual config below.
## Quick Setup
**WebUI**
1. Add the image provider credential under **Settings → Models** if it is not already configured.
2. Open **Settings → Image**.
3. Select the provider and image model, then enable image generation.
4. Save, restart when prompted, and ask for a simple test image.
**Manual config**
This snippet uses the current built-in image-generation default so the JSON has concrete names. It is not a provider recommendation; replace `provider` and `model` with any supported image provider and model you intend to use.
```json
@@ -32,11 +41,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
View File
@@ -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`:
+7
View File
@@ -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
View File
@@ -39,7 +39,7 @@ Without parameters, returns a key config overview:
my(action="check")
# → max_iterations: 40
# context_window_tokens: 200000
# model: 'anthropic/claude-sonnet-4-20250514'
# model: 'anthropic/claude-sonnet-4-6'
# workspace: PosixPath('/tmp/workspace')
# provider_retry_mode: 'standard'
# max_tool_result_chars: 16000
+2 -2
View File
@@ -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
```
+9 -26
View File
@@ -2,6 +2,8 @@
Use this page when the first reply fails because of provider/model mismatch, or when you want to adapt the concrete setup example to a different provider. If you already know which provider you want and only need a pasteable setup, use [`provider-cookbook.md`](./provider-cookbook.md).
For normal local setup, open **Settings → Models** in the WebUI to add provider credentials, create a model preset, and select the active model. Use the JSON below for manual deployments, local endpoints, provider-specific fields, or diagnosis.
For every setup, answer three questions:
1. Which provider owns the credential or endpoint?
@@ -418,38 +420,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:
For OpenAI Codex, add `providers.openai_codex.proxy` only when Codex OAuth/token refresh or Codex API requests must use a proxy:
```json
{
"providers": {
"openai_codex": {
"proxy": "http://127.0.0.1:7890"
}
},
"modelPresets": {
"codex": {
"provider": "openai_codex",
"model": "gpt-5.1-codex",
"reasoningEffort": "high"
}
},
"agents": {
"defaults": {
"modelPreset": "codex"
}
}
}
```bash
nanobot provider login github-copilot --set-main
```
If you run the login command on a remote/headless machine and open the authorization URL in a local browser, paste the final `http://localhost:1455/auth/callback?...` redirect URL back into the terminal when prompted. See [`configuration.md#providers`](./configuration.md#providers) for the full OAuth provider notes.
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
View File
@@ -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 |
+170 -268
View File
@@ -1,153 +1,197 @@
# Install and Quick Start
This page gets one local nanobot reply working. After that, you can add the WebUI, chat apps, local models, web search, MCP, deployment, or custom plugins.
This guide has one goal: get a normal nanobot reply in your browser. Do not add chat apps, MCP servers, fallback models, or deployment until this path works.
If you have never used a terminal or edited a config file before, use [`start-without-technical-background.md`](./start-without-technical-background.md) first. This page assumes you are comfortable pasting commands and editing JSON snippets.
If terminals, Python, or API keys are unfamiliar, use the [beginner walkthrough](./start-without-technical-background.md), which explains each term and screen.
## Before You Start
These repository docs follow current `main`. The recommended installer uses the stable package, so a newly documented WebUI screen may not appear until the next release. Each advanced guide also provides a CLI or manual config path.
You need:
## What You Need
- Python 3.11 or newer.
- One LLM provider, company endpoint, subscription endpoint, or local model server you can call. The examples below use a generic OpenAI-compatible `custom` provider so the compact path does not recommend one hosted service; any supported provider works when the key, provider name, and model ID match.
- Git only if you install from source.
- Node.js or Bun only if you are developing the WebUI itself.
- Access to one supported AI provider, company endpoint, or local model server.
- The credential, endpoint URL, and model ID required by that service. Local providers such as Ollama may not require a key.
> [!IMPORTANT]
> Repository docs may describe features that are available first in source. Install from PyPI or `uv` for the stable day-to-day release; install from source when you want the newest repository behavior or plan to contribute.
Git is only needed for a source install. The published package already contains the WebUI. A current-source install needs `bun` or `npm` so its WebUI bundle can be built.
## 1. Install
## 1. Install nanobot
Pick one install method.
The recommended installer keeps nanobot out of the system Python environment and opens the setup wizard when installation finishes.
**One-command setup:**
**macOS / Linux**
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh
```
On Windows PowerShell:
**Windows PowerShell**
```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 installer chooses an active virtual environment, `uv`, `pipx`, or a managed environment under `~/.nanobot/venv`. It installs the stable PyPI release unless you explicitly pass `--dev`. At the end it prints the exact command it used to run nanobot; if `nanobot` is not on `PATH`, reuse that full command in the examples below.
To preview the plan without changing your environment, pass `--dry-run`; combine it with `--dev` when you want to preview the main-branch install.
If you prefer to inspect the scripts first, open [`install.sh`](../scripts/install.sh) or [`install.ps1`](../scripts/install.ps1).
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dry-run
```
## 2. Complete Quick Start
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dry-run
```
The installer opens `nanobot onboard --wizard`. Choose **Quick Start** and follow the prompts:
To install the current `main` branch instead, pass `--dev`:
1. Choose the provider or endpoint that owns your credential.
2. Enter its API key or base URL when requested.
3. Enter a model ID that the same provider can run.
4. Let Quick Start enable the local WebUI.
5. Set a WebUI password and review the summary.
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dev
```
Quick Start creates or updates:
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dev
```
| Path | Purpose |
|---|---|
| `~/.nanobot/config.json` | Provider, model, WebUI, channel, tool, and runtime settings |
| `~/.nanobot/workspace/` | Sessions, memory, skills, automations, and generated files |
If `curl` or `irm` is unavailable, or GitHub raw downloads are blocked on your network, use one of the manual install methods below.
If you prefer to inspect the script first, open [`../scripts/install.sh`](../scripts/install.sh) or [`../scripts/install.ps1`](../scripts/install.ps1).
**Stable release with `uv`:**
```bash
uv tool install nanobot-ai
nanobot --version
```
**Stable release with pip:**
```bash
python -m pip install nanobot-ai
nanobot --version
```
Use pip only inside an environment you control. If pip reports `externally-managed-environment` on macOS or Linux, use the one-command installer, `uv tool install nanobot-ai`, `pipx install nanobot-ai`, or create a virtual environment first.
**Latest source checkout:**
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install -e .
nanobot --version
```
If your shell cannot find `nanobot` after a pip install, run the module form:
```bash
python -m nanobot --version
python -m nanobot onboard
```
On Windows, `~` in the docs means your user profile directory, for example `C:\Users\you`.
The docs use `python` in commands. If your system exposes Python 3.11+ as `python3` or `py`, use that command in the same place, for example `python3 -m pip install nanobot-ai` or `py -m nanobot --version`.
## 2. Initialize
Skip this section if the one-command setup already started the wizard and Quick Start finished there.
```bash
nanobot onboard
```
Use the wizard if you prefer prompts instead of editing JSON by hand:
If the installer did not open the wizard, run it yourself:
```bash
nanobot onboard --wizard
```
Initialization creates:
Current source versions also provide `nanobot webui`. When run without a usable model, that launcher offers the same Quick Start flow before starting the browser.
| Path | What it is |
|------|------------|
| `~/.nanobot/config.json` | Main settings file for providers, models, channels, tools, gateway, and API |
| `~/.nanobot/workspace/` | Agent workspace for memory, sessions, heartbeat tasks, skills, and artifacts |
## 3. Check the Setup
If you already have a config, `nanobot onboard` can refresh missing default fields without overwriting your existing values.
```bash
nanobot status
```
## 3. Configure a Provider
You want:
Skip this section if you already configured provider and model settings in the wizard.
- a check mark for **Config** and **Workspace**;
- the model or preset you selected;
- a configured state for the provider used by that model.
Open `~/.nanobot/config.json`. Add or merge these blocks into the file created by `nanobot onboard`; do not replace the whole file unless you want to reset the config.
Most other providers can say `not set`. This command validates local setup but does not call the model.
**API key:**
## 4. Get the First Reply
```bash
nanobot gateway
```
Quick Start has already prepared the local WebSocket channel. Leave the gateway terminal open and visit `http://127.0.0.1:8765`; the first-run WebUI is bound to localhost, so other devices on your network cannot reach it. On current source versions, you can run `nanobot webui` instead to perform the local WebUI checks, start the gateway, and open the browser automatically.
Send:
```text
Hello!
```
Any normal assistant answer is success. It proves that nanobot can load the config, reach the selected model, use the workspace, and serve the browser UI.
Leave the terminal open while using the WebUI. If you prefer a managed background process, stop the foreground process with `Ctrl+C`, then run:
```bash
nanobot gateway --background
nanobot gateway status
```
Use `nanobot gateway logs`, `restart`, and `stop` to manage that background gateway.
## Terminal-Only Check
If you do not want the browser or need to isolate a WebUI problem, send one message directly:
```bash
nanobot agent -m "Hello!"
```
Then start an interactive terminal chat with:
```bash
nanobot agent
```
In interactive mode, `Enter` sends and `Alt+Enter` inserts a newline. Exit with `exit`, `/exit`, `:q`, or `Ctrl+D`.
## Choose One Next Step
After the first reply works, add one capability and test again:
| Goal | Recommended path |
|---|---|
| Learn sessions, workspaces, tools, and access modes | [WebUI guide](./webui.md) |
| Connect a chat platform | Open **Settings → Channels**, then use [Chat Apps](./chat-apps.md) for platform prerequisites |
| Change or add a model | Open **Settings → Models**; use the [Provider Cookbook](./provider-cookbook.md) for a recipe |
| Add web search, voice, or image generation | Use the matching WebUI Settings page, then consult [Configuration](./configuration.md) for advanced fields |
| Add an App or MCP integration | Open **Apps** or follow [Configure MCP Tools](./guides/configure-mcp-tools.md) |
| Schedule agent work | Read [Automations](./automations.md) |
| Run continuously or remotely | Read [Deployment](./deployment.md) |
| Integrate from code | Use the [Python SDK](./python-sdk.md) or [OpenAI-Compatible API](./openai-api.md) |
## Other Install Methods
Use one method, then continue at [Complete Quick Start](#2-complete-quick-start).
**uv**
```bash
uv tool install nanobot-ai
nanobot onboard --wizard
```
**pip in a virtual environment**
```bash
python -m pip install nanobot-ai
nanobot onboard --wizard
```
If pip reports `externally-managed-environment`, use the recommended installer, `uv tool install nanobot-ai`, `pipx install nanobot-ai`, or create a virtual environment. Do not force a system-wide install.
**Current source**
`bun` or `npm` must be available. Activate a virtual environment first, then run:
```bash
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
python -m pip install .
nanobot onboard --wizard
```
On Windows, if `python -m pip install .` reports that it cannot launch `npm`, run `cd webui`, `npm.cmd install --package-lock=false`, `npm.cmd run build`, and `cd ..` in order, then retry the install.
The source path follows current `main` and can be newer than the published package. A non-editable install triggers the build hook that bundles the current WebUI. For editable Python or frontend development, follow [`../CONTRIBUTING.md`](../CONTRIBUTING.md) and [`../webui/README.md`](../webui/README.md).
If the package is installed but the shell cannot find `nanobot`, use the runner that owns the installation. The recommended installer prints the exact command to reuse. Common forms are:
```bash
uv tool run --from nanobot-ai nanobot --version
pipx run --spec nanobot-ai nanobot --version
~/.nanobot/venv/bin/python -m nanobot --version
```
On Windows, the managed-environment form is `& "$HOME\.nanobot\venv\Scripts\python.exe" -m nanobot --version`. Replace `--version` with `onboard --wizard`, `gateway`, or any other arguments you need. Use plain `python -m nanobot` only when that Python executable belongs to the environment where nanobot was installed.
## Manual Configuration Fallback
Use this only when the wizard is unavailable or you intentionally manage JSON. First run `nanobot onboard`, then merge a provider and a named model preset into `~/.nanobot/config.json`.
A generic OpenAI-compatible setup has this shape:
```json
{
"providers": {
"custom": {
"apiKey": "your-api-key",
"apiKey": "${PROVIDER_API_KEY}",
"apiBase": "https://api.example.com/v1"
}
}
}
```
**Model preset:**
```json
{
},
"modelPresets": {
"primary": {
"label": "Primary",
"provider": "custom",
"model": "model-id-from-your-provider",
"maxTokens": 8192,
"contextWindowTokens": 65536,
"temperature": 0.1
"model": "model-id-from-your-provider"
}
},
"agents": {
@@ -158,190 +202,48 @@ Open `~/.nanobot/config.json`. Add or merge these blocks into the file created b
}
```
The provider and model inside a preset must match. The snippet above is only an example. For another provider, replace these values together:
| Replace | Where |
|---|---|
| Provider config key, such as `custom` | `providers.<provider>` |
| API key or environment variable | `providers.<provider>.apiKey` |
| Preset provider name | `modelPresets.primary.provider` |
| Model ID | `modelPresets.primary.model` |
| Endpoint URL, only when needed | `providers.<provider>.apiBase` |
Direct `agents.defaults.provider` and `agents.defaults.model` still work for existing configs, but named presets are the recommended path because they also power `/model` switching and fallback chains. For provider-specific examples across direct, gateway, OAuth, cloud, and local setups, see [`providers.md`](./providers.md).
**What about `apiBase` / base URL?**
`apiBase` is the HTTP base URL of the provider endpoint, not the model name. Most hosted providers in nanobot already know their default endpoint, so you usually only set `apiKey` and a model preset. Set `apiBase` when you are using:
- `custom` for a third-party or self-hosted OpenAI-compatible API;
- a local OpenAI-compatible server such as Ollama, vLLM, or LM Studio;
- a provider-specific alternate endpoint, regional endpoint, proxy, or subscription endpoint.
Examples:
```json
{
"providers": {
"custom": {
"apiKey": "${CUSTOM_API_KEY}",
"apiBase": "https://api.example.com/v1"
}
}
}
```
```json
{
"providers": {
"ollama": {
"apiBase": "http://localhost:11434/v1"
}
}
}
```
If the provider's docs say the endpoint is `/v1`, include `/v1` in `apiBase`. The model ID still belongs in the active `modelPresets` entry.
If you prefer not to store secrets in `config.json`, reference an environment variable and set it before starting nanobot:
```json
{
"providers": {
"custom": {
"apiKey": "${PROVIDER_API_KEY}",
"apiBase": "https://api.example.com/v1"
}
}
}
```
## 4. Check the Setup
```bash
nanobot status
```
This should show the config path, workspace path, active model or preset, and provider summary. It does not send a message to the model, so use it as a quick config check before the first real request.
Read it like this:
| Status line | What you want |
|---|---|
| `Config` | A check mark. |
| `Workspace` | A check mark. |
| `Model` | The model or preset you expect. |
| Provider list | Most providers can say `not set`; the provider used by the active preset should show a check mark, OAuth status, or local URL. |
## 5. Open the WebUI
If Quick Start enabled the WebSocket channel, start the gateway:
```bash
nanobot gateway
```
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password you set in the wizard, then send your first message there.
## 6. Test One CLI Message
Use this path if you skipped Quick Start, declined the WebSocket channel, or want a terminal-only check.
Run a one-shot CLI message:
```bash
nanobot agent -m "Hello!"
```
A successful first run proves that:
- the `nanobot` command is installed;
- `~/.nanobot/config.json` can be loaded;
- the selected provider and model can answer;
- the default workspace can be created and used.
The reply text itself will vary. Any normal assistant answer means the install, config, provider, model, and workspace path are all usable.
If that works, start an interactive CLI chat:
```bash
nanobot agent
```
After the interactive session can answer normally, nanobot can help with its own next setup step. Ask it to read the relevant docs, inspect your current `~/.nanobot/config.json`, and make one concrete change such as enabling WebUI, adding a provider preset, or configuring one chat channel. When nanobot says the config is updated, run `/restart` in the chat or restart the nanobot process manually so long-running processes reload `config.json`.
Example prompt:
```text
Read docs/quick-start.md, docs/providers.md, and docs/configuration.md in this checkout.
Then update ~/.nanobot/config.json to add a model preset named "primary" for my provider.
Tell me exactly what changed and whether I need to run /restart.
```
Exit interactive mode with `exit`, `quit`, `/exit`, `/quit`, `:q`, or `Ctrl+D`.
## 7. Choose Your Next Step
| Want to... | Go to |
|---|---|
| Understand config, workspace, gateway, channels, memory, and tools | [`concepts.md`](./concepts.md) |
| Copy another provider or local model setup | [`provider-cookbook.md`](./provider-cookbook.md) |
| Understand provider/model matching | [`providers.md`](./providers.md) |
| Open the bundled browser UI | [`webui.md`](./webui.md) |
| Connect Telegram, Discord, WeChat, Slack, Email, or another chat app | [`chat-apps.md`](./chat-apps.md) |
| Configure web search, MCP, security, memory, gateway, or runtime settings | [`configuration.md`](./configuration.md) |
| Run with Docker, systemd, or LaunchAgent | [`deployment.md`](./deployment.md) |
| Debug a failure | [`troubleshooting.md`](./troubleshooting.md) |
Replace the provider, endpoint, and model together. Do not pair a credential from one service with a model ID from another. See [Provider Cookbook](./provider-cookbook.md) for hosted, OAuth, company, and local examples, and [Configuration](./configuration.md) for exact fields.
## Updating
**pip:**
Upgrade with the same method you used to install:
```bash
python -m pip install -U nanobot-ai
nanobot --version
```
# Recommended installer
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh
If pip reports `externally-managed-environment`, upgrade with the same isolated method you used to install nanobot, such as `uv tool upgrade nanobot-ai`, `pipx upgrade nanobot-ai`, or the managed venv created by the one-command installer.
**uv:**
```bash
# Or one of these
uv tool upgrade nanobot-ai
nanobot --version
```
**pipx:**
```bash
pipx upgrade nanobot-ai
nanobot --version
python -m pip install -U nanobot-ai
```
**Source checkout:**
For a source checkout:
```bash
git pull
python -m pip install -e .
nanobot --version
python -m pip install .
```
If you use WhatsApp from a source checkout, keep the optional dependencies installed:
Then check `nanobot --version`. Run `nanobot onboard --refresh` when you want to add newly introduced default fields while preserving existing settings.
## If the First Reply Fails
Do not change several settings at once. Start with:
```bash
python -m pip install -e ".[whatsapp]"
nanobot --version
nanobot status
nanobot agent -m "Hello!"
```
## First-Run Troubleshooting
| Symptom | First check |
|---|---|
| `nanobot: command not found` | Reuse the installer command or method-specific runner described under [Other Install Methods](#other-install-methods) |
| JSON parse error | Check commas and braces; remember that docs examples are usually snippets |
| `401` or invalid API key | Verify the selected provider owns that key and remove accidental spaces |
| Model not found | Use a model ID available from the provider selected in the active preset |
| CLI works but WebUI does not open | Use port `8765`, not gateway health port `18790` |
| WebUI works but a chat app does not | Check **Settings → Channels**, then run `nanobot channels status` |
| Symptom | What to check |
|---------|---------------|
| `nanobot: command not found` | Use `python -m nanobot ...`, or add your Python scripts directory to `PATH`. |
| `ModuleNotFoundError: nanobot` | Confirm you installed into the same Python environment that is running the command. |
| JSON parse errors | Check commas and braces in `~/.nanobot/config.json`; examples above are partial snippets to merge. |
| Authentication or 401 errors | Check that the API key is valid, copied without spaces, and placed under the provider you selected. |
| Provider/model errors | Make sure the active preset uses the provider that owns your API key and that the model exists there. |
| The CLI works but a chat app does not reply | First keep `nanobot gateway` running, then follow [`chat-apps.md`](./chat-apps.md). |
| WebUI does not open | Enable the WebSocket channel and open port `8765`, not the gateway health port `18790`. |
For a fuller diagnosis flow, see [`troubleshooting.md`](./troubleshooting.md).
Continue with the ordered [Troubleshooting guide](./troubleshooting.md) if the cause is still unclear.
+164
View File
@@ -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!
+109 -349
View File
@@ -1,76 +1,62 @@
# Start Without Technical Background
This page is for you if you have never used a terminal, edited a JSON file, or configured an AI model before.
This walkthrough is for people who have not used a terminal, API key, or JSON config file before. The goal is only to get one reply in a browser. You do not need to understand nanobot's architecture or edit its config by hand.
The goal is small: get one local nanobot reply in your browser. Do not connect Telegram, Discord, Docker, local models, or deployment yet. Those are easier after the first reply works.
## What You Will Need
## What You Are Setting Up
- A Windows, macOS, or Linux computer.
- Python 3.11 or newer.
- An account or endpoint that can run an AI model.
- The API key, login, endpoint, and model name required by that service. A local model such as Ollama may not require an API key.
You only need these words for Quick Start:
An API key is password-like. Do not post it in an issue, screenshot, chat, or public config file.
| Word | Plain meaning |
## A Few Useful Words
| Word | Meaning |
|---|---|
| Terminal | A text window where you paste commands and press Enter. |
| Command | One line of text you run in the terminal. |
| API key | A password-like token from an AI provider. Do not share it publicly. |
| Config file | The settings file nanobot reads when it starts. |
| Wizard | An interactive terminal menu that edits the config file for you. |
| Browser UI | The local web page where you chat with nanobot. |
| Terminal | A text window where you paste a command and press Enter |
| Command | One instruction typed into the terminal |
| Provider | The service or local server that runs the AI model |
| Model ID | The exact model name expected by that provider |
| API key | A secret credential that lets software call the provider |
| Wizard | A question-and-answer setup menu |
| WebUI | The local browser page where you use nanobot |
## 1. Open a Terminal
## 1. Install Python
You will paste commands into a terminal. Copy only the command text inside each code block; do not copy the ``` marks.
Download Python from [python.org](https://www.python.org/downloads/) if you do not already have version 3.11 or newer. On Windows, enable **Add python.exe to PATH** if the installer shows that option.
| System | How to open it |
Open a terminal:
| System | How |
|---|---|
| Windows | Press `Win`, type `PowerShell`, then open **Windows PowerShell**. |
| macOS | Press `Command` + `Space`, type `Terminal`, then press `Enter`. |
| Linux | Open your app launcher, search for `Terminal`, then open it. |
| Windows | Press `Win`, type `PowerShell`, and open Windows PowerShell |
| macOS | Press `Command+Space`, type `Terminal`, and press Enter |
| Linux | Open your application menu and search for Terminal |
When the terminal opens, click inside it, paste the command, and press `Enter`. If a command prints text and returns to a prompt, that is usually normal.
## 2. Install Python
Install Python 3.11 or newer from [python.org](https://www.python.org/downloads/).
On Windows, enable **Add python.exe to PATH** during installation if the installer shows that option.
In that terminal, check Python:
Check Python:
```bash
python --version
```
If Windows says `python` is not found, close and reopen PowerShell. If it still does not work, try:
The result should start with `Python 3.11` or a newer number. If the command is not found, close and reopen the terminal. You can also try `python3 --version` on macOS/Linux or `py --version` on Windows.
```bash
py --version
```
## 2. Prepare Your Model Details
If `py` works but `python` does not, replace `python` with `py` in the commands below.
nanobot does not create an AI provider account for you. Before setup, have these details nearby:
If macOS or Linux says `python` is not found, try:
1. The provider or company endpoint name.
2. Its API key, if it requires one.
3. Its base URL, if its documentation gives you one.
4. A model ID your account can use.
```bash
python3 --version
```
The provider, credential, endpoint, and model must belong together. For example, an API key from one provider usually cannot call a model name copied from a different provider.
If `python3` works but `python` does not, replace `python` with `python3` in the manual commands below. The one-command installer already checks both `python3` and `python`.
## 3. Install nanobot
## 3. Get a Provider API Key
nanobot does not create AI accounts or API keys for you. Use an AI provider account, company endpoint, subscription endpoint, or local model server that you already control. If the provider has an OpenAI-compatible base URL in its docs, keep that nearby too.
For the setup path:
1. Open your provider's API key page.
2. Create or copy an API key.
3. Keep the key private.
4. Keep the provider's base URL nearby if the provider docs show one.
## 4. Install nanobot
The easiest path is the one-command installer. It installs or upgrades nanobot, then starts the setup wizard. On macOS and Linux it avoids system-wide pip installs by using an active virtual environment, `uv`, `pipx`, or a managed venv under `~/.nanobot/venv`.
Copy the command for your system, paste it into the terminal, and press Enter. Copy only the text inside the code block.
**macOS / Linux**
@@ -84,75 +70,13 @@ curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.
irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1 | iex
```
These commands install the stable PyPI package. To preview what the installer would do without changing your environment, pass `--dry-run`:
The installer downloads the stable nanobot package into an isolated Python environment and opens the setup wizard. It can take a few minutes on the first run. When it finishes, it prints the exact command it used to run nanobot. Keep that command: if `nanobot` is not found later, reuse the whole printed command instead of switching to a different Python command.
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dry-run
```
If your organization blocks downloaded install scripts, use the [alternative install methods](./quick-start.md#other-install-methods) or ask your administrator to review the scripts first.
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dry-run
```
## 4. Follow Quick Start
Use the development installer only when a maintainer asks you to test the current `main` branch:
```bash
curl -fsSL https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.sh | sh -s -- --dev
```
```powershell
& ([scriptblock]::Create((irm https://raw.githubusercontent.com/HKUDS/nanobot/main/scripts/install.ps1))) --dev
```
If the command says `curl` or `irm` is not found, or it cannot download from GitHub, use one of the manual install commands below.
If `uv` is installed, use:
```bash
uv tool install nanobot-ai
```
If you prefer pip, use it only inside an environment you control:
```bash
python -m pip install nanobot-ai
```
If pip reports `externally-managed-environment` on macOS or Linux, go back to the one-command installer, use `uv tool install nanobot-ai`, use `pipx install nanobot-ai`, or create a virtual environment first.
Then check that nanobot is installed:
```bash
nanobot --version
```
If the terminal cannot find `nanobot`, use the module form:
```bash
python -m nanobot --version
```
Use `python3 -m nanobot --version` or `py -m nanobot --version` if that is the Python command that worked in step 2.
## 5. Run the Setup Wizard
The one-command installer starts this for you after installation. If you installed manually, run:
```bash
nanobot onboard --wizard
```
If `nanobot` is not found, run:
```bash
python -m nanobot onboard --wizard
```
Use `python3 -m nanobot onboard --wizard` or `py -m nanobot onboard --wizard` if that is the Python command that worked in step 2.
The wizard is a terminal menu. It is not a graphical app, but it lets you choose options instead of hand-editing every JSON field.
You will see a menu like this:
The wizard shows a menu similar to:
```text
> What would you like to do?
@@ -161,217 +85,30 @@ You will see a menu like this:
[X] Exit
```
Move through the wizard like this:
Choose **Quick Start**. Use the arrow keys to highlight an option and press `Enter`.
| When you see | Do this |
|---|---|
| A menu | Use the arrow keys to highlight an option, then press `Enter`. |
| The provider menu | Choose the company or service you want to use. |
| An endpoint menu | Choose the standard API or subscription plan endpoint that matches your key. |
| An API key field | Paste the key, then press `Enter`. |
| A provider base URL field | Paste the provider base URL from its docs, then press `Enter`. |
| The Model ID field | Paste a model name from your provider, then press `Enter`. |
| A back option in Advanced Settings | Choose it to return to the previous menu. |
The wizard asks for only the information needed for the first reply:
For the first setup, choose `[Q] Quick Start`. It configures the recommended local browser UI and default AI settings for you. Use `Advanced Settings` later only if you need a chat app, a tool setup, or provider-specific fields.
1. Choose your provider.
2. Choose an endpoint option if the provider offers several plans.
3. Paste the API key if asked.
4. Enter the base URL if asked.
5. Enter a model ID.
6. Confirm the local WebUI setup.
7. Choose a WebUI password.
8. Review the summary and save.
1. Choose `[Q] Quick Start`.
2. Choose the provider you want to use.
3. Choose the endpoint if the wizard asks, such as Standard API, Coding Plan, Token Plan, or Step Plan.
4. Paste your API key if the wizard asks for one.
5. Paste the provider base URL if the wizard asks for one.
6. Paste a model ID that provider can run.
7. Confirm that Quick Start should enable the WebSocket channel for the local WebUI.
8. Set the WebUI password when prompted.
9. Review the Quick Start summary. The wizard saves and exits when Quick Start finishes.
When you paste a password or API key, the terminal may hide the characters. That is normal.
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.
If you already know that you need custom headers, provider-specific request fields, a chat app, or tools, choose `Advanced Settings` instead. [`provider-cookbook.md`](./provider-cookbook.md) has copyable examples for several common provider setups. After you change advanced settings, a save option appears in the main menu. Choose `[S] Save and Exit`.
The wizard creates or updates:
| Path | Meaning |
|---|---|
| `~/.nanobot/config.json` | Settings file. |
| `~/.nanobot/workspace/` | Working folder for memory, sessions, and generated files. |
If Quick Start finished successfully, skip to [Open the WebUI](#7-open-the-webui). The next two sections are only for manual setup.
## Manual Setup: How to Merge JSON Snippets
Most docs examples are snippets, not whole files. Your `config.json` has one outer `{ ... }`. Add new top-level sections such as `providers`, `modelPresets`, `agents`, or `channels` inside that same outer object.
Do not paste two separate JSON objects into one file:
```text
{
"providers": { "...": "..." }
}
{
"channels": { "...": "..." }
}
```
Merge them into one object:
```json
{
"providers": {
"custom": {
"apiKey": "your-api-key",
"apiBase": "https://api.example.com/v1"
}
},
"channels": {
"websocket": {
"enabled": true,
"tokenIssueSecret": "your-webui-password",
"websocketRequiresToken": true
}
}
}
```
Notice the comma after the `providers` block. JSON needs commas between sibling sections, but not after the last section. If this feels hard, use `nanobot onboard --wizard` whenever possible.
## 6. Manual Setup: Config Fallback
Use this only if the wizard is unavailable or you prefer opening the file yourself.
Run `nanobot onboard` first if `~/.nanobot/config.json` does not exist yet.
Use one of these commands:
**Windows PowerShell**
```powershell
notepad "$env:USERPROFILE\.nanobot\config.json"
```
**macOS**
If the installer finishes without opening the wizard and `nanobot` is available, run:
```bash
open -e ~/.nanobot/config.json
nanobot onboard --wizard
```
**Linux**
If the terminal cannot find `nanobot`, take the exact command printed by the installer and replace its final arguments with `onboard --wizard`. That command may begin with `uv tool run`, `pipx run`, or the full path to nanobot's private Python environment.
```bash
xdg-open ~/.nanobot/config.json
```
If this is a brand-new install and you have not configured anything else yet, replace the file with this minimal config:
```json
{
"providers": {
"custom": {
"apiKey": "your-api-key",
"apiBase": "https://api.example.com/v1"
}
},
"modelPresets": {
"primary": {
"label": "Primary",
"provider": "custom",
"model": "model-id-from-your-provider",
"maxTokens": 4096,
"contextWindowTokens": 65536,
"temperature": 0.1
}
},
"agents": {
"defaults": {
"modelPreset": "primary"
}
},
"channels": {
"websocket": {
"enabled": true,
"tokenIssueSecret": "your-webui-password",
"websocketRequiresToken": true
}
}
}
```
Replace `your-api-key`, `https://api.example.com/v1`, `model-id-from-your-provider`, and `your-webui-password` with your own values.
For copyable provider-specific examples, use [`provider-cookbook.md`](./provider-cookbook.md).
Save the file.
## 7. Open the WebUI
First check that nanobot can read the saved setup:
```bash
nanobot status
```
This should show the config file path, workspace path, and the active model or preset. If `nanobot` is not found, use `python -m nanobot status`, `python3 -m nanobot status`, or `py -m nanobot status`, matching the Python command that worked in step 2.
It is normal for most providers to say `not set`. Only the provider you selected for the active preset needs to look configured.
Start the local browser UI:
```bash
nanobot gateway
```
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password you set in the wizard or the `tokenIssueSecret` value from your manual config.
Send this first message in the browser:
```text
Hello!
```
If that works, nanobot is installed and can call the model. You should see a normal assistant reply in the browser. The exact words will differ, but it should look like this shape:
```text
Hello! How can I help you today?
```
If `nanobot` is not found, run:
```bash
python -m nanobot gateway
```
Use `python3 -m nanobot gateway` or `py -m nanobot gateway` if that is the Python command that worked in step 2.
Once this works, nanobot can help with its own next setup step. In the browser UI, ask it to read these docs and update your current config for one specific goal, then run `/restart` when nanobot tells you the config is ready. For example, ask it to add one provider preset or configure one chat app.
## 8. If Something Fails
Do not change many things at once. Check the exact error:
| Error or symptom | What it usually means |
|---|---|
| `JSON parse error` | The config file has a missing comma, extra comma, or mismatched brace. Copy the example again. |
| `401`, `unauthorized`, or `invalid API key` | The API key is wrong, expired, has extra spaces, or was pasted under the wrong provider. |
| `model not found` | Your account cannot use the default model. Return to `nanobot onboard --wizard`, choose `Advanced Settings`, then edit `Model Presets`. |
| `nanobot: command not found` | The install worked in Python, but your shell cannot find the script. Use `python -m nanobot ...`, `python3 -m nanobot ...`, or `py -m nanobot ...`, matching the Python command that worked earlier. |
| No response after editing config | Restart the command. Long-running processes read config when they start. |
For a fuller diagnosis path, see [`troubleshooting.md`](./troubleshooting.md).
## What Not to Configure Yet
Skip these until the first local message works:
- `apiBase`: hosted built-in providers often already have default endpoints. You only need `apiBase` for local models, proxies, custom OpenAI-compatible providers, or special regional/subscription endpoints.
- chat apps: first prove the local browser UI can answer.
- fallback models: useful later, but not needed for the first reply.
- Langfuse: useful for observability, but not needed for first setup.
## Next Steps
After the first reply works, choose only one next goal. Keep the terminal that runs `nanobot gateway` open whenever you use the WebUI or a chat app.
### Open the Browser UI Again
## 5. Open the Browser
Run:
@@ -379,43 +116,66 @@ Run:
nanobot gateway
```
Leave that terminal open, then open `http://127.0.0.1:8765` in your browser.
Leave the terminal open, then open `http://127.0.0.1:8765` in your browser. Enter the WebUI password from the wizard if the browser asks for it. Current source versions also provide `nanobot webui`, which starts the gateway and opens the browser automatically.
To stop the WebUI later, return to the gateway terminal and press `Ctrl+C`.
Send this message:
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).
```text
Hello!
```
### Connect a Chat App
A normal assistant reply means setup is complete. The exact reply does not matter.
1. Read the section for one app in [`chat-apps.md`](./chat-apps.md).
2. Add only that app's config snippet. Merge it into the existing file instead of replacing the whole file.
3. Run:
The first-run address is local to your computer. It is not automatically available to other computers on your network.
## 6. Add One Thing at a Time
Do not configure every feature immediately. Choose one next goal:
| Goal | What to do |
|---|---|
| Change the AI model | Open **Settings → Models** |
| Add a provider credential | Open **Settings → Models**, then find the provider |
| Connect Telegram, Discord, Slack, Feishu, WeChat, or another chat app | Open **Settings → Channels**, choose the platform, and follow its connection steps |
| Add a tool integration | Open **Apps** and choose an App or MCP integration |
| Schedule a reminder or recurring task | Ask nanobot in the target chat, then manage it in **Automations** |
| Work with project files | Start a new chat, choose the project workspace, and review the access setting before sending the task |
Repository docs show the current development version. If your stable package does not yet show **Settings → Channels**, use the [Chat Apps guide](./chat-apps.md) or update to a release that includes it.
Some runtime changes ask you to restart nanobot. Use the restart action shown by the WebUI, or return to the terminal, press `Ctrl+C`, and run `nanobot gateway` again.
For a chat platform's account, bot, token, or permission prerequisites, use the [Chat Apps guide](./chat-apps.md). For local models and provider-specific recipes, use the [Provider Cookbook](./provider-cookbook.md).
## If Something Fails
Run these commands one at a time:
```bash
nanobot --version
nanobot status
nanobot agent -m "Hello!"
```
| What you see | What it usually means |
|---|---|
| `nanobot: command not found` | Reuse the exact nanobot command printed by the installer; it points to the isolated environment that contains the package |
| `401`, unauthorized, or invalid API key | The key is wrong, expired, or belongs to a different provider |
| Model not found | The model ID is misspelled or unavailable to your provider account |
| Browser does not open | Open `http://127.0.0.1:8765` yourself and keep the terminal running |
| Browser opens but messages fail | Test `nanobot agent -m "Hello!"` to separate a model problem from a WebUI problem |
| A change was saved but nothing changed | Restart nanobot so the running process reloads the config |
If you ask for help, include your operating system, `nanobot --version`, `nanobot status`, the exact command, and the exact error. Remove every API key, bot token, password, OAuth token, and private account ID first.
Continue with the full [Troubleshooting guide](./troubleshooting.md) for an ordered diagnosis.
## Open nanobot Later
Run:
```bash
nanobot channels status
nanobot gateway
```
4. Leave the gateway terminal open, then send a message from the allowed account.
Start with a private chat or a test server. Do not set `allowFrom` to `["*"]` unless you intentionally want anyone who can reach that channel to talk to the bot.
### Change Models or Add Backups
Use [`providers.md`](./providers.md) when a provider/model pair fails, and [`provider-cookbook.md`](./provider-cookbook.md) when you want copyable snippets. Keep model choices in `modelPresets`, then select the active one with `agents.defaults.modelPreset`.
### Ask for Help
When you ask for help, include:
- your operating system;
- the command you ran;
- `nanobot --version`;
- `nanobot status`;
- whether the browser UI can answer `Hello!`;
- the exact error text;
- a config snippet with API keys and tokens removed.
Never paste real API keys, bot tokens, OAuth tokens, or private chat IDs into a public issue or chat.
If you find a docs mistake, outdated command, or confusing step, please open an issue: <https://github.com/HKUDS/nanobot/issues>.
Leave that terminal open and visit `http://127.0.0.1:8765`. To stop nanobot, return to the terminal and press `Ctrl+C`. Use `nanobot gateway --background` only after the normal foreground start works; then manage it with `nanobot gateway status`, `logs`, `restart`, and `stop`.
+11 -5
View File
@@ -31,7 +31,7 @@ If `nanobot agent -m "Hello!"` fails, fix that before debugging WebUI, Telegram,
## How to Read `nanobot status`
`nanobot status` does not call a model. It only checks whether nanobot can find the 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
View File
@@ -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": ["*"]
}
+121 -44
View File
@@ -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,30 +50,31 @@ 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).
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.
Start the gateway:
## First 10 Minutes
```bash
nanobot gateway
```
Use the WebUI as the primary setup surface after Quick Start:
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.
1. Send `Hello!` in a new chat to prove the selected model works.
2. Open **Settings → Models** and confirm the active model preset.
3. Start a separate chat before project work, then choose the intended workspace and access mode.
4. Add only one capability next: a chat channel in **Settings → Channels**, a web/voice/image provider in **Settings**, or an App/MCP integration in **Apps**.
5. Restart when the WebUI shows a restart requirement, then test that capability with the smallest possible request.
This path avoids hand-editing `config.json` for normal setup. Use the reference docs when you need an option the WebUI does not expose or when you manage config as code.
## 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 |
| Channels | Connect and validate chat platforms, install their optional support, and manage saved channel setup |
| Apps | Install, test, update, and use local CLI App adapters and MCP presets |
| Skills | Inspect available built-in and workspace skills before relying on them |
| Automations | Review, search, run, pause, edit, and delete scheduled and local-trigger agent turns |
@@ -69,6 +90,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 +111,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
@@ -91,12 +126,38 @@ For image generation, configure an image provider first and then use the WebUI
image mode from the composer. See [`image-generation.md`](./image-generation.md)
for provider setup and output behavior.
## Channels
Open **Settings → Channels** to connect chat apps without assembling JSON by hand. Search for a platform, open its setup panel, and follow the fields or QR flow shown for that channel. The guided setup can:
- install missing optional channel support when the WebUI is running locally;
- collect platform credentials while preserving previously saved values;
- handle supported QR-based login flows;
- validate the connection and show actionable setup errors;
- tell you when the gateway needs to restart.
The platform itself may still require you to create a bot, enable event permissions, copy a token, or configure a webhook. Use [`chat-apps.md`](./chat-apps.md) for those platform-side prerequisites and for manual JSON/reference options.
Test a new channel with a private DM. When a supported channel sends a pairing code, the WebUI surfaces the pending request so you can approve the sender. Keep access narrow; do not use a wildcard allowlist unless public access is intentional.
## Apps
Open Apps from the sidebar 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 +165,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
@@ -121,6 +182,9 @@ 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,
@@ -128,19 +192,6 @@ There are two user-facing automation types:
- Local triggers, created with `/trigger <name>`, run when you call a local
command such as `nanobot trigger trg_8K4P2Q9X "Review PR #4502"`.
If a GitHub webhook, CI system, or another service should wake nanobot up, keep
that webhook/service outside nanobot and have it call the trigger command with
the final message.
Trigger deliveries use the same workspace as the gateway. They survive gateway
restarts and are requeued if the process exits before the linked turn completes.
If the linked session is already running a turn, the local trigger waits until
that session is idle instead of being injected into the active turn. This is an
at-least-once local queue, so repeated delivery is possible after an interrupted
process. A delivered trigger is recorded as an automation turn in the linked
session; if the agent receives it but the turn fails, Automations marks the run
failed instead of retrying indefinitely.
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.
@@ -170,14 +221,17 @@ with the content that should be delivered.
## Settings
Settings is the control surface for the browser session and gateway-backed
runtime configuration. Use it to review or adjust model presets, provider
visibility, image generation, voice transcription, web tools, Apps, Automations,
Skills, runtime identity, and advanced safety controls.
runtime configuration. Use it to review or adjust model presets, providers,
image generation, voice transcription, web tools, chat channels, Apps,
Automations, Skills, runtime identity, and advanced safety controls.
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
@@ -187,7 +241,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"
@@ -201,12 +254,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.
+40
View File
@@ -1,5 +1,44 @@
#!/bin/sh
dir="$HOME/.nanobot"
# Render deploy path (see render.yaml + render-config.json). Gated on Render's
# automatic RENDER=true env var so local Docker/podman usage is unaffected.
# Initializes the on-disk config from the committed template (wiring secrets via
# ${VAR} env vars, keeping runtime data on the persistent disk) and appends the
# --config flag. Logs each decision so a failed start is diagnosable in Render's
# logs. Privilege dropping is handled below, for every root start (not just here).
if [ "$RENDER" = "true" ]; then
echo "[entrypoint] Render deploy — starting as $(id)"
mkdir -p "$dir" || echo "[entrypoint] warning: mkdir $dir failed"
config="$dir/config.json"
# Initialize config only when it does not already exist, so WebUI/provider
# settings edited at runtime survive restarts. The disk persists config.json
# across deploys; overwriting it every boot would discard those changes.
if [ ! -f "$config" ]; then
echo "[entrypoint] initializing $config from render-config.json"
cp /app/render-config.json "$config" || echo "[entrypoint] warning: cp config failed"
else
echo "[entrypoint] existing $config found — leaving it in place"
fi
set -- "$@" --config "$config"
fi
# Drop privileges whenever the container starts as root. Render mounts the
# persistent disk root-owned, and a plain `docker run` also defaults to root now,
# so this covers both. Chown the data dir so the non-root user can write it, then
# re-exec as nanobot. Fail closed: if the privilege drop cannot be performed,
# exit rather than run the agent as root.
if [ "$(id -u)" = "0" ]; then
chown -R nanobot:nanobot "$dir" 2>/dev/null || echo "[entrypoint] warning: chown $dir failed"
if setpriv --reuid=nanobot --regid=nanobot --init-groups true 2>/dev/null; then
echo "[entrypoint] dropping privileges to nanobot via setpriv"
exec setpriv --reuid=nanobot --regid=nanobot --init-groups nanobot "$@"
fi
echo "[entrypoint] error: started as root but setpriv privilege drop failed — refusing to run as root" >&2
exit 1
fi
# Already non-root: make sure the data dir is writable before starting.
if [ -d "$dir" ] && [ ! -w "$dir" ]; then
owner_uid=$(stat -c %u "$dir" 2>/dev/null || stat -f %u "$dir" 2>/dev/null)
cat >&2 <<EOF
@@ -12,4 +51,5 @@ Fix (pick one):
EOF
exit 1
fi
exec nanobot "$@"
+32 -30
View File
@@ -4,7 +4,7 @@ Triggered automatically by `python -m build` (and any other hatch-driven build)
so published wheels and sdists ship a fresh webui without requiring developers
to remember `cd webui && bun run build` beforehand.
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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 287 KiB

After

Width:  |  Height:  |  Size: 657 KiB

+10 -1
View File
@@ -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",
+13 -5
View File
@@ -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:
@@ -62,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():
@@ -74,16 +79,19 @@ class AutoCompact:
continue
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)
+4
View File
@@ -79,6 +79,8 @@ class AutomationTurnCoordinator:
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:
@@ -118,6 +120,8 @@ class AutomationTurnCoordinator:
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)
+29 -64
View File
@@ -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]]:
+11 -6
View File
@@ -425,9 +425,14 @@ class ContextGovernor:
return system_messages + self._legal_history_tail(kept, non_system)
@staticmethod
def _summary_for(message: dict[str, Any]) -> str:
def _tool_result_compaction_message(message: dict[str, Any]) -> str:
name = message.get("name", "tool")
return f"[{name} result omitted from context]"
return (
f"Error: The previous {name} result was compacted to fit context because it was too "
"large. Do not repeat the same call unchanged. Retry with a narrower path, query, "
"range, or result limit, use another tool, or tell the user the task cannot fit in "
"the available context."
)
def _legal_history_tail(
self,
@@ -462,12 +467,12 @@ class ContextGovernor:
tool_call_id = msg.get("tool_call_id")
if not tool_call_id or str(tool_call_id) not in compacted_tool_call_ids:
continue
summary = self._summary_for(msg)
if msg.get("content") == summary:
compaction_message = self._tool_result_compaction_message(msg)
if msg.get("content") == compaction_message:
continue
if updated is messages:
updated = [dict(m) for m in messages]
updated[idx]["content"] = summary
updated[idx]["content"] = compaction_message
return updated
def _inflight_compaction_candidates(
@@ -500,4 +505,4 @@ class ContextGovernor:
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])
messages[idx]["content"] = self._tool_result_compaction_message(messages[idx])
+29
View File
@@ -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)
+91
View File
@@ -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)
+11
View File
@@ -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",
]
+135
View File
@@ -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,
)
+316 -213
View File
File diff suppressed because it is too large Load Diff
+167 -57
View File
@@ -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,
@@ -28,10 +29,15 @@ from nanobot.utils.helpers import (
truncate_text_to_tokens,
)
from nanobot.utils.prompt_templates import render_template
from nanobot.utils.workspace_prompts import (
WORKSPACE_PROMPT_MAX_CHARS,
has_workspace_prompt_override,
load_workspace_prompt_override,
workspace_prompt_file,
)
if TYPE_CHECKING:
from nanobot.providers.base import LLMProvider
from nanobot.session.manager import SessionManager
from nanobot.utils.llm_runtime import LLMRuntime
# ---------------------------------------------------------------------------
# MemoryStore — pure file I/O layer
@@ -41,6 +47,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*")
@@ -63,6 +77,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",
@@ -481,13 +496,49 @@ class MemoryStore:
def get_latest_cursor(self) -> int:
return max(self._next_cursor() - 1, 0)
@property
def dream_prompt_file(self) -> Path:
return workspace_prompt_file(self.workspace, "dream")
def has_dream_prompt_override(self) -> bool:
return has_workspace_prompt_override(self.dream_prompt_file)
@staticmethod
def default_dream_prompt() -> str:
from nanobot.agent.skills import BUILTIN_SKILLS_DIR
return render_template(
"agent/dream.md",
strip=True,
skill_creator_path=str(BUILTIN_SKILLS_DIR / "skill-creator" / "SKILL.md"),
)
def _dream_template(self) -> str:
text, original_chars = load_workspace_prompt_override(self.dream_prompt_file)
if text is not None:
if (
original_chars > WORKSPACE_PROMPT_MAX_CHARS
and not self._dream_prompt_oversize_logged
):
self._dream_prompt_oversize_logged = True
logger.warning(
"workspace Dream prompt exceeds {} chars ({}); truncating. "
"Further occurrences suppressed.",
WORKSPACE_PROMPT_MAX_CHARS, original_chars,
)
return text
return self.default_dream_prompt()
def build_dream_prompt(self, *, max_entries: int = 20) -> tuple[str, int] | None:
"""Build the Dream prompt with unprocessed history context.
Returns ``(prompt, last_cursor)`` or ``None`` if nothing to process.
"""
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:
@@ -498,13 +549,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
@@ -576,7 +661,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}",
@@ -596,23 +684,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
@@ -647,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
@@ -671,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())
@@ -759,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)
@@ -773,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
@@ -789,6 +877,8 @@ 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)
@@ -808,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)
@@ -830,6 +923,7 @@ class Consolidator:
self,
messages: list[dict],
*,
runtime: LLMRuntime,
session_key: str | None = None,
summary_messages: list[dict] | None = None,
) -> str | None:
@@ -844,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",
@@ -862,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}")
@@ -881,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.
@@ -888,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)
@@ -900,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)
@@ -922,7 +1024,7 @@ class Consolidator:
"Token consolidation idle {}: {}/{} via {}, msgs={}",
session.key,
estimated,
self.context_window_tokens,
runtime.context_window_tokens,
source,
unconsolidated_count,
)
@@ -953,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
@@ -974,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)
@@ -989,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.
@@ -1031,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,
)
+1 -1
View File
@@ -34,12 +34,12 @@ def build_static_preset_snapshot(
name: str,
preset: ModelPresetConfig,
) -> ProviderSnapshot:
provider.generation = preset.to_generation_settings()
return ProviderSnapshot(
provider=provider,
model=preset.model,
context_window_tokens=preset.context_window_tokens,
signature=("model_preset", name, preset.model_dump_json()),
generation=preset.to_generation_settings(),
)
+203
View File
@@ -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))
-19
View File
@@ -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 (
+74 -135
View File
@@ -20,16 +20,7 @@ from nanobot.agent.context_governance import (
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
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,
@@ -39,10 +30,7 @@ from nanobot.utils.helpers import (
strip_reasoning_tags,
strip_think,
)
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,
@@ -67,10 +55,6 @@ _MAX_EMPTY_RETRIES = 2
_MAX_LENGTH_RECOVERIES = 3
_MAX_INJECTIONS_PER_TURN = 3
_MAX_INJECTION_CYCLES = 5
# 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:
@@ -78,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
@@ -91,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
@@ -122,8 +102,7 @@ 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
@@ -155,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(
@@ -204,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": [],
@@ -359,15 +340,15 @@ class AgentRunner:
injection_cycles = 0
compacted_tool_call_ids: set[str] = set()
governance_config = ContextGovernanceConfig(
provider=self.provider,
model=spec.model,
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.context_window_tokens,
context_window_tokens=spec.runtime.context_window_tokens,
context_block_limit=spec.context_block_limit,
max_tokens=spec.max_tokens,
max_tokens=spec.runtime.generation.max_tokens,
inflight_start_index=len(spec.initial_messages),
)
@@ -444,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],
@@ -458,6 +439,8 @@ class AgentRunner:
response.tool_calls,
external_lookup_counts,
workspace_violation_counts,
hook,
context,
)
tool_events.extend(new_events)
tools_used.extend(
@@ -504,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": [],
@@ -658,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": [],
@@ -715,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(
@@ -759,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 = ""
@@ -805,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:
@@ -837,44 +799,42 @@ 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
# LLM timeout here, or healthy long reasoning streams can be killed just
# because total elapsed time exceeded NANOBOT_LLM_TIMEOUT_S.
outer_timeout_s = None if (wants_streaming or wants_progress_streaming) else timeout_s
# Streaming requests also have provider-level idle timeouts
# (NANOBOT_STREAM_IDLE_TIMEOUT_S), but a stream that keeps producing
# very slow deltas can still run forever. Use a more generous wall-clock
# timeout for streaming while preserving NANOBOT_LLM_TIMEOUT_S=0 as an
# opt-out for all LLM wall-clock timeouts.
is_streaming_request = wants_streaming or wants_progress_streaming
outer_timeout_s = (
max(300.0, timeout_s * 2)
if is_streaming_request and timeout_s is not None
else timeout_s
)
try:
response = (
await coro if outer_timeout_s is None
else await asyncio.wait_for(coro, timeout=outer_timeout_s)
)
if live_file_edits is not None:
await live_file_edits.flush()
if response.should_execute_tools:
live_file_edits.apply_final_call_ids(response.tool_calls)
await live_file_edits.error_unmatched(
response.tool_calls if response.should_execute_tools else [],
"Tool call did not complete.",
)
except asyncio.TimeoutError:
if outer_timeout_s is None:
return LLMResponse(
response = LLMResponse(
content="Error calling LLM: stream stalled",
finish_reason="error",
error_kind="timeout",
)
return LLMResponse(
content=f"Error calling LLM: timed out after {outer_timeout_s:g}s",
finish_reason="error",
error_kind="timeout",
)
else:
response = LLMResponse(
content=f"Error calling LLM: timed out after {outer_timeout_s:g}s",
finish_reason="error",
error_kind="timeout",
)
if progress_state and progress_state.get("reasoning_open"):
await hook.emit_reasoning_end()
dropped, all_dropped, original_finish_reason = (
@@ -1026,7 +986,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(
@@ -1074,7 +1034,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],
@@ -1128,14 +1093,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
))
@@ -1144,7 +1118,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)
@@ -1165,7 +1144,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,
@@ -1206,30 +1189,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)
@@ -1238,14 +1198,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",
@@ -1267,14 +1220,7 @@ class AgentRunner:
return payload, event, None
if is_tool_error_result(tool_call.name, result):
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
],
)
await hook.on_execute_tool_error(context, tool_call, tool, params, result)
event = {
"name": tool_call.name,
"status": "error",
@@ -1293,14 +1239,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()
+92 -20
View File
@@ -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,13 @@ 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.exec_session import ExecSessionManager
from nanobot.agent.tools.file_state import FileStates
from nanobot.agent.tools.loader import ToolLoader
from nanobot.agent.tools.registry import ToolRegistry
@@ -26,6 +33,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,10 +84,10 @@ 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,
@@ -89,11 +97,33 @@ class SubagentManager:
fail_on_tool_error: bool | None = None,
llm_wall_timeout_for_session: Callable[[str | None], float | None] | None = None,
):
if workspace is None:
raise TypeError("SubagentManager.__init__() missing required argument: 'workspace'")
if bus is None:
raise TypeError("SubagentManager.__init__() missing required argument: 'bus'")
if max_tool_result_chars is None:
raise TypeError(
"SubagentManager.__init__() missing required argument: 'max_tool_result_chars'"
)
if model is not None and provider is None:
raise TypeError("SubagentManager model compatibility argument requires provider")
defaults = AgentDefaults()
self.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
@@ -113,12 +143,48 @@ class SubagentManager:
if fail_on_tool_error is not None
else defaults.fail_on_tool_error
)
self.runner = AgentRunner(provider)
self.runner = AgentRunner()
self._exec_session_manager = ExecSessionManager()
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(
@@ -140,6 +206,7 @@ class SubagentManager:
ctx = ToolContext(
config=cfg,
workspace=str(root.resolve()),
exec_session_manager=self._exec_session_manager,
file_state_store=FileStates(),
workspace_sandbox=workspace_sandbox_status(
restrict_to_workspace=cfg.restrict_to_workspace,
@@ -149,11 +216,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,
@@ -164,8 +226,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}
@@ -185,8 +253,8 @@ class SubagentManager:
display_label,
origin,
status,
runtime,
origin_message_id,
temperature,
workspace_scope,
)
)
@@ -214,8 +282,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."""
@@ -244,13 +312,19 @@ 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),
@@ -266,6 +340,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
@@ -361,10 +436,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,
@@ -372,7 +445,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 "",
)
+5
View File
@@ -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")
@@ -206,6 +207,10 @@ class Tool(ABC):
def create(cls, ctx: ToolContext) -> Tool:
return cls()
def runtime_context_provider(self) -> RuntimeContextProvider | None:
"""Return optional per-turn prompt context owned by this tool."""
return None
@abstractmethod
async def execute(self, **kwargs: Any) -> Any:
"""Run the tool; return content, or ``ToolResult.error(...)`` for failures."""
+20
View File
@@ -8,6 +8,7 @@ from typing import Any
from pydantic import Field
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import RequestContext
from nanobot.agent.tools.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,
+22 -1
View File
@@ -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()
@@ -51,6 +71,7 @@ class ToolContext:
bus: Any | None = None
subagent_manager: Any | None = None
cron_service: Any | None = None
exec_session_manager: Any | None = None
sessions: Any | None = None
file_state_store: Any = field(default=None)
provider_snapshot_loader: Callable[[], Any] | None = None
+12 -19
View File
@@ -7,7 +7,7 @@ from datetime import datetime
from typing import Any
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ContextAware, RequestContext
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."""
@@ -171,11 +166,9 @@ class CronTool(Tool, ContextAware):
"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 ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
origin_channel = self._origin_channel.get()
origin_chat_id = self._origin_chat_id.get()
if not origin_channel or not origin_chat_id:
return ToolResult.error("Error: scheduled cron jobs must be created from a chat session")
if tz and not cron_expr:
@@ -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})"
+24 -13
View File
@@ -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
@@ -233,11 +250,7 @@ class ExecSessionManager:
session = self._sessions.get(session_id)
if session is None:
raise KeyError(session_id)
if (
owner_session_key
and session.owner_session_key
and session.owner_session_key != owner_session_key
):
if session.owner_session_key and session.owner_session_key != owner_session_key:
raise KeyError(session_id)
if chars:
@@ -279,9 +292,7 @@ class ExecSessionManager:
owner_session_key=session.owner_session_key,
)
for session_id, session in sorted(self._sessions.items())
if not owner_session_key
or not session.owner_session_key
or session.owner_session_key == owner_session_key
if session.owner_session_key == owner_session_key
]
async def _cleanup_locked(self) -> None:
@@ -425,7 +436,7 @@ class WriteStdinTool(Tool):
@classmethod
def create(cls, ctx: Any) -> Tool:
return cls()
return cls(manager=getattr(ctx, "exec_session_manager", None))
@property
def exclusive(self) -> bool:
@@ -569,7 +580,7 @@ class ListExecSessionsTool(Tool):
@classmethod
def create(cls, ctx: Any) -> Tool:
return cls()
return cls(manager=getattr(ctx, "exec_session_manager", None))
@property
def name(self) -> str:
+85 -78
View File
@@ -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(
@@ -275,6 +281,8 @@ class ReadFileTool(_FsTool):
return ToolResult.error(f"Error: Reading {path} is blocked (device path that could hang or produce infinite output).")
fp = self._resolve_read(path)
if not fp.exists():
fp = _builtin_skill_read_path(path) or fp
if _is_blocked_device(fp):
return ToolResult.error(f"Error: Reading {fp} is blocked (device path that could hang or produce infinite output).")
if not fp.exists():
@@ -386,49 +394,33 @@ class ReadFileTool(_FsTool):
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 ToolResult.error("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 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 ToolResult.error(f"Error: Invalid page range '{pages}'. Use format like '1-5'.")
if start > end or start >= total_pages:
doc.close()
return ToolResult.error(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:
@@ -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
@@ -883,36 +888,21 @@ class EditFileTool(_FsTool):
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 ToolResult.error("Error: line_hint cannot be used with occurrence.")
if count > 1 and not replace_all:
if occurrence is not None:
if occurrence > count:
return ToolResult.error(
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 ToolResult.error(
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:
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,10 +913,27 @@ 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 ToolResult.error(
f"Error: expected {expected_replacements} replacements but "
+1
View File
@@ -129,6 +129,7 @@ class ImageGenerationTool(Tool):
"api_base": provider.api_base if provider else None,
"extra_headers": provider.extra_headers if provider else None,
"extra_body": provider.extra_body if provider else None,
"proxy": provider.proxy if provider else None,
}
return cls(**kwargs)
+3
View File
@@ -138,6 +138,9 @@ class _LegacyErrorPrefixTool(Tool):
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
+259 -140
View File
@@ -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 / redirectedin 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.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 ContextAware, RequestContext
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 ToolResult.error(
"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 ToolResult.error(
"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 ToolResult.error("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})."
+234 -131
View File
@@ -1,6 +1,7 @@
"""MCP client: connects to MCP servers and wraps their tools as native nanobot tools."""
import asyncio
import hashlib
import json
import os
import re
@@ -8,7 +9,7 @@ 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
@@ -22,7 +23,14 @@ 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,
)
from nanobot.utils.cancellation import task_is_cancelling
# Transient connection errors that warrant a single retry.
# These typically happen when an MCP server restarts or a network
@@ -47,6 +55,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":
@@ -122,6 +150,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
@@ -129,6 +176,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:
@@ -153,17 +202,24 @@ 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:
@@ -185,6 +241,14 @@ def _redact_url(url: str) -> str:
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:
"""Validate each outgoing MCP HTTP request, including redirect targets."""
ok, error = validate_url_target(str(request.url))
@@ -387,7 +451,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)
@@ -418,15 +482,16 @@ 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).
task = asyncio.current_task()
if task is not None and task.cancelling() > 0:
if task_is_cancelling():
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,
@@ -451,22 +516,35 @@ 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 text and persist any image content as artifacts.
rendered = self._render_call_result(result.content, kwargs)
if getattr(result, "isError", False):
return ToolResult.error(rendered)
return rendered
return "(MCP tool call failed)" # Unreachable, but satisfies type checkers
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__})"
)
def _render_call_result(self, content: Any, arguments: Mapping[str, Any]) -> str:
"""Turn MCP content blocks into a tool result string.
@@ -529,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] = {
@@ -572,8 +650,7 @@ class MCPResourceWrapper(_MCPWrapperBase):
)
return f"(MCP resource read timed out after {self._resource_timeout}s)"
except asyncio.CancelledError:
task = asyncio.current_task()
if task is not None and task.cancelling() > 0:
if task_is_cancelling():
raise
logger.warning("MCP resource '{}' was cancelled by server/SDK", self._name)
return "(MCP resource read was cancelled)"
@@ -619,8 +696,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."""
@@ -630,7 +705,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"
@@ -688,8 +763,7 @@ class MCPPromptWrapper(_MCPWrapperBase):
)
return f"(MCP prompt call timed out after {self._prompt_timeout}s)"
except asyncio.CancelledError:
task = asyncio.current_task()
if task is not None and task.cancelling() > 0:
if task_is_cancelling():
raise
logger.warning("MCP prompt '{}' was cancelled by server/SDK", self._name)
return "(MCP prompt call was cancelled)"
@@ -755,24 +829,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__()
@@ -837,6 +909,7 @@ async def connect_mcp_servers(
follow_redirects=True,
timeout=timeout,
auth=auth,
**_pinned_transport_kwargs(),
)
read, write = await server_stack.enter_async_context(
@@ -854,6 +927,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(
@@ -874,9 +948,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
@@ -989,7 +1063,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:
@@ -1009,93 +1119,48 @@ 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:
if task_is_cancelling():
raise
logger.warning("MCP connection cancelled (will retry next message)")
except BaseException as e:
logger.warning("Failed to connect MCP servers (will retry next message): {}", e)
finally:
state._mcp_connecting = False
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
@@ -1134,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
@@ -1255,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)
@@ -1272,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(
@@ -1293,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
@@ -1312,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
@@ -1328,5 +1410,26 @@ async def _close_server(state: Any, server_name: str) -> None:
return
try:
await stack.aclose()
except asyncio.CancelledError:
if task_is_cancelling():
raise
logger.debug("MCP server '{}' cleanup error (can be ignored)", server_name)
except (RuntimeError, BaseExceptionGroup):
logger.debug("MCP server '{}' cleanup error (can be ignored)", server_name)
async def close_mcp_servers(state: Any) -> None:
"""Close every MCP connection while excluding reconnect and hot reload."""
state._mcp_closing = True
async with _reload_lock(state):
connections = list(state._mcp_stacks.items())
state._mcp_stacks.clear()
for name, connection in connections:
try:
await connection.aclose()
except asyncio.CancelledError:
if task_is_cancelling():
raise
logger.debug("MCP server '{}' cleanup error (can be ignored)", name)
except (RuntimeError, BaseExceptionGroup):
logger.debug("MCP server '{}' cleanup error (can be ignored)", name)
+25 -27
View File
@@ -7,7 +7,7 @@ from typing import Any, Awaitable, Callable
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ContextAware, RequestContext
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
@@ -199,8 +182,23 @@ class MessageTool(Tool, ContextAware):
for row in buttons
):
return ToolResult.error("Error: buttons must be a list of list of strings")
default_channel = self._default_channel.get()
default_chat_id = self._default_chat_id.get()
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 (
@@ -224,7 +222,7 @@ 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
@@ -240,7 +238,7 @@ class MessageTool(Tool, ContextAware):
except (OSError, PermissionError, ValueError) as 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:
+22 -1
View File
@@ -1,9 +1,15 @@
"""Tool registry for dynamic tool management."""
from __future__ import annotations
import json
from typing import Any
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:
@@ -35,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."""
@@ -109,6 +124,12 @@ class ToolRegistry:
)
)
# 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, (
+4 -2
View File
@@ -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
+3
View File
@@ -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",
]
+61 -21
View File
@@ -8,7 +8,7 @@ from typing import TYPE_CHECKING, Any
from loguru import logger
from nanobot.agent.tools.base import Tool, ToolResult
from nanobot.agent.tools.context import ContextAware, RequestContext
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)
# ------------------------------------------------------------------
@@ -328,9 +336,33 @@ class MyTool(Tool, ContextAware):
# -- inspect --
def _current_runtime_value(self, key: str) -> tuple[bool, Any]:
request_ctx = current_request_context()
runtime = request_ctx.runtime if request_ctx is not None else None
if runtime is None or key not in self._MODEL_RUNTIME_FIELDS:
return False, None
return True, getattr(runtime, key)
def _inspect(self, key: str | None) -> str:
if not key:
return self._inspect_all()
if key == "request" or key.startswith("request."):
request_ctx = current_request_context()
if request_ctx is None:
return ToolResult.error("Error: current request context is unavailable")
if key == "request":
return self._format_value(
{field: getattr(request_ctx, field) for field in self._REQUEST_FIELDS},
key,
)
field = key.removeprefix("request.")
if field not in self._REQUEST_FIELDS:
return ToolResult.error(f"Error: '{key}' not found")
return self._format_value(getattr(request_ctx, field), key)
if "." not in key:
found, value = self._current_runtime_value(key)
if found:
return self._format_value(value, key)
top = key.split(".")[0]
if top in self._DENIED_ATTRS or top.startswith("__"):
return ToolResult.error(f"Error: '{top}' is not accessible")
@@ -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):
@@ -435,13 +472,16 @@ class MyTool(Tool, ContextAware):
return ToolResult.error(f"Error: '{key}' must be <= {spec['max']}")
if "min_len" in spec and len(str(value)) < spec["min_len"]:
return ToolResult.error(f"Error: '{key}' must be at least {spec['min_len']} characters")
setattr(self._runtime_state, key, value)
if key == "model":
self._runtime_state._active_preset = None
sync_replay = getattr(self._runtime_state, "_sync_replay_max_messages", None)
if key == "context_window_tokens" and callable(sync_replay):
sync_replay()
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})"
+133 -17
View File
@@ -9,7 +9,7 @@ import shutil
import sys
from contextlib import suppress
from dataclasses import dataclass
from pathlib import Path
from pathlib import Path, PureWindowsPath
from typing import Any
from loguru import logger
@@ -41,6 +41,30 @@ from nanobot.security.workspace_policy import is_path_within
_IS_WINDOWS = sys.platform == "win32"
def _reap_pid(pid: int) -> None:
"""Best-effort ``waitpid`` to reap a child and prevent zombies.
Call this after killing or after normal completion of any subprocess
as a safety net asyncio's child-watcher *should* have reaped it,
but in containers / edge-cases it sometimes doesn't.
Uses ``os`` capability checks rather than ``_IS_WINDOWS`` so this is
safe when tests patch the platform flag while still running on Windows
(``os.waitpid`` / ``os.WNOHANG`` do not exist there).
"""
waitpid = getattr(os, "waitpid", None)
wnohang = getattr(os, "WNOHANG", None)
if waitpid is None or wnohang is None:
return
try:
waitpid(pid, wnohang)
except (ProcessLookupError, ChildProcessError):
# Already reaped, or not our child — both are fine.
pass
except OSError as exc:
logger.debug("_reap_pid({}): {}", pid, exc)
# Policy note appended to recoverable workspace-boundary guard errors.
_WORKSPACE_BOUNDARY_NOTE = (
"\n\nNote: this is a hard policy boundary, not a transient failure. "
@@ -89,7 +113,15 @@ class _PreparedCommand:
maximum=600,
),
shell=StringSchema(
"Optional shell binary to launch. On Unix, supports sh, bash, or zsh.",
(
"Override the Windows shell only when needed. Omit to use "
"PowerShell by default (pwsh when available, else powershell). "
"Pass 'cmd' only for cmd.exe syntax or cmd built-ins."
if _IS_WINDOWS
else "Override the Unix shell only when needed. Omit to use "
"bash by default. Pass 'sh' for POSIX sh or 'zsh' for "
"zsh-specific syntax."
),
nullable=True,
),
login=BooleanSchema(
@@ -156,6 +188,7 @@ class ExecTool(Tool):
allowed_env_keys=cfg.allowed_env_keys,
allow_patterns=cfg.allow_patterns,
deny_patterns=cfg.deny_patterns,
session_manager=getattr(ctx, "exec_session_manager", None),
)
def __init__(
@@ -227,6 +260,13 @@ class ExecTool(Tool):
@property
def description(self) -> str:
platform_note = (
"On Windows, use PowerShell syntax by default; pass shell='cmd' "
"only for cmd-specific commands. "
if _IS_WINDOWS
else "On Unix, commands run through bash by default; pass shell='sh' "
"or shell='zsh' when needed. "
)
return (
"Execute a shell command and return its output. "
"Use this for tests, builds, package commands, git commands, and "
@@ -234,6 +274,7 @@ class ExecTool(Tool):
"inspection and apply_patch/write_file/edit_file for file changes "
"instead of cat, shell find/grep, echo, or sed. "
"Use -y or --yes flags to avoid interactive prompts. "
f"{platform_note}"
"For long-running or interactive commands, pass yield_time_ms; "
"if the command keeps running, exec returns a session_id that can "
"be polled or written to with write_stdin. Output is truncated at "
@@ -267,6 +308,7 @@ class ExecTool(Tool):
if yield_time_ms is not None:
return await self._execute_session(prepared, yield_time_ms, max_output_chars)
process: asyncio.subprocess.Process | None = None
try:
process = await self._spawn(
prepared.command,
@@ -288,6 +330,11 @@ class ExecTool(Tool):
await self._kill_process(process)
raise
# Safety-net reap: asyncio *should* have reaped the child via
# communicate(), but in containers the child-watcher sometimes
# misses it, leaving a zombie.
_reap_pid(process.pid)
output_parts = []
if stdout:
@@ -314,6 +361,10 @@ class ExecTool(Tool):
return result
except Exception as e:
# Kill and reap the child if it was spawned but an unexpected
# error prevented communicate() from completing.
if process is not None:
await self._kill_process(process)
return ToolResult.error(f"Error executing command: {str(e)}")
async def _execute_session(
@@ -468,17 +519,31 @@ class ExecTool(Tool):
) -> asyncio.subprocess.Process:
"""Launch *command* in a platform-appropriate shell."""
if _IS_WINDOWS:
if "\n" in command:
return await asyncio.create_subprocess_exec(
"powershell", "-NoProfile", "-Command", command,
# Default to PowerShell so single-line and multi-line commands
# share the same shell semantics. cmd.exe is reachable via the
# explicit shell="cmd" parameter (see _resolve_shell).
default_program = shutil.which("pwsh") or shutil.which("powershell") or "powershell"
program = shell_program or default_program
program_name = PureWindowsPath(program).name.lower()
if program_name in ("cmd", "cmd.exe"):
cmd_env = {**env, "COMSPEC": program}
return await asyncio.create_subprocess_shell(
command,
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
cwd=cwd,
env=env,
env=cmd_env,
)
return await asyncio.create_subprocess_shell(
command,
command = ExecTool._normalize_powershell_command(command)
command = (
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false)\n"
"$PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'\n"
f"{command}\n"
"if ($LASTEXITCODE -ne $null) { exit $LASTEXITCODE }"
)
return await asyncio.create_subprocess_exec(
program, "-NoProfile", "-NonInteractive", "-Command", command,
stdin=stdin,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
@@ -500,14 +565,60 @@ class ExecTool(Tool):
env=env,
)
@staticmethod
def _normalize_powershell_command(command: str) -> str:
stripped = command.lstrip()
if not stripped or stripped[0] not in {"'", '"'}:
return command
quote = stripped[0]
end = stripped.find(quote, 1)
if end == -1 or end + 1 >= len(stripped) or not stripped[end + 1].isspace():
return command
executable = stripped[1:end]
looks_like_windows_executable = (
bool(re.match(r"^[A-Za-z]:[\\/]", executable))
or executable.startswith(r"\\")
or executable.lower().endswith((".exe", ".cmd", ".bat", ".ps1"))
)
if not looks_like_windows_executable:
return command
leading = command[: len(command) - len(stripped)]
return f"{leading}& {stripped}"
@staticmethod
def _resolve_shell(shell: str | None) -> tuple[str | None, str | None]:
if not shell:
return None, None
if _IS_WINDOWS:
return None, ToolResult.error("Error: shell parameter is not supported on Windows")
if "\0" in shell or "\n" in shell or "\r" in shell:
return None, ToolResult.error("Error: shell contains invalid characters")
if _IS_WINDOWS:
win_allowed = {"powershell", "powershell.exe", "pwsh", "pwsh.exe", "cmd", "cmd.exe"}
path = Path(shell).expanduser()
if path.is_absolute():
name = path.name.lower()
if name not in win_allowed:
return None, ToolResult.error(
f"Error: unsupported shell {shell!r}. "
"Allowed: powershell, pwsh, cmd"
)
if not path.is_file():
return None, ToolResult.error(f"Error: shell is not found: {shell}")
return str(path), None
if "/" in shell or "\\" in shell:
return None, ToolResult.error("Error: shell must be a shell name or absolute path")
if shell.lower() not in win_allowed:
return None, ToolResult.error(
f"Error: unsupported shell {shell!r}. "
"Allowed: powershell, pwsh, cmd"
)
if shell.lower() in ("cmd", "cmd.exe"):
resolved = os.environ.get("COMSPEC") or shutil.which("cmd") or "cmd"
return resolved, None
resolved = shutil.which(shell) or shell
return resolved, None
allowed = {"sh", "bash", "zsh"}
path = Path(shell).expanduser()
if path.is_absolute():
@@ -527,17 +638,22 @@ class ExecTool(Tool):
@staticmethod
async def _kill_process(process: asyncio.subprocess.Process) -> None:
"""Kill a subprocess and reap it to prevent zombies."""
process.kill()
"""Kill a subprocess and reap it to prevent zombies.
Safe to call when the process has already exited (e.g. generic
exception handlers after a successful ``communicate()``): skips
``kill()`` and only runs the safety-net reap.
"""
if process.returncode is not None:
_reap_pid(process.pid)
return
try:
with suppress(ProcessLookupError):
process.kill()
with suppress(asyncio.TimeoutError):
await asyncio.wait_for(process.wait(), timeout=5.0)
finally:
if not _IS_WINDOWS:
try:
os.waitpid(process.pid, os.WNOHANG)
except (ProcessLookupError, ChildProcessError) as e:
logger.debug("Process already reaped or not found: {}", e)
_reap_pid(process.pid)
def _build_env(self) -> dict[str, str]:
"""Build a minimal environment for subprocess execution.
+14 -22
View File
@@ -2,11 +2,10 @@
from __future__ import annotations
from contextvars import ContextVar
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.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import current_request_context
from nanobot.agent.tools.schema import NumberSchema, StringSchema, tool_parameters_schema
from nanobot.security.workspace_access import current_workspace_scope
@@ -30,30 +29,16 @@ if TYPE_CHECKING:
required=["task"],
)
)
class SpawnTool(Tool, ContextAware):
class SpawnTool(Tool):
"""Tool to spawn a subagent for background task execution."""
def __init__(self, manager: "SubagentManager"):
self._manager = manager
self._origin_channel: ContextVar[str] = ContextVar("spawn_origin_channel", default="cli")
self._origin_chat_id: ContextVar[str] = ContextVar("spawn_origin_chat_id", default="direct")
self._session_key: ContextVar[str] = ContextVar("spawn_session_key", default="cli:direct")
self._origin_message_id: ContextVar[str | None] = ContextVar(
"spawn_origin_message_id",
default=None,
)
@classmethod
def create(cls, ctx: Any) -> Tool:
return cls(manager=ctx.subagent_manager)
def set_context(self, ctx: RequestContext) -> None:
"""Set the origin context for subagent announcements."""
self._origin_channel.set(ctx.channel)
self._origin_chat_id.set(ctx.chat_id)
self._session_key.set(ctx.session_key or f"{ctx.channel}:{ctx.chat_id}")
self._origin_message_id.set(ctx.message_id)
@property
def name(self) -> str:
return "spawn"
@@ -84,13 +69,20 @@ class SpawnTool(Tool, ContextAware):
f"({running}/{limit} running). Wait for a running subagent "
f"to complete before spawning a new one."
)
request_ctx = current_request_context()
if request_ctx is None or request_ctx.runtime is None:
return ToolResult.error("Error: spawn requires an active model runtime")
origin_channel = request_ctx.channel
origin_chat_id = request_ctx.chat_id
session_key = request_ctx.session_key or f"{origin_channel}:{origin_chat_id}"
return await self._manager.spawn(
task=task,
runtime=request_ctx.runtime,
label=label,
origin_channel=self._origin_channel.get(),
origin_chat_id=self._origin_chat_id.get(),
session_key=self._session_key.get(),
origin_message_id=self._origin_message_id.get(),
origin_channel=origin_channel,
origin_chat_id=origin_chat_id,
session_key=session_key,
origin_message_id=request_ctx.message_id,
temperature=temperature,
workspace_scope=current_workspace_scope(),
)
+98 -7
View File
@@ -111,6 +111,39 @@ def _validate_url_safe(url: str) -> tuple[bool, str]:
return validate_url_target(url)
def _resolve_url_safe(url: str) -> tuple[bool, str, tuple[str, ...]]:
"""Validate URL and return the resolved IPs to pin during the request."""
from nanobot.security.network import resolve_url_target
return resolve_url_target(url)
def _pinned_dns_transport() -> httpx.AsyncBaseTransport:
from nanobot.security.network import PinnedDNSAsyncTransport
return PinnedDNSAsyncTransport()
def _fetch_client_kwargs(proxy: str | None, timeout: float) -> dict[str, Any]:
from nanobot.security.network import httpx_env_proxy_mounts
kwargs: dict[str, Any] = {"timeout": timeout}
if proxy:
kwargs["proxy"] = proxy
else:
kwargs["transport"] = _pinned_dns_transport()
mounts = httpx_env_proxy_mounts()
if mounts:
kwargs["mounts"] = mounts
return kwargs
def _unsafe_url_request_error(exc: BaseException) -> str | None:
from nanobot.security.network import UnsafeURLRequestError
return str(exc) if isinstance(exc, UnsafeURLRequestError) else None
async def _get_with_safe_redirects(
client: httpx.AsyncClient,
url: str,
@@ -119,11 +152,17 @@ async def _get_with_safe_redirects(
"""GET a URL while validating every redirect target before requesting it."""
current_url = url
for _ in range(MAX_REDIRECTS + 1):
is_valid, error_msg = _validate_url_safe(current_url)
is_valid, error_msg, _ = _resolve_url_safe(current_url)
if not is_valid:
return None, f"Redirect blocked: {error_msg}"
response = await client.get(current_url, headers=headers, follow_redirects=False)
try:
response = await client.get(current_url, headers=headers, follow_redirects=False)
except httpx.RequestError as exc:
unsafe_error = _unsafe_url_request_error(exc)
if unsafe_error is not None:
return None, f"Redirect blocked: {unsafe_error}"
raise
is_redirect = 300 <= response.status_code < 400
if not is_redirect:
return response, None
@@ -152,7 +191,7 @@ async def _stream_with_safe_redirects(
"""Open a streamed response while validating every redirect target first."""
current_url = url
for _ in range(MAX_REDIRECTS + 1):
is_valid, error_msg = _validate_url_safe(current_url)
is_valid, error_msg, _ = _resolve_url_safe(current_url)
if not is_valid:
return None, None, f"Redirect blocked: {error_msg}"
@@ -162,7 +201,13 @@ async def _stream_with_safe_redirects(
headers=headers,
follow_redirects=False,
)
response = await stream.__aenter__()
try:
response = await stream.__aenter__()
except httpx.RequestError as exc:
unsafe_error = _unsafe_url_request_error(exc)
if unsafe_error is not None:
return None, None, f"Redirect blocked: {unsafe_error}"
raise
is_redirect = 300 <= response.status_code < 400
if not is_redirect:
return response, stream, None
@@ -338,6 +383,9 @@ class WebSearchTool(Tool):
return "volcengine" if api_key else "duckduckgo"
if provider == "keenable":
return "keenable"
if provider == "serper":
api_key = self.config.api_key or os.environ.get("SERPER_API_KEY", "")
return "serper" if api_key else "duckduckgo"
return provider
@property
@@ -394,6 +442,8 @@ class WebSearchTool(Tool):
)
elif provider == "keenable":
return await self._search_keenable(query, n)
elif provider == "serper":
return await self._search_serper(query, n)
else:
return ToolResult.error(f"Error: unknown search provider '{provider}'")
@@ -668,6 +718,43 @@ class WebSearchTool(Tool):
except Exception as e:
return ToolResult.error(f"Error: Exa search failed: {e}")
async def _search_serper(self, query: str, n: int) -> str:
"""Search via Serper.dev (Google Search API)."""
api_key = self.config.api_key or os.environ.get("SERPER_API_KEY", "")
if not api_key:
logger.warning("SERPER_API_KEY not set, falling back to DuckDuckGo")
return await self._search_duckduckgo(query, n)
try:
headers = {
"X-API-KEY": api_key,
"Content-Type": "application/json",
"User-Agent": self.user_agent,
}
async with httpx.AsyncClient(proxy=self.proxy) as client:
r = await client.post(
"https://google.serper.dev/search",
headers=headers,
json={"q": query, "num": n},
timeout=float(self.config.timeout),
)
r.raise_for_status()
items = [
{
"title": result.get("title", ""),
"url": result.get("link", ""),
"content": result.get("snippet", ""),
}
for result in r.json().get("organic", [])
if isinstance(result, dict)
]
return _format_results(query, items, n)
except httpx.HTTPStatusError as e:
if e.response.status_code == 429:
return ToolResult.error("Error: Serper search rate limited. Try again later or reduce search frequency.")
return ToolResult.error(f"Error: Serper search failed ({e.response.status_code}): {e}")
except Exception as e:
return ToolResult.error(f"Error: Serper search failed: {e}")
async def _search_volcengine(
self,
query: str,
@@ -911,7 +998,9 @@ class WebFetchTool(Tool):
# Detect and fetch images directly to avoid Jina's textual image captioning
try:
async with httpx.AsyncClient(proxy=self.proxy, timeout=15.0) as client:
async with httpx.AsyncClient(
**_fetch_client_kwargs(self.proxy, 15.0),
) as client:
r, stream, redirect_error = await _stream_with_safe_redirects(
client,
url,
@@ -932,6 +1021,9 @@ class WebFetchTool(Tool):
if stream is not None:
await stream.__aexit__(None, None, None)
except Exception as e:
unsafe_error = _unsafe_url_request_error(e)
if unsafe_error is not None:
return json.dumps({"error": f"URL validation failed: {unsafe_error}", "url": url}, ensure_ascii=False)
logger.debug("Pre-fetch image detection failed for {}: {}", url, e)
result = None
@@ -981,8 +1073,7 @@ class WebFetchTool(Tool):
"""Local fallback using readability-lxml."""
try:
async with httpx.AsyncClient(
timeout=30.0,
proxy=self.proxy,
**_fetch_client_kwargs(self.proxy, 30.0),
) as client:
r, redirect_error = await _get_with_safe_redirects(
client,
+90
View File
@@ -0,0 +1,90 @@
"""Turn-scoped hook assembly for agent runs."""
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
from nanobot.agent.hook import (
AgentHook,
AgentTurnHookContext,
AgentTurnHookFactory,
CompositeHook,
)
from nanobot.agent.progress_hook import AgentProgressHook
@dataclass(slots=True)
class AgentTurnHookSpec:
"""Inputs needed to build the hook chain for one agent turn."""
on_progress: Callable[..., Awaitable[None]] | None = None
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
workspace: Path | None = None
tool_hint_max_length: int = 40
on_iteration: Callable[[int], None] | None = None
registered_hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
turn_hook_factories: list[AgentTurnHookFactory] = field(default_factory=list)
registered_hooks: list[AgentHook] = field(default_factory=list)
turn_hooks: list[AgentHook] = field(default_factory=list)
ephemeral: bool = False
run_extra_hooks_for_ephemeral: bool = False
def build_agent_turn_hook(spec: AgentTurnHookSpec) -> AgentHook:
"""Build the hook chain used by ``AgentRunner`` for one turn."""
progress_hook = AgentProgressHook(
on_progress=spec.on_progress,
on_stream=spec.on_stream,
on_stream_end=spec.on_stream_end,
session_key=spec.session_key,
tool_hint_max_length=spec.tool_hint_max_length,
on_iteration=spec.on_iteration,
)
if spec.ephemeral and not spec.run_extra_hooks_for_ephemeral:
return progress_hook
turn_context = AgentTurnHookContext(
on_progress=spec.on_progress,
workspace=spec.workspace,
channel=spec.channel,
chat_id=spec.chat_id,
message_id=spec.message_id,
session_key=spec.session_key,
metadata=dict(spec.metadata or {}),
ephemeral=spec.ephemeral,
)
hook_chain: list[AgentHook] = [progress_hook]
for factory in spec.registered_hook_factories:
try:
created_hook = factory(turn_context)
except Exception:
logger.exception("Agent turn hook factory failed: {}", factory)
continue
if created_hook is not None:
hook_chain.append(created_hook)
hook_chain.extend(spec.registered_hooks)
for factory in spec.turn_hook_factories:
try:
created_hook = factory(turn_context)
except Exception:
logger.exception("Agent turn hook factory failed: {}", factory)
continue
if created_hook is not None:
hook_chain.append(created_hook)
hook_chain.extend(spec.turn_hooks)
return CompositeHook(hook_chain) if len(hook_chain) > 1 else progress_hook
+60
View File
@@ -0,0 +1,60 @@
"""Background process control for the WebUI-managed OpenAI-compatible API."""
from __future__ import annotations
import hashlib
import sys
from dataclasses import dataclass
from pathlib import Path
from nanobot.process_runtime import (
ManagedProcessRuntime,
ProcessRuntimePaths,
ProcessStartOptions,
)
@dataclass(frozen=True)
class ApiStartOptions(ProcessStartOptions):
"""Options needed to start a managed ``nanobot serve`` process."""
host: str = "127.0.0.1"
def api_runtime_paths(config_path: Path) -> ProcessRuntimePaths:
"""Return isolated state and log paths for one API process."""
resolved = config_path.expanduser().resolve(strict=False)
suffix = hashlib.sha256(str(resolved).encode("utf-8")).hexdigest()[:16]
run_dir = resolved.parent / "run"
logs_dir = resolved.parent / "logs"
return ProcessRuntimePaths(
run_dir=run_dir,
logs_dir=logs_dir,
state_path=run_dir / f"api.{suffix}.json",
log_path=logs_dir / f"api.{suffix}.log",
)
class ApiRuntime(ManagedProcessRuntime):
"""Manage a WebUI-controlled OpenAI-compatible API process."""
service_name = "api"
def _build_child_command(self, options: ApiStartOptions) -> list[str]:
command = [
self.python_executable or sys.executable,
"-m",
"nanobot",
"serve",
"--host",
options.host,
"--port",
str(options.port),
]
if options.verbose:
command.append("--verbose")
if options.workspace:
command.extend(["--workspace", options.workspace])
if options.config_path:
command.extend(["--config", options.config_path])
return command
+41 -12
View File
@@ -41,6 +41,26 @@ __all__ = (
API_SESSION_KEY = "api:default"
API_CHAT_ID = "default"
_AGENT_LOOP_KEY = web.AppKey[Any]("agent_loop")
_MODEL_NAME_KEY = web.AppKey[str]("model_name")
_REQUEST_TIMEOUT_KEY = web.AppKey[float]("request_timeout")
_SESSION_LOCKS_KEY = web.AppKey[dict]("session_locks")
_MISSING = object()
def _app_value(
app: Any,
key: web.AppKey[Any],
legacy_key: str,
default: Any = _MISSING,
) -> Any:
"""Read typed aiohttp state while accepting lightweight dict test doubles."""
try:
return app[key]
except KeyError:
if default is _MISSING:
return app[legacy_key]
return app.get(legacy_key, default)
# ---------------------------------------------------------------------------
@@ -209,9 +229,14 @@ async def handle_chat_completions(request: web.Request) -> web.Response:
if not isinstance(content_type, str):
content_type = ""
agent_loop = request.app["agent_loop"]
timeout_s: float = request.app.get("request_timeout", 120.0)
model_name: str = request.app.get("model_name", "nanobot")
agent_loop = _app_value(request.app, _AGENT_LOOP_KEY, "agent_loop")
timeout_s: float = _app_value(
request.app,
_REQUEST_TIMEOUT_KEY,
"request_timeout",
120.0,
)
model_name: str = _app_value(request.app, _MODEL_NAME_KEY, "model_name", "nanobot")
stream = False
try:
@@ -238,7 +263,11 @@ async def handle_chat_completions(request: web.Request) -> web.Response:
return _error_json(400, f"Only configured model '{model_name}' is available")
session_key = f"api:{session_id}" if session_id else API_SESSION_KEY
session_locks: dict[str, asyncio.Lock] = request.app["session_locks"]
session_locks: dict[str, asyncio.Lock] = _app_value(
request.app,
_SESSION_LOCKS_KEY,
"session_locks",
)
session_lock = session_locks.setdefault(session_key, asyncio.Lock())
logger.info(
@@ -366,7 +395,7 @@ async def handle_chat_completions(request: web.Request) -> web.Response:
async def handle_models(request: web.Request) -> web.Response:
"""GET /v1/models"""
model_name = request.app.get("model_name", "nanobot")
model_name = _app_value(request.app, _MODEL_NAME_KEY, "model_name", "nanobot")
return web.json_response(
{
"object": "list",
@@ -404,21 +433,21 @@ def create_app(
agent_loop: An initialized AgentLoop instance.
model_name: Model name reported in responses.
request_timeout: Per-request timeout in seconds.
api_key: Optional API key for Bearer-token authentication.
api_key: Optional API key for Bearer-token authentication on API routes.
"""
app = web.Application(client_max_size=20 * 1024 * 1024) # 20MB for base64 images
app["agent_loop"] = agent_loop
app["model_name"] = model_name
app["request_timeout"] = request_timeout
app["session_locks"] = {} # per-user locks, keyed by session_key
app[_AGENT_LOOP_KEY] = agent_loop
app[_MODEL_NAME_KEY] = model_name
app[_REQUEST_TIMEOUT_KEY] = request_timeout
app[_SESSION_LOCKS_KEY] = {} # per-user locks, keyed by session_key
@web.middleware
async def auth_middleware(request: web.Request, handler) -> web.StreamResponse:
if not api_key:
return await handler(request)
# Allow unauthenticated health checks.
if request.path == "/health":
return await handler(request)
if not api_key:
return await handler(request)
auth = request.headers.get("Authorization", "")
if not auth.startswith("Bearer "):
return _error_json(401, "Missing Authorization header. Use: Bearer <api_key>")

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