Initial source archive with page bridge fix

这个提交存在于:
YokiiroBW 2026-08-03 16:32:49 +08:00
当前提交 45041f0af9
共有 7 个文件被更改,包括 1886 次插入 和 0 次删除

2
__init__.py 普通文件
查看文件

@ -0,0 +1,2 @@
"""AstrBot Codex route gateway plugin."""

30
_conf_schema.json 普通文件
查看文件

@ -0,0 +1,30 @@
{
"enable_llm_tools": {
"description": "允许管理员通过 AstrBot LLM tools 查询、测试和切换 Codex 线路",
"type": "bool",
"default": true
},
"enable_natural_language_switch": {
"description": "允许管理员直接发送“切换到0.5X”执行精确线路切换",
"type": "bool",
"default": true
},
"request_timeout_seconds": {
"description": "普通控制请求超时时间(秒)",
"type": "int",
"default": 15,
"hint": "允许范围 2-120"
},
"test_timeout_seconds": {
"description": "测试、切换和回滚等长操作超时时间(秒)",
"type": "int",
"default": 540,
"hint": "允许范围 480-600"
},
"max_history_items": {
"description": "单次允许展示的最大历史记录条数",
"type": "int",
"default": 20,
"hint": "允许范围 1-100"
}
}

556
gateway_client.py 普通文件
查看文件

