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 -5
View File
@@ -2639,7 +2639,6 @@ class AgentLoop:
hooks: list[AgentHook] | None = None,
hook_factories: list[AgentTurnHookFactory] | None = None,
tools: ToolRegistry | None = None,
persist_user_message: bool = True,
runtime: LLMRuntime | None = None,
on_runtime_admitted: Callable[[LLMRuntime], Awaitable[None]] | None = None,
attributes: Mapping[str, Any] | None = None,
@@ -2652,12 +2651,9 @@ class AgentLoop:
"""
if channel == "system":
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(
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.
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.schema import Config, ProviderConfig
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
@@ -179,7 +179,7 @@ async def transcribe_audio_data_url(
get_media_dir("webui-transcription"),
max_bytes=max_bytes,
)
except FileSizeExceeded as exc:
except FileSizeExceededError as exc:
raise TranscriptionIngressError("size") from exc
except Exception as 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.
import typer # noqa: E402
from loguru import logger # noqa: E402
from typer.core import TyperGroup # 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 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.agent import agent # 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.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 ( # noqa: E402
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.
SafeFileHistory = cli_terminal.SafeFileHistory
@@ -141,6 +134,23 @@ def main(
_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()
def onboard(
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})")
@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)
-3
View File
@@ -19,7 +19,6 @@ def initialize_config(path: Path) -> None:
return
web_token = os.environ.get("NANOBOT_WEB_TOKEN") or secrets.token_hex(16)
api_key = os.environ.get("NANOBOT_API_KEY") or secrets.token_hex(16)
websocket = WebSocketConfig(
enabled=True, host="0.0.0.0", token_issue_secret=web_token,
websocket_requires_token=True,
@@ -27,12 +26,10 @@ def initialize_config(path: Path) -> None:
config = Config.model_validate({
"gateway": {"host": "0.0.0.0"},
"channels": {"websocket": websocket.model_dump(by_alias=True)},
"api": {"host": "0.0.0.0", "api_key": api_key},
})
save_config(config, path)
print(f"[entrypoint] initialized {path}")
print(f"[entrypoint] WebUI: http://localhost:8765 — password: {web_token}")
print(f"[entrypoint] OpenAI-compatible API key: {api_key}")
if __name__ == "__main__":
-6
View File
@@ -1281,7 +1281,6 @@ def _configure_channels(config: Config) -> None:
_SETTINGS_SECTIONS: dict[str, tuple[str, str, set[str] | 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),
"API Server": ("API Server", "Configure OpenAI-compatible API endpoint", None),
"Gateway": ("Gateway Settings", "Configure server host, port", None),
"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]] = {
"Agent Settings": lambda c: c.agents.defaults,
"Channel Common": lambda c: c.channels,
"API Server": lambda c: c.api,
"Gateway": lambda c: c.gateway,
"Tools": lambda c: c.tools,
}
@@ -1297,7 +1295,6 @@ _SETTINGS_GETTER: dict[str, Callable[[Config], BaseModel]] = {
_SETTINGS_SETTER: dict[str, Callable[[Config, BaseModel], None]] = {
"Agent Settings": lambda c, v: setattr(c.agents, "defaults", 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),
"Tools": lambda c, v: setattr(c, "tools", v),
}
@@ -1380,7 +1377,6 @@ def _show_summary(config: Config) -> None:
for title, model in [
("Agent Settings", config.agents.defaults),
("Channel Common", config.channels),
("API Server", config.api),
("Gateway", config.gateway),
("Tools", config.tools),
]:
@@ -1813,7 +1809,6 @@ def _configure_advanced_settings(config: Config) -> None:
"[C] Chat Channel",
"[H] Channel Common",
"[A] Agent Settings",
"[I] API Server",
"[G] Gateway",
"[T] Tools",
"[V] View Configuration Summary",
@@ -1843,7 +1838,6 @@ def _configure_advanced_settings(config: Config) -> None:
"[C] Chat Channel": lambda: _configure_channels(config),
"[H] Channel Common": lambda: _configure_general_settings(config, "Channel Common"),
"[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"),
"[T] Tools": lambda: _configure_general_settings(config, "Tools"),
"[V] View Configuration Summary": lambda: _show_summary(config),
+5 -22
View File
@@ -380,26 +380,6 @@ class HeartbeatConfig(Base):
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):
"""Gateway/server configuration."""
@@ -506,7 +486,6 @@ class Config(BaseSettings):
transcription: TranscriptionConfig = Field(default_factory=TranscriptionConfig)
providers: ProvidersConfig = Field(default_factory=ProvidersConfig)
network: NetworkConfig = Field(default_factory=NetworkConfig)
api: ApiConfig = Field(default_factory=ApiConfig)
gateway: GatewayConfig = Field(default_factory=GatewayConfig)
tools: ToolsConfig = Field(default_factory=ToolsConfig)
model_presets: dict[str, ModelPresetConfig] = Field(
@@ -517,7 +496,11 @@ class Config(BaseSettings):
@model_validator(mode="before")
@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)
@classmethod
+1 -1
View File
@@ -50,7 +50,7 @@ class InstallResult:
_INSTALL_TIMEOUT_SECONDS = 300
_LOG_OUTPUT_LIMIT = 4000
_HIDDEN_OPTIONAL_FEATURES = {"documents", "pdf"}
_HIDDEN_OPTIONAL_FEATURES = {"api", "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.
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:
current = self.status()
if current.running:
@@ -151,11 +146,6 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
self._write_state(state)
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:
status = self.status()
if not status.pid:
@@ -189,15 +179,6 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
self._clear_state()
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:
"""Return live status, clearing stale state when needed."""
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``.
"""
@@ -13,7 +13,6 @@ from pathlib import Path
from nanobot.utils.helpers import safe_filename
DEFAULT_MAX_BYTES = 10 * 1024 * 1024
MAX_FILE_SIZE = DEFAULT_MAX_BYTES
_MIME_EXTENSION_OVERRIDES = {
# 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."""
FileSizeExceeded = FileSizeExceededError
def save_base64_data_url(
data_url: str,
media_dir: Path,
@@ -64,7 +60,7 @@ def save_base64_data_url(
"""Decode a ``data:<mime>;base64,<payload>`` URL and persist it.
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).
"""
# Parse delimiters directly so malformed MIME parameters cannot trigger regex backtracking.
@@ -83,7 +79,7 @@ def save_base64_data_url(
return None
limit = DEFAULT_MAX_BYTES if max_bytes is None else max_bytes
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.write_bytes(raw)
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(
query: QueryParams,
*,
-203
View File
@@ -1,30 +1,22 @@
from __future__ import annotations
import asyncio
import os
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Awaitable, Callable, TypedDict
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_registry import (
resolve_transcription_provider,
transcription_provider_names,
)
from nanobot.config.schema import Config
from nanobot.optional_features import (
OptionalFeatureError,
extra_installed,
optional_dependency_groups,
)
from nanobot.providers.image_generation import (
get_image_gen_provider,
image_gen_provider_names,
)
from nanobot.providers.registry import find_by_name
from nanobot.security.network import is_loopback_host
from nanobot.webui.request_settings import (
parse_request_object,
redact_request_secrets,
@@ -59,19 +51,15 @@ SettingsOperation = Callable[..., dict[str, Any]]
@dataclass(frozen=True)
class CapabilitySettingsOperations:
update_web_search: SettingsOperation
update_api: SettingsOperation
update_image: SettingsOperation
update_transcription: SettingsOperation
update_network: SettingsOperation
nanobot_features_action: SettingsOperation
api_runtime: Callable[[], ApiRuntime]
reload_image: Callable[[], Awaitable[dict[str, Any]]]
class CapabilitySettingsPayload(TypedDict):
web_search: dict[str, Any]
web: dict[str, Any]
api: dict[str, Any]
observability: dict[str, Any]
image_generation: 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,
},
},
"api": {
"host": config.api.host,
"port": config.api.port,
"timeout": config.api.timeout,
"api_key_hint": mask_secret_hint(config.api.api_key),
},
"observability": {
"provider": "langfuse",
"configured": bool(
@@ -365,45 +347,6 @@ def update_web_search_settings(config: Config, query: QueryParams) -> tuple[bool
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(
config: Config,
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:
"""Handle capability commands after transport authentication and decoding."""
@@ -665,15 +559,6 @@ class CapabilitySettingsHandler:
request: SettingsRequest,
operations: CapabilitySettingsOperations,
) -> 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 = {
"web-search-update": (
operations.update_web_search,
@@ -741,91 +626,3 @@ class CapabilitySettingsHandler:
result.get("message") or "hot reload failed",
)
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 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.channels.registry import load_channel_plugin
from nanobot.channels.validation import validate_channel_config
@@ -48,7 +47,6 @@ from nanobot.webui.settings_api import (
settings_payload,
settings_usage_payload,
update_agent_settings,
update_api_settings,
update_image_generation_settings,
update_model_call_order,
update_model_configuration,
@@ -122,9 +120,6 @@ _MODEL_ROUTES = {
_CAPABILITY_ROUTES = {
"/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/transcription/update": "transcription-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-logout",
"/api/settings/web-search/update",
"/api/settings/api-service/start",
"/api/settings/api-service/stop",
"/api/settings/image-generation/update",
"/api/settings/transcription/update",
"/api/settings/network-safety/update",
@@ -334,7 +327,6 @@ class WebUISettingsRouter:
request,
needs_local_browser=(
action in {
"api-start",
"runtime-config-update",
"features-enable",
"channel-configure",
@@ -534,12 +526,9 @@ class WebUISettingsRouter:
) -> capability_domain.CapabilitySettingsOperations:
return capability_domain.CapabilitySettingsOperations(
update_web_search=update_web_search_settings,
update_api=update_api_settings,
update_image=update_image_generation_settings,
update_transcription=update_transcription_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,
)
@@ -633,9 +622,6 @@ class WebUISettingsRouter:
def _parse_mcp_settings_query(self, request: WsRequest) -> QueryParams:
return self._query(request)
def _api_runtime(self) -> ApiRuntime:
return ApiRuntime(paths=api_runtime_paths(self.settings.config.path))
def _save_channel_config_values(
self,
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.loader import resolve_config_env_vars
from nanobot.config.schema import Config
from nanobot.security.network import is_loopback_host
from nanobot.webui.settings_contracts import WebUISettingsError
# 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.user_agent",
"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_result_chars": 1,
"gateway.port": 1,
"api.timeout": 1,
}
for path, minimum in numeric_minima.items():
if path in values:
@@ -132,15 +128,13 @@ def update_runtime_config(
raise WebUISettingsError(f"{path}: must be at least {minimum}")
if "gateway.port" in values and validated.gateway.port > 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:
limit = validated.tools.exec.max_runtime_limit
if validated.tools.exec.max_runtime > limit:
raise WebUISettingsError(
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:
parent, leaf = _parent(validated, path)
if not str(getattr(parent, leaf)).strip():
@@ -150,9 +144,6 @@ def update_runtime_config(
if (PureWindowsPath(directory).drive or directory.startswith(("/", "\\"))
or ".." in PurePosixPath(directory.replace("\\", "/")).parts):
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"}:
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:
@@ -199,5 +190,4 @@ def update_runtime_config(
config.tools = validated.tools
config.network = validated.network
config.gateway = validated.gateway
config.api = validated.api
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_logout": "/api/settings/provider/oauth-logout",
"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.transcription.update": "/api/settings/transcription/update",
"settings.runtime_config.update": "/api/settings/runtime-config/update",