"""Chat-facing orchestration built entirely on the existing ImageStudio API contract.""" from __future__ import annotations import hashlib import re from concurrent.futures import ThreadPoolExecutor, as_completed from pathlib import Path from typing import Any, Callable from adapters.astrbot_command_adapter import ChatCommandContext from backend.dto.chat_command_dto import SingleImageCommand from backend.services.chat_media_import_service import ChatMediaImportService from backend.services.chat_command_guard_service import ChatCommandGuardService from backend.services.cross_review_service import CrossReviewService from core.identity import RequestContext from core.chat_access_policy import chat_action_allowed from database.db_helper import load_config_payload from engines.character_flow import canonical_gradual_node_key Dispatcher = Callable[..., dict[str, Any]] class ChatWorkflowService: def __init__(self, dispatcher: Dispatcher, config_loader: Callable[[], dict[str, Any]] = load_config_payload, media_importer: ChatMediaImportService | None = None, guard: ChatCommandGuardService | None = None, cross_reviewer_factory: Callable[[], CrossReviewService] = CrossReviewService): self.dispatcher = dispatcher self.config_loader = config_loader self.media_importer = media_importer or ChatMediaImportService() self.guard = guard or ChatCommandGuardService() self.cross_reviewer_factory = cross_reviewer_factory def submit_single_image(self, command: SingleImageCommand, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat, "single_image") config = self.config_loader() active = self._data(self.dispatcher(ctx, "GET", "jobs", query={"status": "running", "page": 1, "page_size": 100})) active_items = active.get("items", []) if isinstance(active, dict) else [] self.guard.check_generation(config, chat, size=command.size, active_jobs=active_items) profile = self._resolve_profile(ctx, command.profile_ref, chat.user_id) workflow = self._data(self.dispatcher( ctx, "POST", f"profiles/{profile['profile_id']}/workflows", payload={ "workflow_type": "single_image", "display_name": f"聊天单图 · {command.prompt[:24]}", "mode": "quick", "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, }, )) workflow_data = workflow["workflow"] node = workflow["nodes"][0] self._data(self.dispatcher(ctx, "POST", f"workflows/{workflow_data['workflow_id']}/start", payload={})) idempotency_source = chat.message_id or f"{chat.message_origin}:{chat.user_id}:{command.prompt}" generation = self._data(self.dispatcher( ctx, "POST", f"nodes/{node['node_id']}/generate", payload={ "prompt": command.prompt, "negative_prompt": command.negative_prompt, "model_route": command.model_route, "size": command.size, "count": command.count, "entrypoint": _chat_entrypoint(chat.platform), "platform": chat.platform, "user_id": chat.user_id, "group_id": chat.group_id, "translation_consent": command.translation_consent, "content_permissions": _content_permissions(config, chat), "idempotency_key": "chat_" + hashlib.sha256(idempotency_source.encode("utf-8")).hexdigest()[:32], "metadata": { "source": "astrbot_chat", "platform": chat.platform, "message_origin": chat.message_origin, "user_id": chat.user_id, "group_id": chat.group_id, }, }, )) images = [ self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) for item in generation.get("images", []) if item.get("image_id") ] self.guard.record(chat, "single_image", target_id=generation.get("task_id"), details={"size": command.size, "count": command.count}) return { "profile": profile, "workflow": workflow_data, "node": node, "generation": generation, "images": images, } def list_node_images(self, node_id: str, chat: ChatCommandContext) -> list[dict[str, Any]]: ctx = self._request_context(chat) self._owned_node(ctx, node_id) return self._data( self.dispatcher( ctx, "GET", f"nodes/{node_id}/images", query={"include_archived": False}, ) ) def list_jobs(self, chat: ChatCommandContext, *, task_id: str | None = None) -> Any: ctx = self._request_context(chat, "single_image") if task_id: return self._owned_task(ctx, task_id) profiles = self._owned_profiles(ctx) items: list[dict[str, Any]] = [] for profile in profiles: page = self._data( self.dispatcher( ctx, "GET", "jobs", query={"profile_id": profile["profile_id"], "page": 1, "page_size": 10}, ) ) if isinstance(page, dict): items.extend(item for item in page.get("items", []) if isinstance(item, dict)) items.sort(key=lambda item: str(item.get("created_at") or ""), reverse=True) return {"items": items[:10], "total": len(items)} def cancel_job(self, chat: ChatCommandContext, task_id: str) -> Any: ctx = self._request_context(chat, "single_image") self._owned_task(ctx, task_id) return self._data(self.dispatcher(ctx, "POST", f"jobs/{task_id}/cancel", payload={})) def retry_job(self, chat: ChatCommandContext, task_id: str) -> Any: ctx = self._request_context(chat, "single_image") self._owned_task(ctx, task_id) return self._data(self.dispatcher(ctx, "POST", f"jobs/{task_id}/retry", payload={})) def create_quick_profile_draft(self, description: str, chat: ChatCommandContext) -> dict[str, Any]: text = str(description or "").strip() if not text: raise ValueError("请提供角色名称和描述,例如:/yp 快速角色 米卡 银发蓝眼的冷静少女") questionnaire = _quick_questionnaire(text) return self._data(self.dispatcher(self._request_context(chat), "POST", "profiles/quick-draft", payload={ "questionnaire": questionnaire, })) def save_quick_profile_draft(self, draft: dict[str, Any], chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat, "quick_profile") saved = self._data(self.dispatcher(ctx, "POST", "profiles/quick-draft/save", payload={ **draft, "draft": draft, # ``quick_profile`` is the questionnaire/planning flow. Chat # quick characters must reuse the existing four-image fast flow. "create_workflow": False, "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, })) profile = saved["profile"] detail = self._data( self.dispatcher( ctx, "POST", f"profiles/{profile['profile_id']}/workflows", payload={ "workflow_type": "character_fast", "display_name": f"{profile['name']} 快速角色四图", "mode": "quick", "status": "draft", "metadata": { "source": "astrbot_chat", "message_origin": chat.message_origin, "quick_profile_draft_id": saved.get("draft_id"), }, }, ) ) execution = self._data( self.dispatcher( ctx, "POST", f"workflows/{detail['workflow']['workflow_id']}/execute-character", payload={}, ) ) return { **saved, "workflow": execution.get("workflow") or detail["workflow"], "nodes": execution.get("nodes") or detail.get("nodes", []), "execution": execution, } def generate_quick_character(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]: """Generate the four independent fast-character nodes in parallel. This method is intended to run in a background thread from ``main``. Every provider request still goes through ``nodes/{id}/generate`` so Web and chat share queue records, identity locks and model routing. """ ctx = self._request_context(chat, "quick_profile") detail = self._owned_workflow(ctx, workflow_id) workflow = detail["workflow"] if workflow.get("workflow_type") != "character_fast": raise ValueError("快速角色只能执行 character_fast 四图工作流") branch = str(workflow.get("current_branch") or "main") nodes = [ item for item in detail.get("nodes", []) if isinstance(item, dict) and str(item.get("branch_name") or "main") == branch and item.get("node_type") in {"generation", "single_image"} ] if len(nodes) != 4: raise ValueError(f"快速角色四图工作流节点数量异常:{len(nodes)}") results: list[dict[str, Any]] = [] failures: list[dict[str, str]] = [] with ThreadPoolExecutor(max_workers=4, thread_name_prefix="imagestudio-chat-fast") as executor: futures = { executor.submit(self.generate_node, str(node["node_id"]), chat): node for node in nodes } for future in as_completed(futures): node = futures[future] try: generated = future.result() results.append({"node": node, "generation": generated}) except Exception as exc: failures.append( { "node_id": str(node.get("node_id") or ""), "node_key": str(node.get("node_key") or ""), "message": " ".join(str(exc).split())[:500], } ) order = {str(item["node_id"]): index for index, item in enumerate(nodes)} results.sort(key=lambda item: order.get(str(item["node"].get("node_id")), 999)) images = [ image for item in results for image in item["generation"].get("images", []) if isinstance(image, dict) ] return { "workflow": workflow, "nodes": nodes, "results": results, "failures": failures, "images": images, "succeeded": len(results), "failed": len(failures), } def create_or_resume_character_workflow(self, profile_ref: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat, "character_workflow") profile = self._resolve_required_profile(ctx, profile_ref) workflows = self._data(self.dispatcher(ctx, "GET", f"profiles/{profile['profile_id']}/workflows", query={})) active = next((item for item in workflows if item.get("workflow_type") == "character_gradual" and item.get("status") not in {"completed", "cancelled", "archived"}), None) if active: detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{active['workflow_id']}", query={})) return {"profile": profile, **detail, "resumed": True} detail = self._data(self.dispatcher(ctx, "POST", f"profiles/{profile['profile_id']}/workflows", payload={ "workflow_type": "character_gradual", "display_name": f"{profile['name']} 详细角色工作流", "mode": "gradual", "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, })) return {"profile": profile, **detail, "resumed": False} def workflow_detail(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]: return self._owned_workflow(self._request_context(chat), workflow_id) def chat_status(self, chat: ChatCommandContext, workflow_id: str = "") -> dict[str, Any]: """Return the newest owned detailed workflow and its next chat action.""" ctx = self._request_context(chat) detail: dict[str, Any] | None = None if str(workflow_id or "").strip(): detail = self._owned_workflow(ctx, str(workflow_id).strip()) else: workflows: list[dict[str, Any]] = [] for profile in self._owned_profiles(ctx): items = self._data( self.dispatcher( ctx, "GET", f"profiles/{profile['profile_id']}/workflows", query={}, ) ) workflows.extend( item for item in items if isinstance(item, dict) and item.get("workflow_type") == "character_gradual" and item.get("status") not in {"cancelled", "archived"} ) workflows.sort( key=lambda item: str(item.get("updated_at") or item.get("created_at") or ""), reverse=True, ) if workflows: detail = self._owned_workflow(ctx, str(workflows[0]["workflow_id"])) if detail is None: return { "workflow": None, "branch_name": None, "current_node": None, "current_round": None, "next_action": "使用 /yp 工作流 <角色名> 创建或继续详细工作流", } workflow = detail["workflow"] branch = str(workflow.get("current_branch") or "main") branch_nodes = self._branch_nodes(detail) current = next( (item for item in branch_nodes if item.get("node_id") == workflow.get("current_node_id")), None, ) or next( (item for item in branch_nodes if item.get("status") not in {"completed", "selected", "skipped"}), None, ) latest_round = None if current and current.get("node_type") in {"generation", "single_image"}: rounds = self._data( self.dispatcher( ctx, "GET", f"nodes/{current['node_id']}/rounds", query={"include_legacy": True}, ) ) items = rounds.get("items", []) if isinstance(rounds, dict) else [] latest_round = items[0] if items else None return { "workflow": workflow, "branch_name": branch, "current_node": current, "current_round": latest_round, "next_action": _workflow_next_action(current, latest_round), } def create_round( self, node_id: str, chat: ChatCommandContext, *, count: int = 4, prompt: str = "", model_route: str = "", ) -> dict[str, Any]: ctx = self._request_context(chat) node = self._owned_node(ctx, node_id) detail = self._owned_workflow(ctx, str(node["workflow_id"])) if detail["workflow"].get("workflow_type") != "character_gradual": raise ValueError("候选轮次只用于详细角色工作流") payload: dict[str, Any] = { "count": int(count), "idempotency_key": self._idempotency(chat, "round", node_id, f"{count}:{prompt}:{model_route}"), "chat_notification": _chat_notification(chat), "metadata": { "source": "astrbot_chat", "reply_target": _chat_reply_target(chat), "notify_on_terminal": True, }, } if str(prompt or "").strip(): payload["prompt"] = str(prompt).strip() if str(model_route or "").strip(): payload["model_route"] = str(model_route).strip() created = self._data( self.dispatcher(ctx, "POST", f"nodes/{node_id}/rounds", payload=payload) ) return created def round_detail(self, round_id: str, chat: ChatCommandContext) -> dict[str, Any]: return self._owned_round(self._request_context(chat), round_id) def submit_round_feedback( self, round_id: str, feedback_text: str, chat: ChatCommandContext, ) -> dict[str, Any]: text = str(feedback_text or "").strip() if not text: raise ValueError("请提供候选反馈,例如:1、2喜欢,3严格拒绝") ctx = self._request_context(chat) self._owned_round(ctx, round_id) return self._data( self.dispatcher( ctx, "POST", f"rounds/{round_id}/feedback", payload={ "feedback_text": text, "idempotency_key": self._idempotency(chat, "feedback", round_id, text), }, ) ) def create_next_round( self, parent_round_id: str, chat: ChatCommandContext, *, count: int | None = None, ) -> dict[str, Any]: ctx = self._request_context(chat) parent = self._owned_round(ctx, parent_round_id) payload: dict[str, Any] = { "idempotency_key": self._idempotency(chat, "next-round", parent_round_id, str(count or "")), "chat_notification": _chat_notification(chat), } if count is not None: payload["count"] = int(count) created = self._data( self.dispatcher(ctx, "POST", f"rounds/{parent_round_id}/next", payload=payload) ) if created.get("round", {}).get("node_id") != parent.get("round", {}).get("node_id"): raise ValueError("下一轮返回了不一致的工作流节点") return created def confirm_round_candidate( self, round_id: str, candidate_ref: str, chat: ChatCommandContext, ) -> dict[str, Any]: ctx = self._request_context(chat) detail = self._owned_round(ctx, round_id) candidate = _resolve_round_candidate(detail, candidate_ref, require_succeeded=True) return self._data( self.dispatcher( ctx, "POST", f"rounds/{round_id}/confirm", payload={ "candidate_id": candidate["candidate_id"], "idempotency_key": self._idempotency( chat, "confirm-round", round_id, str(candidate["candidate_id"]), ), }, ) ) def decide_generation_cross_review( self, round_id: str, candidate_ref: str, decision: str, chat: ChatCommandContext, ) -> dict[str, Any]: normalized = str(decision or "review").strip().lower() normalized = {"审核": "review", "审查": "review", "跳过": "skip"}.get(normalized, normalized) if normalized not in {"review", "skip"}: raise ValueError("审查动作必须是审核或跳过") ctx = self._request_context(chat) detail = self._owned_round(ctx, round_id) candidate = _resolve_round_candidate(detail, candidate_ref, require_succeeded=True) return self._data( self.dispatcher( ctx, "POST", f"rounds/{round_id}/generation-cross-review", payload={ "decision": normalized, "candidate_id": candidate["candidate_id"], "idempotency_key": self._idempotency( chat, f"cross-review-{normalized}", round_id, str(candidate["candidate_id"]), ), "chat_notification": _chat_notification(chat), }, ) ) def regenerate_cross_review( self, round_id: str, candidate_refs: list[str], chat: ChatCommandContext, *, prompt_patch: str = "", ) -> dict[str, Any]: ctx = self._request_context(chat) detail = self._owned_round(ctx, round_id) candidates = [ _resolve_round_candidate(detail, value, require_succeeded=True) for value in candidate_refs ] candidate_ids = list(dict.fromkeys(str(item["candidate_id"]) for item in candidates)) if not candidate_ids: raise ValueError("请至少选择一个交叉审查候选") return self._data( self.dispatcher( ctx, "POST", f"rounds/{round_id}/generation-cross-review/regenerate", payload={ "candidate_ids": candidate_ids, "prompt_patch": str(prompt_patch or "").strip(), "idempotency_key": self._idempotency( chat, "cross-review-regenerate", round_id, ",".join(candidate_ids) + ":" + str(prompt_patch or ""), ), "chat_notification": _chat_notification(chat), }, ) ) def approve_cross_review( self, round_id: str, candidate_ref: str, chat: ChatCommandContext, ) -> dict[str, Any]: ctx = self._request_context(chat) detail = self._owned_round(ctx, round_id) candidate = _resolve_round_candidate(detail, candidate_ref, require_succeeded=True) return self._data( self.dispatcher( ctx, "POST", f"rounds/{round_id}/generation-cross-review/approve", payload={ "candidate_id": candidate["candidate_id"], "idempotency_key": self._idempotency( chat, "cross-review-approve", round_id, str(candidate["candidate_id"]), ), }, ) ) def get_node_materials(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) node = self._owned_node(ctx, node_id) return self._data( self.dispatcher( ctx, "GET", f"nodes/{node_id}/material-bindings", query={ "workflow_id": node["workflow_id"], "branch_name": node.get("branch_name") or "main", "node_id": node_id, "return_view": "chat", }, ) ) def save_node_materials( self, node_id: str, material_ids: list[str], chat: ChatCommandContext, ) -> dict[str, Any]: ctx = self._request_context(chat) node = self._owned_node(ctx, node_id) normalized = list(dict.fromkeys(str(value).strip() for value in material_ids if str(value).strip())) return self._data( self.dispatcher( ctx, "PUT", f"nodes/{node_id}/material-bindings", payload={ "selected_material_ids": normalized, "navigation_context": { "workflow_id": node["workflow_id"], "branch_name": node.get("branch_name") or "main", "node_id": node_id, "return_view": "chat", }, }, ) ) def list_branches(self, workflow_id: str, chat: ChatCommandContext) -> list[dict[str, Any]]: ctx = self._request_context(chat) self._owned_workflow(ctx, workflow_id) return self._data( self.dispatcher(ctx, "GET", f"workflows/{workflow_id}/branches", query={}) ) def create_branch( self, workflow_id: str, branch_name: str, base_node_id: str, chat: ChatCommandContext, ) -> dict[str, Any]: ctx = self._request_context(chat) detail = self._owned_workflow(ctx, workflow_id) base_node = self._owned_node(ctx, base_node_id) if base_node.get("workflow_id") != workflow_id: raise ValueError("分支切点不属于指定工作流") base_branch = str(base_node.get("branch_name") or detail["workflow"].get("current_branch") or "main") return self._data( self.dispatcher( ctx, "POST", f"workflows/{workflow_id}/branches", payload={ "branch_name": str(branch_name or "").strip(), "base_branch_name": base_branch, "base_node_id": base_node_id, }, ) ) def switch_branch(self, workflow_id: str, branch_name: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) self._owned_workflow(ctx, workflow_id) return self._data( self.dispatcher( ctx, "POST", f"workflows/{workflow_id}/switch-branch", payload={"branch_name": str(branch_name or "").strip()}, ) ) def finalize_profile_card( self, workflow_id: str, chat: ChatCommandContext, *, persona_document: str = "", ) -> dict[str, Any]: ctx = self._request_context(chat) detail = self._owned_workflow(ctx, workflow_id) workflow = detail["workflow"] branch_nodes = self._branch_nodes(detail) selected_by_stage = { canonical_gradual_node_key(str(node.get("node_key") or "")): str(node.get("selected_image_id") or "") for node in branch_nodes if node.get("selected_image_id") } profile = self._owned_profile(ctx, str(workflow["profile_id"])) persona = str(persona_document or "").strip() or _profile_persona_document(profile) assets = { "avatar": selected_by_stage.get("headshot"), "persona_image": selected_by_stage.get("design_sheet") or selected_by_stage.get("turnaround"), "standing": selected_by_stage.get("full_body"), "pv": selected_by_stage.get("style_lock"), } missing = [role for role, image_id in assets.items() if not image_id] if missing: raise ValueError("档案卡缺少已确认资产:" + "、".join(missing)) return self._data( self.dispatcher( ctx, "POST", f"workflows/{workflow_id}/finalize-card", payload={ "persona_document": persona, "assets": assets, "idempotency_key": self._idempotency(chat, "profile-card", workflow_id, persona), "metadata": {"source": "astrbot_chat"}, }, ) ) def list_profile_cards(self, profile_ref: str, chat: ChatCommandContext) -> list[dict[str, Any]]: ctx = self._request_context(chat) profile = self._resolve_required_profile(ctx, profile_ref) return self._data( self.dispatcher(ctx, "GET", f"profiles/{profile['profile_id']}/profile-cards", query={}) ) def generate_node(self, node_id: str, chat: ChatCommandContext, *, prompt: str = "") -> dict[str, Any]: config = self.config_loader() payload = { **({"prompt": prompt} if prompt else {}), "entrypoint": _chat_entrypoint(chat.platform), "platform": chat.platform, "user_id": chat.user_id, "group_id": chat.group_id, "content_permissions": _content_permissions(config, chat), } ctx = self._request_context(chat) node = self._owned_node(ctx, node_id) workflow_detail = self._owned_workflow(ctx, str(node["workflow_id"])) if workflow_detail["workflow"].get("workflow_type") == "character_gradual": # Detailed workflow generation is round based. Never fall back to # the legacy synchronous endpoint, which merges four candidates # into one task/timeout and may auto-adopt the first image. return self.create_round(node_id, chat, count=4, prompt=prompt) payload["metadata"] = { "source": "astrbot_chat", "reply_target": _chat_reply_target(chat), "notify_on_terminal": True, } result = self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/generate", payload=payload)) result["images"] = [ self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) for item in result.get("images", []) if item.get("image_id") ] return result def retry_node(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) self._owned_node(ctx, node_id) return self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/retry", payload={})) def complete_node(self, node_id: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) self._owned_node(ctx, node_id) return self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/complete", payload={})) def next_workflow_step(self, workflow_id: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) detail = self._owned_workflow(ctx, workflow_id) workflow = detail["workflow"] nodes = self._branch_nodes(detail) current = next((item for item in nodes if item.get("node_id") == workflow.get("current_node_id")), None) candidate = current if current and current.get("status") not in {"completed", "selected", "skipped"} else next( (item for item in nodes if item.get("status") in {"pending", "draft", "failed", "completed"} and not item.get("selected_image_id")), None, ) if candidate is None: return {"completed": True, "workflow": workflow} if str(candidate.get("branch_name") or "main") != str(workflow.get("current_branch") or "main"): raise ValueError("当前节点与活动分支不一致,请先刷新工作流状态") node_key = canonical_gradual_node_key(str(candidate.get("node_key") or "")) if node_key == "profile_card": return { "completed": False, "workflow": workflow, "node": candidate, "requires_profile_card": True, "next_action": f"/yp 档案卡 {workflow_id}", } if candidate.get("node_type") not in {"generation", "single_image"}: # Planning/reference stages need their actual content saved before # completion. A generic chat 'next' command must never fabricate # an empty successful node. return { "completed": False, "workflow": workflow, "node": candidate, "requires_node_input": True, "next_action": f"完成 {candidate.get('title') or candidate.get('node_key')} 后使用 /yp 完成节点 {candidate['node_id']}", } if workflow.get("workflow_type") == "character_gradual": generation = self.create_round(str(candidate["node_id"]), chat, count=4) else: generation = self._data(self.dispatcher(ctx, "POST", f"nodes/{candidate['node_id']}/generate", payload={ "entrypoint": _chat_entrypoint(chat.platform), "platform": chat.platform, "user_id": chat.user_id, "group_id": chat.group_id, "content_permissions": _content_permissions(self.config_loader(), chat), "metadata": { "source": "astrbot_chat", "reply_target": _chat_reply_target(chat), "notify_on_terminal": True, }, })) return {"completed": False, "workflow": workflow, "node": candidate, "generation": generation} def select_node_image(self, node_id: str, image_id: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) node = self._owned_node(ctx, node_id) self._owned_image(ctx, image_id) workflow = self._owned_workflow(ctx, str(node["workflow_id"]))["workflow"] if workflow.get("workflow_type") == "character_gradual": round_detail, candidate = self._round_candidate_for_image(ctx, node_id, image_id) updated = self._data( self.dispatcher( ctx, "POST", f"rounds/{round_detail['round']['round_id']}/feedback", payload={"draft_final_candidate_id": candidate["candidate_id"]}, ) ) return { "selection": updated, "image": candidate.get("image"), "node": node, "image_id": image_id, "round_id": round_detail["round"]["round_id"], "candidate_id": candidate["candidate_id"], "confirmation_required": True, } selected = self._data(self.dispatcher(ctx, "POST", f"nodes/{node_id}/select-image", payload={"image_id": image_id})) image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={})) node = self._data(self.dispatcher(ctx, "GET", f"nodes/{node_id}", query={})) return { "selection": selected, "image": image, "node": node, "image_id": image_id, "confirmation_required": True, } def confirm_node_image(self, node_id: str, image_id: str, chat: ChatCommandContext) -> dict[str, Any]: """Adopt a previously selected candidate and advance through the shared backend path.""" ctx = self._request_context(chat) node = self._owned_node(ctx, node_id) self._owned_image(ctx, image_id) detail = self._owned_workflow(ctx, node["workflow_id"]) workflow = detail["workflow"] if workflow.get("workflow_type") == "character_gradual": round_detail, candidate = self._round_candidate_for_image(ctx, node_id, image_id) confirmed = self._data( self.dispatcher( ctx, "POST", f"rounds/{round_detail['round']['round_id']}/confirm", payload={ "candidate_id": candidate["candidate_id"], "idempotency_key": self._idempotency( chat, "confirm-round-image", round_detail["round"]["round_id"], candidate["candidate_id"], ), }, ) ) return { "history": confirmed.get("history"), "image": candidate.get("image"), "node": confirmed.get("node") or node, "next_node": confirmed.get("next_node"), "image_id": image_id, "round_id": round_detail["round"]["round_id"], "candidate_id": candidate["candidate_id"], } branch = workflow.get("current_branch") or node.get("branch_name") or "main" branch_nodes = sorted( (item for item in detail.get("nodes", []) if (item.get("branch_name") or "main") == branch), key=lambda item: (int(item.get("sort_order") or 0), str(item.get("node_id") or "")), ) next_node = next( (item for item in branch_nodes if int(item.get("sort_order") or 0) > int(node.get("sort_order") or 0)), None, ) adopted = self._data( self.dispatcher( ctx, "POST", f"nodes/{node_id}/adopt-image", payload={ "image_id": image_id, "title": f"聊天确认候选 · {node.get('title') or node.get('node_key') or node_id}", "metadata": { "source": "astrbot_chat_candidate_confirm", "next_backend_node_id": next_node.get("node_id") if next_node else None, "source_ui_node_id": node.get("node_key"), "next_ui_node_id": next_node.get("node_key") if next_node else None, "handoff_role": "next_stage_input", }, }, ) ) image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={})) if node.get("node_key") in {"headshot", "quick_avatar"} and image.get("profile_id") and image.get("image_uri"): self._data( self.dispatcher( ctx, "PUT", f"profiles/{image['profile_id']}", payload={"avatar_image_uri": image["image_uri"]}, ) ) return { "history": adopted, "image": image, "node": node, "next_node": next_node, "image_id": image_id, } def select_node_image_by_number(self, node_id: str, number: int, chat: ChatCommandContext) -> dict[str, Any]: images = self.list_node_images(node_id, chat) if number < 1 or number > len(images): raise ValueError(f"图片序号必须在 1 到 {len(images)} 之间") return self.select_node_image(node_id, images[number - 1]["image_id"], chat) def review(self, target_id: str, chat: ChatCommandContext) -> dict[str, Any]: prefix = "workflows" if target_id.startswith(("wf_", "workflow_")) else "nodes" ctx = self._request_context(chat) if prefix == "workflows": self._owned_workflow(ctx, target_id) else: self._owned_node(ctx, target_id) rules = self._data(self.dispatcher(ctx, "GET", f"{prefix}/{target_id}/review", query={})) node_ids = [target_id] if prefix == "workflows": detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{target_id}", query={})) node_ids = [item["node_id"] for item in detail.get("nodes", []) if item.get("status") == "completed"] model_reviews = {node_id: self.cross_reviewer_factory().review_node(node_id) for node_id in node_ids} return {"rules": rules, "model_reviews": model_reviews} def hires_fix(self, image_id: str, size: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) image = self._owned_image(ctx, image_id) workflow = self._data(self.dispatcher( ctx, "POST", f"profiles/{image['profile_id']}/workflows", payload={ "workflow_type": "single_image", "display_name": f"高清修复 · {image_id}", "mode": "quick", "metadata": {"source": "astrbot_chat_hires", "source_image_id": image_id}, }, )) workflow_data = workflow["workflow"] node = workflow["nodes"][0] self._data(self.dispatcher(ctx, "POST", f"workflows/{workflow_data['workflow_id']}/start", payload={})) config = load_config_payload() assignments = config.get("model_assignments") if isinstance(config.get("model_assignments"), dict) else {} generation = self._data(self.dispatcher(ctx, "POST", f"nodes/{node['node_id']}/generate", payload={ "prompt": "high resolution restoration, preserve identity, composition, clothing and original style", "negative_prompt": "identity change, composition change, clothing change, oversharpening, artifacts", "model_route": assignments.get("hires_fix"), "size": size, "count": 1, "input_images": [{"image_uri": image["image_uri"]}], "metadata": { "source": "astrbot_chat_hires", "source_image_id": image_id, "reply_target": _chat_reply_target(chat), "notify_on_terminal": True, }, })) images = [self._data(self.dispatcher(ctx, "GET", f"images/{item['image_id']}", query={})) for item in generation.get("images", [])] return {"source_image": image, "workflow": workflow_data, "node": node, "generation": generation, "images": images} def import_material(self, image_reference: str, category_ref: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) categories = self._data(self.dispatcher(ctx, "GET", "material-categories", query={})) category = next((item for item in categories if item.get("category_id") == category_ref or item.get("name") == category_ref), None) if category is None: raise ValueError(f"未找到素材分类:{category_ref}") uri, filename, size_bytes = self.media_importer.import_image(image_reference) material = self._data(self.dispatcher(ctx, "POST", "materials/upload", payload={ "category_id": category["category_id"], "display_name": Path(filename).stem, "image_uri": uri, "thumbnail_uri": uri, "filename": filename, "size_bytes": size_bytes, "metadata": {"source": "astrbot_chat", "message_origin": chat.message_origin}, })) recognized = self._data(self.dispatcher(ctx, "POST", f"materials/{material['material_id']}/recognize", payload={})) profiles = self._data(self.dispatcher(ctx, "GET", "profiles", query={"page": 1, "page_size": 20})) return {"category": category, "material": recognized, "profiles": profiles.get("items", []) if isinstance(profiles, dict) else []} def confirm_material(self, material_id: str, chat: ChatCommandContext) -> dict[str, Any]: return self._data(self.dispatcher(self._request_context(chat), "POST", f"materials/{material_id}/confirm", payload={})) def re_recognize_material(self, material_id: str, chat: ChatCommandContext) -> dict[str, Any]: return self._data(self.dispatcher(self._request_context(chat), "POST", f"materials/{material_id}/re-recognize", payload={})) def add_material_to_wardrobe(self, material_id: str, profile_ref: str, wardrobe_category: str, chat: ChatCommandContext) -> dict[str, Any]: ctx = self._request_context(chat) profile = self._resolve_required_profile(ctx, profile_ref) return self._data(self.dispatcher(ctx, "POST", f"profiles/{profile['profile_id']}/wardrobe/import-material", payload={ "material_id": material_id, "wardrobe_category": wardrobe_category, })) def _resolve_profile(self, ctx: RequestContext, profile_ref: str | None, user_id: str) -> dict[str, Any]: keyword = profile_ref or f"聊天单图 {user_id}" result = self._data(self.dispatcher(ctx, "GET", "profiles", query={"keyword": keyword, "page": 1, "page_size": 30})) items = result.get("items", []) if isinstance(result, dict) else [] if profile_ref: exact = next((item for item in items if item.get("profile_id") == profile_ref or item.get("name") == profile_ref), None) if exact: return exact raise ValueError(f"未找到角色:{profile_ref}") if items: return items[0] return self._data(self.dispatcher(ctx, "POST", "profiles", payload={ "name": f"聊天单图 {user_id}", "profile_type": "quick", "description": "AstrBot 聊天单图专用角色容器", "metadata": {"source": "astrbot_chat", "system_container": True}, })) def _resolve_required_profile(self, ctx: RequestContext, profile_ref: str) -> dict[str, Any]: text = str(profile_ref or "").strip() if not text: raise ValueError("请提供角色名称或角色 ID") result = self._data(self.dispatcher(ctx, "GET", "profiles", query={"keyword": text, "page": 1, "page_size": 30})) items = result.get("items", []) if isinstance(result, dict) else [] profile = next((item for item in items if item.get("profile_id") == text or item.get("name") == text), None) if profile is None: raise ValueError(f"未找到角色:{text}") return profile def _owned_profiles(self, ctx: RequestContext) -> list[dict[str, Any]]: result = self._data( self.dispatcher( ctx, "GET", "profiles", query={"page": 1, "page_size": 100}, ) ) if not isinstance(result, dict): return [] return [item for item in result.get("items", []) if isinstance(item, dict)] def _owned_profile(self, ctx: RequestContext, profile_id: str) -> dict[str, Any]: profile = self._data(self.dispatcher(ctx, "GET", f"profiles/{profile_id}", query={})) if not isinstance(profile, dict): raise ValueError("角色档案不存在或无权访问") return profile def _owned_workflow(self, ctx: RequestContext, workflow_id: str) -> dict[str, Any]: detail = self._data(self.dispatcher(ctx, "GET", f"workflows/{workflow_id}", query={})) if not isinstance(detail, dict) or not isinstance(detail.get("workflow"), dict): raise ValueError("工作流不存在或无权访问") workflow = detail["workflow"] profile_id = str(workflow.get("profile_id") or "").strip() if not profile_id: raise ValueError("工作流缺少角色归属信息") self._owned_profile(ctx, profile_id) return detail def _owned_node(self, ctx: RequestContext, node_id: str) -> dict[str, Any]: node = self._data(self.dispatcher(ctx, "GET", f"nodes/{node_id}", query={})) if not isinstance(node, dict): raise ValueError("工作流节点不存在或无权访问") workflow_id = str(node.get("workflow_id") or "").strip() if not workflow_id: raise ValueError("工作流节点缺少工作流归属信息") detail = self._owned_workflow(ctx, workflow_id) if not any( isinstance(item, dict) and str(item.get("node_id") or "") == node_id for item in detail.get("nodes", []) ): raise ValueError("工作流节点不存在或无权访问") return node def _owned_image(self, ctx: RequestContext, image_id: str) -> dict[str, Any]: image = self._data(self.dispatcher(ctx, "GET", f"images/{image_id}", query={})) if not isinstance(image, dict): raise ValueError("图片不存在或无权访问") workflow_id = str(image.get("workflow_id") or "").strip() profile_id = str(image.get("profile_id") or "").strip() if workflow_id: detail = self._owned_workflow(ctx, workflow_id) workflow_profile_id = str(detail["workflow"].get("profile_id") or "").strip() if profile_id and workflow_profile_id != profile_id: raise ValueError("图片归属链不一致") elif profile_id: self._owned_profile(ctx, profile_id) else: raise ValueError("图片缺少角色或工作流归属信息") return image def _owned_task(self, ctx: RequestContext, task_id: str) -> dict[str, Any]: task = self._data(self.dispatcher(ctx, "GET", f"jobs/{task_id}", query={})) if not isinstance(task, dict): raise ValueError("任务不存在或无权访问") profile_id = str(task.get("profile_id") or "").strip() workflow_id = str(task.get("workflow_id") or "").strip() node_id = str(task.get("node_id") or "").strip() if profile_id: self._owned_profile(ctx, profile_id) elif workflow_id: self._owned_workflow(ctx, workflow_id) elif node_id: self._owned_node(ctx, node_id) else: raise ValueError("任务缺少角色、工作流或节点归属信息") return task def _owned_round(self, ctx: RequestContext, round_id: str) -> dict[str, Any]: detail = self._data(self.dispatcher(ctx, "GET", f"rounds/{round_id}", query={})) if not isinstance(detail, dict) or not isinstance(detail.get("round"), dict): raise ValueError("候选轮次不存在或无权访问") round_record = detail["round"] node_id = str(round_record.get("node_id") or "").strip() workflow_id = str(round_record.get("workflow_id") or "").strip() if not node_id or not workflow_id: raise ValueError("候选轮次缺少节点或工作流归属信息") node = self._owned_node(ctx, node_id) if str(node.get("workflow_id") or "") != workflow_id: raise ValueError("候选轮次归属链不一致") return detail def _round_candidate_for_image( self, ctx: RequestContext, node_id: str, image_id: str, ) -> tuple[dict[str, Any], dict[str, Any]]: rounds = self._data( self.dispatcher( ctx, "GET", f"nodes/{node_id}/rounds", query={"include_legacy": True}, ) ) for detail in rounds.get("items", []) if isinstance(rounds, dict) else []: if not isinstance(detail, dict): continue for candidate in detail.get("candidates", []): image = candidate.get("image") if isinstance(candidate, dict) else None if isinstance(image, dict) and str(image.get("image_id") or "") == image_id: return detail, candidate raise ValueError("图片不属于该节点的任何候选轮次") @staticmethod def _branch_nodes(detail: dict[str, Any]) -> list[dict[str, Any]]: workflow = detail.get("workflow") if isinstance(detail.get("workflow"), dict) else {} branch = str(workflow.get("current_branch") or "main") return sorted( [ item for item in detail.get("nodes", []) if isinstance(item, dict) and str(item.get("branch_name") or "main") == branch ], key=lambda item: (int(item.get("sort_order") or 0), str(item.get("node_id") or "")), ) @staticmethod def _idempotency( chat: ChatCommandContext, action: str, target_id: str, content: str = "", ) -> str: source = "|".join( [ str(action or ""), str(target_id or ""), str(chat.platform or ""), str(chat.message_origin or ""), str(chat.message_id or ""), str(chat.user_id or ""), str(content or ""), ] ) return "chat_" + hashlib.sha256(source.encode("utf-8")).hexdigest()[:48] def _request_context(self, chat: ChatCommandContext, action: str = "character_workflow") -> RequestContext: config = self.config_loader() if not chat_action_allowed(config, action, group_id=chat.group_id, user_id=chat.user_id): try: self.guard.record(chat, action, allowed=False, details={"reason": "allowlist"}) except Exception: pass raise ValueError("当前群聊或用户不满足聊天白名单规则") return RequestContext.from_astrbot( username=chat.user_id or "chat-user", user_id=chat.user_id or "chat-user", permissions={"can_write", "can_retry_tasks", "can_manage_materials"}, source=f"astrbot_chat:{chat.platform}", platform=chat.platform or "astrbot", session_key=chat.message_origin or None, ) @staticmethod def _data(response: dict[str, Any]) -> Any: if not response.get("ok"): raise ValueError(str(response.get("message") or response.get("error_code") or "ImageStudio 请求失败")) return response.get("data") def _content_permissions(config: dict[str, Any], chat: ChatCommandContext) -> dict[str, Any]: access = config.get("chat_access") if isinstance(config.get("chat_access"), dict) else {} adult_users = _id_set(access.get("adult_user_allowlist")) adult_groups = _id_set(access.get("adult_group_allowlist")) return { "adult_user_allowed": bool(chat.user_id and chat.user_id in adult_users), "adult_group_allowed": bool(not chat.group_id or chat.group_id in adult_groups), "quota_allowed": True, } def _chat_entrypoint(platform: str) -> str: value = str(platform or "").lower() if "qq" in value or "onebot" in value: return "qq" if "telegram" in value: return "telegram" if "discord" in value: return "discord" return "unknown" def _chat_reply_target(chat: ChatCommandContext) -> dict[str, str | None]: """Persist only the stable fields needed for a terminal task callback.""" return { "platform": str(chat.platform or "unknown"), "message_origin": str(chat.message_origin or ""), "message_id": str(chat.message_id or ""), "user_id": str(chat.user_id or ""), "group_id": str(chat.group_id) if chat.group_id else None, } def _chat_notification(chat: ChatCommandContext) -> dict[str, Any]: return { "notify_on_terminal": True, "reply_target": _chat_reply_target(chat), "source": "astrbot_chat", } def _resolve_round_candidate( detail: dict[str, Any], candidate_ref: str, *, require_succeeded: bool = False, ) -> dict[str, Any]: reference = str(candidate_ref or "").strip() if not reference: raise ValueError("请提供候选编号,例如 1 或 TX-01-01") candidates = [item for item in detail.get("candidates", []) if isinstance(item, dict)] normalized = reference.upper() selected = next( ( item for item in candidates if reference in { str(item.get("candidate_id") or ""), str((item.get("candidate") or {}).get("candidate_id") or ""), } or normalized == str(item.get("display_code") or "").upper() ), None, ) if selected is None and reference.isdigit(): index = int(reference) selected = next( (item for item in candidates if int(item.get("display_index") or 0) == index), None, ) if selected is None: allowed = "、".join(str(item.get("display_code") or "") for item in candidates) raise ValueError(f"未找到候选 {reference};可选:{allowed or '暂无'}") candidate = selected.get("candidate") if isinstance(selected.get("candidate"), dict) else {} candidate_id = str(selected.get("candidate_id") or candidate.get("candidate_id") or "").strip() generation_status = str(candidate.get("generation_status") or "").strip() image = selected.get("image") if isinstance(selected.get("image"), dict) else None if require_succeeded and (generation_status != "succeeded" or not image): raise ValueError(f"候选 {selected.get('display_code') or reference} 尚未生成成功") return {**selected, "candidate_id": candidate_id, "candidate": candidate} def _profile_persona_document(profile: dict[str, Any]) -> str: lines = [ f"角色:{profile.get('name') or '未命名'}", f"基础设定:{profile.get('base_prompt') or profile.get('description') or '—'}", f"外观:{profile.get('appearance_prompt') or '—'}", f"风格:{profile.get('style_prompt') or '—'}", f"负面约束:{profile.get('negative_prompt') or '—'}", ] return "\n".join(lines) def _workflow_next_action( current_node: dict[str, Any] | None, latest_round: dict[str, Any] | None, ) -> str: if current_node is None: return "当前分支已完成;可建立档案卡或查看历史" node_id = str(current_node.get("node_id") or "") node_key = canonical_gradual_node_key(str(current_node.get("node_key") or "")) if node_key == "profile_card": return "使用 /yp 档案卡 封存角色" if current_node.get("node_type") not in {"generation", "single_image"}: return f"完成「{current_node.get('title') or node_key}」后使用 /yp 完成节点 {node_id}" if not latest_round: return f"使用 /yp 轮次 {node_id} 4 创建候选" round_record = latest_round.get("round") if isinstance(latest_round.get("round"), dict) else {} round_id = str(round_record.get("round_id") or "") status = str(round_record.get("status") or "") if status in {"queued", "running", "draft"}: return f"候选轮次 {round_record.get('display_code') or round_id} 正在生成" if status in {"all_failed", "cancelled"}: return f"轮次失败;检查错误后重新使用 /yp 轮次 {node_id} 4" return f"使用 /yp 候选 {round_id} 查看并反馈,/yp 定稿 {round_id} <编号> 明确采用" def _id_set(value: Any) -> set[str]: if isinstance(value, str): value = re.split(r"[,,\n]", value) if not isinstance(value, (list, tuple, set)): return set() return {str(item).strip() for item in value if str(item).strip()} def _quick_questionnaire(text: str) -> dict[str, Any]: parts = text.split(maxsplit=1) if len(parts) < 2: raise ValueError("请同时提供角色名和角色描述,例如:/yp 快速角色 米卡 银发蓝眼的冷静少女") name, description = parts[0].strip(), parts[1].strip() colors = re.findall(r"([黑白红橙黄绿青蓝紫粉灰棕金银]{1,2})色?(?:头发|发|眼睛|眼)", description) hair = next((value for value in colors if f"{value}发" in description or f"{value}色头发" in description), "") eyes = next((value for value in colors if f"{value}眼" in description or f"{value}色眼睛" in description), "") personality_keywords = [item for item in ("冷静", "温柔", "活泼", "开朗", "内向", "傲娇", "成熟", "勇敢", "神秘") if item in description] clothing_keywords = [item for item in ("制服", "礼服", "外套", "裙", "衬衫", "盔甲", "斗篷", "和服", "运动服") if item in description] hairstyle = next((item for item in ("长发", "短发", "双马尾", "马尾", "卷发", "直发", "齐刘海") if item in description), "") return { "name": name, "identity": description, "personality": personality_keywords, "hair_color": hair, "hairstyle": hairstyle, "eye_color": eyes, "clothing_keywords": clothing_keywords, }