@ -0,0 +1,556 @@
"""Safe HTTP-over-Unix-socket client for the Codex route controller.
The client intentionally has no support for authorization headers, arbitrary URLs,
or arbitrary controller paths. Upstream credentials belong to the controller and
the model gateway; this AstrBot plugin only sends route identifiers and actor identifiers.
"""
from __future__ import annotations
import json
import os
import re
import stat
from dataclasses import dataclass
from typing import Any
from urllib.parse import quote
import aiohttp
SOCKET_PATH = "/run/codex-route/control.sock"
_HTTP_ORIGIN = "http://localhost"
_MAX_RESPONSE_BYTES = 1024 * 1024
_MAX_SAFE_TEXT = 600
_URL_RE = re.compile(r"(?i)\bhttps?://[^\s<>'\"]+")
_BEARER_RE = re.compile(r"(?i)\bBearer\s+[A-Za-z0-9._~+/=-]+")
_KEY_VALUE_RE = re.compile(
r"(?i)\b(?:api[_-]?key|authorization|token|secret|password)\b"
r"\s*[:=]\s*[^\s,;]+"
)
_OPENAI_KEY_RE = re.compile(r"(?i)\bsk-[A-Za-z0-9_-]{8,}")
_JWT_RE = re.compile(
r"\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b"
)
_CONTROL_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]")
_ROUTE_FIELDS = {
"route_id",
"id",
"name",
"display_name",
"active",
"is_active",
"enabled",
"deleted",
"healthy",
"health",
"status",
"model",
"cost_multiplier",
"multiplier",
"revision",
"updated_at",
"last_test_at",
"latency_ms",
}
_STATUS_FIELDS = {
"active_route_id",
"active_route",
"route_id",
"revision",
"state",
"status",
"healthy",
"health",
"busy_tasks",
"active_tasks",
"pending_route",
"can_switch",
"changed_at",
"updated_at",
"last_test_at",
"latency_ms",
}
_HISTORY_FIELDS = {
"revision",
"action",
"route_id",
"from_route",
"to_route",
"actor",
"created_at",
"updated_at",
"timestamp",
"result",
"success",
"status",
"message",
}
_OPERATION_FIELDS = {
"route_id",
"display_name",
"active_route_id",
"previous_route_id",
"revision",
"rolled_back_to",
"healthy",
"health",
"success",
"status",
"model",
"latency_ms",
"responses_ok",
"streaming_ok",
"sse_ok",
"tool_call_ok",
"tool_result_ok",
"checks",
}
_CHECK_FIELDS = {
"auth",
"model",
"responses",
"streaming",
"sse",
"tool_call",
"tool_result",
"canary",
}
def sanitize_text(value: object, *, max_length: int = _MAX_SAFE_TEXT) -> str:
"""Return controller text with common credential and endpoint forms removed."""
text = _CONTROL_RE.sub("", str(value or ""))
text = _BEARER_RE.sub("[REDACTED_CREDENTIAL]", text)
text = _KEY_VALUE_RE.sub("[REDACTED_CREDENTIAL]", text)
text = _OPENAI_KEY_RE.sub("[REDACTED_CREDENTIAL]", text)
text = _JWT_RE.sub("[REDACTED_CREDENTIAL]", text)
text = _URL_RE.sub("[REDACTED_URL]", text)
text = text.strip()
if len(text) > max_length:
return text[: max_length - 1] + "…"
return text
class GatewayError(RuntimeError):
"""An error that is already safe to present to an AstrBot administrator."""
def __init__(
self,
safe_message: str,
*,
status: int | None = None,
code: str | None = None,
) -> None:
super().__init__(safe_message)
self.safe_message = sanitize_text(safe_message) or "路由控制器请求失败"
self.status = status
self.code = sanitize_text(code, max_length=80) if code else None
@dataclass(slots=True, frozen=True)
class ControllerResponse:
"""Sanitized response returned to the plugin UI layer."""
message: str
data: dict[str, Any]
class GatewayClient:
"""Whitelisted route-controller client over a fixed Unix socket."""
def __init__(
self,
*,
request_timeout_seconds: int = 15,
test_timeout_seconds: int = 180,
) -> None:
self.request_timeout_seconds = max(2, min(int(request_timeout_seconds), 120))
self.test_timeout_seconds = max(
self.request_timeout_seconds,
min(int(test_timeout_seconds), 600),
)
self._session: aiohttp.ClientSession | None = None
async def open(self) -> None:
if self._session and not self._session.closed:
return
connector = aiohttp.UnixConnector(path=SOCKET_PATH)
timeout = aiohttp.ClientTimeout(total=self.request_timeout_seconds)
self._session = aiohttp.ClientSession(
connector=connector,
timeout=timeout,
headers={
"Accept": "application/json",
"User-Agent": "astrbot-route-gateway/0.1",
},
raise_for_status=False,
)
async def close(self) -> None:
if self._session and not self._session.closed:
await self._session.close()
self._session = None
async def list_routes(self) -> ControllerResponse:
payload, message = await self._request("GET", "/v1/routes")
source = self._payload_data(payload)
if isinstance(source, list):
raw_routes = source
elif isinstance(source, dict):
raw_routes = source.get("routes", [])
else:
raw_routes = []
routes = [
self._whitelist_dict(item, _ROUTE_FIELDS)
for item in raw_routes
if isinstance(item, dict)
]
data: dict[str, Any] = {"routes": routes}
if isinstance(source, dict) and isinstance(source.get("revision"), int):
data["revision"] = source["revision"]
return ControllerResponse(message=message, data=data)
async def status(self) -> ControllerResponse:
payload, message = await self._request("GET", "/v1/status")
source = self._payload_data(payload)
data = self._whitelist_dict(source, _STATUS_FIELDS)
return ControllerResponse(message=message, data=data)
async def use_route(
self,
route_id: str,
*,
actor: str,
force: bool = False,
) -> ControllerResponse:
return await self._operation(
"POST",
"/v1/routes/use",
json_body={"route_id": route_id, "actor": actor, "force": bool(force)},
timeout_seconds=self.test_timeout_seconds,
)
async def test_route(self, route_id: str, *, actor: str) -> ControllerResponse:
return await self._operation(
"POST",
"/v1/routes/test",
json_body={"route_id": route_id, "actor": actor, "force": False},
timeout_seconds=self.test_timeout_seconds,
)
async def history(self, *, limit: int = 10) -> ControllerResponse:
payload, message = await self._request(
"GET",
"/v1/history",
params={"limit": str(max(1, min(int(limit), 100)))},
)
source = self._payload_data(payload)
if isinstance(source, list):
raw_history = source
elif isinstance(source, dict):
raw_history = source.get("history", source.get("items", []))
else:
raw_history = []
items = []
for item in raw_history:
if not isinstance(item, dict):
continue
clean = self._whitelist_dict(item, _HISTORY_FIELDS)
if "message" in clean:
clean["message"] = sanitize_text(clean["message"])
items.append(clean)
return ControllerResponse(message=message, data={"history": items})
async def list_secrets(self) -> ControllerResponse:
"""SECRET_REFERENCE_API: reference names and usage counts — never values."""
payload, message = await self._request("GET", "/v1/secrets")
source = self._payload_data(payload)
raw = source.get("secrets", []) if isinstance(source, dict) else []
secrets = [
{
"secret_ref": str(item.get("secret_ref") or ""),
"used_by_routes": int(item.get("used_by_routes") or 0),
}
for item in raw
if isinstance(item, dict) and item.get("secret_ref")
]
return ControllerResponse(message=message, data={"secrets": secrets})
async def import_secret(self, secret_ref: str, value: str, *, actor: str) -> ControllerResponse:
"""Write-only: the value goes to the controller and can never be read back."""
payload, message = await self._request(
"POST",
"/v1/secrets",
json_body={"secret_ref": secret_ref, "value": value, "actor": actor},
)
source = self._payload_data(payload)
data = {"secret_ref": secret_ref}
if isinstance(source, dict) and isinstance(source.get("replaced"), bool):
data["replaced"] = source["replaced"]
return ControllerResponse(message=message, data=data)
async def delete_secret(self, secret_ref: str, *, actor: str) -> ControllerResponse:
payload, message = await self._request(
"POST",
"/v1/secrets/delete",
json_body={"secret_ref": secret_ref, "actor": actor},
)
del payload
return ControllerResponse(message=message, data={"secret_ref": secret_ref})
async def rollback(
self,
*,
actor: str,
revision: int | None = None,
force: bool = False,
) -> ControllerResponse:
body: dict[str, Any] = {"actor": actor, "force": bool(force)}
if revision is not None:
body["revision"] = int(revision)
return await self._operation(
"POST",
"/v1/rollback",
json_body=body,
timeout_seconds=self.test_timeout_seconds,
)
async def create_route(
self,
*,
route_id: str,
display_name: str,
secret_ref: str,
base_url: str,
model: str,
actor: str,
force: bool = False,
) -> ControllerResponse:
return await self._operation(
"POST",
"/v1/routes",
json_body={
"route_id": route_id,
"display_name": display_name,
"secret_ref": secret_ref,
"base_url": base_url,
"model": model,
"actor": actor,
"force": bool(force),
},
)
async def copy_route(
self,
*,
source_route_id: str,
new_route_id: str,
display_name: str,
actor: str,
force: bool = False,
) -> ControllerResponse:
return await self._operation(
"POST",
"/v1/routes/copy",
json_body={
"source_id": source_route_id,
"new_id": new_route_id,
"display_name": display_name,
"actor": actor,
"force": bool(force),
},
)
async def rename_route(
self,
*,
route_id: str,
display_name: str,
actor: str,
force: bool = False,
) -> ControllerResponse:
return await self._operation(
"POST",
"/v1/routes/rename",
json_body={
"route_id": route_id,
"display_name": display_name,
"actor": actor,
"force": bool(force),
},
)
async def delete_route(
self,
*,
route_id: str,
actor: str,
confirm: bool,
force: bool = False,
) -> ControllerResponse:
path = f"/v1/routes/{quote(route_id, safe='')}"
return await self._operation(
"DELETE",
path,
json_body={
"confirm": bool(confirm),
"actor": actor,
"force": bool(force),
},
)
async def _operation(
self,
method: str,
path: str,
*,
json_body: dict[str, Any],
timeout_seconds: int | None = None,
) -> ControllerResponse:
payload, message = await self._request(
method,
path,
json_body=json_body,
timeout_seconds=timeout_seconds,
)
source = self._payload_data(payload)
data = self._whitelist_dict(source, _OPERATION_FIELDS)
checks = data.get("checks")
if isinstance(checks, dict):
data["checks"] = self._whitelist_dict(checks, _CHECK_FIELDS)
else:
data.pop("checks", None)
return ControllerResponse(message=message, data=data)
async def _request(
self,
method: str,
path: str,
*,
json_body: dict[str, Any] | None = None,
params: dict[str, str] | None = None,
timeout_seconds: int | None = None,
) -> tuple[Any, str]:
if not path.startswith("/") or "://" in path or ".." in path:
raise GatewayError("插件拒绝了无效的控制器路径")
self._check_socket()
await self.open()
assert self._session is not None
timeout = None
if timeout_seconds is not None:
timeout = aiohttp.ClientTimeout(total=max(2, min(timeout_seconds, 600)))
try:
async with self._session.request(
method,
_HTTP_ORIGIN + path,
json=json_body,
params=params,
timeout=timeout,
) as response:
body = await response.content.read(_MAX_RESPONSE_BYTES + 1)
if len(body) > _MAX_RESPONSE_BYTES:
raise GatewayError("路由控制器响应过大,已拒绝处理")
payload = self._decode_json(body)
message = self._response_message(payload)
if response.status < 200 or response.status >= 300:
raise GatewayError(
message or self._status_message(response.status),
status=response.status,
code=self._response_code(payload),
)
if isinstance(payload, dict):
if payload.get("ok") is False or str(payload.get("status", "")).lower() in {
"error",
"failed",
"failure",
}:
raise GatewayError(
message or "路由控制器拒绝了请求",
status=response.status,
code=self._response_code(payload),
)
return payload, message
except GatewayError:
raise
except (aiohttp.ClientError, TimeoutError, ConnectionError, OSError):
# Drop pooled Unix-socket connections so the next request can recover
# cleanly after a controller restart or socket inode replacement.
await self.close()
raise GatewayError("无法连接路由控制器,请检查控制器服务和 Socket 权限") from None
@staticmethod
def _check_socket() -> None:
try:
socket_stat = os.stat(SOCKET_PATH)
except FileNotFoundError:
raise GatewayError("路由控制器尚未启动") from None
except OSError:
raise GatewayError("无法访问路由控制器 Socket") from None
if not stat.S_ISSOCK(socket_stat.st_mode):
raise GatewayError("路由控制器路径不是 Unix Socket,已拒绝连接")
@staticmethod
def _decode_json(body: bytes) -> Any:
if not body:
return {}
try:
return json.loads(body.decode("utf-8"))
except (UnicodeDecodeError, json.JSONDecodeError):
raise GatewayError("路由控制器返回了无效 JSON") from None
@staticmethod
def _payload_data(payload: Any) -> Any:
if isinstance(payload, dict) and "data" in payload:
return payload.get("data")
return payload
@staticmethod
def _response_message(payload: Any) -> str:
if not isinstance(payload, dict):
return ""
return sanitize_text(payload.get("message", ""))
@staticmethod
def _response_code(payload: Any) -> str | None:
if not isinstance(payload, dict):
return None
code = payload.get("code") or payload.get("error_code") or payload.get("error")
return sanitize_text(code, max_length=80) if code else None
@staticmethod
def _status_message(status_code: int) -> str:
if status_code == 400:
return "路由控制器拒绝了无效请求"
if status_code == 404:
return "指定线路或控制接口不存在"
if status_code == 409:
return "当前状态不允许执行该路由操作"
if status_code == 422:
return "路由参数校验失败"
if status_code == 429:
return "路由控制器正忙,请稍后重试"
if status_code >= 500:
return "路由控制器内部错误"
return f"路由控制器请求失败(HTTP {status_code})"
@classmethod
def _whitelist_dict(cls, value: Any, fields: set[str]) -> dict[str, Any]:
if not isinstance(value, dict):
return {}
result: dict[str, Any] = {}
for key in fields:
if key not in value:
continue
item = value[key]
if isinstance(item, (str, int, float, bool)) or item is None:
result[key] = sanitize_text(item) if isinstance(item, str) else item
elif key == "checks" and isinstance(item, dict):
result[key] = item
return result

