Skip to content

Your lightweight open-source personal agent.

fix(api): keep unconfigured services running and preserve Docker onboarding

chengyongrude8fbc3ad2cb
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ea8897a36..1b5fe26e6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -423,7 +423,7 @@ jobs:
- name: Build image with default channel dependencies
run: docker build -t nanobot:test .
- - name: Verify first-boot WebUI and optional API
+ - name: Verify first-boot WebUI and API
run: python scripts/docker_compose_smoke.py --image nanobot:test
- name: Verify Docker Compose startup and privilege boundary
@@ -450,7 +450,7 @@ jobs:
done
INNER
OUTER
- docker compose -f docker-compose.yml -f docker-compose.bwrap.yml --profile cli --profile api \
+ docker compose -f docker-compose.yml -f docker-compose.bwrap.yml --profile cli \
config --format json > "${RUNNER_TEMP}/bwrap-compose.json"
python - <<'PY'
import json
diff --git a/docker-compose.yml b/docker-compose.yml
index e5cf24857..509a7e451 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -45,11 +45,6 @@ services:
nanobot-api:
container_name: nanobot-api
<<: *common-config
- # Optional: the OpenAI-compatible API needs a configured provider before it
- # can serve, so it is not part of the default `docker compose up`. Start it
- # with `docker compose --profile api up -d` once a provider is configured.
- profiles:
- - api
command:
["serve", "--host", "0.0.0.0", "-w", "/home/nanobot/.nanobot/api-workspace"]
restart: unless-stopped
diff --git a/docs/deployment.md b/docs/deployment.md
index be4c2b098..b2fb74f6d 100644
--- a/docs/deployment.md
+++ b/docs/deployment.md
@@ -90,7 +90,7 @@ On a new Linux host, install Git and Docker with the Compose plugin, then get th
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
docker compose up -d
-docker compose logs nanobot-gateway
+docker compose logs
```
On first boot, Compose initializes `~/.nanobot/config.json` with container bind addresses and random WebUI/API credentials. Open `http://HOST:8765`, enter the WebUI password printed in the first-boot logs, then configure your provider and model in **Settings → Models**. Send a message to verify the setup. No provider is required just to open the WebUI.
@@ -99,15 +99,15 @@ Export `NANOBOT_WEB_TOKEN` or `NANOBOT_API_KEY` before the first startup to supp
The configuration and workspace persist in the `~/.nanobot` bind mount. Keep `agents.defaults.workspace` as a container path, normally `~/.nanobot/workspace`, rather than a host home-directory path. Other config `${VAR}` references require explicit `environment` entries in the CLI and gateway services; Compose does not forward arbitrary host variables.
-The OpenAI-compatible API is optional and requires a configured provider. After completing model setup, enable it with:
+Compose starts both the gateway and the OpenAI-compatible API. Before a provider/model is configured, the API remains available for health checks and returns HTTP 503 with a `configuration_error` for model requests, including streaming requests. After configuring the model, restart the API to load those settings:
```bash
-docker compose --profile api up -d
+docker compose restart nanobot-api
```
Its endpoint is `http://127.0.0.1:8900/v1`; use the API key from the first-boot logs or `api.apiKey` in the persisted config. It is published to host loopback only.
-For terminal setup, run `docker compose run --rm nanobot-cli onboard --wizard` and preserve existing settings. Verify it with `docker compose run --rm nanobot-cli agent -m "Hello!"` before starting the persistent gateway.
+CLI commands do not trigger Docker service initialization. For terminal setup, run `docker compose run --rm nanobot-cli onboard --wizard`, configure the model, and merge the [Docker bind and authentication settings](#docker) and set `api.apiKey` to a private credential before starting services. Plain `onboard` keeps its original first-run behavior without an extra overwrite prompt. Verify it with `docker compose run --rm nanobot-cli agent -m "Hello!"` before starting the persistent gateway.
The default image preinstalls WhatsApp dependencies. To bake other enabled channels into an image (recommended for deployments without PyPI access), pass a comma-separated `NANOBOT_CHANNELS` build argument:
diff --git a/docs/openai-api.md b/docs/openai-api.md
index 86af82007..829d72669 100644
--- a/docs/openai-api.md
+++ b/docs/openai-api.md
@@ -53,6 +53,8 @@ curl http://127.0.0.1:8900/v1/models \
`nanobot serve` creates its own in-process message queue without starting chat-channel consumers. The API service started from **Settings → System** uses the same command. An explicit `channel` and `chat_id` can enqueue a tool message, but it does not cause platform delivery, even when that channel is enabled or a separate gateway is running. Do not treat the tool acknowledgement as a delivery receipt. Applications that need to forward an API result to Telegram, Discord, or another platform must handle that delivery separately.
+The API can start before provider/model setup is complete. Health checks remain available, and authenticated model requests return a setup error without executing an agent turn. Configure the provider/model, then restart the API process to load the new settings.
+
## Sessions, failures, and retries
All callers use the same configured API key, agent, workspace, long-term memory, and tool permissions. Any authorized caller can select any `session_id`; the server does not bind it to a user identity. A distinct ID separates conversation history, not access to files or memory. Use [separate instances](./multiple-instances.md) for separate trust boundaries, or enforce user-to-session authorization in your own application before forwarding requests.
@@ -63,6 +65,7 @@ Requests with the same session ID are serialized within one API process. Differe
|---|---|
| Missing or incorrect configured key | HTTP 401 |
| Invalid request or wrong model | HTTP 400 |
+| Provider/model setup incomplete, including streaming requests | HTTP 503 with `configuration_error` |
| Oversized or invalid upload | HTTP 413 |
| Non-streaming execution timeout | HTTP 504 |
| Unhandled non-streaming execution failure | HTTP 500 |
diff --git a/entrypoint.sh b/entrypoint.sh
index 62a98309c..d69e047ad 100755
--- a/entrypoint.sh
+++ b/entrypoint.sh
@@ -1,24 +1,6 @@
#!/bin/sh
dir="$HOME/.nanobot"
-# Render keeps environment references in its deployment template. Local
-# Compose generates and validates its initial config through Python instead.
-if [ "$RENDER" = "true" ]; then
- config="$dir/config.json"
- mkdir -p "$dir" || exit 1
- if [ ! -f "$config" ]; then
- echo "[entrypoint] initializing $config from render-config.json"
- cp /app/render-config.json "$config" || exit 1
- else
- echo "[entrypoint] existing $config found — leaving it in place"
- fi
- set -- "$@" --config "$config"
-elif [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ]; then
- config="$dir/config.json"
- python -m nanobot.cli.docker_bootstrap "$config" || exit 1
- 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
@@ -28,7 +10,7 @@ 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 "$@"
+ exec setpriv --reuid=nanobot --regid=nanobot --init-groups "$0" "$@"
fi
echo "[entrypoint] error: started as root but setpriv privilege drop failed — refusing to run as root" >&2
exit 1
@@ -48,4 +30,22 @@ EOF
exit 1
fi
+# Render keeps environment references in its deployment template. Local
+# Compose generates and validates its initial config through Python instead.
+if [ "$RENDER" = "true" ]; then
+ config="$dir/config.json"
+ mkdir -p "$dir" || exit 1
+ if [ ! -f "$config" ]; then
+ echo "[entrypoint] initializing $config from render-config.json"
+ cp /app/render-config.json "$config" || exit 1
+ else
+ echo "[entrypoint] existing $config found — leaving it in place"
+ fi
+ set -- "$@" --config "$config"
+elif [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ] && { [ "$1" = "gateway" ] || [ "$1" = "serve" ]; }; then
+ config="$dir/config.json"
+ python -m nanobot.cli.docker_bootstrap "$config" || exit 1
+ set -- "$@" --config "$config"
+fi
+
exec nanobot "$@"
diff --git a/nanobot/api/server.py b/nanobot/api/server.py
index f18e03d8b..d5062f820 100644
--- a/nanobot/api/server.py
+++ b/nanobot/api/server.py
@@ -20,6 +20,7 @@ from loguru import logger
from nanobot.agent.hook import AgentHook, AgentRunHookContext
from nanobot.config.paths import get_media_dir
from nanobot.providers.base import LLMUsage
+from nanobot.providers.unconfigured_provider import UnconfiguredProvider
from nanobot.utils.helpers import safe_filename
from nanobot.utils.media_decode import (
MAX_FILE_SIZE,
@@ -275,6 +276,13 @@ async def handle_chat_completions(request: web.Request) -> web.Response | web.St
content_type = _as_str(cast(object, request.content_type or ""))
agent_loop = request.app[_AGENT_LOOP_KEY]
+ if isinstance(agent_loop.provider, UnconfiguredProvider):
+ return _error_json(
+ 503,
+ "Model is not configured. Open Settings → Models to configure a provider "
+ "and model, then restart the API server.",
+ err_type="configuration_error",
+ )
timeout_s: float = request.app[_REQUEST_TIMEOUT_KEY]
model_name: str = request.app[_MODEL_NAME_KEY]
diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.py
index a37c754d3..aa42ba452 100644
--- a/nanobot/cli/commands.py
+++ b/nanobot/cli/commands.py
@@ -393,9 +393,17 @@ def serve(
tools = ToolRegistry()
register_image_generation_tool(runtime_config, tools, workspace=runtime_config.workspace_path)
mcp_provider = MCPProvider.from_config(runtime_config, tools)
+ from nanobot.providers.factory import build_unconfigured_provider_snapshot
+
+ setup_error = _provider_setup_error(runtime_config)
+ unconfigured_provider = (
+ build_unconfigured_provider_snapshot(runtime_config, setup_error).provider
+ if setup_error else None
+ )
try:
agent_loop = AgentLoop.from_config(
runtime_config, bus,
+ provider=unconfigured_provider,
session_manager=session_manager,
hook_factories=[create_file_edit_activity_hook],
tool_registry=tools,
diff --git a/nanobot/cli/docker_bootstrap.py b/nanobot/cli/docker_bootstrap.py
index af1898242..5dc49b9d5 100644
--- a/nanobot/cli/docker_bootstrap.py
+++ b/nanobot/cli/docker_bootstrap.py
@@ -5,32 +5,36 @@ import secrets
import sys
from pathlib import Path
+from filelock import FileLock
+
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.config.loader import save_config
from nanobot.config.schema import Config
def initialize_config(path: Path) -> None:
- if path.exists():
- print(f"[entrypoint] existing {path} found — leaving it in place")
- print(f"[entrypoint] WebUI password: {path} (channels.websocket.tokenIssueSecret)")
- return
-
- web_token = os.environ.get("NANOBOT_WEB_TOKEN") or secrets.token_hex(16)
- api_key = os.environ.get("NANOBOT_API_KEY") or secrets.token_hex(16)
- websocket = WebSocketConfig(
- enabled=True, host="0.0.0.0", token_issue_secret=web_token,
- websocket_requires_token=True,
- )
- config = Config.model_validate({
- "gateway": {"host": "0.0.0.0"},
- "channels": {"websocket": websocket.model_dump(by_alias=True)},
- "api": {"host": "0.0.0.0", "api_key": api_key},
- })
- save_config(config, path)
- print(f"[entrypoint] initialized {path}")
- print(f"[entrypoint] WebUI: http://localhost:8765 — password: {web_token}")
- print(f"[entrypoint] OpenAI-compatible API key: {api_key}")
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with FileLock(path.parent / ".docker-bootstrap.lock"):
+ if path.exists():
+ print(f"[entrypoint] existing {path} found — leaving it in place")
+ print(f"[entrypoint] WebUI password: {path} (channels.websocket.tokenIssueSecret)")
+ return
+
+ web_token = os.environ.get("NANOBOT_WEB_TOKEN") or secrets.token_hex(16)
+ api_key = os.environ.get("NANOBOT_API_KEY") or secrets.token_hex(16)
+ websocket = WebSocketConfig(
+ enabled=True, host="0.0.0.0", token_issue_secret=web_token,
+ websocket_requires_token=True,
+ )
+ config = Config.model_validate({
+ "gateway": {"host": "0.0.0.0"},
+ "channels": {"websocket": websocket.model_dump(by_alias=True)},
+ "api": {"host": "0.0.0.0", "api_key": api_key},
+ })
+ save_config(config, path)
+ print(f"[entrypoint] initialized {path}")
+ print(f"[entrypoint] WebUI: http://localhost:8765 — password: {web_token}")
+ print(f"[entrypoint] OpenAI-compatible API key: {api_key}")
if __name__ == "__main__":
diff --git a/nanobot/providers/factory.py b/nanobot/providers/factory.py
index eeae10948..7f1190b91 100644
--- a/nanobot/providers/factory.py
+++ b/nanobot/providers/factory.py
@@ -222,7 +222,7 @@ def make_provider(
def build_unconfigured_provider_snapshot(config: Config, setup_error: str) -> ProviderSnapshot:
- """Build a non-networking runtime so the WebUI can collect first-time setup."""
+ """Build a non-networking runtime while provider/model setup is incomplete."""
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
preset = config.resolve_preset()
diff --git a/nanobot/providers/unconfigured_provider.py b/nanobot/providers/unconfigured_provider.py
index 9a3f6420b..c06e134a9 100644
--- a/nanobot/providers/unconfigured_provider.py
+++ b/nanobot/providers/unconfigured_provider.py
@@ -1,4 +1,4 @@
-"""Provider used while the local WebUI is waiting for first-time setup."""
+"""Provider used while an application is waiting for model setup."""
from __future__ import annotations
@@ -8,7 +8,7 @@ from nanobot.providers.base import LLMProvider, LLMResponse
class UnconfiguredProvider(LLMProvider):
- """Keep the gateway available for settings before a model is configured."""
+ """Keep the runtime available before a model is configured."""
def __init__(self, default_model: str) -> None:
super().__init__(provider_name="unconfigured")
diff --git a/scripts/docker_compose_smoke.py b/scripts/docker_compose_smoke.py
index cfcd51537..807561bb4 100644
--- a/scripts/docker_compose_smoke.py
+++ b/scripts/docker_compose_smoke.py
@@ -1,4 +1,4 @@
-"""Verify Compose first boot, WebUI authentication, restart, and optional API."""
+"""Verify Compose first boot, WebUI authentication, restart, and API readiness."""
import argparse
import json
@@ -11,10 +11,13 @@ from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
-def request(url: str, secret: str = "") -> tuple[int, bytes]:
+def request(url: str, secret: str = "", body: dict[str, object] | None = None) -> tuple[int, bytes]:
headers = {"Authorization": f"Bearer {secret}"} if secret else {}
+ if body is not None:
+ headers["Content-Type"] = "application/json"
+ data = json.dumps(body).encode() if body is not None else None
try:
- with urlopen(Request(url, headers=headers), timeout=3) as response:
+ with urlopen(Request(url, data=data, headers=headers), timeout=3) as response:
return response.status, response.read()
except HTTPError as exc:
return exc.code, exc.read()
@@ -27,7 +30,7 @@ def main() -> None:
repo = Path(__file__).resolve().parents[1]
config = json.loads(subprocess.check_output(
["docker", "compose", "-f", str(repo / "docker-compose.yml"),
- "--profile", "cli", "--profile", "api", "config", "--format", "json"],
+ "--profile", "cli", "config", "--format", "json"],
text=True,
))
with tempfile.TemporaryDirectory(prefix="nanobot-compose-smoke-") as temporary:
@@ -74,16 +77,27 @@ def main() -> None:
)
compose_path.write_text(json.dumps(config))
try:
+ onboard = run("run", "--rm", "--no-deps", "-T", "nanobot-cli", "onboard")
+ assert "Overwrite?" not in onboard
+ assert "Created config" in onboard
+ subprocess.run([
+ "docker", "run", "--rm", "--user", "1000:1000", "--entrypoint", "python",
+ "-v", f"{data}:/home/nanobot/.nanobot", args.image,
+ "-c", "from pathlib import Path; Path('/home/nanobot/.nanobot/config.json').unlink()",
+ ], check=True)
run("up", "-d")
health = endpoint("nanobot-gateway", 18790)
webui = endpoint("nanobot-gateway", 8765)
wait_for(health + "/health")
wait_for(webui + "/")
- assert run("ps", "--services").split() == ["nanobot-gateway"]
+ assert set(run("ps", "--services").split()) == {"nanobot-gateway", "nanobot-api"}
path = data / "config.json"
saved = json.loads(path.read_text())
password = saved["channels"]["websocket"]["tokenIssueSecret"]
api_key = saved["api"]["apiKey"]
+ logs = run("logs", "--no-color")
+ assert logs.count("[entrypoint] initialized") == 1
+ assert password in logs and api_key in logs
if secret:
assert password == api_key == secret
else:
@@ -91,14 +105,28 @@ def main() -> None:
assert request(webui + "/webui/bootstrap", "wrong-password")[0] == 401
status, body = request(webui + "/webui/bootstrap", password)
assert status == 200 and json.loads(body)["token"]
- print(f"PASS {label}: default gateway only, health, WebUI, password authentication")
+ api = endpoint("nanobot-api", 8900)
+ wait_for(api + "/health")
+ for stream in (False, True):
+ status, body = request(api + "/v1/chat/completions", api_key, {
+ "messages": [{"role": "user", "content": "hello"}], "stream": stream,
+ })
+ assert status == 503 and json.loads(body)["error"]["type"] == "configuration_error"
+ assert request(api + "/v1/models")[0] == 401
+ print(f"PASS {label}: both default services, authenticated WebUI, API model-setup errors")
# Configure a provider without making external model requests.
saved["providers"]["custom"] = {
"apiKey": "smoke-provider-key", "apiBase": "http://127.0.0.1:9/v1",
}
saved["agents"]["defaults"].update(provider="custom", model="smoke-model")
- path.write_text(json.dumps(saved))
+ subprocess.run([
+ *compose, "exec", "-T", "--user", "1000:1000", "nanobot-gateway", "python", "-c",
+ "import json, sys; from pathlib import Path; "
+ "from nanobot.config.schema import Config; from nanobot.config.loader import save_config; "
+ "save_config(Config.model_validate(json.load(sys.stdin)), "
+ "Path('/home/nanobot/.nanobot/config.json'))",
+ ], input=json.dumps(saved), text=True, check=True)
previous = path.read_bytes()
for service in config["services"].values():
service["environment"].update(
@@ -113,7 +141,7 @@ def main() -> None:
assert request(webui + "/webui/bootstrap", "changed-env")[0] == 401
print(f"PASS {label}: recreate preserves provider settings and credentials")
- run("--profile", "api", "up", "-d")
+ run("up", "-d", "--force-recreate", "nanobot-api")
api = endpoint("nanobot-api", 8900)
deadline = time.monotonic() + 60
while True:
@@ -127,12 +155,12 @@ def main() -> None:
raise RuntimeError("Configured API did not start")
time.sleep(1)
assert request(api + "/v1/models")[0] == 401
- print(f"PASS {label}: opt-in API starts and requires its persisted key")
+ print(f"PASS {label}: configured API starts and requires its persisted key")
except Exception:
print(run("logs", "--no-color", "--tail", "80"), flush=True)
raise
finally:
- subprocess.run([*compose, "--profile", "api", "down", "--volumes"], check=True)
+ subprocess.run([*compose, "down", "--volumes"], check=True)
# The non-root container owns the bind mount on Linux.
if os.name != "nt":
subprocess.run([
diff --git a/tests/test_docker_config.py b/tests/test_docker_config.py
index ec7309b8e..de87b729a 100644
--- a/tests/test_docker_config.py
+++ b/tests/test_docker_config.py
@@ -70,4 +70,4 @@ def test_failed_write_does_not_leave_an_existing_config(tmp_path):
with pytest.raises(PermissionError, match="read-only mount"):
initialize_config(path)
assert not path.exists()
- assert list(tmp_path.iterdir()) == []
+ assert not list(tmp_path.glob("*.tmp"))
diff --git a/tests/test_openai_api.py b/tests/test_openai_api.py
index 1b5647545..b801d02f6 100644
--- a/tests/test_openai_api.py
+++ b/tests/test_openai_api.py
@@ -20,6 +20,7 @@ from nanobot.api.server import (
handle_chat_completions,
)
from nanobot.providers.base import LLMUsage
+from nanobot.providers.unconfigured_provider import UnconfiguredProvider
try:
from aiohttp.test_utils import TestClient, TestServer
@@ -76,6 +77,29 @@ def test_error_json() -> None:
assert body["error"]["code"] == 400
[email protected]("stream", [False, True])
+async def test_unconfigured_model_returns_503_before_execution(aiohttp_client, mock_agent, stream):
+ mock_agent.provider = UnconfiguredProvider("not-configured")
+ prepare = AsyncMock()
+ app = create_app(mock_agent, api_key=API_KEY, prepare_agent=prepare)
+ client = await aiohttp_client(app)
+
+ assert (await client.get("/health")).status == 200
+ denied = await client.post("/v1/chat/completions", json={"messages": []})
+ assert denied.status == 401
+ response = await client.post(
+ "/v1/chat/completions", headers=AUTH_HEADERS,
+ json={"messages": [{"role": "user", "content": "hello"}], "stream": stream},
+ )
+ assert response.status == 503
+ error = (await response.json())["error"]
+ assert error["type"] == "configuration_error"
+ assert "Model is not configured" in error["message"]
+ mock_agent.process_direct.assert_not_called()
+ prepare.assert_not_called()
+
+
def test_chat_completion_response() -> None:
result = _chat_completion_response("hello world", "test-model")
assert result["object"] == "chat.completion"