astrbot_plugin_route_gateway/main.py

853 行
34 KiB
Python

"""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,
)