refactor(api)!: remove the standalone API server (#6614)

This commit is contained in:
Xubin Ren authored and GitHub committed 2026-11-10 10:46:14 +08:00
1 parent 5c72ced2fe
commit 220d5e6970
99 files changed
+240 -4133

No files matched your search

+1 -1
View File
@@ -76,7 +76,7 @@ body:
attributes: attributes:
label: Channel / Platform label: Channel / Platform
description: Which messaging platform are you using? description: Which messaging platform are you using?
placeholder: e.g., WebSocket, Telegram, Feishu (Lark), API Server placeholder: e.g., WebSocket, Telegram, Feishu (Lark)
validations: validations:
required: true required: true
@@ -42,7 +42,6 @@ body:
- Skills / Plugins - Skills / Plugins
- Configuration - Configuration
- CLI - CLI
- API Server
- Documentation - Documentation
- Other - Other
validations: validations:
+2 -2
View File
@@ -495,7 +495,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 API - name: Verify first-boot gateway and WebUI
run: python scripts/docker_compose_smoke.py --image nanobot:test run: python scripts/docker_compose_smoke.py --image nanobot:test
- name: Check out the real previous release for retained-volume acceptance - name: Check out the real previous release for retained-volume acceptance
@@ -553,7 +553,7 @@ jobs:
from pathlib import Path from pathlib import Path
config = json.loads(Path(os.environ["RUNNER_TEMP"], "bwrap-compose.json").read_text()) config = json.loads(Path(os.environ["RUNNER_TEMP"], "bwrap-compose.json").read_text())
for service_name in ("nanobot-gateway", "nanobot-api", "nanobot-cli"): for service_name in ("nanobot-gateway", "nanobot-cli"):
service = config["services"][service_name] service = config["services"][service_name]
assert {"CHOWN", "SETGID", "SETUID", "SYS_ADMIN"} <= set(service["cap_add"]) assert {"CHOWN", "SETGID", "SETUID", "SYS_ADMIN"} <= set(service["cap_add"])
assert "no-new-privileges:true" in service["security_opt"] assert "no-new-privileges:true" in service["security_opt"]
+5 -5
View File
@@ -47,7 +47,7 @@
| Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, Linear, or another channel | [Chat app guide](./docs/guides/chat-app-ai-agent.md) | | Connect Telegram, Discord, WeChat, Slack, Email, Mattermost, Linear, or another channel | [Chat app guide](./docs/guides/chat-app-ai-agent.md) |
| Configure providers, fallback models, Langfuse, MCP, web tools, or security | [Docs](./docs/README.md) and [Configuration](./docs/configuration.md) | | Configure providers, fallback models, Langfuse, MCP, web tools, or security | [Docs](./docs/README.md) and [Configuration](./docs/configuration.md) |
| Develop the browser UI | [Install current source](#-install), then [WebUI development](./webui/README.md) and [Contributing](./CONTRIBUTING.md) | | Develop the browser UI | [Install current source](#-install), then [WebUI development](./webui/README.md) and [Contributing](./CONTRIBUTING.md) |
| Integrate from Python or HTTP | [Python SDK](./docs/python-sdk.md) or [Agent API](./docs/openai-api.md) | | Integrate from Python | [Python SDK](./docs/python-sdk.md) |
| Understand or extend the internals | [Architecture](./docs/architecture.md), [Contributing](./CONTRIBUTING.md), and [Provider extensions](./docs/development.md) | | Understand or extend the internals | [Architecture](./docs/architecture.md), [Contributing](./CONTRIBUTING.md), and [Provider extensions](./docs/development.md) |
| Deploy to the cloud or keep nanobot running as a service | [Deployment](./docs/deployment.md) | | Deploy to the cloud or keep nanobot running as a service | [Deployment](./docs/deployment.md) |
@@ -61,13 +61,13 @@ nanobot can:
- use shell, web search/fetch, MCP integrations, cron, image generation, and multi-agent delegation - use shell, web search/fetch, MCP integrations, cron, image generation, and multi-agent delegation
- keep session history and long-term memory through [Dream](./docs/memory.md#save-and-check-a-preference) - keep session history and long-term memory through [Dream](./docs/memory.md#save-and-check-a-preference)
- run [long-horizon goals](./docs/guides/long-running-ai-agent.md) and [scheduled automations](./docs/automations.md) - run [long-horizon goals](./docs/guides/long-running-ai-agent.md) and [scheduled automations](./docs/automations.md)
- expose a Python SDK and OpenAI-compatible API for integrations - embed the agent with the Python SDK
- deploy as a long-running local or server-side agent gateway - deploy as a long-running local or server-side agent gateway
## 💡 Why nanobot ## 💡 Why nanobot
- **Persistent workflows**: keep saved conversations, long-term memory, and task results for later work. - **Persistent workflows**: keep saved conversations, long-term memory, and task results for later work.
- **Chat-native reach**: WebUI, API, Telegram, Feishu, Slack, Discord, Teams, email, Mattermost, and Linear. - **Chat-native reach**: WebUI, Telegram, Feishu, Slack, Discord, Teams, email, Mattermost, and Linear.
- **Model freedom**: OpenAI-compatible APIs, local LLMs, image generation, search, and fallbacks. - **Model freedom**: OpenAI-compatible APIs, local LLMs, image generation, search, and fallbacks.
- **Small core**: readable internals with MCP, memory, deployment, and automation built in. - **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. - **Own your stack**: inspect, customize, self-host, and extend without a giant platform.
@@ -459,7 +459,7 @@ See the [WebUI guide](./docs/webui.md) for LAN access, background operation, wor
The Python gateway owns agent execution, sessions, tools, memory, and security policy for the WebUI, TUI, and chat apps. The clients share that runtime; the core agent loop builds context, calls the model, executes requested tools, and returns the result. Memory, skills, channels, and MCP integrations extend that loop. The Python gateway owns agent execution, sessions, tools, memory, and security policy for the WebUI, TUI, and chat apps. The clients share that runtime; the core agent loop builds context, calls the model, executes requested tools, and returns the result. Memory, skills, channels, and MCP integrations extend that loop.
The [Python SDK](./docs/python-sdk.md) embeds the agent runtime in your application process. The [OpenAI-compatible API](./docs/openai-api.md) starts a separate HTTP service for `/v1/chat/completions`: each request contains one user message, history is managed by the server, and the model comes from configuration. Responses return to the HTTP client; that service does not deliver tool messages to chat apps. The [Python SDK](./docs/python-sdk.md) embeds the agent runtime in your application process.
See [Architecture](./docs/architecture.md) for source ownership and extension points. See [Architecture](./docs/architecture.md) for source ownership and extension points.
@@ -471,7 +471,7 @@ Browse the [repo docs](./docs/README.md) for current source documentation, or vi
- Choose and configure a model: [Providers and Models](./docs/providers.md) and [Provider Cookbook](./docs/provider-cookbook.md). - Choose and configure a model: [Providers and Models](./docs/providers.md) and [Provider Cookbook](./docs/provider-cookbook.md).
- Connect a chat app: [Chat App AI Agent](./docs/guides/chat-app-ai-agent.md) and [channel reference](./docs/chat-apps.md). - Connect a chat app: [Chat App AI Agent](./docs/guides/chat-app-ai-agent.md) and [channel reference](./docs/chat-apps.md).
- Schedule or deploy work: [Automations](./docs/automations.md) and [Deployment](./docs/deployment.md). - Schedule or deploy work: [Automations](./docs/automations.md) and [Deployment](./docs/deployment.md).
- Integrate from code: [Python SDK](./docs/python-sdk.md) and [OpenAI-Compatible API](./docs/openai-api.md). - Integrate from code: [Python SDK](./docs/python-sdk.md).
- Look up runtime concepts or exact settings: [Concepts](./docs/concepts.md) and [Configuration](./docs/configuration.md). - Look up runtime concepts or exact settings: [Concepts](./docs/concepts.md) and [Configuration](./docs/configuration.md).
- Diagnose a failure: [Troubleshooting](./docs/troubleshooting.md). - Diagnose a failure: [Troubleshooting](./docs/troubleshooting.md).
- Extend the core: [Architecture](./docs/architecture.md) and [contribution workflow](./CONTRIBUTING.md). - Extend the core: [Architecture](./docs/architecture.md) and [contribution workflow](./CONTRIBUTING.md).
-1
View File
@@ -124,7 +124,6 @@ File operations have path traversal protection, but:
**API Calls:** **API Calls:**
- All external API calls use HTTPS by default - All external API calls use HTTPS by default
- Timeouts are configured to prevent hanging requests - Timeouts are configured to prevent hanging requests
- The OpenAI-compatible API server must set `api.api_key` when binding to `0.0.0.0` or `::`; otherwise startup fails to prevent unauthenticated network access
- Consider using a firewall to restrict outbound connections if needed - Consider using a firewall to restrict outbound connections if needed
**WhatsApp:** **WhatsApp:**
-3
View File
@@ -9,8 +9,5 @@ services:
nanobot-gateway: nanobot-gateway:
<<: *bwrap-security <<: *bwrap-security
nanobot-api:
<<: *bwrap-security
nanobot-cli: nanobot-cli:
<<: *bwrap-security <<: *bwrap-security
-18
View File
@@ -7,7 +7,6 @@ x-common-config: &common-config
environment: environment:
NANOBOT_DOCKER_BOOTSTRAP: "1" NANOBOT_DOCKER_BOOTSTRAP: "1"
NANOBOT_WEB_TOKEN: ${NANOBOT_WEB_TOKEN:-} NANOBOT_WEB_TOKEN: ${NANOBOT_WEB_TOKEN:-}
NANOBOT_API_KEY: ${NANOBOT_API_KEY:-}
volumes: volumes:
- ~/.nanobot:/home/nanobot/.nanobot - ~/.nanobot:/home/nanobot/.nanobot
cap_drop: cap_drop:
@@ -40,23 +39,6 @@ services:
cpus: "0.25" cpus: "0.25"
memory: 256M memory: 256M
nanobot-api:
container_name: nanobot-api
<<: *common-config
command:
["serve", "--host", "0.0.0.0", "-w", "/home/nanobot/.nanobot/api-workspace"]
restart: unless-stopped
ports:
- 127.0.0.1:8900:8900
deploy:
resources:
limits:
cpus: "1"
memory: 1G
reservations:
cpus: "0.25"
memory: 256M
nanobot-cli: nanobot-cli:
<<: *common-config <<: *common-config
profiles: profiles:
-2
View File
@@ -49,7 +49,6 @@ Pick the row that matches what you want to accomplish next:
| Run nanobot continuously | [Deployment](./deployment.md) | | Run nanobot continuously | [Deployment](./deployment.md) |
| Run separate bots or workspaces | [Multiple Instances](./multiple-instances.md) | | Run separate bots or workspaces | [Multiple Instances](./multiple-instances.md) |
| Call nanobot from Python | [Python SDK](./python-sdk.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). For shorter, outcome-focused walkthroughs, browse the [task guide index](./guides/README.md).
@@ -76,7 +75,6 @@ Use reference pages to look up an exact option after you know what you are tryin
| Chat channel prerequisites and manual JSON | [Chat Apps](./chat-apps.md) | | Chat channel prerequisites and manual JSON | [Chat Apps](./chat-apps.md) |
| WebSocket authentication and wire protocol | [WebSocket](./websocket.md) | | WebSocket authentication and wire protocol | [WebSocket](./websocket.md) |
| Python SDK classes, events, sessions, and hooks | [Python SDK](./python-sdk.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) | | Runtime self-inspection and tuning | [My Tool](./my-tool.md) |
Configuration examples are usually snippets to merge into `~/.nanobot/config.json`, not complete replacement files. The docs use camelCase because nanobot writes config that way. Keep real API keys, bot tokens, and passwords out of issues and public logs. 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.
+1 -27
View File
@@ -17,7 +17,6 @@ Use this page when you know what you want to run and need the command shape. For
| Chat in the terminal | `nanobot` | Interactive local chat; `nanobot agent` remains an explicit alias | | Chat in the terminal | `nanobot` | Interactive local chat; `nanobot agent` remains an explicit alias |
| Run the gateway directly | `nanobot gateway` | Service/ops command for WebUI, chat apps, cron, and heartbeat | | 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 | | 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` | | 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 | | 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 QR/OAuth-style channels | `nanobot channels login <channel>` | Used by channels such as WhatsApp and WeChat |
@@ -79,17 +78,15 @@ Most day-to-day commands use the default config and workspace. Advanced or multi
```bash ```bash
nanobot agent --config ./bot-a/config.json --workspace ./bot-a/workspace -m "Hello" nanobot agent --config ./bot-a/config.json --workspace ./bot-a/workspace -m "Hello"
nanobot gateway --config ./bot-a/config.json --workspace ./bot-a/workspace nanobot gateway --config ./bot-a/config.json --workspace ./bot-a/workspace
nanobot serve --config ./bot-a/config.json --workspace ./bot-a/workspace
``` ```
Use `--verbose` on long-running processes when you need startup or runtime logs: Use `--verbose` on long-running processes when you need startup or runtime logs:
```bash ```bash
nanobot gateway --verbose nanobot gateway --verbose
nanobot serve --verbose
``` ```
Long-running commands keep working until you stop them. Press `Ctrl+C` in that terminal to stop foreground `nanobot gateway` or `nanobot serve`. If you started the gateway with `--background`, use `nanobot gateway stop`. Long-running commands keep working until you stop them. Press `Ctrl+C` in that terminal to stop a foreground `nanobot gateway`. If you started the gateway with `--background`, use `nanobot gateway stop`.
## Setup ## Setup
@@ -252,28 +249,6 @@ For webhooks or other external systems, run your own small service and have it c
See [Automations](./automations.md) for the broader automation model, WebUI management, and delivery behavior. See [Automations](./automations.md) for the broader automation model, WebUI management, and delivery behavior.
## OpenAI-Compatible API
| Command | Description |
|---|---|
| `nanobot serve` | Start `/v1/chat/completions`, `/v1/models`, and `/health` |
| `nanobot serve --host <host>` | Override API bind host |
| `nanobot serve --port <port>` | Override API port |
| `nanobot serve --timeout <seconds>` | Override per-request timeout |
| `nanobot serve --verbose` | Show runtime logs |
| `nanobot serve --workspace <path>` | Override workspace |
| `nanobot serve --config <path>` | Use a specific config file |
Default API endpoint:
```text
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 ## Status
```bash ```bash
@@ -317,7 +292,6 @@ The `plugins` command name is retained for compatibility, but these entries are
| Feature name | What it enables | | Feature name | What it enables |
|---|---| |---|---|
| `api` | Dependencies required by the OpenAI-compatible `nanobot serve` process |
| `azure` | Azure identity support for Azure-hosted models | | `azure` | Azure identity support for Azure-hosted models |
| `bedrock` | AWS Bedrock model provider support | | `bedrock` | AWS Bedrock model provider support |
| `langfuse` | Langfuse tracing support for OpenAI-compatible providers and the Codex OAuth provider | | `langfuse` | Langfuse tracing support for OpenAI-compatible providers and the Codex OAuth provider |
-1
View File
@@ -76,7 +76,6 @@ That flow is the same whether the message starts in the CLI, WebUI, Telegram, Di
| CLI one-shot | `nanobot agent -m "..."` | First-run checks, scripts, and quick local questions | | CLI one-shot | `nanobot agent -m "..."` | First-run checks, scripts, and quick local questions |
| CLI interactive | `nanobot agent` | Terminal chat with persistent session history | | CLI interactive | `nanobot agent` | Terminal chat with persistent session history |
| Gateway | `nanobot gateway` | Chat apps, WebUI, heartbeat, Dream, and long-running service mode | | Gateway | `nanobot gateway` | Chat apps, WebUI, heartbeat, Dream, and long-running service mode |
| OpenAI-compatible API | `nanobot serve` | Programmatic access through `/v1/chat/completions` |
| WebUI | `nanobot webui` | Prepare the local WebUI, start the gateway, and open the browser workbench | | WebUI | `nanobot webui` | Prepare the local WebUI, start the gateway, and open the browser workbench |
The WebUI launcher is the normal browser entry point. Underneath, the gateway keeps the WebSocket channel and other long-running services alive. The gateway health endpoint is on `gateway.port` (`18790` by default); the browser WebUI is served on `8765` by default, not by the health endpoint. The 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.
+1 -1
View File
@@ -255,7 +255,7 @@ Install the optional package in the same Python environment that runs nanobot:
nanobot plugins enable langfuse nanobot plugins enable langfuse
``` ```
Set Langfuse credentials before starting `nanobot agent`, `nanobot gateway`, or `nanobot serve`: Set Langfuse credentials before starting `nanobot agent` or `nanobot gateway`:
```bash ```bash
export LANGFUSE_SECRET_KEY="sk-lf-..." export LANGFUSE_SECRET_KEY="sk-lf-..."
+5 -11
View File
@@ -13,7 +13,7 @@ Check these before making a deployment persistent. For a new container host, per
| Secrets are in environment variables or protected config files | API keys, bot tokens, OAuth state, and chat credentials should not be world-readable | | Secrets are in environment variables or protected config files | API keys, bot tokens, OAuth state, and chat credentials should not be world-readable |
| The active config directory (including `sessions/`) and workspace are persistent | Sessions follow `--config`; memory, generated artifacts, and the workspace identity marker follow the workspace | | The active config directory (including `sessions/`) and workspace are persistent | Sessions follow `--config`; memory, generated artifacts, and the workspace identity marker follow the workspace |
| Channel access control is intentional | Use `allowFrom`, pairing, WebSocket `token`/`tokenIssueSecret`, or private test channels before exposing the bot | | Channel access control is intentional | Use `allowFrom`, pairing, WebSocket `token`/`tokenIssueSecret`, or private test channels before exposing the bot |
| Ports are planned | Gateway health defaults to local-only `127.0.0.1:18790`; WebUI/WebSocket defaults to `8765`; `nanobot serve` defaults to `8900` | | Ports are planned | Gateway health defaults to local-only `127.0.0.1:18790`; WebUI/WebSocket defaults to `8765` |
| Logs are easy to reach | Use `docker compose logs`, `journalctl`, LaunchAgent log files, or `nanobot gateway --verbose` while diagnosing startup | | 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. Restart the deployed process after editing `config.json`. Long-running processes read config at startup.
@@ -93,21 +93,15 @@ docker compose up -d
docker compose logs 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 a random WebUI password. 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.
Export `NANOBOT_WEB_TOKEN` or `NANOBOT_API_KEY` before the first startup to supply your own credentials. Compose forwards these variables into the containers. Existing configuration is left untouched, including credentials and bind addresses; changing these variables later does not rotate persisted credentials. An explicit `--config` or `-c` selects a user-managed configuration and skips default-instance initialization. If you reuse an existing configuration, check the [Docker bind and authentication settings](#docker) above. Export `NANOBOT_WEB_TOKEN` before the first startup to supply your own WebUI password. Compose forwards this variable into the containers. Existing configuration is left untouched, including credentials and bind addresses; changing this variable later does not rotate persisted credentials. An explicit `--config` or `-c` selects a user-managed configuration and skips default-instance initialization. If you reuse an existing configuration, check the [Docker bind and authentication settings](#docker) above.
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.
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: The default Compose service runs the gateway and WebUI. If you are updating a deployment that used the former API service, follow the [API service removal steps](./updating.md#standalone-api-service-removal).
```bash 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) before starting the gateway. 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.
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.
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:
-1
View File
@@ -38,7 +38,6 @@ Use **Channels** in the WebUI for guided setup. These guides explain the account
| Goal | Guide | | Goal | Guide |
|---|---| |---|---|
| Run from Python | [Python AI agent SDK](./python-ai-agent-sdk.md) | | Run from Python | [Python AI agent SDK](./python-ai-agent-sdk.md) |
| Expose `/v1/chat/completions` | [OpenAI-compatible agent API](./openai-compatible-agent-api.md) |
## Configure and Operate ## Configure and Operate
+1 -1
View File
@@ -26,7 +26,7 @@ Continue in the WebUI from Quick Start. Start a new topic, select a practice fol
- Choose a project folder for file work. Use [separate instances](../multiple-instances.md) when identity or long-term memory must be isolated. - Choose a project folder for file work. Use [separate instances](../multiple-instances.md) when identity or long-term memory must be isolated.
- Use `modelPresets` when you want stable names for fast, deep, local, or fallback models. - 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. - 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. - Use the Python SDK when a Python application should call the agent.
## Security notes ## Security notes
@@ -87,4 +87,3 @@ Verify in the WebUI with the new preset selected. For the manual snippet above,
- [Provider Cookbook: Custom OpenAI-Compatible Provider](../provider-cookbook.md#recipe-custom-openai-compatible-provider) - [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) - [Providers: Custom OpenAI-Compatible Endpoint](../providers.md#custom-openai-compatible-endpoint)
- [OpenAI-Compatible Agent API](./openai-compatible-agent-api.md)
+2 -2
View File
@@ -49,8 +49,8 @@ nanobot gateway --verbose
## Security notes ## Security notes
- Plan ports before exposing services. Gateway health defaults to `18790`, WebUI/WebSocket defaults to `8765`, and `nanobot serve` defaults to `8900`. - Plan ports before exposing services. Gateway health defaults to `18790`, and WebUI/WebSocket defaults to `8765`.
- Protect WebUI and API network listeners with their respective token or key settings. The health endpoint has no authentication; keep its published port on loopback or behind a restricted monitoring interface. - Protect shared WebUI access with a WebSocket token. The health endpoint has no authentication; keep its published port on loopback or behind a restricted monitoring interface.
- Keep chat access control intentional before deploying. - Keep chat access control intentional before deploying.
- Use Docker or Linux sandboxing when shell tools are enabled for unattended work. - Use Docker or Linux sandboxing when shell tools are enabled for unattended work.
-1
View File
@@ -118,4 +118,3 @@ Authentication failures remain skipped messages. Keep the default `postActionIgn
- [Chat Apps reference](../chat-apps.md) - [Chat Apps reference](../chat-apps.md)
- [Secure local AI agent](./secure-local-ai-agent.md) - [Secure local AI agent](./secure-local-ai-agent.md)
- [AI Agent Memory](./ai-agent-memory.md) - [AI Agent Memory](./ai-agent-memory.md)
- [OpenAI-compatible agent API](./openai-compatible-agent-api.md)
@@ -1,67 +0,0 @@
# How to Run an OpenAI-Compatible Agent API with nanobot
nanobot can expose a local OpenAI-compatible endpoint behind `/v1/chat/completions`. This lets existing OpenAI-style clients talk to a tool-using nanobot agent instead of a raw model.
## What you will build
- a working nanobot agent
- a local API server on `127.0.0.1:8900`
- a `/v1/chat/completions` request
- optional session isolation with `session_id`
## When to use this
Use this when an existing client, another language, or a separate process already knows how to call an OpenAI-compatible API. Use the Python SDK when you want in-process access to sessions, memory, runtime helpers, and hooks.
## Start from your current setup
If you already get replies in the WebUI, open **Settings → System**, configure the API service, and start it. Keep that gateway running; do not also start `nanobot serve` on the same port.
If nanobot is not configured yet, complete the [quick start](../quick-start.md) first. For a terminal-managed API using that existing config:
```bash
nanobot plugins enable api
nanobot agent -m "Hello!"
nanobot serve
```
## Make a request
In another terminal, call the chat endpoint. If you configured an API key, set `NANOBOT_API_KEY` to it first:
```bash
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Authorization: Bearer $NANOBOT_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "hi"}],
"session_id": "demo"
}'
```
## Production notes
- Pass `session_id` to separate conversation histories. Callers still share files, memory, and tool permissions; it is not a user authorization boundary.
- Streaming uses Server-Sent Events when `stream` is `true`. A stream without `[DONE]` is incomplete; retries can repeat tool actions. See [sessions, failures, and retries](../openai-api.md#sessions-failures-and-retries).
- The API service returns results to its HTTP client; it does not deliver `message` tool calls to chat apps. Forward results from your application when that is needed.
- `/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 a distinct, stable `session_id` for each conversation. Requests without `session_id` all share the `api:default` session. See [session behavior](../openai-api.md#sessions-failures-and-retries) before changing existing IDs.
## Related nanobot docs
- [Nanobot OpenAI-Compatible API](../openai-api.md)
- [Python SDK](../python-sdk.md)
- [Configuration](../configuration.md)
- [Deployment](../deployment.md)
-3
View File
@@ -12,8 +12,6 @@ This guide shows when to use the Nanobot Python SDK instead of calling a model d
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 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.
## Before you start ## Before you start
Use an installation with a configured model that has already returned a reply. If this is your first setup, follow [Quick Start](../quick-start.md), then return here. Existing WebUI users can continue in the current instance. Use an installation with a configured model that has already returned a reply. If this is your first setup, follow [Quick Start](../quick-start.md), then return here. Existing WebUI users can continue in the current instance.
@@ -58,6 +56,5 @@ asyncio.run(main())
## Related nanobot docs ## Related nanobot docs
- [Nanobot Python SDK](../python-sdk.md) - [Nanobot Python SDK](../python-sdk.md)
- [OpenAI-Compatible API](../openai-api.md)
- [Configuration](../configuration.md) - [Configuration](../configuration.md)
- [Concepts](../concepts.md) - [Concepts](../concepts.md)
+1 -1
View File
@@ -47,7 +47,7 @@ Start with workspace restriction:
- Use environment variables for provider keys, bot tokens, and mailbox passwords. - Use environment variables for provider keys, bot tokens, and mailbox passwords.
- Use [separate instances and workspaces](../multiple-instances.md) for data that must not share memory. Project selection inside one instance does not isolate memory. Use separate OS accounts or containers for mutually untrusted users. - Use [separate instances and workspaces](../multiple-instances.md) for data that must not share memory. Project selection inside one instance does not isolate memory. Use separate OS accounts or containers for mutually untrusted users.
- Prefer [pairing](../configuration.md#pairing) for DM-capable chat apps. Slack and Mattermost DMs default to open access: set `dm.policy` to `"allowlist"` to require approval. Configure group access separately; mention-only controls when the bot responds, not who is trusted. - Prefer [pairing](../configuration.md#pairing) for DM-capable chat apps. Slack and Mattermost DMs default to open access: set `dm.policy` to `"allowlist"` to require approval. Configure group access separately; mention-only controls when the bot responds, not who is trusted.
- Bind WebUI, WebSocket, and API services to localhost unless remote access is intentional. Share [WebUI access](../webui.md#sharing-access) only with trusted administrators; it has no per-user roles or private topic ownership. - Bind WebUI and WebSocket listeners to localhost unless remote access is intentional. Share [WebUI access](../webui.md#sharing-access) only with trusted administrators; it has no per-user roles or private topic ownership.
## Security notes ## Security notes
+5 -7
View File
@@ -1,13 +1,13 @@
# How to Run a Self-Hosted AI Agent with nanobot # 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. This guide sets up nanobot as a self-hosted AI agent runtime on your own machine or server. The result is a gateway process for the WebUI, chat apps, and automations.
## What you will build ## What you will build
- a nanobot config and workspace under your control - a nanobot config and workspace under your control
- a model provider connected through `config.json` - a model provider connected through `config.json`
- a long-running `nanobot gateway` - a long-running `nanobot gateway`
- optional browser, chat app, and API access - optional browser and chat app access
## When to use this ## When to use this
@@ -25,19 +25,18 @@ Self-hosting keeps the agent runtime and its state on your machine. A hosted mod
## Confirm the result ## Confirm the result
Send a message through the interface you intend to use. Check that it replies, then confirm the chosen gateway or service stays running after you close the setup terminal. Browser, chat channels, and automations use the gateway; the optional OpenAI-compatible API has its own [service setup](./openai-compatible-agent-api.md). Send a message through the interface you intend to use. Check that it replies, then confirm the chosen gateway or service stays running after you close the setup terminal. Browser, chat channels, and automations use the gateway.
## Production notes ## Production notes
- Use Docker, systemd, or a macOS LaunchAgent when the process should survive terminal exits. - 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. - 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. - 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. - Use gateway health checks alongside chat app delivery.
## Security notes ## Security notes
- Bind local-only services to `127.0.0.1` unless you intentionally expose them. - 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. - 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. - Enable `tools.restrictToWorkspace`; on Linux, use the bubblewrap sandbox for shell execution.
@@ -45,7 +44,7 @@ Send a message through the interface you intend to use. Check that it replies, t
- Run `nanobot status` with the same `--config` and `--workspace` flags used by the service. - Run `nanobot status` with the same `--config` and `--workspace` flags used by the service.
- Run `nanobot gateway --verbose` while debugging channel startup. - Run `nanobot gateway --verbose` while debugging channel startup.
- Check port conflicts if the WebUI, WebSocket channel, or API endpoint fails to bind. - Check port conflicts if the WebUI or gateway health endpoint fails to bind.
## Related nanobot docs ## Related nanobot docs
@@ -53,4 +52,3 @@ Send a message through the interface you intend to use. Check that it replies, t
- [Multiple Instances](../multiple-instances.md) - [Multiple Instances](../multiple-instances.md)
- [Configuration](../configuration.md) - [Configuration](../configuration.md)
- [Chat Apps](../chat-apps.md) - [Chat Apps](../chat-apps.md)
- [OpenAI-Compatible API](../openai-api.md)
-186
View File
@@ -1,186 +0,0 @@
# Nanobot OpenAI-Compatible API: Run a Local Agent Behind /v1/chat/completions
nanobot can expose a minimal OpenAI-compatible endpoint for local integrations. If your agent already replies in the WebUI, open **Settings → System**, configure and start the API service there. You do not need another installation or a separate `nanobot serve` process.
For a terminal-managed API, use your existing configured installation:
```bash
nanobot plugins enable api
nanobot agent -m "Hello!"
nanobot serve
```
Run the CLI check first. If `nanobot agent -m "Hello!"` fails, fix provider or config setup before debugging the API server. By default, the API binds to `127.0.0.1:8900`. You can change this in `config.json`.
For setup help, see [`quick-start.md`](./quick-start.md), [`providers.md`](./providers.md), and [`troubleshooting.md`](./troubleshooting.md).
## Authentication
For graphical setup, open **Settings → System**, find the API service, enter its host, port, and API key, and start it. Set a key before binding to a network interface. The config-file alternative is collapsed below.
Local-only `127.0.0.1` usage does not require an API key. If you bind the API server to all interfaces with `api.host: "0.0.0.0"` or `"::"`, nanobot requires `api.apiKey`; otherwise startup fails to avoid exposing an unauthenticated agent endpoint on the network.
<details>
<summary>Manual configuration</summary>
```json
{
"api": {
"host": "0.0.0.0",
"port": 8900,
"apiKey": "${NANOBOT_API_KEY}"
}
}
```
</details>
When `api.apiKey` is set, send it as a Bearer token on API routes. The health endpoint remains unauthenticated so local probes and load balancers can still check process health.
```bash
curl http://127.0.0.1:8900/v1/models \
-H "Authorization: Bearer $NANOBOT_API_KEY"
```
## Behavior
- Conversation history: pass `"session_id"` in the request body to select a conversation; omit for a shared default session (`api:default`). The request's chat route matches that session for both JSON replies and SSE. This is not user authentication or a separate workspace.
- Single-message input: each request must contain exactly one `user` message
- Fixed model: omit `model`, or pass the same model shown by `/v1/models`
- Streaming: set `stream=true` to receive Server-Sent Events (`text/event-stream`) with OpenAI-compatible delta chunks, terminated by `data: [DONE]`; omit or set `stream=false` for a single JSON response
- **File uploads**: supports images, PDF, Word (.docx), Excel (.xlsx), PowerPoint (.pptx) via JSON base64 or `multipart/form-data` (max 10MB per file)
- API requests run in the synthetic `api` channel. Responses are returned to the HTTP client; the standalone API service does not deliver `message` tool calls to chat apps.
`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.
Send a stable, non-empty string ID for each conversation. JSON IDs retain surrounding spaces, so `"chat-a"` and `" chat-a "` select different histories. Multipart IDs retain their existing whitespace trimming. Omitted or empty IDs use `api:default`, as does the explicit ID `"default"`. Existing session keys and stored histories are unchanged; no migration is required.
Requests with the same session ID are serialized within one API process. Different sessions can run concurrently and share workspace files; session locking does not make file changes transactional. Send one turn at a time per conversation when ordering matters.
| Failure | Client-visible result |
|---|---|
| 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 |
These API error responses use `{"error":{"message":"...","type":"...","code":400}}`, with the status code for that failure. An HTTP 200 response can still contain a model or tool failure described in assistant text; it does not certify that the requested action succeeded.
Once an SSE response has started, an execution failure or timeout closes it **without** a final `finish_reason: "stop"` chunk or `data: [DONE]`. There is no separate SSE error event. Treat a stream ending without `[DONE]` as incomplete, even if HTTP status was 200 or some text arrived.
Execution timeout defaults to 120 seconds (`api.timeout`, or `nanobot serve --timeout`). It starts after acquiring the session lock, so waiting behind another request can make total request time longer. A client timeout or disconnect is not a reliable cancellation interface. A failed SSE write cancels its running task, but disconnect detection may wait for output; non-streaming work can continue after a client disconnects. Cancellation and timeout do not undo tool actions already performed.
There is no request idempotency key or automatic deduplication. Retrying can repeat a message, file edit, or external action. Check the result before retrying side-effecting requests, and disable automatic client retries when duplicate actions would matter.
## Endpoints
- `GET /health`
- `GET /v1/models`
- `POST /v1/chat/completions`
## curl
The examples below use a local server. If you configured `api.apiKey`, set `NANOBOT_API_KEY` to that same value in the client shell; it is separate from your model provider key. The authorization header is ignored when the local server has no configured key.
```bash
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Authorization: Bearer $NANOBOT_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "hi"}],
"session_id": "my-session"
}'
```
## File Upload (JSON base64)
Send images inline using the OpenAI multimodal content format:
```bash
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Authorization: Bearer $NANOBOT_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": [
{"type": "text", "text": "Describe this image"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBOR..."}}
]}]
}'
```
## File Upload (multipart/form-data)
Upload any supported file type (images, PDF, Word, Excel, PPT) via multipart:
```bash
# Single file
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Authorization: Bearer $NANOBOT_API_KEY" \
-F "message=Summarize this report" \
-F "files=@report.docx"
# Multiple files with session isolation
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Authorization: Bearer $NANOBOT_API_KEY" \
-F "message=Compare these files" \
-F "files=@chart.png" \
-F "files=@data.xlsx" \
-F "session_id=my-session"
```
Supported file types:
- **Images**: PNG, JPEG, GIF, WebP (sent to AI as base64 for vision analysis)
- **Documents**: PDF, Word (.docx), Excel (.xlsx), PowerPoint (.pptx) (text extracted and sent to AI)
- **Text**: TXT, Markdown, CSV, JSON, etc. (read directly)
## Python (`requests`)
```python
import os
import requests
resp = requests.post(
"http://127.0.0.1:8900/v1/chat/completions",
headers={"Authorization": f"Bearer {os.environ.get('NANOBOT_API_KEY', '')}"},
json={
"messages": [{"role": "user", "content": "hi"}],
"session_id": "my-session", # optional: isolate conversation
},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["choices"][0]["message"]["content"])
```
## Python (`openai`)
`local-no-key` is only a client-library placeholder for a local server with no key configured. For an authenticated server, supply its actual API key. Discover the configured model instead of copying a provider-specific model ID.
```python
import os
from openai import OpenAI
client = OpenAI(
base_url="http://127.0.0.1:8900/v1",
api_key=os.environ.get("NANOBOT_API_KEY") or "local-no-key",
max_retries=0, # A retry could repeat a tool action.
)
model_id = client.models.list().data[0].id
resp = client.chat.completions.create(
model=model_id,
messages=[{"role": "user", "content": "hi"}],
extra_body={"session_id": "my-session"}, # optional: isolate conversation
)
print(resp.choices[0].message.content)
```
-14
View File
@@ -197,19 +197,6 @@ For most users, the mental model is:
4. Read `RunResult` or stream events. 4. Read `RunResult` or stream events.
5. Use session/memory/runtime helpers only when you need more control. 5. Use session/memory/runtime helpers only when you need more control.
## SDK Or OpenAI-Compatible API?
nanobot has two programming surfaces:
| Use | Choose | Why |
|-----|--------|-----|
| Python code running in the same process as nanobot | Python SDK | Direct access to `RunResult`, sessions, memory, runtime helpers, hooks, and stream events. |
| Existing OpenAI-compatible clients, another language, or a separate process | [OpenAI-Compatible API](openai-api.md) | HTTP `/v1/chat/completions` compatibility with familiar client libraries. |
The Python SDK is best when you are writing evals, notebooks, benchmark runners, product backends, local scripts, or integrations that should control nanobot directly.
The OpenAI-compatible API is best when you already have an HTTP client, want process isolation, or need to call nanobot from a non-Python service.
## Common Patterns ## Common Patterns
### Use a specific config or workspace ### Use a specific config or workspace
@@ -426,7 +413,6 @@ The SDK page is the programming entry point. The fuller conceptual and configura
| Pasteable provider recipes | [Provider Cookbook](provider-cookbook.md) | | Pasteable provider recipes | [Provider Cookbook](provider-cookbook.md) |
| Complete configuration reference | [Configuration](configuration.md) | | Complete configuration reference | [Configuration](configuration.md) |
| Long-term memory design | [Memory](memory.md) | | Long-term memory design | [Memory](memory.md) |
| HTTP API instead of Python SDK | [OpenAI-Compatible API](openai-api.md) |
| Debugging install, config, provider, or runtime failures | [Troubleshooting](troubleshooting.md) | | Debugging install, config, provider, or runtime failures | [Troubleshooting](troubleshooting.md) |
## API Reference ## API Reference
+1 -1
View File
@@ -141,7 +141,7 @@ This requires a model that supports tools and an enabled `nanobot-document` skil
| Add an App or MCP integration | Open **Apps** or follow [Configure MCP Tools](./guides/configure-mcp-tools.md) | | 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) | | Schedule agent work | Read [Automations](./automations.md) |
| Run continuously or remotely | Read [Deployment](./deployment.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) | | Integrate from code | Use the [Python SDK](./python-sdk.md) |
## Other Install Methods ## Other Install Methods
-1
View File
@@ -194,7 +194,6 @@ Default ports:
|---|---| |---|---|
| Gateway health endpoint | `http://127.0.0.1:18790/health` | | Gateway health endpoint | `http://127.0.0.1:18790/health` |
| WebUI/WebSocket channel | `http://127.0.0.1:8765` | | WebUI/WebSocket channel | `http://127.0.0.1:8765` |
| OpenAI-compatible API (`nanobot serve`) | `http://127.0.0.1:8900` |
Common gateway checks: Common gateway checks:
+10
View File
@@ -52,6 +52,16 @@ For an external update, stop all affected writers, back up configuration and dat
Do not switch package managers to work around an error. Fixed wheel sources, locked requirements and custom installations need their original settings reviewed. If a fresh official installation fails, fix the reported prerequisite or network error and rerun the same installer command. Do not switch package managers to work around an error. Fixed wheel sources, locked requirements and custom installations need their original settings reviewed. If a fresh official installation fails, fix the reported prerequisite or network error and rerun the same installer command.
## Standalone API service removal
`nanobot serve` and its OpenAI-compatible `/v1` endpoints have been removed. This also removes the API server controls in Settings and the `nanobot-api` Compose service. The Gateway, WebUI, Python SDK, and OpenAI-compatible model connections are separate and still supported. The Python SDK embeds nanobot in a Python application; it is not an HTTP-compatible replacement. The `api` install extra is now empty so upgrades can preserve an existing installation's recorded extras. New installations do not need it.
Before updating, stop any existing standalone API process through the launcher that started it. For a process started from Settings, use **Settings → System → Stop** in the old version. For Compose, use `docker compose stop nanobot-api` and `docker compose rm -f nanobot-api` with the old Compose file before switching to the new file. If you already switched, confirm which container belongs to your deployment and stop that old container explicitly; removing a service from the Compose file does not stop an existing container. Keep your bind mounts and volumes.
Back up the configuration and data before updating. The old top-level `api` block is ignored on read and is omitted the next time nanobot saves the configuration. Session data and workspaces are not deleted or moved. If you must roll back, use the previous version and its matching deployment files, and recover the old service settings from your backup if necessary. Do not overwrite current configuration or conversations with a stale backup.
To read old API conversations after updating, open the same configuration and workspace with [the Python SDK](./python-sdk.md#botsessions). Use `await bot.sessions.list()` to find keys such as `api:default` and `api:<session_id>`, then use `await bot.sessions.get(key)` to read their messages. If the old launcher used a separate API workspace, pass that workspace to `Nanobot.from_config(config_path, workspace=workspace)` instead of using the Gateway's workspace.
## Recover an interrupted update ## Recover an interrupted update
Refreshing restores saved progress, **not installation consent**. A staged update may ask you to review and confirm it again. A disconnected page cannot tell whether the worker stopped: do not start another installation while it reconnects. Closing the browser does not stop the managed update or its recovery. Refreshing restores saved progress, **not installation consent**. A staged update may ask you to review and confirm it again. A disconnected page cannot tell whether the worker stopped: do not start another installation while it reconnects. Closing the browser does not stop the managed update or its recovery.
+1 -1
View File
@@ -41,7 +41,7 @@ if [ "$RENDER" = "true" ]; then
echo "[entrypoint] existing $config found — leaving it in place" echo "[entrypoint] existing $config found — leaving it in place"
fi fi
set -- "$@" --config "$config" set -- "$@" --config "$config"
elif [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ] && { [ "$1" = "gateway" ] || [ "$1" = "serve" ]; }; then elif [ "$NANOBOT_DOCKER_BOOTSTRAP" = "1" ] && [ "$1" = "gateway" ]; then
# Explicit config selectors belong to the CLI; bootstrap only the default instance. # Explicit config selectors belong to the CLI; bootstrap only the default instance.
initialize_default=1 initialize_default=1
for argument in "$@"; do for argument in "$@"; do
+1 -5
View File
@@ -2639,7 +2639,6 @@ class AgentLoop:
hooks: list[AgentHook] | None = None, hooks: list[AgentHook] | None = None,
hook_factories: list[AgentTurnHookFactory] | None = None, hook_factories: list[AgentTurnHookFactory] | None = None,
tools: ToolRegistry | None = None, tools: ToolRegistry | None = None,
persist_user_message: bool = True,
runtime: LLMRuntime | None = None, runtime: LLMRuntime | None = None,
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None, on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None,
attributes: Mapping[str, Any] | None = None, attributes: Mapping[str, Any] | None = None,
@@ -2652,12 +2651,9 @@ class AgentLoop:
""" """
if channel == "system": if channel == "system":
raise ValueError("channel 'system' is reserved for internal messages") raise ValueError("channel 'system' is reserved for internal messages")
metadata: dict[str, Any] = {}
if not persist_user_message:
metadata[turn_continuation.SKIP_USER_PERSIST_META] = True
msg = InboundMessage( msg = InboundMessage(
channel=channel, sender_id=sender_id, chat_id=chat_id, channel=channel, sender_id=sender_id, chat_id=chat_id,
content=content, media=media or [], metadata=metadata, content=content, media=media or [],
) )
# Share the dispatch lock so direct calls serialize with bus turns. # Share the dispatch lock so direct calls serialize with bus turns.
lock = self._get_session_lock(session_key) lock = self._get_session_lock(session_key)
View File
Whitespace-only changes.
-58
View File
@@ -1,58 +0,0 @@
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[ApiStartOptions]):
"""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
-526
View File
@@ -1,526 +0,0 @@
"""OpenAI-compatible HTTP API server for nanobot sessions.
Provides /v1/chat/completions and /v1/models endpoints.
Requests without ``session_id`` share one persistent default session; each
``session_id`` owns an isolated session with its own chat route.
"""
from __future__ import annotations
import asyncio
import contextlib
import hmac
import json as _json
import time
import uuid
from typing import TYPE_CHECKING, Any, Awaitable, Callable, cast
from aiohttp import web
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,
)
from nanobot.utils.media_decode import (
FileSizeExceeded as _FileSizeExceeded,
)
from nanobot.utils.media_decode import (
save_base64_data_url as _save_base64_data_url,
)
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
if TYPE_CHECKING:
from nanobot.agent.loop import AgentLoop
__all__ = (
"MAX_FILE_SIZE",
"_FileSizeExceeded",
"_save_base64_data_url",
"create_app",
"handle_chat_completions",
)
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[str, asyncio.Lock]]("session_locks")
_PREPARE_AGENT_KEY = web.AppKey[Callable[[], Awaitable[None]] | None]("prepare_agent")
_REQUEST_ID_KEY = web.RequestKey[str]("request_id")
class _UsageCaptureHook(AgentHook):
"""Capture the aggregate usage owned by one API run."""
def __init__(self) -> None:
super().__init__()
self.usage: LLMUsage | None = None
async def after_run(self, context: AgentRunHookContext) -> None:
self.usage = context.usage
async def _prepare_agent(app: web.Application) -> None:
prepare = app[_PREPARE_AGENT_KEY]
if prepare is not None:
await prepare()
def _error_json(status: int, message: str, err_type: str = "invalid_request_error") -> web.Response:
return web.json_response(
{"error": {"message": message, "type": err_type, "code": status}},
status=status,
)
def _chat_completion_response(
content: str,
model: str,
usage: LLMUsage | None = None,
) -> dict[str, Any]:
prompt = usage.input_tokens if usage else 0
completion = usage.output_tokens if usage else 0
total = usage.total_tokens if usage else 0
return {
"id": f"chatcmpl-{uuid.uuid4().hex[:12]}",
"object": "chat.completion",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": content},
"finish_reason": "stop",
}
],
"usage": {
"prompt_tokens": prompt,
"completion_tokens": completion,
"total_tokens": total,
},
}
def _response_text(value: Any) -> str:
if value is None:
return ""
if hasattr(value, "content"):
return str(getattr(value, "content") or "")
return str(value)
def _as_str(value: object) -> str:
return value if isinstance(value, str) else ""
def _require_json_object(value: object, field: str) -> dict[str, Any]:
if not isinstance(value, dict):
raise TypeError(f"{field} must be an object")
return cast(dict[str, Any], value)
def _require_json_string(value: object, field: str) -> str:
if not isinstance(value, str):
raise TypeError(f"{field} must be a string")
return value
def _sse_chunk(delta: str, model: str, chunk_id: str, finish_reason: str | None = None) -> bytes:
payload = {
"id": chunk_id,
"object": "chat.completion.chunk",
"created": int(time.time()),
"model": model,
"choices": [
{
"index": 0,
"delta": {"content": delta} if delta else {},
"finish_reason": finish_reason,
}
],
}
return f"data: {_json.dumps(payload)}\n\n".encode()
_SSE_DONE = b"data: [DONE]\n\n"
def _parse_json_content(body: dict[str, Any]) -> tuple[str, list[str]]:
messages_value = cast(object, body.get("messages"))
if not isinstance(messages_value, list):
raise ValueError("Only a single user message is supported")
messages = cast(list[object], messages_value)
if len(messages) != 1:
raise ValueError("Only a single user message is supported")
message_value: object = messages[0]
if not isinstance(message_value, dict):
raise ValueError("Only a single user message is supported")
message = cast(dict[str, Any], message_value)
if message.get("role") != "user":
raise ValueError("Only a single user message is supported")
user_content = message.get("content", "")
media_dir = get_media_dir("api")
media_paths: list[str] = []
if isinstance(user_content, list):
text_parts: list[str] = []
for part_value in cast(list[object], user_content):
if not isinstance(part_value, dict):
continue
part = cast(dict[str, Any], part_value)
if part.get("type") == "text":
text_parts.append(
_require_json_string(
cast(object, part.get("text", "")),
"messages[0].content[].text",
)
)
elif part.get("type") == "image_url":
image_url = _require_json_object(
cast(object, part.get("image_url", {})),
"messages[0].content[].image_url",
)
url = _require_json_string(
cast(object, image_url.get("url", "")),
"messages[0].content[].image_url.url",
)
if url.startswith("data:"):
saved = _save_base64_data_url(url, media_dir)
if saved:
media_paths.append(saved)
elif url:
raise ValueError(
"Remote image URLs are not supported. "
"Use base64 data URLs or upload files via multipart/form-data."
)
text = " ".join(text_parts)
elif isinstance(user_content, str):
text = user_content
else:
raise ValueError("Invalid content format")
return text, media_paths
async def _parse_multipart(request: web.Request) -> tuple[str, list[str], str | None, str | None]:
media_dir = get_media_dir("api")
reader = await request.multipart()
text = ""
session_id = None
model = None
media_paths: list[str] = []
while True:
part: Any = await reader.next()
if part is None:
break
if part.name == "message":
text = (await part.read()).decode("utf-8")
elif part.name == "session_id":
session_id = (await part.read()).decode("utf-8").strip()
elif part.name == "model":
model = (await part.read()).decode("utf-8").strip()
elif part.name == "files":
raw = await part.read()
if len(raw) > MAX_FILE_SIZE:
raise _FileSizeExceeded(
f"File '{part.filename}' exceeds {MAX_FILE_SIZE // (1024 * 1024)}MB limit"
)
base = safe_filename(part.filename or "upload.bin")
filename = f"{uuid.uuid4().hex[:12]}_{base}"
dest = media_dir / filename
dest.write_bytes(raw)
media_paths.append(str(dest))
if not text:
text = "请分析上传的文件"
return text, media_paths, session_id, model
async def handle_chat_completions(request: web.Request) -> web.Response | web.StreamResponse:
"""POST /v1/chat/completions — supports JSON and multipart/form-data."""
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]
stream = False
try:
if content_type.startswith("multipart/"):
text, media_paths, session_id, requested_model = await _parse_multipart(request)
else:
try:
body = await request.json()
except Exception:
return _error_json(400, "Invalid JSON body")
if not isinstance(body, dict):
return _error_json(400, "Invalid JSON body")
body = cast(dict[str, Any], body)
stream_value = body.get("stream", False)
if stream_value is not None and not isinstance(stream_value, bool):
return _error_json(400, "stream must be a boolean")
stream = stream_value is True
requested_model = body.get("model")
text, media_paths = _parse_json_content(body)
session_id = body.get("session_id")
except (TypeError, ValueError) as e:
return _error_json(400, str(e))
except _FileSizeExceeded as e:
return _error_json(413, str(e), err_type="invalid_request_error")
except Exception:
logger.exception("Error parsing upload")
return _error_json(413, "File too large or invalid upload")
if requested_model and requested_model != model_name:
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
# Keep the existing history identity; derive its route without normalizing the ID.
chat_id = session_key.removeprefix("api:")
session_locks: dict[str, asyncio.Lock] = request.app[_SESSION_LOCKS_KEY]
session_lock = session_locks.setdefault(session_key, asyncio.Lock())
logger.info(
"API request session_key={} media={} text={} stream={}",
session_key, len(media_paths), text[:80], stream,
)
if stream:
resp = web.StreamResponse()
resp.content_type = "text/event-stream"
resp.headers["Cache-Control"] = "no-cache"
resp.headers["Connection"] = "keep-alive"
await resp.prepare(request)
chunk_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
queue: asyncio.Queue[str | None] = asyncio.Queue()
stream_failed = False
emitted_content = False
async def _on_stream(token: str) -> None:
nonlocal emitted_content
if token:
emitted_content = True
await queue.put(token)
async def _on_stream_end(*_a: Any, **_kw: Any) -> None:
# Agent stream-end callbacks mark generation segment boundaries.
# Tool-backed requests may continue after a segment ends, so the
# HTTP SSE stream is closed only when process_direct returns.
return None
async def _run() -> None:
nonlocal stream_failed
try:
async with session_lock:
async with asyncio.timeout(timeout_s):
await _prepare_agent(request.app)
response = await agent_loop.process_direct(
content=text,
media=media_paths if media_paths else None,
session_key=session_key,
channel="api",
chat_id=chat_id,
on_stream=_on_stream,
on_stream_end=_on_stream_end,
)
if not emitted_content:
response_text = _response_text(response)
if response_text.strip():
await queue.put(response_text)
except Exception:
stream_failed = True
logger.exception("Streaming error for session {}", session_key)
finally:
await queue.put(None)
task = asyncio.create_task(_run())
try:
while True:
token = await queue.get()
if token is None:
break
await resp.write(_sse_chunk(token, model_name, chunk_id))
finally:
if not task.done():
task.cancel()
with contextlib.suppress(asyncio.CancelledError):
await task
if not stream_failed:
await resp.write(_sse_chunk("", model_name, chunk_id, finish_reason="stop"))
await resp.write(_SSE_DONE)
return resp
usage_capture = _UsageCaptureHook()
try:
async with session_lock:
try:
async with asyncio.timeout(timeout_s):
await _prepare_agent(request.app)
response = await agent_loop.process_direct(
content=text,
media=media_paths if media_paths else None,
session_key=session_key,
channel="api",
chat_id=chat_id,
hooks=[usage_capture],
)
response_text = _response_text(response)
if not response_text or not response_text.strip():
logger.warning("Empty response for session {}, using fallback", session_key)
response_text = EMPTY_FINAL_RESPONSE_MESSAGE
except asyncio.TimeoutError:
return _error_json(504, f"Request timed out after {timeout_s}s")
except Exception:
logger.exception("Error processing request for session {}", session_key)
return _error_json(500, "Internal server error", err_type="server_error")
except Exception:
logger.exception("Unexpected API lock error for session {}", session_key)
return _error_json(500, "Internal server error", err_type="server_error")
return web.json_response(
_chat_completion_response(response_text, model_name, usage_capture.usage)
)
async def handle_models(request: web.Request) -> web.Response:
"""GET /v1/models"""
model_name = request.app[_MODEL_NAME_KEY]
return web.json_response(
{
"object": "list",
"data": [
{
"id": model_name,
"object": "model",
"created": 0,
"owned_by": "nanobot",
}
],
}
)
async def handle_health(request: web.Request) -> web.Response:
"""GET /health"""
return web.json_response({"status": "ok"})
def create_app(
agent_loop: "AgentLoop",
model_name: str = "nanobot",
request_timeout: float = 120.0,
api_key: str = "",
prepare_agent: Callable[[], Awaitable[None]] | None = None,
) -> web.Application:
"""Create the aiohttp application.
Args:
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 on API routes.
prepare_agent: Optional application-owned readiness callback run before each turn.
"""
app = web.Application(client_max_size=20 * 1024 * 1024)
app[_AGENT_LOOP_KEY] = agent_loop
app[_MODEL_NAME_KEY] = model_name
app[_REQUEST_TIMEOUT_KEY] = request_timeout
app[_SESSION_LOCKS_KEY] = {}
app[_PREPARE_AGENT_KEY] = prepare_agent
@web.middleware
async def request_logging_middleware(
request: web.Request,
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
request_id = uuid.uuid4().hex[:16]
request[_REQUEST_ID_KEY] = request_id
started_at = time.perf_counter()
with logger.contextualize(request_id=request_id):
try:
response = await handler(request)
except Exception:
duration_ms = round((time.perf_counter() - started_at) * 1000, 1)
logger.opt(exception=True).bind(
event="http_request",
outcome="error",
duration_ms=duration_ms,
method=request.method,
path=request.path,
).error(
"HTTP request failed method={} path={} duration_ms={}",
request.method,
request.path,
duration_ms,
)
raise
duration_ms = round((time.perf_counter() - started_at) * 1000, 1)
request_log = logger.bind(
event="http_request",
outcome="success" if response.status < 400 else "error",
duration_ms=duration_ms,
method=request.method,
path=request.path,
status_code=response.status,
)
log_method = request_log.debug if request.path == "/health" else request_log.info
log_method(
"HTTP request completed method={} path={} status={} duration_ms={}",
request.method,
request.path,
response.status,
duration_ms,
)
return response
async def add_request_id_header(
request: web.Request,
response: web.StreamResponse,
) -> None:
request_id = request.get(_REQUEST_ID_KEY)
if request_id:
response.headers["X-Request-ID"] = request_id
@web.middleware
async def auth_middleware(
request: web.Request,
handler: Callable[[web.Request], Awaitable[web.StreamResponse]],
) -> web.StreamResponse:
# 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>")
if not hmac.compare_digest(auth[len("Bearer "):], api_key):
return _error_json(401, "Invalid API key")
return await handler(request)
app.middlewares.extend((request_logging_middleware, auth_middleware))
app.on_response_prepare.append(add_request_id_header)
app.router.add_post("/v1/chat/completions", handle_chat_completions)
app.router.add_get("/v1/models", handle_models)
app.router.add_get("/health", handle_health)
return app
+2 -2
View File
@@ -24,7 +24,7 @@ from nanobot.config.loader import resolve_env_refs
from nanobot.config.paths import get_media_dir from nanobot.config.paths import get_media_dir
from nanobot.config.schema import Config, ProviderConfig from nanobot.config.schema import Config, ProviderConfig
from nanobot.providers.registry import find_by_name from nanobot.providers.registry import find_by_name
from nanobot.utils.media_decode import FileSizeExceeded, save_base64_data_url from nanobot.utils.media_decode import FileSizeExceededError, save_base64_data_url
TranscriptionProviderName = str TranscriptionProviderName = str
@@ -179,7 +179,7 @@ async def transcribe_audio_data_url(
get_media_dir("webui-transcription"), get_media_dir("webui-transcription"),
max_bytes=max_bytes, max_bytes=max_bytes,
) )
except FileSizeExceeded as exc: except FileSizeExceededError as exc:
raise TranscriptionIngressError("size") from exc raise TranscriptionIngressError("size") from exc
except Exception as exc: except Exception as exc:
logger.warning("transcription audio decode failed: {}", exc) logger.warning("transcription audio decode failed: {}", exc)
+17 -107
View File
@@ -18,7 +18,6 @@ if sys.platform == "win32":
# Keep console encoding setup before importing CLI UI/logging libraries. # Keep console encoding setup before importing CLI UI/logging libraries.
import typer # noqa: E402 import typer # noqa: E402
from loguru import logger # noqa: E402
from typer.core import TyperGroup # noqa: E402 from typer.core import TyperGroup # noqa: E402
from nanobot.utils.log_config import configure_console_logging # noqa: E402 from nanobot.utils.log_config import configure_console_logging # noqa: E402
@@ -33,10 +32,6 @@ from rich.text import Text # noqa: E402
from nanobot import __logo__, __version__ # noqa: E402 from nanobot import __logo__, __version__ # noqa: E402
from nanobot import optional_features as feature_support # noqa: E402 from nanobot import optional_features as feature_support # noqa: E402
from nanobot.agent.hooks import create_file_edit_activity_hook # noqa: E402
from nanobot.agent.loop import AgentLoop # noqa: E402
from nanobot.agent.tools.mcp import MCPProvider # noqa: E402
from nanobot.agent.tools.registry import ToolRegistry # noqa: E402
from nanobot.cli import terminal as cli_terminal # noqa: E402 from nanobot.cli import terminal as cli_terminal # noqa: E402
from nanobot.cli.agent import agent # noqa: E402 from nanobot.cli.agent import agent # noqa: E402
from nanobot.cli.gateway import create_gateway_app # noqa: E402 from nanobot.cli.gateway import create_gateway_app # noqa: E402
@@ -60,12 +55,10 @@ from nanobot.cli.webui_support import ( # noqa: E402
) )
from nanobot.config.paths import get_workspace_path # noqa: E402 from nanobot.config.paths import get_workspace_path # noqa: E402
from nanobot.config.schema import Config # noqa: E402 from nanobot.config.schema import Config # noqa: E402
from nanobot.security.network import is_loopback_host # noqa: E402
from nanobot.utils.helpers import sanitize_surrogates as _sanitize_surrogates # noqa: E402,F401 from nanobot.utils.helpers import sanitize_surrogates as _sanitize_surrogates # noqa: E402,F401
from nanobot.utils.helpers import ( # noqa: E402 from nanobot.utils.helpers import ( # noqa: E402
sync_workspace_templates, sync_workspace_templates,
) )
from nanobot.webui.context_source_hook import create_context_source_hook # noqa: E402
# Backward-compatible import for callers that used the former module location. # Backward-compatible import for callers that used the former module location.
SafeFileHistory = cli_terminal.SafeFileHistory SafeFileHistory = cli_terminal.SafeFileHistory
@@ -141,6 +134,23 @@ def main(
_run_agent([], prog_name="nanobot") _run_agent([], prog_name="nanobot")
@app.command(
"serve",
hidden=True,
add_help_option=False,
context_settings={"allow_extra_args": True, "ignore_unknown_options": True},
)
def _retired_serve() -> None:
"""Explain the removal without processing flags from old launch scripts."""
typer.echo(
"'nanobot serve' has been removed. No API server was started.\n"
"To chat in your browser, run 'nanobot webui'.\n"
"The old /v1 endpoints have no drop-in replacement.",
err=True,
)
raise typer.Exit(2)
@app.command() @app.command()
def onboard( def onboard(
workspace: str | None = typer.Option(None, "--workspace", "-w", help="Workspace directory"), workspace: str | None = typer.Option(None, "--workspace", "-w", help="Workspace directory"),
@@ -334,106 +344,6 @@ def trigger(
console.print(f"[green]Queued[/green] {delivery.trigger_id} ({delivery.id})") console.print(f"[green]Queued[/green] {delivery.trigger_id} ({delivery.id})")
@app.command()
def serve(
port: int | None = typer.Option(None, "--port", "-p", help="API server port"),
host: str | None = typer.Option(None, "--host", "-H", help="Bind address"),
timeout: float | None = typer.Option(None, "--timeout", "-t", help="Per-request timeout (seconds)"),
verbose: bool = typer.Option(False, "--verbose", "-v", help="Show nanobot runtime logs"),
workspace: str | None = typer.Option(None, "--workspace", "-w", help="Workspace directory"),
config: str | None = typer.Option(None, "--config", "-c", help="Path to config file"),
):
"""Start the OpenAI-compatible API server (/v1/chat/completions)."""
runtime_config = _load_runtime_config(config, workspace)
try:
from aiohttp import web # noqa: F401
except ImportError:
console.print("[red]aiohttp is required. Install with: nanobot plugins enable api[/red]")
raise typer.Exit(1)
from nanobot.agent.tools.image_generation import register_image_generation_tool
from nanobot.api.server import create_app
from nanobot.bus.queue import MessageBus
from nanobot.session.manager import SessionManager
_set_nanobot_logs(verbose)
api_cfg = runtime_config.api
host = host if host is not None else api_cfg.host
port = port if port is not None else api_cfg.port
timeout = timeout if timeout is not None else api_cfg.timeout
api_key = api_cfg.api_key.strip() if api_cfg.api_key else ""
if not is_loopback_host(host) and not api_key:
console.print(
f"[red]Error: host {host} is available beyond this device but api_key is not set. "
"Set api.api_key in config to prevent unauthenticated access.[/red]"
)
raise typer.Exit(1)
sync_workspace_templates(runtime_config.workspace_path)
bus = MessageBus()
session_manager = SessionManager(runtime_config.workspace_path)
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
)
from nanobot.goal.assembly import install_goal
try:
agent_loop = AgentLoop.from_config(
runtime_config, bus,
provider=unconfigured_provider,
session_manager=session_manager,
hook_factories=[create_file_edit_activity_hook, create_context_source_hook],
tool_registry=tools,
builtin_assembly=install_goal,
)
except ValueError as exc:
console.print(f"[red]Error: {exc}[/red]")
raise typer.Exit(1) from exc
model_name, preset_tag = _model_display(runtime_config)
console.print(f"{__logo__} Starting OpenAI-compatible API server")
console.print(f" [cyan]Endpoint[/cyan] : http://{host}:{port}/v1/chat/completions")
console.print(f" [cyan]Model[/cyan] : {model_name}{preset_tag}")
console.print(" [cyan]Session[/cyan] : api:default")
console.print(f" [cyan]Timeout[/cyan] : {timeout}s")
if not is_loopback_host(host):
console.print(
"[yellow]API is available beyond this device "
"(authentication required).[/yellow]"
)
console.print()
api_app = create_app(
agent_loop, model_name=model_name, request_timeout=timeout,
api_key=api_key,
prepare_agent=mcp_provider.connect,
)
async def on_startup(_app: Any) -> None:
await mcp_provider.connect()
async def on_cleanup(_app: Any) -> None:
try:
await agent_loop.aclose()
finally:
await mcp_provider.aclose()
api_app.on_startup.append(on_startup)
api_app.on_cleanup.append(on_cleanup)
def _log_aiohttp(message: object) -> None:
logger.info("{}", message)
web.run_app(api_app, host=host, port=port, print=_log_aiohttp)
app.command(name="webui")(webui) app.command(name="webui")(webui)
-3
View File
@@ -19,7 +19,6 @@ def initialize_config(path: Path) -> None:
return 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)
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,
@@ -27,12 +26,10 @@ def initialize_config(path: Path) -> None:
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},
}) })
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}")
if __name__ == "__main__": if __name__ == "__main__":
-6
View File
@@ -1281,7 +1281,6 @@ def _configure_channels(config: Config) -> None:
_SETTINGS_SECTIONS: dict[str, tuple[str, str, set[str] | None]] = { _SETTINGS_SECTIONS: dict[str, tuple[str, str, set[str] | None]] = {
"Agent Settings": ("Agent Defaults", "Configure default model, temperature, and behavior", None), "Agent Settings": ("Agent Defaults", "Configure default model, temperature, and behavior", None),
"Channel Common": ("Channel Common", "Configure cross-channel behavior: progress, tool hints, retries", None), "Channel Common": ("Channel Common", "Configure cross-channel behavior: progress, tool hints, retries", None),
"API Server": ("API Server", "Configure OpenAI-compatible API endpoint", None),
"Gateway": ("Gateway Settings", "Configure server host, port", None), "Gateway": ("Gateway Settings", "Configure server host, port", None),
"Tools": ("Tools Settings", "Configure web search, shell exec, and other tools", {"mcp_servers"}), "Tools": ("Tools Settings", "Configure web search, shell exec, and other tools", {"mcp_servers"}),
} }
@@ -1289,7 +1288,6 @@ _SETTINGS_SECTIONS: dict[str, tuple[str, str, set[str] | None]] = {
_SETTINGS_GETTER: dict[str, Callable[[Config], BaseModel]] = { _SETTINGS_GETTER: dict[str, Callable[[Config], BaseModel]] = {
"Agent Settings": lambda c: c.agents.defaults, "Agent Settings": lambda c: c.agents.defaults,
"Channel Common": lambda c: c.channels, "Channel Common": lambda c: c.channels,
"API Server": lambda c: c.api,
"Gateway": lambda c: c.gateway, "Gateway": lambda c: c.gateway,
"Tools": lambda c: c.tools, "Tools": lambda c: c.tools,
} }
@@ -1297,7 +1295,6 @@ _SETTINGS_GETTER: dict[str, Callable[[Config], BaseModel]] = {
_SETTINGS_SETTER: dict[str, Callable[[Config, BaseModel], None]] = { _SETTINGS_SETTER: dict[str, Callable[[Config, BaseModel], None]] = {
"Agent Settings": lambda c, v: setattr(c.agents, "defaults", v), "Agent Settings": lambda c, v: setattr(c.agents, "defaults", v),
"Channel Common": lambda c, v: setattr(c, "channels", v), "Channel Common": lambda c, v: setattr(c, "channels", v),
"API Server": lambda c, v: setattr(c, "api", v),
"Gateway": lambda c, v: setattr(c, "gateway", v), "Gateway": lambda c, v: setattr(c, "gateway", v),
"Tools": lambda c, v: setattr(c, "tools", v), "Tools": lambda c, v: setattr(c, "tools", v),
} }
@@ -1380,7 +1377,6 @@ def _show_summary(config: Config) -> None:
for title, model in [ for title, model in [
("Agent Settings", config.agents.defaults), ("Agent Settings", config.agents.defaults),
("Channel Common", config.channels), ("Channel Common", config.channels),
("API Server", config.api),
("Gateway", config.gateway), ("Gateway", config.gateway),
("Tools", config.tools), ("Tools", config.tools),
]: ]:
@@ -1813,7 +1809,6 @@ def _configure_advanced_settings(config: Config) -> None:
"[C] Chat Channel", "[C] Chat Channel",
"[H] Channel Common", "[H] Channel Common",
"[A] Agent Settings", "[A] Agent Settings",
"[I] API Server",
"[G] Gateway", "[G] Gateway",
"[T] Tools", "[T] Tools",
"[V] View Configuration Summary", "[V] View Configuration Summary",
@@ -1843,7 +1838,6 @@ def _configure_advanced_settings(config: Config) -> None:
"[C] Chat Channel": lambda: _configure_channels(config), "[C] Chat Channel": lambda: _configure_channels(config),
"[H] Channel Common": lambda: _configure_general_settings(config, "Channel Common"), "[H] Channel Common": lambda: _configure_general_settings(config, "Channel Common"),
"[A] Agent Settings": lambda: _configure_general_settings(config, "Agent Settings"), "[A] Agent Settings": lambda: _configure_general_settings(config, "Agent Settings"),
"[I] API Server": lambda: _configure_general_settings(config, "API Server"),
"[G] Gateway": lambda: _configure_general_settings(config, "Gateway"), "[G] Gateway": lambda: _configure_general_settings(config, "Gateway"),
"[T] Tools": lambda: _configure_general_settings(config, "Tools"), "[T] Tools": lambda: _configure_general_settings(config, "Tools"),
"[V] View Configuration Summary": lambda: _show_summary(config), "[V] View Configuration Summary": lambda: _show_summary(config),
+5 -22
View File
@@ -380,26 +380,6 @@ class HeartbeatConfig(Base):
interval_s: int = 30 * 60 interval_s: int = 30 * 60
class ApiConfig(Base):
"""OpenAI-compatible API server configuration."""
host: str = "127.0.0.1" # Safer default: local-only bind.
port: int = 8900
timeout: float = 120.0 # Per-request timeout in seconds.
api_key: str = Field(default="", repr=False)
@model_validator(mode="after")
def wildcard_host_requires_auth(self) -> "ApiConfig":
if self.host not in ("0.0.0.0", "::"):
return self
if self.api_key.strip():
return self
raise ValueError(
"host is 0.0.0.0 (all interfaces) but api_key is not set "
"- set api.api_key to prevent unauthenticated access"
)
class GatewayConfig(Base): class GatewayConfig(Base):
"""Gateway/server configuration.""" """Gateway/server configuration."""
@@ -506,7 +486,6 @@ class Config(BaseSettings):
transcription: TranscriptionConfig = Field(default_factory=TranscriptionConfig) transcription: TranscriptionConfig = Field(default_factory=TranscriptionConfig)
providers: ProvidersConfig = Field(default_factory=ProvidersConfig) providers: ProvidersConfig = Field(default_factory=ProvidersConfig)
network: NetworkConfig = Field(default_factory=NetworkConfig) network: NetworkConfig = Field(default_factory=NetworkConfig)
api: ApiConfig = Field(default_factory=ApiConfig)
gateway: GatewayConfig = Field(default_factory=GatewayConfig) gateway: GatewayConfig = Field(default_factory=GatewayConfig)
tools: ToolsConfig = Field(default_factory=ToolsConfig) tools: ToolsConfig = Field(default_factory=ToolsConfig)
model_presets: dict[str, ModelPresetConfig] = Field( model_presets: dict[str, ModelPresetConfig] = Field(
@@ -517,7 +496,11 @@ class Config(BaseSettings):
@model_validator(mode="before") @model_validator(mode="before")
@classmethod @classmethod
def _migrate_proxy_config(cls, value: Any) -> Any: def _migrate_legacy_config(cls, value: Any) -> Any:
if isinstance(value, dict) and "api" in value:
# Old installations saved this block even if they never ran serve.
legacy = cast(dict[object, object], value)
value = {key: item for key, item in legacy.items() if key != "api"}
return migrate_legacy_proxy_config(value) return migrate_legacy_proxy_config(value)
@classmethod @classmethod
+1 -1
View File
@@ -50,7 +50,7 @@ class InstallResult:
_INSTALL_TIMEOUT_SECONDS = 300 _INSTALL_TIMEOUT_SECONDS = 300
_LOG_OUTPUT_LIMIT = 4000 _LOG_OUTPUT_LIMIT = 4000
_HIDDEN_OPTIONAL_FEATURES = {"documents", "pdf"} _HIDDEN_OPTIONAL_FEATURES = {"api", "documents", "pdf"}
_BUNDLED_FEATURE_ALIASES = {"documents", "pdf"} _BUNDLED_FEATURE_ALIASES = {"documents", "pdf"}
-19
View File
@@ -103,11 +103,6 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
# it; poll() both reaps it and reports the real lifecycle state. # it; poll() both reaps it and reports the real lifecycle state.
self._owned_process: Any | None = None self._owned_process: Any | None = None
def start_background(self, options: _StartOptionsT) -> ProcessResult:
"""Start the configured command as a detached process."""
with self._lifecycle_lock():
return self._start_background(options)
def _start_background(self, options: _StartOptionsT) -> ProcessResult: def _start_background(self, options: _StartOptionsT) -> ProcessResult:
current = self.status() current = self.status()
if current.running: if current.running:
@@ -151,11 +146,6 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
self._write_state(state) self._write_state(state)
return ProcessResult(True, self._message("started_background"), self.status()) return ProcessResult(True, self._message("started_background"), self.status())
def stop(self, *, timeout_s: int = 20) -> ProcessResult:
"""Stop the process recorded in this runtime's state file."""
with self._lifecycle_lock():
return self._stop(timeout_s=timeout_s)
def _stop(self, *, timeout_s: int) -> ProcessResult: def _stop(self, *, timeout_s: int) -> ProcessResult:
status = self.status() status = self.status()
if not status.pid: if not status.pid:
@@ -189,15 +179,6 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
self._clear_state() self._clear_state()
return ProcessResult(True, self._message("stopped"), self.status(reason="stopped")) return ProcessResult(True, self._message("stopped"), self.status(reason="stopped"))
def restart(self, options: _StartOptionsT, *, timeout_s: int = 20) -> ProcessResult:
"""Restart the managed process."""
with self._lifecycle_lock():
stop_result = self._stop(timeout_s=timeout_s)
recoverable = {self._message("not_running"), self._message("state_stale")}
if not stop_result.ok and stop_result.message not in recoverable:
return stop_result
return self._start_background(options)
def status(self, *, reason: str | None = None) -> ProcessStatus: def status(self, *, reason: str | None = None) -> ProcessStatus:
"""Return live status, clearing stale state when needed.""" """Return live status, clearing stale state when needed."""
state = self._read_state() state = self._read_state()
+3 -7
View File
@@ -1,4 +1,4 @@
"""Data-URL persistence for API uploads and audio transcription. """Data-URL persistence for audio transcription.
Binary WebUI uploads share the media filename layout through ``media_destination``. Binary WebUI uploads share the media filename layout through ``media_destination``.
""" """
@@ -13,7 +13,6 @@ from pathlib import Path
from nanobot.utils.helpers import safe_filename from nanobot.utils.helpers import safe_filename
DEFAULT_MAX_BYTES = 10 * 1024 * 1024 DEFAULT_MAX_BYTES = 10 * 1024 * 1024
MAX_FILE_SIZE = DEFAULT_MAX_BYTES
_MIME_EXTENSION_OVERRIDES = { _MIME_EXTENSION_OVERRIDES = {
# Python's ``mimetypes`` maps browser-recorded audio/webm to ``.weba`` and # Python's ``mimetypes`` maps browser-recorded audio/webm to ``.weba`` and
@@ -51,9 +50,6 @@ class FileSizeExceededError(Exception):
"""Raised when a decoded payload exceeds the caller's size limit.""" """Raised when a decoded payload exceeds the caller's size limit."""
FileSizeExceeded = FileSizeExceededError
def save_base64_data_url( def save_base64_data_url(
data_url: str, data_url: str,
media_dir: Path, media_dir: Path,
@@ -64,7 +60,7 @@ def save_base64_data_url(
"""Decode a ``data:<mime>;base64,<payload>`` URL and persist it. """Decode a ``data:<mime>;base64,<payload>`` URL and persist it.
Returns the absolute path on success, ``None`` when the URL shape or the Returns the absolute path on success, ``None`` when the URL shape or the
base64 payload itself is malformed. Raises :class:`FileSizeExceeded` base64 payload itself is malformed. Raises :class:`FileSizeExceededError`
when the decoded payload is larger than ``max_bytes`` (default 10 MB). when the decoded payload is larger than ``max_bytes`` (default 10 MB).
""" """
# Parse delimiters directly so malformed MIME parameters cannot trigger regex backtracking. # Parse delimiters directly so malformed MIME parameters cannot trigger regex backtracking.
@@ -83,7 +79,7 @@ def save_base64_data_url(
return None return None
limit = DEFAULT_MAX_BYTES if max_bytes is None else max_bytes limit = DEFAULT_MAX_BYTES if max_bytes is None else max_bytes
if len(raw) > limit: if len(raw) > limit:
raise FileSizeExceeded(f"File exceeds {limit // (1024 * 1024)}MB limit") raise FileSizeExceededError(f"File exceeds {limit // (1024 * 1024)}MB limit")
dest = media_destination(media_dir, mime_type, filename=filename) dest = media_destination(media_dir, mime_type, filename=filename)
dest.write_bytes(raw) dest.write_bytes(raw)
return str(dest) return str(dest)
-11
View File
@@ -429,17 +429,6 @@ def update_web_search_settings(
) )
def update_api_settings(
query: QueryParams,
*,
config_path: Path | None = None,
) -> dict[str, Any]:
config = _load_settings_config(config_path)
capabilities.update_api_settings(config, query)
_save_settings_config(config, config_path)
return settings_payload(config_path=config_path)
def update_image_generation_settings( def update_image_generation_settings(
query: QueryParams, query: QueryParams,
*, *,
-203
View File
@@ -1,30 +1,22 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import os import os
import re import re
from dataclasses import dataclass from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypedDict from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypedDict
from nanobot.agent.tools.web import SEARCH_PROVIDER_OPTIONS from nanobot.agent.tools.web import SEARCH_PROVIDER_OPTIONS
from nanobot.api.runtime import ApiRuntime, ApiStartOptions
from nanobot.audio.transcription import resolve_transcription_config from nanobot.audio.transcription import resolve_transcription_config
from nanobot.audio.transcription_registry import ( from nanobot.audio.transcription_registry import (
resolve_transcription_provider, resolve_transcription_provider,
transcription_provider_names, transcription_provider_names,
) )
from nanobot.config.schema import Config from nanobot.config.schema import Config
from nanobot.optional_features import (
OptionalFeatureError,
extra_installed,
optional_dependency_groups,
)
from nanobot.providers.image_generation import ( from nanobot.providers.image_generation import (
get_image_gen_provider, get_image_gen_provider,
image_gen_provider_names, image_gen_provider_names,
) )
from nanobot.providers.registry import find_by_name from nanobot.providers.registry import find_by_name
from nanobot.security.network import is_loopback_host
from nanobot.webui.request_settings import ( from nanobot.webui.request_settings import (
parse_request_object, parse_request_object,
redact_request_secrets, redact_request_secrets,
@@ -59,19 +51,15 @@ SettingsOperation = Callable[..., dict[str, Any]]
@dataclass(frozen=True) @dataclass(frozen=True)
class CapabilitySettingsOperations: class CapabilitySettingsOperations:
update_web_search: SettingsOperation update_web_search: SettingsOperation
update_api: SettingsOperation
update_image: SettingsOperation update_image: SettingsOperation
update_transcription: SettingsOperation update_transcription: SettingsOperation
update_network: SettingsOperation update_network: SettingsOperation
nanobot_features_action: SettingsOperation
api_runtime: Callable[[], ApiRuntime]
reload_image: Callable[[], Awaitable[dict[str, Any]]] reload_image: Callable[[], Awaitable[dict[str, Any]]]
class CapabilitySettingsPayload(TypedDict): class CapabilitySettingsPayload(TypedDict):
web_search: dict[str, Any] web_search: dict[str, Any]
web: dict[str, Any] web: dict[str, Any]
api: dict[str, Any]
observability: dict[str, Any] observability: dict[str, Any]
image_generation: dict[str, Any] image_generation: dict[str, Any]
transcription: dict[str, Any] transcription: dict[str, Any]
@@ -194,12 +182,6 @@ def capability_settings_payload(
"use_jina_reader": config.tools.web.fetch.use_jina_reader, "use_jina_reader": config.tools.web.fetch.use_jina_reader,
}, },
}, },
"api": {
"host": config.api.host,
"port": config.api.port,
"timeout": config.api.timeout,
"api_key_hint": mask_secret_hint(config.api.api_key),
},
"observability": { "observability": {
"provider": "langfuse", "provider": "langfuse",
"configured": bool( "configured": bool(
@@ -365,45 +347,6 @@ def update_web_search_settings(config: Config, query: QueryParams) -> tuple[bool
return changed, restart_required return changed, restart_required
def update_api_settings(config: Config, query: QueryParams) -> None:
"""Update the managed OpenAI-compatible API configuration."""
api = config.api
host = query_first(query, "host")
if host is not None:
host = host.strip()
if not host:
raise WebUISettingsError("host is required")
api.host = host
port = query_first(query, "port")
if port is not None:
try:
parsed_port = int(port)
except ValueError:
raise WebUISettingsError("port must be an integer") from None
if parsed_port < 1 or parsed_port > 65535:
raise WebUISettingsError("port must be between 1 and 65535")
api.port = parsed_port
timeout = query_first(query, "timeout")
if timeout is not None:
try:
parsed_timeout = float(timeout)
except ValueError:
raise WebUISettingsError("timeout must be a number") from None
if parsed_timeout < 1 or parsed_timeout > 3600:
raise WebUISettingsError("timeout must be between 1 and 3600")
api.timeout = parsed_timeout
api_key = query_first_alias(query, "api_key", "apiKey")
if api_key is not None:
api.api_key = api_key.strip()
if not is_loopback_host(api.host) and not api.api_key.strip():
raise WebUISettingsError(
"an API key is required when the API is available on the network"
)
def update_image_generation_settings( def update_image_generation_settings(
config: Config, config: Config,
query: QueryParams, query: QueryParams,
@@ -603,55 +546,6 @@ def network_safety_payload(config: Config) -> dict[str, Any]:
} }
def masked_api_secret(value: str) -> str | None:
value = value.strip()
if not value:
return None
return f"{value[:3]}...{value[-4:]}" if len(value) > 8 else "configured"
def api_runtime_message(message: str) -> str:
known = {
"api_exited_during_startup": "API server exited during startup. Check its log for details.",
"api_stop_timeout": "API server did not stop in time.",
"api_state_stale": "API server state was stale; try starting it again.",
}
if message in known:
return known[message]
if message.startswith("api_"):
return f"API server {message.removeprefix('api_').replace('_', ' ')}"
return message.replace("_", " ")
def api_service_payload(
settings: WebUISettingsServices,
runtime: ApiRuntime,
*,
last_action: str | None = None,
) -> dict[str, Any]:
config = settings.config.load()
status = runtime.status()
extras = optional_dependency_groups()
connect_host = (
"127.0.0.1" if config.api.host in {"0.0.0.0", "::"} else config.api.host
)
payload = {
"installed": extra_installed("api", extras.get("api")),
"running": status.running,
"managed": status.running,
"host": config.api.host,
"port": config.api.port,
"timeout": config.api.timeout,
"api_key_hint": masked_api_secret(config.api.api_key),
"endpoint": f"http://{connect_host}:{config.api.port}/v1",
"command": "nanobot serve",
"log_path": str(status.log_path),
}
if last_action:
payload["last_action"] = last_action
return payload
class CapabilitySettingsHandler: class CapabilitySettingsHandler:
"""Handle capability commands after transport authentication and decoding.""" """Handle capability commands after transport authentication and decoding."""
@@ -665,15 +559,6 @@ class CapabilitySettingsHandler:
request: SettingsRequest, request: SettingsRequest,
operations: CapabilitySettingsOperations, operations: CapabilitySettingsOperations,
) -> SettingsRouteResult: ) -> SettingsRouteResult:
if action == "api-status":
return SettingsRouteResult.success(
api_service_payload(self.settings, operations.api_runtime())
)
if action == "api-start":
return await self._start_api(request, operations)
if action == "api-stop":
return await self._stop_api(operations)
mutation = { mutation = {
"web-search-update": ( "web-search-update": (
operations.update_web_search, operations.update_web_search,
@@ -741,91 +626,3 @@ class CapabilitySettingsHandler:
result.get("message") or "hot reload failed", result.get("message") or "hot reload failed",
) )
return updated, applied return updated, applied
async def _start_api(
self,
request: SettingsRequest,
operations: CapabilitySettingsOperations,
) -> SettingsRouteResult:
api_key = (request.payload or {}).get("api_key")
if api_key is not None and not isinstance(api_key, str):
return SettingsRouteResult.failure(
400,
"API service API key must be a string",
)
try:
await asyncio.to_thread(
self.settings.mutate,
operations.nanobot_features_action,
"enable",
{"name": ["api"]},
allow_install=self._allow_feature_package_install(request),
)
self.settings.mutate(operations.update_api, request.query)
config = self.settings.config.load()
runtime = operations.api_runtime()
options = ApiStartOptions(
host=config.api.host,
port=config.api.port,
workspace=str(config.workspace_path),
config_path=str(self.settings.config.path),
)
current = runtime.status()
result = await asyncio.to_thread(
runtime.restart if current.running else runtime.start_background,
options,
)
if not result.ok:
return SettingsRouteResult.failure(
500,
api_runtime_message(result.message),
)
except (WebUISettingsError, OptionalFeatureError) as exc:
return SettingsRouteResult.failure(
getattr(exc, "status", 400),
getattr(exc, "message", str(exc)),
)
except Exception as exc:
self.logger.exception("failed to start managed API service")
return SettingsRouteResult.failure(500, str(exc))
return SettingsRouteResult.success(
api_service_payload(
self.settings,
operations.api_runtime(),
last_action="started",
)
)
async def _stop_api(
self,
operations: CapabilitySettingsOperations,
) -> SettingsRouteResult:
runtime = operations.api_runtime()
try:
result = await asyncio.to_thread(runtime.stop)
except Exception as exc:
self.logger.exception("failed to stop managed API service")
return SettingsRouteResult.failure(500, str(exc))
if not result.ok and result.message != "api_not_running":
return SettingsRouteResult.failure(
500,
api_runtime_message(result.message),
)
return SettingsRouteResult.success(
api_service_payload(
self.settings,
operations.api_runtime(),
last_action="stopped",
)
)
def _allow_feature_package_install(self, request: SettingsRequest) -> bool:
if request.local_browser:
return True
try:
return bool(
self.settings.config.load().tools.webui_allow_remote_package_install
)
except Exception:
self.logger.exception("failed to load remote package install policy")
return False
-14
View File
@@ -11,7 +11,6 @@ from websockets.http11 import Request as WsRequest
from websockets.http11 import Response from websockets.http11 import Response
from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH from nanobot.agent.tools.mcp_oauth import MCP_OAUTH_CALLBACK_PATH
from nanobot.api.runtime import ApiRuntime, api_runtime_paths
from nanobot.bus.queue import MessageBus from nanobot.bus.queue import MessageBus
from nanobot.channels.registry import load_channel_plugin from nanobot.channels.registry import load_channel_plugin
from nanobot.channels.validation import validate_channel_config from nanobot.channels.validation import validate_channel_config
@@ -48,7 +47,6 @@ from nanobot.webui.settings_api import (
settings_payload, settings_payload,
settings_usage_payload, settings_usage_payload,
update_agent_settings, update_agent_settings,
update_api_settings,
update_image_generation_settings, update_image_generation_settings,
update_model_call_order, update_model_call_order,
update_model_configuration, update_model_configuration,
@@ -122,9 +120,6 @@ _MODEL_ROUTES = {
_CAPABILITY_ROUTES = { _CAPABILITY_ROUTES = {
"/api/settings/web-search/update": "web-search-update", "/api/settings/web-search/update": "web-search-update",
"/api/settings/api-service": "api-status",
"/api/settings/api-service/start": "api-start",
"/api/settings/api-service/stop": "api-stop",
"/api/settings/image-generation/update": "image-update", "/api/settings/image-generation/update": "image-update",
"/api/settings/transcription/update": "transcription-update", "/api/settings/transcription/update": "transcription-update",
"/api/settings/network-safety/update": "network-update", "/api/settings/network-safety/update": "network-update",
@@ -183,8 +178,6 @@ _SETTINGS_MUTATION_PATHS = frozenset({
"/api/settings/provider/oauth-login/complete", "/api/settings/provider/oauth-login/complete",
"/api/settings/provider/oauth-logout", "/api/settings/provider/oauth-logout",
"/api/settings/web-search/update", "/api/settings/web-search/update",
"/api/settings/api-service/start",
"/api/settings/api-service/stop",
"/api/settings/image-generation/update", "/api/settings/image-generation/update",
"/api/settings/transcription/update", "/api/settings/transcription/update",
"/api/settings/network-safety/update", "/api/settings/network-safety/update",
@@ -334,7 +327,6 @@ class WebUISettingsRouter:
request, request,
needs_local_browser=( needs_local_browser=(
action in { action in {
"api-start",
"runtime-config-update", "runtime-config-update",
"features-enable", "features-enable",
"channel-configure", "channel-configure",
@@ -534,12 +526,9 @@ class WebUISettingsRouter:
) -> capability_domain.CapabilitySettingsOperations: ) -> capability_domain.CapabilitySettingsOperations:
return capability_domain.CapabilitySettingsOperations( return capability_domain.CapabilitySettingsOperations(
update_web_search=update_web_search_settings, update_web_search=update_web_search_settings,
update_api=update_api_settings,
update_image=update_image_generation_settings, update_image=update_image_generation_settings,
update_transcription=update_transcription_settings, update_transcription=update_transcription_settings,
update_network=update_network_safety_settings, update_network=update_network_safety_settings,
nanobot_features_action=nanobot_features_action,
api_runtime=self._api_runtime,
reload_image=self._reload_image_generation_runtime, reload_image=self._reload_image_generation_runtime,
) )
@@ -633,9 +622,6 @@ class WebUISettingsRouter:
def _parse_mcp_settings_query(self, request: WsRequest) -> QueryParams: def _parse_mcp_settings_query(self, request: WsRequest) -> QueryParams:
return self._query(request) return self._query(request)
def _api_runtime(self) -> ApiRuntime:
return ApiRuntime(paths=api_runtime_paths(self.settings.config.path))
def _save_channel_config_values( def _save_channel_config_values(
self, self,
name: str, name: str,
+1 -11
View File
@@ -11,7 +11,6 @@ from pydantic import BaseModel, TypeAdapter, ValidationError
from nanobot.config.errors import ConfigLoadError from nanobot.config.errors import ConfigLoadError
from nanobot.config.loader import resolve_config_env_vars from nanobot.config.loader import resolve_config_env_vars
from nanobot.config.schema import Config from nanobot.config.schema import Config
from nanobot.security.network import is_loopback_host
from nanobot.webui.settings_contracts import WebUISettingsError from nanobot.webui.settings_contracts import WebUISettingsError
# Only these leaves may be read or patched through this surface. Model/provider, # Only these leaves may be read or patched through this surface. Model/provider,
@@ -57,8 +56,6 @@ RUNTIME_CONFIG_PATHS = (
"tools.web.use_proxy", "tools.web.use_proxy",
"tools.web.user_agent", "tools.web.user_agent",
"tools.image_generation.save_dir", "tools.image_generation.save_dir",
"api.host",
"api.timeout",
) )
@@ -123,7 +120,6 @@ def update_runtime_config(
"agents.defaults.max_tool_iterations": 1, "agents.defaults.max_tool_iterations": 1,
"agents.defaults.max_tool_result_chars": 1, "agents.defaults.max_tool_result_chars": 1,
"gateway.port": 1, "gateway.port": 1,
"api.timeout": 1,
} }
for path, minimum in numeric_minima.items(): for path, minimum in numeric_minima.items():
if path in values: if path in values:
@@ -132,15 +128,13 @@ def update_runtime_config(
raise WebUISettingsError(f"{path}: must be at least {minimum}") raise WebUISettingsError(f"{path}: must be at least {minimum}")
if "gateway.port" in values and validated.gateway.port > 65535: if "gateway.port" in values and validated.gateway.port > 65535:
raise WebUISettingsError("gateway.port: must be at most 65535") raise WebUISettingsError("gateway.port: must be at most 65535")
if "api.timeout" in values and validated.api.timeout > 3600:
raise WebUISettingsError("api.timeout: must be at most 3600 seconds")
if "tools.exec.timeout" in values: if "tools.exec.timeout" in values:
limit = validated.tools.exec.max_runtime_limit limit = validated.tools.exec.max_runtime_limit
if validated.tools.exec.max_runtime > limit: if validated.tools.exec.max_runtime > limit:
raise WebUISettingsError( raise WebUISettingsError(
f"tools.exec.timeout: enter 1–{limit} seconds, or 0 for no time limit" f"tools.exec.timeout: enter 1–{limit} seconds, or 0 for no time limit"
) )
for path in ("gateway.host", "api.host", "tools.image_generation.save_dir"): for path in ("gateway.host", "tools.image_generation.save_dir"):
if path in values: if path in values:
parent, leaf = _parent(validated, path) parent, leaf = _parent(validated, path)
if not str(getattr(parent, leaf)).strip(): if not str(getattr(parent, leaf)).strip():
@@ -150,9 +144,6 @@ def update_runtime_config(
if (PureWindowsPath(directory).drive or directory.startswith(("/", "\\")) if (PureWindowsPath(directory).drive or directory.startswith(("/", "\\"))
or ".." in PurePosixPath(directory.replace("\\", "/")).parts): or ".." in PurePosixPath(directory.replace("\\", "/")).parts):
raise WebUISettingsError("tools.image_generation.save_dir: use a relative path inside the media directory") raise WebUISettingsError("tools.image_generation.save_dir: use a relative path inside the media directory")
if "api.host" in values and not is_loopback_host(validated.api.host):
if not validated.api.api_key.strip():
raise WebUISettingsError("Set an API key in System before using a network bind address.")
if "tools.exec.sandbox" in values and validated.tools.exec.sandbox not in {"", "bwrap", "seatbelt"}: if "tools.exec.sandbox" in values and validated.tools.exec.sandbox not in {"", "bwrap", "seatbelt"}:
raise WebUISettingsError("tools.exec.sandbox: choose no sandbox, bwrap, or seatbelt") raise WebUISettingsError("tools.exec.sandbox: choose no sandbox, bwrap, or seatbelt")
if {"tools.exec.sandbox_launcher", "tools.exec.sandbox_rw_binds"} & values.keys() and validated.tools.exec.sandbox_launcher: if {"tools.exec.sandbox_launcher", "tools.exec.sandbox_rw_binds"} & values.keys() and validated.tools.exec.sandbox_launcher:
@@ -199,5 +190,4 @@ def update_runtime_config(
config.tools = validated.tools config.tools = validated.tools
config.network = validated.network config.network = validated.network
config.gateway = validated.gateway config.gateway = validated.gateway
config.api = validated.api
return True return True
-2
View File
@@ -212,8 +212,6 @@ _WEBUI_MUTATION_PATHS = {
"settings.provider.oauth_complete": "/api/settings/provider/oauth-login/complete", "settings.provider.oauth_complete": "/api/settings/provider/oauth-login/complete",
"settings.provider.oauth_logout": "/api/settings/provider/oauth-logout", "settings.provider.oauth_logout": "/api/settings/provider/oauth-logout",
"settings.web_search.update": "/api/settings/web-search/update", "settings.web_search.update": "/api/settings/web-search/update",
"settings.api_service.start": "/api/settings/api-service/start",
"settings.api_service.stop": "/api/settings/api-service/stop",
"settings.image_generation.update": "/api/settings/image-generation/update", "settings.image_generation.update": "/api/settings/image-generation/update",
"settings.transcription.update": "/api/settings/transcription/update", "settings.transcription.update": "/api/settings/transcription/update",
"settings.runtime_config.update": "/api/settings/runtime-config/update", "settings.runtime_config.update": "/api/settings/runtime-config/update",
+2 -3
View File
@@ -69,9 +69,8 @@ dependencies = [
] ]
[project.optional-dependencies] [project.optional-dependencies]
api = [ # Keep this empty extra so older updaters can preserve recorded installations.
"aiohttp>=3.9.0,<4.0.0", api = []
]
azure = [ azure = [
"azure-identity>=1.19.0,<2.0.0", "azure-identity>=1.19.0,<2.0.0",
] ]
+1 -2
View File
@@ -34,7 +34,6 @@ class Violation:
_ADAPTERS = ( _ADAPTERS = (
"nanobot.api",
"nanobot.channels", "nanobot.channels",
"nanobot.cli", "nanobot.cli",
"nanobot.gateway", "nanobot.gateway",
@@ -63,7 +62,7 @@ IMPORT_RULES = (
("nanobot.update_service", "nanobot.update_plan", "nanobot.update_jobs", ("nanobot.update_service", "nanobot.update_plan", "nanobot.update_jobs",
"nanobot.update_worker", "nanobot.update_stop", "nanobot.update_worker", "nanobot.update_stop",
"nanobot.update_profiles", "nanobot.update_handoff", "nanobot.update_guidance"), "nanobot.update_profiles", "nanobot.update_handoff", "nanobot.update_guidance"),
("nanobot.agent", "nanobot.session", "nanobot.api", "nanobot.cli", ("nanobot.agent", "nanobot.session", "nanobot.cli",
"nanobot.channels", "nanobot.webui"), "nanobot.channels", "nanobot.webui"),
), ),
ImportRule( ImportRule(
+60 -81
View File
@@ -1,4 +1,4 @@
"""Verify Compose first boot, WebUI authentication, restart, and API readiness.""" """Verify Compose first boot, WebUI authentication, and restart."""
import argparse import argparse
import json import json
@@ -11,13 +11,10 @@ from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
def request(url: str, secret: str = "", body: dict[str, object] | None = None) -> tuple[int, bytes]: def request(url: str, secret: str = "") -> 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, data=data, headers=headers), timeout=3) as response: with urlopen(Request(url, 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()
@@ -73,10 +70,20 @@ def main() -> None:
"target": "/home/nanobot/.nanobot", "target": "/home/nanobot/.nanobot",
}] }]
service["environment"].update( service["environment"].update(
NANOBOT_WEB_TOKEN=secret, NANOBOT_API_KEY=secret, NANOBOT_WEB_TOKEN=secret,
) )
compose_path.write_text(json.dumps(config), encoding="utf-8") compose_path.write_text(json.dumps(config), encoding="utf-8")
try: try:
if label == "generated":
retired = subprocess.run(
[*compose, "run", "--rm", "--no-deps", "-T", "nanobot-cli", "serve", "--port", "8900"],
capture_output=True, text=True, timeout=45,
)
output = retired.stdout + retired.stderr
assert retired.returncode == 2, output
assert "'nanobot serve' has been removed" in output, output
assert not (data / "config.json").exists()
print("PASS retired serve command: migration hint without Compose bootstrap")
onboard = run("run", "--rm", "--no-deps", "-T", "nanobot-cli", "onboard") onboard = run("run", "--rm", "--no-deps", "-T", "nanobot-cli", "onboard")
assert "Overwrite?" not in onboard assert "Overwrite?" not in onboard
assert "Created config" in onboard assert "Created config" in onboard
@@ -90,46 +97,38 @@ def main() -> None:
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 set(run("ps", "--services").split()) == {"nanobot-gateway", "nanobot-api"} assert set(run("ps", "--services").split()) == {"nanobot-gateway"}
path = data / "config.json" path = data / "config.json"
saved = json.loads(path.read_text(encoding="utf-8")) saved = json.loads(path.read_text(encoding="utf-8"))
password = saved["channels"]["websocket"]["tokenIssueSecret"] password = saved["channels"]["websocket"]["tokenIssueSecret"]
api_key = saved["api"]["apiKey"]
logs = run("logs", "--no-color") logs = run("logs", "--no-color")
assert logs.count("[entrypoint] initialized") == 1 assert logs.count("[entrypoint] initialized") == 1
assert password in logs and api_key in logs assert password in logs
if secret: if secret:
assert password == api_key == secret assert password == secret
else: else:
assert len(password) == len(api_key) == 32 and password != api_key assert len(password) == 32
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"]
api = endpoint("nanobot-api", 8900) print(f"PASS {label}: authenticated WebUI")
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")
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")
# Simulate the persisted block from the previous Compose deployment.
saved["api"] = {"host": "0.0.0.0", "apiKey": "${RETIRED_SERVE_TOKEN}"}
# Use the mounted owner to write the legacy config on Linux.
subprocess.run([ subprocess.run([
*compose, "exec", "-T", "--user", "1000:1000", "nanobot-gateway", "python", "-c", *compose, "exec", "-T", "--user", "1000:1000", "nanobot-gateway", "python", "-c",
"import json, sys; from pathlib import Path; " "import sys; from pathlib import Path; "
"from nanobot.config.schema import Config; from nanobot.config.loader import save_config; " "Path('/home/nanobot/.nanobot/config.json').write_text(sys.stdin.read(), encoding='utf-8')",
"save_config(Config.model_validate(json.load(sys.stdin)), "
"Path('/home/nanobot/.nanobot/config.json'))",
], input=json.dumps(saved), text=True, check=True) ], 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(
NANOBOT_WEB_TOKEN="changed-env", NANOBOT_API_KEY="changed-env", NANOBOT_WEB_TOKEN="changed-env",
) )
compose_path.write_text(json.dumps(config), encoding="utf-8") compose_path.write_text(json.dumps(config), encoding="utf-8")
run("up", "-d", "--force-recreate", "nanobot-gateway") run("up", "-d", "--force-recreate", "nanobot-gateway")
@@ -140,21 +139,6 @@ 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("up", "-d", "--force-recreate", "nanobot-api")
api = endpoint("nanobot-api", 8900)
deadline = time.monotonic() + 60
while True:
try:
status, _body = request(api + "/v1/models", api_key)
if status == 200:
break
except (URLError, ConnectionError, TimeoutError):
pass
if time.monotonic() >= deadline:
raise RuntimeError("Configured API did not start")
time.sleep(1)
assert request(api + "/v1/models")[0] == 401
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
@@ -176,46 +160,41 @@ def main() -> None:
("short", ["-c", selected_path]), ("short", ["-c", selected_path]),
("short-attached", [f"-c{selected_path}"]), ("short-attached", [f"-c{selected_path}"]),
) )
for service_name in ("nanobot-gateway", "nanobot-api"): service_name = "nanobot-gateway"
for label, selector in selectors: for label, selector in selectors:
data = root / f"{service_name}-{label}" data = root / f"{service_name}-{label}"
data.mkdir() data.mkdir()
selected = data / "selected.json" selected = data / "selected.json"
selected.write_text(json.dumps(saved), encoding="utf-8") selected.write_text(json.dumps(saved), encoding="utf-8")
previous = selected.read_bytes() previous = selected.read_bytes()
for service in config["services"].values(): for service in config["services"].values():
service["volumes"] = [{ service["volumes"] = [{
"type": "bind", "source": str(data), "type": "bind", "source": str(data),
"target": "/home/nanobot/.nanobot", "target": "/home/nanobot/.nanobot",
}] }]
config["services"][service_name]["command"] = [*commands[service_name], *selector] config["services"][service_name]["command"] = [*commands[service_name], *selector]
compose_path.write_text(json.dumps(config), encoding="utf-8") compose_path.write_text(json.dumps(config), encoding="utf-8")
try: try:
run("up", "-d", "--no-deps", service_name) run("up", "-d", "--no-deps", service_name)
gateway = service_name == "nanobot-gateway" health = endpoint(service_name, 18790)
health = endpoint(service_name, 18790 if gateway else 8900) wait_for(health + "/health")
wait_for(health + "/health") webui = endpoint(service_name, 8765)
if gateway: assert request(webui + "/webui/bootstrap", password)[0] == 200
webui = endpoint(service_name, 8765) assert selected.read_bytes() == previous
assert request(webui + "/webui/bootstrap", password)[0] == 200 assert not (data / "config.json").exists()
else: assert "[entrypoint] initialized" not in run("logs", "--no-color")
assert request(health + "/v1/models", api_key)[0] == 200 print(f"PASS {service_name} {label}: explicit config preserved without default initialization")
assert request(health + "/v1/models", "changed-env")[0] == 401 except Exception:
assert selected.read_bytes() == previous print(run("logs", "--no-color", "--tail", "80"), flush=True)
assert not (data / "config.json").exists() raise
assert "[entrypoint] initialized" not in run("logs", "--no-color") finally:
print(f"PASS {service_name} {label}: explicit config preserved without default initialization") subprocess.run([*compose, "down", "--volumes"], check=True)
except Exception: if os.name != "nt":
print(run("logs", "--no-color", "--tail", "80"), flush=True) subprocess.run([
raise "docker", "run", "--rm", "--entrypoint", "chown",
finally: "-v", f"{data}:/data", args.image,
subprocess.run([*compose, "down", "--volumes"], check=True) "-R", f"{os.getuid()}:{os.getgid()}", "/data",
if os.name != "nt": ], check=True)
subprocess.run([
"docker", "run", "--rm", "--entrypoint", "chown",
"-v", f"{data}:/data", args.image,
"-R", f"{os.getuid()}:{os.getgid()}", "/data",
], check=True)
readonly = root / "readonly" readonly = root / "readonly"
readonly.mkdir() readonly.mkdir()
+1 -4
View File
@@ -335,16 +335,13 @@ async def test_non_goal_direct_turn_cannot_reuse_prior_goal_command(tmp_path):
]) ])
loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model", loop = AgentLoop(bus=MessageBus(), provider=provider, workspace=tmp_path, model="test-model",
builtin_assembly=install_goal) builtin_assembly=install_goal)
session = loop.sessions.get_or_create("api:default") session = loop.sessions.get_or_create("cli:direct")
session.add_message("user", "/goal old completed request") session.add_message("user", "/goal old completed request")
session.add_message("assistant", "The old request is complete.") session.add_message("assistant", "The old request is complete.")
result = await loop.process_direct( result = await loop.process_direct(
"Handle this as an ordinary one-time task.", "Handle this as an ordinary one-time task.",
session_key=session.key, session_key=session.key,
channel="api",
chat_id="default",
persist_user_message=False,
) )
assert result is not None assert result is not None
-26
View File
@@ -1807,32 +1807,6 @@ async def test_process_direct_rejects_reserved_system_channel(tmp_path: Path) ->
loop._process_message.assert_not_awaited() loop._process_message.assert_not_awaited()
@pytest.mark.asyncio
async def test_process_direct_skip_user_persist_does_not_save_retry_user(
tmp_path: Path,
) -> None:
loop = _make_full_loop(tmp_path)
session = loop.sessions.get_or_create("api:default")
session.add_message("user", "hello")
session.add_message("assistant", "previous empty-response attempt")
loop.sessions.save(session)
await loop.process_direct(
"hello",
session_key=session.key,
channel="api",
chat_id="default",
persist_user_message=False,
)
session = loop.sessions.get_or_create("api:default")
assert [(m["role"], m["content"]) for m in session.messages] == [
("user", "hello"),
("assistant", "previous empty-response attempt"),
("assistant", "Test title"),
]
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_request_context_uses_effective_key_for_subagent_tool(tmp_path: Path) -> None: async def test_request_context_uses_effective_key_for_subagent_tool(tmp_path: Path) -> None:
loop = _make_full_loop(tmp_path) loop = _make_full_loop(tmp_path)
-56
View File
@@ -755,33 +755,6 @@ class TestChannelCommonRegistration:
assert config.channels.feishu["appId"] == "test123" assert config.channels.feishu["appId"] == "test123"
class TestApiServerRegistration:
def test_api_server_in_settings_sections(self):
from nanobot.cli.onboard import _SETTINGS_SECTIONS
assert "API Server" in _SETTINGS_SECTIONS
def test_api_server_getter_returns_api(self):
from nanobot.cli.onboard import _SETTINGS_GETTER
config = Config()
result = _SETTINGS_GETTER["API Server"](config)
assert result is config.api
def test_api_server_setter_writes_api(self):
from nanobot.cli.onboard import _SETTINGS_SETTER
config = Config()
from nanobot.config.schema import ApiConfig
new_api = ApiConfig(host="0.0.0.0", port=9999, api_key="secret")
_SETTINGS_SETTER["API Server"](config, new_api)
assert config.api.host == "0.0.0.0"
assert config.api.port == 9999
assert config.api.api_key == "secret"
@pytest.fixture @pytest.fixture
def prompt_input(): def prompt_input():
with create_pipe_input() as pipe: with create_pipe_input() as pipe:
@@ -1708,35 +1681,6 @@ class TestMainMenuInteraction:
assert result.should_save is True assert result.should_save is True
assert result.config.channels.send_tool_hints is True assert result.config.channels.send_tool_hints is True
def test_run_onboard_api_server_edit(self, monkeypatch):
initial_config = Config()
responses = iter([
"[A] Advanced Settings",
"[I] API Server",
KeyboardInterrupt(),
"[S] Save and Exit",
])
def fake_select_with_back(*_args, **_kwargs):
response = next(responses)
if isinstance(response, BaseException):
raise response
return response
def fake_configure_general_settings(config, section):
if section == "API Server":
config.api.port = 9999
monkeypatch.setattr(onboard_wizard, "_show_main_menu_header", lambda: None)
monkeypatch.setattr(onboard_wizard, "_select_with_back", fake_select_with_back)
monkeypatch.setattr(onboard_wizard, "_configure_general_settings", fake_configure_general_settings)
result = run_onboard(initial_config=initial_config)
assert result.should_save is True
assert result.config.api.port == 9999
def test_view_summary_calls_pause(self, monkeypatch): def test_view_summary_calls_pause(self, monkeypatch):
initial_config = Config() initial_config = Config()
pause_called = {"n": 0} pause_called = {"n": 0}
+3 -2
View File
@@ -2614,7 +2614,7 @@ def test_optional_dependency_metadata_for_enable():
assert "boto3>=1.43.0" not in data["project"]["dependencies"] assert "boto3>=1.43.0" not in data["project"]["dependencies"]
assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"] assert deps["bedrock"] == ["boto3>=1.43.0", "botocore>=1.43.0,<2.0.0"]
assert "aiohttp>=3.14.3,<4.0.0" in required assert "aiohttp>=3.14.3,<4.0.0" in required
assert deps["api"] == ["aiohttp>=3.9.0,<4.0.0"] assert deps["api"] == [] # Older updaters preserve this recorded extra.
for dep_name in ( for dep_name in (
"dingtalk-stream", "dingtalk-stream",
"lark-oapi", "lark-oapi",
@@ -2713,6 +2713,7 @@ def test_optional_dependency_metadata_for_enable():
assert plugin.dependencies == expected assert plugin.dependencies == expected
visible = optional_features.optional_dependency_groups() visible = optional_features.optional_dependency_groups()
assert "api" not in visible
assert "documents" not in visible assert "documents" not in visible
assert "pdf" not in visible assert "pdf" not in visible
@@ -2723,7 +2724,7 @@ def test_optional_dependency_groups_falls_back_to_package_metadata(monkeypatch):
class _Metadata: class _Metadata:
def get_all(self, key: str): def get_all(self, key: str):
assert key == "Provides-Extra" assert key == "Provides-Extra"
return ["bedrock", "dev"] return ["api", "bedrock", "dev"]
monkeypatch.setattr(optional_features, "load_pyproject", lambda _path: {}) monkeypatch.setattr(optional_features, "load_pyproject", lambda _path: {})
monkeypatch.setattr("importlib.metadata.metadata", lambda _name: _Metadata()) monkeypatch.setattr("importlib.metadata.metadata", lambda _name: _Metadata())
-173
View File
@@ -3159,54 +3159,6 @@ def test_webui_foreground_reports_an_existing_gateway_without_leaking_secret(
assert "do-not-leak" not in result.stdout assert "do-not-leak" not in result.stdout
def _patch_serve_runtime(monkeypatch, config: Config, seen: dict[str, object]) -> None:
pytest.importorskip("aiohttp")
class _FakeApiApp:
def __init__(self) -> None:
self.on_startup: list[object] = []
self.on_cleanup: list[object] = []
class _FakeAgentLoop:
@classmethod
def from_config(cls, config, bus=None, **extra):
return cls(workspace=config.workspace_path, **extra)
def __init__(self, **kwargs) -> None:
seen["workspace"] = kwargs["workspace"]
async def aclose(self) -> None:
return None
def _fake_create_app(
agent_loop,
model_name: str,
request_timeout: float,
api_key: str = "",
prepare_agent=None,
):
seen["agent_loop"] = agent_loop
seen["model_name"] = model_name
seen["request_timeout"] = request_timeout
seen["api_key"] = api_key
seen["prepare_agent"] = prepare_agent
return _FakeApiApp()
def _fake_run_app(api_app, host: str, port: int, print):
seen["api_app"] = api_app
seen["host"] = host
seen["port"] = port
_patch_cli_command_runtime(
monkeypatch,
config,
message_bus=MessageBus,
session_manager=lambda _workspace: _EmptyGatewaySessionManager(),
)
_patch_fake_agent_loop(monkeypatch, "nanobot.cli.commands.AgentLoop", _FakeAgentLoop)
monkeypatch.setattr("nanobot.api.server.create_app", _fake_create_app)
monkeypatch.setattr("aiohttp.web.run_app", _fake_run_app)
def test_gateway_uses_workspace_from_config_by_default(monkeypatch, tmp_path: Path) -> None: def test_gateway_uses_workspace_from_config_by_default(monkeypatch, tmp_path: Path) -> None:
config_file = _write_instance_config(tmp_path) config_file = _write_instance_config(tmp_path)
config = Config() config = Config()
@@ -4476,34 +4428,6 @@ def test_gateway_shutdown_event_exits_forever_runtime_tasks(
assert shutdown_order == ["channels_stopped", "channel_task_cleaned_up"] assert shutdown_order == ["channels_stopped", "channel_task_cleaned_up"]
def test_serve_uses_api_config_defaults_and_workspace_override(
monkeypatch, tmp_path: Path
) -> None:
config_file = _write_instance_config(tmp_path)
config = Config()
config.agents.defaults.workspace = str(tmp_path / "config-workspace")
config.api.host = "127.0.0.2"
config.api.port = 18900
config.api.timeout = 45.0
config.api.api_key = "secret"
override_workspace = tmp_path / "override-workspace"
seen: dict[str, object] = {}
_patch_serve_runtime(monkeypatch, config, seen)
result = runner.invoke(
app,
["serve", "--config", str(config_file), "--workspace", str(override_workspace)],
)
assert result.exit_code == 0
assert seen["workspace"] == override_workspace
assert seen["host"] == "127.0.0.2"
assert seen["port"] == 18900
assert seen["request_timeout"] == 45.0
assert seen["api_key"] == "secret"
def test_trigger_cli_queues_message_in_workspace( def test_trigger_cli_queues_message_in_workspace(
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
tmp_path: Path, tmp_path: Path,
@@ -4536,103 +4460,6 @@ def test_trigger_cli_queues_message_in_workspace(
assert deliveries[0].content == "Review PR #4502" assert deliveries[0].content == "Review PR #4502"
def test_serve_cli_options_override_api_config(monkeypatch, tmp_path: Path) -> None:
config_file = _write_instance_config(tmp_path)
config = Config()
config.api.host = "127.0.0.2"
config.api.port = 18900
config.api.timeout = 45.0
config.api.api_key = "secret"
seen: dict[str, object] = {}
_patch_serve_runtime(monkeypatch, config, seen)
result = runner.invoke(
app,
[
"serve",
"--config",
str(config_file),
"--host",
"127.0.0.1",
"--port",
"18901",
"--timeout",
"46",
],
)
assert result.exit_code == 0
assert seen["host"] == "127.0.0.1"
assert seen["port"] == 18901
assert seen["request_timeout"] == 46.0
assert seen["api_key"] == "secret"
def test_serve_allows_loopback_without_api_key(monkeypatch, tmp_path: Path) -> None:
config_file = _write_instance_config(tmp_path)
config = Config()
seen: dict[str, object] = {}
_patch_serve_runtime(monkeypatch, config, seen)
result = runner.invoke(app, ["serve", "--config", str(config_file)])
assert result.exit_code == 0
assert seen["host"] == "127.0.0.1"
assert seen["api_key"] == ""
def test_serve_passes_configured_api_key(monkeypatch, tmp_path: Path) -> None:
config_file = _write_instance_config(tmp_path)
config = Config()
config.api.api_key = " secret "
seen: dict[str, object] = {}
_patch_serve_runtime(monkeypatch, config, seen)
result = runner.invoke(app, ["serve", "--config", str(config_file)])
assert result.exit_code == 0
assert seen["api_key"] == "secret"
def test_serve_rejects_wildcard_host_without_api_key(monkeypatch, tmp_path: Path) -> None:
config_file = _write_instance_config(tmp_path)
config = Config()
seen: dict[str, object] = {}
_patch_serve_runtime(monkeypatch, config, seen)
result = runner.invoke(app, ["serve", "--config", str(config_file), "--host", "0.0.0.0"])
assert result.exit_code == 1
assert "api_key is not set" in result.stdout
assert "workspace" not in seen
assert "api_app" not in seen
def test_serve_rejects_specific_network_interface_without_api_key(
monkeypatch,
tmp_path: Path,
) -> None:
config_file = _write_instance_config(tmp_path)
config = Config()
seen: dict[str, object] = {}
_patch_serve_runtime(monkeypatch, config, seen)
result = runner.invoke(
app,
["serve", "--config", str(config_file), "--host", "192.168.1.10"],
)
assert result.exit_code == 1
assert "api_key" in result.stdout
assert "prevent unauthenticated access" in result.stdout
assert "api_app" not in seen
def test_channels_login_requires_channel_name() -> None: def test_channels_login_requires_channel_name() -> None:
result = runner.invoke(app, ["channels", "login"]) result = runner.invoke(app, ["channels", "login"])
+19
View File
@@ -1,4 +1,5 @@
import json import json
import os
import subprocess import subprocess
import sys import sys
from pathlib import Path from pathlib import Path
@@ -79,6 +80,24 @@ def test_home_rejects_file(tmp_path):
assert result.exit_code == 2 assert result.exit_code == 2
@pytest.mark.parametrize("legacy_args", [[], ["--help"], ["--host", "0.0.0.0", "-p", "8900", "-c", "old-config.json"]])
def test_retired_serve_prints_migration_hint_without_initializing(tmp_path, legacy_args):
instance = tmp_path / "old API instance"
result = subprocess.run(
[sys.executable, "-m", "nanobot", "--home", str(instance), "serve", *legacy_args],
cwd=Path(__file__).parents[2],
env=dict(os.environ, HOME=str(tmp_path), USERPROFILE=str(tmp_path)),
capture_output=True, text=True, encoding="utf-8", check=False, timeout=20,
)
assert result.returncode == 2, result.stderr
assert result.stdout == ""
assert "'nanobot serve' has been removed" in result.stderr
assert "'nanobot webui'" in result.stderr
assert "/v1 endpoints have no drop-in replacement" in result.stderr
assert "old-config.json" not in result.stderr
assert not instance.exists()
def test_home_bare_command_starts_agent_and_restores_selection(monkeypatch, tmp_path): def test_home_bare_command_starts_agent_and_restores_selection(monkeypatch, tmp_path):
from nanobot.cli import entry from nanobot.cli import entry
-1
View File
@@ -21,7 +21,6 @@ def isolate_config_path(monkeypatch: pytest.MonkeyPatch) -> None:
["agent", "--message", "hello"], ["agent", "--message", "hello"],
["gateway", "--foreground"], ["gateway", "--foreground"],
["gateway", "--background"], ["gateway", "--background"],
["serve"],
["webui", "--yes", "--no-open"], ["webui", "--yes", "--no-open"],
], ],
) )
+21 -11
View File
@@ -3,8 +3,7 @@ import json
import pytest import pytest
from nanobot.config.errors import ConfigLoadError from nanobot.config.errors import ConfigLoadError
from nanobot.config.loader import load_config, resolve_config_env_vars from nanobot.config.loader import load_config, resolve_config_env_vars, save_config
from nanobot.config.schema import ApiConfig
def test_load_config_missing_file_uses_defaults(tmp_path) -> None: def test_load_config_missing_file_uses_defaults(tmp_path) -> None:
@@ -173,14 +172,25 @@ def test_load_config_malformed_legacy_sections_use_structured_error(
assert "tools" in str(error) assert "tools" in str(error)
@pytest.mark.parametrize("host", ["0.0.0.0", "::"]) def test_loads_pre_removal_config_without_the_retired_service_secret(tmp_path, monkeypatch) -> None:
def test_api_config_requires_key_for_wildcard_hosts(host: str) -> None: config_path = tmp_path / "config.json"
with pytest.raises(ValueError, match="api_key is not set"): monkeypatch.delenv("REMOVED_SERVE_TOKEN", raising=False)
ApiConfig(host=host) legacy = json.dumps({
"api": {"host": "0.0.0.0", "port": 8900, "apiKey": "${REMOVED_SERVE_TOKEN}"},
"gateway": {"port": 18791},
"providers": {"custom": {"apiBase": "http://model:8000/v1"}},
})
config_path.write_text(legacy, encoding="utf-8")
stored = load_config(config_path)
config = resolve_config_env_vars(stored, config_path=config_path)
assert config.gateway.port == 18791
assert config.providers.custom.api_base == "http://model:8000/v1"
assert config_path.read_text(encoding="utf-8") == legacy
def test_api_config_allows_wildcard_host_with_key() -> None: stored.gateway.port = 18792
config = ApiConfig(host="0.0.0.0", api_key="secret") save_config(stored, config_path)
saved = json.loads(config_path.read_text(encoding="utf-8"))
assert config.host == "0.0.0.0" assert "api" not in saved
assert config.api_key == "secret" assert saved["gateway"]["port"] == 18792
assert saved["providers"]["custom"]["apiBase"] == "http://model:8000/v1"
+1 -1
View File
@@ -40,7 +40,7 @@ class RuntimeImportBlocker(importlib.abc.MetaPathFinder):
if fullname in config_modules: if fullname in config_modules:
return None return None
forbidden = ( forbidden = (
'nanobot.agent', 'nanobot.api', 'nanobot.apps', 'nanobot.channels', 'nanobot.agent', 'nanobot.apps', 'nanobot.channels',
'nanobot.cli', 'nanobot.session', 'nanobot.webui', 'nanobot.providers.base', 'nanobot.cli', 'nanobot.session', 'nanobot.webui', 'nanobot.providers.base',
) )
if any(fullname == name or fullname.startswith(name + '.') for name in forbidden): if any(fullname == name or fullname.startswith(name + '.') for name in forbidden):
-57
View File
@@ -1,57 +0,0 @@
from pathlib import Path
from nanobot.api.runtime import ApiRuntime, ApiStartOptions, api_runtime_paths
class FakeProcess:
pid = 23456
def test_api_runtime_uses_isolated_paths(tmp_path: Path) -> None:
paths = api_runtime_paths(tmp_path / "config.json")
assert paths.state_path.parent == tmp_path / "run"
assert paths.state_path.name.startswith("api.")
assert paths.log_path.parent == tmp_path / "logs"
def test_api_runtime_builds_detached_serve_command(tmp_path: Path, monkeypatch) -> None:
calls: list[list[str]] = []
def fake_popen(command, **_kwargs):
calls.append(command)
return FakeProcess()
runtime = ApiRuntime(
paths=api_runtime_paths(tmp_path / "config.json"),
platform_name="Linux",
python_executable="/python",
popen=fake_popen,
sleep=lambda _seconds: None,
)
monkeypatch.setattr(runtime, "_is_pid_running", lambda _pid: True)
monkeypatch.setattr(runtime, "_process_identity", lambda _pid: 23456)
result = runtime.start_background(ApiStartOptions(
host="0.0.0.0",
port=9900,
workspace="/tmp/workspace",
config_path="/tmp/config.json",
))
assert result.ok is True
assert result.message == "api_started_background"
assert calls == [[
"/python",
"-m",
"nanobot",
"serve",
"--host",
"0.0.0.0",
"--port",
"9900",
"--workspace",
"/tmp/workspace",
"--config",
"/tmp/config.json",
]]
-440
View File
@@ -1,440 +0,0 @@
from __future__ import annotations
import base64
import subprocess
import sys
from io import BytesIO
from pathlib import Path
from unittest.mock import AsyncMock, MagicMock
import pytest
import pytest_asyncio
from nanobot.api.server import (
_FileSizeExceeded,
_parse_json_content,
_save_base64_data_url,
create_app,
)
try:
from aiohttp.test_utils import TestClient, TestServer
HAS_AIOHTTP = True
except ImportError:
HAS_AIOHTTP = False
pytest_plugins = ("pytest_asyncio",)
API_KEY = "secret"
AUTH_HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def _make_mock_agent(response_text: str = "mock response") -> MagicMock:
agent = MagicMock()
agent.process_direct = AsyncMock(return_value=response_text)
agent.aclose = AsyncMock()
return agent
@pytest.fixture
def mock_agent():
return _make_mock_agent()
@pytest_asyncio.fixture
async def aiohttp_client():
clients: list[TestClient] = []
async def _make_client(app):
client = TestClient(TestServer(app))
await client.start_server()
clients.append(client)
return client
try:
yield _make_client
finally:
for client in clients:
await client.close()
def test_save_base64_data_url_saves_png(tmp_path) -> None:
b64_data = base64.b64encode(b"fake png data").decode()
data_url = f"data:image/png;base64,{b64_data}"
result = _save_base64_data_url(data_url, tmp_path)
assert result is not None
assert result.endswith(".png")
assert (tmp_path / result.replace(str(tmp_path) + "/", "")).read_bytes() == b"fake png data"
def test_save_base64_data_url_handles_invalid_b64(tmp_path) -> None:
result = _save_base64_data_url("data:image/png;base64,not-valid-base64!!!", tmp_path)
assert result is None
def test_save_base64_data_url_handles_unknown_mime(tmp_path) -> None:
b64_data = base64.b64encode(b"some data").decode()
data_url = f"data:unknown/type;base64,{b64_data}"
result = _save_base64_data_url(data_url, tmp_path)
assert result is not None
assert result.endswith(".bin")
def test_save_base64_data_url_rejects_oversized_payload(tmp_path) -> None:
large_payload = base64.b64encode(b"x" * (11 * 1024 * 1024)).decode()
data_url = f"data:image/png;base64,{large_payload}"
with pytest.raises(_FileSizeExceeded, match="10MB limit"):
_save_base64_data_url(data_url, tmp_path)
def test_parse_json_content_extracts_text_and_media(tmp_path) -> None:
b64_data = base64.b64encode(b"img").decode()
body = {
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "describe this"},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64_data}"}},
],
}
]
}
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
text, media_paths = _parse_json_content(body)
assert text == "describe this"
assert len(media_paths) == 1
finally:
os.chdir(original_cwd)
def test_parse_json_content_rejects_malformed_parameter_header_without_stalling(tmp_path) -> None:
# Isolate the parser so a backtracking regression cannot hang the test runner.
code = """
import sys
from pathlib import Path
from unittest.mock import patch
from nanobot.api.server import _parse_json_content
media_dir = Path(sys.argv[1])
url = "data:image/png" + ";a" * 128 + ",eA=="
body = {"messages": [{"role": "user", "content": [
{"type": "text", "text": "describe this"},
{"type": "image_url", "image_url": {"url": url}},
]}]}
with patch("nanobot.api.server.get_media_dir", return_value=media_dir):
assert _parse_json_content(body) == ("describe this", [])
assert list(media_dir.iterdir()) == []
"""
result = subprocess.run(
[sys.executable, "-c", code, str(tmp_path)],
cwd=Path(__file__).resolve().parents[1],
capture_output=True, text=True, timeout=10,
)
assert result.returncode == 0, result.stderr
def test_parse_json_content_plain_text_only() -> None:
body = {"messages": [{"role": "user", "content": "hello"}]}
text, media_paths = _parse_json_content(body)
assert text == "hello"
assert media_paths == []
def test_parse_json_content_validates_single_message() -> None:
body = {
"messages": [
{"role": "user", "content": "first"},
{"role": "user", "content": "second"},
]
}
with pytest.raises(ValueError, match="single user message"):
_parse_json_content(body)
def test_parse_json_content_validates_user_role() -> None:
body = {"messages": [{"role": "system", "content": "you are a bot"}]}
with pytest.raises(ValueError, match="single user message"):
_parse_json_content(body)
@pytest.mark.parametrize(
("part", "field"),
[
({"type": "text", "text": 1}, r"content\[\]\.text"),
(
{"type": "image_url", "image_url": "not-an-object"},
r"content\[\]\.image_url",
),
(
{"type": "image_url", "image_url": {"url": 1}},
r"image_url\.url",
),
],
)
def test_parse_json_content_validates_typed_block_fields(part, field) -> None:
body = {"messages": [{"role": "user", "content": [part]}]}
with pytest.raises(TypeError, match=field):
_parse_json_content(body)
def test_parse_json_content_rejects_oversized_base64_file(tmp_path) -> None:
large_payload = base64.b64encode(b"x" * (11 * 1024 * 1024)).decode()
body = {
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "describe"},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{large_payload}"}},
],
}
]
}
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
with pytest.raises(_FileSizeExceeded, match="10MB limit"):
_parse_json_content(body)
finally:
os.chdir(original_cwd)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multipart_upload_saves_file(aiohttp_client, mock_agent, tmp_path) -> None:
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
file_data = b"test file content"
data = BytesIO(file_data)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
data={"message": "analyze this", "files": data},
)
assert resp.status == 200
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "analyze this"
assert len(call_kwargs.get("media") or []) == 1
finally:
os.chdir(original_cwd)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multipart_multiple_files(aiohttp_client, mock_agent, tmp_path, monkeypatch) -> None:
import aiohttp
media_dir = tmp_path / "media"
media_dir.mkdir()
monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: media_dir)
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
files = [("first.txt", b"first file content"), ("second.bin", b"\x00second file\xff")]
data = aiohttp.FormData()
data.add_field("message", "analyze both files")
for filename, payload in files:
data.add_field("files", payload, filename=filename, content_type="application/octet-stream")
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)
assert resp.status == 200
mock_agent.process_direct.assert_called_once()
mock_agent.process_direct.assert_awaited_once()
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "analyze both files"
saved_paths = [Path(path) for path in call_kwargs["media"]]
assert len(saved_paths) == 2
assert saved_paths[0] != saved_paths[1]
for path, (_, payload) in zip(saved_paths, files, strict=True):
assert path.parent == media_dir
assert path.read_bytes() == payload
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multipart_file_size_limit(aiohttp_client, mock_agent, tmp_path) -> None:
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
large_data = b"x" * (11 * 1024 * 1024)
data = BytesIO(large_data)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
data={"message": "analyze", "files": data},
)
assert resp.status == 413
finally:
os.chdir(original_cwd)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multipart_defaults_text_when_missing(aiohttp_client, mock_agent, tmp_path) -> None:
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
file_data = b"content"
data = BytesIO(file_data)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
data={"files": data},
)
assert resp.status == 200
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "请分析上传的文件"
finally:
os.chdir(original_cwd)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
@pytest.mark.parametrize(("session_id", "chat_id"), [
("my-session", "my-session"), (" my-session ", "my-session"), (" ", "default"),
])
async def test_multipart_with_session_id(
aiohttp_client, mock_agent, tmp_path, session_id, chat_id,
) -> None:
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
file_data = b"content"
data = BytesIO(file_data)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
data={"message": "hello", "session_id": session_id, "files": data},
)
assert resp.status == 200
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["session_key"] == f"api:{chat_id}"
assert call_kwargs["chat_id"] == chat_id
finally:
os.chdir(original_cwd)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_plain_text_backward_compat(aiohttp_client, mock_agent) -> None:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hello world"}]},
)
assert resp.status == 200
body = await resp.json()
assert body["choices"][0]["message"]["content"] == "mock response"
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "hello world"
assert call_kwargs.get("media") is None
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
@pytest.mark.parametrize("marker", ["base64", "BASE64", "Base64"])
async def test_json_base64_image_upload(
aiohttp_client, mock_agent, tmp_path, monkeypatch, marker: str,
) -> None:
monkeypatch.setattr("nanobot.api.server.get_media_dir", lambda _channel=None: tmp_path)
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
tiny_png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "what is this"},
{"type": "image_url", "image_url": {"url": f"data:image/png;{marker},{tiny_png_b64}"}},
],
}
]
},
)
assert resp.status == 200
mock_agent.process_direct.assert_awaited_once()
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "what is this"
saved, = call_kwargs["media"]
assert Path(saved).parent == tmp_path
assert Path(saved).read_bytes() == base64.b64decode(tiny_png_b64)
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_docx_upload_passes_media_path(aiohttp_client, tmp_path) -> None:
agent = _make_mock_agent("report summary")
import os
original_cwd = os.getcwd()
os.chdir(tmp_path)
try:
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
from docx import Document
doc = Document()
doc.add_paragraph("Total revenue: $5,000,000")
buf = BytesIO()
doc.save(buf)
import aiohttp
data = aiohttp.FormData()
data.add_field("message", "summarize the report")
data.add_field("files", buf.getvalue(), filename="report.docx",
content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, data=data)
assert resp.status == 200
call_kwargs = agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "summarize the report"
media = call_kwargs.get("media", [])
assert len(media) == 1
assert "report.docx" in media[0]
finally:
os.chdir(original_cwd)
-360
View File
@@ -1,360 +0,0 @@
from __future__ import annotations
import asyncio
import json
from unittest.mock import AsyncMock, MagicMock
import pytest
import pytest_asyncio
from nanobot.api.server import (
_SSE_DONE,
_sse_chunk,
create_app,
)
try:
from aiohttp.test_utils import TestClient, TestServer
HAS_AIOHTTP = True
except ImportError:
HAS_AIOHTTP = False
pytest_plugins = ("pytest_asyncio",)
API_KEY = "secret"
AUTH_HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def test_sse_chunk_with_delta() -> None:
raw = _sse_chunk("hello", "test-model", "chatcmpl-abc123")
line = raw.decode()
assert line.startswith("data: ")
payload = json.loads(line[len("data: "):])
assert payload["id"] == "chatcmpl-abc123"
assert payload["object"] == "chat.completion.chunk"
assert payload["model"] == "test-model"
assert payload["choices"][0]["delta"]["content"] == "hello"
assert payload["choices"][0]["finish_reason"] is None
def test_sse_chunk_finish_reason() -> None:
raw = _sse_chunk("", "m", "id1", finish_reason="stop")
payload = json.loads(raw.decode().split("data: ", 1)[1])
assert payload["choices"][0]["delta"] == {}
assert payload["choices"][0]["finish_reason"] == "stop"
def test_sse_done_format() -> None:
assert _SSE_DONE == b"data: [DONE]\n\n"
def _make_streaming_agent(tokens: list[str]) -> MagicMock:
"""Create a mock agent that streams tokens via on_stream callback."""
agent = MagicMock()
agent.aclose = AsyncMock()
async def fake_process_direct(*, content="", media=None, session_key="",
channel="", chat_id="", on_stream=None,
on_stream_end=None, **kwargs):
if on_stream:
for token in tokens:
await on_stream(token)
if on_stream_end:
await on_stream_end()
return " ".join(tokens)
agent.process_direct = fake_process_direct
return agent
@pytest_asyncio.fixture
async def aiohttp_client():
clients: list[TestClient] = []
async def _make_client(app):
client = TestClient(TestServer(app))
await client.start_server()
clients.append(client)
return client
try:
yield _make_client
finally:
for client in clients:
await client.close()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_true_returns_sse(aiohttp_client) -> None:
agent = _make_streaming_agent(["Hello", " world"])
app = create_app(agent, model_name="test-model", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
)
assert resp.status == 200
assert resp.content_type == "text/event-stream"
assert resp.headers["X-Request-ID"]
body = await resp.text()
lines = [line for line in body.split("\n") if line.startswith("data: ")]
data_lines = [line[len("data: "):] for line in lines]
assert data_lines[-1] == "[DONE]"
chunks = [json.loads(line) for line in data_lines[:-1]]
assert chunks[0]["choices"][0]["delta"]["content"] == "Hello"
assert chunks[1]["choices"][0]["delta"]["content"] == " world"
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
assert chunks[-1]["choices"][0]["delta"] == {}
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_false_returns_json(aiohttp_client) -> None:
agent = MagicMock()
agent.process_direct = AsyncMock(return_value="normal reply")
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": False},
)
assert resp.status == 200
body = await resp.json()
assert body["object"] == "chat.completion"
assert body["choices"][0]["message"]["content"] == "normal reply"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_default_is_false(aiohttp_client) -> None:
agent = MagicMock()
agent.process_direct = AsyncMock(return_value="default reply")
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}]},
)
assert resp.status == 200
body = await resp.json()
assert body["object"] == "chat.completion"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", ["false", "true", 0, 1, [], {}])
async def test_stream_rejects_non_boolean_values(aiohttp_client, stream) -> None:
agent = MagicMock()
agent.process_direct = AsyncMock(return_value="normal reply")
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": stream},
)
assert resp.status == 400
body = await resp.json()
assert body["error"]["message"] == "stream must be a boolean"
agent.process_direct.assert_not_called()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_null_preserves_non_streaming_compatibility(aiohttp_client) -> None:
agent = MagicMock()
agent.process_direct = AsyncMock(return_value="normal reply")
agent.aclose = AsyncMock()
client = await aiohttp_client(create_app(agent, model_name="m", api_key=API_KEY))
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": None},
)
assert resp.status == 200
assert resp.content_type == "application/json"
assert (await resp.json())["choices"][0]["message"]["content"] == "normal reply"
agent.process_direct.assert_awaited_once()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_sse_chunk_ids_are_consistent(aiohttp_client) -> None:
agent = _make_streaming_agent(["A", "B", "C"])
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "go"}], "stream": True},
)
body = await resp.text()
data_lines = [
line[len("data: "):]
for line in body.split("\n")
if line.startswith("data: ") and line != "data: [DONE]"
]
chunks = [json.loads(line) for line in data_lines]
chunk_ids = {c["id"] for c in chunks}
assert len(chunk_ids) == 1, f"Expected single chunk id, got {chunk_ids}"
assert chunk_ids.pop().startswith("chatcmpl-")
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_segment_end_does_not_close_sse(aiohttp_client) -> None:
agent = MagicMock()
async def fake_process_direct(*, on_stream=None, on_stream_end=None, **kwargs):
assert on_stream is not None
assert on_stream_end is not None
await on_stream("planning")
await on_stream_end(resuming=True)
await asyncio.sleep(0)
await on_stream(" final")
await on_stream_end(resuming=False)
return "planning final"
agent.process_direct = fake_process_direct
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "use a tool"}], "stream": True},
)
assert resp.status == 200
body = await resp.text()
data_lines = [
line[len("data: "):] for line in body.split("\n") if line.startswith("data: ")
]
assert data_lines[-1] == "[DONE]"
chunks = [json.loads(line) for line in data_lines[:-1]]
deltas = [c["choices"][0]["delta"].get("content", "") for c in chunks]
assert "planning" in deltas
assert " final" in deltas
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_uses_final_response_when_no_deltas(aiohttp_client) -> None:
agent = MagicMock()
async def fake_process_direct(*, on_stream=None, on_stream_end=None, **kwargs):
assert on_stream is not None
assert on_stream_end is not None
await on_stream_end(resuming=False)
return "plain final"
agent.process_direct = fake_process_direct
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
)
assert resp.status == 200
body = await resp.text()
data_lines = [
line[len("data: "):] for line in body.split("\n") if line.startswith("data: ")
]
chunks = [json.loads(line) for line in data_lines[:-1]]
deltas = [c["choices"][0]["delta"].get("content", "") for c in chunks]
assert "plain final" in deltas
assert data_lines[-1] == "[DONE]"
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_stream_with_session_id(aiohttp_client) -> None:
captured_key: str = ""
async def fake_process_direct(*, session_key="", on_stream=None, on_stream_end=None, **kwargs):
nonlocal captured_key
captured_key = session_key
if on_stream:
await on_stream("ok")
if on_stream_end:
await on_stream_end()
return "ok"
agent = MagicMock()
agent.process_direct = fake_process_direct
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={
"messages": [{"role": "user", "content": "hi"}],
"stream": True,
"session_id": "my-session",
},
)
assert resp.status == 200
assert captured_key == "api:my-session"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_streaming_backend_failure_does_not_emit_success_terminator(aiohttp_client) -> None:
agent = MagicMock()
async def boom(**kwargs):
raise RuntimeError("backend blew up")
agent.process_direct = boom
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hi"}], "stream": True},
)
assert resp.status == 200
body = await resp.text()
assert '"finish_reason": "stop"' not in body
assert "[DONE]" not in body
+9 -11
View File
@@ -12,8 +12,8 @@ from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.config.loader import load_config, resolve_config_env_vars from nanobot.config.loader import load_config, resolve_config_env_vars
def _initialize(path: Path, web_token: str = "", api_key: str = "") -> subprocess.CompletedProcess[str]: def _initialize(path: Path, web_token: str = "") -> subprocess.CompletedProcess[str]:
env = dict(os.environ, NANOBOT_WEB_TOKEN=web_token, NANOBOT_API_KEY=api_key) env = dict(os.environ, NANOBOT_WEB_TOKEN=web_token)
return subprocess.run( return subprocess.run(
[sys.executable, "-m", "nanobot.cli.docker_bootstrap", str(path)], [sys.executable, "-m", "nanobot.cli.docker_bootstrap", str(path)],
env=env, capture_output=True, text=True, env=env, capture_output=True, text=True,
@@ -33,36 +33,34 @@ def test_first_boot_generates_valid_container_config(tmp_path):
assert result.returncode == 0, result.stderr assert result.returncode == 0, result.stderr
config = resolve_config_env_vars(load_config(path)) config = resolve_config_env_vars(load_config(path))
ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"]) ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"])
assert config.gateway.host == ws.host == config.api.host == "0.0.0.0" assert config.gateway.host == ws.host == "0.0.0.0"
assert ws.enabled and ws.websocket_requires_token assert ws.enabled and ws.websocket_requires_token
assert len(ws.token_issue_secret) == len(config.api.api_key) == 32 assert len(ws.token_issue_secret) == 32
assert ws.token_issue_secret != config.api.api_key
assert ws.token_issue_secret in result.stdout assert ws.token_issue_secret in result.stdout
assert config.api.api_key in result.stdout
@pytest.mark.parametrize("secret", ['review&secret', 'review|secret', 'review"secret', r'review\secret']) @pytest.mark.parametrize("secret", ['review&secret', 'review|secret', 'review"secret', r'review\secret'])
def test_custom_secrets_survive_json_serialization(tmp_path, secret): def test_custom_secrets_survive_json_serialization(tmp_path, secret):
path = tmp_path / "config.json" path = tmp_path / "config.json"
result = _initialize(path, secret, secret) result = _initialize(path, secret)
assert result.returncode == 0, result.stderr assert result.returncode == 0, result.stderr
config = resolve_config_env_vars(load_config(path)) config = resolve_config_env_vars(load_config(path))
ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"]) ws = WebSocketConfig.model_validate(config.channels.model_dump()["websocket"])
assert ws.token_issue_secret == config.api.api_key == secret assert ws.token_issue_secret == secret
def test_restart_preserves_user_settings_and_credentials(tmp_path): def test_restart_preserves_user_settings_and_credentials(tmp_path):
path = tmp_path / "config.json" path = tmp_path / "config.json"
assert _initialize(path, "original-web", "original-api").returncode == 0 assert _initialize(path, "original-web").returncode == 0
data = json.loads(path.read_text(encoding="utf-8")) data = json.loads(path.read_text(encoding="utf-8"))
data["api"] = {"host": "0.0.0.0", "apiKey": "${RETIRED_SERVE_TOKEN}"}
data["providers"]["custom"] = {"apiKey": "provider-key", "apiBase": "http://model:8000/v1"} data["providers"]["custom"] = {"apiKey": "provider-key", "apiBase": "http://model:8000/v1"}
path.write_text(json.dumps(data), encoding="utf-8") path.write_text(json.dumps(data), encoding="utf-8")
previous = path.read_bytes() previous = path.read_bytes()
result = _initialize(path, "replacement-web", "replacement-api") result = _initialize(path, "replacement-web")
assert result.returncode == 0, result.stderr assert result.returncode == 0, result.stderr
assert path.read_bytes() == previous assert path.read_bytes() == previous
assert "replacement-web" not in result.stdout assert "replacement-web" not in result.stdout
assert "replacement-api" not in result.stdout
def test_failed_write_does_not_leave_an_existing_config(tmp_path): def test_failed_write_does_not_leave_an_existing_config(tmp_path):
-650
View File
@@ -1,650 +0,0 @@
from __future__ import annotations
import asyncio
import json
from unittest.mock import AsyncMock, MagicMock
import pytest
import pytest_asyncio
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentRunHookContext
from nanobot.api.server import (
API_CHAT_ID,
API_SESSION_KEY,
_chat_completion_response,
_error_json,
create_app,
handle_chat_completions,
)
from nanobot.providers.base import LLMUsage
from nanobot.providers.unconfigured_provider import UnconfiguredProvider
try:
from aiohttp.test_utils import TestClient, TestServer
HAS_AIOHTTP = True
except ImportError:
HAS_AIOHTTP = False
pytest_plugins = ("pytest_asyncio",)
API_KEY = "secret"
AUTH_HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def _make_mock_agent(response_text: str = "mock response") -> MagicMock:
agent = MagicMock()
agent.process_direct = AsyncMock(return_value=response_text)
agent.aclose = AsyncMock()
return agent
@pytest.fixture
def mock_agent():
return _make_mock_agent()
@pytest.fixture
def app(mock_agent):
return create_app(mock_agent, model_name="test-model", request_timeout=10.0, api_key=API_KEY)
@pytest_asyncio.fixture
async def aiohttp_client():
clients: list[TestClient] = []
async def _make_client(app):
client = TestClient(TestServer(app))
await client.start_server()
clients.append(client)
return client
try:
yield _make_client
finally:
for client in clients:
await client.close()
def test_error_json() -> None:
resp = _error_json(400, "bad request")
assert resp.status == 400
body = json.loads(resp.body)
assert body["error"]["message"] == "bad request"
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:
result = _chat_completion_response("hello world", "test-model")
assert result["object"] == "chat.completion"
assert result["model"] == "test-model"
assert result["choices"][0]["message"]["content"] == "hello world"
assert result["choices"][0]["finish_reason"] == "stop"
assert result["id"].startswith("chatcmpl-")
assert result["usage"]["prompt_tokens"] == 0
assert result["usage"]["completion_tokens"] == 0
assert result["usage"]["total_tokens"] == 0
def test_chat_completion_response_with_usage() -> None:
usage = LLMUsage.reported(input_tokens=150, output_tokens=42)
result = _chat_completion_response("hello world", "test-model", usage)
assert result["usage"]["prompt_tokens"] == 150
assert result["usage"]["completion_tokens"] == 42
assert result["usage"]["total_tokens"] == 192
def test_chat_completion_response_preserves_explicit_total_usage() -> None:
usage = LLMUsage.reported(input_tokens=70, output_tokens=7, total_tokens=175)
result = _chat_completion_response("hello world", "test-model", usage)
assert result["usage"]["prompt_tokens"] == 70
assert result["usage"]["completion_tokens"] == 7
assert result["usage"]["total_tokens"] == 175
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_missing_messages_returns_400(aiohttp_client, app) -> None:
client = await aiohttp_client(app)
resp = await client.post("/v1/chat/completions", headers=AUTH_HEADERS, json={"model": "test"})
assert resp.status == 400
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_key_protects_api_routes_but_not_health(aiohttp_client, mock_agent) -> None:
app = create_app(mock_agent, model_name="test-model", api_key=API_KEY)
client = await aiohttp_client(app)
health = await client.get("/health")
missing = await client.get("/v1/models")
wrong = await client.get("/v1/models", headers={"Authorization": "Bearer wrong"})
ok = await client.get("/v1/models", headers=AUTH_HEADERS)
assert health.status == 200
assert missing.status == 401
assert wrong.status == 401
assert ok.status == 200
assert health.headers["X-Request-ID"]
assert ok.headers["X-Request-ID"]
assert health.headers["X-Request-ID"] != ok.headers["X-Request-ID"]
assert (await missing.json())["error"]["message"].startswith("Missing Authorization")
assert (await wrong.json())["error"]["message"] == "Invalid API key"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_request_log_has_correlation_and_completion_fields(
aiohttp_client, mock_agent
) -> None:
records = []
sink = logger.add(lambda message: records.append(message.record), level="INFO")
try:
client = await aiohttp_client(create_app(mock_agent, api_key=API_KEY))
response = await client.get("/v1/models", headers=AUTH_HEADERS)
finally:
logger.remove(sink)
completion = next(
record for record in records if record["extra"].get("event") == "http_request"
)
assert completion["extra"]["request_id"] == response.headers["X-Request-ID"]
assert completion["extra"]["outcome"] == "success"
assert completion["extra"]["status_code"] == 200
assert completion["extra"]["duration_ms"] >= 0
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_routes_allow_requests_without_configured_api_key(aiohttp_client, mock_agent) -> None:
app = create_app(mock_agent, model_name="test-model")
client = await aiohttp_client(app)
health = await client.get("/health")
models = await client.get("/v1/models")
chat = await client.post(
"/v1/chat/completions",
json={"messages": [{"role": "user", "content": "hello"}]},
)
assert health.status == 200
assert models.status == 200
assert chat.status == 200
mock_agent.process_direct.assert_called_once()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_prepares_application_resources_before_each_turn(aiohttp_client) -> None:
events: list[str] = []
agent = _make_mock_agent()
async def prepare_agent() -> None:
events.append("prepare")
async def process_direct(**_kwargs):
events.append("process")
return "ready"
agent.process_direct = process_direct
app = create_app(agent, prepare_agent=prepare_agent)
client = await aiohttp_client(app)
response = await client.post(
"/v1/chat/completions",
json={"messages": [{"role": "user", "content": "hello"}]},
)
assert response.status == 200
assert events == ["prepare", "process"]
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_api_preparation_is_bounded_by_request_timeout(aiohttp_client) -> None:
agent = _make_mock_agent()
started = asyncio.Event()
async def prepare_agent() -> None:
started.set()
await asyncio.Event().wait()
app = create_app(
agent,
request_timeout=0.01,
prepare_agent=prepare_agent,
)
client = await aiohttp_client(app)
response = await client.post(
"/v1/chat/completions",
json={"messages": [{"role": "user", "content": "hello"}]},
)
assert started.is_set()
assert response.status == 504
agent.process_direct.assert_not_awaited()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_no_user_message_returns_400(aiohttp_client, app) -> None:
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "system", "content": "you are a bot"}]},
)
assert resp.status == 400
@pytest.mark.asyncio
async def test_model_mismatch_returns_400() -> None:
request = MagicMock()
request.json = AsyncMock(
return_value={
"model": "other-model",
"messages": [{"role": "user", "content": "hello"}],
}
)
request.app = create_app(_make_mock_agent(), model_name="test-model", request_timeout=10.0)
resp = await handle_chat_completions(request)
assert resp.status == 400
body = json.loads(resp.body)
assert "test-model" in body["error"]["message"]
@pytest.mark.asyncio
async def test_single_user_message_required() -> None:
request = MagicMock()
request.json = AsyncMock(
return_value={
"messages": [
{"role": "user", "content": "hello"},
{"role": "assistant", "content": "previous reply"},
],
}
)
request.app = create_app(_make_mock_agent(), model_name="test-model", request_timeout=10.0)
resp = await handle_chat_completions(request)
assert resp.status == 400
body = json.loads(resp.body)
assert "single user message" in body["error"]["message"].lower()
@pytest.mark.asyncio
async def test_single_user_message_must_have_user_role() -> None:
request = MagicMock()
request.json = AsyncMock(
return_value={
"messages": [{"role": "system", "content": "you are a bot"}],
}
)
request.app = create_app(_make_mock_agent(), model_name="test-model", request_timeout=10.0)
resp = await handle_chat_completions(request)
assert resp.status == 400
body = json.loads(resp.body)
assert "single user message" in body["error"]["message"].lower()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_successful_request_uses_fixed_api_session_and_run_usage(
aiohttp_client,
mock_agent,
) -> None:
usage = LLMUsage.reported(input_tokens=100, output_tokens=50)
async def process_direct(*, hooks: list[AgentHook], **_kwargs: object) -> str:
for hook in hooks:
await hook.after_run(AgentRunHookContext(messages=[], usage=usage))
return "mock response"
mock_agent.process_direct = AsyncMock(side_effect=process_direct)
app = create_app(mock_agent, model_name="test-model", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hello"}]},
)
assert resp.status == 200
body = await resp.json()
assert body["choices"][0]["message"]["content"] == "mock response"
assert body["model"] == "test-model"
assert body["usage"] == {
"prompt_tokens": 100,
"completion_tokens": 50,
"total_tokens": 150,
}
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "hello"
assert call_kwargs["media"] is None
assert call_kwargs["session_key"] == API_SESSION_KEY
assert call_kwargs["channel"] == "api"
assert call_kwargs["chat_id"] == API_CHAT_ID
assert len(call_kwargs["hooks"]) == 1
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_followup_requests_share_same_session_key(aiohttp_client) -> None:
call_log: list[str] = []
async def fake_process(content, session_key="", channel="", chat_id="", **kwargs):
call_log.append(session_key)
return f"reply to {content}"
agent = MagicMock()
agent.process_direct = fake_process
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
r1 = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "first"}]},
)
r2 = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "second"}]},
)
assert r1.status == 200
assert r2.status == 200
assert call_log == [API_SESSION_KEY, API_SESSION_KEY]
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize(("session_id", "chat_id"), [
("chat-a", "chat-a"),
(" chat-a ", " chat-a "),
(" ", " "),
("api:chat-a", "api:chat-a"),
("会话:a", "会话:a"),
("default", "default"),
(None, "default"),
("", "default"),
(0, "default"),
(42, "42"),
({"id": 1}, "{'id': 1}"),
])
async def test_session_route_preserves_existing_json_identity(
aiohttp_client, mock_agent, session_id, chat_id, stream,
) -> None:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={
"messages": [{"role": "user", "content": "hi"}],
"session_id": session_id, "stream": stream,
},
)
assert resp.status == 200
await resp.read()
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["session_key"] == f"api:{chat_id}"
assert call_kwargs["channel"] == "api"
assert call_kwargs["chat_id"] == chat_id
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_fixed_session_requests_are_serialized(aiohttp_client) -> None:
order: list[str] = []
first_started = asyncio.Event()
release_first = asyncio.Event()
async def slow_process(content, session_key="", channel="", chat_id="", **kwargs):
order.append(f"start:{content}")
if content == "first":
first_started.set()
await release_first.wait()
order.append(f"end:{content}")
return content
agent = MagicMock()
agent.process_direct = slow_process
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
async def send(msg: str):
return await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": msg}]},
)
first = asyncio.create_task(send("first"))
await asyncio.wait_for(first_started.wait(), timeout=1.0)
second = asyncio.create_task(send("second"))
await asyncio.sleep(0)
assert order == ["start:first"]
release_first.set()
r1, r2 = await asyncio.gather(first, second)
assert r1.status == 200
assert r2.status == 200
assert order == ["start:first", "end:first", "start:second", "end:second"]
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_models_endpoint(aiohttp_client, app) -> None:
client = await aiohttp_client(app)
resp = await client.get("/v1/models", headers=AUTH_HEADERS)
assert resp.status == 200
body = await resp.json()
assert body["object"] == "list"
assert body["data"][0]["id"] == "test-model"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_health_endpoint(aiohttp_client, app) -> None:
client = await aiohttp_client(app)
resp = await client.get("/health")
assert resp.status == 200
body = await resp.json()
assert body["status"] == "ok"
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multimodal_content_extracts_text(aiohttp_client, mock_agent) -> None:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "describe this"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,abc"}},
],
}
]
},
)
assert resp.status == 200
call_kwargs = mock_agent.process_direct.call_args.kwargs
assert call_kwargs["content"] == "describe this"
assert call_kwargs["session_key"] == API_SESSION_KEY
assert call_kwargs["channel"] == "api"
assert call_kwargs["chat_id"] == API_CHAT_ID
assert len(call_kwargs.get("media") or []) >= 0
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
@pytest.mark.parametrize(
("content_part", "expected_error"),
[
({"type": "text", "text": 123}, "messages[0].content[].text must be a string"),
(
{"type": "image_url", "image_url": "not-an-object"},
"messages[0].content[].image_url must be an object",
),
(
{"type": "image_url", "image_url": {"url": 123}},
"messages[0].content[].image_url.url must be a string",
),
],
)
async def test_multimodal_invalid_field_type_returns_400(
aiohttp_client,
mock_agent,
content_part: dict[str, object],
expected_error: str,
) -> None:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={
"messages": [
{
"role": "user",
"content": [content_part],
}
]
},
)
assert resp.status == 400
body = await resp.json()
assert body["error"]["message"] == expected_error
assert body["error"]["code"] == 400
mock_agent.process_direct.assert_not_called()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_multimodal_remote_image_url_returns_400(aiohttp_client, mock_agent) -> None:
app = create_app(mock_agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={
"messages": [
{
"role": "user",
"content": [
{"type": "text", "text": "describe this"},
{"type": "image_url", "image_url": {"url": "https://example.com/image.png"}},
],
}
]
},
)
assert resp.status == 400
body = await resp.json()
assert "remote image urls are not supported" in body["error"]["message"].lower()
mock_agent.process_direct.assert_not_called()
@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed")
@pytest.mark.asyncio
async def test_empty_response_falls_back_without_retry(aiohttp_client) -> None:
from nanobot.utils.runtime import EMPTY_FINAL_RESPONSE_MESSAGE
call_count = 0
async def always_empty(content, session_key="", channel="", chat_id="", **kwargs):
nonlocal call_count
call_count += 1
return ""
agent = MagicMock()
agent.process_direct = always_empty
agent.aclose = AsyncMock()
app = create_app(agent, model_name="m", api_key=API_KEY)
client = await aiohttp_client(app)
resp = await client.post(
"/v1/chat/completions",
headers=AUTH_HEADERS,
json={"messages": [{"role": "user", "content": "hello"}]},
)
assert resp.status == 200
body = await resp.json()
assert body["choices"][0]["message"]["content"] == EMPTY_FINAL_RESPONSE_MESSAGE
assert call_count == 1
@pytest.mark.asyncio
async def test_process_direct_accepts_media() -> None:
from nanobot.agent.loop import AgentLoop
from nanobot.agent.turn_delivery import TurnDeliveryFactory
from nanobot.bus.queue import MessageBus
loop = AgentLoop.__new__(AgentLoop)
loop._session_locks = {}
loop.bus = MessageBus()
loop.turn_delivery_factory = TurnDeliveryFactory(loop.bus)
loop.runtime_event_publisher = loop.turn_delivery_factory.runtime_event_publisher
captured_msg = None
async def fake_process(
msg, *, session_key="", on_progress=None, on_stream=None, on_stream_end=None, ephemeral=False, delivery=None,
):
nonlocal captured_msg
captured_msg = msg
return None
loop._process_message = fake_process
await loop.process_direct(
content="analyze this",
media=["/tmp/image.png", "/tmp/report.pdf"],
session_key="test:1",
)
assert captured_msg is not None
assert captured_msg.media == ["/tmp/image.png", "/tmp/report.pdf"]
assert captured_msg.content == "analyze this"
-184
View File
@@ -1,184 +0,0 @@
from __future__ import annotations
import asyncio
import json
from contextlib import asynccontextmanager
from copy import deepcopy
import pytest
from aiohttp import web
from aiohttp.test_utils import TestClient, TestServer
from nanobot.agent.loop import AgentLoop
from nanobot.agent.tools.context import current_request_context
from nanobot.api.server import API_CHAT_ID, API_SESSION_KEY, create_app
from nanobot.bus.queue import MessageBus
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
pytestmark = pytest.mark.asyncio
AUTH = {"Authorization": "Bearer test-api-key"}
class RouteProvider(LLMProvider):
def __init__(self, *, hold_first=False):
super().__init__(provider_name="offline-api-test")
self.calls = []
self.hold_first = hold_first
self.started = asyncio.Event()
self.release = asyncio.Event()
def get_default_model(self):
return "offline-api-test"
async def chat(self, messages, tools=None, **kwargs):
ctx = current_request_context()
assert ctx is not None
self.calls.append({
"session_key": ctx.session_key,
"messages": deepcopy(self._sanitize_empty_content(messages)),
"tools": deepcopy(tools),
})
if self.hold_first and len(self.calls) == 1:
self.started.set()
await asyncio.wait_for(self.release.wait(), 10)
if messages[-1]["role"] != "tool":
call_number = 1 + sum(len(message.get("tool_calls", [])) for message in messages)
return LLMResponse(content=None, tool_calls=[ToolCallRequest(
id=f"inspect-route-{call_number}", name="my",
arguments={"action": "check", "key": "request.chat_id"},
)])
return LLMResponse(content=json.dumps({
"session_key": ctx.session_key,
"chat_id": ctx.chat_id,
"tool_result": messages[-1]["content"],
}))
async def chat_stream(self, messages, tools=None, on_content_delta=None, **kwargs):
response = await self.chat(messages, tools, **kwargs)
if response.content and on_content_delta:
midpoint = len(response.content) // 2
await on_content_delta(response.content[:midpoint])
await on_content_delta(response.content[midpoint:])
return response
@asynccontextmanager
async def runtime(workspace, provider, *, received=None):
agent = AgentLoop(
bus=MessageBus(), provider=provider, workspace=workspace,
restrict_to_workspace=True, max_iterations=3,
)
app = create_app(agent, api_key="test-api-key")
if received is not None:
@web.middleware
async def observe_request(request, handler):
body = await request.json()
if body["messages"][0]["content"] == "SECOND_TURN":
received.set()
return await handler(request)
app.middlewares.append(observe_request)
client = TestClient(TestServer(app))
try:
await client.start_server()
yield agent, client
finally:
await client.close()
await agent.aclose()
async def post(client, session_id, text, stream=False):
response = await client.post(
"/v1/chat/completions", headers=AUTH,
json={
"session_id": session_id, "stream": stream,
"messages": [{"role": "user", "content": text}],
},
)
assert response.status == 200, await response.text()
if not stream:
return json.loads((await response.json())["choices"][0]["message"]["content"])
body = await response.text()
assert body.endswith("data: [DONE]\n\n")
chunks = [json.loads(line[6:]) for line in body.splitlines()
if line.startswith("data: ") and line != "data: [DONE]"]
assert chunks[-1]["choices"][0]["finish_reason"] == "stop"
assert len({chunk["id"] for chunk in chunks}) == 1
return json.loads("".join(chunk["choices"][0]["delta"].get("content", "") for chunk in chunks))
def assert_route(result, chat_id):
assert result["session_key"] == f"api:{chat_id}"
assert result["chat_id"] == chat_id
assert result["tool_result"] == f"request.chat_id: {chat_id!r}"
def assert_prefix(previous, following):
assert json.dumps(previous["messages"], ensure_ascii=False) == json.dumps(
following["messages"][:len(previous["messages"])], ensure_ascii=False,
)
assert json.dumps(previous["tools"], ensure_ascii=False) == json.dumps(
following["tools"], ensure_ascii=False,
)
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("second_id", ["alpha", " alpha ", "beta"])
async def test_concurrent_requests_keep_routes_history_and_order(tmp_path, stream, second_id):
provider = RouteProvider(hold_first=True)
received = asyncio.Event()
async with runtime(tmp_path / "workspace", provider, received=received) as (_, client):
first = asyncio.create_task(post(client, "alpha", "FIRST_TURN", stream))
tasks = [first]
try:
await asyncio.wait_for(provider.started.wait(), 10)
second = asyncio.create_task(post(client, second_id, "SECOND_TURN", stream))
tasks.append(second)
await asyncio.wait_for(received.wait(), 10)
if second_id == "alpha":
assert len(provider.calls) == 1
assert not second.done()
provider.release.set()
else:
assert_route(await asyncio.wait_for(second, 10), second_id)
assert not first.done()
provider.release.set()
assert_route(await asyncio.wait_for(first, 10), "alpha")
assert_route(await asyncio.wait_for(second, 10), second_id)
second_call = next(call for call in provider.calls
if "SECOND_TURN" in json.dumps(call["messages"]))
assert ("FIRST_TURN" in json.dumps(second_call["messages"])) == (second_id == "alpha")
finally:
provider.release.set()
await asyncio.gather(*tasks, return_exceptions=True)
@pytest.mark.parametrize("session_id", ["alpha", " alpha ", " ", None])
async def test_old_history_survives_route_fix_restart_and_rollback(tmp_path, session_id):
workspace = tmp_path / "workspace"
old_key = f"api:{session_id}" if session_id else API_SESSION_KEY
old_provider = RouteProvider()
async with runtime(workspace, old_provider) as (agent, _):
await agent.process_direct(
"LEGACY_HISTORY", session_key=old_key, channel="api", chat_id=API_CHAT_ID,
)
upgraded = RouteProvider()
async with runtime(workspace, upgraded) as (_, client):
result = await post(client, session_id, "UPGRADED_TURN")
assert_route(result, session_id or "default")
assert "LEGACY_HISTORY" in json.dumps(upgraded.calls[0]["messages"])
assert_prefix(old_provider.calls[0], upgraded.calls[0])
old_tool_prefix = old_provider.calls[1]["messages"]
assert old_tool_prefix == upgraded.calls[0]["messages"][:len(old_tool_prefix)]
assert_prefix(upgraded.calls[0], upgraded.calls[1])
reopened = RouteProvider()
async with runtime(workspace, reopened) as (agent, client):
assert_route(await post(client, session_id, "AFTER_RESTART"), session_id or "default")
replay = json.dumps(reopened.calls[0]["messages"])
assert "LEGACY_HISTORY" in replay and "UPGRADED_TURN" in replay
await agent.process_direct(
"ROLLBACK_TURN", session_key=old_key, channel="api", chat_id=API_CHAT_ID,
)
replay = json.dumps(reopened.calls[-1]["messages"])
assert all(text in replay for text in ("LEGACY_HISTORY", "UPGRADED_TURN", "AFTER_RESTART"))
+5 -21
View File
@@ -6,9 +6,7 @@ from pathlib import Path
import pytest import pytest
from nanobot.utils.media_decode import ( from nanobot.utils.media_decode import (
DEFAULT_MAX_BYTES, FileSizeExceededError,
MAX_FILE_SIZE,
FileSizeExceeded,
save_base64_data_url, save_base64_data_url,
) )
@@ -134,19 +132,15 @@ def test_unknown_mime_falls_back_to_bin(tmp_path) -> None:
def test_default_limit_is_10mb(tmp_path) -> None: def test_default_limit_is_10mb(tmp_path) -> None:
assert DEFAULT_MAX_BYTES == 10 * 1024 * 1024 oversized = b"x" * (10 * 1024 * 1024 + 1)
assert MAX_FILE_SIZE == 10 * 1024 * 1024 with pytest.raises(FileSizeExceededError, match="10MB limit"):
oversized = b"x" * (11 * 1024 * 1024)
with pytest.raises(FileSizeExceeded, match="10MB limit"):
save_base64_data_url(_data_url(oversized), tmp_path) save_base64_data_url(_data_url(oversized), tmp_path)
def test_explicit_max_bytes_overrides_default(tmp_path) -> None: def test_explicit_max_bytes_overrides_default(tmp_path) -> None:
"""WS channel passes 8 MB; a 9 MB payload should be rejected there even """The caller can reject a payload smaller than the default limit."""
though it would pass the 10 MB API limit."""
payload = b"y" * (9 * 1024 * 1024) payload = b"y" * (9 * 1024 * 1024)
with pytest.raises(FileSizeExceeded, match="8MB limit"): with pytest.raises(FileSizeExceededError, match="8MB limit"):
save_base64_data_url(_data_url(payload), tmp_path, max_bytes=8 * 1024 * 1024) save_base64_data_url(_data_url(payload), tmp_path, max_bytes=8 * 1024 * 1024)
@@ -154,13 +148,3 @@ def test_saved_file_lives_under_media_dir(tmp_path) -> None:
result = save_base64_data_url(_data_url(b"ok"), tmp_path) result = save_base64_data_url(_data_url(b"ok"), tmp_path)
assert result is not None assert result is not None
assert result.startswith(str(tmp_path)) assert result.startswith(str(tmp_path))
def test_legacy_symbols_reexported_from_api_server() -> None:
"""Existing tests import ``_save_base64_data_url`` / ``_FileSizeExceeded``
from ``nanobot.api.server`` — keep the aliases working."""
from nanobot.api import server
assert server._save_base64_data_url is save_base64_data_url
assert server._FileSizeExceeded is FileSizeExceeded
assert server.MAX_FILE_SIZE == MAX_FILE_SIZE
@@ -38,7 +38,5 @@
"network.proxy", "network.proxy",
"tools.web.use_proxy", "tools.web.use_proxy",
"tools.web.user_agent", "tools.web.user_agent",
"tools.image_generation.save_dir", "tools.image_generation.save_dir"
"api.host",
"api.timeout"
] ]
+16
View File
@@ -229,6 +229,11 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
gateway_port=gateway_port, gateway_port=gateway_port,
) )
legacy_config = json.loads(config_path.read_text(encoding="utf-8"))
legacy_config["api"] = {"host": "0.0.0.0", "apiKey": "${RETIRED_SMOKE_TOKEN}"}
config_path.write_text(json.dumps(legacy_config), encoding="utf-8")
before = config_path.read_bytes()
process = _start_gateway(config_path, log_path) process = _start_gateway(config_path, log_path)
base_url = f"http://127.0.0.1:{ws_port}" base_url = f"http://127.0.0.1:{ws_port}"
try: try:
@@ -240,6 +245,17 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
ready = await _recv_until(ws, "ready") ready = await _recv_until(ws, "ready")
assert ready["client_id"] == "smoke" assert ready["client_id"] == "smoke"
# An old WebUI can still connect, but cannot start the retired listener.
await ws.send(json.dumps({
"type": "webui_request", "request_id": "old-api-start",
"action": "settings.api_service.start",
"payload": {"host": "127.0.0.1", "port": _free_port(), "timeout": 120},
}))
rejected = await _recv_until(ws, "webui_response")
assert rejected["request_id"] == "old-api-start"
assert rejected["ok"] is False and rejected["error"]["status"] == 404
assert config_path.read_bytes() == before
await ws.send(json.dumps({"type": "new_chat"})) await ws.send(json.dumps({"type": "new_chat"}))
attached = await _recv_until(ws, "attached") attached = await _recv_until(ws, "attached")
chat_id = attached["chat_id"] chat_id = attached["chat_id"]
-54
View File
@@ -34,7 +34,6 @@ from nanobot.webui.settings_api import (
settings_payload, settings_payload,
settings_usage_payload, settings_usage_payload,
update_agent_settings, update_agent_settings,
update_api_settings,
update_model_call_order, update_model_call_order,
update_model_configuration, update_model_configuration,
update_network_safety_settings, update_network_safety_settings,
@@ -169,7 +168,6 @@ def test_settings_payload_includes_relocated_capabilities(
) -> None: ) -> None:
config_path = tmp_path / "config.json" config_path = tmp_path / "config.json"
config = Config() config = Config()
config.api.port = 9910
save_config(config, config_path) save_config(config, config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path) monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret") monkeypatch.setenv("LANGFUSE_SECRET_KEY", "secret")
@@ -177,8 +175,6 @@ def test_settings_payload_includes_relocated_capabilities(
payload = settings_payload() payload = settings_payload()
assert payload["api"]["port"] == 9910
assert payload["api"]["api_key_hint"] is None
assert payload["observability"]["provider"] == "langfuse" assert payload["observability"]["provider"] == "langfuse"
assert payload["observability"]["configured"] is True assert payload["observability"]["configured"] is True
@@ -198,56 +194,6 @@ def test_settings_payload_exposes_modelscope_image_model(
assert providers["modelscope"]["default_model"] == "Qwen/Qwen-Image-2512" assert providers["modelscope"]["default_model"] == "Qwen/Qwen-Image-2512"
def test_update_api_settings_requires_key_for_network_access(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
config_path = tmp_path / "config.json"
save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
with pytest.raises(WebUISettingsError, match="API key"):
update_api_settings({"host": ["0.0.0.0"], "port": ["8900"]})
payload = update_api_settings(
{
"host": ["0.0.0.0"],
"port": ["9900"],
"api_key": ["secret-token"],
}
)
saved = load_config(config_path)
assert saved.api.host == "0.0.0.0"
assert saved.api.port == 9900
assert saved.api.api_key == "secret-token"
assert payload["api"]["api_key_hint"]
def test_update_api_settings_requires_key_for_specific_network_interface(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
config_path = tmp_path / "config.json"
save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
with pytest.raises(WebUISettingsError, match="API key"):
update_api_settings({"host": ["192.168.1.10"], "port": ["8900"]})
def test_update_api_settings_allows_alternate_loopback_without_key(
tmp_path,
monkeypatch: pytest.MonkeyPatch,
) -> None:
config_path = tmp_path / "config.json"
save_config(Config(), config_path)
monkeypatch.setattr("nanobot.config.loader._current_config_path", config_path)
update_api_settings({"host": ["127.0.0.2"], "port": ["8900"]})
assert load_config(config_path).api.host == "127.0.0.2"
def _dynamic_provider_config( def _dynamic_provider_config(
*, *,
api_base: str = DYNAMIC_PROVIDER_API_BASE, api_base: str = DYNAMIC_PROVIDER_API_BASE,
@@ -7,7 +7,6 @@ import pytest
from nanobot.config.schema import Config from nanobot.config.schema import Config
from nanobot.webui.settings_capabilities import ( from nanobot.webui.settings_capabilities import (
capability_settings_payload, capability_settings_payload,
update_api_settings,
update_image_generation_settings, update_image_generation_settings,
update_network_safety_settings, update_network_safety_settings,
update_transcription_settings, update_transcription_settings,
@@ -75,10 +74,6 @@ def test_capability_domain_updates_representative_settings() -> None:
"use_jina_reader": ["false"], "use_jina_reader": ["false"],
}, },
) )
update_api_settings(
config,
{"host": ["127.0.0.2"], "port": ["8900"], "timeout": ["90"]},
)
image_changed = update_image_generation_settings( image_changed = update_image_generation_settings(
config, config,
{"enabled": ["true"], "provider": ["openrouter"]}, {"enabled": ["true"], "provider": ["openrouter"]},
@@ -102,7 +97,5 @@ def test_capability_domain_updates_representative_settings() -> None:
assert transcription_changed is True assert transcription_changed is True
assert (network_changed, access_mode) == (True, "default") assert (network_changed, access_mode) == (True, "default")
assert payload["web_search"]["max_results"] == 7 assert payload["web_search"]["max_results"] == 7
assert payload["api"]["host"] == "127.0.0.2"
assert payload["api"]["port"] == 8900
assert payload["image_generation"]["enabled"] is True assert payload["image_generation"]["enabled"] is True
assert payload["transcription"]["provider"] == "openrouter" assert payload["transcription"]["provider"] == "openrouter"
+5 -8
View File
@@ -974,19 +974,16 @@ async def test_runtime_config_route_authentication_validation_and_restart(tmp_pa
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"] assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]
async def test_runtime_settings_only_save_without_refreshing_or_rebinding(tmp_path, monkeypatch): async def test_runtime_settings_only_save_without_refreshing_or_rebinding(tmp_path):
refresh = MagicMock() refresh = MagicMock()
runtime = MagicMock()
monkeypatch.setattr(WebUISettingsRouter, "_api_runtime", lambda _self: runtime)
router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh) router = _router(config_path=tmp_path / "config.json", refresh_runtime_config=refresh)
path = "/api/settings/runtime-config/update" path = "/api/settings/runtime-config/update"
response = await router.dispatch(None, _mutation_request(path, { response = await router.dispatch(None, _mutation_request(path, {
"values": {"agents.defaults.dream.enabled": False, "api.timeout": 45}, "values": {"agents.defaults.dream.enabled": False, "gateway.port": 19001},
}), path) }), path)
assert response.status_code == 200 assert response.status_code == 200
assert json.loads(response.body)["requires_restart"] assert json.loads(response.body)["requires_restart"]
refresh.assert_not_called() refresh.assert_not_called()
runtime.restart.assert_not_called()
async def test_reverting_runtime_switch_clears_restart_but_preserves_other_changes(tmp_path): async def test_reverting_runtime_switch_clears_restart_but_preserves_other_changes(tmp_path):
@@ -1015,7 +1012,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
router = _router(config_path=tmp_path / "config.json") router = _router(config_path=tmp_path / "config.json")
config = router.settings.config.load() config = router.settings.config.load()
original_reader = config.tools.web.fetch.use_jina_reader original_reader = config.tools.web.fetch.use_jina_reader
original_timeout = config.api.timeout original_port = config.gateway.port
path = "/api/settings/web-search/update" path = "/api/settings/web-search/update"
first = await router.dispatch(None, _mutation_request(path, { first = await router.dispatch(None, _mutation_request(path, {
"provider": "duckduckgo", "use_jina_reader": not original_reader, "provider": "duckduckgo", "use_jina_reader": not original_reader,
@@ -1025,7 +1022,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
runtime_path = "/api/settings/runtime-config/update" runtime_path = "/api/settings/runtime-config/update"
changed = await router.dispatch(None, _mutation_request(runtime_path, { changed = await router.dispatch(None, _mutation_request(runtime_path, {
"values": {"api.timeout": original_timeout + 1}, "values": {"gateway.port": original_port + 1},
}), runtime_path) }), runtime_path)
assert changed.status_code == 200 assert changed.status_code == 200
assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"} assert set(json.loads(changed.body)["restart_required_sections"]) == {"browser", "runtime"}
@@ -1038,7 +1035,7 @@ async def test_reverting_web_reader_preserves_unrelated_restart_reason(tmp_path)
refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings") refreshed = await router.dispatch(None, SimpleNamespace(path="/api/settings", headers=Headers()), "/api/settings")
assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"] assert json.loads(refreshed.body)["restart_required_sections"] == ["runtime"]
reverted = await router.dispatch(None, _mutation_request(runtime_path, { reverted = await router.dispatch(None, _mutation_request(runtime_path, {
"values": {"api.timeout": original_timeout}, "values": {"gateway.port": original_port},
}), runtime_path) }), runtime_path)
assert reverted.status_code == 200 assert reverted.status_code == 200
assert json.loads(reverted.body)["restart_required_sections"] == [] assert json.loads(reverted.body)["restart_required_sections"] == []
-10
View File
@@ -121,7 +121,6 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
assert saved.channels.telegram == {"token": "keep-me", "streaming": False} assert saved.channels.telegram == {"token": "keep-me", "streaming": False}
assert payload["requires_restart"] assert payload["requires_restart"]
assert payload["runtime_config"]["tools.image_generation.save_dir"] == "images" assert payload["runtime_config"]["tools.image_generation.save_dir"] == "images"
assert "api.api_key" not in runtime_config_payload(saved)
assert "PRIVATE_API_KEY" not in json.dumps(runtime_config_payload(saved)) assert "PRIVATE_API_KEY" not in json.dumps(runtime_config_payload(saved))
@@ -153,8 +152,6 @@ def test_runtime_patch_persists_and_preserves_other_domains(tmp_path):
{"agents.defaults.timezone_mode": "manual", "agents.defaults.timezone": "Mars/Olympus"}, {"agents.defaults.timezone_mode": "manual", "agents.defaults.timezone": "Mars/Olympus"},
{"gateway.port": 65536}, {"gateway.port": 65536},
{"gateway.heartbeat.interval_s": 0}, {"gateway.heartbeat.interval_s": 0},
{"api.host": "192.168.1.2"},
{"api.timeout": float("nan")},
{"tools.image_generation.save_dir": ""}, {"tools.image_generation.save_dir": ""},
{"tools.image_generation.save_dir": "../outside"}, {"tools.image_generation.save_dir": "../outside"},
{"tools.image_generation.save_dir": "C:/outside"}, {"tools.image_generation.save_dir": "C:/outside"},
@@ -230,13 +227,6 @@ def test_timezone_auto_and_nullable_fields():
assert not update_runtime_config(config, {}, local_browser=True) assert not update_runtime_config(config, {}, local_browser=True)
def test_api_changes_require_explicit_restart(tmp_path):
path = tmp_path / "config.json"
payload = update_runtime_config_settings({"api.timeout": 222.5}, config_path=path)
assert payload["api"]["timeout"] == 222.5
assert payload["requires_restart"]
def test_runtime_payload_matches_shared_catalogue_contract(): def test_runtime_payload_matches_shared_catalogue_contract():
fixture = Path(__file__).with_name("fixtures") / "runtime-config-keys.json" fixture = Path(__file__).with_name("fixtures") / "runtime-config-keys.json"
paths = json.loads(fixture.read_text(encoding="utf-8")) paths = json.loads(fixture.read_text(encoding="utf-8"))
+21 -17
View File
@@ -11,7 +11,11 @@ from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.config.loader import load_config, save_config from nanobot.config.loader import load_config, save_config
from nanobot.config.schema import Config from nanobot.config.schema import Config
from nanobot.webui.gateway_services import build_gateway_services from nanobot.webui.gateway_services import build_gateway_services
from nanobot.webui.settings_api import settings_payload, update_agent_settings, update_api_settings from nanobot.webui.settings_api import (
settings_payload,
update_agent_settings,
update_runtime_config_settings,
)
from nanobot.webui.settings_services import ( from nanobot.webui.settings_services import (
WebUIOAuthFlowRegistry, WebUIOAuthFlowRegistry,
WebUISettingsServices, WebUISettingsServices,
@@ -56,9 +60,9 @@ def test_gateway_settings_services_isolate_config_paths_and_oauth_flows(
first_path = tmp_path / "first" / "config.json" first_path = tmp_path / "first" / "config.json"
second_path = tmp_path / "second" / "config.json" second_path = tmp_path / "second" / "config.json"
first_config = Config() first_config = Config()
first_config.api.host = "127.0.0.2" first_config.gateway.host = "127.0.0.2"
second_config = Config() second_config = Config()
second_config.api.host = "127.0.0.3" second_config.gateway.host = "127.0.0.3"
save_config(first_config, first_path) save_config(first_config, first_path)
save_config(second_config, second_path) save_config(second_config, second_path)
@@ -69,14 +73,14 @@ def test_gateway_settings_services_isolate_config_paths_and_oauth_flows(
assert second.settings.config.path == second_path.resolve() assert second.settings.config.path == second_path.resolve()
assert first.http.settings_routes.settings is first.settings assert first.http.settings_routes.settings is first.settings
assert second.http.settings_routes.settings is second.settings assert second.http.settings_routes.settings is second.settings
assert first.settings.config.load().api.host == "127.0.0.2" assert first.settings.config.load().gateway.host == "127.0.0.2"
assert second.settings.config.load().api.host == "127.0.0.3" assert second.settings.config.load().gateway.host == "127.0.0.3"
assert first.settings.read(settings_payload)["api"]["host"] == "127.0.0.2" assert first.settings.read(settings_payload)["runtime_config"]["gateway.host"] == "127.0.0.2"
assert second.settings.read(settings_payload)["api"]["host"] == "127.0.0.3" assert second.settings.read(settings_payload)["runtime_config"]["gateway.host"] == "127.0.0.3"
first.settings.mutate(update_api_settings, {"port": ["19001"]}) first.settings.mutate(update_runtime_config_settings, {"gateway.port": 19001})
assert load_config(first_path).api.port == 19001 assert load_config(first_path).gateway.port == 19001
assert load_config(second_path).api.port != 19001 assert load_config(second_path).gateway.port != 19001
first_flow = _Flow() first_flow = _Flow()
second_flow = _Flow() second_flow = _Flow()
@@ -94,9 +98,9 @@ def test_settings_service_supports_a_new_config_directory(tmp_path: Path) -> Non
config_path = tmp_path / "new" / "nested" / "config.json" config_path = tmp_path / "new" / "nested" / "config.json"
services = WebUISettingsServices.create(config_path) services = WebUISettingsServices.create(config_path)
services.mutate(update_api_settings, {"port": ["19001"]}) services.mutate(update_runtime_config_settings, {"gateway.port": 19001})
assert load_config(config_path).api.port == 19001 assert load_config(config_path).gateway.port == 19001
def test_settings_mutations_serialize_read_modify_write( def test_settings_mutations_serialize_read_modify_write(
@@ -137,7 +141,7 @@ def test_settings_mutations_serialize_read_modify_write(
def run_second() -> None: def run_second() -> None:
try: try:
second_started.set() second_started.set()
services.mutate(update_api_settings, {"host": ["127.0.0.9"]}) services.mutate(update_runtime_config_settings, {"gateway.host": "127.0.0.9"})
except BaseException as exc: # noqa: BLE001 - re-raised in the test thread except BaseException as exc: # noqa: BLE001 - re-raised in the test thread
errors.append(exc) errors.append(exc)
@@ -157,7 +161,7 @@ def test_settings_mutations_serialize_read_modify_write(
assert not errors assert not errors
saved = load_config(config_path) saved = load_config(config_path)
assert saved.agents.defaults.timezone == "Asia/Tokyo" assert saved.agents.defaults.timezone == "Asia/Tokyo"
assert saved.api.host == "127.0.0.9" assert saved.gateway.host == "127.0.0.9"
def test_distinct_gateways_serialize_mutations_for_the_same_config( def test_distinct_gateways_serialize_mutations_for_the_same_config(
@@ -192,7 +196,7 @@ def test_distinct_gateways_serialize_mutations_for_the_same_config(
def mutate( def mutate(
services: WebUISettingsServices, services: WebUISettingsServices,
operation: Callable[..., object], operation: Callable[..., object],
query: dict[str, list[str]], query: dict[str, str],
) -> None: ) -> None:
try: try:
services.mutate(operation, query) services.mutate(operation, query)
@@ -206,7 +210,7 @@ def test_distinct_gateways_serialize_mutations_for_the_same_config(
) )
second = threading.Thread( second = threading.Thread(
target=mutate, target=mutate,
args=(second_services, update_api_settings, {"host": ["127.0.0.9"]}), args=(second_services, update_runtime_config_settings, {"gateway.host": "127.0.0.9"}),
name="gateway-second", name="gateway-second",
) )
first.start() first.start()
@@ -222,7 +226,7 @@ def test_distinct_gateways_serialize_mutations_for_the_same_config(
assert not errors assert not errors
saved = load_config(config_path) saved = load_config(config_path)
assert saved.agents.defaults.timezone == "Asia/Tokyo" assert saved.agents.defaults.timezone == "Asia/Tokyo"
assert saved.api.host == "127.0.0.9" assert saved.gateway.host == "127.0.0.9"
def test_oauth_registry_preserves_expiry_capacity_completion_and_cancel() -> None: def test_oauth_registry_preserves_expiry_capacity_completion_and_cancel() -> None:
@@ -42,8 +42,6 @@ export function installIdleCompactionApi() {
const bodies: Record<string, unknown> = { const bodies: Record<string, unknown> = {
"/api/settings": persisted, "/api/settings": persisted,
"/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false }, "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false },
"/api/settings/api-service": { installed: false, running: false, managed: false, host: "127.0.0.1",
port: 8900, timeout: 120, endpoint: "http://127.0.0.1:8900/v1", command: "nanobot serve" },
}; };
return Response.json(bodies[url.pathname] ?? {}); return Response.json(bodies[url.pathname] ?? {});
}; };
@@ -69,7 +69,6 @@ export function installSkeletonPreviewApi() {
"/api/settings": previewSettings, "/api/settings/usage": { usage: null }, "/api/settings": previewSettings, "/api/settings/usage": { usage: null },
"/api/webui/automations": { jobs }, "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false }, "/api/webui/automations": { jobs }, "/api/settings/nanobot-features": { features: [], enabled_count: 0, requires_restart: false },
"/api/settings/cli-apps": { apps: [], installed_count: 0 }, "/api/settings/mcp-presets": { presets: [], installed_count: 0 }, "/api/settings/cli-apps": { apps: [], installed_count: 0 }, "/api/settings/mcp-presets": { presets: [], installed_count: 0 },
"/api/settings/api-service": { installed: false, running: false, managed: false, host: "127.0.0.1", port: 8900, timeout: 120, endpoint: "http://127.0.0.1:8900/v1", command: "nanobot serve" },
}; };
return Response.json(bodies[url.pathname] ?? {}); return Response.json(bodies[url.pathname] ?? {});
}; };
+1 -1
View File
@@ -71,7 +71,7 @@ for (const width of [390, 1440]) for (const locale of ["en", "zh-CN"]) {
await expect(target.getByRole("switch")).toHaveCount(2); await expect(target.getByRole("switch")).toHaveCount(2);
await expect(target.getByRole("switch").first()).toBeEnabled(); await expect(target.getByRole("switch").first()).toBeEnabled();
} }
if (section === "runtime") await expect(page.locator('[data-settings-section] button').filter({ hasText: locale === "en" ? "Start API server" : "启动 API 服务" })).toBeVisible(); if (section === "runtime") await expect(target.getByText("Langfuse", { exact: true })).toBeVisible();
await settle(page); await settle(page);
// Collapsed options remain mounted for drafts but do not occupy the visible layout. // Collapsed options remain mounted for drafts but do not occupy the visible layout.
const selector = section === "overview" ? "section button.group" : section === "models" ? '[data-testid^="model-call-order-row"], .settings-footer' : section === "about" ? ".settings-list-row" : ".settings-row:not([inert] *)"; const selector = section === "overview" ? "section button.group" : section === "models" ? '[data-testid^="model-call-order-row"], .settings-footer' : section === "about" ? ".settings-list-row" : ".settings-row:not([inert] *)";
@@ -467,15 +467,10 @@ export function SettingsPage({
onRestart={showSidebar ? undefined : restartViaSettingsSurface} onRestart={showSidebar ? undefined : restartViaSettingsSurface}
isRestarting={restartInProgress} isRestarting={restartInProgress}
requiresRestartPending={pendingRestartSections.runtime} requiresRestartPending={pendingRestartSections.runtime}
apiService={systemState.apiService}
apiServiceLoading={systemState.apiServiceLoading}
apiServiceAction={systemState.apiServiceAction}
apiServiceError={systemState.apiServiceError}
langfuseFeature={featureCatalog.find((feature) => feature.name === "langfuse")} langfuseFeature={featureCatalog.find((feature) => feature.name === "langfuse")}
capabilitiesLoading={systemState.nanobotFeaturesLoading} capabilitiesLoading={systemState.nanobotFeaturesLoading}
capabilityAction={systemState.nanobotFeatureAction} capabilityAction={systemState.nanobotFeatureAction}
capabilityError={systemState.nanobotFeaturesError} capabilityError={systemState.nanobotFeaturesError}
onApiServiceAction={systemActions.handleApiServiceAction}
onInstallCapability={(name) => void systemActions.installCapabilities([name])} onInstallCapability={(name) => void systemActions.installCapabilities([name])}
/> />
</div> </div>
@@ -119,7 +119,7 @@ export function SettingsSectionSkeleton({ section, showRestart = false, sandboxS
</SettingsGroup><div className="settings-footer flex items-center justify-between gap-2"><div className="flex h-11 items-center sm:h-9"><div className={cn(block, "h-3 w-20")} /></div><div className="flex h-11 items-center sm:h-9"><div className={cn(block, "h-3 w-28")} /></div></div></section>; </SettingsGroup><div className="settings-footer flex items-center justify-between gap-2"><div className="flex h-11 items-center sm:h-9"><div className={cn(block, "h-3 w-20")} /></div><div className="flex h-11 items-center sm:h-9"><div className={cn(block, "h-3 w-28")} /></div></div></section>;
break; break;
case "runtime": case "runtime":
content = <><RuntimeGroups page="runtime" /><Group controls={["input", "segments", "input", "input"]} /><Group controls={["input"]} /><Group controls={showRestart ? ["text", "text", "input"] : ["text", "text"]} /></>; content = <><RuntimeGroups page="runtime" /><Group controls={["input"]} /><Group controls={showRestart ? ["text", "text", "input"] : ["text", "text"]} /></>;
break; break;
case "advanced": case "advanced":
content = <RuntimeGroups page="advanced" sandboxSupported={sandboxSupported} />; content = <RuntimeGroups page="advanced" sandboxSupported={sandboxSupported} />;
@@ -93,7 +93,7 @@ export function useRuntimeConfigSettings(
const maximum = field.kind === "duration" ? settings.advanced.exec_max_runtime_limit : field.max; const maximum = field.kind === "duration" ? settings.advanced.exec_max_runtime_limit : field.max;
const parsed = Number(raw); const parsed = Number(raw);
if (String(raw).trim() === "" || !Number.isFinite(parsed) if (String(raw).trim() === "" || !Number.isFinite(parsed)
|| (field.path !== "api.timeout" && !Number.isInteger(parsed)) || !Number.isInteger(parsed)
|| (field.min !== undefined && parsed < field.min) || (field.min !== undefined && parsed < field.min)
|| (maximum !== undefined && parsed > maximum)) { || (maximum !== undefined && parsed > maximum)) {
setErrors((prev) => ({ ...prev, [group]: t("settings.runtimeConfig.numberError") })); setErrors((prev) => ({ ...prev, [group]: t("settings.runtimeConfig.numberError") }));
@@ -288,7 +288,7 @@ export function RuntimeConfigSettings({
onChange={(next) => state.change(field, next === "__none__" ? "" : next)} /> onChange={(next) => state.change(field, next === "__none__" ? "" : next)} />
) : ( ) : (
<Input {...common} type={field.kind === "number" ? "number" : "text"} <Input {...common} type={field.kind === "number" ? "number" : "text"}
min={field.min} max={field.max} step={field.path === "api.timeout" ? "any" : 1} min={field.min} max={field.max} step={1}
value={String(current)} className="h-9 rounded-full text-[13px]" autoComplete="off" value={String(current)} className="h-9 rounded-full text-[13px]" autoComplete="off"
onChange={(event) => state.change(field, event.target.value)} /> onChange={(event) => state.change(field, event.target.value)} />
)} )}
@@ -1,10 +1,9 @@
import { useEffect, useState } from "react"; import { useState } from "react";
import { Eye, EyeOff, Loader2, PauseCircle, PlayCircle, RotateCcw } from "lucide-react"; import { Loader2, RotateCcw } from "lucide-react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import type { AgentSettingsDraft } from "@/components/settings/models/ModelsSettings"; import type { AgentSettingsDraft } from "@/components/settings/models/ModelsSettings";
import { import {
NumberInput,
ReadOnlyRow, ReadOnlyRow,
SettingsGroup, SettingsGroup,
SettingsRow, SettingsRow,
@@ -12,11 +11,8 @@ import {
StatusPill, StatusPill,
} from "@/components/settings/shared/SettingsControls"; } from "@/components/settings/shared/SettingsControls";
import { Button } from "@/components/ui/button"; import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { SegmentedControl } from "@/components/ui/segmented-control";
import { isLoopbackHost } from "@/lib/network";
import { getRuntimeHost, isNativeRuntime } from "@/lib/runtime"; import { getRuntimeHost, isNativeRuntime } from "@/lib/runtime";
import type { ApiServicePayload, NanobotFeatureInfo, SettingsPayload } from "@/lib/types"; import type { NanobotFeatureInfo, SettingsPayload } from "@/lib/types";
export function RuntimeSettings({ export function RuntimeSettings({
form, form,
@@ -24,15 +20,10 @@ export function RuntimeSettings({
onRestart, onRestart,
isRestarting, isRestarting,
requiresRestartPending, requiresRestartPending,
apiService,
apiServiceLoading,
apiServiceAction,
apiServiceError,
langfuseFeature, langfuseFeature,
capabilitiesLoading, capabilitiesLoading,
capabilityAction, capabilityAction,
capabilityError, capabilityError,
onApiServiceAction,
onInstallCapability, onInstallCapability,
}: { }: {
form: AgentSettingsDraft; form: AgentSettingsDraft;
@@ -40,18 +31,10 @@ export function RuntimeSettings({
onRestart?: () => void; onRestart?: () => void;
isRestarting?: boolean; isRestarting?: boolean;
requiresRestartPending: boolean; requiresRestartPending: boolean;
apiService: ApiServicePayload | null;
apiServiceLoading: boolean;
apiServiceAction: "start" | "stop" | null;
apiServiceError: string | null;
langfuseFeature?: NanobotFeatureInfo; langfuseFeature?: NanobotFeatureInfo;
capabilitiesLoading: boolean; capabilitiesLoading: boolean;
capabilityAction: string | null; capabilityAction: string | null;
capabilityError: string | null; capabilityError: string | null;
onApiServiceAction: (
action: "start" | "stop",
values?: { host: string; port: number; timeout: number; apiKey?: string },
) => void;
onInstallCapability: (name: string) => void; onInstallCapability: (name: string) => void;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
@@ -74,30 +57,6 @@ export function RuntimeSettings({
} | null>(null); } | null>(null);
const [hostActionBusy, setHostActionBusy] = const [hostActionBusy, setHostActionBusy] =
useState<"logs" | "diagnostics" | null>(null); useState<"logs" | "diagnostics" | null>(null);
const apiDefaults = apiService ?? {
installed: false,
running: false,
managed: false,
host: settings.api?.host ?? "127.0.0.1",
port: settings.api?.port ?? 8900,
timeout: settings.api?.timeout ?? 120,
api_key_hint: settings.api?.api_key_hint,
endpoint: `http://127.0.0.1:${settings.api?.port ?? 8900}/v1`,
command: "nanobot serve",
};
const [apiHost, setApiHost] = useState(apiDefaults.host);
const [apiPort, setApiPort] = useState(apiDefaults.port);
const [apiKey, setApiKey] = useState("");
const [apiKeyVisible, setApiKeyVisible] = useState(false);
useEffect(() => {
if (!apiService) return;
setApiHost(settings.api?.host ?? apiService.host);
setApiPort(settings.api?.port ?? apiService.port);
setApiKey("");
setApiKeyVisible(false);
}, [apiService, settings.api?.host, settings.api?.port]);
const apiNetworkAccess = !isLoopbackHost(apiHost);
const apiMissingNetworkKey = apiNetworkAccess && !apiKey.trim() && !apiDefaults.api_key_hint;
const engineState = isRestarting const engineState = isRestarting
? tx("settings.values.restartingEngine", "Restarting") ? tx("settings.values.restartingEngine", "Restarting")
: settings.apply_state?.status === "pending" : settings.apply_state?.status === "pending"
@@ -205,118 +164,6 @@ export function RuntimeSettings({
</section> </section>
) : null} ) : null}
<section>
<SettingsSectionTitle>{tx("settings.api.title", "API server")}</SettingsSectionTitle>
<SettingsGroup>
<SettingsRow
title={tx("settings.api.openaiCompatible", "OpenAI-compatible API")}
description={
apiServiceError
? apiServiceError
: apiDefaults.running
? apiDefaults.endpoint
: undefined
}
>
<div className="flex items-center justify-end gap-2">
<StatusPill tone={apiDefaults.running ? "success" : "neutral"}>
{apiServiceLoading
? tx("settings.values.checking", "Checking")
: apiDefaults.running
? tx("settings.values.running", "Running")
: tx("settings.values.off", "Off")}
</StatusPill>
<Button
size="sm"
variant="outline"
disabled={apiServiceLoading || apiServiceAction !== null || apiMissingNetworkKey}
onClick={() =>
onApiServiceAction(
apiDefaults.running ? "stop" : "start",
apiDefaults.running
? undefined
: {
host: apiHost,
port: apiPort,
timeout: settings.api?.timeout ?? apiDefaults.timeout,
apiKey: apiKey.trim() || undefined,
},
)
}
className="rounded-full"
>
{apiServiceAction ? (
<Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" aria-hidden />
) : apiDefaults.running ? (
<PauseCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
) : (
<PlayCircle className="mr-1.5 h-3.5 w-3.5" aria-hidden />
)}
{apiServiceAction === "start"
? tx("settings.api.starting", "Starting...")
: apiServiceAction === "stop"
? tx("settings.api.stopping", "Stopping...")
: apiDefaults.running
? tx("settings.api.stop", "Stop")
: tx("settings.api.start", "Start API server")}
</Button>
</div>
</SettingsRow>
{!apiDefaults.running ? (
<>
<SettingsRow
title={tx("settings.api.access", "Access")}
description={
apiNetworkAccess
? tx("settings.api.networkHelp", "Other devices can connect; an API key is required.")
: tx("settings.api.localHelp", "Only this device can connect.")
}
>
<SegmentedControl
value={apiNetworkAccess ? "network" : "local"}
options={[
{ value: "local", label: tx("settings.api.thisDevice", "This device") },
{ value: "network", label: tx("settings.api.localNetwork", "Local network") },
]}
onChange={(value) => setApiHost(value === "network" ? "0.0.0.0" : "127.0.0.1")}
/>
</SettingsRow>
<SettingsRow title={tx("settings.api.port", "Port")}>
<NumberInput value={apiPort} min={1} max={65535} onChange={setApiPort} />
</SettingsRow>
<SettingsRow
title={tx("settings.api.apiKey", "API key")}
description={
apiMissingNetworkKey
? tx("settings.api.apiKeyRequired", "Required before exposing the API to your network.")
: tx("settings.api.apiKeyHelp", "Clients send this as a Bearer token.")
}
>
<div className="relative w-full">
<Input
type={apiKeyVisible ? "text" : "password"}
value={apiKey}
onChange={(event) => setApiKey(event.target.value)}
placeholder={apiDefaults.api_key_hint ?? tx("settings.api.apiKeyPlaceholder", "Enter an API key")}
className="h-9 rounded-full pr-10 text-[13px]"
/>
<Button
type="button"
variant="ghost"
size="icon"
onClick={() => setApiKeyVisible((visible) => !visible)}
aria-label={apiKeyVisible ? tx("settings.byok.hideApiKey", "Hide API key") : tx("settings.byok.showApiKey", "Show API key")}
className="absolute right-1 top-1/2 h-7 w-7 -translate-y-1/2 rounded-full"
>
{apiKeyVisible ? <EyeOff className="h-3.5 w-3.5" /> : <Eye className="h-3.5 w-3.5" />}
</Button>
</div>
</SettingsRow>
</>
) : null}
</SettingsGroup>
</section>
<section> <section>
<SettingsSectionTitle>{tx("settings.observability.title", "Observability")}</SettingsSectionTitle> <SettingsSectionTitle>{tx("settings.observability.title", "Observability")}</SettingsSectionTitle>
<SettingsGroup> <SettingsGroup>
@@ -2,7 +2,6 @@ import type { Dispatch, SetStateAction } from "react";
import type { TFunction } from "i18next"; import type { TFunction } from "i18next";
import type { import type {
ApplySettingsPayload,
MaybeRestartHostEngine, MaybeRestartHostEngine,
PendingRestartSections, PendingRestartSections,
} from "@/components/settings/contracts"; } from "@/components/settings/contracts";
@@ -15,8 +14,6 @@ import {
completeMcpOAuth, completeMcpOAuth,
disableNanobotFeature, disableNanobotFeature,
enableNanobotFeature, enableNanobotFeature,
fetchNanobotFeatures,
fetchSettings,
fetchMcpOAuthStatus, fetchMcpOAuthStatus,
fetchMcpPresets, fetchMcpPresets,
importMcpConfig, importMcpConfig,
@@ -25,8 +22,6 @@ import {
runMcpPresetAction, runMcpPresetAction,
saveCustomMcpServer, saveCustomMcpServer,
startMcpOAuth, startMcpOAuth,
startApiService,
stopApiService,
updateAutomation, updateAutomation,
updateMcpServerTools, updateMcpServerTools,
} from "@/lib/api"; } from "@/lib/api";
@@ -71,10 +66,8 @@ interface SystemSettingsActionsOptions {
state: SystemSettingsState; state: SystemSettingsState;
featureCatalog: NanobotFeatureInfo[]; featureCatalog: NanobotFeatureInfo[];
client: NanobotClient; client: NanobotClient;
token: string;
getToken: () => string; getToken: () => string;
t: TFunction; t: TFunction;
applyPayload: ApplySettingsPayload;
maybeRestartHostEngine: MaybeRestartHostEngine; maybeRestartHostEngine: MaybeRestartHostEngine;
setPendingRestartSections: Dispatch<SetStateAction<PendingRestartSections>>; setPendingRestartSections: Dispatch<SetStateAction<PendingRestartSections>>;
refreshAutomations: (showLoading?: boolean) => Promise<void>; refreshAutomations: (showLoading?: boolean) => Promise<void>;
@@ -84,16 +77,13 @@ export function createSystemSettingsActions({
state, state,
featureCatalog, featureCatalog,
client, client,
token,
getToken, getToken,
t, t,
applyPayload,
maybeRestartHostEngine, maybeRestartHostEngine,
setPendingRestartSections, setPendingRestartSections,
refreshAutomations, refreshAutomations,
}: SystemSettingsActionsOptions) { }: SystemSettingsActionsOptions) {
const { const {
apiServiceAction,
customMcpForm, customMcpForm,
mcpConfigImport, mcpConfigImport,
mcpOAuthCallbackUrl, mcpOAuthCallbackUrl,
@@ -102,9 +92,6 @@ export function createSystemSettingsActions({
mcpOAuthPopupRef, mcpOAuthPopupRef,
nanobotFeatureActionRef, nanobotFeatureActionRef,
nanobotFeatures, nanobotFeatures,
setApiService,
setApiServiceAction,
setApiServiceError,
setAutomationAction, setAutomationAction,
setAutomationPendingDelete, setAutomationPendingDelete,
setAutomationPendingEdit, setAutomationPendingEdit,
@@ -172,29 +159,6 @@ export function createSystemSettingsActions({
} }
}; };
const handleApiServiceAction = async (
action: "start" | "stop",
values?: { host: string; port: number; timeout: number; apiKey?: string },
) => {
if (apiServiceAction) return;
setApiServiceAction(action);
setApiServiceError(null);
try {
const payload = action === "start"
? await startApiService(client, values!)
: await stopApiService(client);
setApiService(payload);
const refreshed = await fetchNanobotFeatures(token);
setNanobotFeatures(refreshed);
const nextSettings = await fetchSettings(token);
applyPayload(nextSettings);
} catch (err) {
setApiServiceError((err as Error).message);
} finally {
setApiServiceAction(null);
}
};
const handleCliAppAction = async ( const handleCliAppAction = async (
action: "install" | "update" | "uninstall" | "test", action: "install" | "update" | "uninstall" | "test",
name: string, name: string,
@@ -709,7 +673,6 @@ export function createSystemSettingsActions({
}; };
return { return {
handleApiServiceAction,
handleAutomationAction, handleAutomationAction,
handleAutomationEdit, handleAutomationEdit,
handleAutomationChat, handleAutomationChat,
@@ -25,7 +25,6 @@ export const RUNTIME_CONFIG_GROUPS: { id: string; page: RuntimeConfigPage; enabl
{ id: "safety", page: "advanced" }, { id: "safety", page: "advanced" },
{ id: "cli", page: "advanced", enabledBy: "tools.cli_apps.enable" }, { id: "cli", page: "advanced", enabledBy: "tools.cli_apps.enable" },
{ id: "gateway", page: "advanced" }, { id: "gateway", page: "advanced" },
{ id: "api", page: "advanced" },
{ id: "storage", page: "image" }, { id: "storage", page: "image" },
]; ];
@@ -68,7 +67,5 @@ export const RUNTIME_CONFIG_FIELDS: RuntimeConfigField[] = [
{ group: "gateway", path: "gateway.host", kind: "text", manual: true }, { group: "gateway", path: "gateway.host", kind: "text", manual: true },
{ group: "gateway", path: "gateway.port", kind: "number", min: 1, max: 65535, manual: true }, { group: "gateway", path: "gateway.port", kind: "number", min: 1, max: 65535, manual: true },
{ group: "gateway", path: "gateway.restart_mode", kind: "select", options: ["auto", "exec", "spawn", "exit"] }, { group: "gateway", path: "gateway.restart_mode", kind: "select", options: ["auto", "exec", "spawn", "exit"] },
{ group: "api", path: "api.host", kind: "text", manual: true },
{ group: "api", path: "api.timeout", kind: "number", min: 1, max: 3600 },
{ group: "storage", path: "tools.image_generation.save_dir", kind: "text" }, { group: "storage", path: "tools.image_generation.save_dir", kind: "text" },
]; ];
@@ -7,7 +7,6 @@ import {
} from "@/components/settings/system/AppsSettings"; } from "@/components/settings/system/AppsSettings";
import type { SystemSettingsState } from "@/components/settings/system/useSystemSettingsState"; import type { SystemSettingsState } from "@/components/settings/system/useSystemSettingsState";
import { import {
fetchApiService,
fetchAutomations, fetchAutomations,
fetchNanobotFeatures, fetchNanobotFeatures,
} from "@/lib/api"; } from "@/lib/api";
@@ -28,9 +27,6 @@ export function useSystemSettingsEffects({
pageVisible, pageVisible,
}: SystemSettingsEffectsOptions) { }: SystemSettingsEffectsOptions) {
const { const {
setApiService,
setApiServiceError,
setApiServiceLoading,
setAutomations, setAutomations,
setAutomationsError, setAutomationsError,
setAutomationsLoading, setAutomationsLoading,
@@ -136,28 +132,6 @@ export function useSystemSettingsEffects({
}; };
}, [activeSection, getToken, pageVisible]); }, [activeSection, getToken, pageVisible]);
useEffect(() => {
if (activeSection !== "runtime") return;
let cancelled = false;
setApiServiceLoading(true);
fetchApiService(getToken())
.then((payload) => {
if (!cancelled) {
setApiService(payload);
setApiServiceError(null);
}
})
.catch((err) => {
if (!cancelled) setApiServiceError((err as Error).message);
})
.finally(() => {
if (!cancelled) setApiServiceLoading(false);
});
return () => {
cancelled = true;
};
}, [activeSection, getToken]);
useEffect(() => { useEffect(() => {
if (activeSection !== "apps" || !pageVisible) return; if (activeSection !== "apps" || !pageVisible) return;
let cancelled = false; let cancelled = false;
@@ -9,7 +9,6 @@ import {
type CustomMcpForm, type CustomMcpForm,
} from "@/components/settings/system/AppsSettings"; } from "@/components/settings/system/AppsSettings";
import type { import type {
ApiServicePayload,
AutomationsPayload, AutomationsPayload,
McpOAuthFlowPayload, McpOAuthFlowPayload,
NanobotFeatureInfo, NanobotFeatureInfo,
@@ -45,10 +44,6 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
const [mcpOAuthCallbackUrl, setMcpOAuthCallbackUrl] = useState(""); const [mcpOAuthCallbackUrl, setMcpOAuthCallbackUrl] = useState("");
const [mcpOAuthCompleting, setMcpOAuthCompleting] = useState(false); const [mcpOAuthCompleting, setMcpOAuthCompleting] = useState(false);
const [mcpOAuthCallbackError, setMcpOAuthCallbackError] = useState<string | null>(null); const [mcpOAuthCallbackError, setMcpOAuthCallbackError] = useState<string | null>(null);
const [apiService, setApiService] = useState<ApiServicePayload | null>(null);
const [apiServiceLoading, setApiServiceLoading] = useState(false);
const [apiServiceAction, setApiServiceAction] = useState<"start" | "stop" | null>(null);
const [apiServiceError, setApiServiceError] = useState<string | null>(null);
const [appsQuery, setAppsQuery] = useState(""); const [appsQuery, setAppsQuery] = useState("");
const [automationsFilter, setAutomationsFilter] = useState<AutomationFilter>("all"); const [automationsFilter, setAutomationsFilter] = useState<AutomationFilter>("all");
const [cliAppsMessage, setCliAppsMessage] = useState<string | null>(null); const [cliAppsMessage, setCliAppsMessage] = useState<string | null>(null);
@@ -71,10 +66,6 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
return { return {
toolsCatalog, toolsCatalog,
toolsCatalogInvalidation, toolsCatalogInvalidation,
apiService,
apiServiceAction,
apiServiceError,
apiServiceLoading,
appsKindFilter, appsKindFilter,
appsQuery, appsQuery,
automationAction, automationAction,
@@ -112,10 +103,6 @@ export function useSystemSettingsState(toolsCatalog: ToolsCatalog) {
nanobotFeatures, nanobotFeatures,
nanobotFeaturesError, nanobotFeaturesError,
nanobotFeaturesLoading, nanobotFeaturesLoading,
setApiService,
setApiServiceAction,
setApiServiceError,
setApiServiceLoading,
setAppsKindFilter, setAppsKindFilter,
setAppsQuery, setAppsQuery,
setAutomationAction, setAutomationAction,
@@ -415,10 +415,8 @@ export function useSettingsController({
state: systemState, state: systemState,
featureCatalog, featureCatalog,
client, client,
token,
getToken, getToken,
t, t,
applyPayload,
maybeRestartHostEngine, maybeRestartHostEngine,
setPendingRestartSections, setPendingRestartSections,
refreshAutomations, refreshAutomations,
-34
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "Saved. Restart the API service to apply changes.",
"commandRuntime": { "commandRuntime": {
"custom": "Custom (seconds)", "custom": "Custom (seconds)",
"customLabel": "Custom runtime (seconds)", "customLabel": "Custom runtime (seconds)",
@@ -702,14 +701,6 @@
"label": "Restart mode", "label": "Restart mode",
"help": "Choose a restart method; Automatic follows your environment.\n\nChoose how the gateway restarts. Automatic selects a method for your environment." "help": "Choose a restart method; Automatic follows your environment.\n\nChoose how the gateway restarts. Automatic selects a method for your environment."
}, },
"api_host": {
"label": "API address",
"help": "Set a key before allowing network access; restart the API after changes.\n\nSet an API key in System before binding to a network address. Restart the API service to apply changes."
},
"api_timeout": {
"label": "API timeout",
"help": "Maximum seconds per API request; restart to apply.\n\nHow long each API request can take. Restart the API service to apply changes."
},
"tools_image_generation_save_dir": { "tools_image_generation_save_dir": {
"label": "Save directory", "label": "Save directory",
"help": "Relative path inside the media directory; existing images stay put.\n\nSubdirectory of nanobot’s media directory. Use a relative path; existing images are not moved." "help": "Relative path inside the media directory; existing images stay put.\n\nSubdirectory of nanobot’s media directory. Use a relative path; existing images are not moved."
@@ -768,10 +759,6 @@
"title": "Gateway", "title": "Gateway",
"help": "Set deployment and restart options." "help": "Set deployment and restart options."
}, },
"api": {
"title": "API settings",
"help": "Set the listening address and request timeout."
},
"storage": { "storage": {
"title": "Image storage", "title": "Image storage",
"help": "Choose where generated images are saved." "help": "Choose where generated images are saved."
@@ -1433,27 +1420,6 @@
"searchInstallOnSave": "Required Olostep packages will be installed automatically when you save.", "searchInstallOnSave": "Required Olostep packages will be installed automatically when you save.",
"installing": "Installing required packages…" "installing": "Installing required packages…"
}, },
"api": {
"title": "API server",
"openaiCompatible": "OpenAI-compatible API",
"description": "Connect through an OpenAI-compatible API.",
"start": "Start API server",
"starting": "Starting...",
"stop": "Stop",
"stopping": "Stopping...",
"access": "Access",
"thisDevice": "This device",
"localNetwork": "Local network",
"localHelp": "Only this device can connect.",
"networkHelp": "LAN access requires an API key.\n\nOther devices can connect; an API key is required.",
"port": "Port",
"portHelp": "Local port used by the API service.",
"apiKey": "API key",
"apiKeyHelp": "Send the key as a Bearer token.",
"apiKeyRequired": "Required before exposing the API to your network.",
"apiKeyPlaceholder": "Enter an API key",
"autoInstall": "Required API server packages will be installed automatically when you start it."
},
"observability": { "observability": {
"title": "Run tracing", "title": "Run tracing",
"configured": "Tracing credentials are available to nanobot.", "configured": "Tracing credentials are available to nanobot.",
-14
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "Guardado. Reinicia el servicio API para aplicar los cambios.",
"commandRuntime": { "commandRuntime": {
"custom": "Personalizada (segundos)", "custom": "Personalizada (segundos)",
"customLabel": "Duración personalizada (segundos)", "customLabel": "Duración personalizada (segundos)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "Dirección de la puerta de enlace", "help": "Dirección de la puerta de enlace; configura el listener WebUI aparte.\n\nDirección de escucha de la pasarela. Las direcciones de WebSocket y WebUI se configuran en Canales → WebSocket."}, "gateway_host": {"label": "Dirección de la puerta de enlace", "help": "Dirección de la puerta de enlace; configura el listener WebUI aparte.\n\nDirección de escucha de la pasarela. Las direcciones de WebSocket y WebUI se configuran en Canales → WebSocket."},
"gateway_port": {"label": "Puerto de la pasarela", "help": "Puerto de la puerta de enlace; los argumentos de inicio tienen prioridad.\n\nPuerto guardado. Los argumentos de línea de comandos tienen prioridad."}, "gateway_port": {"label": "Puerto de la pasarela", "help": "Puerto de la puerta de enlace; los argumentos de inicio tienen prioridad.\n\nPuerto guardado. Los argumentos de línea de comandos tienen prioridad."},
"gateway_restart_mode": {"label": "Modo de reinicio", "help": "Elige cómo reiniciar; Automático se adapta al entorno.\n\nMétodo de reinicio del proceso. El modo automático depende del entorno del host."}, "gateway_restart_mode": {"label": "Modo de reinicio", "help": "Elige cómo reiniciar; Automático se adapta al entorno.\n\nMétodo de reinicio del proceso. El modo automático depende del entorno del host."},
"api_host": {"label": "Dirección API", "help": "Configura una clave antes del acceso por red; reinicia la API tras los cambios.\n\nSe requiere una clave API para escuchar en una dirección distinta de localhost. Configúrala en Sistema y reinicia el servicio API para aplicar los cambios."},
"api_timeout": {"label": "Tiempo límite de API", "help": "Segundos máximos por solicitud API; reinicia para aplicar.\n\nDuración máxima de las solicitudes. Reinicia el servicio API para aplicar los cambios."},
"tools_image_generation_save_dir": {"label": "Directorio de guardado", "help": "Ruta relativa dentro del directorio multimedia; las imágenes existentes no se mueven.\n\nRuta relativa dentro de la carpeta multimedia de nanobot. Las imágenes existentes no se mueven."} "tools_image_generation_save_dir": {"label": "Directorio de guardado", "help": "Ruta relativa dentro del directorio multimedia; las imágenes existentes no se mueven.\n\nRuta relativa dentro de la carpeta multimedia de nanobot. Las imágenes existentes no se mueven."}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "Permisos globales", "help": "Configura límites del espacio, excepciones de red e instalaciones remotas.\n\nRestricciones del espacio de trabajo, redes privadas e instalaciones remotas."}, "safety": {"title": "Permisos globales", "help": "Configura límites del espacio, excepciones de red e instalaciones remotas.\n\nRestricciones del espacio de trabajo, redes privadas e instalaciones remotas."},
"cli": {"title": "Límites CLI", "help": "Configura tiempos límite de instalación y ejecución y la duración de caché.\n\nTiempos de instalación, ejecución y caché del catálogo."}, "cli": {"title": "Límites CLI", "help": "Configura tiempos límite de instalación y ejecución y la duración de caché.\n\nTiempos de instalación, ejecución y caché del catálogo."},
"gateway": {"title": "Puerta de enlace", "help": "Configura el despliegue y el reinicio."}, "gateway": {"title": "Puerta de enlace", "help": "Configura el despliegue y el reinicio."},
"api": {"title": "Ajustes API", "help": "Configura la dirección de escucha y el tiempo límite de solicitudes."},
"storage": {"title": "Almacenamiento de imágenes", "help": "Elige dónde guardar las imágenes generadas."}, "storage": {"title": "Almacenamiento de imágenes", "help": "Elige dónde guardar las imágenes generadas."},
"maintenance": {"title": "Organización de memoria", "help": ""}, "maintenance": {"title": "Organización de memoria", "help": ""},
"web": {"title": "Acceso web", "help": ""}, "web": {"title": "Acceso web", "help": ""},
@@ -1238,16 +1234,6 @@
"supabase": "Consulta y gestiona proyectos." "supabase": "Consulta y gestiona proyectos."
} }
}, },
"api": {
"title": "Servidor API", "openaiCompatible": "API compatible con OpenAI",
"description": "Conecta mediante una API compatible con OpenAI.",
"start": "Iniciar servidor API", "starting": "Iniciando...", "stop": "Detener", "stopping": "Deteniendo...",
"access": "Acceso", "thisDevice": "Este dispositivo", "localNetwork": "Red local",
"localHelp": "Solo este dispositivo puede conectarse.", "networkHelp": "El acceso desde la red local requiere una clave API.\n\nOtros dispositivos pueden conectarse; se requiere una clave API.",
"port": "Puerto", "portHelp": "Puerto local del servicio API.", "apiKey": "Clave API",
"apiKeyHelp": "Envía la clave como Bearer token.", "apiKeyRequired": "Obligatoria antes de exponer la API en la red.",
"apiKeyPlaceholder": "Introduce una clave API", "autoInstall": "Las dependencias del servidor API se instalarán automáticamente al iniciarlo."
},
"observability": { "observability": {
"title": "Trazas de ejecución", "configured": "Las credenciales de trazas están disponibles para nanobot.", "title": "Trazas de ejecución", "configured": "Las credenciales de trazas están disponibles para nanobot.",
"environment": "Configura LANGFUSE_SECRET_KEY y LANGFUSE_PUBLIC_KEY y reinicia nanobot.", "enable": "Activar trazas" "environment": "Configura LANGFUSE_SECRET_KEY y LANGFUSE_PUBLIC_KEY y reinicia nanobot.", "enable": "Activar trazas"
-13
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "Enregistré. Redémarrez le service API pour appliquer les modifications.",
"commandRuntime": { "commandRuntime": {
"custom": "Personnalisée (secondes)", "custom": "Personnalisée (secondes)",
"customLabel": "Durée personnalisée (secondes)", "customLabel": "Durée personnalisée (secondes)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "Adresse de la passerelle", "help": "Adresse de la passerelle ; configurez l’écoute WebUI séparément.\n\nAdresse d’écoute de la passerelle. L’adresse de WebSocket et de la WebUI se règle dans Canaux → WebSocket."}, "gateway_host": {"label": "Adresse de la passerelle", "help": "Adresse de la passerelle ; configurez l’écoute WebUI séparément.\n\nAdresse d’écoute de la passerelle. L’adresse de WebSocket et de la WebUI se règle dans Canaux → WebSocket."},
"gateway_port": {"label": "Port de la passerelle", "help": "Port de la passerelle ; les arguments de lancement sont prioritaires.\n\nPort enregistré. Les arguments de ligne de commande ont priorité."}, "gateway_port": {"label": "Port de la passerelle", "help": "Port de la passerelle ; les arguments de lancement sont prioritaires.\n\nPort enregistré. Les arguments de ligne de commande ont priorité."},
"gateway_restart_mode": {"label": "Mode de redémarrage", "help": "Choisissez le redémarrage ; Automatique suit votre environnement.\n\nMode de redémarrage du processus. Le mode automatique dépend de l’environnement hôte."}, "gateway_restart_mode": {"label": "Mode de redémarrage", "help": "Choisissez le redémarrage ; Automatique suit votre environnement.\n\nMode de redémarrage du processus. Le mode automatique dépend de l’environnement hôte."},
"api_host": {"label": "Adresse API", "help": "Définissez une clé avant l’accès réseau ; redémarrez l’API après modification.\n\nUne clé API est requise pour écouter sur une adresse autre que localhost. Configurez-la dans Système, puis redémarrez le service API pour appliquer les modifications."},
"api_timeout": {"label": "Délai API", "help": "Secondes maximales par requête API ; redémarrez pour appliquer.\n\nDurée maximale des requêtes. Redémarrez le service API pour appliquer les modifications."},
"tools_image_generation_save_dir": {"label": "Dossier de sauvegarde", "help": "Chemin relatif dans le dossier des médias ; les images existantes ne sont pas déplacées.\n\nChemin relatif sous le dossier multimédia de nanobot. Les images existantes ne sont pas déplacées."} "tools_image_generation_save_dir": {"label": "Dossier de sauvegarde", "help": "Chemin relatif dans le dossier des médias ; les images existantes ne sont pas déplacées.\n\nChemin relatif sous le dossier multimédia de nanobot. Les images existantes ne sont pas déplacées."}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "Permissions globales", "help": "Réglez les limites de l’espace, les exceptions réseau et les installations distantes.\n\nRestrictions de l’espace de travail, réseaux privés et installations à distance."}, "safety": {"title": "Permissions globales", "help": "Réglez les limites de l’espace, les exceptions réseau et les installations distantes.\n\nRestrictions de l’espace de travail, réseaux privés et installations à distance."},
"cli": {"title": "Limites CLI", "help": "Réglez les délais d’installation et d’exécution, et la durée du cache.\n\nDélais d’installation, d’exécution et de cache du catalogue."}, "cli": {"title": "Limites CLI", "help": "Réglez les délais d’installation et d’exécution, et la durée du cache.\n\nDélais d’installation, d’exécution et de cache du catalogue."},
"gateway": {"title": "Passerelle", "help": "Réglez le déploiement et le redémarrage."}, "gateway": {"title": "Passerelle", "help": "Réglez le déploiement et le redémarrage."},
"api": {"title": "Réglages API", "help": "Réglez l’adresse d’écoute et le délai des requêtes."},
"storage": {"title": "Stockage des images", "help": "Choisissez où enregistrer les images générées."}, "storage": {"title": "Stockage des images", "help": "Choisissez où enregistrer les images générées."},
"maintenance": {"title": "Organisation de la mémoire", "help": ""}, "maintenance": {"title": "Organisation de la mémoire", "help": ""},
"web": {"title": "Accès web", "help": ""}, "web": {"title": "Accès web", "help": ""},
@@ -1238,15 +1234,6 @@
"supabase": "Consultez et gérez les projets." "supabase": "Consultez et gérez les projets."
} }
}, },
"api": {
"title": "Serveur API", "openaiCompatible": "API compatible OpenAI", "description": "Connectez-vous via une API compatible OpenAI.",
"start": "Démarrer le serveur API", "starting": "Démarrage...", "stop": "Arrêter", "stopping": "Arrêt...",
"access": "Accès", "thisDevice": "Cet appareil", "localNetwork": "Réseau local",
"localHelp": "Seul cet appareil peut se connecter.", "networkHelp": "L’accès réseau local nécessite une clé API.\n\nD’autres appareils peuvent se connecter ; une clé API est requise.",
"port": "Port", "portHelp": "Port local du service API.", "apiKey": "Clé API", "apiKeyHelp": "Envoyez la clé comme Bearer token.",
"apiKeyRequired": "Requise avant d’exposer l’API au réseau.", "apiKeyPlaceholder": "Saisissez une clé API",
"autoInstall": "Les dépendances du serveur API seront installées automatiquement au démarrage."
},
"observability": { "observability": {
"title": "Traces d’exécution", "configured": "Les identifiants de traçage sont disponibles pour nanobot.", "title": "Traces d’exécution", "configured": "Les identifiants de traçage sont disponibles pour nanobot.",
"environment": "Définissez LANGFUSE_SECRET_KEY et LANGFUSE_PUBLIC_KEY, puis redémarrez nanobot.", "enable": "Activer les traces" "environment": "Définissez LANGFUSE_SECRET_KEY et LANGFUSE_PUBLIC_KEY, puis redémarrez nanobot.", "enable": "Activer les traces"
-13
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "Tersimpan. Mulai ulang layanan API untuk menerapkan perubahan.",
"commandRuntime": { "commandRuntime": {
"custom": "Kustom (detik)", "custom": "Kustom (detik)",
"customLabel": "Durasi kustom (detik)", "customLabel": "Durasi kustom (detik)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "Alamat gateway", "help": "Alamat gateway; atur listener WebUI secara terpisah.\n\nAlamat tempat gateway menerima koneksi. Alamat WebSocket dan WebUI diatur di Kanal → WebSocket."}, "gateway_host": {"label": "Alamat gateway", "help": "Alamat gateway; atur listener WebUI secara terpisah.\n\nAlamat tempat gateway menerima koneksi. Alamat WebSocket dan WebUI diatur di Kanal → WebSocket."},
"gateway_port": {"label": "Port gateway", "help": "Port gateway; argumen peluncuran diutamakan.\n\nPort yang disimpan. Argumen baris perintah lebih diutamakan."}, "gateway_port": {"label": "Port gateway", "help": "Port gateway; argumen peluncuran diutamakan.\n\nPort yang disimpan. Argumen baris perintah lebih diutamakan."},
"gateway_restart_mode": {"label": "Mode mulai ulang", "help": "Pilih cara mulai ulang; Otomatis mengikuti lingkungan.\n\nCara memulai ulang proses. Mode otomatis memilih berdasarkan lingkungan host."}, "gateway_restart_mode": {"label": "Mode mulai ulang", "help": "Pilih cara mulai ulang; Otomatis mengikuti lingkungan.\n\nCara memulai ulang proses. Mode otomatis memilih berdasarkan lingkungan host."},
"api_host": {"label": "Alamat API", "help": "Tetapkan kunci sebelum akses jaringan; mulai ulang API setelah perubahan.\n\nKunci API diperlukan untuk menerima koneksi pada alamat selain localhost. Atur kunci di Sistem, lalu mulai ulang layanan API untuk menerapkan perubahan."},
"api_timeout": {"label": "Batas waktu API", "help": "Batas detik tiap permintaan API; mulai ulang untuk menerapkan.\n\nDurasi maksimum permintaan. Mulai ulang layanan API untuk menerapkan perubahan."},
"tools_image_generation_save_dir": {"label": "Direktori penyimpanan", "help": "Lokasi relatif dalam direktori media; gambar yang ada tidak dipindahkan.\n\nJalur relatif di dalam folder media nanobot. Gambar yang ada tidak dipindahkan."} "tools_image_generation_save_dir": {"label": "Direktori penyimpanan", "help": "Lokasi relatif dalam direktori media; gambar yang ada tidak dipindahkan.\n\nJalur relatif di dalam folder media nanobot. Gambar yang ada tidak dipindahkan."}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "Izin global", "help": "Atur batas ruang kerja, pengecualian jaringan, dan pemasangan jarak jauh.\n\nPembatasan ruang kerja, jaringan privat, dan instalasi jarak jauh."}, "safety": {"title": "Izin global", "help": "Atur batas ruang kerja, pengecualian jaringan, dan pemasangan jarak jauh.\n\nPembatasan ruang kerja, jaringan privat, dan instalasi jarak jauh."},
"cli": {"title": "Batas CLI", "help": "Atur batas waktu pemasangan dan eksekusi, serta durasi cache daftar.\n\nBatas waktu instalasi, eksekusi, dan cache katalog."}, "cli": {"title": "Batas CLI", "help": "Atur batas waktu pemasangan dan eksekusi, serta durasi cache daftar.\n\nBatas waktu instalasi, eksekusi, dan cache katalog."},
"gateway": {"title": "Gateway", "help": "Atur opsi penerapan dan mulai ulang."}, "gateway": {"title": "Gateway", "help": "Atur opsi penerapan dan mulai ulang."},
"api": {"title": "Pengaturan API", "help": "Atur alamat listener dan batas waktu permintaan."},
"storage": {"title": "Penyimpanan gambar", "help": "Pilih lokasi penyimpanan gambar yang dibuat."}, "storage": {"title": "Penyimpanan gambar", "help": "Pilih lokasi penyimpanan gambar yang dibuat."},
"maintenance": {"title": "Pengaturan memori", "help": ""}, "maintenance": {"title": "Pengaturan memori", "help": ""},
"web": {"title": "Akses web", "help": ""}, "web": {"title": "Akses web", "help": ""},
@@ -1238,15 +1234,6 @@
"supabase": "Lihat dan kelola proyek." "supabase": "Lihat dan kelola proyek."
} }
}, },
"api": {
"title": "Server API", "openaiCompatible": "API kompatibel OpenAI", "description": "Hubungkan melalui API yang kompatibel dengan OpenAI.",
"start": "Mulai server API", "starting": "Memulai...", "stop": "Hentikan", "stopping": "Menghentikan...",
"access": "Akses", "thisDevice": "Perangkat ini", "localNetwork": "Jaringan lokal",
"localHelp": "Hanya perangkat ini yang dapat terhubung.", "networkHelp": "Akses LAN memerlukan kunci API.\n\nPerangkat lain dapat terhubung; kunci API diperlukan.",
"port": "Port", "portHelp": "Port lokal untuk layanan API.", "apiKey": "Kunci API", "apiKeyHelp": "Kirim kunci sebagai Bearer token.",
"apiKeyRequired": "Wajib sebelum membuka API ke jaringan.", "apiKeyPlaceholder": "Masukkan kunci API",
"autoInstall": "Paket yang diperlukan server API akan dipasang otomatis saat server dimulai."
},
"observability": { "observability": {
"title": "Pelacakan eksekusi", "configured": "Kredensial pelacakan sudah tersedia untuk nanobot.", "title": "Pelacakan eksekusi", "configured": "Kredensial pelacakan sudah tersedia untuk nanobot.",
"environment": "Atur LANGFUSE_SECRET_KEY dan LANGFUSE_PUBLIC_KEY, lalu mulai ulang nanobot.", "enable": "Aktifkan pelacakan" "environment": "Atur LANGFUSE_SECRET_KEY dan LANGFUSE_PUBLIC_KEY, lalu mulai ulang nanobot.", "enable": "Aktifkan pelacakan"
-13
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "保存しました。API サービスを再起動すると反映されます。",
"commandRuntime": { "commandRuntime": {
"custom": "カスタム(秒)", "custom": "カスタム(秒)",
"customLabel": "カスタム実行時間(秒)", "customLabel": "カスタム実行時間(秒)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "ゲートウェイアドレス", "help": "ゲートウェイのアドレスです。WebUI の待ち受けは別に設定します。\n\nゲートウェイの待ち受けアドレスです。WebSocket と WebUI のアドレスは「チャンネル → WebSocket」で設定します。"}, "gateway_host": {"label": "ゲートウェイアドレス", "help": "ゲートウェイのアドレスです。WebUI の待ち受けは別に設定します。\n\nゲートウェイの待ち受けアドレスです。WebSocket と WebUI のアドレスは「チャンネル → WebSocket」で設定します。"},
"gateway_port": {"label": "ゲートウェイのポート", "help": "ゲートウェイのポートです。起動引数が優先されます。\n\n保存するポート番号。コマンドライン引数が優先されます。"}, "gateway_port": {"label": "ゲートウェイのポート", "help": "ゲートウェイのポートです。起動引数が優先されます。\n\n保存するポート番号。コマンドライン引数が優先されます。"},
"gateway_restart_mode": {"label": "再起動モード", "help": "再起動方法を選びます。「自動」は環境に合わせます。\n\nプロセスの再起動方法。自動モードではホスト環境に応じて選択します。"}, "gateway_restart_mode": {"label": "再起動モード", "help": "再起動方法を選びます。「自動」は環境に合わせます。\n\nプロセスの再起動方法。自動モードではホスト環境に応じて選択します。"},
"api_host": {"label": "API アドレス", "help": "ネットワーク公開前にキーを設定し、変更後は API を再起動します。\n\nlocalhost 以外のアドレスで待ち受けるには API キーが必要です。「システム」でキーを設定し、API サービスを再起動して変更を反映してください。"},
"api_timeout": {"label": "API 制限時間", "help": "API 要求の最大秒数です。適用には再起動が必要です。\n\nリクエストの時間制限です。API サービスの再起動後に反映されます。"},
"tools_image_generation_save_dir": {"label": "保存先", "help": "メディア内の相対パスです。既存の画像は移動しません。\n\nnanobot のメディアディレクトリ内の相対パス。既存の画像は移動しません。"} "tools_image_generation_save_dir": {"label": "保存先", "help": "メディア内の相対パスです。既存の画像は移動しません。\n\nnanobot のメディアディレクトリ内の相対パス。既存の画像は移動しません。"}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "全体の権限", "help": "ワークスペース制限、ネットワーク例外、リモートインストールを設定します。\n\nワークスペース制限、プライベートネットワーク、リモートインストール。"}, "safety": {"title": "全体の権限", "help": "ワークスペース制限、ネットワーク例外、リモートインストールを設定します。\n\nワークスペース制限、プライベートネットワーク、リモートインストール。"},
"cli": {"title": "CLI 制限", "help": "インストール・実行の制限時間と一覧のキャッシュ期間を設定します。\n\nインストール、実行、カタログキャッシュの時間制限。"}, "cli": {"title": "CLI 制限", "help": "インストール・実行の制限時間と一覧のキャッシュ期間を設定します。\n\nインストール、実行、カタログキャッシュの時間制限。"},
"gateway": {"title": "ゲートウェイ", "help": "配置と再起動の方法を設定します。"}, "gateway": {"title": "ゲートウェイ", "help": "配置と再起動の方法を設定します。"},
"api": {"title": "API 設定", "help": "待ち受けアドレスと要求の制限時間を設定します。"},
"storage": {"title": "画像の保存", "help": "生成した画像の保存先を選びます。"}, "storage": {"title": "画像の保存", "help": "生成した画像の保存先を選びます。"},
"maintenance": {"title": "メモリー整理", "help": ""}, "maintenance": {"title": "メモリー整理", "help": ""},
"web": {"title": "ウェブアクセス", "help": ""}, "web": {"title": "ウェブアクセス", "help": ""},
@@ -1238,15 +1234,6 @@
"supabase": "プロジェクトを確認・管理します。" "supabase": "プロジェクトを確認・管理します。"
} }
}, },
"api": {
"title": "API サーバー", "openaiCompatible": "OpenAI 互換 API", "description": "OpenAI 互換の API で接続します。",
"start": "API サーバーを起動", "starting": "起動中...", "stop": "停止", "stopping": "停止中...",
"access": "アクセス", "thisDevice": "このデバイス", "localNetwork": "ローカルネットワーク",
"localHelp": "この端末だけが接続できます。", "networkHelp": "LAN からのアクセスには API キーが必要です。\n\n他のデバイスも接続できるため API キーが必要です。",
"port": "ポート", "portHelp": "API サービスが使うローカルポートです。", "apiKey": "API キー", "apiKeyHelp": "キーを Bearer Token として送信します。",
"apiKeyRequired": "ネットワークに公開する前に必要です。", "apiKeyPlaceholder": "API キーを入力",
"autoInstall": "起動時に API サーバーに必要なパッケージを自動的にインストールします。"
},
"observability": { "observability": {
"title": "実行の追跡", "configured": "nanobot がトレース認証情報を利用できます。", "title": "実行の追跡", "configured": "nanobot がトレース認証情報を利用できます。",
"environment": "LANGFUSE_SECRET_KEY と LANGFUSE_PUBLIC_KEY を設定して nanobot を再起動してください。", "enable": "追跡を有効化" "environment": "LANGFUSE_SECRET_KEY と LANGFUSE_PUBLIC_KEY を設定して nanobot を再起動してください。", "enable": "追跡を有効化"
-13
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "저장했습니다. API 서비스를 다시 시작하면 적용됩니다.",
"commandRuntime": { "commandRuntime": {
"custom": "사용자 지정(초)", "custom": "사용자 지정(초)",
"customLabel": "사용자 지정 실행 시간(초)", "customLabel": "사용자 지정 실행 시간(초)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "게이트웨이 주소", "help": "게이트웨이 주소입니다. WebUI 수신 주소는 별도로 설정합니다.\n\n게이트웨이가 연결을 수신하는 주소입니다. WebSocket과 WebUI 주소는 채널 → WebSocket에서 설정합니다."}, "gateway_host": {"label": "게이트웨이 주소", "help": "게이트웨이 주소입니다. WebUI 수신 주소는 별도로 설정합니다.\n\n게이트웨이가 연결을 수신하는 주소입니다. WebSocket과 WebUI 주소는 채널 → WebSocket에서 설정합니다."},
"gateway_port": {"label": "게이트웨이 포트", "help": "게이트웨이 포트입니다. 시작 인수가 우선합니다.\n\n저장할 포트입니다. 명령줄 인수가 우선 적용됩니다."}, "gateway_port": {"label": "게이트웨이 포트", "help": "게이트웨이 포트입니다. 시작 인수가 우선합니다.\n\n저장할 포트입니다. 명령줄 인수가 우선 적용됩니다."},
"gateway_restart_mode": {"label": "다시 시작 방식", "help": "재시작 방법을 선택하세요. 자동은 실행 환경에 맞춥니다.\n\n프로세스를 다시 시작하는 방식입니다. 자동 모드는 호스트 환경에 따라 선택합니다."}, "gateway_restart_mode": {"label": "다시 시작 방식", "help": "재시작 방법을 선택하세요. 자동은 실행 환경에 맞춥니다.\n\n프로세스를 다시 시작하는 방식입니다. 자동 모드는 호스트 환경에 따라 선택합니다."},
"api_host": {"label": "API 주소", "help": "네트워크 접근 허용 전 키를 설정하고, 변경 후 API를 재시작하세요.\n\nlocalhost 이외의 주소에서 연결을 받으려면 API 키가 필요합니다. 시스템에서 키를 설정하고 API 서비스를 다시 시작해 변경 사항을 적용하세요."},
"api_timeout": {"label": "API 제한 시간", "help": "API 요청당 최대 초입니다. 적용하려면 재시작하세요.\n\n요청에 허용되는 최대 시간입니다. API 서비스를 다시 시작하면 적용됩니다."},
"tools_image_generation_save_dir": {"label": "저장 디렉터리", "help": "미디어 디렉터리 내부의 상대 경로입니다. 기존 이미지는 이동하지 않습니다.\n\nnanobot 미디어 폴더 아래의 상대 경로입니다. 기존 이미지는 이동하지 않습니다."} "tools_image_generation_save_dir": {"label": "저장 디렉터리", "help": "미디어 디렉터리 내부의 상대 경로입니다. 기존 이미지는 이동하지 않습니다.\n\nnanobot 미디어 폴더 아래의 상대 경로입니다. 기존 이미지는 이동하지 않습니다."}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "전체 권한", "help": "작업 공간 제한, 네트워크 예외 및 원격 설치를 설정하세요.\n\n작업 공간 제한, 사설 네트워크 및 원격 설치입니다."}, "safety": {"title": "전체 권한", "help": "작업 공간 제한, 네트워크 예외 및 원격 설치를 설정하세요.\n\n작업 공간 제한, 사설 네트워크 및 원격 설치입니다."},
"cli": {"title": "CLI 제한", "help": "설치와 실행 제한 시간, 목록 캐시 시간을 설정하세요.\n\n설치, 실행 및 카탈로그 캐시의 시간 제한입니다."}, "cli": {"title": "CLI 제한", "help": "설치와 실행 제한 시간, 목록 캐시 시간을 설정하세요.\n\n설치, 실행 및 카탈로그 캐시의 시간 제한입니다."},
"gateway": {"title": "게이트웨이", "help": "배포와 재시작 옵션을 설정하세요."}, "gateway": {"title": "게이트웨이", "help": "배포와 재시작 옵션을 설정하세요."},
"api": {"title": "API 설정", "help": "수신 주소와 요청 제한 시간을 설정하세요."},
"storage": {"title": "이미지 저장", "help": "생성한 이미지의 저장 위치를 선택하세요."}, "storage": {"title": "이미지 저장", "help": "생성한 이미지의 저장 위치를 선택하세요."},
"maintenance": {"title": "메모리 정리", "help": ""}, "maintenance": {"title": "메모리 정리", "help": ""},
"web": {"title": "웹 접근", "help": ""}, "web": {"title": "웹 접근", "help": ""},
@@ -1238,15 +1234,6 @@
"supabase": "프로젝트를 확인하고 관리합니다." "supabase": "프로젝트를 확인하고 관리합니다."
} }
}, },
"api": {
"title": "API 서버", "openaiCompatible": "OpenAI 호환 API", "description": "OpenAI 호환 API로 연결합니다.",
"start": "API 서버 시작", "starting": "시작 중...", "stop": "중지", "stopping": "중지 중...",
"access": "접근", "thisDevice": "이 기기", "localNetwork": "로컬 네트워크",
"localHelp": "이 기기만 연결할 수 있습니다.", "networkHelp": "LAN 접근에는 API 키가 필요합니다.\n\n다른 기기도 연결할 수 있으므로 API 키가 필요합니다.",
"port": "포트", "portHelp": "API 서비스가 사용하는 로컬 포트입니다.", "apiKey": "API 키", "apiKeyHelp": "키를 Bearer Token으로 전송합니다.",
"apiKeyRequired": "네트워크에 공개하기 전에 필요합니다.", "apiKeyPlaceholder": "API 키 입력",
"autoInstall": "서버를 시작할 때 필요한 패키지를 자동으로 설치합니다."
},
"observability": { "observability": {
"title": "실행 추적", "configured": "nanobot이 추적 인증 정보을 사용할 수 있습니다.", "title": "실행 추적", "configured": "nanobot이 추적 인증 정보을 사용할 수 있습니다.",
"environment": "LANGFUSE_SECRET_KEY와 LANGFUSE_PUBLIC_KEY를 설정한 뒤 nanobot을 다시 시작하세요.", "enable": "추적 활성화" "environment": "LANGFUSE_SECRET_KEY와 LANGFUSE_PUBLIC_KEY를 설정한 뒤 nanobot을 다시 시작하세요.", "enable": "추적 활성화"
-25
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "Salvo. Reinicie o serviço de API para aplicar as alterações.",
"commandRuntime": { "commandRuntime": {
"custom": "Personalizada (segundos)", "custom": "Personalizada (segundos)",
"customLabel": "Duração personalizada (segundos)", "customLabel": "Duração personalizada (segundos)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "Endereço do gateway", "help": "Endereço do gateway; configure a escuta WebUI separadamente.\n\nEndereço em que o gateway recebe conexões. Os endereços de WebSocket e WebUI são configurados em Canais → WebSocket."}, "gateway_host": {"label": "Endereço do gateway", "help": "Endereço do gateway; configure a escuta WebUI separadamente.\n\nEndereço em que o gateway recebe conexões. Os endereços de WebSocket e WebUI são configurados em Canais → WebSocket."},
"gateway_port": {"label": "Porta do gateway", "help": "Porta do gateway; os argumentos de inicialização têm prioridade.\n\nPorta salva. Os argumentos de linha de comando têm prioridade."}, "gateway_port": {"label": "Porta do gateway", "help": "Porta do gateway; os argumentos de inicialização têm prioridade.\n\nPorta salva. Os argumentos de linha de comando têm prioridade."},
"gateway_restart_mode": {"label": "Modo de reinicialização", "help": "Escolha como reiniciar; Automático segue o ambiente.\n\nMétodo de reinicialização do processo. O modo automático depende do ambiente do host."}, "gateway_restart_mode": {"label": "Modo de reinicialização", "help": "Escolha como reiniciar; Automático segue o ambiente.\n\nMétodo de reinicialização do processo. O modo automático depende do ambiente do host."},
"api_host": {"label": "Endereço da API", "help": "Defina uma chave antes do acesso pela rede; reinicie a API após alterações.\n\nÉ necessária uma chave de API para receber conexões em um endereço diferente de localhost. Configure a chave em Sistema e reinicie o serviço de API para aplicar as alterações."},
"api_timeout": {"label": "Tempo limite da API", "help": "Máximo de segundos por solicitação API; reinicie para aplicar.\n\nDuração máxima das solicitações. Reinicie o serviço de API para aplicar as alterações."},
"tools_image_generation_save_dir": {"label": "Pasta de destino", "help": "Caminho relativo dentro da pasta de mídia; imagens existentes não são movidas.\n\nCaminho relativo dentro da pasta de mídia do nanobot. As imagens existentes não são movidas."} "tools_image_generation_save_dir": {"label": "Pasta de destino", "help": "Caminho relativo dentro da pasta de mídia; imagens existentes não são movidas.\n\nCaminho relativo dentro da pasta de mídia do nanobot. As imagens existentes não são movidas."}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "Permissões globais", "help": "Configure limites do espaço, exceções de rede e instalações remotas.\n\nRestrições do espaço de trabalho, redes privadas e instalações remotas."}, "safety": {"title": "Permissões globais", "help": "Configure limites do espaço, exceções de rede e instalações remotas.\n\nRestrições do espaço de trabalho, redes privadas e instalações remotas."},
"cli": {"title": "Limites CLI", "help": "Configure tempos limite de instalação e execução e duração do cache.\n\nTempos de instalação, execução e cache do catálogo."}, "cli": {"title": "Limites CLI", "help": "Configure tempos limite de instalação e execução e duração do cache.\n\nTempos de instalação, execução e cache do catálogo."},
"gateway": {"title": "Gateway", "help": "Configure implantação e reinício."}, "gateway": {"title": "Gateway", "help": "Configure implantação e reinício."},
"api": {"title": "Ajustes da API", "help": "Configure o endereço de escuta e o tempo limite das solicitações."},
"storage": {"title": "Armazenamento de imagens", "help": "Escolha onde salvar as imagens geradas."}, "storage": {"title": "Armazenamento de imagens", "help": "Escolha onde salvar as imagens geradas."},
"maintenance": {"title": "Organização de memória", "help": ""}, "maintenance": {"title": "Organização de memória", "help": ""},
"web": {"title": "Acesso web", "help": ""}, "web": {"title": "Acesso web", "help": ""},
@@ -1241,27 +1237,6 @@
"searchInstallOnSave": "As dependências do Olostep serão instaladas automaticamente ao salvar.", "searchInstallOnSave": "As dependências do Olostep serão instaladas automaticamente ao salvar.",
"installing": "Instalando dependências…" "installing": "Instalando dependências…"
}, },
"api": {
"title": "Servidor de API",
"openaiCompatible": "API compatível com OpenAI",
"description": "Conecte por uma API compatível com OpenAI.",
"start": "Iniciar servidor de API",
"starting": "Iniciando...",
"stop": "Parar",
"stopping": "Parando...",
"access": "Acesso",
"thisDevice": "Este dispositivo",
"localNetwork": "Rede local",
"localHelp": "Somente este dispositivo pode conectar.",
"networkHelp": "O acesso pela LAN exige uma chave API.\n\nOutros dispositivos podem se conectar; é necessária uma chave de API.",
"port": "Porta",
"portHelp": "Porta local do serviço API.",
"apiKey": "Chave de API",
"apiKeyHelp": "Envie a chave como Bearer token.",
"apiKeyRequired": "Obrigatória antes de expor a API na rede.",
"apiKeyPlaceholder": "Informe uma chave de API",
"autoInstall": "As dependências do servidor de API serão instaladas automaticamente ao iniciá-lo."
},
"observability": { "observability": {
"title": "Rastreamento de execução", "title": "Rastreamento de execução",
"configured": "As credenciais de rastreamento estão disponíveis para o nanobot.", "configured": "As credenciais de rastreamento estão disponíveis para o nanobot.",
-13
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "Đã lưu. Khởi động lại dịch vụ API để áp dụng thay đổi.",
"commandRuntime": { "commandRuntime": {
"custom": "Tùy chỉnh (giây)", "custom": "Tùy chỉnh (giây)",
"customLabel": "Thời gian chạy tùy chỉnh (giây)", "customLabel": "Thời gian chạy tùy chỉnh (giây)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "Địa chỉ gateway", "help": "Địa chỉ gateway; đặt địa chỉ lắng nghe WebUI riêng.\n\nĐịa chỉ gateway dùng để nhận kết nối. Địa chỉ WebSocket và WebUI được cấu hình trong Kênh → WebSocket."}, "gateway_host": {"label": "Địa chỉ gateway", "help": "Địa chỉ gateway; đặt địa chỉ lắng nghe WebUI riêng.\n\nĐịa chỉ gateway dùng để nhận kết nối. Địa chỉ WebSocket và WebUI được cấu hình trong Kênh → WebSocket."},
"gateway_port": {"label": "Cổng gateway", "help": "Cổng gateway; tham số khởi chạy được ưu tiên.\n\nCổng được lưu. Tham số dòng lệnh được ưu tiên."}, "gateway_port": {"label": "Cổng gateway", "help": "Cổng gateway; tham số khởi chạy được ưu tiên.\n\nCổng được lưu. Tham số dòng lệnh được ưu tiên."},
"gateway_restart_mode": {"label": "Chế độ khởi động lại", "help": "Chọn cách khởi động lại; Tự động dựa theo môi trường.\n\nCách khởi động lại tiến trình. Chế độ tự động chọn theo môi trường máy chủ."}, "gateway_restart_mode": {"label": "Chế độ khởi động lại", "help": "Chọn cách khởi động lại; Tự động dựa theo môi trường.\n\nCách khởi động lại tiến trình. Chế độ tự động chọn theo môi trường máy chủ."},
"api_host": {"label": "Địa chỉ API", "help": "Đặt khóa trước khi cho phép truy cập mạng; khởi động lại API sau thay đổi.\n\nCần khóa API khi nhận kết nối trên địa chỉ khác localhost. Đặt khóa trong Hệ thống rồi khởi động lại dịch vụ API để áp dụng thay đổi."},
"api_timeout": {"label": "Thời hạn API", "help": "Số giây mỗi yêu cầu API tối đa; khởi động lại để áp dụng.\n\nThời gian tối đa của yêu cầu. Khởi động lại dịch vụ API để áp dụng."},
"tools_image_generation_save_dir": {"label": "Thư mục lưu", "help": "Đường dẫn tương đối trong thư mục media; không chuyển ảnh có sẵn.\n\nĐường dẫn tương đối trong thư mục phương tiện của nanobot. Ảnh hiện có không bị di chuyển."} "tools_image_generation_save_dir": {"label": "Thư mục lưu", "help": "Đường dẫn tương đối trong thư mục media; không chuyển ảnh có sẵn.\n\nĐường dẫn tương đối trong thư mục phương tiện của nanobot. Ảnh hiện có không bị di chuyển."}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "Quyền chung", "help": "Đặt giới hạn vùng làm việc, ngoại lệ mạng và cài đặt từ xa.\n\nGiới hạn không gian làm việc, mạng riêng và cài đặt từ xa."}, "safety": {"title": "Quyền chung", "help": "Đặt giới hạn vùng làm việc, ngoại lệ mạng và cài đặt từ xa.\n\nGiới hạn không gian làm việc, mạng riêng và cài đặt từ xa."},
"cli": {"title": "Giới hạn CLI", "help": "Đặt thời hạn cài đặt, chạy và thời gian cache danh sách.\n\nGiới hạn thời gian cài đặt, thực thi và lưu đệm danh mục."}, "cli": {"title": "Giới hạn CLI", "help": "Đặt thời hạn cài đặt, chạy và thời gian cache danh sách.\n\nGiới hạn thời gian cài đặt, thực thi và lưu đệm danh mục."},
"gateway": {"title": "Gateway", "help": "Đặt cách triển khai và khởi động lại."}, "gateway": {"title": "Gateway", "help": "Đặt cách triển khai và khởi động lại."},
"api": {"title": "Thiết lập API", "help": "Đặt địa chỉ lắng nghe và thời hạn yêu cầu."},
"storage": {"title": "Lưu trữ ảnh", "help": "Chọn nơi lưu ảnh được tạo."}, "storage": {"title": "Lưu trữ ảnh", "help": "Chọn nơi lưu ảnh được tạo."},
"maintenance": {"title": "Sắp xếp bộ nhớ", "help": ""}, "maintenance": {"title": "Sắp xếp bộ nhớ", "help": ""},
"web": {"title": "Truy cập web", "help": ""}, "web": {"title": "Truy cập web", "help": ""},
@@ -1238,15 +1234,6 @@
"supabase": "Xem và quản lý dự án." "supabase": "Xem và quản lý dự án."
} }
}, },
"api": {
"title": "Máy chủ API", "openaiCompatible": "API tương thích OpenAI", "description": "Kết nối qua API tương thích OpenAI.",
"start": "Khởi động API", "starting": "Đang khởi động...", "stop": "Dừng", "stopping": "Đang dừng...",
"access": "Truy cập", "thisDevice": "Thiết bị này", "localNetwork": "Mạng nội bộ",
"localHelp": "Chỉ thiết bị này có thể kết nối.", "networkHelp": "Truy cập LAN cần khóa API.\n\nThiết bị khác có thể kết nối; cần khóa API.",
"port": "Cổng", "portHelp": "Cổng cục bộ dịch vụ API sử dụng.", "apiKey": "Khóa API", "apiKeyHelp": "Gửi khóa dưới dạng Bearer Token.",
"apiKeyRequired": "Bắt buộc trước khi mở API ra mạng.", "apiKeyPlaceholder": "Nhập khóa API",
"autoInstall": "Các gói cần thiết cho máy chủ API sẽ được cài tự động khi khởi động."
},
"observability": { "observability": {
"title": "Theo dõi chạy", "configured": "nanobot đã có thông tin xác thực để ghi lại quá trình xử lý.", "title": "Theo dõi chạy", "configured": "nanobot đã có thông tin xác thực để ghi lại quá trình xử lý.",
"environment": "Đặt LANGFUSE_SECRET_KEY và LANGFUSE_PUBLIC_KEY rồi khởi động lại nanobot.", "enable": "Bật theo dõi" "environment": "Đặt LANGFUSE_SECRET_KEY và LANGFUSE_PUBLIC_KEY rồi khởi động lại nanobot.", "enable": "Bật theo dõi"
-34
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "已保存,重启 API 服务后生效。",
"commandRuntime": { "commandRuntime": {
"custom": "自定义(秒)", "custom": "自定义(秒)",
"customLabel": "自定义运行时长(秒)", "customLabel": "自定义运行时长(秒)",
@@ -702,14 +701,6 @@
"label": "重启模式", "label": "重启模式",
"help": "选择重启方式,自动按环境决定\n\n选择网关的重启方式。“自动”会根据运行环境选择。" "help": "选择重启方式,自动按环境决定\n\n选择网关的重启方式。“自动”会根据运行环境选择。"
}, },
"api_host": {
"label": "API 地址",
"help": "对外开放须设密钥;修改后重启 API\n\n允许其他设备连接前,请先在“系统”中设置 API 密钥。修改后需重启 API 服务。"
},
"api_timeout": {
"label": "API 超时",
"help": "API 最长等待秒数,重启服务生效\n\n每次 API 请求最长等待多久。修改后需重启 API 服务。"
},
"tools_image_generation_save_dir": { "tools_image_generation_save_dir": {
"label": "保存目录", "label": "保存目录",
"help": "媒体目录内相对路径,不迁移已有图片\n\nnanobot 媒体目录内的子目录。请使用相对路径,已有图片不会迁移。" "help": "媒体目录内相对路径,不迁移已有图片\n\nnanobot 媒体目录内的子目录。请使用相对路径,已有图片不会迁移。"
@@ -768,10 +759,6 @@
"title": "网关", "title": "网关",
"help": "设置部署和重启方式" "help": "设置部署和重启方式"
}, },
"api": {
"title": "API 设置",
"help": "设置监听地址和请求超时"
},
"storage": { "storage": {
"title": "图片存储", "title": "图片存储",
"help": "选择生成图片的保存位置" "help": "选择生成图片的保存位置"
@@ -1433,27 +1420,6 @@
"searchInstallOnSave": "保存时会自动安装 Olostep 所需的软件包。", "searchInstallOnSave": "保存时会自动安装 Olostep 所需的软件包。",
"installing": "正在安装所需软件包…" "installing": "正在安装所需软件包…"
}, },
"api": {
"title": "API 服务",
"openaiCompatible": "OpenAI 兼容 API",
"description": "通过兼容 OpenAI 的 API 连接",
"start": "启动 API 服务",
"starting": "正在启动...",
"stop": "停止",
"stopping": "正在停止...",
"access": "访问范围",
"thisDevice": "仅此设备",
"localNetwork": "局域网",
"localHelp": "仅当前设备可连接",
"networkHelp": "局域网可连接,须设置 API 密钥\n\n局域网内其他设备可以连接,因此必须设置 API 密钥。",
"port": "端口",
"portHelp": "API 服务使用的本地端口",
"apiKey": "API 密钥",
"apiKeyHelp": "通过 Bearer Token 发送密钥",
"apiKeyRequired": "向局域网开放 API 前必须设置密钥。",
"apiKeyPlaceholder": "输入 API 密钥",
"autoInstall": "启动时会自动安装 API 服务所需的软件包。"
},
"observability": { "observability": {
"title": "运行追踪", "title": "运行追踪",
"configured": "nanobot 已检测到追踪凭证。", "configured": "nanobot 已检测到追踪凭证。",
-13
View File
@@ -537,7 +537,6 @@
} }
}, },
"runtimeConfig": { "runtimeConfig": {
"apiSaved": "已儲存,重新啟動 API 服務後生效。",
"commandRuntime": { "commandRuntime": {
"custom": "自訂(秒)", "custom": "自訂(秒)",
"customLabel": "自訂執行時間(秒)", "customLabel": "自訂執行時間(秒)",
@@ -585,8 +584,6 @@
"gateway_host": {"label": "閘道器地址", "help": "閘道器地址,WebUI 監聽地址另設\n\n閘道器使用的地址。WebUI 的監聽地址需在聊天平臺的 WebSocket 設定中單獨配置。"}, "gateway_host": {"label": "閘道器地址", "help": "閘道器地址,WebUI 監聽地址另設\n\n閘道器使用的地址。WebUI 的監聽地址需在聊天平臺的 WebSocket 設定中單獨配置。"},
"gateway_port": {"label": "閘道連接埠", "help": "閘道器埠,啟動引數優先\n\n閘道器使用的埠。啟動時指定的命令列引數優先於此設定。"}, "gateway_port": {"label": "閘道連接埠", "help": "閘道器埠,啟動引數優先\n\n閘道器使用的埠。啟動時指定的命令列引數優先於此設定。"},
"gateway_restart_mode": {"label": "重新啟動方式", "help": "選擇重啟方式,自動按環境決定\n\n選擇閘道器的重啟方式。“自動”會根據執行環境選擇。"}, "gateway_restart_mode": {"label": "重新啟動方式", "help": "選擇重啟方式,自動按環境決定\n\n選擇閘道器的重啟方式。“自動”會根據執行環境選擇。"},
"api_host": {"label": "API 地址", "help": "對外開放須設金鑰;修改後重啟 API\n\n允許其他裝置連線前,請先在“系統”中設定 API 金鑰。修改後需重啟 API 服務。"},
"api_timeout": {"label": "API 超時", "help": "API 最長等待秒數,重啟服務生效\n\n每次 API 請求最長等待多久。修改後需重啟 API 服務。"},
"tools_image_generation_save_dir": {"label": "儲存目錄", "help": "媒體目錄內相對路徑,不遷移已有圖片\n\nnanobot 媒體目錄內的子目錄。請使用相對路徑,已有圖片不會遷移。"} "tools_image_generation_save_dir": {"label": "儲存目錄", "help": "媒體目錄內相對路徑,不遷移已有圖片\n\nnanobot 媒體目錄內的子目錄。請使用相對路徑,已有圖片不會遷移。"}
}, },
"groups": { "groups": {
@@ -603,7 +600,6 @@
"safety": {"title": "全域性許可權", "help": "設定目錄限制、網路例外和遠端安裝\n\n設定工作區訪問限制、網路訪問例外和遠端安裝許可權。"}, "safety": {"title": "全域性許可權", "help": "設定目錄限制、網路例外和遠端安裝\n\n設定工作區訪問限制、網路訪問例外和遠端安裝許可權。"},
"cli": {"title": "CLI 限制", "help": "設定安裝、執行超時和列表快取\n\n設定安裝和執行超時,以及應用列表的快取時長。"}, "cli": {"title": "CLI 限制", "help": "設定安裝、執行超時和列表快取\n\n設定安裝和執行超時,以及應用列表的快取時長。"},
"gateway": {"title": "閘道器", "help": "設定部署和重啟方式"}, "gateway": {"title": "閘道器", "help": "設定部署和重啟方式"},
"api": {"title": "API 設定", "help": "設定監聽地址和請求超時"},
"storage": {"title": "圖片儲存", "help": "選擇生成圖片的儲存位置"}, "storage": {"title": "圖片儲存", "help": "選擇生成圖片的儲存位置"},
"maintenance": {"title": "記憶整理", "help": ""}, "maintenance": {"title": "記憶整理", "help": ""},
"web": {"title": "網路存取", "help": ""}, "web": {"title": "網路存取", "help": ""},
@@ -1238,15 +1234,6 @@
"supabase": "檢視和管理專案" "supabase": "檢視和管理專案"
} }
}, },
"api": {
"title": "API 伺服器", "openaiCompatible": "OpenAI 相容 API", "description": "透過相容 OpenAI 的 API 連線",
"start": "啟動 API 伺服器", "starting": "正在啟動…", "stop": "停止", "stopping": "正在停止…",
"access": "存取範圍", "thisDevice": "僅此裝置", "localNetwork": "區域網路",
"localHelp": "僅當前裝置可連線", "networkHelp": "區域網可連線,須設定 API 金鑰\n\n區域網內其他裝置可以連線,因此必須設定 API 金鑰。",
"port": "連接埠", "portHelp": "API 服務使用的本地埠", "apiKey": "API 金鑰", "apiKeyHelp": "透過 Bearer Token 傳送金鑰",
"apiKeyRequired": "向區域網路開放 API 前必須設定金鑰。", "apiKeyPlaceholder": "輸入 API 金鑰",
"autoInstall": "啟動時會自動安裝 API 服務所需的套件。"
},
"observability": { "observability": {
"title": "執行追蹤", "configured": "nanobot 已偵測到追蹤憑證。", "title": "執行追蹤", "configured": "nanobot 已偵測到追蹤憑證。",
"environment": "設定 LANGFUSE_SECRET_KEY 和 LANGFUSE_PUBLIC_KEY 後重新啟動 nanobot。", "enable": "啟用追蹤" "environment": "設定 LANGFUSE_SECRET_KEY 和 LANGFUSE_PUBLIC_KEY 後重新啟動 nanobot。", "enable": "啟用追蹤"
-28
View File
@@ -1,7 +1,6 @@
import { isContextGraph, isContextInspection } from "@/lib/context-graph"; import { isContextGraph, isContextInspection } from "@/lib/context-graph";
import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications"; import { isCompactionPhase, isCompactionReason } from "../../../packages/client-events/notifications";
import type { import type {
ApiServicePayload,
AutomationChatsPayload, AutomationChatsPayload,
AutomationChatUpdate, AutomationChatUpdate,
AutomationsPayload, AutomationsPayload,
@@ -1011,33 +1010,6 @@ export async function fetchNanobotFeatures(
); );
} }
export async function fetchApiService(token: string, base: string = ""): Promise<ApiServicePayload> {
return request<ApiServicePayload>(`${base}/api/settings/api-service`, token);
}
export async function startApiService(
transport: WebUIMutationTransport,
values: { host: string; port: number; timeout: number; apiKey?: string },
): Promise<ApiServicePayload> {
return mutation<ApiServicePayload>(
transport,
"settings.api_service.start",
{
host: values.host,
port: values.port,
timeout: values.timeout,
...(values.apiKey !== undefined ? { api_key: values.apiKey } : {}),
},
PACKAGE_MUTATION_TIMEOUT_MS,
);
}
export async function stopApiService(
transport: WebUIMutationTransport,
): Promise<ApiServicePayload> {
return mutation<ApiServicePayload>(transport, "settings.api_service.stop");
}
export async function enableNanobotFeature( export async function enableNanobotFeature(
transport: WebUIMutationTransport, transport: WebUIMutationTransport,
name: string, name: string,
-20
View File
@@ -845,12 +845,6 @@ export interface SettingsPayload {
use_jina_reader: boolean; use_jina_reader: boolean;
}; };
}; };
api?: {
host: string;
port: number;
timeout: number;
api_key_hint?: string | null;
};
observability?: { observability?: {
provider: "langfuse" | string; provider: "langfuse" | string;
configured: boolean; configured: boolean;
@@ -1048,20 +1042,6 @@ export interface SettingsPayload {
}; };
} }
export interface ApiServicePayload {
installed: boolean;
running: boolean;
managed: boolean;
host: string;
port: number;
timeout: number;
api_key_hint?: string | null;
endpoint: string;
command: string;
log_path?: string | null;
last_action?: "started" | "stopped" | string;
}
interface AppPackageRef { interface AppPackageRef {
manager: string; manager: string;
name?: string; name?: string;
+2 -39
View File
@@ -17,7 +17,6 @@ import {
fetchAutomations, fetchAutomations,
fetchAutomationChats, fetchAutomationChats,
fetchAutomationRunResult, fetchAutomationRunResult,
fetchApiService,
fetchCliApps, fetchCliApps,
fetchInstalledCliApps, fetchInstalledCliApps,
fetchMcpOAuthStatus, fetchMcpOAuthStatus,
@@ -27,6 +26,7 @@ import {
fetchProviderModels, fetchProviderModels,
fetchPromptIndex, fetchPromptIndex,
fetchSessionAutomations, fetchSessionAutomations,
fetchSettings,
fetchSettingsUsage, fetchSettingsUsage,
fetchSidebarState, fetchSidebarState,
fetchSkillDetail, fetchSkillDetail,
@@ -50,9 +50,7 @@ import {
runMcpPresetAction, runMcpPresetAction,
saveCustomMcpServer, saveCustomMcpServer,
searchMarketplaceSkills, searchMarketplaceSkills,
startApiService,
startMcpOAuth, startMcpOAuth,
stopApiService,
cancelChannelConnect, cancelChannelConnect,
pollChannelConnect, pollChannelConnect,
startChannelConnect, startChannelConnect,
@@ -781,7 +779,7 @@ describe("webui API helpers", () => {
}), }),
); );
await expect(fetchApiService("tok")).rejects.toMatchObject({ await expect(fetchSettings("tok")).rejects.toMatchObject({
status: 200, status: 200,
message: "Gateway returned WebUI HTML instead of JSON. Restart nanobot gateway and try again.", message: "Gateway returned WebUI HTML instead of JSON. Restart nanobot gateway and try again.",
}); });
@@ -1101,41 +1099,6 @@ describe("webui API helpers", () => {
); );
}); });
it("manages the API service capability", async () => {
await fetchApiService("tok");
expect(fetch).toHaveBeenCalledWith(
"/api/settings/api-service",
expect.objectContaining({ headers: { Authorization: "Bearer tok" } }),
);
await startApiService(
mutationTransport,
{ host: "127.0.0.1", port: 8900, timeout: 120 },
);
expect(requestMutation).toHaveBeenLastCalledWith(
"settings.api_service.start",
{ host: "127.0.0.1", port: 8900, timeout: 120 },
150_000,
);
await startApiService(
mutationTransport,
{ host: "0.0.0.0", port: 8900, timeout: 120, apiKey: "secret-token" },
);
expect(requestMutation).toHaveBeenLastCalledWith(
"settings.api_service.start",
{ host: "0.0.0.0", port: 8900, timeout: 120, api_key: "secret-token" },
150_000,
);
await stopApiService(mutationTransport);
expect(requestMutation).toHaveBeenLastCalledWith(
"settings.api_service.stop",
{},
20_000,
);
});
it("reads MCP presets and serializes actions", async () => { it("reads MCP presets and serializes actions", async () => {
vi.mocked(fetch).mockResolvedValueOnce({ vi.mocked(fetch).mockResolvedValueOnce({
ok: true, ok: true,
@@ -496,10 +496,8 @@ function renderMcpActions() {
state, state,
featureCatalog: [], featureCatalog: [],
client, client,
token: "tok",
getToken: () => "tok", getToken: () => "tok",
t: i18n.t, t: i18n.t,
applyPayload: vi.fn(),
maybeRestartHostEngine: vi.fn(), maybeRestartHostEngine: vi.fn(),
setPendingRestartSections: vi.fn(), setPendingRestartSections: vi.fn(),
refreshAutomations: vi.fn(), refreshAutomations: vi.fn(),
@@ -1,11 +1,9 @@
import { fireEvent, render, screen, waitFor, within } from "@testing-library/react"; import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event"; import userEvent from "@testing-library/user-event";
import { describe, expect, it, vi } from "vitest"; import { describe, expect, it, vi } from "vitest";
import { RuntimeSettings } from "@/components/settings/system/RuntimeSettings";
import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS } from "@/components/settings/system/runtime-config-fields"; import { RUNTIME_CONFIG_FIELDS, RUNTIME_CONFIG_GROUPS } from "@/components/settings/system/runtime-config-fields";
import runtimeConfigKeys from "../../../tests/webui/fixtures/runtime-config-keys.json"; import runtimeConfigKeys from "../../../tests/webui/fixtures/runtime-config-keys.json";
import { TimezonePicker } from "@/components/settings/shared/TimezonePicker"; import { TimezonePicker } from "@/components/settings/shared/TimezonePicker";
import { DEFAULT_AGENT_SETTINGS_DRAFT } from "@/components/settings/models/ModelsSettings";
import type { SettingsPayload } from "@/lib/types"; import type { SettingsPayload } from "@/lib/types";
import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils"; import { installSettingsViewTestHooks, jsonResponse, renderSettingsView, requestMutationMock, settingsPayload } from "@/tests/settings-test-utils";
@@ -136,24 +134,6 @@ describe("Runtime configuration settings", () => {
expect(within(screen.getByRole("dialog")).getByRole("textbox")).toHaveValue("TERM\nCOLORTERM"); expect(within(screen.getByRole("dialog")).getByRole("textbox")).toHaveValue("TERM\nCOLORTERM");
}); });
it("starts the API with newly saved advanced settings", async () => {
const payload = runtimeSettings();
payload.api = { ...payload.api, host: "192.168.1.7", port: 8900, timeout: 77.5, api_key_hint: "set" };
const action = vi.fn();
render(<RuntimeSettings form={DEFAULT_AGENT_SETTINGS_DRAFT} settings={payload}
requiresRestartPending={false} apiService={{
installed: true, running: false, managed: false, host: "127.0.0.1", port: 8900,
timeout: 120, endpoint: "http://127.0.0.1:8900/v1", command: "nanobot serve",
api_key_hint: "set",
}} apiServiceLoading={false} apiServiceAction={null} apiServiceError={null}
capabilitiesLoading={false} capabilityAction={null} capabilityError={null}
onApiServiceAction={action} onInstallCapability={() => {}} />);
fireEvent.click(screen.getByRole("button", { name: "Start API server" }));
expect(action).toHaveBeenCalledWith("start", {
host: "192.168.1.7", port: 8900, timeout: 77.5, apiKey: undefined,
});
});
it("saves only edited fields using the existing settings footer", async () => { it("saves only edited fields using the existing settings footer", async () => {
const payload = runtimeSettings(); const payload = runtimeSettings();
requestMutationMock.mockResolvedValue({ ...payload, requires_restart: true, requestMutationMock.mockResolvedValue({ ...payload, requires_restart: true,
-45
View File
@@ -487,51 +487,6 @@ describe("Settings system domains", () => {
}); });
}); });
it("starts the managed API server from System", async () => {
const base = settingsPayload();
const stopped = {
installed: false,
running: false,
managed: false,
host: "127.0.0.1",
port: 8900,
timeout: 120,
api_key_hint: null,
endpoint: "http://127.0.0.1:8900/v1",
command: "nanobot serve",
};
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url === "/api/settings") return jsonResponse(base);
if (url === "/api/settings/api-service") return jsonResponse(stopped);
if (url === "/api/settings/nanobot-features") {
return jsonResponse({ features: [], enabled_count: 0 });
}
return jsonResponse({});
});
vi.stubGlobal("fetch", fetchMock);
requestMutationMock.mockResolvedValueOnce({
...stopped,
installed: true,
running: true,
managed: true,
});
renderSettingsView({ initialSection: "runtime", initialSettings: base, showSidebar: true });
const startButton = await screen.findByRole("button", { name: "Start API server" });
await waitFor(() => expect(startButton).toBeEnabled());
fireEvent.click(startButton);
await waitFor(() => {
expect(requestMutationMock).toHaveBeenCalledWith(
"settings.api_service.start",
{ host: "127.0.0.1", port: 8900, timeout: 120 },
150_000,
);
});
});
it("shows a visible uninstall button for installed CLI apps and calls uninstall", async () => { it("shows a visible uninstall button for installed CLI apps and calls uninstall", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => { const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input); const url = String(input);
-6
View File
@@ -64,12 +64,6 @@ export function settingsPayload(): SettingsPayload {
search: { max_results: 5, timeout: 30 }, search: { max_results: 5, timeout: 30 },
fetch: { use_jina_reader: true }, fetch: { use_jina_reader: true },
}, },
api: {
host: "127.0.0.1",
port: 8900,
timeout: 120,
api_key_hint: null,
},
observability: { observability: {
provider: "langfuse", provider: "langfuse",
configured: false, configured: false,