refactor(api)!: remove the standalone API server (#6614)
This commit is contained in:
1 parent
5c72ced2fe
commit
220d5e6970
99 files changed
+240
-4133
No files matched your search
@@ -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,
|
||||
*,
|
||||
|
||||
@@ -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
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
@@ -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",
|
||||
|
||||
Reference in new issue
Block a user