fix(api): keep unconfigured services running and preserve Docker onboarding
This commit is contained in:
1 parent
e20737a509
commit
de8fbc3ad2
13 files changed
+133
-63
No files matched your search
@@ -423,7 +423,7 @@ jobs:
|
|||||||
- name: Build image with default channel dependencies
|
- name: Build image with default channel dependencies
|
||||||
run: docker build -t nanobot:test .
|
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
|
run: python scripts/docker_compose_smoke.py --image nanobot:test
|
||||||
|
|
||||||
- name: Verify Docker Compose startup and privilege boundary
|
- name: Verify Docker Compose startup and privilege boundary
|
||||||
@@ -450,7 +450,7 @@ jobs:
|
|||||||
done
|
done
|
||||||
INNER
|
INNER
|
||||||
OUTER
|
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"
|
config --format json > "${RUNNER_TEMP}/bwrap-compose.json"
|
||||||
python - <<'PY'
|
python - <<'PY'
|
||||||
import json
|
import json
|
||||||
|
|||||||
@@ -45,11 +45,6 @@ services:
|
|||||||
nanobot-api:
|
nanobot-api:
|
||||||
container_name: nanobot-api
|
container_name: nanobot-api
|
||||||
<<: *common-config
|
<<: *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:
|
command:
|
||||||
["serve", "--host", "0.0.0.0", "-w", "/home/nanobot/.nanobot/api-workspace"]
|
["serve", "--host", "0.0.0.0", "-w", "/home/nanobot/.nanobot/api-workspace"]
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|||||||
+4
-4
@@ -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
|
git clone https://github.com/HKUDS/nanobot.git
|
||||||
cd nanobot
|
cd nanobot
|
||||||
docker compose up -d
|
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.
|
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 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
|
```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.
|
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:
|
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:
|
||||||
|
|
||||||
|
|||||||
@@ -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.
|
`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
|
## 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.
|
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 |
|
| Missing or incorrect configured key | HTTP 401 |
|
||||||
| Invalid request or wrong model | HTTP 400 |
|
| 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 |
|
| Oversized or invalid upload | HTTP 413 |
|
||||||
| Non-streaming execution timeout | HTTP 504 |
|
| Non-streaming execution timeout | HTTP 504 |
|
||||||
| Unhandled non-streaming execution failure | HTTP 500 |
|
| Unhandled non-streaming execution failure | HTTP 500 |
|
||||||
|
|||||||
+19
-19
@@ -1,24 +1,6 @@
|
|||||||
#!/bin/sh
|
#!/bin/sh
|
||||||
dir="$HOME/.nanobot"
|
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
|
# 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,
|
# 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
|
# 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"
|
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
|
if setpriv --reuid=nanobot --regid=nanobot --init-groups true 2>/dev/null; then
|
||||||
echo "[entrypoint] dropping privileges to nanobot via setpriv"
|
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
|
fi
|
||||||
echo "[entrypoint] error: started as root but setpriv privilege drop failed — refusing to run as root" >&2
|
echo "[entrypoint] error: started as root but setpriv privilege drop failed — refusing to run as root" >&2
|
||||||
exit 1
|
exit 1
|
||||||
@@ -48,4 +30,22 @@ EOF
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
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 "$@"
|
exec nanobot "$@"
|
||||||
@@ -20,6 +20,7 @@ from loguru import logger
|
|||||||
from nanobot.agent.hook import AgentHook, AgentRunHookContext
|
from nanobot.agent.hook import AgentHook, AgentRunHookContext
|
||||||
from nanobot.config.paths import get_media_dir
|
from nanobot.config.paths import get_media_dir
|
||||||
from nanobot.providers.base import LLMUsage
|
from nanobot.providers.base import LLMUsage
|
||||||
|
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
|
||||||
from nanobot.utils.helpers import safe_filename
|
from nanobot.utils.helpers import safe_filename
|
||||||
from nanobot.utils.media_decode import (
|
from nanobot.utils.media_decode import (
|
||||||
MAX_FILE_SIZE,
|
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 ""))
|
content_type = _as_str(cast(object, request.content_type or ""))
|
||||||
|
|
||||||
agent_loop = request.app[_AGENT_LOOP_KEY]
|
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]
|
timeout_s: float = request.app[_REQUEST_TIMEOUT_KEY]
|
||||||
model_name: str = request.app[_MODEL_NAME_KEY]
|
model_name: str = request.app[_MODEL_NAME_KEY]
|
||||||
|
|
||||||
|
|||||||
@@ -393,9 +393,17 @@ def serve(
|
|||||||
tools = ToolRegistry()
|
tools = ToolRegistry()
|
||||||
register_image_generation_tool(runtime_config, tools, workspace=runtime_config.workspace_path)
|
register_image_generation_tool(runtime_config, tools, workspace=runtime_config.workspace_path)
|
||||||
mcp_provider = MCPProvider.from_config(runtime_config, tools)
|
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:
|
try:
|
||||||
agent_loop = AgentLoop.from_config(
|
agent_loop = AgentLoop.from_config(
|
||||||
runtime_config, bus,
|
runtime_config, bus,
|
||||||
|
provider=unconfigured_provider,
|
||||||
session_manager=session_manager,
|
session_manager=session_manager,
|
||||||
hook_factories=[create_file_edit_activity_hook],
|
hook_factories=[create_file_edit_activity_hook],
|
||||||
tool_registry=tools,
|
tool_registry=tools,
|
||||||
|
|||||||
@@ -5,32 +5,36 @@ import secrets
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from filelock import FileLock
|
||||||
|
|
||||||
from nanobot.channels.websocket.runtime import WebSocketConfig
|
from nanobot.channels.websocket.runtime import WebSocketConfig
|
||||||
from nanobot.config.loader import save_config
|
from nanobot.config.loader import save_config
|
||||||
from nanobot.config.schema import Config
|
from nanobot.config.schema import Config
|
||||||
|
|
||||||
|
|
||||||
def initialize_config(path: Path) -> None:
|
def initialize_config(path: Path) -> None:
|
||||||
if path.exists():
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
print(f"[entrypoint] existing {path} found — leaving it in place")
|
with FileLock(path.parent / ".docker-bootstrap.lock"):
|
||||||
print(f"[entrypoint] WebUI password: {path} (channels.websocket.tokenIssueSecret)")
|
if path.exists():
|
||||||
return
|
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)
|
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)
|
api_key = os.environ.get("NANOBOT_API_KEY") or secrets.token_hex(16)
|
||||||
websocket = WebSocketConfig(
|
websocket = WebSocketConfig(
|
||||||
enabled=True, host="0.0.0.0", token_issue_secret=web_token,
|
enabled=True, host="0.0.0.0", token_issue_secret=web_token,
|
||||||
websocket_requires_token=True,
|
websocket_requires_token=True,
|
||||||
)
|
)
|
||||||
config = Config.model_validate({
|
config = Config.model_validate({
|
||||||
"gateway": {"host": "0.0.0.0"},
|
"gateway": {"host": "0.0.0.0"},
|
||||||
"channels": {"websocket": websocket.model_dump(by_alias=True)},
|
"channels": {"websocket": websocket.model_dump(by_alias=True)},
|
||||||
"api": {"host": "0.0.0.0", "api_key": api_key},
|
"api": {"host": "0.0.0.0", "api_key": api_key},
|
||||||
})
|
})
|
||||||
save_config(config, path)
|
save_config(config, path)
|
||||||
print(f"[entrypoint] initialized {path}")
|
print(f"[entrypoint] initialized {path}")
|
||||||
print(f"[entrypoint] WebUI: http://localhost:8765 — password: {web_token}")
|
print(f"[entrypoint] WebUI: http://localhost:8765 — password: {web_token}")
|
||||||
print(f"[entrypoint] OpenAI-compatible API key: {api_key}")
|
print(f"[entrypoint] OpenAI-compatible API key: {api_key}")
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
@@ -222,7 +222,7 @@ def make_provider(
|
|||||||
|
|
||||||
|
|
||||||
def build_unconfigured_provider_snapshot(config: Config, setup_error: str) -> ProviderSnapshot:
|
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
|
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
|
||||||
|
|
||||||
preset = config.resolve_preset()
|
preset = config.resolve_preset()
|
||||||
|
|||||||
@@ -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
|
from __future__ import annotations
|
||||||
|
|
||||||
@@ -8,7 +8,7 @@ from nanobot.providers.base import LLMProvider, LLMResponse
|
|||||||
|
|
||||||
|
|
||||||
class UnconfiguredProvider(LLMProvider):
|
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:
|
def __init__(self, default_model: str) -> None:
|
||||||
super().__init__(provider_name="unconfigured")
|
super().__init__(provider_name="unconfigured")
|
||||||
|
|||||||
@@ -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 argparse
|
||||||
import json
|
import json
|
||||||
@@ -11,10 +11,13 @@ from urllib.error import HTTPError, URLError
|
|||||||
from urllib.request import Request, urlopen
|
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 {}
|
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:
|
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()
|
return response.status, response.read()
|
||||||
except HTTPError as exc:
|
except HTTPError as exc:
|
||||||
return exc.code, exc.read()
|
return exc.code, exc.read()
|
||||||
@@ -27,7 +30,7 @@ def main() -> None:
|
|||||||
repo = Path(__file__).resolve().parents[1]
|
repo = Path(__file__).resolve().parents[1]
|
||||||
config = json.loads(subprocess.check_output(
|
config = json.loads(subprocess.check_output(
|
||||||
["docker", "compose", "-f", str(repo / "docker-compose.yml"),
|
["docker", "compose", "-f", str(repo / "docker-compose.yml"),
|
||||||
"--profile", "cli", "--profile", "api", "config", "--format", "json"],
|
"--profile", "cli", "config", "--format", "json"],
|
||||||
text=True,
|
text=True,
|
||||||
))
|
))
|
||||||
with tempfile.TemporaryDirectory(prefix="nanobot-compose-smoke-") as temporary:
|
with tempfile.TemporaryDirectory(prefix="nanobot-compose-smoke-") as temporary:
|
||||||
@@ -74,16 +77,27 @@ def main() -> None:
|
|||||||
)
|
)
|
||||||
compose_path.write_text(json.dumps(config))
|
compose_path.write_text(json.dumps(config))
|
||||||
try:
|
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")
|
run("up", "-d")
|
||||||
health = endpoint("nanobot-gateway", 18790)
|
health = endpoint("nanobot-gateway", 18790)
|
||||||
webui = endpoint("nanobot-gateway", 8765)
|
webui = endpoint("nanobot-gateway", 8765)
|
||||||
wait_for(health + "/health")
|
wait_for(health + "/health")
|
||||||
wait_for(webui + "/")
|
wait_for(webui + "/")
|
||||||
assert run("ps", "--services").split() == ["nanobot-gateway"]
|
assert set(run("ps", "--services").split()) == {"nanobot-gateway", "nanobot-api"}
|
||||||
path = data / "config.json"
|
path = data / "config.json"
|
||||||
saved = json.loads(path.read_text())
|
saved = json.loads(path.read_text())
|
||||||
password = saved["channels"]["websocket"]["tokenIssueSecret"]
|
password = saved["channels"]["websocket"]["tokenIssueSecret"]
|
||||||
api_key = saved["api"]["apiKey"]
|
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:
|
if secret:
|
||||||
assert password == api_key == secret
|
assert password == api_key == secret
|
||||||
else:
|
else:
|
||||||
@@ -91,14 +105,28 @@ def main() -> None:
|
|||||||
assert request(webui + "/webui/bootstrap", "wrong-password")[0] == 401
|
assert request(webui + "/webui/bootstrap", "wrong-password")[0] == 401
|
||||||
status, body = request(webui + "/webui/bootstrap", password)
|
status, body = request(webui + "/webui/bootstrap", password)
|
||||||
assert status == 200 and json.loads(body)["token"]
|
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.
|
# Configure a provider without making external model requests.
|
||||||
saved["providers"]["custom"] = {
|
saved["providers"]["custom"] = {
|
||||||
"apiKey": "smoke-provider-key", "apiBase": "http://127.0.0.1:9/v1",
|
"apiKey": "smoke-provider-key", "apiBase": "http://127.0.0.1:9/v1",
|
||||||
}
|
}
|
||||||
saved["agents"]["defaults"].update(provider="custom", model="smoke-model")
|
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()
|
previous = path.read_bytes()
|
||||||
for service in config["services"].values():
|
for service in config["services"].values():
|
||||||
service["environment"].update(
|
service["environment"].update(
|
||||||
@@ -113,7 +141,7 @@ def main() -> None:
|
|||||||
assert request(webui + "/webui/bootstrap", "changed-env")[0] == 401
|
assert request(webui + "/webui/bootstrap", "changed-env")[0] == 401
|
||||||
print(f"PASS {label}: recreate preserves provider settings and credentials")
|
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)
|
api = endpoint("nanobot-api", 8900)
|
||||||
deadline = time.monotonic() + 60
|
deadline = time.monotonic() + 60
|
||||||
while True:
|
while True:
|
||||||
@@ -127,12 +155,12 @@ def main() -> None:
|
|||||||
raise RuntimeError("Configured API did not start")
|
raise RuntimeError("Configured API did not start")
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
assert request(api + "/v1/models")[0] == 401
|
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:
|
except Exception:
|
||||||
print(run("logs", "--no-color", "--tail", "80"), flush=True)
|
print(run("logs", "--no-color", "--tail", "80"), flush=True)
|
||||||
raise
|
raise
|
||||||
finally:
|
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.
|
# The non-root container owns the bind mount on Linux.
|
||||||
if os.name != "nt":
|
if os.name != "nt":
|
||||||
subprocess.run([
|
subprocess.run([
|
||||||
|
|||||||
@@ -70,4 +70,4 @@ def test_failed_write_does_not_leave_an_existing_config(tmp_path):
|
|||||||
with pytest.raises(PermissionError, match="read-only mount"):
|
with pytest.raises(PermissionError, match="read-only mount"):
|
||||||
initialize_config(path)
|
initialize_config(path)
|
||||||
assert not path.exists()
|
assert not path.exists()
|
||||||
assert list(tmp_path.iterdir()) == []
|
assert not list(tmp_path.glob("*.tmp"))
|
||||||
@@ -20,6 +20,7 @@ from nanobot.api.server import (
|
|||||||
handle_chat_completions,
|
handle_chat_completions,
|
||||||
)
|
)
|
||||||
from nanobot.providers.base import LLMUsage
|
from nanobot.providers.base import LLMUsage
|
||||||
|
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from aiohttp.test_utils import TestClient, TestServer
|
from aiohttp.test_utils import TestClient, TestServer
|
||||||
@@ -76,6 +77,29 @@ def test_error_json() -> None:
|
|||||||
assert body["error"]["code"] == 400
|
assert body["error"]["code"] == 400
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize("stream", [False, True])
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
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:
|
def test_chat_completion_response() -> None:
|
||||||
result = _chat_completion_response("hello world", "test-model")
|
result = _chat_completion_response("hello world", "test-model")
|
||||||
assert result["object"] == "chat.completion"
|
assert result["object"] == "chat.completion"
|
||||||
|
|||||||
Reference in new issue
Block a user