astrbot_plugin_imagestudio/main.py

2575 行
116 KiB
Python

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
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
import re
2026-07-06 09:19:54 +08:00
import sys
from uuid import uuid4
2026-07-06 09:19:54 +08:00
from pathlib import Path
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))
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,
)
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
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
2026-07-13 01:49:00 +08:00
from core.config_service import PLUGIN_VERSION
from core.astrbot_provider_bridge import configure_astrbot_provider_bridge
2026-07-05 22:07:36 +08:00
from core.identity import RequestContext
from core.media_proxy import MediaProxy
2026-07-06 11:20:56 +08:00
from database import db_helper as _database_db_helper
from database.repositories.model_provider_repository import ModelProviderRepository
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."
BRIDGE_PERMISSIONS = frozenset(
{"can_write", "can_manage_config", "can_manage_materials", "can_retry_tasks"}
)
_MISSING = object()
_RUNTIME_PATH_TO_ASTRBOT_KEY = {
"plugin.display_name": "display_name",
"generation.default_model": "default_generation_model",
"generation.provider.provider_id": "generation_provider_id",
"generation.provider.base_url": "generation_provider_base_url",
"generation.provider.image_endpoint": "generation_provider_image_endpoint",
"generation.provider.model_id": "generation_provider_model",
"generation.provider.route_name": "generation_provider_route",
"generation.provider.api_key_env_var": "generation_provider_api_key_env_var",
"generation.provider.timeout_seconds": "generation_provider_timeout_seconds",
"vision.default_route": "vision_provider_route",
"vision.provider.provider_id": "vision_provider_id",
"vision.provider.base_url": "vision_provider_base_url",
"vision.provider.vision_endpoint": "vision_provider_endpoint",
"vision.provider.model_id": "vision_provider_model",
"vision.provider.route_name": "vision_provider_route",
"vision.provider.api_key_env_var": "vision_provider_api_key_env_var",
"vision.provider.timeout_seconds": "vision_provider_timeout_seconds",
"vision.provider.enabled": "vision_provider_enabled",
"model_assignments.material_recognition": "model_material_recognition",
"model_assignments.advanced_material_recognition": "model_advanced_material_recognition",
"model_assignments.advanced_material_validation_generation": "model_advanced_material_validation_generation",
"advanced_materials.cost_budget.enabled": "advanced_material_budget_enabled",
"advanced_materials.cost_budget.days": "advanced_material_budget_days",
"advanced_materials.cost_budget.max_task_count": "advanced_material_budget_max_task_count",
"advanced_materials.cost_budget.max_image_count": "advanced_material_budget_max_image_count",
"advanced_materials.cost_budget.max_estimated_cost": "advanced_material_budget_max_estimated_cost",
"advanced_materials.cost_budget.price_key": "advanced_material_budget_price_key",
"advanced_materials.cost_budget.per_request": "advanced_material_budget_per_request",
"advanced_materials.cost_budget.per_image": "advanced_material_budget_per_image",
"advanced_materials.cost_budget.per_1k_tokens": "advanced_material_budget_per_1k_tokens",
"model_assignments.profile_parse": "model_profile_parse",
"model_assignments.persona_split": "model_persona_split",
"model_assignments.prompt_planning": "model_prompt_planning",
"model_assignments.visual_review_routes": "model_visual_review_routes",
"model_assignments.cross_review_primary": "model_cross_review_primary",
"model_assignments.cross_review_secondary": "model_cross_review_secondary",
"model_assignments.cross_review_routes": "model_cross_review_routes",
"model_assignments.generation_cross_review_primary": "model_generation_cross_review_primary",
"model_assignments.generation_cross_review_secondary": "model_generation_cross_review_secondary",
"model_assignments.generation_cross_review_routes": "model_generation_cross_review_routes",
"model_assignments.quick_generation": "model_quick_generation",
"model_assignments.portrait_generation": "model_portrait_generation",
"model_assignments.halfbody_generation": "model_halfbody_generation",
"model_assignments.fullbody_generation": "model_fullbody_generation",
"model_assignments.sheet_generation": "model_sheet_generation",
"model_assignments.hires_fix": "model_hires_fix",
"chat_access.group_allowlist": "chat_group_allowlist",
"chat_access.user_allowlist": "chat_user_allowlist",
"chat_access.user_concurrency_limit": "chat_user_concurrency_limit",
"chat_access.group_concurrency_limit": "chat_group_concurrency_limit",
"chat_access.daily_user_generation_limit": "chat_daily_user_generation_limit",
"chat_access.daily_group_generation_limit": "chat_daily_group_generation_limit",
"chat_access.allow_2k": "chat_allow_2k",
"chat_access.allow_4k": "chat_allow_4k",
"features.private_companion_integration": "enable_private_companion_integration",
"storage.advanced_materials_path": "advanced_materials_path",
"database.backend": "database_backend",
"database.sqlite.path": "sqlite_path",
"database.postgresql.enabled": "postgresql_enabled",
"database.postgresql.dsn": "postgresql_dsn",
"database.postgresql.host": "postgresql_host",
"database.postgresql.port": "postgresql_port",
"database.postgresql.database": "postgresql_database",
"database.postgresql.user": "postgresql_user",
"database.postgresql.password": "postgresql_password",
}
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
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
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()
def initialize_runtime_database(settings: DatabaseSettings | None = None) -> dict[str, Any]:
database = Database(settings or load_database_settings())
database.initialize()
seed = seed_default_material_categories(database)
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,
}
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)
_set_runtime_config_persister(config)
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,
) -> Any:
2026-07-06 10:00:18 +08:00
ctx = _request_context_from_astrbot_request(request)
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,
dispatch_method,
dispatch_endpoint,
query=dispatch_query,
payload=dispatch_payload,
2026-07-06 10:00:18 +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:
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
self.astrbot_config = runtime_config if runtime_config is not None else _attr(self, "config")
self.registration_result: dict[str, Any] | None = None
self.database_result: dict[str, Any] | None = None
self.runtime_config_result: dict[str, Any] | None = None
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()
self.round_worker_runtime: Any | None = None
self.round_worker_result: dict[str, Any] | None = None
self.advanced_material_worker_runtime: Any | None = None
self.advanced_material_worker_result: dict[str, Any] | None = None
self.runtime_loop: asyncio.AbstractEventLoop | None = None
2026-07-06 09:26:29 +08:00
async def initialize(self) -> None:
self.runtime_loop = asyncio.get_running_loop()
configure_astrbot_provider_bridge(self.context, self.runtime_loop)
self.runtime_config_result = apply_astrbot_config_overrides(self.astrbot_config)
2026-07-13 01:49:00 +08:00
# Database migrations must complete before AstrBot registers or inspects
# any route handlers. Registration is not guaranteed to be passive on
# every supported AstrBot version.
self.database_result = initialize_runtime_database()
try:
from backend.services.workflow_round_worker_runtime import (
create_workflow_round_worker_runtime,
)
self.round_worker_runtime = create_workflow_round_worker_runtime(
terminal_notification_callback=self._schedule_round_terminal_notification,
)
self.round_worker_result = self.round_worker_runtime.start()
replay_task = asyncio.create_task(self._replay_round_terminal_notifications())
self.chat_background_tasks.add(replay_task)
replay_task.add_done_callback(self.chat_background_tasks.discard)
except Exception as exc:
# Keep the plugin and its recovery UI available even when a worker
# cannot start. The persisted queue remains intact for the next
# reload, and status diagnostics can expose the startup reason.
self.round_worker_runtime = None
self.round_worker_result = {
"running": False,
"error_type": type(exc).__name__,
"message": " ".join(str(exc).split())[:500],
}
try:
from backend.services.advanced_material_worker_runtime import (
create_advanced_material_worker_runtime,
)
self.advanced_material_worker_runtime = create_advanced_material_worker_runtime()
self.advanced_material_worker_result = self.advanced_material_worker_runtime.start()
except Exception as exc:
# Keep the normal material library and recovery UI usable when the
# optional advanced-material worker cannot start. Its persisted
# imports/tasks remain available for retry after configuration is
# corrected or the plugin is reloaded.
self.advanced_material_worker_runtime = None
self.advanced_material_worker_result = {
"running": False,
"error_type": type(exc).__name__,
"message": " ".join(str(exc).split())[:500],
}
if self.context is not None:
self.registration_result = register_plugin(self.context)
2026-07-06 09:26:29 +08:00
return None
async def terminate(self) -> None:
if self.advanced_material_worker_runtime is not None:
self.advanced_material_worker_result = self.advanced_material_worker_runtime.stop()
self.advanced_material_worker_runtime = None
if self.round_worker_runtime is not None:
self.round_worker_result = self.round_worker_runtime.stop()
self.round_worker_runtime = None
configure_astrbot_provider_bridge(None, None)
self.runtime_loop = None
_set_runtime_config_persister(None)
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
@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, workflow_id: str = ""):
health = get_runtime_health()
state = "正常" if health.get("healthy") is not False else "异常"
database = "已初始化" if self.database_result else "等待初始化"
details: list[str] = []
workflow_summary: dict[str, Any] = {}
try:
workflow_summary = await asyncio.to_thread(
self.chat_workflow_service.chat_status,
command_context_from_event(event),
workflow_id.strip(),
)
except Exception:
workflow_summary = {}
workflow = workflow_summary.get("workflow") if isinstance(workflow_summary.get("workflow"), dict) else None
current = workflow_summary.get("current_node") if isinstance(workflow_summary.get("current_node"), dict) else None
current_round = workflow_summary.get("current_round") if isinstance(workflow_summary.get("current_round"), dict) else None
round_record = current_round.get("round") if isinstance(current_round, dict) and isinstance(current_round.get("round"), dict) else None
if workflow:
details.extend(
[
f"分支 {workflow_summary.get('branch_name') or 'main'}",
f"节点 {(current or {}).get('title') or (current or {}).get('node_key') or '已完成'}",
f"轮次 {(round_record or {}).get('display_code') or '暂无'}",
f"下一动作 {workflow_summary.get('next_action') or '查看工作流'}",
]
)
else:
details.append("下一动作 使用 /yp 工作流 <角色名>")
text = (
f"🛰 ImageStudio 状态:{state}\n版本:{PLUGIN_VERSION}\nAPI:{API_BASE}\n数据库:{database}"
+ ("\n" + "\n".join(details) if details else "")
)
yield self._card_result(
event,
lambda: render_status_card(
state=state,
version=PLUGIN_VERSION,
database=database,
api=API_BASE,
details=details,
),
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)
workflow_id = str(result.get("workflow", {}).get("workflow_id") or "")
if not workflow_id:
raise ValueError("快速角色四图工作流未创建")
request_id = f"chatfast_{uuid4().hex}"
task = asyncio.create_task(
self._run_quick_character_background(workflow_id, context, request_id)
)
self.chat_background_tasks.add(task)
task.add_done_callback(self.chat_background_tasks.discard)
yield event.plain_result(
f"✅ 快速角色已保存,四张角色图已并行加入生成队列\n"
f"角色:{result['profile']['name']}\nID:{result['profile']['profile_id']}\n"
f"工作流:{workflow_id}\n请求:{request_id}\n"
"头像、半身像、立绘与设定图相互独立,完成后会主动回传。"
)
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
if session.action == "confirm_candidate":
try:
result = await asyncio.to_thread(
self.chat_workflow_service.confirm_node_image,
session.payload["node_id"],
session.payload["image_id"],
context,
)
next_node = result.get("next_node") or {}
next_hint = (
f"\n下一节点:{next_node.get('title') or next_node.get('node_key')}"
if next_node
else "\n当前阶段链路已到末尾。"
)
yield event.plain_result(
f"✅ 已确认采用图片:{result.get('image_id')}" + next_hint
)
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)
if isinstance(result.get("round"), dict):
round_record = result["round"]
round_id = str(round_record.get("round_id") or "")
self.chat_sessions.put(
self._session_key(context),
"round_feedback",
{"round_id": round_id, "node_id": node_id.strip()},
)
yield event.plain_result(
f"✅ 已加入候选生成队列\n节点:{node_id}\n"
f"轮次:{round_record.get('display_code') or round_id}\n"
f"候选:{round_record.get('requested_count') or 4} 个独立任务\n"
"生成结束后会主动回传;也可使用 /yp 轮次状态 <round_id> 查询。"
)
return
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}")
elif result.get("requires_profile_card"):
yield event.plain_result(
f"📦 当前已到档案卡节点\n下一动作:{result.get('next_action')}"
)
elif result.get("requires_node_input"):
yield event.plain_result(
f"📝 当前节点需要先填写或确认内容\n节点:{result['node'].get('title') or result['node'].get('node_key')}\n"
f"下一动作:{result.get('next_action')}"
)
else:
generation = result.get("generation") if isinstance(result.get("generation"), dict) else {}
round_record = generation.get("round") if isinstance(generation.get("round"), dict) else None
if round_record:
self.chat_sessions.put(
self._session_key(command_context_from_event(event)),
"round_feedback",
{"round_id": round_record["round_id"], "node_id": result["node"]["node_id"]},
)
yield event.plain_result(
f"✅ 下一节点候选已入队\n节点:{result['node']['node_id']}\n"
f"轮次:{round_record.get('display_code') or round_record.get('round_id')}"
)
else:
yield event.plain_result(f"✅ 已执行下一节点\n节点:{result['node']['node_id']}\n任务:{generation.get('task_id') or '—'}")
except Exception as exc:
yield event.plain_result(f"❌ 下一步执行失败:{exc}")
@imagestudio_command.command("轮次")
async def imagestudio_round(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=2)
if not parts:
yield event.plain_result("用法:/yp 轮次 <node_id> [4|5] [可选提示词]")
return
node_id = parts[0]
count = 4
prompt = ""
if len(parts) >= 2 and parts[1].isdigit():
count = int(parts[1])
prompt = parts[2] if len(parts) >= 3 else ""
elif len(parts) >= 2:
prompt = " ".join(parts[1:])
if count not in {4, 5}:
yield event.plain_result("详细工作流每轮候选数量只能是 4 或 5。")
return
context = command_context_from_event(event)
try:
result = await asyncio.to_thread(
self.chat_workflow_service.create_round,
node_id,
context,
count=count,
prompt=prompt,
)
except Exception as exc:
yield event.plain_result(f"❌ 创建候选轮次失败:{exc}")
return
round_record = result.get("round", {})
round_id = str(round_record.get("round_id") or "")
self.chat_sessions.put(
self._session_key(context),
"round_feedback",
{"round_id": round_id, "node_id": node_id},
)
yield event.plain_result(
f"✅ 已加入候选生成队列\n轮次:{round_record.get('display_code') or round_id}\n"
f"节点:{node_id}\n候选:{round_record.get('requested_count') or count} 个独立任务\n"
f"ID:{round_id}\n生成结束后会主动回传。"
)
@imagestudio_command.command("轮次状态")
async def imagestudio_round_status(self, event: AstrMessageEvent, round_id: str = ""):
try:
detail = await asyncio.to_thread(
self.chat_workflow_service.round_detail,
round_id.strip(),
command_context_from_event(event),
)
yield event.plain_result(self._format_round(detail, include_failures=True))
except Exception as exc:
yield event.plain_result(f"❌ 轮次查询失败:{exc}")
@imagestudio_command.command("候选")
async def imagestudio_round_candidates(self, event: AstrMessageEvent, round_id: str = ""):
context = command_context_from_event(event)
try:
detail = await asyncio.to_thread(
self.chat_workflow_service.round_detail,
round_id.strip(),
context,
)
except Exception as exc:
yield event.plain_result(f"❌ 候选读取失败:{exc}")
return
self.chat_sessions.put(
self._session_key(context),
"round_feedback",
{"round_id": round_id.strip(), "node_id": detail.get("round", {}).get("node_id")},
)
images = [
{
**item["image"],
"display_code": item.get("display_code"),
}
for item in detail.get("candidates", [])
if isinstance(item, dict) and isinstance(item.get("image"), dict)
]
yield self._generation_result(
event,
self._format_round(detail) + "\n可直接回复:1、2喜欢,3严格拒绝。",
images,
)
@imagestudio_command.command("反馈")
async def imagestudio_round_feedback(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if len(parts) < 2:
yield event.plain_result("用法:/yp 反馈 <round_id> <自然语言反馈>")
return
round_id, feedback = parts
try:
result = await asyncio.to_thread(
self.chat_workflow_service.submit_round_feedback,
round_id,
feedback,
command_context_from_event(event),
)
yield event.plain_result("✅ 候选反馈已保存\n" + self._format_round_feedback(result))
except Exception as exc:
yield event.plain_result(f"❌ 候选反馈失败:{exc}")
@imagestudio_command.command("下一轮")
async def imagestudio_next_round(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if not parts:
yield event.plain_result("用法:/yp 下一轮 <round_id> [4|5]")
return
count = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else None
if count is not None and count not in {4, 5}:
yield event.plain_result("下一轮候选数量只能是 4 或 5。")
return
context = command_context_from_event(event)
try:
result = await asyncio.to_thread(
self.chat_workflow_service.create_next_round,
parts[0],
context,
count=count,
)
except Exception as exc:
yield event.plain_result(f"❌ 创建下一轮失败:{exc}")
return
round_record = result.get("round", {})
self.chat_sessions.put(
self._session_key(context),
"round_feedback",
{"round_id": round_record.get("round_id"), "node_id": round_record.get("node_id")},
)
yield event.plain_result(
f"✅ 优化轮次已入队\n轮次:{round_record.get('display_code')}\n"
f"父轮次:{result.get('parent_round_id')}\n候选:{round_record.get('requested_count')}"
)
@imagestudio_command.command("定稿")
async def imagestudio_confirm_round(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if len(parts) < 2:
yield event.plain_result("用法:/yp 定稿 <round_id> <候选编号>")
return
try:
result = await asyncio.to_thread(
self.chat_workflow_service.confirm_round_candidate,
parts[0],
parts[1],
command_context_from_event(event),
)
next_node = result.get("next_node") or {}
yield event.plain_result(
f"✅ 已明确定稿:{parts[1]}\n轮次:{parts[0]}\n"
+ (
f"下一节点:{next_node.get('title') or next_node.get('node_key')}"
if next_node
else "当前分支已到末尾。"
)
)
except Exception as exc:
yield event.plain_result(f"❌ 定稿失败:{exc}")
@imagestudio_command.command("审查")
async def imagestudio_generation_cross_review(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=2)
if len(parts) < 2:
yield event.plain_result("用法:/yp 审查 <round_id> <候选编号> [审核|跳过]")
return
decision = parts[2] if len(parts) > 2 else "审核"
try:
result = await asyncio.to_thread(
self.chat_workflow_service.decide_generation_cross_review,
parts[0],
parts[1],
decision,
command_context_from_event(event),
)
except Exception as exc:
yield event.plain_result(f"❌ 生成式交叉审查失败:{exc}")
return
if result.get("review_decision", {}).get("decision") == "skip":
yield event.plain_result(f"✅ 已跳过交叉审查并采用候选 {parts[1]}")
return
round_record = result.get("round", {})
yield event.plain_result(
f"✅ 交叉审查候选已入队\n轮次:{round_record.get('display_code') or round_record.get('round_id')}\n"
"原始候选保留为 01,其余候选由不同生图模型生成;完成后会主动回传。"
)
@imagestudio_command.command("审查重做")
async def imagestudio_cross_review_regenerate(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=2)
if len(parts) < 2:
yield event.plain_result("用法:/yp 审查重做 <round_id> <候选编号,候选编号> [提示词修订]")
return
refs = [value for value in re.split(r"[,,、]", parts[1]) if value.strip()]
prompt_patch = parts[2] if len(parts) > 2 else ""
try:
result = await asyncio.to_thread(
self.chat_workflow_service.regenerate_cross_review,
parts[0],
refs,
command_context_from_event(event),
prompt_patch=prompt_patch,
)
round_record = result.get("round", {})
yield event.plain_result(
f"✅ 选中的审查候选已重新入队\n轮次:{round_record.get('display_code') or round_record.get('round_id')}"
)
except Exception as exc:
yield event.plain_result(f"❌ 审查重做失败:{exc}")
@imagestudio_command.command("审查通过")
async def imagestudio_cross_review_approve(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if len(parts) < 2:
yield event.plain_result("用法:/yp 审查通过 <round_id> <候选编号>")
return
try:
result = await asyncio.to_thread(
self.chat_workflow_service.approve_cross_review,
parts[0],
parts[1],
command_context_from_event(event),
)
next_node = result.get("next_node") or {}
yield event.plain_result(
f"✅ 交叉审查候选已采用:{parts[1]}\n"
f"下一节点:{next_node.get('title') or next_node.get('node_key') or '当前阶段末尾'}"
)
except Exception as exc:
yield event.plain_result(f"❌ 审查通过失败:{exc}")
@imagestudio_command.command("素材")
async def imagestudio_node_materials(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if not parts:
yield event.plain_result("用法:/yp 素材 <node_id> [material_id,material_id];不填素材 ID 时仅查看")
return
context = command_context_from_event(event)
try:
if len(parts) == 1:
result = await asyncio.to_thread(
self.chat_workflow_service.get_node_materials,
parts[0],
context,
)
else:
material_ids = [value.strip() for value in re.split(r"[,,、]", parts[1]) if value.strip()]
result = await asyncio.to_thread(
self.chat_workflow_service.save_node_materials,
parts[0],
material_ids,
context,
)
bindings = result.get("material_bindings") if isinstance(result.get("material_bindings"), dict) else {}
selected = bindings.get("selected_material_ids") or []
temporary = result.get("temporary_references") or []
yield event.plain_result(
f"🧵 节点素材\n节点:{parts[0]}\n"
f"素材:{'、'.join(selected) if selected else '未绑定'}\n临时参考:{len(temporary)}\n"
f"状态:{'可修改' if result.get('writable') else '只读'}"
)
except Exception as exc:
yield event.plain_result(f"❌ 节点素材操作失败:{exc}")
@imagestudio_command.command("分支")
async def imagestudio_branches(self, event: AstrMessageEvent, workflow_id: str = ""):
try:
branches = await asyncio.to_thread(
self.chat_workflow_service.list_branches,
workflow_id.strip(),
command_context_from_event(event),
)
lines = [f"🌿 工作流分支 · {workflow_id}"]
for branch in branches:
lines.append(
f"• {branch.get('branch_name')} · {branch.get('status')} · 父分支 {branch.get('base_branch_name') or '—'}"
)
yield event.plain_result("\n".join(lines))
except Exception as exc:
yield event.plain_result(f"❌ 分支查询失败:{exc}")
@imagestudio_command.command("新建分支")
async def imagestudio_create_branch(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=2)
if len(parts) < 3:
yield event.plain_result("用法:/yp 新建分支 <workflow_id> <已完成切点node_id> <新分支名>")
return
try:
result = await asyncio.to_thread(
self.chat_workflow_service.create_branch,
parts[0],
parts[2],
parts[1],
command_context_from_event(event),
)
yield event.plain_result(
f"✅ 分支已创建:{result.get('branch_name')}\n父分支:{result.get('base_branch_name') or 'main'}"
)
except Exception as exc:
yield event.plain_result(f"❌ 新建分支失败:{exc}")
@imagestudio_command.command("切换分支")
async def imagestudio_switch_branch(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if len(parts) < 2:
yield event.plain_result("用法:/yp 切换分支 <workflow_id> <分支名>")
return
try:
result = await asyncio.to_thread(
self.chat_workflow_service.switch_branch,
parts[0],
parts[1],
command_context_from_event(event),
)
yield event.plain_result(
f"✅ 已切换到分支:{result.get('current_branch')}\n当前节点:{result.get('current_node_id') or '—'}"
)
except Exception as exc:
yield event.plain_result(f"❌ 切换分支失败:{exc}")
@imagestudio_command.command("档案卡")
async def imagestudio_profile_card(self, event: AstrMessageEvent, argument: str = ""):
parts = str(argument or "").strip().split(maxsplit=1)
if not parts:
yield event.plain_result("用法:/yp 档案卡 <workflow_id> [可选人设文档]")
return
try:
result = await asyncio.to_thread(
self.chat_workflow_service.finalize_profile_card,
parts[0],
command_context_from_event(event),
persona_document=parts[1] if len(parts) > 1 else "",
)
yield event.plain_result(
f"✅ 角色档案卡已原子封存\nID:{result.get('card_id')}\n"
f"分支:{result.get('branch_name')}\n资产:{len(result.get('assets') 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 = ""):
context = command_context_from_event(event)
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), context)
else:
result = await asyncio.to_thread(self.chat_workflow_service.select_node_image, node_id.strip(), image_id.strip(), context)
selected_image_id = result.get("image_id", image_id)
self.chat_sessions.put(
self._session_key(context),
"confirm_candidate",
{"node_id": node_id.strip(), "image_id": selected_image_id},
)
yield event.plain_result(
f"✅ 已暂选图片:{selected_image_id}\n发送 /yp 确认 正式采用并推进,或 /yp 放弃 取消。"
)
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.put(
self._session_key(context),
"confirm_candidate",
{"node_id": session.payload["node_id"], "image_id": result.get("image_id", image_id)},
)
yield event.plain_result(
f"✅ 已暂选第 {index + 1} 张:{result.get('image_id', image_id)}\n"
"发送 /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
context = command_context_from_event(event)
request_id = f"chathires_{uuid4().hex}"
task = asyncio.create_task(
self._run_hires_background(
image_id.strip(),
normalized_size,
context,
request_id,
)
)
self.chat_background_tasks.add(task)
task.add_done_callback(self.chat_background_tasks.discard)
yield event.plain_result(
f"✅ 高清修复请求已进入后台\n请求:{request_id}\n原图:{image_id}\n"
f"尺寸:{normalized_size}\n完成或失败后会主动回传。"
)
@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 == "round_feedback":
try:
result = await asyncio.to_thread(
self.chat_workflow_service.submit_round_feedback,
str(session.payload["round_id"]),
text,
context,
)
yield event.plain_result("✅ 候选反馈已保存\n" + self._format_round_feedback(result))
except Exception as exc:
yield event.plain_result(f"❌ 候选反馈失败:{exc}")
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, workflow_id: str = ""):
async for result in self.imagestudio_status(event, workflow_id):
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_round(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_round(event, argument): yield result
@imagestudio_short_command.command("轮次状态")
async def imagestudio_short_round_status(self, event: AstrMessageEvent, round_id: str = ""):
async for result in self.imagestudio_round_status(event, round_id): yield result
@imagestudio_short_command.command("候选")
async def imagestudio_short_round_candidates(self, event: AstrMessageEvent, round_id: str = ""):
async for result in self.imagestudio_round_candidates(event, round_id): yield result
@imagestudio_short_command.command("反馈")
async def imagestudio_short_round_feedback(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_round_feedback(event, argument): yield result
@imagestudio_short_command.command("下一轮")
async def imagestudio_short_next_round(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_next_round(event, argument): yield result
@imagestudio_short_command.command("定稿")
async def imagestudio_short_confirm_round(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_confirm_round(event, argument): yield result
@imagestudio_short_command.command("审查")
async def imagestudio_short_generation_cross_review(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_generation_cross_review(event, argument): yield result
@imagestudio_short_command.command("审查重做")
async def imagestudio_short_cross_review_regenerate(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_cross_review_regenerate(event, argument): yield result
@imagestudio_short_command.command("审查通过")
async def imagestudio_short_cross_review_approve(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_cross_review_approve(event, argument): yield result
@imagestudio_short_command.command("素材")
async def imagestudio_short_node_materials(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_node_materials(event, argument): yield result
@imagestudio_short_command.command("分支")
async def imagestudio_short_branches(self, event: AstrMessageEvent, workflow_id: str = ""):
async for result in self.imagestudio_branches(event, workflow_id): yield result
@imagestudio_short_command.command("新建分支")
async def imagestudio_short_create_branch(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_create_branch(event, argument): yield result
@imagestudio_short_command.command("切换分支")
async def imagestudio_short_switch_branch(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_switch_branch(event, argument): yield result
@imagestudio_short_command.command("档案卡")
async def imagestudio_short_profile_card(self, event: AstrMessageEvent, argument: str = ""):
async for result in self.imagestudio_profile_card(event, argument): 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)
@staticmethod
def _format_round(detail: dict[str, Any], *, include_failures: bool = False) -> str:
round_record = detail.get("round") if isinstance(detail.get("round"), dict) else {}
lines = [
f"🎞 候选轮次 {round_record.get('display_code') or round_record.get('round_id') or '—'}",
f"状态:{round_record.get('status') or 'unknown'}",
f"分支:{round_record.get('branch_name') or 'main'}",
]
for item in detail.get("candidates", []):
if not isinstance(item, dict):
continue
candidate = item.get("candidate") if isinstance(item.get("candidate"), dict) else {}
line = (
f"• {item.get('display_code') or item.get('display_index')} · "
f"{candidate.get('generation_status') or 'unknown'} · "
f"{item.get('preference_status') or 'neutral'}"
)
if item.get("is_final"):
line += " · 已定稿"
if include_failures:
failure = candidate.get("failure") if isinstance(candidate.get("failure"), dict) else {}
if failure.get("message"):
line += f" · {str(failure['message'])[:180]}"
lines.append(line)
return "\n".join(lines)
@staticmethod
def _format_round_feedback(detail: dict[str, Any]) -> str:
lines: list[str] = []
interpretation = detail.get("interpretation") if isinstance(detail.get("interpretation"), dict) else {}
for label, key in (("喜欢", "liked"), ("拒绝", "rejected"), ("严格拒绝", "strict_rejected")):
values = interpretation.get(key) if isinstance(interpretation.get(key), list) else []
codes = [str(item.get("display_code") or "") for item in values if isinstance(item, dict)]
if codes:
lines.append(f"{label}:{'、'.join(codes)}")
final = interpretation.get("final") if isinstance(interpretation.get("final"), dict) else None
if final:
lines.append(f"草稿定稿:{final.get('display_code')}")
snapshot = detail.get("round", {}).get("feedback_snapshot") if isinstance(detail.get("round"), dict) else {}
if not lines and isinstance(snapshot, dict):
lines.append("反馈快照已更新。")
lines.append("正式推进仍需使用 /yp 定稿 <round_id> <候选编号>。")
return "\n".join(lines)
def _help_card(self) -> Path:
return render_help_card([
"/影棚 帮助 /yp 帮助",
"/影棚 状态 /yp 状态",
"/影棚 快速角色 <角色描述>",
"/影棚 工作流 <角色名或 ID>",
"/影棚 单图 <提示词>",
"/yp 轮次 <node_id> 4|5",
"/yp 候选 / 反馈 / 下一轮 / 定稿",
"/yp 审查 / 素材 / 分支 / 档案卡",
])
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 _run_quick_character_background(
self,
workflow_id: str,
context: Any,
request_id: str,
) -> None:
try:
result = await asyncio.to_thread(
self.chat_workflow_service.generate_quick_character,
workflow_id,
context,
)
text = (
f"🎭 快速角色四图生成结束\n请求:{request_id}\n工作流:{workflow_id}\n"
f"成功:{result.get('succeeded', 0)} / 4\n失败:{result.get('failed', 0)}"
)
failures = result.get("failures") if isinstance(result.get("failures"), list) else []
for item in failures:
text += f"\n• {item.get('node_key') or item.get('node_id')}:{item.get('message')}"
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工作流:{workflow_id}\n错误:{exc}",
[],
)
async def _run_hires_background(
self,
image_id: str,
normalized_size: str,
context: Any,
request_id: str,
) -> None:
try:
result = await asyncio.to_thread(
self.chat_workflow_service.hires_fix,
image_id,
normalized_size,
context,
)
await self._send_proactive(
context.message_origin,
f"✅ 高清修复完成\n请求:{request_id}\n原图:{image_id}\n尺寸:{normalized_size}",
result.get("images", []),
)
except asyncio.CancelledError:
raise
except Exception as exc:
await self._send_proactive(
context.message_origin,
f"❌ 高清修复失败\n请求:{request_id}\n原图:{image_id}\n错误:{exc}",
[],
)
async def _send_proactive(self, message_origin: str, text: str, images: list[dict[str, Any]]) -> bool:
sender = getattr(self.context, "send_message", None)
if not callable(sender) or not message_origin:
return False
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
return True
except Exception:
return False
def _schedule_round_terminal_notification(self, notification: dict[str, Any]) -> None:
loop = self.runtime_loop
if loop is None or loop.is_closed():
raise RuntimeError("AstrBot event loop is unavailable for terminal notification")
def schedule() -> None:
task = asyncio.create_task(self._deliver_round_terminal_notification(notification))
self.chat_background_tasks.add(task)
task.add_done_callback(self.chat_background_tasks.discard)
loop.call_soon_threadsafe(schedule)
async def _replay_round_terminal_notifications(self) -> None:
runtime = self.round_worker_runtime
if runtime is None:
return
try:
pending = await asyncio.to_thread(runtime.pending_terminal_notifications)
except Exception:
return
for notification in pending:
await self._deliver_round_terminal_notification(notification)
async def _deliver_round_terminal_notification(self, notification: dict[str, Any]) -> None:
runtime = self.round_worker_runtime
round_id = str(notification.get("round_id") or "")
target = notification.get("reply_target")
target = target if isinstance(target, dict) else {}
candidates = [
item for item in notification.get("candidates", []) if isinstance(item, dict)
]
succeeded = [item for item in candidates if item.get("generation_status") == "succeeded"]
failed = [item for item in candidates if item.get("generation_status") in {"failed", "cancelled"}]
status_labels = {
"completed": "全部完成",
"partial_success": "部分完成",
"all_failed": "全部失败",
"cancelled": "已取消",
}
lines = [
"🎨 候选轮次已结束",
f"轮次:{notification.get('display_code') or round_id}",
f"状态:{status_labels.get(str(notification.get('status')), notification.get('status') or '未知')}",
f"成功:{len(succeeded)} / {len(candidates)}",
]
for item in candidates:
line = f"• {item.get('display_code') or item.get('candidate_id')} · {item.get('generation_status')}"
failure = item.get("failure") if isinstance(item.get("failure"), dict) else {}
if failure.get("message"):
line += f" · {str(failure['message'])[:160]}"
lines.append(line)
if succeeded:
lines.append(f"使用 /yp 候选 {round_id} 查看;/yp 反馈 {round_id} <自然语言反馈>")
elif failed:
lines.append("请检查模型/网络错误后重新创建轮次。")
delivered = await self._send_proactive(
str(target.get("message_origin") or ""),
"\n".join(lines),
succeeded,
)
if runtime is not None and round_id:
await asyncio.to_thread(
runtime.mark_terminal_notification,
round_id,
delivered=delivered,
error_message=None if delivered else "AstrBot send_message returned no delivery",
)
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]]:
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
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",
"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",
"model_material_recognition",
"model_advanced_material_recognition",
"model_advanced_material_validation_generation",
"advanced_material_budget_enabled",
"advanced_material_budget_days",
"advanced_material_budget_max_task_count",
"advanced_material_budget_max_image_count",
"advanced_material_budget_max_estimated_cost",
"advanced_material_budget_price_key",
"advanced_material_budget_per_request",
"advanced_material_budget_per_image",
"advanced_material_budget_per_1k_tokens",
"model_profile_parse",
"model_persona_split",
"model_prompt_planning",
"model_visual_review_routes",
"model_cross_review_primary",
"model_cross_review_secondary",
"model_cross_review_routes",
"model_generation_cross_review_primary",
"model_generation_cross_review_secondary",
"model_generation_cross_review_routes",
"model_quick_generation",
"model_portrait_generation",
"model_halfbody_generation",
"model_fullbody_generation",
"model_sheet_generation",
"model_hires_fix",
"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",
"enable_private_companion_integration",
"advanced_materials_path",
"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)
def _set_runtime_config_persister(config: Any | None) -> None:
setter = getattr(_database_db_helper, "set_runtime_config_persister", None)
if not callable(setter):
return
save_config = getattr(config, "save_config", None)
if config is None or not callable(save_config):
setter(None)
return
def persist(values: Mapping[str, Any]) -> dict[str, Any]:
return _persist_astrbot_config_values(config, values)
setter(persist)
def _persist_astrbot_config_values(config: Any, values: Mapping[str, Any]) -> dict[str, Any]:
"""Write ImageStudio runtime-managed paths back to AstrBot's plugin config."""
updated_keys: list[str] = []
previous: dict[str, Any] = {}
for path, value in values.items():
source_key = _RUNTIME_PATH_TO_ASTRBOT_KEY.get(str(path))
if not source_key:
continue
previous[source_key] = config.get(source_key, _MISSING)
config[source_key] = value
updated_keys.append(source_key)
if not updated_keys:
return {"available": True, "saved": False, "paths": [], "astrbot_keys": []}
try:
config.save_config()
except Exception:
for key, value in previous.items():
if value is _MISSING:
config.pop(key, None)
else:
config[key] = value
raise
patch = _runtime_config_patch_from_mapping(_mapping_from_runtime_config(config))
_set_runtime_config_overrides(patch)
return {
"available": True,
"saved": True,
"paths": sorted(str(path) for path in values),
"astrbot_keys": sorted(updated_keys),
}
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 {}
storage = _mapping_from_any(mapping.get("storage"))
features = _mapping_from_any(mapping.get("features"))
plugin = _mapping_from_any(mapping.get("plugin"))
vision = _mapping_from_any(mapping.get("vision"))
vision_provider_config = _mapping_from_any(vision.get("provider")) if vision else {}
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)
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)
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)
# Advanced-material assignments deliberately preserve an empty value so
# administrators can clear a dedicated route and return to its documented
# fallback without a stale AstrBot runtime override restoring it.
for target_key, source_key in {
"advanced_material_recognition": "model_advanced_material_recognition",
"advanced_material_validation_generation": "model_advanced_material_validation_generation",
}.items():
value = _runtime_value(mapping, source_key)
if value is not _MISSING:
_set_nested(patch, ("model_assignments", target_key), _runtime_text(value))
advanced_materials_path = _runtime_text(
_runtime_value(
mapping,
"advanced_materials_path",
fallback=storage.get("advanced_materials_path", _MISSING),
)
)
if advanced_materials_path:
_set_nested(patch, ("storage", "advanced_materials_path"), advanced_materials_path)
advanced_materials = mapping.get("advanced_materials") if isinstance(mapping.get("advanced_materials"), Mapping) else {}
current_budget = advanced_materials.get("cost_budget") if isinstance(advanced_materials.get("cost_budget"), Mapping) else {}
budget_enabled = _runtime_value(
mapping,
"advanced_material_budget_enabled",
fallback=current_budget.get("enabled", _MISSING),
)
if budget_enabled is not _MISSING:
_set_nested(patch, ("advanced_materials", "cost_budget", "enabled"), _runtime_bool(budget_enabled))
for target_key, source_key, converter in (
("days", "advanced_material_budget_days", int),
("max_task_count", "advanced_material_budget_max_task_count", int),
("max_image_count", "advanced_material_budget_max_image_count", int),
("max_estimated_cost", "advanced_material_budget_max_estimated_cost", float),
("per_request", "advanced_material_budget_per_request", float),
("per_image", "advanced_material_budget_per_image", float),
("per_1k_tokens", "advanced_material_budget_per_1k_tokens", float),
):
raw_value = _runtime_value(mapping, source_key, fallback=current_budget.get(target_key, _MISSING))
if raw_value is _MISSING:
continue
text_value = _runtime_text(raw_value)
if text_value == "" and target_key in {"max_task_count", "max_image_count", "max_estimated_cost"}:
_set_nested(patch, ("advanced_materials", "cost_budget", target_key), None)
continue
try:
normalized_value = converter(text_value or 0)
except (TypeError, ValueError):
continue
_set_nested(patch, ("advanced_materials", "cost_budget", target_key), normalized_value)
budget_price_key = _runtime_value(
mapping,
"advanced_material_budget_price_key",
fallback=current_budget.get("price_key", _MISSING),
)
if budget_price_key is not _MISSING:
_set_nested(
patch,
("advanced_materials", "cost_budget", "price_key"),
_runtime_text(budget_price_key),
)
# Multi-route assignments are first-class AstrBot plugin settings. Keep
# empty lists as explicit values so clearing a selection in the Web UI is
# persisted back to AstrBot instead of being restored from a stale runtime
# override on the next settings reload.
assignment_list_fields = {
"visual_review_routes": "model_visual_review_routes",
"cross_review_routes": "model_cross_review_routes",
"generation_cross_review_routes": "model_generation_cross_review_routes",
}
for target_key, source_key in assignment_list_fields.items():
value = _runtime_value(mapping, source_key)
if value is _MISSING:
continue
if isinstance(value, (list, tuple, set, frozenset)):
normalized = [str(item).strip() for item in value if str(item).strip()]
elif value in (None, ""):
normalized = []
else:
normalized = [str(value).strip()]
_set_nested(patch, ("model_assignments", target_key), normalized)
# Unlike legacy assignment fields, these routes intentionally accept an
# empty string. That value means "not configured" and still has to remain
# runtime-managed so a later UI selection can round-trip through
# AstrBotConfig.save_config().
for target_key, source_key in {
"generation_cross_review_primary": "model_generation_cross_review_primary",
"generation_cross_review_secondary": "model_generation_cross_review_secondary",
}.items():
value = _runtime_value(mapping, source_key)
if value is not _MISSING:
_set_nested(patch, ("model_assignments", target_key), _runtime_text(value))
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)
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]:
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:
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:
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(
_attr(request, "username"),
_current_quart_username(),
) or None
2026-07-06 10:00:18 +08:00
user_id = _first_text(
_attr(request, "user_id"),
2026-07-06 10:00:18 +08:00
username,
) 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",
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"),
_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)
if inspect.isawaitable(loader):
try:
loaded = await loader
except Exception:
continue
return _mapping_from_any(loaded)
payload = _mapping_from_any(loader)
if payload:
return payload
2026-07-06 10:00:18 +08:00
if not callable(loader):
continue
try:
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)
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 {}
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"),
}
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
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 ""
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:
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