2026-07-05 22:07:36 +08:00
|
|
|
|
"""AstrBot ImageStudio plugin entrypoint helpers.
|
2026-07-04 22:51:52 +08:00
|
|
|
|
|
2026-07-05 22:07:36 +08:00
|
|
|
|
The plugin is mounted inside AstrBot. This module exposes pure metadata and
|
|
|
|
|
|
dispatch helpers for the runtime layer without starting a standalone server.
|
2026-07-04 22:51:52 +08:00
|
|
|
|
"""
|
2026-07-05 22:07:36 +08:00
|
|
|
|
|
|
|
|
|
|
from __future__ import annotations
|
|
|
|
|
|
|
2026-07-11 21:50:34 +08:00
|
|
|
|
import asyncio
|
|
|
|
|
|
import base64
|
|
|
|
|
|
import binascii
|
2026-07-06 10:00:18 +08:00
|
|
|
|
import inspect
|
2026-07-06 11:20:56 +08:00
|
|
|
|
import importlib
|
2026-07-06 10:00:18 +08:00
|
|
|
|
import json
|
2026-07-06 09:19:54 +08:00
|
|
|
|
import sys
|
2026-07-12 00:59:06 +08:00
|
|
|
|
from uuid import uuid4
|
2026-07-06 09:19:54 +08:00
|
|
|
|
from pathlib import Path
|
2026-07-06 10:59:28 +08:00
|
|
|
|
from typing import Any, Callable, Mapping
|
2026-07-05 22:07:36 +08:00
|
|
|
|
|
2026-07-06 09:19:54 +08:00
|
|
|
|
|
|
|
|
|
|
PLUGIN_ROOT = Path(__file__).resolve().parent
|
|
|
|
|
|
if str(PLUGIN_ROOT) not in sys.path:
|
|
|
|
|
|
# AstrBot may import the plugin entrypoint without adding the plugin root.
|
|
|
|
|
|
sys.path.insert(0, str(PLUGIN_ROOT))
|
|
|
|
|
|
|
2026-07-12 20:30:10 +08:00
|
|
|
|
|
|
|
|
|
|
def _prepend_plugin_package_path(package_name: str) -> None:
|
|
|
|
|
|
"""Let absolute legacy imports resolve inside the plugin package.
|
|
|
|
|
|
|
|
|
|
|
|
AstrBot itself may already have imported a top-level package named
|
|
|
|
|
|
``core``. In that case, merely adding the plugin root to ``sys.path`` is
|
|
|
|
|
|
insufficient because Python reuses the existing package from
|
|
|
|
|
|
``sys.modules``. Prepending our package directory to that package's
|
|
|
|
|
|
search path keeps the host package intact while allowing imports such as
|
|
|
|
|
|
``core.config_service`` to resolve to ImageStudio's implementation.
|
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
|
|
package_dir = PLUGIN_ROOT / package_name
|
|
|
|
|
|
loaded_package = sys.modules.get(package_name)
|
|
|
|
|
|
search_path = getattr(loaded_package, "__path__", None)
|
|
|
|
|
|
if search_path is None or not package_dir.is_dir():
|
|
|
|
|
|
return
|
|
|
|
|
|
package_path = str(package_dir)
|
|
|
|
|
|
if package_path in search_path:
|
|
|
|
|
|
search_path.remove(package_path)
|
|
|
|
|
|
search_path.insert(0, package_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
for _package_name in ("core", "adapters", "backend", "database", "engines"):
|
|
|
|
|
|
_prepend_plugin_package_path(_package_name)
|
|
|
|
|
|
|
2026-07-06 04:00:59 +08:00
|
|
|
|
from adapters.astrbot_adapter import (
|
|
|
|
|
|
dispatch_extension_request,
|
2026-07-06 10:00:18 +08:00
|
|
|
|
normalize_extension_path,
|
2026-07-06 04:00:59 +08:00
|
|
|
|
register_astrbot_runtime,
|
|
|
|
|
|
runtime_health,
|
|
|
|
|
|
runtime_registration_manifest,
|
|
|
|
|
|
runtime_route_table,
|
|
|
|
|
|
)
|
2026-07-12 00:59:06 +08:00
|
|
|
|
from adapters.astrbot_command_adapter import (
|
|
|
|
|
|
accepted_text,
|
|
|
|
|
|
access_denied_text,
|
|
|
|
|
|
command_allowed,
|
|
|
|
|
|
command_context_from_event,
|
|
|
|
|
|
help_text,
|
|
|
|
|
|
message_text_from_event,
|
|
|
|
|
|
)
|
|
|
|
|
|
from adapters.astrbot_card_renderer import render_help_card, render_profile_card, render_status_card
|
|
|
|
|
|
from adapters.astrbot_command_parser import parse_single_image_command, single_image_usage
|
|
|
|
|
|
from adapters.astrbot_media_adapter import image_references_from_event
|
|
|
|
|
|
from backend.dto.chat_command_dto import ChatCommandParseError
|
|
|
|
|
|
from backend.services.chat_workflow_service import ChatWorkflowService
|
|
|
|
|
|
from backend.services.chat_session_service import ChatSessionStore
|
2026-07-05 22:07:36 +08:00
|
|
|
|
from adapters.webui_adapter import get_web_mount_manifest
|
2026-07-06 10:00:18 +08:00
|
|
|
|
from backend.route_registry import ROUTES
|
2026-07-11 21:50:34 +08:00
|
|
|
|
from backend.services.model_provider_bootstrap import (
|
|
|
|
|
|
sync_generation_provider_from_config,
|
|
|
|
|
|
sync_vision_provider_from_config,
|
|
|
|
|
|
)
|
|
|
|
|
|
from backend.services.model_provider_service import ModelProviderService
|
2026-07-05 22:07:36 +08:00
|
|
|
|
from backend.services.ui_service import API_BASE
|
|
|
|
|
|
from core.identity import RequestContext
|
2026-07-11 21:50:34 +08:00
|
|
|
|
from core.media_proxy import MediaProxy
|
2026-07-06 11:20:56 +08:00
|
|
|
|
from database import db_helper as _database_db_helper
|
2026-07-11 21:50:34 +08:00
|
|
|
|
from database.repositories.model_provider_repository import ModelProviderRepository
|
2026-07-10 01:25:15 +08:00
|
|
|
|
from database.seed import seed_default_material_categories
|
2026-07-06 11:20:56 +08:00
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
if not hasattr(_database_db_helper, "set_runtime_config_overrides"):
|
|
|
|
|
|
_database_db_helper = importlib.reload(_database_db_helper)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
Database = _database_db_helper.Database
|
|
|
|
|
|
DatabaseSettings = _database_db_helper.DatabaseSettings
|
|
|
|
|
|
load_database_settings = _database_db_helper.load_database_settings
|
2026-07-05 22:07:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
PLUGIN_NAME = "astrbot_plugin_imagestudio"
|
2026-07-06 09:26:29 +08:00
|
|
|
|
PLUGIN_DESC = "AstrBot ImageStudio role asset production and image-generation workspace."
|
2026-07-12 23:59:14 +08:00
|
|
|
|
PLUGIN_VERSION = "1.0.5"
|
2026-07-11 21:50:34 +08:00
|
|
|
|
BRIDGE_PERMISSIONS = frozenset(
|
|
|
|
|
|
{"can_write", "can_manage_config", "can_manage_materials", "can_retry_tasks"}
|
|
|
|
|
|
)
|
2026-07-06 10:59:28 +08:00
|
|
|
|
_MISSING = object()
|
2026-07-06 09:26:29 +08:00
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
from astrbot.api.star import Star as AstrBotStar
|
|
|
|
|
|
from astrbot.api.star import register as astrbot_star_register
|
2026-07-12 00:59:06 +08:00
|
|
|
|
from astrbot.api.event import AstrMessageEvent, filter as astrbot_filter
|
|
|
|
|
|
from astrbot.api.event import MessageChain as AstrBotMessageChain
|
|
|
|
|
|
from astrbot.api.message_components import Image as AstrBotImage
|
|
|
|
|
|
from astrbot.api.message_components import Plain as AstrBotPlain
|
2026-07-06 09:26:29 +08:00
|
|
|
|
except Exception: # pragma: no cover - AstrBot is only present in runtime.
|
|
|
|
|
|
class AstrBotStar: # type: ignore[no-redef]
|
|
|
|
|
|
def __init__(self, context: Any | None = None, *args: Any, **kwargs: Any) -> None:
|
|
|
|
|
|
self.context = context
|
|
|
|
|
|
|
|
|
|
|
|
def astrbot_star_register(*args: Any, **kwargs: Any) -> Any:
|
|
|
|
|
|
def decorator(cls: type[Any]) -> type[Any]:
|
|
|
|
|
|
return cls
|
|
|
|
|
|
|
|
|
|
|
|
return decorator
|
2026-07-05 22:07:36 +08:00
|
|
|
|
|
2026-07-12 00:59:06 +08:00
|
|
|
|
AstrMessageEvent = Any # type: ignore[misc,assignment]
|
|
|
|
|
|
AstrBotImage = None # type: ignore[assignment]
|
|
|
|
|
|
AstrBotPlain = None # type: ignore[assignment]
|
|
|
|
|
|
AstrBotMessageChain = None # type: ignore[assignment]
|
|
|
|
|
|
|
|
|
|
|
|
class _FallbackCommandGroup:
|
|
|
|
|
|
def __call__(self, function: Callable[..., Any]) -> Callable[..., Any]:
|
|
|
|
|
|
setattr(function, "command", self.command)
|
|
|
|
|
|
return function
|
|
|
|
|
|
|
|
|
|
|
|
def command(self, *args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
|
|
|
|
return lambda function: function
|
|
|
|
|
|
|
|
|
|
|
|
class _FallbackFilter:
|
|
|
|
|
|
class EventMessageType:
|
|
|
|
|
|
ALL = "all"
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def command_group(*args: Any, **kwargs: Any) -> _FallbackCommandGroup:
|
|
|
|
|
|
return _FallbackCommandGroup()
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def event_message_type(*args: Any, **kwargs: Any) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
|
|
|
|
|
|
return lambda function: function
|
|
|
|
|
|
|
|
|
|
|
|
astrbot_filter = _FallbackFilter()
|
|
|
|
|
|
|
2026-07-05 22:07:36 +08:00
|
|
|
|
|
|
|
|
|
|
def get_plugin_manifest() -> dict[str, Any]:
|
|
|
|
|
|
web_manifest = get_web_mount_manifest()
|
2026-07-06 04:00:59 +08:00
|
|
|
|
runtime = runtime_registration_manifest()
|
2026-07-05 22:07:36 +08:00
|
|
|
|
return {
|
|
|
|
|
|
"plugin_name": PLUGIN_NAME,
|
|
|
|
|
|
"api_base": API_BASE,
|
2026-07-06 04:21:50 +08:00
|
|
|
|
"contract_url": f"{API_BASE}/contract",
|
2026-07-05 22:07:36 +08:00
|
|
|
|
"web": web_manifest,
|
|
|
|
|
|
"routes": runtime_route_table(),
|
2026-07-06 04:00:59 +08:00
|
|
|
|
"runtime": runtime,
|
|
|
|
|
|
"health": runtime["health"],
|
2026-07-05 22:07:36 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 04:00:59 +08:00
|
|
|
|
def register_plugin(runtime: Any) -> dict[str, Any]:
|
2026-07-06 10:00:18 +08:00
|
|
|
|
result = register_astrbot_runtime(runtime, runtime_registration_manifest())
|
|
|
|
|
|
result["bridge_api"] = register_bridge_api(runtime)
|
|
|
|
|
|
return result
|
2026-07-06 04:00:59 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_runtime_health() -> dict[str, Any]:
|
|
|
|
|
|
return runtime_health()
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:36:39 +08:00
|
|
|
|
def initialize_runtime_database(settings: DatabaseSettings | None = None) -> dict[str, Any]:
|
|
|
|
|
|
database = Database(settings or load_database_settings())
|
|
|
|
|
|
database.initialize()
|
2026-07-10 01:25:15 +08:00
|
|
|
|
seed = seed_default_material_categories(database)
|
2026-07-11 21:50:34 +08:00
|
|
|
|
model_provider_service = ModelProviderService(ModelProviderRepository(database))
|
|
|
|
|
|
config_payload = _database_db_helper.load_config_payload()
|
|
|
|
|
|
generation_provider = sync_generation_provider_from_config(model_provider_service, config_payload)
|
|
|
|
|
|
vision_provider = sync_vision_provider_from_config(model_provider_service, config_payload)
|
|
|
|
|
|
return {
|
|
|
|
|
|
"initialized": True,
|
|
|
|
|
|
"backend": database.backend,
|
|
|
|
|
|
"seed": {"material_categories": seed},
|
|
|
|
|
|
"generation_provider": generation_provider,
|
|
|
|
|
|
"vision_provider": vision_provider,
|
|
|
|
|
|
}
|
2026-07-06 10:36:39 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:59:28 +08:00
|
|
|
|
def apply_astrbot_config_overrides(config: Any | None) -> dict[str, Any]:
|
|
|
|
|
|
mapping = _mapping_from_runtime_config(config)
|
|
|
|
|
|
patch = _runtime_config_patch_from_mapping(mapping)
|
2026-07-06 11:20:56 +08:00
|
|
|
|
_set_runtime_config_overrides(patch)
|
2026-07-06 10:59:28 +08:00
|
|
|
|
return {"applied": bool(patch), "keys": _flatten_config_keys(patch)}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-05 22:07:36 +08:00
|
|
|
|
def dispatch_web_request(
|
|
|
|
|
|
ctx: RequestContext,
|
|
|
|
|
|
method: str,
|
|
|
|
|
|
path: str,
|
|
|
|
|
|
*,
|
|
|
|
|
|
query: dict[str, Any] | None = None,
|
|
|
|
|
|
payload: dict[str, Any] | None = None,
|
|
|
|
|
|
) -> dict[str, Any]:
|
|
|
|
|
|
return dispatch_extension_request(ctx, method, path, query=query, payload=payload)
|
2026-07-06 09:26:29 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:00:18 +08:00
|
|
|
|
def register_bridge_api(runtime: Any) -> dict[str, Any]:
|
|
|
|
|
|
"""Register AstrBot Plugin Page bridge endpoints under /api/plug/{plugin}."""
|
|
|
|
|
|
|
|
|
|
|
|
registrar = getattr(runtime, "register_web_api", None)
|
|
|
|
|
|
if not callable(registrar):
|
|
|
|
|
|
return {"registered": False, "routes_registered": 0, "missing_capabilities": ["register_web_api"]}
|
|
|
|
|
|
|
|
|
|
|
|
registered = 0
|
|
|
|
|
|
errors: list[dict[str, Any]] = []
|
|
|
|
|
|
for route in _bridge_registration_routes():
|
|
|
|
|
|
handler = _make_bridge_handler(endpoint=route["endpoint"], method=route["method"])
|
|
|
|
|
|
try:
|
|
|
|
|
|
if _call_web_api_registrar(registrar, route["path"], handler, route["method"]):
|
|
|
|
|
|
registered += 1
|
|
|
|
|
|
except Exception as exc: # pragma: no cover - depends on AstrBot runtime version.
|
|
|
|
|
|
errors.append(
|
|
|
|
|
|
{
|
|
|
|
|
|
"method": route["method"],
|
|
|
|
|
|
"path": route["path"],
|
|
|
|
|
|
"message": str(exc),
|
|
|
|
|
|
"exception": exc.__class__.__name__,
|
|
|
|
|
|
}
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
|
"registered": registered > 0,
|
|
|
|
|
|
"routes_registered": registered,
|
|
|
|
|
|
"missing_capabilities": [],
|
|
|
|
|
|
"errors": errors,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def dispatch_bridge_request(
|
|
|
|
|
|
endpoint: str,
|
|
|
|
|
|
*,
|
|
|
|
|
|
method: str = "GET",
|
|
|
|
|
|
request: Any | None = None,
|
|
|
|
|
|
query: dict[str, Any] | None = None,
|
|
|
|
|
|
payload: dict[str, Any] | None = None,
|
2026-07-11 21:50:34 +08:00
|
|
|
|
) -> Any:
|
2026-07-06 10:00:18 +08:00
|
|
|
|
ctx = _request_context_from_astrbot_request(request)
|
2026-07-11 21:50:34 +08:00
|
|
|
|
request_method = _request_method(request, fallback=method)
|
|
|
|
|
|
request_payload = payload if payload is not None else await _request_payload(request)
|
|
|
|
|
|
dispatch_method, dispatch_payload = _unwrap_method_override(request_method, request_payload)
|
|
|
|
|
|
dispatch_endpoint = _bridge_endpoint(endpoint, request)
|
|
|
|
|
|
dispatch_query = query if query is not None else _request_query(request)
|
|
|
|
|
|
if dispatch_method == "GET" and normalize_extension_path(dispatch_endpoint) == "media/fetch":
|
|
|
|
|
|
file_response = await _to_media_file_response(dispatch_query)
|
|
|
|
|
|
if file_response is not None:
|
|
|
|
|
|
return file_response
|
|
|
|
|
|
response = await asyncio.to_thread(
|
|
|
|
|
|
dispatch_web_request,
|
2026-07-06 10:00:18 +08:00
|
|
|
|
ctx,
|
2026-07-11 21:50:34 +08:00
|
|
|
|
dispatch_method,
|
|
|
|
|
|
dispatch_endpoint,
|
|
|
|
|
|
query=dispatch_query,
|
|
|
|
|
|
payload=dispatch_payload,
|
2026-07-06 10:00:18 +08:00
|
|
|
|
)
|
2026-07-11 21:50:34 +08:00
|
|
|
|
media_response = _to_media_http_response(dispatch_endpoint, response)
|
|
|
|
|
|
if media_response is not None:
|
|
|
|
|
|
return media_response
|
2026-07-06 10:00:18 +08:00
|
|
|
|
return _to_bridge_response(response)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 09:26:29 +08:00
|
|
|
|
def _register_star_class(cls: type[Any]) -> type[Any]:
|
|
|
|
|
|
try:
|
|
|
|
|
|
return astrbot_star_register(PLUGIN_NAME, "YokiiroBW", PLUGIN_DESC, PLUGIN_VERSION)(cls)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return cls
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@_register_star_class
|
|
|
|
|
|
class Main(AstrBotStar):
|
|
|
|
|
|
"""Minimal AstrBot plugin class for runtime discovery."""
|
|
|
|
|
|
|
|
|
|
|
|
def __init__(self, context: Any | None = None, *args: Any, **kwargs: Any) -> None:
|
2026-07-06 10:59:28 +08:00
|
|
|
|
runtime_config = _runtime_config_argument(args, kwargs)
|
2026-07-06 09:26:29 +08:00
|
|
|
|
try:
|
|
|
|
|
|
super().__init__(context, *args, **kwargs)
|
|
|
|
|
|
except TypeError:
|
|
|
|
|
|
try:
|
|
|
|
|
|
super().__init__(*args, **kwargs)
|
|
|
|
|
|
except TypeError:
|
|
|
|
|
|
super().__init__()
|
|
|
|
|
|
self.context = context
|
2026-07-06 10:59:28 +08:00
|
|
|
|
self.astrbot_config = runtime_config if runtime_config is not None else _attr(self, "config")
|
2026-07-06 09:37:00 +08:00
|
|
|
|
self.registration_result: dict[str, Any] | None = None
|
2026-07-06 10:36:39 +08:00
|
|
|
|
self.database_result: dict[str, Any] | None = None
|
2026-07-06 10:59:28 +08:00
|
|
|
|
self.runtime_config_result: dict[str, Any] | None = None
|
2026-07-12 00:59:06 +08:00
|
|
|
|
self.chat_workflow_service = ChatWorkflowService(dispatch_web_request)
|
|
|
|
|
|
self.chat_sessions = ChatSessionStore(ttl_seconds=600, max_sessions=1000)
|
|
|
|
|
|
self.chat_background_tasks: set[asyncio.Task[Any]] = set()
|
2026-07-06 09:26:29 +08:00
|
|
|
|
|
|
|
|
|
|
async def initialize(self) -> None:
|
2026-07-06 10:59:28 +08:00
|
|
|
|
self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config)
|
2026-07-06 09:37:00 +08:00
|
|
|
|
if self.context is not None:
|
|
|
|
|
|
self.registration_result = register_plugin(self.context)
|
2026-07-06 10:36:39 +08:00
|
|
|
|
if self.registration_result.get("bridge_api", {}).get("registered"):
|
|
|
|
|
|
self.database_result = initialize_runtime_database()
|
2026-07-06 09:26:29 +08:00
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
async def terminate(self) -> None:
|
2026-07-12 00:59:06 +08:00
|
|
|
|
for task in list(self.chat_background_tasks):
|
|
|
|
|
|
task.cancel()
|
|
|
|
|
|
if self.chat_background_tasks:
|
|
|
|
|
|
await asyncio.gather(*self.chat_background_tasks, return_exceptions=True)
|
2026-07-06 09:26:29 +08:00
|
|
|
|
return None
|
|
|
|
|
|
|
2026-07-12 00:59:06 +08:00
|
|
|
|
@astrbot_filter.command_group("影棚")
|
|
|
|
|
|
def imagestudio_command(self) -> None:
|
|
|
|
|
|
"""ImageStudio chat command group."""
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("帮助")
|
|
|
|
|
|
async def imagestudio_help(self, event: AstrMessageEvent):
|
|
|
|
|
|
yield self._card_result(event, self._help_card, help_text())
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("状态")
|
|
|
|
|
|
async def imagestudio_status(self, event: AstrMessageEvent):
|
|
|
|
|
|
health = get_runtime_health()
|
|
|
|
|
|
state = "正常" if health.get("healthy") is not False else "异常"
|
|
|
|
|
|
database = "已初始化" if self.database_result else "等待初始化"
|
|
|
|
|
|
text = f"🛰 ImageStudio 状态:{state}\n版本:{PLUGIN_VERSION}\nAPI:{API_BASE}\n数据库:{database}"
|
|
|
|
|
|
yield self._card_result(event, lambda: render_status_card(state=state, version=PLUGIN_VERSION, database=database, api=API_BASE), text)
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("快速角色")
|
|
|
|
|
|
async def imagestudio_quick_profile(self, event: AstrMessageEvent, description: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
config = _database_db_helper.load_config_payload()
|
|
|
|
|
|
if not command_allowed(config, "quick_profile", context):
|
|
|
|
|
|
self._record_chat_denied(context, "quick_profile")
|
|
|
|
|
|
yield event.plain_result(access_denied_text("快速角色", context))
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
draft = await asyncio.to_thread(self.chat_workflow_service.create_quick_profile_draft, description, context)
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 快速角色草稿创建失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
self.chat_sessions.put(self._session_key(context), "confirm_quick_profile", {"draft": draft})
|
|
|
|
|
|
preview = draft.get("profile_preview", {})
|
|
|
|
|
|
text = (
|
|
|
|
|
|
f"🧩 快速角色草稿\n\n名称:{preview.get('name')}\n基础:{preview.get('base_prompt') or '—'}\n"
|
|
|
|
|
|
f"外观:{preview.get('appearance_prompt') or '—'}\n风格:{preview.get('style_prompt') or '—'}\n\n"
|
|
|
|
|
|
"发送 /yp 确认 保存,或 /yp 放弃 取消。"
|
|
|
|
|
|
)
|
|
|
|
|
|
yield self._card_result(
|
|
|
|
|
|
event,
|
|
|
|
|
|
lambda: render_profile_card(
|
|
|
|
|
|
name=str(preview.get("name") or ""), base=str(preview.get("base_prompt") or ""),
|
|
|
|
|
|
appearance=str(preview.get("appearance_prompt") or ""), style=str(preview.get("style_prompt") or ""),
|
|
|
|
|
|
),
|
|
|
|
|
|
text,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("工作流")
|
|
|
|
|
|
async def imagestudio_workflow(self, event: AstrMessageEvent, profile: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
config = _database_db_helper.load_config_payload()
|
|
|
|
|
|
if not command_allowed(config, "character_workflow", context):
|
|
|
|
|
|
self._record_chat_denied(context, "character_workflow")
|
|
|
|
|
|
yield event.plain_result(access_denied_text("角色工作流", context))
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
detail = await asyncio.to_thread(self.chat_workflow_service.create_or_resume_character_workflow, profile, context)
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 工作流创建失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
yield event.plain_result(self._format_workflow(detail))
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("确认")
|
|
|
|
|
|
async def imagestudio_confirm(self, event: AstrMessageEvent):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
session = self.chat_sessions.pop(self._session_key(context))
|
|
|
|
|
|
if session is None:
|
|
|
|
|
|
yield event.plain_result("当前没有等待确认的 ImageStudio 操作。")
|
|
|
|
|
|
return
|
|
|
|
|
|
if session.action == "confirm_quick_profile":
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.save_quick_profile_draft, session.payload["draft"], context)
|
|
|
|
|
|
nodes = result.get("nodes", [])
|
|
|
|
|
|
if nodes:
|
|
|
|
|
|
self.chat_sessions.put(self._session_key(context), "quick_profile_ready", {"node_id": nodes[0]["node_id"]})
|
|
|
|
|
|
yield event.plain_result(f"✅ 快速角色已保存\n角色:{result['profile']['name']}\nID:{result['profile']['profile_id']}\n工作流:{result.get('workflow', {}).get('workflow_id', '—')}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 保存失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
if session.action == "confirm_materials":
|
|
|
|
|
|
confirmed = []
|
|
|
|
|
|
try:
|
|
|
|
|
|
for material_id in session.payload["material_ids"]:
|
|
|
|
|
|
confirmed.append(await asyncio.to_thread(self.chat_workflow_service.confirm_material, material_id, context))
|
|
|
|
|
|
yield event.plain_result("✅ 素材已确认:" + "、".join(item["material_id"] for item in confirmed))
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 素材确认失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
if session.action == "confirm_material":
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.confirm_material, session.payload["material_id"], context)
|
|
|
|
|
|
yield event.plain_result(f"✅ 素材已确认:{result['material_id']}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 素材确认失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
yield event.plain_result("该会话暂不支持确认。")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("放弃")
|
|
|
|
|
|
async def imagestudio_discard(self, event: AstrMessageEvent):
|
|
|
|
|
|
session = self.chat_sessions.pop(self._session_key(command_context_from_event(event)))
|
|
|
|
|
|
yield event.plain_result("已取消当前操作。" if session else "当前没有待取消的操作。")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("修改")
|
|
|
|
|
|
async def imagestudio_modify_draft(self, event: AstrMessageEvent, addition: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
session = self.chat_sessions.get(self._session_key(context))
|
|
|
|
|
|
if session is None or session.action != "confirm_quick_profile":
|
|
|
|
|
|
yield event.plain_result("当前没有等待修改的快速角色草稿。")
|
|
|
|
|
|
return
|
|
|
|
|
|
preview = session.payload["draft"].get("profile_preview", {})
|
|
|
|
|
|
description = f"{preview.get('name', '')} {preview.get('base_prompt', '')} {addition}".strip()
|
|
|
|
|
|
try:
|
|
|
|
|
|
draft = await asyncio.to_thread(self.chat_workflow_service.create_quick_profile_draft, description, context)
|
|
|
|
|
|
self.chat_sessions.put(self._session_key(context), "confirm_quick_profile", {"draft": draft})
|
|
|
|
|
|
updated = draft.get("profile_preview", {})
|
|
|
|
|
|
yield event.plain_result(f"📝 草稿已更新\n名称:{updated.get('name')}\n设定:{updated.get('base_prompt')}\n发送 /yp 确认 保存。")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 修改失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("节点")
|
|
|
|
|
|
async def imagestudio_nodes(self, event: AstrMessageEvent, workflow_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
detail = await asyncio.to_thread(self.chat_workflow_service.workflow_detail, workflow_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result(self._format_workflow(detail))
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 节点查询失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("生成")
|
|
|
|
|
|
async def imagestudio_generate_node(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.generate_node, node_id.strip(), context)
|
|
|
|
|
|
images = result.get("images", [])
|
|
|
|
|
|
if images:
|
|
|
|
|
|
self.chat_sessions.put(self._session_key(context), "select_image", {"node_id": node_id.strip(), "image_ids": [item["image_id"] for item in images]})
|
|
|
|
|
|
yield self._generation_result(event, f"✅ 节点生成完成\n节点:{node_id}\n任务:{result.get('task_id') or result.get('request_id') or '—'}\n回复数字选图,或使用 /yp 选择 <序号>。", images)
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 节点生成失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("重试节点")
|
|
|
|
|
|
async def imagestudio_retry_node(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.retry_node, node_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result(f"✅ 节点已重试:{result.get('task_id') or node_id}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 节点重试失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("完成节点")
|
|
|
|
|
|
async def imagestudio_complete_node(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.complete_node, node_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result(f"✅ 节点已完成:{result.get('node_id', node_id)}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 完成节点失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("下一步")
|
|
|
|
|
|
async def imagestudio_next_step(self, event: AstrMessageEvent, workflow_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.next_workflow_step, workflow_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
if result.get("completed"):
|
|
|
|
|
|
yield event.plain_result(f"✅ 工作流已没有待执行节点:{workflow_id}")
|
|
|
|
|
|
else:
|
|
|
|
|
|
yield event.plain_result(f"✅ 已执行下一节点\n节点:{result['node']['node_id']}\n任务:{result['generation'].get('task_id') or '—'}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 下一步执行失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("选图")
|
|
|
|
|
|
async def imagestudio_select_image(self, event: AstrMessageEvent, node_id: str = "", image_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
if image_id.strip().isdigit():
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.select_node_image_by_number, node_id.strip(), int(image_id), command_context_from_event(event))
|
|
|
|
|
|
else:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.select_node_image, node_id.strip(), image_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result(f"✅ 已选择图片:{result.get('image_id', image_id)}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 选图失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("候选图")
|
|
|
|
|
|
async def imagestudio_candidate_images(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
try:
|
|
|
|
|
|
images = await asyncio.to_thread(self.chat_workflow_service.list_node_images, node_id.strip(), context)
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 候选图读取失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
if not images:
|
|
|
|
|
|
yield event.plain_result("当前节点没有候选图。")
|
|
|
|
|
|
return
|
|
|
|
|
|
self.chat_sessions.put(
|
|
|
|
|
|
self._session_key(context),
|
|
|
|
|
|
"select_image",
|
|
|
|
|
|
{"node_id": node_id.strip(), "image_ids": [item["image_id"] for item in images]},
|
|
|
|
|
|
)
|
|
|
|
|
|
yield self._generation_result(event, "回复 /yp 选择 1 采用第一张候选图。", images)
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("选择")
|
|
|
|
|
|
async def imagestudio_choose_candidate(self, event: AstrMessageEvent, number: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
session = self.chat_sessions.get(self._session_key(context))
|
|
|
|
|
|
if session is None or session.action != "select_image":
|
|
|
|
|
|
yield event.plain_result("当前没有等待选择的候选图。")
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
index = int(number) - 1
|
|
|
|
|
|
image_id = session.payload["image_ids"][index]
|
|
|
|
|
|
result = await asyncio.to_thread(
|
|
|
|
|
|
self.chat_workflow_service.select_node_image,
|
|
|
|
|
|
session.payload["node_id"],
|
|
|
|
|
|
image_id,
|
|
|
|
|
|
context,
|
|
|
|
|
|
)
|
|
|
|
|
|
self.chat_sessions.pop(self._session_key(context))
|
|
|
|
|
|
yield event.plain_result(f"✅ 已采用第 {index + 1} 张:{result.get('image_id', image_id)}\n可继续使用 /yp 下一步、/yp 重试节点 或 /yp 审核。")
|
|
|
|
|
|
except (ValueError, IndexError):
|
|
|
|
|
|
yield event.plain_result(f"请输入 1 到 {len(session.payload['image_ids'])} 之间的序号。")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 选图失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("审核")
|
|
|
|
|
|
async def imagestudio_review(self, event: AstrMessageEvent, target_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.review, target_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result("🔎 审核结果\n" + json.dumps(result, ensure_ascii=False, indent=2)[:3000])
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 审核失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("高清")
|
|
|
|
|
|
async def imagestudio_hires(self, event: AstrMessageEvent, image_id: str = "", size: str = "2K"):
|
|
|
|
|
|
normalized_size = {"1K": "1920x1080", "2K": "2560x1440", "4K": "3840x2160"}.get(size.upper())
|
|
|
|
|
|
if not image_id.strip() or normalized_size is None:
|
|
|
|
|
|
yield event.plain_result("用法:/yp 高清 <image_id> 2K|4K")
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.hires_fix, image_id.strip(), normalized_size, command_context_from_event(event))
|
|
|
|
|
|
yield self._generation_result(event, f"✅ 高清修复完成\n原图:{image_id}\n尺寸:{normalized_size}", result.get("images", []))
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 高清修复失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("素材导入")
|
|
|
|
|
|
async def imagestudio_import_material(self, event: AstrMessageEvent, category: str = ""):
|
|
|
|
|
|
references = image_references_from_event(event)
|
|
|
|
|
|
if not category.strip() or not references:
|
|
|
|
|
|
yield event.plain_result("用法:发送图片并附带 /yp 素材导入 <现有分类名称或ID>")
|
|
|
|
|
|
return
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
try:
|
|
|
|
|
|
results = [await asyncio.to_thread(self.chat_workflow_service.import_material, reference, category.strip(), context) for reference in references]
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 素材导入或识别失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
material = results[0]["material"]
|
|
|
|
|
|
material_ids = [item["material"]["material_id"] for item in results]
|
|
|
|
|
|
profile_names = [item.get("name") for item in results[0].get("profiles", []) if item.get("name")]
|
|
|
|
|
|
self.chat_sessions.put(self._session_key(context), "confirm_materials", {"material_ids": material_ids})
|
|
|
|
|
|
yield event.plain_result(
|
|
|
|
|
|
f"🧵 已识别 {len(results)} 个素材\nID:{'、'.join(material_ids)}\n分类:{results[0]['category']['name']}\n"
|
|
|
|
|
|
f"提示词:{material.get('prompt') or '—'}\n标签:{'、'.join(material.get('tags') or [])}\n\n"
|
|
|
|
|
|
f"可用角色:{'、'.join(profile_names[:10]) or '暂无'}\n\n发送 /yp 确认 保存素材,或 /yp 放弃 取消。"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("重新识别")
|
|
|
|
|
|
async def imagestudio_re_recognize_material(self, event: AstrMessageEvent, material_id: str = ""):
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.re_recognize_material, material_id.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result(f"✅ 素材已重新识别\nID:{result['material_id']}\n提示词:{result.get('prompt') or '—'}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 重新识别失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("加入衣橱")
|
|
|
|
|
|
async def imagestudio_add_wardrobe(self, event: AstrMessageEvent, material_id: str = "", profile: str = "", category: str = "top"):
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.add_material_to_wardrobe, material_id.strip(), profile.strip(), category.strip(), command_context_from_event(event))
|
|
|
|
|
|
yield event.plain_result(f"✅ 素材已加入角色衣橱:{result.get('wardrobe_item_id') or material_id}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 加入衣橱失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("单图")
|
|
|
|
|
|
async def imagestudio_single_image(self, event: AstrMessageEvent, prompt: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
config = _database_db_helper.load_config_payload()
|
|
|
|
|
|
if not command_allowed(config, "single_image", context):
|
|
|
|
|
|
self._record_chat_denied(context, "single_image")
|
|
|
|
|
|
yield event.plain_result(access_denied_text("单图生成", context))
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
command = parse_single_image_command(prompt)
|
|
|
|
|
|
except ChatCommandParseError as exc:
|
|
|
|
|
|
yield event.plain_result(single_image_usage(str(exc)))
|
|
|
|
|
|
return
|
|
|
|
|
|
request_id = f"chatreq_{uuid4().hex}"
|
|
|
|
|
|
task = asyncio.create_task(self._run_single_image_background(command, context, request_id))
|
|
|
|
|
|
self.chat_background_tasks.add(task)
|
|
|
|
|
|
task.add_done_callback(self.chat_background_tasks.discard)
|
|
|
|
|
|
yield event.plain_result(
|
|
|
|
|
|
"✅ 单图请求已进入后台执行\n\n"
|
|
|
|
|
|
f"请求:{request_id}\n尺寸:{command.size}\n数量:{command.count}\n"
|
|
|
|
|
|
f"模型:{command.model_route or 'quick_generation'}\n\n生成完成后会自动发送到当前会话。"
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("任务")
|
|
|
|
|
|
async def imagestudio_jobs(self, event: AstrMessageEvent, task_id: str = ""):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.list_jobs, context, task_id=task_id.strip() or None)
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 任务查询失败:{exc}")
|
|
|
|
|
|
return
|
|
|
|
|
|
yield event.plain_result(self._format_jobs(result))
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("取消")
|
|
|
|
|
|
async def imagestudio_cancel_job(self, event: AstrMessageEvent, task_id: str = ""):
|
|
|
|
|
|
if not task_id.strip():
|
|
|
|
|
|
yield event.plain_result("请提供任务 ID,例如:/yp 取消 task_xxx")
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.cancel_job, command_context_from_event(event), task_id.strip())
|
|
|
|
|
|
yield event.plain_result(f"✅ 任务已取消:{result.get('task_id', task_id)}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 取消失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_command.command("重试")
|
|
|
|
|
|
async def imagestudio_retry_job(self, event: AstrMessageEvent, task_id: str = ""):
|
|
|
|
|
|
if not task_id.strip():
|
|
|
|
|
|
yield event.plain_result("请提供任务 ID,例如:/yp 重试 task_xxx")
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.retry_job, command_context_from_event(event), task_id.strip())
|
|
|
|
|
|
yield event.plain_result(f"✅ 已创建重试任务:{result.get('task_id', task_id)}")
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
yield event.plain_result(f"❌ 重试失败:{exc}")
|
|
|
|
|
|
|
|
|
|
|
|
async def _chat_command_result(self, event: AstrMessageEvent, action: str, label: str, argument: str):
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
config = _database_db_helper.load_config_payload()
|
|
|
|
|
|
if not command_allowed(config, action, context):
|
|
|
|
|
|
yield event.plain_result(access_denied_text(label, context))
|
|
|
|
|
|
return
|
|
|
|
|
|
yield event.plain_result(accepted_text(label, argument, context))
|
|
|
|
|
|
|
|
|
|
|
|
@astrbot_filter.event_message_type(astrbot_filter.EventMessageType.ALL)
|
|
|
|
|
|
async def imagestudio_session_reply(self, event: AstrMessageEvent):
|
|
|
|
|
|
text = message_text_from_event(event)
|
|
|
|
|
|
if not text or text.startswith(("/", "!", "!")):
|
|
|
|
|
|
return
|
|
|
|
|
|
context = command_context_from_event(event)
|
|
|
|
|
|
session = self.chat_sessions.get(self._session_key(context))
|
|
|
|
|
|
if session is None:
|
|
|
|
|
|
return
|
|
|
|
|
|
normalized = text.strip().lower()
|
|
|
|
|
|
if normalized in {"取消", "退出", "放弃", "cancel"}:
|
|
|
|
|
|
self.chat_sessions.pop(self._session_key(context))
|
|
|
|
|
|
yield event.plain_result("已取消当前 ImageStudio 会话。")
|
|
|
|
|
|
return
|
|
|
|
|
|
if normalized in {"确认", "保存", "confirm"}:
|
|
|
|
|
|
async for result in self.imagestudio_confirm(event):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
return
|
|
|
|
|
|
if session.action == "select_image" and normalized.isdigit():
|
|
|
|
|
|
async for result in self.imagestudio_choose_candidate(event, normalized):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
return
|
|
|
|
|
|
if session.action == "quick_profile_ready" and normalized in {"生成", "开始", "generate"}:
|
|
|
|
|
|
self.chat_sessions.pop(self._session_key(context))
|
|
|
|
|
|
async for result in self.imagestudio_generate_node(event, session.payload["node_id"]):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@astrbot_filter.command_group("yp")
|
|
|
|
|
|
def imagestudio_short_command(self) -> None:
|
|
|
|
|
|
"""Short alias for the ImageStudio command group."""
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("帮助")
|
|
|
|
|
|
async def imagestudio_short_help(self, event: AstrMessageEvent):
|
|
|
|
|
|
async for result in self.imagestudio_help(event):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("状态")
|
|
|
|
|
|
async def imagestudio_short_status(self, event: AstrMessageEvent):
|
|
|
|
|
|
async for result in self.imagestudio_status(event):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("快速角色")
|
|
|
|
|
|
async def imagestudio_short_quick_profile(self, event: AstrMessageEvent, description: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_quick_profile(event, description):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("工作流")
|
|
|
|
|
|
async def imagestudio_short_workflow(self, event: AstrMessageEvent, profile: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_workflow(event, profile):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("单图")
|
|
|
|
|
|
async def imagestudio_short_single_image(self, event: AstrMessageEvent, prompt: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_single_image(event, prompt):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("任务")
|
|
|
|
|
|
async def imagestudio_short_jobs(self, event: AstrMessageEvent, task_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_jobs(event, task_id):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("取消")
|
|
|
|
|
|
async def imagestudio_short_cancel_job(self, event: AstrMessageEvent, task_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_cancel_job(event, task_id):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("重试")
|
|
|
|
|
|
async def imagestudio_short_retry_job(self, event: AstrMessageEvent, task_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_retry_job(event, task_id):
|
|
|
|
|
|
yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("确认")
|
|
|
|
|
|
async def imagestudio_short_confirm(self, event: AstrMessageEvent):
|
|
|
|
|
|
async for result in self.imagestudio_confirm(event): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("放弃")
|
|
|
|
|
|
async def imagestudio_short_discard(self, event: AstrMessageEvent):
|
|
|
|
|
|
async for result in self.imagestudio_discard(event): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("修改")
|
|
|
|
|
|
async def imagestudio_short_modify_draft(self, event: AstrMessageEvent, addition: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_modify_draft(event, addition): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("节点")
|
|
|
|
|
|
async def imagestudio_short_nodes(self, event: AstrMessageEvent, workflow_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_nodes(event, workflow_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("生成")
|
|
|
|
|
|
async def imagestudio_short_generate_node(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_generate_node(event, node_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("重试节点")
|
|
|
|
|
|
async def imagestudio_short_retry_node(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_retry_node(event, node_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("完成节点")
|
|
|
|
|
|
async def imagestudio_short_complete_node(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_complete_node(event, node_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("下一步")
|
|
|
|
|
|
async def imagestudio_short_next_step(self, event: AstrMessageEvent, workflow_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_next_step(event, workflow_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("选图")
|
|
|
|
|
|
async def imagestudio_short_select_image(self, event: AstrMessageEvent, node_id: str = "", image_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_select_image(event, node_id, image_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("审核")
|
|
|
|
|
|
async def imagestudio_short_review(self, event: AstrMessageEvent, target_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_review(event, target_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("高清")
|
|
|
|
|
|
async def imagestudio_short_hires(self, event: AstrMessageEvent, image_id: str = "", size: str = "2K"):
|
|
|
|
|
|
async for result in self.imagestudio_hires(event, image_id, size): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("素材导入")
|
|
|
|
|
|
async def imagestudio_short_import_material(self, event: AstrMessageEvent, category: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_import_material(event, category): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("重新识别")
|
|
|
|
|
|
async def imagestudio_short_re_recognize_material(self, event: AstrMessageEvent, material_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_re_recognize_material(event, material_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("加入衣橱")
|
|
|
|
|
|
async def imagestudio_short_add_wardrobe(self, event: AstrMessageEvent, material_id: str = "", profile: str = "", category: str = "top"):
|
|
|
|
|
|
async for result in self.imagestudio_add_wardrobe(event, material_id, profile, category): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("候选图")
|
|
|
|
|
|
async def imagestudio_short_candidate_images(self, event: AstrMessageEvent, node_id: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_candidate_images(event, node_id): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@imagestudio_short_command.command("选择")
|
|
|
|
|
|
async def imagestudio_short_choose_candidate(self, event: AstrMessageEvent, number: str = ""):
|
|
|
|
|
|
async for result in self.imagestudio_choose_candidate(event, number): yield result
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _format_jobs(result: Any) -> str:
|
|
|
|
|
|
if isinstance(result, dict) and "task_id" in result:
|
|
|
|
|
|
request = result.get("request") if isinstance(result.get("request"), dict) else {}
|
|
|
|
|
|
return (
|
|
|
|
|
|
f"📋 任务 {result['task_id']}\n状态:{result.get('status', 'unknown')}\n"
|
|
|
|
|
|
f"进度:{result.get('progress', 0)}%\n模型:{result.get('model_route') or '—'}\n"
|
|
|
|
|
|
f"尺寸:{request.get('size') or '—'}\n数量:{request.get('count') or '—'}\n"
|
|
|
|
|
|
f"节点:{result.get('node_id') or '—'}\n创建:{result.get('created_at') or '—'}"
|
|
|
|
|
|
)
|
|
|
|
|
|
items = result.get("items", []) if isinstance(result, dict) else result if isinstance(result, list) else []
|
|
|
|
|
|
if not items:
|
|
|
|
|
|
return "当前没有任务。"
|
|
|
|
|
|
lines = ["📋 最近任务"]
|
|
|
|
|
|
for item in items[:10]:
|
|
|
|
|
|
request = item.get("request") if isinstance(item.get("request"), dict) else {}
|
|
|
|
|
|
lines.append(f"• {item.get('task_id')} · {item.get('status')} · {item.get('progress', 0)}% · {request.get('size') or '默认尺寸'} · {item.get('model_route') or '默认模型'}")
|
|
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _session_key(context: Any) -> str:
|
|
|
|
|
|
return f"{context.platform}:{context.message_origin}:{context.user_id}"
|
|
|
|
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
|
def _format_workflow(detail: dict[str, Any]) -> str:
|
|
|
|
|
|
workflow = detail.get("workflow", detail)
|
|
|
|
|
|
nodes = detail.get("nodes", [])
|
|
|
|
|
|
lines = [f"📋 {detail.get('profile', {}).get('name', '角色')} 工作流", f"ID:{workflow.get('workflow_id')}", f"状态:{workflow.get('status')}"]
|
|
|
|
|
|
for node in nodes:
|
|
|
|
|
|
marker = "▶" if node.get("node_id") == workflow.get("current_node_id") else "✅" if node.get("status") == "completed" else "○"
|
|
|
|
|
|
lines.append(f"{marker} {node.get('display_name') or node.get('node_key')} · {node.get('status')}")
|
|
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
|
|
|
|
|
|
def _help_card(self) -> Path:
|
|
|
|
|
|
return render_help_card([
|
|
|
|
|
|
"/影棚 帮助 /yp 帮助",
|
|
|
|
|
|
"/影棚 状态 /yp 状态",
|
|
|
|
|
|
"/影棚 快速角色 <角色描述>",
|
|
|
|
|
|
"/影棚 工作流 <角色名或 ID>",
|
|
|
|
|
|
"/影棚 单图 <提示词>",
|
|
|
|
|
|
])
|
|
|
|
|
|
|
|
|
|
|
|
def _card_result(self, event: AstrMessageEvent, renderer: Callable[[], Path], fallback: str):
|
|
|
|
|
|
if AstrBotImage is not None and hasattr(event, "chain_result"):
|
|
|
|
|
|
try:
|
|
|
|
|
|
return event.chain_result([AstrBotImage.fromFileSystem(str(renderer()))])
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
return event.plain_result(fallback)
|
|
|
|
|
|
|
|
|
|
|
|
def _generation_result(self, event: AstrMessageEvent, text: str, images: list[dict[str, Any]]):
|
|
|
|
|
|
if AstrBotImage is not None and AstrBotPlain is not None and hasattr(event, "chain_result"):
|
|
|
|
|
|
try:
|
|
|
|
|
|
chain: list[Any] = [AstrBotPlain(text)]
|
|
|
|
|
|
for index, item in enumerate(images, 1):
|
|
|
|
|
|
url = item.get("image_url") or item.get("thumbnail_url")
|
|
|
|
|
|
if url:
|
|
|
|
|
|
chain.extend([AstrBotPlain(f"\n候选图 {index}\n"), AstrBotImage.fromURL(str(url))])
|
|
|
|
|
|
if len(chain) > 1:
|
|
|
|
|
|
return event.chain_result(chain)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
suffix = "".join(
|
|
|
|
|
|
f"\n候选图 {index}:{item.get('image_url') or item.get('image_id')}"
|
|
|
|
|
|
for index, item in enumerate(images, 1)
|
|
|
|
|
|
)
|
|
|
|
|
|
return event.plain_result(text + suffix)
|
|
|
|
|
|
|
|
|
|
|
|
async def _run_single_image_background(self, command: Any, context: Any, request_id: str) -> None:
|
|
|
|
|
|
try:
|
|
|
|
|
|
result = await asyncio.to_thread(self.chat_workflow_service.submit_single_image, command, context)
|
|
|
|
|
|
generation = result["generation"]
|
|
|
|
|
|
text = (
|
|
|
|
|
|
f"✅ 单图生成完成\n请求:{request_id}\n任务:{generation.get('task_id') or '—'}\n"
|
|
|
|
|
|
f"工作流:{result['workflow']['workflow_id']}\n节点:{result['node']['node_id']}"
|
|
|
|
|
|
)
|
|
|
|
|
|
await self._send_proactive(context.message_origin, text, result.get("images", []))
|
|
|
|
|
|
except asyncio.CancelledError:
|
|
|
|
|
|
raise
|
|
|
|
|
|
except Exception as exc:
|
|
|
|
|
|
await self._send_proactive(context.message_origin, f"❌ 单图生成失败\n请求:{request_id}\n错误:{exc}", [])
|
|
|
|
|
|
|
|
|
|
|
|
async def _send_proactive(self, message_origin: str, text: str, images: list[dict[str, Any]]) -> None:
|
|
|
|
|
|
sender = getattr(self.context, "send_message", None)
|
|
|
|
|
|
if not callable(sender) or not message_origin:
|
|
|
|
|
|
return
|
|
|
|
|
|
try:
|
|
|
|
|
|
components: list[Any] = []
|
|
|
|
|
|
if AstrBotPlain is not None:
|
|
|
|
|
|
components.append(AstrBotPlain(text))
|
|
|
|
|
|
for index, item in enumerate(images, 1):
|
|
|
|
|
|
url = item.get("image_url") or item.get("thumbnail_url")
|
|
|
|
|
|
if url and AstrBotImage is not None:
|
|
|
|
|
|
if AstrBotPlain is not None:
|
|
|
|
|
|
components.append(AstrBotPlain(f"\n候选图 {index}\n"))
|
|
|
|
|
|
components.append(AstrBotImage.fromURL(str(url)))
|
|
|
|
|
|
message = AstrBotMessageChain(components) if AstrBotMessageChain is not None else components
|
|
|
|
|
|
result = sender(message_origin, message)
|
|
|
|
|
|
if inspect.isawaitable(result):
|
|
|
|
|
|
await result
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
|
|
|
|
|
def _record_chat_denied(self, context: Any, action: str) -> None:
|
|
|
|
|
|
try:
|
|
|
|
|
|
self.chat_workflow_service.guard.record(context, action, allowed=False, details={"reason": "allowlist"})
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return
|
|
|
|
|
|
|
2026-07-06 09:26:29 +08:00
|
|
|
|
def get_plugin_manifest(self) -> dict[str, Any]:
|
|
|
|
|
|
return get_plugin_manifest()
|
|
|
|
|
|
|
|
|
|
|
|
def register_plugin(self, runtime: Any) -> dict[str, Any]:
|
|
|
|
|
|
return register_plugin(runtime)
|
2026-07-06 10:00:18 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _bridge_registration_routes() -> list[dict[str, str]]:
|
2026-07-11 21:50:34 +08:00
|
|
|
|
path = f"/{PLUGIN_NAME}/<path:endpoint>"
|
|
|
|
|
|
return [
|
|
|
|
|
|
{"method": method, "path": path, "endpoint": ""}
|
|
|
|
|
|
for method in sorted({route.method for route in ROUTES})
|
|
|
|
|
|
]
|
2026-07-06 10:00:18 +08:00
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:59:28 +08:00
|
|
|
|
def _mapping_from_runtime_config(config: Any | None) -> dict[str, Any]:
|
|
|
|
|
|
if config is None:
|
|
|
|
|
|
return {}
|
|
|
|
|
|
mapping = _mapping_from_any(config)
|
|
|
|
|
|
if mapping:
|
|
|
|
|
|
return mapping
|
|
|
|
|
|
for method_name in ("to_dict", "dict", "model_dump"):
|
|
|
|
|
|
method = getattr(config, method_name, None)
|
|
|
|
|
|
if not callable(method):
|
|
|
|
|
|
continue
|
|
|
|
|
|
try:
|
|
|
|
|
|
mapping = _mapping_from_any(method())
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
mapping = {}
|
|
|
|
|
|
if mapping:
|
|
|
|
|
|
return mapping
|
|
|
|
|
|
for attr_name in ("config", "data", "_config", "_data"):
|
|
|
|
|
|
mapping = _mapping_from_any(_attr(config, attr_name))
|
|
|
|
|
|
if mapping:
|
|
|
|
|
|
return mapping
|
|
|
|
|
|
|
|
|
|
|
|
known_keys = (
|
|
|
|
|
|
"default_generation_model",
|
2026-07-11 21:50:34 +08:00
|
|
|
|
"generation_provider_id",
|
|
|
|
|
|
"generation_provider_base_url",
|
|
|
|
|
|
"generation_provider_image_endpoint",
|
|
|
|
|
|
"generation_provider_model",
|
|
|
|
|
|
"generation_provider_route",
|
|
|
|
|
|
"generation_provider_api_key_env_var",
|
|
|
|
|
|
"generation_provider_timeout_seconds",
|
|
|
|
|
|
"vision_provider_id",
|
|
|
|
|
|
"vision_provider_base_url",
|
|
|
|
|
|
"vision_provider_endpoint",
|
|
|
|
|
|
"vision_provider_model",
|
|
|
|
|
|
"vision_provider_route",
|
|
|
|
|
|
"vision_provider_api_key_env_var",
|
|
|
|
|
|
"vision_provider_timeout_seconds",
|
|
|
|
|
|
"vision_provider_enabled",
|
2026-07-11 23:48:36 +08:00
|
|
|
|
"model_material_recognition",
|
|
|
|
|
|
"model_profile_parse",
|
|
|
|
|
|
"model_persona_split",
|
|
|
|
|
|
"model_prompt_planning",
|
|
|
|
|
|
"model_cross_review_primary",
|
|
|
|
|
|
"model_cross_review_secondary",
|
|
|
|
|
|
"model_quick_generation",
|
|
|
|
|
|
"model_portrait_generation",
|
|
|
|
|
|
"model_halfbody_generation",
|
|
|
|
|
|
"model_fullbody_generation",
|
|
|
|
|
|
"model_sheet_generation",
|
|
|
|
|
|
"model_hires_fix",
|
2026-07-12 00:59:06 +08:00
|
|
|
|
"chat_group_allowlist",
|
|
|
|
|
|
"chat_user_allowlist",
|
|
|
|
|
|
"chat_user_concurrency_limit",
|
|
|
|
|
|
"chat_group_concurrency_limit",
|
|
|
|
|
|
"chat_daily_user_generation_limit",
|
|
|
|
|
|
"chat_daily_group_generation_limit",
|
|
|
|
|
|
"chat_allow_2k",
|
|
|
|
|
|
"chat_allow_4k",
|
2026-07-06 10:59:28 +08:00
|
|
|
|
"enable_private_companion_integration",
|
|
|
|
|
|
"database_backend",
|
|
|
|
|
|
"sqlite_path",
|
|
|
|
|
|
"postgresql_enabled",
|
|
|
|
|
|
"postgresql_dsn",
|
|
|
|
|
|
"postgresql_host",
|
|
|
|
|
|
"postgresql_port",
|
|
|
|
|
|
"postgresql_database",
|
|
|
|
|
|
"postgresql_user",
|
|
|
|
|
|
"postgresql_password",
|
|
|
|
|
|
)
|
|
|
|
|
|
getter = getattr(config, "get", None)
|
|
|
|
|
|
if not callable(getter):
|
|
|
|
|
|
return {}
|
|
|
|
|
|
values: dict[str, Any] = {}
|
|
|
|
|
|
for key in known_keys:
|
|
|
|
|
|
try:
|
|
|
|
|
|
value = getter(key, _MISSING)
|
|
|
|
|
|
except TypeError:
|
|
|
|
|
|
try:
|
|
|
|
|
|
value = getter(key)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
value = _MISSING
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
value = _MISSING
|
|
|
|
|
|
if value is not _MISSING:
|
|
|
|
|
|
values[key] = value
|
|
|
|
|
|
return values
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 11:20:56 +08:00
|
|
|
|
def _set_runtime_config_overrides(patch: Mapping[str, Any]) -> None:
|
|
|
|
|
|
setter = getattr(_database_db_helper, "set_runtime_config_overrides", None)
|
|
|
|
|
|
if callable(setter):
|
|
|
|
|
|
setter(patch)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:59:28 +08:00
|
|
|
|
def _runtime_config_argument(args: tuple[Any, ...], kwargs: Mapping[str, Any]) -> Any | None:
|
|
|
|
|
|
if "config" in kwargs and kwargs["config"] is not None:
|
|
|
|
|
|
return kwargs["config"]
|
|
|
|
|
|
if "plugin_config" in kwargs and kwargs["plugin_config"] is not None:
|
|
|
|
|
|
return kwargs["plugin_config"]
|
|
|
|
|
|
return args[0] if args else None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _runtime_config_patch_from_mapping(mapping: Mapping[str, Any]) -> dict[str, Any]:
|
|
|
|
|
|
patch: dict[str, Any] = {}
|
|
|
|
|
|
if not mapping:
|
|
|
|
|
|
return patch
|
|
|
|
|
|
|
|
|
|
|
|
database = _mapping_from_any(mapping.get("database"))
|
|
|
|
|
|
sqlite = _mapping_from_any(database.get("sqlite")) if database else {}
|
|
|
|
|
|
postgresql = _mapping_from_any(database.get("postgresql")) if database else {}
|
|
|
|
|
|
features = _mapping_from_any(mapping.get("features"))
|
|
|
|
|
|
plugin = _mapping_from_any(mapping.get("plugin"))
|
2026-07-11 21:50:34 +08:00
|
|
|
|
vision = _mapping_from_any(mapping.get("vision"))
|
|
|
|
|
|
vision_provider_config = _mapping_from_any(vision.get("provider")) if vision else {}
|
2026-07-06 10:59:28 +08:00
|
|
|
|
|
|
|
|
|
|
display_name = _runtime_text(_runtime_value(mapping, "display_name", fallback=plugin.get("display_name", _MISSING)))
|
|
|
|
|
|
if display_name:
|
|
|
|
|
|
_set_nested(patch, ("plugin", "display_name"), display_name)
|
|
|
|
|
|
|
|
|
|
|
|
default_model = _runtime_text(_runtime_value(mapping, "default_generation_model"))
|
|
|
|
|
|
if default_model:
|
|
|
|
|
|
_set_nested(patch, ("generation", "default_model"), default_model)
|
|
|
|
|
|
|
2026-07-11 21:50:34 +08:00
|
|
|
|
generation_provider_fields = {
|
|
|
|
|
|
"provider_id": "generation_provider_id",
|
|
|
|
|
|
"base_url": "generation_provider_base_url",
|
|
|
|
|
|
"image_endpoint": "generation_provider_image_endpoint",
|
|
|
|
|
|
"model_id": "generation_provider_model",
|
|
|
|
|
|
"route_name": "generation_provider_route",
|
|
|
|
|
|
"api_key_env_var": "generation_provider_api_key_env_var",
|
|
|
|
|
|
}
|
|
|
|
|
|
generation_provider: dict[str, Any] = {}
|
|
|
|
|
|
for target_key, source_key in generation_provider_fields.items():
|
|
|
|
|
|
value = _runtime_text(_runtime_value(mapping, source_key))
|
|
|
|
|
|
if value:
|
|
|
|
|
|
generation_provider[target_key] = value
|
|
|
|
|
|
timeout = _runtime_text(_runtime_value(mapping, "generation_provider_timeout_seconds"))
|
|
|
|
|
|
if timeout:
|
|
|
|
|
|
try:
|
|
|
|
|
|
generation_provider["timeout_seconds"] = int(timeout)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
generation_provider["timeout_seconds"] = timeout
|
|
|
|
|
|
if generation_provider:
|
|
|
|
|
|
_set_nested(patch, ("generation", "provider"), generation_provider)
|
|
|
|
|
|
|
|
|
|
|
|
vision_route = _runtime_text(
|
|
|
|
|
|
_runtime_value(
|
|
|
|
|
|
mapping,
|
|
|
|
|
|
"vision_provider_route",
|
|
|
|
|
|
fallback=vision_provider_config.get("route_name", vision.get("default_route", _MISSING)),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
if vision_route:
|
|
|
|
|
|
_set_nested(patch, ("vision", "default_route"), vision_route)
|
|
|
|
|
|
|
|
|
|
|
|
vision_provider_fields = {
|
|
|
|
|
|
"provider_id": "vision_provider_id",
|
|
|
|
|
|
"base_url": "vision_provider_base_url",
|
|
|
|
|
|
"vision_endpoint": "vision_provider_endpoint",
|
|
|
|
|
|
"model_id": "vision_provider_model",
|
|
|
|
|
|
"route_name": "vision_provider_route",
|
|
|
|
|
|
"api_key_env_var": "vision_provider_api_key_env_var",
|
|
|
|
|
|
}
|
|
|
|
|
|
vision_provider: dict[str, Any] = {}
|
|
|
|
|
|
for target_key, source_key in vision_provider_fields.items():
|
|
|
|
|
|
value = _runtime_text(
|
|
|
|
|
|
_runtime_value(mapping, source_key, fallback=vision_provider_config.get(target_key, _MISSING))
|
|
|
|
|
|
)
|
|
|
|
|
|
if value:
|
|
|
|
|
|
vision_provider[target_key] = value
|
|
|
|
|
|
vision_timeout = _runtime_text(
|
|
|
|
|
|
_runtime_value(
|
|
|
|
|
|
mapping,
|
|
|
|
|
|
"vision_provider_timeout_seconds",
|
|
|
|
|
|
fallback=vision_provider_config.get("timeout_seconds", _MISSING),
|
|
|
|
|
|
)
|
|
|
|
|
|
)
|
|
|
|
|
|
if vision_timeout:
|
|
|
|
|
|
try:
|
|
|
|
|
|
vision_provider["timeout_seconds"] = int(vision_timeout)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
vision_provider["timeout_seconds"] = vision_timeout
|
|
|
|
|
|
vision_enabled = _runtime_value(
|
|
|
|
|
|
mapping,
|
|
|
|
|
|
"vision_provider_enabled",
|
|
|
|
|
|
fallback=vision_provider_config.get("enabled", _MISSING),
|
|
|
|
|
|
)
|
|
|
|
|
|
if vision_enabled is not _MISSING:
|
|
|
|
|
|
vision_provider["enabled"] = _runtime_bool(vision_enabled)
|
|
|
|
|
|
if vision_provider:
|
|
|
|
|
|
_set_nested(patch, ("vision", "provider"), vision_provider)
|
|
|
|
|
|
|
2026-07-11 23:48:36 +08:00
|
|
|
|
assignment_fields = {
|
|
|
|
|
|
"material_recognition": "model_material_recognition",
|
|
|
|
|
|
"profile_parse": "model_profile_parse",
|
|
|
|
|
|
"persona_split": "model_persona_split",
|
|
|
|
|
|
"prompt_planning": "model_prompt_planning",
|
|
|
|
|
|
"cross_review_primary": "model_cross_review_primary",
|
|
|
|
|
|
"cross_review_secondary": "model_cross_review_secondary",
|
|
|
|
|
|
"quick_generation": "model_quick_generation",
|
|
|
|
|
|
"portrait_generation": "model_portrait_generation",
|
|
|
|
|
|
"halfbody_generation": "model_halfbody_generation",
|
|
|
|
|
|
"fullbody_generation": "model_fullbody_generation",
|
|
|
|
|
|
"sheet_generation": "model_sheet_generation",
|
|
|
|
|
|
"hires_fix": "model_hires_fix",
|
|
|
|
|
|
}
|
|
|
|
|
|
for target_key, source_key in assignment_fields.items():
|
|
|
|
|
|
value = _runtime_text(_runtime_value(mapping, source_key))
|
|
|
|
|
|
if value:
|
|
|
|
|
|
_set_nested(patch, ("model_assignments", target_key), value)
|
|
|
|
|
|
|
2026-07-12 00:59:06 +08:00
|
|
|
|
for target_key, source_key in {
|
|
|
|
|
|
"group_allowlist": "chat_group_allowlist",
|
|
|
|
|
|
"user_allowlist": "chat_user_allowlist",
|
|
|
|
|
|
}.items():
|
|
|
|
|
|
value = _runtime_value(mapping, source_key)
|
|
|
|
|
|
if isinstance(value, (list, tuple, set, frozenset)):
|
|
|
|
|
|
_set_nested(patch, ("chat_access", target_key), [str(item).strip() for item in value if str(item).strip()])
|
|
|
|
|
|
for target_key, source_key in {
|
|
|
|
|
|
"user_concurrency_limit": "chat_user_concurrency_limit",
|
|
|
|
|
|
"group_concurrency_limit": "chat_group_concurrency_limit",
|
|
|
|
|
|
"daily_user_generation_limit": "chat_daily_user_generation_limit",
|
|
|
|
|
|
"daily_group_generation_limit": "chat_daily_group_generation_limit",
|
|
|
|
|
|
"allow_2k": "chat_allow_2k",
|
|
|
|
|
|
"allow_4k": "chat_allow_4k",
|
|
|
|
|
|
}.items():
|
|
|
|
|
|
value = _runtime_value(mapping, source_key)
|
|
|
|
|
|
if value is not None:
|
|
|
|
|
|
_set_nested(patch, ("chat_access", target_key), value)
|
|
|
|
|
|
|
2026-07-06 10:59:28 +08:00
|
|
|
|
private_companion = _runtime_value(
|
|
|
|
|
|
mapping,
|
|
|
|
|
|
"enable_private_companion_integration",
|
|
|
|
|
|
fallback=features.get("private_companion_integration", _MISSING),
|
|
|
|
|
|
)
|
|
|
|
|
|
if private_companion is not _MISSING:
|
|
|
|
|
|
_set_nested(patch, ("features", "private_companion_integration"), _runtime_bool(private_companion))
|
|
|
|
|
|
|
|
|
|
|
|
backend = _runtime_text(_runtime_value(mapping, "database_backend", fallback=database.get("backend", _MISSING))).lower()
|
|
|
|
|
|
if backend:
|
|
|
|
|
|
_set_nested(patch, ("database", "backend"), backend)
|
|
|
|
|
|
|
|
|
|
|
|
sqlite_path = _runtime_text(_runtime_value(mapping, "sqlite_path", fallback=sqlite.get("path", _MISSING)))
|
|
|
|
|
|
if sqlite_path:
|
|
|
|
|
|
_set_nested(patch, ("database", "sqlite", "path"), sqlite_path)
|
|
|
|
|
|
|
|
|
|
|
|
pg_patch: dict[str, Any] = {}
|
|
|
|
|
|
pg_enabled = _runtime_value(mapping, "postgresql_enabled", fallback=postgresql.get("enabled", _MISSING))
|
|
|
|
|
|
if pg_enabled is not _MISSING and (_runtime_bool(pg_enabled) or backend == "sqlite"):
|
|
|
|
|
|
pg_patch["enabled"] = _runtime_bool(pg_enabled)
|
|
|
|
|
|
elif backend in {"postgresql", "postgres", "pg"}:
|
|
|
|
|
|
pg_patch["enabled"] = True
|
|
|
|
|
|
|
|
|
|
|
|
pg_text_fields = {
|
|
|
|
|
|
"dsn": ("postgresql_dsn", "dsn"),
|
|
|
|
|
|
"host": ("postgresql_host", "host"),
|
|
|
|
|
|
"database": ("postgresql_database", "database"),
|
|
|
|
|
|
"user": ("postgresql_user", "user"),
|
|
|
|
|
|
"password": ("postgresql_password", "password"),
|
|
|
|
|
|
}
|
|
|
|
|
|
for target_key, (flat_key, nested_key) in pg_text_fields.items():
|
|
|
|
|
|
value = _runtime_text(_runtime_value(mapping, flat_key, fallback=postgresql.get(nested_key, _MISSING)))
|
|
|
|
|
|
if value:
|
|
|
|
|
|
pg_patch[target_key] = value
|
|
|
|
|
|
|
|
|
|
|
|
pg_port = _runtime_text(_runtime_value(mapping, "postgresql_port", fallback=postgresql.get("port", _MISSING)))
|
|
|
|
|
|
if pg_port:
|
|
|
|
|
|
try:
|
|
|
|
|
|
pg_patch["port"] = int(pg_port)
|
|
|
|
|
|
except ValueError:
|
|
|
|
|
|
pg_patch["port"] = pg_port
|
|
|
|
|
|
|
|
|
|
|
|
has_connection_fields = any(key in pg_patch for key in ("dsn", "host", "database", "user", "password"))
|
|
|
|
|
|
if has_connection_fields and backend != "sqlite" and "enabled" not in pg_patch:
|
|
|
|
|
|
pg_patch["enabled"] = True
|
|
|
|
|
|
if pg_patch:
|
|
|
|
|
|
_set_nested(patch, ("database", "postgresql"), pg_patch)
|
|
|
|
|
|
return patch
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _runtime_value(mapping: Mapping[str, Any], key: str, *, fallback: Any = _MISSING) -> Any:
|
|
|
|
|
|
if key in mapping:
|
|
|
|
|
|
return mapping[key]
|
|
|
|
|
|
return fallback
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _runtime_text(value: Any) -> str:
|
|
|
|
|
|
if value is _MISSING or value is None:
|
|
|
|
|
|
return ""
|
|
|
|
|
|
return str(value).strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _runtime_bool(value: Any) -> bool:
|
|
|
|
|
|
if isinstance(value, bool):
|
|
|
|
|
|
return value
|
|
|
|
|
|
if isinstance(value, str):
|
|
|
|
|
|
return value.strip().lower() in {"1", "true", "yes", "on", "enabled", "启用", "是"}
|
|
|
|
|
|
return bool(value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _set_nested(target: dict[str, Any], path: tuple[str, ...], value: Any) -> None:
|
|
|
|
|
|
current = target
|
|
|
|
|
|
for key in path[:-1]:
|
|
|
|
|
|
child = current.get(key)
|
|
|
|
|
|
if not isinstance(child, dict):
|
|
|
|
|
|
child = {}
|
|
|
|
|
|
current[key] = child
|
|
|
|
|
|
current = child
|
|
|
|
|
|
current[path[-1]] = value
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _flatten_config_keys(value: Mapping[str, Any], prefix: str = "") -> list[str]:
|
|
|
|
|
|
keys: list[str] = []
|
|
|
|
|
|
for key, child in value.items():
|
|
|
|
|
|
path = f"{prefix}.{key}" if prefix else str(key)
|
|
|
|
|
|
if isinstance(child, Mapping):
|
|
|
|
|
|
keys.extend(_flatten_config_keys(child, path))
|
|
|
|
|
|
else:
|
|
|
|
|
|
keys.append(path)
|
|
|
|
|
|
return sorted(keys)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:00:18 +08:00
|
|
|
|
def _call_web_api_registrar(registrar: Callable[..., Any], path: str, handler: Callable[..., Any], method: str) -> bool:
|
|
|
|
|
|
methods = [method]
|
2026-07-06 10:11:30 +08:00
|
|
|
|
desc = f"ImageStudio {method} {path}"
|
2026-07-06 10:00:18 +08:00
|
|
|
|
attempts = (
|
2026-07-06 10:11:30 +08:00
|
|
|
|
lambda: registrar(route=path, view_handler=handler, methods=methods, desc=desc),
|
|
|
|
|
|
lambda: registrar(route=path, view_handler=handler, methods=methods),
|
2026-07-06 10:00:18 +08:00
|
|
|
|
lambda: registrar(path=path, handler=handler, methods=methods),
|
2026-07-06 10:11:30 +08:00
|
|
|
|
lambda: registrar(path=path, handler=handler, methods=methods, desc=desc),
|
2026-07-06 10:00:18 +08:00
|
|
|
|
lambda: registrar(path=path, handler=handler, method=method),
|
|
|
|
|
|
lambda: registrar(endpoint=path, handler=handler, methods=methods),
|
2026-07-06 10:11:30 +08:00
|
|
|
|
lambda: registrar(path, handler, methods, desc),
|
2026-07-06 10:00:18 +08:00
|
|
|
|
lambda: registrar(path, handler, methods=methods),
|
2026-07-06 10:11:30 +08:00
|
|
|
|
lambda: registrar(path, handler, methods=methods, desc=desc),
|
2026-07-06 10:00:18 +08:00
|
|
|
|
lambda: registrar(path, handler, method=method),
|
|
|
|
|
|
lambda: registrar(path, methods, handler),
|
|
|
|
|
|
lambda: registrar(path, method, handler),
|
|
|
|
|
|
lambda: registrar(path, handler),
|
|
|
|
|
|
)
|
|
|
|
|
|
last_error: TypeError | None = None
|
|
|
|
|
|
for attempt in attempts:
|
|
|
|
|
|
try:
|
|
|
|
|
|
attempt()
|
|
|
|
|
|
return True
|
|
|
|
|
|
except TypeError as exc:
|
|
|
|
|
|
last_error = exc
|
|
|
|
|
|
if last_error is not None:
|
|
|
|
|
|
raise last_error
|
|
|
|
|
|
return False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _make_bridge_handler(endpoint: str, method: str) -> Callable[..., Any]:
|
2026-07-11 21:50:34 +08:00
|
|
|
|
async def handler(request: Any | None = None, **kwargs: Any) -> Any:
|
2026-07-06 10:00:18 +08:00
|
|
|
|
positional_endpoint = request if isinstance(request, str) else None
|
|
|
|
|
|
actual_request = None if positional_endpoint is not None else request or kwargs.get("request")
|
2026-07-06 10:11:30 +08:00
|
|
|
|
actual_request = actual_request or _current_astrbot_web_request()
|
2026-07-06 10:00:18 +08:00
|
|
|
|
actual_endpoint = endpoint or _first_text(
|
|
|
|
|
|
positional_endpoint,
|
|
|
|
|
|
kwargs.get("endpoint"),
|
|
|
|
|
|
kwargs.get("path"),
|
|
|
|
|
|
kwargs.get("route_path"),
|
|
|
|
|
|
kwargs.get("wildcard"),
|
|
|
|
|
|
)
|
|
|
|
|
|
actual_query = _mapping_from_any(kwargs.get("query") or kwargs.get("params"))
|
|
|
|
|
|
actual_payload = _mapping_from_any(kwargs.get("payload") or kwargs.get("body") or kwargs.get("data"))
|
|
|
|
|
|
return await dispatch_bridge_request(
|
|
|
|
|
|
actual_endpoint,
|
|
|
|
|
|
method=method,
|
|
|
|
|
|
request=actual_request,
|
|
|
|
|
|
query=actual_query or None,
|
|
|
|
|
|
payload=actual_payload or None,
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
return handler
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:11:30 +08:00
|
|
|
|
def _current_astrbot_web_request() -> Any | None:
|
|
|
|
|
|
try:
|
|
|
|
|
|
from astrbot.api.web import request as astrbot_web_request
|
|
|
|
|
|
except Exception:
|
2026-07-11 21:50:34 +08:00
|
|
|
|
astrbot_web_request = None
|
|
|
|
|
|
if astrbot_web_request is not None:
|
|
|
|
|
|
try:
|
|
|
|
|
|
getattr(astrbot_web_request, "method")
|
|
|
|
|
|
return astrbot_web_request
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
2026-07-06 10:11:30 +08:00
|
|
|
|
try:
|
2026-07-11 21:50:34 +08:00
|
|
|
|
from quart import request as quart_request
|
|
|
|
|
|
getattr(quart_request, "method")
|
|
|
|
|
|
return quart_request
|
2026-07-06 10:11:30 +08:00
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:00:18 +08:00
|
|
|
|
def _request_context_from_astrbot_request(request: Any | None) -> RequestContext:
|
|
|
|
|
|
username = _first_text(
|
2026-07-11 21:50:34 +08:00
|
|
|
|
_attr(request, "username"),
|
|
|
|
|
|
_current_quart_username(),
|
|
|
|
|
|
) or None
|
2026-07-06 10:00:18 +08:00
|
|
|
|
user_id = _first_text(
|
2026-07-11 21:50:34 +08:00
|
|
|
|
_attr(request, "user_id"),
|
2026-07-06 10:00:18 +08:00
|
|
|
|
username,
|
2026-07-11 21:50:34 +08:00
|
|
|
|
) or None
|
|
|
|
|
|
# AstrBot authenticates extension routes before invoking the plugin, but
|
|
|
|
|
|
# PluginRequest currently exposes only the authenticated username. Grant
|
|
|
|
|
|
# the capabilities that exist today explicitly instead of a wildcard so a
|
|
|
|
|
|
# future permission cannot become enabled accidentally.
|
|
|
|
|
|
permissions = BRIDGE_PERMISSIONS if username or user_id else frozenset()
|
2026-07-06 10:00:18 +08:00
|
|
|
|
return RequestContext.from_astrbot(
|
|
|
|
|
|
username=username,
|
|
|
|
|
|
user_id=user_id,
|
|
|
|
|
|
client_ip=_client_ip(request),
|
|
|
|
|
|
source="astrbot_plugin_page",
|
2026-07-11 21:50:34 +08:00
|
|
|
|
permissions=permissions,
|
2026-07-06 10:00:18 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _request_method(request: Any | None, *, fallback: str) -> str:
|
|
|
|
|
|
return (_first_text(_attr(request, "method"), fallback) or "GET").upper()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _bridge_endpoint(endpoint: str | None, request: Any | None) -> str:
|
|
|
|
|
|
candidate = _first_text(
|
|
|
|
|
|
endpoint,
|
|
|
|
|
|
_mapping_value(_attr(request, "path_params"), "endpoint", "path", "route_path", "wildcard"),
|
|
|
|
|
|
_mapping_value(_attr(request, "match_info"), "endpoint", "path", "route_path", "wildcard"),
|
|
|
|
|
|
_attr(request, "path"),
|
|
|
|
|
|
_nested_attr(request, "url", "path"),
|
|
|
|
|
|
_attr(request, "rel_url"),
|
|
|
|
|
|
)
|
|
|
|
|
|
normalized = str(candidate or "").split("?", 1)[0].replace("\\", "/").strip("/")
|
|
|
|
|
|
prefixes = (
|
|
|
|
|
|
f"api/plug/{PLUGIN_NAME}/",
|
|
|
|
|
|
f"api/v1/plugins/extensions/{PLUGIN_NAME}/",
|
|
|
|
|
|
f"{API_BASE.strip('/')}/",
|
|
|
|
|
|
)
|
|
|
|
|
|
for prefix in prefixes:
|
|
|
|
|
|
if normalized.startswith(prefix):
|
|
|
|
|
|
normalized = normalized[len(prefix) :]
|
|
|
|
|
|
break
|
|
|
|
|
|
return normalize_extension_path(normalized)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _request_query(request: Any | None) -> dict[str, Any]:
|
|
|
|
|
|
for candidate in (
|
|
|
|
|
|
_attr(request, "query"),
|
2026-07-11 21:50:34 +08:00
|
|
|
|
_attr(request, "query_params"),
|
2026-07-06 10:00:18 +08:00
|
|
|
|
_attr(request, "args"),
|
|
|
|
|
|
_attr(request, "GET"),
|
|
|
|
|
|
):
|
|
|
|
|
|
query = _mapping_from_any(candidate)
|
|
|
|
|
|
if query:
|
|
|
|
|
|
return query
|
|
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _request_payload(request: Any | None) -> dict[str, Any]:
|
|
|
|
|
|
if request is None or _request_method(request, fallback="GET") == "GET":
|
|
|
|
|
|
return {}
|
|
|
|
|
|
for name in ("json", "get_json"):
|
|
|
|
|
|
loader = getattr(request, name, None)
|
2026-07-11 21:50:34 +08:00
|
|
|
|
payload = _mapping_from_any(loader)
|
|
|
|
|
|
if payload:
|
|
|
|
|
|
return payload
|
2026-07-06 10:00:18 +08:00
|
|
|
|
if not callable(loader):
|
|
|
|
|
|
continue
|
|
|
|
|
|
try:
|
2026-07-11 21:50:34 +08:00
|
|
|
|
try:
|
|
|
|
|
|
loaded = loader(default={}) if name == "json" else loader(silent=True)
|
|
|
|
|
|
except TypeError:
|
|
|
|
|
|
loaded = loader()
|
2026-07-06 10:00:18 +08:00
|
|
|
|
if inspect.isawaitable(loaded):
|
|
|
|
|
|
loaded = await loaded
|
|
|
|
|
|
payload = _mapping_from_any(loaded)
|
2026-07-11 21:50:34 +08:00
|
|
|
|
return payload
|
2026-07-06 10:00:18 +08:00
|
|
|
|
except Exception:
|
|
|
|
|
|
continue
|
|
|
|
|
|
body = getattr(request, "body", None)
|
|
|
|
|
|
if callable(body):
|
|
|
|
|
|
body = body()
|
|
|
|
|
|
if inspect.isawaitable(body):
|
|
|
|
|
|
body = await body
|
|
|
|
|
|
if isinstance(body, bytes):
|
|
|
|
|
|
body = body.decode("utf-8")
|
|
|
|
|
|
if isinstance(body, str) and body.strip():
|
|
|
|
|
|
try:
|
|
|
|
|
|
return _mapping_from_any(json.loads(body))
|
|
|
|
|
|
except json.JSONDecodeError:
|
|
|
|
|
|
return {}
|
|
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-11 21:50:34 +08:00
|
|
|
|
def _unwrap_method_override(method: str, payload: dict[str, Any]) -> tuple[str, dict[str, Any]]:
|
|
|
|
|
|
normalized_method = str(method or "GET").upper()
|
|
|
|
|
|
if normalized_method != "POST":
|
|
|
|
|
|
return normalized_method, payload
|
|
|
|
|
|
override = str(payload.get("__imagestudio_method") or "").strip().upper()
|
|
|
|
|
|
if override not in {"PUT", "DELETE", "PATCH"}:
|
|
|
|
|
|
return normalized_method, payload
|
|
|
|
|
|
body = payload.get("__imagestudio_body", {})
|
|
|
|
|
|
return override, _mapping_from_any(body)
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:00:18 +08:00
|
|
|
|
def _to_bridge_response(response: dict[str, Any]) -> dict[str, Any]:
|
|
|
|
|
|
if response.get("ok"):
|
|
|
|
|
|
return {
|
|
|
|
|
|
"status": "ok",
|
|
|
|
|
|
"message": "",
|
|
|
|
|
|
"data": response.get("data"),
|
|
|
|
|
|
"request_id": response.get("request_id"),
|
|
|
|
|
|
}
|
|
|
|
|
|
return {
|
|
|
|
|
|
"status": "error",
|
|
|
|
|
|
"message": str(response.get("message") or "request failed"),
|
|
|
|
|
|
"data": response,
|
|
|
|
|
|
"request_id": response.get("request_id"),
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-11 21:50:34 +08:00
|
|
|
|
def _to_media_http_response(endpoint: str, response: dict[str, Any]) -> Any | None:
|
|
|
|
|
|
if normalize_extension_path(endpoint) != "media/fetch" or not response.get("ok"):
|
|
|
|
|
|
return None
|
|
|
|
|
|
data = _mapping_from_any(response.get("data"))
|
|
|
|
|
|
encoded = str(data.get("body_base64") or "")
|
|
|
|
|
|
try:
|
|
|
|
|
|
body = base64.urlsafe_b64decode(encoded + ("=" * (-len(encoded) % 4)))
|
|
|
|
|
|
except (binascii.Error, ValueError):
|
|
|
|
|
|
return None
|
|
|
|
|
|
content_type = str(data.get("content_type") or "application/octet-stream")
|
|
|
|
|
|
cache_control = str(data.get("cache_control") or "private, max-age=300")
|
|
|
|
|
|
headers = {"Cache-Control": cache_control}
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
|
from astrbot.api.web import request as _astrbot_request # noqa: F401
|
|
|
|
|
|
from starlette.responses import Response
|
|
|
|
|
|
|
|
|
|
|
|
return Response(content=body, media_type=content_type, headers=headers)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
try:
|
|
|
|
|
|
from quart import Response
|
|
|
|
|
|
|
|
|
|
|
|
return Response(body, content_type=content_type, headers=headers)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def _to_media_file_response(query: dict[str, Any]) -> Any | None:
|
|
|
|
|
|
"""Use AstrBot/Quart native file responses to avoid base64 memory copies."""
|
|
|
|
|
|
|
|
|
|
|
|
token = str(query.get("token") or "").strip()
|
|
|
|
|
|
if not token:
|
|
|
|
|
|
return None
|
|
|
|
|
|
try:
|
|
|
|
|
|
path, metadata = MediaProxy().resolve_file(token)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
|
|
|
|
|
content_type = str(metadata.get("content_type") or "application/octet-stream")
|
|
|
|
|
|
headers = {"Cache-Control": "private, max-age=300"}
|
|
|
|
|
|
try:
|
|
|
|
|
|
from astrbot.api.web import file_response
|
|
|
|
|
|
|
|
|
|
|
|
return file_response(path, content_type=content_type, headers=headers)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
pass
|
|
|
|
|
|
try:
|
|
|
|
|
|
from quart import send_file
|
|
|
|
|
|
|
|
|
|
|
|
response = send_file(path, mimetype=content_type, conditional=True, max_age=300)
|
|
|
|
|
|
if inspect.isawaitable(response):
|
|
|
|
|
|
response = await response
|
|
|
|
|
|
response.headers["Cache-Control"] = headers["Cache-Control"]
|
|
|
|
|
|
return response
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-06 10:00:18 +08:00
|
|
|
|
def _mapping_from_any(value: Any) -> dict[str, Any]:
|
|
|
|
|
|
if value is None:
|
|
|
|
|
|
return {}
|
|
|
|
|
|
if isinstance(value, dict):
|
|
|
|
|
|
return dict(value)
|
|
|
|
|
|
if hasattr(value, "items"):
|
|
|
|
|
|
return {str(key): item for key, item in value.items()}
|
|
|
|
|
|
return {}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _mapping_value(value: Any, *keys: str) -> Any:
|
|
|
|
|
|
mapping = _mapping_from_any(value)
|
|
|
|
|
|
for key in keys:
|
|
|
|
|
|
if key in mapping:
|
|
|
|
|
|
return mapping[key]
|
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _attr(value: Any, name: str) -> Any:
|
|
|
|
|
|
if value is None:
|
|
|
|
|
|
return None
|
2026-07-11 21:50:34 +08:00
|
|
|
|
try:
|
|
|
|
|
|
return getattr(value, name, None)
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return None
|
2026-07-06 10:00:18 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _nested_attr(value: Any, *names: str) -> Any:
|
|
|
|
|
|
current = value
|
|
|
|
|
|
for name in names:
|
|
|
|
|
|
current = _attr(current, name)
|
|
|
|
|
|
if current is None:
|
|
|
|
|
|
return None
|
|
|
|
|
|
return current
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _first_text(*values: Any) -> str:
|
|
|
|
|
|
for value in values:
|
|
|
|
|
|
if value is None:
|
|
|
|
|
|
continue
|
|
|
|
|
|
text = str(value).strip()
|
|
|
|
|
|
if text:
|
|
|
|
|
|
return text
|
|
|
|
|
|
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
2026-07-11 21:50:34 +08:00
|
|
|
|
def _current_quart_username() -> str:
|
|
|
|
|
|
try:
|
|
|
|
|
|
from quart import g
|
|
|
|
|
|
|
|
|
|
|
|
return _first_text(getattr(g, "username", None))
|
|
|
|
|
|
except Exception:
|
|
|
|
|
|
return ""
|
2026-07-06 10:00:18 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _client_ip(request: Any | None) -> str | None:
|
2026-07-11 21:50:34 +08:00
|
|
|
|
client_host = _attr(request, "client_host")
|
|
|
|
|
|
if client_host:
|
|
|
|
|
|
return str(client_host)
|
|
|
|
|
|
remote_addr = _attr(request, "remote_addr")
|
|
|
|
|
|
if remote_addr:
|
|
|
|
|
|
return str(remote_addr)
|
2026-07-06 10:00:18 +08:00
|
|
|
|
client = _attr(request, "client")
|
|
|
|
|
|
host = _attr(client, "host")
|
|
|
|
|
|
if host:
|
|
|
|
|
|
return str(host)
|
|
|
|
|
|
remote = _attr(request, "remote")
|
|
|
|
|
|
return str(remote) if remote else None
|