852
main.py 普通文件
查看文件

@ -0,0 +1,852 @@
"""AstrBot plugin for safely managing the Codex model route controller."""
from __future__ import annotations
import asyncio
import ipaddress
import re
from collections.abc import Awaitable, Callable
from typing import Any
from urllib.parse import urlsplit
from astrbot.api import AstrBotConfig, logger
from astrbot.api.event import AstrMessageEvent, filter
from astrbot.api.star import Context, Star, register
from .gateway_client import ControllerResponse, GatewayClient, GatewayError, sanitize_text
_ROUTE_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$")
_REFERENCE_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")
_MODEL_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$")
_CONTROL_RE = re.compile(r"[\x00-\x1f\x7f]")
_NATURAL_SWITCH_RE = re.compile(
r"^\s*(?:(?:请|麻烦)\s*)?(?:帮我\s*)?"
r"(?:把\s*(?:Codex|代码模型)?\s*)?切换到\s*"
r"(?:线路\s*)?([A-Za-z0-9][A-Za-z0-9._-]{0,31})"
r"\s*[。.!!]?\s*$",
re.IGNORECASE,
)
_LLM_TOOL_NAMES = {
"codex_route_list",
"codex_route_status",
"codex_route_switch",
"codex_route_test",
}
class InputError(ValueError):
"""Safe input validation error."""
@register(
"astrbot_plugin_route_gateway",
"Codex Route",
"通过本机 Unix Socket 安全管理 Codex 模型线路",
"0.1.0",
)
class RouteGatewayPlugin(Star):
def __init__(self, context: Context, config: AstrBotConfig):
super().__init__(context)
self.context = context
self.config = config
self._enable_llm_tools = bool(config.get("enable_llm_tools", True))
self._enable_natural_language = bool(
config.get("enable_natural_language_switch", True)
)
self._max_history_items = self._bounded_int(
config.get("max_history_items", 20), 20, minimum=1, maximum=100
)
request_timeout = self._bounded_int(
config.get("request_timeout_seconds", 15), 15, minimum=2, maximum=120
)
test_timeout = self._bounded_int(
config.get("test_timeout_seconds", 540), 540, minimum=480, maximum=600
)
self.gateway = GatewayClient(
request_timeout_seconds=request_timeout,
test_timeout_seconds=test_timeout,
)
self._mutation_lock = asyncio.Lock()
async def initialize(self):
await self.gateway.open()
self._register_page_api()
logger.info("Codex Route 插件已初始化(Unix Socket 控制模式)")
def _register_page_api(self) -> None:
"""SECRET_REFERENCE_API: dashboard page APIs; absent register_web_api is not fatal."""
if not hasattr(self.context, "register_web_api"):
logger.debug("Codex Route:当前 AstrBot 未提供 register_web_api,跳过页面 API")
return
try:
from .page_api import RouteGatewayPageApi
RouteGatewayPageApi(self).register_routes()
logger.info("Codex Route:线路管理页面 API 已注册")
except Exception as exc:
logger.warning("Codex Route:页面 API 注册失败 %s", type(exc).__name__, exc_info=True)
async def terminate(self):
await self.gateway.close()
logger.info("Codex Route 插件已停止")
def _is_admin(self, event: AstrMessageEvent) -> bool:
"""Dynamically validate the platform sender against AstrBot admins_id."""
try:
astrbot_config = self.context.get_config(event.unified_msg_origin)
admin_ids = {str(item) for item in astrbot_config.get("admins_id", [])}
return str(event.get_sender_id()) in admin_ids
except Exception:
logger.warning("Codex Route 管理员校验失败,已按无权限处理")
return False
def _actor(self, event: AstrMessageEvent) -> str:
actor = str(event.get_sender_id()).strip()
if not actor or len(actor) > 128 or _CONTROL_RE.search(actor):
raise InputError("无法取得有效的管理员身份")
return actor
@staticmethod
def _bounded_int(
value: object,
default: int,
*,
minimum: int,
maximum: int,
) -> int:
try:
parsed = int(value)
except (TypeError, ValueError):
parsed = default
return max(minimum, min(parsed, maximum))
@staticmethod
def _force(value: object) -> bool:
if isinstance(value, bool):
return value
return str(value or "").strip().lower() in {
"1",
"true",
"yes",
"force",
"强制",
}
@staticmethod
def _validate_route_id(route_id: str) -> str:
value = str(route_id or "").strip()
if not _ROUTE_ID_RE.fullmatch(value):
raise InputError("线路 ID 仅允许 1-32 位字母、数字、点、下划线和短横线")
return value
@staticmethod
def _validate_model(model: str) -> str:
value = str(model or "").strip()
if not _MODEL_RE.fullmatch(value):
raise InputError("模型 ID 格式无效")
return value
@staticmethod
def _validate_secret_ref(secret_ref: str) -> str:
value = str(secret_ref or "").strip().lower()
if not _REFERENCE_RE.fullmatch(value):
raise InputError("Secret 引用格式无效;这里只能填写已导入的引用 ID")
lowered = value.lower()
if lowered.startswith(("sk-", "bearer", "http:", "https:")):
raise InputError("禁止在聊天中提交 API Key、Token 或 URL 作为 Secret 引用")
return value
@staticmethod
def _validate_display_name(display_name: str, *, fallback: str = "") -> str:
value = str(display_name or fallback).strip()
if not value or len(value) > 64 or _CONTROL_RE.search(value):
raise InputError("显示名称必须为 1-64 个可见字符")
return value
@staticmethod
def _validate_base_url(base_url: str) -> str:
value = str(base_url or "").strip()
try:
parsed = urlsplit(value)
except ValueError:
raise InputError("上游地址格式无效") from None
if parsed.scheme.lower() != "https" or not parsed.hostname:
raise InputError("生产线路上游地址必须使用 HTTPS")
if parsed.username or parsed.password or parsed.query or parsed.fragment:
raise InputError("上游地址不得包含凭据、查询参数或片段")
host = parsed.hostname.rstrip(".").lower()
if host == "localhost" or host.endswith((".localhost", ".local")):
raise InputError("禁止使用本机或本地域名作为上游地址")
try:
address = ipaddress.ip_address(host)
except ValueError:
try:
host.encode("idna")
except UnicodeError:
raise InputError("上游域名无效") from None
else:
if not address.is_global:
raise InputError("禁止使用回环、私网、链路本地或保留地址")
return value.rstrip("/")
async def _safe_call(
self,
operation: Callable[[], Awaitable[ControllerResponse]],
formatter: Callable[[ControllerResponse], str],
*,
mutation: bool = False,
) -> str:
try:
if mutation:
async with self._mutation_lock:
response = await operation()
else:
response = await operation()
return formatter(response)
except InputError as exc:
return f"⚠️ {sanitize_text(exc)}"
except GatewayError as exc:
logger.warning(
"Codex Route 控制请求失败(status=%s, code=%s)",
exc.status,
exc.code or "-",
)
return f"⚠️ {exc.safe_message}"
except Exception as exc:
logger.error(
"Codex Route 出现未预期错误(type=%s)", type(exc).__name__
)
return "⚠️ 路由操作失败,详细信息已写入脱敏日志"
@staticmethod
def _route_id_from(item: dict[str, Any]) -> str:
return str(item.get("route_id") or item.get("id") or item.get("name") or "-")
@classmethod
def _format_routes(cls, response: ControllerResponse) -> str:
routes = response.data.get("routes", [])
if not routes:
return response.message or "当前没有可用线路"
heading = response.message or f"共有 {len(routes)} 条线路"
if response.data.get("revision") is not None:
heading += f"(rev {response.data['revision']})"
lines = [heading + ":"]
for route in routes:
route_id = cls._route_id_from(route)
display_name = str(route.get("display_name") or "")
flags = []
if route.get("active") is True or route.get("is_active") is True:
flags.append("当前")
if route.get("enabled") is False:
flags.append("停用")
if route.get("deleted") is True:
flags.append("已删除")
health = route.get("healthy", route.get("health"))
if health is True:
flags.append("健康")
elif health is False:
flags.append("异常")
suffix = f" [{' / '.join(flags)}]" if flags else ""
details = []
if display_name and display_name != route_id:
details.append(display_name)
if route.get("model"):
details.append(f"模型={route['model']}")
multiplier = route.get("cost_multiplier", route.get("multiplier"))
if multiplier is not None:
details.append(f"倍率={multiplier}")
detail_text = f" — {';'.join(details)}" if details else ""
lines.append(f"- {route_id}{suffix}{detail_text}")
return "\n".join(lines)
@classmethod
def _format_status(cls, response: ControllerResponse) -> str:
data = response.data
if not data:
return response.message or "路由控制器未返回状态"
active = (
data.get("active_route_id")
or data.get("active_route")
or data.get("route_id")
or "-"
)
lines = [response.message or "Codex 路由状态", f"当前线路:{active}"]
if data.get("revision") is not None:
lines.append(f"配置修订:{data['revision']}")
state = data.get("state", data.get("status"))
if state is not None:
lines.append(f"控制器状态:{state}")
health = data.get("healthy", data.get("health"))
if health is not None:
lines.append(f"健康状态:{'正常' if health is True else health}")
tasks = data.get("active_tasks", data.get("busy_tasks"))
if tasks is not None:
lines.append(f"活动任务:{tasks}")
if data.get("pending_route"):
lines.append(f"待切换线路:{data['pending_route']}")
if data.get("can_switch") is not None:
lines.append(f"允许切换:{'是' if data['can_switch'] else '否'}")
return "\n".join(lines)
@classmethod
def _format_history(cls, response: ControllerResponse) -> str:
items = response.data.get("history", [])
if not items:
return response.message or "暂无路由变更记录"
lines = [response.message or f"最近 {len(items)} 条路由记录:"]
for item in items:
revision = item.get("revision", "-")
action = item.get("action", item.get("result", "变更"))
source = item.get("from_route", "-")
target = item.get("to_route", item.get("route_id", "-"))
timestamp = item.get("created_at", item.get("timestamp", ""))
success = item.get("success")
success_text = "成功" if success is True else "失败" if success is False else ""
line = f"- rev {revision}:{action},{source} → {target}"
if success_text:
line += f",{success_text}"
if timestamp:
line += f",{timestamp}"
lines.append(line)
return "\n".join(lines)
@classmethod
def _format_operation(cls, response: ControllerResponse) -> str:
data = response.data
lines = [response.message or "路由操作已完成"]
route_id = data.get("active_route_id", data.get("route_id"))
if route_id:
lines.append(f"线路:{route_id}")
if data.get("previous_route_id"):
lines.append(f"原线路:{data['previous_route_id']}")
if data.get("revision") is not None:
lines.append(f"配置修订:{data['revision']}")
health = data.get("healthy", data.get("health"))
if health is not None:
lines.append(f"健康状态:{'正常' if health is True else health}")
if data.get("latency_ms") is not None:
lines.append(f"延迟:{data['latency_ms']} ms")
checks = data.get("checks")
if isinstance(checks, dict) and checks:
formatted = ", ".join(
f"{key}={'通过' if value is True else '失败' if value is False else value}"
for key, value in checks.items()
)
lines.append(f"检查:{formatted}")
return "\n".join(lines)
def _stop_event(self, event: AstrMessageEvent) -> None:
stop = getattr(event, "stop_event", None)
if callable(stop):
stop()
# ---- LLM tool visibility: first layer of authorization ----
@filter.on_llm_request()
async def on_llm_request(self, event: AstrMessageEvent, request):
if self._enable_llm_tools and self._is_admin(event):
return
func_tool = getattr(request, "func_tool", None)
if not func_tool:
return
for tool_name in _LLM_TOOL_NAMES:
try:
func_tool.remove_tool(tool_name)
except Exception:
# A tool may already be absent or disabled in AstrBot configuration.
continue
# ---- Direct natural-language shortcut ----
@filter.regex(_NATURAL_SWITCH_RE)
@filter.event_message_type(filter.EventMessageType.ALL, priority=20)
async def natural_language_switch(self, event: AstrMessageEvent):
if not self._enable_natural_language:
return
text = str(getattr(event, "message_str", "") or "")
if text.lstrip().startswith("/"):
return
match = _NATURAL_SWITCH_RE.fullmatch(text)
if not match:
return
self._stop_event(event)
if not self._is_admin(event):
yield event.plain_result("⚠️ 此操作仅限 AstrBot 管理员")
return
try:
route_id = self._validate_route_id(match.group(1))
actor = self._actor(event)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.use_route(route_id, actor=actor, force=False),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
# ---- /route command group ----
@filter.command_group("route")
def route(self):
"""Codex route management commands."""
pass
def _button_gateway(self) -> Any | None:
"""BUTTON_GATEWAY_WIRED: shared button plugin; absent is a normal text-only state."""
meta = self.context.get_registered_star("astrbot_plugin_button_gateway")
return getattr(meta, "star_cls", None) if meta else None
async def on_button(self, action: str, payload: dict[str, Any], identity: dict[str, str]) -> tuple[bool, str]:
"""Button gateway callback for route switching / rollback / delete."""
actor = str(identity.get("user_id") or "button")[:128]
if action == "cancel":
return True, "已取消,未做任何改动。"
if action == "check":
return await self._check_then_offer(payload, identity, actor)
if action.startswith("r") and action[1:].isdigit():
routes = list(payload.get("routes") or [])
index = int(action[1:])
if index >= len(routes):
return False, "线路列表已变化,请重新 /route list。"
route_id = str(routes[index])
text = await self._safe_call(
lambda: self.gateway.use_route(route_id, actor=actor, force=False),
self._format_operation,
mutation=True,
)
return not text.startswith("⚠️"), text
if action == "rollback":
revision = payload.get("revision") or None
text = await self._safe_call(
lambda: self.gateway.rollback(actor=actor, revision=revision, force=False),
self._format_operation,
mutation=True,
)
return not text.startswith("⚠️"), text
if action == "delete":
route_id = str(payload.get("route_id") or "")
if not route_id:
return False, "缺少线路 ID。"
text = await self._safe_call(
lambda: self.gateway.delete_route(route_id=route_id, actor=actor, confirm=True, force=False),
self._format_operation,
mutation=True,
)
return not text.startswith("⚠️"), text
return False, "未知的按钮操作。"
async def _check_then_offer(self, payload: dict[str, Any], identity: dict[str, str],
actor: str) -> tuple[bool, str]:
"""Test each candidate route, then offer only the healthy ones as switch buttons."""
candidates = [str(r) for r in (payload.get("routes") or [])]
if not candidates:
return False, "没有可检测的线路,请重新 /route list。"
healthy: list[str] = []
lines: list[str] = []
for route_id in candidates:
text = await self._safe_call(
lambda rid=route_id: self.gateway.test_route(rid, actor=actor),
self._format_operation,
)
if text.startswith("⚠️"):
lines.append(f"- ❌ `{route_id}` — {sanitize_text(text.lstrip('⚠️ '))[:60]}")
else:
healthy.append(route_id)
lines.append(f"- ✅ `{route_id}` — 检测通过")
summary = "# 线路检测结果\n" + "\n".join(lines)
if not healthy:
return True, summary + "\n\n没有线路通过检测,未做任何切换。"
gateway = self._button_gateway()
if gateway is None:
return True, summary + "\n\n通过的线路:" + "、".join(healthy)
sent = await gateway.send_buttons_to(
identity,
summary + "\n\n点按钮切换到通过检测的线路。",
[
{"label": rid[:20], "action": f"r{i}", "style": 0}
for i, rid in enumerate(healthy)
],
owner="astrbot_plugin_route_gateway",
handler="on_button",
payload={"routes": healthy},
ttl_seconds=900,
)
# Empty reply when the follow-up card went out, so the gateway does not also post text.
return True, "" if sent else summary + "\n\n通过的线路:" + "、".join(healthy)
async def _offer_buttons(self, event: AstrMessageEvent, text: str, buttons: list[dict[str, Any]],
payload: dict[str, Any], *, ttl_seconds: int = 600) -> bool:
gateway = self._button_gateway()
if gateway is None:
return False
return await gateway.send_buttons(
event, text, buttons,
owner="astrbot_plugin_route_gateway",
handler="on_button",
payload=payload,
allowed_user_id=str(event.get_sender_id()),
ttl_seconds=ttl_seconds,
)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("list")
async def route_list(self, event: AstrMessageEvent):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
response = await self.gateway.list_routes()
except Exception:
yield event.plain_result(await self._safe_call(self.gateway.list_routes, self._format_routes))
return
text = self._format_routes(response)
selectable = [
r for r in (response.data.get("routes") or [])
if not r.get("deleted") and not (r.get("active") is True or r.get("is_active") is True)
][:8]
if selectable:
# CHECK_THEN_SWITCH: offer a check rather than raw switch buttons, so dead routes
# never appear as clickable options.
sent = await self._offer_buttons(
event,
"# Codex 线路\n" + text + "\n\n先检测各线路连通性,再从通过的里面选。",
[{"label": "检测并选择线路", "action": "check", "style": 1}],
{"routes": [self._route_id_from(r) for r in selectable]},
ttl_seconds=900,
)
if sent:
# Consume the event: without a result the pipeline falls through to the LLM,
# which answers the same question again with codex_route_list.
yield event.plain_result("已发送检测按钮。")
return
yield event.plain_result(text)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("status")
async def route_status(self, event: AstrMessageEvent):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
result = await self._safe_call(self.gateway.status, self._format_status)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("use")
async def route_use(
self, event: AstrMessageEvent, route_id: str, force: str = ""
):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
route_id = self._validate_route_id(route_id)
actor = self._actor(event)
force_flag = self._force(force)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.use_route(route_id, actor=actor, force=force_flag),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("test")
async def route_test(self, event: AstrMessageEvent, route_id: str):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
route_id = self._validate_route_id(route_id)
actor = self._actor(event)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.test_route(route_id, actor=actor),
self._format_operation,
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("history")
async def route_history(self, event: AstrMessageEvent, limit: int = 10):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
safe_limit = max(1, min(int(limit), self._max_history_items))
result = await self._safe_call(
lambda: self.gateway.history(limit=safe_limit), self._format_history
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("rollback")
async def route_rollback(
self, event: AstrMessageEvent, revision: int = 0, force: str = ""
):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
actor = self._actor(event)
revision_value = int(revision)
if revision_value < 0:
raise InputError("修订号不能为负数")
except (InputError, TypeError, ValueError) as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc) or '修订号无效'}")
return
if not self._force(force):
sent = await self._offer_buttons(
event,
"# 确认回滚线路配置\n"
+ (f"目标修订:`{revision_value}`\n" if revision_value else "目标:上一个修订\n")
+ "\n回滚会立即改写网关的上游配置。",
[
{"label": "确认回滚", "action": "rollback", "style": 1},
{"label": "取消", "action": "cancel", "style": 0},
],
{"revision": revision_value or None},
)
if sent:
yield event.plain_result("已发送确认按钮。")
return
result = await self._safe_call(
lambda: self.gateway.rollback(
actor=actor,
revision=revision_value or None,
force=self._force(force),
),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("create")
async def route_create(
self,
event: AstrMessageEvent,
route_id: str,
secret_ref: str,
base_url: str,
model: str,
display_name: str = "",
):
"""Usage: /route create <id> <secret_ref> <https_base_url> <model> [name]."""
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
route_id = self._validate_route_id(route_id)
secret_ref = self._validate_secret_ref(secret_ref)
base_url = self._validate_base_url(base_url)
model = self._validate_model(model)
display_name = self._validate_display_name(display_name, fallback=route_id)
actor = self._actor(event)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.create_route(
route_id=route_id,
display_name=display_name,
secret_ref=secret_ref,
base_url=base_url,
model=model,
actor=actor,
force=False,
),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("copy")
async def route_copy(
self,
event: AstrMessageEvent,
source_route_id: str,
new_route_id: str,
display_name: str = "",
):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
source_route_id = self._validate_route_id(source_route_id)
new_route_id = self._validate_route_id(new_route_id)
display_name = self._validate_display_name(
display_name, fallback=new_route_id
)
actor = self._actor(event)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.copy_route(
source_route_id=source_route_id,
new_route_id=new_route_id,
display_name=display_name,
actor=actor,
force=False,
),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("rename")
async def route_rename(
self, event: AstrMessageEvent, route_id: str, display_name: str
):
"""Rename the display label; the stable route ID is not changed."""
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
try:
route_id = self._validate_route_id(route_id)
display_name = self._validate_display_name(display_name)
actor = self._actor(event)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.rename_route(
route_id=route_id,
display_name=display_name,
actor=actor,
force=False,
),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
@filter.permission_type(filter.PermissionType.ADMIN)
@route.command("delete")
async def route_delete(
self,
event: AstrMessageEvent,
route_id: str,
confirmation: str = "",
force: str = "",
):
if not self._is_admin(event):
yield event.plain_result("⚠️ 此命令仅限 AstrBot 管理员")
return
if str(confirmation).strip().lower() not in {"confirm", "确认"}:
sent = await self._offer_buttons(
event,
f"# 确认删除线路 `{route_id}`\n\n软删除,可通过 /route rollback 找回。",
[
{"label": "确认删除", "action": "delete", "style": 1},
{"label": "取消", "action": "cancel", "style": 0},
],
{"route_id": str(route_id)},
)
yield event.plain_result(
"已发送确认按钮。" if sent
else f"⚠️ 删除采用软删除且需要确认:/route delete {route_id} confirm"
)
return
try:
route_id = self._validate_route_id(route_id)
actor = self._actor(event)
except InputError as exc:
yield event.plain_result(f"⚠️ {sanitize_text(exc)}")
return
result = await self._safe_call(
lambda: self.gateway.delete_route(
route_id=route_id,
actor=actor,
confirm=True,
force=self._force(force),
),
self._format_operation,
mutation=True,
)
yield event.plain_result(result)
# ---- LLM tools: runtime authorization is the second layer ----
def _llm_tool_allowed(self, event: AstrMessageEvent) -> bool:
return self._enable_llm_tools and self._is_admin(event)
@filter.llm_tool(name="codex_route_list")
async def tool_route_list(self, event: AstrMessageEvent):
"""列出 Codex 可用线路及其脱敏状态。"""
if not self._llm_tool_allowed(event):
yield "此工具仅限 AstrBot 管理员使用"
return
yield await self._safe_call(self.gateway.list_routes, self._format_routes)
@filter.llm_tool(name="codex_route_status")
async def tool_route_status(self, event: AstrMessageEvent):
"""查询 Codex 当前线路、配置修订和活动任务状态。"""
if not self._llm_tool_allowed(event):
yield "此工具仅限 AstrBot 管理员使用"
return
yield await self._safe_call(self.gateway.status, self._format_status)
@filter.llm_tool(name="codex_route_switch")
async def tool_route_switch(
self, event: AstrMessageEvent, route_id: str, force: bool = False
):
'''切换 Codex 后续新任务使用的线路。
Args:
route_id(string): 线路 ID,例如 0.5X 或 1X
force(boolean): 是否强制切换;默认 false,除非管理员明确要求否则不得设为 true
'''
if not self._llm_tool_allowed(event):
yield "此工具仅限 AstrBot 管理员使用"
return
try:
route_id = self._validate_route_id(route_id)
actor = self._actor(event)
except InputError as exc:
yield f"⚠️ {sanitize_text(exc)}"
return
yield await self._safe_call(
lambda: self.gateway.use_route(
route_id, actor=actor, force=bool(force)
),
self._format_operation,
mutation=True,
)
@filter.llm_tool(name="codex_route_test")
async def tool_route_test(self, event: AstrMessageEvent, route_id: str):
'''测试指定 Codex 线路的 Responses、SSE 和工具调用能力。
Args:
route_id(string): 要测试的线路 ID
'''
if not self._llm_tool_allowed(event):
yield "此工具仅限 AstrBot 管理员使用"
return
try:
route_id = self._validate_route_id(route_id)
actor = self._actor(event)
except InputError as exc:
yield f"⚠️ {sanitize_text(exc)}"
return
yield await self._safe_call(
lambda: self.gateway.test_route(route_id, actor=actor),
self._format_operation,
)

11
metadata.yaml 普通文件
查看文件

@ -0,0 +1,11 @@
name: astrbot_plugin_route_gateway
display_name: Codex 路由网关
desc: "通过本机 Unix Socket 管理 Codex 模型线路;插件不持有上游 API Key 或管理 Token。"
version: v0.1.0
author: Codex Route
repo: ""
keywords:
- codex
- route
- gateway
- cliproxyapi

154
page_api.py 普通文件
查看文件

@ -0,0 +1,154 @@
"""Dashboard-facing API for the route management page.
Everything here is a thin pass-through to the route controller over its Unix socket; the plugin
holds no key material of its own. A secret value only ever travels inbound — `secrets` returns
reference names and usage counts, and nothing in this module can read a stored value back.
"""
from __future__ import annotations
from typing import Any
from astrbot.api import logger
from .gateway_client import GatewayError
def _ok(data: Any = None, message: str = "") -> dict[str, Any]:
return {"status": "ok", "message": message, "data": data if data is not None else {}}
def _err(message: str) -> dict[str, Any]:
return {"status": "error", "message": message, "data": {}}
class RouteGatewayPageApi:
PREFIX = "/route-gateway"
def __init__(self, plugin: Any) -> None:
self.plugin = plugin
def register_routes(self) -> None:
register = self.plugin.context.register_web_api
routes = [
("/routes", self.routes, ["GET"], "Route gateway: list routes"),
("/status", self.status, ["GET"], "Route gateway: active route status"),
("/secrets", self.secrets, ["GET"], "Route gateway: list secret references"),
("/secrets/import", self.secret_import, ["POST"], "Route gateway: import a secret"),
("/secrets/delete", self.secret_delete, ["POST"], "Route gateway: delete a secret"),
("/routes/create", self.route_create, ["POST"], "Route gateway: create a route"),
("/routes/use", self.route_use, ["POST"], "Route gateway: switch active route"),
("/routes/test", self.route_test, ["POST"], "Route gateway: test a route"),
("/routes/delete", self.route_delete, ["POST"], "Route gateway: soft-delete a route"),
]
for path, handler, methods, desc in routes:
register(self.PREFIX + path, handler, methods, desc)
# ──── helpers ────
@staticmethod
async def _body() -> dict[str, Any]:
from quart import request # noqa: PLC0415 (provided by the dashboard's compat layer)
try:
value = await request.get_json(force=True, silent=True)
except Exception:
value = None
return value if isinstance(value, dict) else {}
def _actor(self) -> str:
try:
from quart import g # noqa: PLC0415
return str(getattr(g, "username", "") or "dashboard")[:128]
except Exception:
return "dashboard"
async def _call(self, coro_factory) -> dict[str, Any]:
try:
response = await coro_factory()
except GatewayError as exc:
return _err(str(exc) or "路由控制器请求失败")
except Exception as exc: # noqa: BLE001 - surface a safe message, log the detail
logger.warning("Route gateway page API 失败:%s", type(exc).__name__, exc_info=True)
return _err("处理失败,请查看 AstrBot 日志")
return _ok(response.data, response.message)
# ──── read ────
async def routes(self):
return await self._call(self.plugin.gateway.list_routes)
async def status(self):
return await self._call(self.plugin.gateway.status)
async def secrets(self):
return await self._call(self.plugin.gateway.list_secrets)
# ──── write ────
async def secret_import(self):
body = await self._body()
secret_ref = str(body.get("secret_ref") or "").strip().lower()
value = str(body.get("value") or "")
if not secret_ref or not value.strip():
return _err("secret_ref 与密钥值都不能为空")
return await self._call(
lambda: self.plugin.gateway.import_secret(secret_ref, value, actor=self._actor())
)
async def secret_delete(self):
body = await self._body()
secret_ref = str(body.get("secret_ref") or "").strip().lower()
if not secret_ref:
return _err("secret_ref 不能为空")
return await self._call(
lambda: self.plugin.gateway.delete_secret(secret_ref, actor=self._actor())
)
async def route_create(self):
body = await self._body()
required = ("route_id", "secret_ref", "base_url", "model")
missing = [k for k in required if not str(body.get(k) or "").strip()]
if missing:
return _err("缺少字段:" + "、".join(missing))
route_id = str(body["route_id"]).strip()
return await self._call(
lambda: self.plugin.gateway.create_route(
route_id=route_id,
# display_name is required downstream; fall back to the id rather than sending None.
display_name=str(body.get("display_name") or "").strip() or route_id,
secret_ref=str(body["secret_ref"]).strip().lower(),
base_url=str(body["base_url"]).strip(),
model=str(body["model"]).strip(),
actor=self._actor(),
)
)
async def route_use(self):
body = await self._body()
route_id = str(body.get("route_id") or "").strip()
if not route_id:
return _err("route_id 不能为空")
return await self._call(
lambda: self.plugin.gateway.use_route(route_id, actor=self._actor(), force=False)
)
async def route_test(self):
body = await self._body()
route_id = str(body.get("route_id") or "").strip()
if not route_id:
return _err("route_id 不能为空")
return await self._call(
lambda: self.plugin.gateway.test_route(route_id, actor=self._actor())
)
async def route_delete(self):
body = await self._body()
route_id = str(body.get("route_id") or "").strip()
if not route_id:
return _err("route_id 不能为空")
return await self._call(
lambda: self.plugin.gateway.delete_route(
route_id=route_id, actor=self._actor(), confirm=True, force=False
)
)

281
pages/routes/index.html 普通文件
查看文件

@ -0,0 +1,281 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Codex 线路管理</title>
<style>
:root {
--bg: #f7f8fa; --card: #fff; --line: #e4e6eb; --fg: #1f2329; --muted: #6b7280;
--accent: #2f6feb; --ok: #16a34a; --bad: #dc2626; --warn: #b45309;
}
@media (prefers-color-scheme: dark) {
:root { --bg:#16181d; --card:#1e2127; --line:#31343b; --fg:#e6e8ec; --muted:#9aa1ac; --accent:#5b8cff; }
}
* { box-sizing: border-box; }
body { margin:0; padding:16px; background:var(--bg); color:var(--fg);
font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans CJK SC",sans-serif; }
.card { background:var(--card); border:1px solid var(--line); border-radius:10px;
padding:16px; margin-bottom:16px; }
h2 { margin:0 0 4px; font-size:16px; }
.sub { color:var(--muted); font-size:12px; margin-bottom:12px; }
table { width:100%; border-collapse:collapse; }
th,td { text-align:left; padding:8px 6px; border-bottom:1px solid var(--line); vertical-align:middle; }
th { color:var(--muted); font-weight:600; font-size:12px; }
code { background:rgba(127,127,127,.14); padding:1px 5px; border-radius:4px; font-size:12px; }
button { font:inherit; padding:5px 12px; border-radius:6px; border:1px solid var(--line);
background:var(--card); color:var(--fg); cursor:pointer; }
button:hover:not(:disabled) { border-color:var(--accent); color:var(--accent); }
button:disabled { opacity:.45; cursor:not-allowed; }
button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
button.danger:hover:not(:disabled) { border-color:var(--bad); color:var(--bad); }
.row { display:flex; gap:8px; flex-wrap:wrap; align-items:flex-end; }
.field { display:flex; flex-direction:column; gap:4px; }
.field label { font-size:12px; color:var(--muted); }
input, select { font:inherit; padding:6px 8px; border:1px solid var(--line);
border-radius:6px; background:var(--bg); color:var(--fg); min-width:150px; }
.pill { font-size:11px; padding:1px 7px; border-radius:999px; border:1px solid var(--line); }
.pill.active { color:var(--ok); border-color:var(--ok); }
.note { font-size:12px; color:var(--warn); margin-top:8px; }
#toast { position:fixed; right:16px; bottom:16px; max-width:min(460px,80vw);
background:var(--card); border:1px solid var(--line); border-left-width:4px;
border-radius:8px; padding:10px 14px; box-shadow:0 6px 20px rgba(0,0,0,.14);
opacity:0; transform:translateY(8px); transition:.18s; pointer-events:none; }
#toast.show { opacity:1; transform:none; }
#toast.ok { border-left-color:var(--ok); } #toast.bad { border-left-color:var(--bad); }
</style>
</head>
<body>
<div class="card">
<h2>线路</h2>
<div class="sub">切换会先跑连通性检查,失败自动回滚。删除是软删除,可用 <code>/route rollback</code> 找回。</div>
<table id="routes"><thead>
<tr><th>ID</th><th>模型</th><th>端点</th><th style="width:210px">操作</th></tr>
</thead><tbody><tr><td colspan="4">加载中…</td></tr></tbody></table>
</div>
<div class="card">
<h2>新增线路</h2>
<div class="sub">密钥引用必须先在下方导入。</div>
<div class="row">
<div class="field"><label>线路 ID</label><input id="c_id" placeholder="2X" /></div>
<div class="field"><label>密钥引用</label><select id="c_secret"></select></div>
<div class="field" style="flex:1"><label>Base URL</label>
<input id="c_url" placeholder="https://example.com/v1" style="width:100%" /></div>
<div class="field"><label>模型</label><input id="c_model" placeholder="gpt-5.6-sol" /></div>
<div class="field"><label>显示名(可选)</label><input id="c_name" placeholder="2X" /></div>
<button class="primary" id="c_go">创建</button>
</div>
</div>
<div class="card">
<h2>密钥引用</h2>
<div class="sub">
密钥写入后<strong>无法再读出</strong>——本页面和所有接口都只返回引用名。仍被线路引用的密钥不可删除。
</div>
<table id="secrets"><thead>
<tr><th>引用名</th><th>被引用线路数</th><th style="width:110px">操作</th></tr>
</thead><tbody><tr><td colspan="3">加载中…</td></tr></tbody></table>
<div class="row" style="margin-top:12px">
<div class="field"><label>引用名</label><input id="s_ref" placeholder="relay_2x" /></div>
<div class="field" style="flex:1"><label>密钥值</label>
<input id="s_val" type="password" autocomplete="new-password" placeholder="sk-…" style="width:100%" /></div>
<button class="primary" id="s_go">导入</button>
</div>
<div class="note">
面板当前未启用 TLS,密钥会以明文经过局域网。这是已知并被接受的取舍。
</div>
</div>
<div id="toast"></div>
<script>
let B = null;
const PAGE_ENDPOINT_PREFIX = "page";
const $ = (id) => document.getElementById(id);
let busy = false;
function toast(msg, ok = true) {
const t = $("toast");
t.textContent = msg;
t.className = "show " + (ok ? "ok" : "bad");
clearTimeout(t._h);
t._h = setTimeout(() => (t.className = ""), 4200);
}
function setBusy(v) {
busy = v;
document.querySelectorAll("button").forEach((b) => (b.disabled = v));
}
async function call(method, endpoint, body) {
if (!B) throw new Error("页面桥接尚未就绪,请稍后重试");
const url = new URL(endpoint, "https://astrbot-plugin-page.local/");
const routePath = url.pathname
.replace(/^\/route-gateway\/?/, "")
.replace(/^\/+/, "");
const pageEndpoint = `${PAGE_ENDPOINT_PREFIX}/${routePath}`.replace(/\/+/g, "/");
const params = Object.fromEntries(url.searchParams.entries());
const res = method === "GET"
? await B.apiGet(pageEndpoint, Object.keys(params).length ? params : undefined)
: await B.apiPost(pageEndpoint, body || {});
// The dashboard forwards the plugin's payload verbatim.
if (res && res.status === "error") throw new Error(res.message || "请求失败");
return res && res.data ? res.data : {};
}
async function guard(label, fn) {
if (busy) return;
setBusy(true);
try {
const msg = await fn();
toast(msg || (label + "完成"), true);
await refresh();
} catch (e) {
toast(label + "失败:" + (e && e.message ? e.message : e), false);
} finally {
setBusy(false);
}
}
function renderRoutes(routes) {
const tb = $("routes").querySelector("tbody");
if (!routes.length) { tb.innerHTML = '<tr><td colspan="4">暂无线路</td></tr>'; return; }
tb.innerHTML = "";
for (const r of routes) {
const id = r.route_id || r.id || "-";
const active = r.active === true || r.is_active === true;
const tr = document.createElement("tr");
const name = r.display_name && r.display_name !== id ? ` <span class="pill">${esc(r.display_name)}</span>` : "";
tr.innerHTML =
`<td><code>${esc(id)}</code>${active ? ' <span class="pill active">当前</span>' : ""}${name}</td>` +
`<td>${esc(r.model || "-")}</td><td>${esc(r.endpoint || "-")}</td><td></td>`;
const cell = tr.lastElementChild;
cell.append(
btn("检测", () => guard("检测", async () => (await call("POST", "/route-gateway/routes/test", { route_id: id })).message || "检测通过")),
);
if (!active) {
cell.append(
btn("切换", () => guard("切换", async () => (await call("POST", "/route-gateway/routes/use", { route_id: id })).message || "已切换"), "primary"),
btn("删除", () => {
if (!confirm(`软删除线路 ${id}?可用 /route rollback 找回。`)) return;
guard("删除", async () => (await call("POST", "/route-gateway/routes/delete", { route_id: id })).message || "已删除");
}, "danger"),
);
}
tb.append(tr);
}
}
function renderSecrets(secrets) {
const tb = $("secrets").querySelector("tbody");
const sel = $("c_secret");
sel.innerHTML = "";
if (!secrets.length) {
tb.innerHTML = '<tr><td colspan="3">还没有密钥引用,请先在下方导入</td></tr>';
return;
}
tb.innerHTML = "";
for (const s of secrets) {
const used = Number(s.used_by_routes || 0);
const tr = document.createElement("tr");
tr.innerHTML = `<td><code>${esc(s.secret_ref)}</code></td><td>${used}</td><td></td>`;
const del = btn("删除", () => {
if (!confirm(`删除密钥引用 ${s.secret_ref}?此操作不可恢复。`)) return;
guard("删除密钥", async () => (await call("POST", "/route-gateway/secrets/delete", { secret_ref: s.secret_ref })).message || "已删除");
}, "danger");
if (used > 0) { del.disabled = true; del.title = "仍被线路引用"; }
tr.lastElementChild.append(del);
tb.append(tr);
sel.append(new Option(s.secret_ref, s.secret_ref));
}
}
function btn(label, onClick, cls) {
const b = document.createElement("button");
b.textContent = label;
if (cls) b.className = cls;
b.style.marginRight = "6px";
b.onclick = onClick;
return b;
}
const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
async function refresh() {
try {
const [routes, secrets] = await Promise.all([
call("GET", "/route-gateway/routes"),
call("GET", "/route-gateway/secrets"),
]);
renderRoutes(routes.routes || []);
renderSecrets(secrets.secrets || []);
} catch (e) {
toast("加载失败:" + (e && e.message ? e.message : e), false);
}
}
$("c_go").onclick = () =>
guard("创建线路", async () => {
const payload = {
route_id: $("c_id").value.trim(),
secret_ref: $("c_secret").value,
base_url: $("c_url").value.trim(),
model: $("c_model").value.trim(),
display_name: $("c_name").value.trim(),
};
const r = await call("POST", "/route-gateway/routes/create", payload);
["c_id", "c_url", "c_model", "c_name"].forEach((i) => ($(i).value = ""));
return r.message || "线路已创建";
});
$("s_go").onclick = () =>
guard("导入密钥", async () => {
const ref = $("s_ref").value.trim().toLowerCase();
const val = $("s_val").value;
const r = await call("POST", "/route-gateway/secrets/import", { secret_ref: ref, value: val });
// Clear immediately — the value must not linger in the DOM.
$("s_val").value = "";
$("s_ref").value = "";
return r.message || "密钥已导入";
});
function getBridge() {
if (window.AstrBotPluginPage) return window.AstrBotPluginPage;
try {
if (window.parent && window.parent !== window && window.parent.AstrBotPluginPage) {
return window.parent.AstrBotPluginPage;
}
} catch (error) {
return null;
}
return null;
}
async function waitForBridge(timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const candidate = getBridge();
if (
candidate &&
typeof candidate.ready === "function" &&
typeof candidate.apiGet === "function" &&
typeof candidate.apiPost === "function"
) {
B = candidate;
return candidate;
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error("未能初始化 AstrBot 页面桥接");
}
waitForBridge()
.then((bridge) => bridge.ready())
.then(refresh)
.catch((error) => toast(`页面初始化失败:${error.message}`, false));
</script>
</body>
</html>