Răsfoiți Sursa

feat(core): 重构统一入口并完善插件动态元数据与状态监控

- 统一运行入口为 main.py,支持 standalone / sentinel / booker 三种角色启动
- 引入 In-Memory AST 动态插件扫描 (utils/plugin_updater.py) 并移除静态版本文件落盘
- 插件全面支持被动式云端下发升级 (Redis PubSub 监听与动态热重载)
- 优化 RoleStatus / GroupStatus / PluginStatus 数据契约,时间统一采用人类可读 UTC 格式
- 各插件子类独立实现 get_plugin_status() 实时状态监控上报
- bel_plugin 集成 Capsolver hCaptcha 自动化解析与注入流程
- 全面清理冗余的防御性代码与无意义字段
jerry 2 luni în urmă
părinte
comite
757dc068dc

+ 66 - 33
booker.py

@@ -6,7 +6,7 @@ import random
 from datetime import datetime
 from typing import List, Dict, Callable, Optional
 
-from vs_types import GroupConfig, VSPlgConfig, Task, VSQueryResult, AppointmentType, AvailabilityStatus
+from vs_types import GroupConfig, VSPlgConfig, Task, VSQueryResult, AppointmentType, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str
 from vs_plg_factory import VSPlgFactory
 from toolkit.thread_pool import ThreadPool
 from toolkit.vs_cloud_api import VSCloudApi
@@ -28,14 +28,41 @@ class BaseBookerGCO:
         self.m_stop_event = threading.Event()
         self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
         self.m_tracker_key = f"vs:worker:tasks_tracker:{self.m_cfg.identifier}"
+        self.m_last_group_query_time = 0.0
 
-    def _log(self, message: str):
-        prefix = f'[{self.TAG}] [{self.m_cfg.identifier}]'
+    def _log(self, message):
+        prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
         if self.m_logger:
             self.m_logger(f'{prefix} {message}')
         else:
             print(f'{prefix} {message}')
 
+    def get_status(self) -> GroupStatus:
+        with self.m_lock:
+            tasks = list(self.m_tasks)
+            gid = self.m_cfg.identifier
+            enable = self.m_cfg.enable
+            plugin_name = self.m_cfg.plugin_config.plugin_name
+
+        plugins_status = []
+        healthy_count = 0
+        for t in tasks:
+            if t and t.instance:
+                st = t.instance.get_plugin_status()
+                if st.is_healthy:
+                    healthy_count += 1
+                plugins_status.append(st)
+
+        return GroupStatus(
+            group_id=gid,
+            enable=enable,
+            plugin_name=plugin_name,
+            total_tasks=len(tasks),
+            healthy_tasks=healthy_count,
+            plugins=plugins_status,
+            updated_at=utc_now_str(),
+        )
+
     def start(self):
         if not self.m_cfg.enable:
             return
@@ -280,6 +307,7 @@ class BuiltinBookerGCO(BaseBookerGCO):
 
     def _spawn_worker(self):
         instance = None
+        task = None
         success = False
         plg_cfg = None
         
@@ -300,21 +328,21 @@ class BuiltinBookerGCO(BaseBookerGCO):
             instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
             instance.set_log(self.m_logger)
             instance.set_config(plg_cfg)
-            instance.create_session()
-            success = True
+            all_keys = [apt.routing_key for apt in self.m_cfg.appointment_types]
+            task = Task(
+                instance=instance,
+                next_run=time.time() + 999999, 
+                task_ref=None,
+                acceptable_routing_keys=all_keys,
+                source_queue="built-in",
+                book_allowed=True,
+                next_remote_ping=time.time() + random.gauss(self.m_cfg.booker.keep_alive, 5) 
+            )
             with self.m_lock:
-                all_keys = [apt.routing_key for apt in self.m_cfg.appointment_types]
-                self.m_tasks.append(
-                    Task(
-                        instance=instance,
-                        next_run=time.time(), 
-                        task_ref=None,
-                        acceptable_routing_keys=all_keys,
-                        source_queue="built-in",
-                        book_allowed=True,
-                        next_remote_ping=time.time() + random.gauss(self.m_cfg.booker.keep_alive, 5) 
-                    )
-                )
+                self.m_tasks.append(task)
+
+            instance.create_session()
+            task.next_run = time.time()
             success = True
             self._log(f"+++ Built-in Booker spawned: {plg_cfg.account.username}")
         except Exception as e:
@@ -329,7 +357,9 @@ class BuiltinBookerGCO(BaseBookerGCO):
                     VSCloudApi.lock_account(plg_cfg.account.id, self.m_cfg.login_backoff)
         finally:
             if not success:
-                if instance:
+                if task:
+                    self._remove_task(task, "spawn failed")
+                elif instance:
                     instance.cleanup()
 
     def _execute_book_job(self, task: Task, query_result: VSQueryResult):
@@ -502,6 +532,7 @@ class OrderBookerGCO(BaseBookerGCO):
 
     def _spawn_worker(self, target_routing_key: str):
         instance = None
+        task = None
         success = False
         task_id = None
         try:
@@ -535,20 +566,20 @@ class OrderBookerGCO(BaseBookerGCO):
             instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
             instance.set_log(self.m_logger)
             instance.set_config(plg_cfg)
-            instance.create_session() 
-            
+            task = Task(
+                instance=instance,
+                next_run=time.time() + 999999, 
+                task_ref=task_id,
+                acceptable_routing_keys=acceptable_keys, 
+                source_queue=target_routing_key,
+                book_allowed=True,
+                next_remote_ping=time.time() + random.gauss(self.m_cfg.booker.keep_alive, 5)
+            )
             with self.m_lock:
-                self.m_tasks.append(
-                    Task(
-                        instance=instance,
-                        next_run=time.time(), 
-                        task_ref=task_id,
-                        acceptable_routing_keys=acceptable_keys, 
-                        source_queue=target_routing_key,
-                        book_allowed=True,
-                        next_remote_ping=time.time() + random.gauss(self.m_cfg.booker.keep_alive, 5)
-                    )
-                )
+                self.m_tasks.append(task)
+
+            instance.create_session() 
+            task.next_run = time.time()
             success = True             
             self._log(f"+++ Order Booker spawned: {plg_cfg.account.username} (Target: {acceptable_keys})")
         except Exception as e:
@@ -564,8 +595,10 @@ class OrderBookerGCO(BaseBookerGCO):
         
         finally:
             if not success:
+                if task:
+                    self._remove_task(task, "spawn failed")
+                elif instance:
+                    instance.cleanup()
                 if task_id:
                     with self.m_lock:
                         self.m_task_data_cache.pop(str(task_id), None)
-                if instance:
-                    instance.cleanup()

+ 26 - 18
docker-compose.yml

@@ -5,7 +5,7 @@ services:
     build: .
     image: coordinator:latest
     container_name: coordinator-sentinel
-    command: ["python3", "main_sentinel.py"]
+    command: ["python3", "main.py", "sentinel"]
     restart: unless-stopped
     shm_size: '2gb'
     volumes:
@@ -28,7 +28,30 @@ services:
     build: .
     image: coordinator:latest
     container_name: coordinator-booker
-    command: ["python3", "main_booker.py"]
+    command: ["python3", "main.py", "booker"]
+    restart: unless-stopped
+    shm_size: '2gb'
+    volumes:
+      - ./config:/app/config
+      - ./logs:/app/logs
+      - ./data:/app/data
+      - ./plugins:/app/plugins
+    environment:
+      - TZ=Asia/Shanghai
+      - DISPLAY=:99
+      - CHROME_BIN=/opt/ungoogled-chromium/chrome
+      - MIHOMO_BIN=/bin/mihomo
+    deploy:
+      resources:
+        limits:
+          cpus: '2.0'
+          memory: 2G
+
+  visa-standalone:
+    build: .
+    image: coordinator:latest
+    container_name: coordinator-standalone
+    command: ["python3", "main.py", "standalone"]
     restart: unless-stopped
     shm_size: '2gb'
     volumes:
@@ -63,19 +86,4 @@ services:
       resources:
         limits:
           cpus: '0.2'
-          memory: 256M
-
-  # registration-bot:
-  #   build: .
-  #   image: coordinator:latest
-  #   container_name: tls-bot-worker
-  #   environment:
-  #     - CAPSOLVER_KEY=CAP-5441DD341DD3CC2FAEF0BE6FE493EE9A
-  #   command: ["python3", "-u" ,"tls_registration_bot.py", "-n", "1", "-m", "50", "-p", "isp_all", "-u", "https://visas-fr.tlscontact.com/en-us/country/gb/vac/gbLON2fr"]
-  #   volumes:
-  #     - ./config:/app/config
-  #     - ./data:/app/data
-  #   deploy:
-  #     resources:
-  #       limits:
-  #         memory: 2G
+          memory: 256M

+ 1 - 1
entrypoint.sh

@@ -16,7 +16,7 @@ Xvfb :99 -ac -screen 0 1920x1080x24 -nolisten tcp &
 echo "Waiting for Xvfb and DBus..."
 sleep 3
 
-# 5. 执行外部传进来的命令 (如 python3 main_sentinel.py)
+# 5. 执行外部传进来的命令 (如 python3 main.py sentinel)
 if [ $# -eq 0 ]; then
     echo "No command provided, starting bash..."
     exec bash

+ 21 - 2
gco_wrapper.py

@@ -2,7 +2,7 @@ import threading
 import collections
 from enum import Enum, auto
 from typing import Callable, Type, Any, Dict
-from vs_types import GroupConfig
+from vs_types import GroupConfig, GroupStatus
 from vs_log_macros import VSC_INFO
 
 class State(Enum):
@@ -95,4 +95,23 @@ class GCOWrapper:
             self.m_cfg = new_cfg
             
         if self._gco:
-            self._gco.update_config(new_cfg)
+            self._gco.update_config(new_cfg)
+
+    def get_status(self) -> GroupStatus:
+        """
+        获取当前 GCOWrapper 及其内部 GCO 实例的聚合状态
+        """
+        with self._lock:
+            state_name = self._state.name
+
+        if self._gco:
+            status: GroupStatus = self._gco.get_status()
+            status.wrapper_state = state_name
+            return status
+
+        return GroupStatus(
+            group_id=self.m_cfg.identifier,
+            enable=self.m_cfg.enable,
+            plugin_name=self.m_cfg.plugin_config.plugin_name,
+            wrapper_state=state_name,
+        )

+ 358 - 0
main.py

@@ -0,0 +1,358 @@
+import os
+import sys
+import time
+import json
+import queue
+import argparse
+import threading
+from typing import Dict, Any, List
+
+from vs_types import GroupConfig, BookerStandaloneConfig, RoleStatus, utc_now_str
+from gco_wrapper import GCOWrapper
+from logger_setup import setup_app_logger
+from configure import REDIS_CFG
+from sentinel import SentinelGCO
+from booker import BuiltinBookerGCO, OrderBookerGCO
+from standalone import StandaloneGCO
+from utils.safe_redis_cli import SafeRedisClient
+from utils.cloud_config import (
+    load_remote_or_cache,
+    compute_config_hash,
+    fetch_cloud_config,
+    save_local_cache,
+)
+from utils.plugin_updater import (
+    get_installed_plugins,
+    get_installed_plugin_metas,
+    is_newer_version,
+    download_and_install_plugin,
+)
+
+# 升级指令队列(由 Redis PubSub 线程推送)
+upgrade_queue = queue.Queue()
+
+
+def get_gco_class(role: str, cfg: Any):
+    """根据角色与配置决定具体的 GCO 实现类"""
+    if role == "sentinel":
+        return SentinelGCO
+    if role == "standalone":
+        return StandaloneGCO
+    if role == "booker":
+        if cfg.booker.account_source == "order":
+            return OrderBookerGCO
+        return BuiltinBookerGCO
+    raise ValueError(f"Unknown role: {role}")
+
+
+def parse_group_configs(role: str, raw_conf: Any) -> Dict[str, Any]:
+    """统一解析组配置为字典 {identifier: config_obj}"""
+    items = raw_conf if isinstance(raw_conf, list) else ([raw_conf] if isinstance(raw_conf, dict) else [])
+    cfg_cls = BookerStandaloneConfig if role == "standalone" else GroupConfig
+
+    result = {}
+    for item in items:
+        cfg = cfg_cls.from_json(item)
+        result[cfg.identifier] = cfg
+    return result
+
+
+def collect_role_status(role: str, node_id: str, wrappers: Dict[str, GCOWrapper]) -> RoleStatus:
+    """收集当前节点下所有 GroupWrapper 的聚合状态及本地已安装插件完整元数据列表"""
+    groups_status = [wrapper.get_status() for wrapper in wrappers.values()]
+    installed = get_installed_plugin_metas()
+
+    return RoleStatus(
+        role=role,
+        node_id=node_id,
+        installed_plugins=installed,
+        groups=groups_status,
+        collected_at=utc_now_str(),
+    )
+
+
+def reload_wrappers_for_plugin(
+    plugin_name: str,
+    wrappers: Dict[str, GCOWrapper],
+    gco_classes: Dict[str, type],
+    logger,
+):
+    """找到正在使用该插件的 Wrapper 并进行动态热重载"""
+    for gid, wrapper in list(wrappers.items()):
+        if wrapper.m_cfg.plugin_config.plugin_name == plugin_name:
+            logger.info(f"Hot-reloading group [{gid}] for upgraded plugin '{plugin_name}'...")
+            try:
+                wrapper.stop()
+            except Exception as e:
+                logger.error(f"Error stopping group [{gid}] during reload: {e}")
+
+            # 清除旧模块缓存以加载最新代码
+            sys.modules.pop(plugin_name, None)
+
+            try:
+                target_cls = gco_classes[gid]
+                new_wrapper = GCOWrapper(target_cls, wrapper.m_cfg, REDIS_CFG)
+                new_wrapper.load()
+                new_wrapper.start()
+                wrappers[gid] = new_wrapper
+                logger.info(f"Group [{gid}] successfully reloaded with updated plugin '{plugin_name}'.")
+            except Exception as e:
+                logger.error(f"Failed to restart group [{gid}] after upgrade: {e}")
+
+
+def handle_plugin_upgrades(
+    upgrade_items: List[Dict[str, Any]],
+    wrappers: Dict[str, GCOWrapper],
+    gco_classes: Dict[str, type],
+    logger,
+) -> bool:
+    """
+    检查并执行插件升级列表
+    支持格式:
+    [
+        {
+            "plugin_name": "tls_plugin",
+            "version": "1.1.0",
+            "download_url": "https://...",  # 或 "code": "..."
+            "filename": "tls_plugin.py"
+        }
+    ]
+    """
+    installed = get_installed_plugins()
+    upgraded_any = False
+
+    for item in upgrade_items:
+        plugin_name = item.get("plugin_name")
+        target_version = str(item.get("version", ""))
+        if not plugin_name or not target_version:
+            continue
+
+        current_version = installed.get(plugin_name, "0.0.0")
+        if is_newer_version(target_version, current_version):
+            logger.info(
+                f"🚀 Upgrading plugin '{plugin_name}' (v{current_version} -> v{target_version})..."
+            )
+            try:
+                download_and_install_plugin(
+                    plugin_name=plugin_name,
+                    version=target_version,
+                    download_url=item.get("download_url"),
+                    code_content=item.get("code"),
+                    filename=item.get("filename"),
+                )
+                logger.info(f"✅ Plugin '{plugin_name}' v{target_version} installed successfully.")
+                reload_wrappers_for_plugin(plugin_name, wrappers, gco_classes, logger)
+                upgraded_any = True
+                installed[plugin_name] = target_version
+            except Exception as e:
+                logger.error(f"❌ Plugin '{plugin_name}' upgrade failed: {e}")
+
+    return upgraded_any
+
+
+def start_upgrade_listener(redis_conf: Dict, node_id: str, logger):
+    """启动 Redis PubSub 后台线程,秒级监听云端下发的即时升级指令"""
+    def _listen():
+        import redis
+        while True:
+            try:
+                r = redis.Redis(**redis_conf)
+                pubsub = r.pubsub()
+                channels = ["vs:channel:upgrade", f"vs:channel:upgrade:{node_id}"]
+                pubsub.subscribe(*channels)
+                logger.info(f"Subscribed to upgrade channels: {channels}")
+
+                for msg in pubsub.listen():
+                    if msg and msg.get("type") == "message":
+                        try:
+                            raw_data = msg.get("data")
+                            if isinstance(raw_data, bytes):
+                                raw_data = raw_data.decode("utf-8")
+                            payload = json.loads(raw_data)
+                            logger.info(f"Received cloud upgrade command: {payload}")
+                            upgrade_queue.put(payload)
+                        except Exception as e:
+                            logger.error(f"Error parsing upgrade message: {e}")
+            except Exception as e:
+                logger.warning(f"PubSub connection error: {e}. Reconnecting in 5s...")
+                time.sleep(5)
+
+    threading.Thread(target=_listen, daemon=True, name="Upgrade-Listener").start()
+
+
+def sync_groups(
+    role: str,
+    raw_conf: Any,
+    wrappers: Dict[str, GCOWrapper],
+    gco_classes: Dict[str, type],
+    logger,
+):
+    """根据最新配置同步 GCOWrapper 实例的生命周期(停止、重启、更新、新增)"""
+    new_groups = parse_group_configs(role, raw_conf)
+
+    # 1. 停止已被移除或禁用的组
+    for gid in list(wrappers.keys()):
+        cfg = new_groups.get(gid)
+        if not cfg or not cfg.enable:
+            logger.info(f"Stopping disabled/removed group [{gid}]...")
+            try:
+                wrappers[gid].stop()
+            except Exception as e:
+                logger.error(f"Error stopping group [{gid}]: {e}")
+            del wrappers[gid]
+            gco_classes.pop(gid, None)
+
+    # 2. 处理现有组更新或新增组
+    for gid, cfg in new_groups.items():
+        if not cfg.enable:
+            continue
+
+        target_cls = get_gco_class(role, cfg)
+
+        if gid in wrappers:
+            if gco_classes.get(gid) != target_cls:
+                logger.info(f"Mode changed for group [{gid}]. Restarting with {target_cls.__name__}...")
+                try:
+                    wrappers[gid].stop()
+                except Exception as e:
+                    logger.error(f"Error stopping group [{gid}]: {e}")
+                
+                try:
+                    wrapper = GCOWrapper(target_cls, cfg, REDIS_CFG)
+                    wrapper.load()
+                    wrapper.start()
+                    wrappers[gid] = wrapper
+                    gco_classes[gid] = target_cls
+                except Exception as e:
+                    logger.error(f"Failed to restart group [{gid}]: {e}")
+            else:
+                logger.info(f"Updating configuration for group [{gid}]...")
+                try:
+                    wrappers[gid].update_config(cfg)
+                except Exception as e:
+                    logger.error(f"Error updating config for group [{gid}]: {e}")
+        else:
+            logger.info(f"Starting group [{gid}] ({target_cls.__name__})...")
+            try:
+                wrapper = GCOWrapper(target_cls, cfg, REDIS_CFG)
+                wrapper.load()
+                wrapper.start()
+                wrappers[gid] = wrapper
+                gco_classes[gid] = target_cls
+            except Exception as e:
+                logger.error(f"Failed to start group [{gid}]: {e}")
+
+
+def main():
+    parser = argparse.ArgumentParser(description="Coordinate Unified Runner")
+    parser.add_argument("role", choices=["sentinel", "booker", "standalone"], help="Role to run")
+    parser.add_argument("-c", "--config", type=str, default=None, help="Path to local config file")
+    parser.add_argument("--poll-interval", type=float, default=30.0, help="Cloud config poll interval in seconds")
+    parser.add_argument("--status-interval", type=float, default=10.0, help="RoleStatus reporting interval in seconds (default: 10s)")
+
+    args = parser.parse_args()
+    role = args.role
+    use_cloud = args.config is None
+    config_path = args.config or f"config/config_{role}.json"
+    node_id = os.getenv("NODE_ID", "node01")
+    config_key = f"{role}_config:{node_id}"
+    status_key = f"vs:status:{role}:{node_id}"
+
+    logger = setup_app_logger(role.title())
+    logger.info(f"{role.title()} Runner started (Node ID: '{node_id}', Cloud Mode: {use_cloud})")
+
+    redis_client = SafeRedisClient(REDIS_CFG, logger.info)
+
+    # 启动云端指令实时监听(响应云端下发的升级指令)
+    start_upgrade_listener(REDIS_CFG, node_id, logger)
+
+    groups_conf, current_hash, _ = load_remote_or_cache(
+        config_key=config_key,
+        local_cache_path=config_path,
+        use_cloud=use_cloud,
+        logger=logger.info,
+    )
+
+    wrappers: Dict[str, GCOWrapper] = {}
+    gco_classes: Dict[str, type] = {}
+
+    sync_groups(role, groups_conf, wrappers, gco_classes, logger)
+    logger.info(f"Successfully initialized {len(wrappers)} active group(s).")
+
+    # 打印本地已安装插件列表与初始 RoleStatus
+    initial_status = collect_role_status(role, node_id, wrappers)
+    status_dict = initial_status.to_dict()
+    logger.info("📊 Initial RoleStatus:\n" + json.dumps(status_dict, indent=2, ensure_ascii=False))
+
+    report_ttl = max(30, int(args.status_interval * 3))
+    try:
+        redis_client.setex(status_key, report_ttl, json.dumps(initial_status.to_dict()))
+    except Exception as e:
+        logger.warning(f"Error reporting initial RoleStatus to Redis: {e}")
+
+    if use_cloud:
+        logger.info(f"Cloud config active for key '{config_key}'. Polling every {args.poll_interval}s.")
+
+    last_poll_time = time.time()
+    last_status_report_time = time.time()
+
+    try:
+        while True:
+            time.sleep(1)
+            now = time.time()
+
+            # 1. 响应云端下发的即时升级指令 (PubSub)
+            while not upgrade_queue.empty():
+                try:
+                    payload = upgrade_queue.get_nowait()
+                    plugins_items = payload.get("plugins", [])
+                    if isinstance(plugins_items, dict):
+                        plugins_items = [plugins_items]
+                    if plugins_items:
+                        if handle_plugin_upgrades(plugins_items, wrappers, gco_classes, logger):
+                            # 升级成功,立即刷新并上报最新 RoleStatus
+                            new_status = collect_role_status(role, node_id, wrappers)
+                            status_dict = new_status.to_dict()
+                            redis_client.setex(status_key, report_ttl, json.dumps(status_dict))
+                            logger.info("📊 Reported RoleStatus:\n" + json.dumps(status_dict, indent=2, ensure_ascii=False))
+                except queue.Empty:
+                    break
+
+            # 2. 定时上报包含 installed_plugins 的 RoleStatus
+            if now - last_status_report_time >= args.status_interval:
+                last_status_report_time = now
+                try:
+                    current_status = collect_role_status(role, node_id, wrappers)
+                    status_dict = current_status.to_dict()
+                    redis_client.setex(status_key, report_ttl, json.dumps(status_dict))
+                    logger.info("📊 Reported RoleStatus:\n" + json.dumps(status_dict, indent=2, ensure_ascii=False))
+                except Exception as e:
+                    logger.warning(f"Error reporting RoleStatus to Redis '{status_key}': {e}")
+
+            # 3. 云端分组配置定时轮询与热更新
+            if use_cloud and (now - last_poll_time >= args.poll_interval):
+                last_poll_time = now
+                try:
+                    new_conf = fetch_cloud_config(config_key)
+                    if new_conf is not None:
+                        new_hash = compute_config_hash(new_conf)
+                        if new_hash != current_hash:
+                            logger.info(f"Cloud config change detected ({current_hash[:8]} -> {new_hash[:8]}). Auto-reloading...")
+                            save_local_cache(config_path, new_conf)
+                            sync_groups(role, new_conf, wrappers, gco_classes, logger)
+                            current_hash = new_hash
+                            logger.info(f"Auto-reload completed. Currently {len(wrappers)} group(s) running.")
+                except Exception as e:
+                    logger.warning(f"Error polling cloud config key '{config_key}': {e}")
+
+    except KeyboardInterrupt:
+        logger.info(f"Shutting down {role}...")
+        for gid, wrapper in list(wrappers.items()):
+            try:
+                wrapper.stop()
+            except Exception as e:
+                logger.error(f"Error stopping group [{gid}]: {e}")
+
+
+if __name__ == "__main__":
+    main()

+ 0 - 184
main_booker.py

@@ -1,184 +0,0 @@
-import os
-import sys
-import time
-import json
-import argparse
-from typing import Dict
-
-from vs_types import GroupConfig
-from gco_wrapper import GCOWrapper
-from logger_setup import setup_app_logger
-from configure import REDIS_CFG
-from booker import BuiltinBookerGCO, OrderBookerGCO
-from utils.cloud_config import load_remote_or_cache, compute_config_hash, fetch_cloud_config, save_local_cache
-
-
-def get_gco_class_for_booker(cfg: GroupConfig):
-    if cfg.booker.account_source == "order":
-        return OrderBookerGCO
-    return BuiltinBookerGCO
-
-
-def sync_booker_groups(
-    groups_conf: list,
-    active_wrappers: Dict[str, GCOWrapper],
-    active_gco_classes: Dict[str, type],
-    app_logger
-):
-    new_groups_by_id: Dict[str, GroupConfig] = {}
-    for item in groups_conf:
-        cfg = GroupConfig.from_json(item)
-        new_groups_by_id[cfg.identifier] = cfg
-
-    current_ids = list(active_wrappers.keys())
-    for gid in current_ids:
-        wrapper = active_wrappers[gid]
-        new_cfg = new_groups_by_id.get(gid)
-
-        if not new_cfg or not new_cfg.enable:
-            app_logger.info(f"Stopping disabled/removed Booker group [{gid}]...")
-            try:
-                wrapper.stop()
-            except Exception as e:
-                app_logger.error(f"Error stopping group [{gid}]: {e}")
-            del active_wrappers[gid]
-            if gid in active_gco_classes:
-                del active_gco_classes[gid]
-
-    for gid, cfg in new_groups_by_id.items():
-        if not cfg.enable:
-            continue
-
-        target_gco_class = get_gco_class_for_booker(cfg)
-
-        if gid in active_wrappers:
-            if active_gco_classes.get(gid) != target_gco_class:
-                app_logger.info(f"Mode changed for Booker group [{gid}]. Restarting group with new class...")
-                try:
-                    active_wrappers[gid].stop()
-                except Exception as e:
-                    app_logger.error(f"Error stopping group [{gid}] for class switch: {e}")
-                
-                try:
-                    wrapper = GCOWrapper(
-                        gco_class=target_gco_class,
-                        gco_cfg=cfg,
-                        redis_conf=REDIS_CFG
-                    )
-                    wrapper.load()
-                    wrapper.start()
-                    active_wrappers[gid] = wrapper
-                    active_gco_classes[gid] = target_gco_class
-                except Exception as e:
-                    app_logger.error(f"Failed to restart group [{gid}]: {e}")
-            else:
-                app_logger.info(f"Updating configuration for active Booker group [{gid}]...")
-                try:
-                    active_wrappers[gid].update_config(cfg)
-                except Exception as e:
-                    app_logger.error(f"Error updating config for group [{gid}]: {e}")
-        else:
-            mode_str = "ORDER (Bound)" if target_gco_class == OrderBookerGCO else "BUILT-IN (Unbound)"
-            app_logger.info(f"Starting new wrapper for Booker group [{gid}] (Mode: {mode_str})...")
-            try:
-                wrapper = GCOWrapper(
-                    gco_class=target_gco_class,
-                    gco_cfg=cfg,
-                    redis_conf=REDIS_CFG
-                )
-                wrapper.load()
-                wrapper.start()
-                active_wrappers[gid] = wrapper
-                active_gco_classes[gid] = target_gco_class
-            except Exception as e:
-                app_logger.error(f"Failed to start group [{gid}]: {e}")
-
-
-def main():
-    parser = argparse.ArgumentParser(description="Booker Runner")
-
-    parser.add_argument(
-        "-c", "--config",
-        type=str,
-        required=False,
-        default=None,
-        help="Path to local config.json. If specified, disables cloud config and runs with local file."
-    )
-    parser.add_argument(
-        "--poll-interval",
-        type=float,
-        required=False,
-        default=30.0,
-        help="Interval in seconds to poll cloud config (default: 30.0s)"
-    )
-
-    args = parser.parse_args()
-
-    # 逻辑 1:默认开启云端配置,除非命令行指定了 -c/--config 本地文件路径
-    if args.config is not None:
-        config_path = args.config
-        use_cloud = False
-    else:
-        config_path = "config/config_booker.json"
-        use_cloud = True
-
-    # 逻辑 2:直接从环境变量获取 node_id,默认 node01
-    node_id = os.getenv("NODE_ID") or "node01"
-    config_key = f"booker_config:{node_id}"
-    poll_interval = args.poll_interval
-
-    app_logger = setup_app_logger("Booker")
-    app_logger.info(f"Booker Logger is ready! (Node ID: '{node_id}', Cloud Mode: {use_cloud})")
-
-    groups_conf, current_hash, loaded_from_remote = load_remote_or_cache(
-        config_key=config_key,
-        local_cache_path=config_path,
-        use_cloud=use_cloud,
-        logger=app_logger.info
-    )
-
-    active_wrappers: Dict[str, GCOWrapper] = {}
-    active_gco_classes: Dict[str, type] = {}
-
-    sync_booker_groups(groups_conf, active_wrappers, active_gco_classes, app_logger)
-    app_logger.info(
-        f"Successfully initialized Booker with {len(active_wrappers)} active group(s)."
-    )
-    if use_cloud:
-        app_logger.info(f"Cloud config active for key '{config_key}'. Polling every {poll_interval}s.")
-
-    last_poll_time = time.time()
-    try:
-        while True:
-            time.sleep(1)
-            now = time.time()
-
-            if use_cloud and (now - last_poll_time >= poll_interval):
-                last_poll_time = now
-                try:
-                    new_conf = fetch_cloud_config(config_key)
-                    if new_conf is not None:
-                        new_hash = compute_config_hash(new_conf)
-
-                        if new_hash != current_hash:
-                            app_logger.info(
-                                f"Cloud config change detected (hash: {current_hash[:8]} -> {new_hash[:8]}). Auto-reloading..."
-                            )
-                            save_local_cache(config_path, new_conf)
-                            sync_booker_groups(new_conf, active_wrappers, active_gco_classes, app_logger)
-                            current_hash = new_hash
-                            app_logger.info(f"Auto-reload completed. Currently {len(active_wrappers)} group(s) running.")
-                except Exception as e:
-                    app_logger.warning(f"Error polling cloud config key '{config_key}': {e}. Retrying next cycle.")
-
-    except KeyboardInterrupt:
-        app_logger.info("Shutting down Bookers...")
-        for gid, wrapper in list(active_wrappers.items()):
-            try:
-                wrapper.stop()
-            except Exception as e:
-                app_logger.error(f"Error stopping group [{gid}]: {e}")
-
-
-if __name__ == "__main__":
-    main()

+ 0 - 150
main_sentinel.py

@@ -1,150 +0,0 @@
-import os
-import sys
-import time
-import json
-import argparse
-from typing import Dict
-
-from vs_types import GroupConfig
-from gco_wrapper import GCOWrapper
-from logger_setup import setup_app_logger
-from configure import REDIS_CFG
-from sentinel import SentinelGCO
-from utils.cloud_config import load_remote_or_cache, compute_config_hash, fetch_cloud_config, save_local_cache
-
-
-def sync_sentinel_groups(
-    groups_conf: list,
-    active_wrappers: Dict[str, GCOWrapper],
-    app_logger
-):
-    new_groups_by_id: Dict[str, GroupConfig] = {}
-    for item in groups_conf:
-        cfg = GroupConfig.from_json(item)
-        new_groups_by_id[cfg.identifier] = cfg
-
-    current_ids = list(active_wrappers.keys())
-    for gid in current_ids:
-        wrapper = active_wrappers[gid]
-        new_cfg = new_groups_by_id.get(gid)
-
-        if not new_cfg or not new_cfg.enable:
-            app_logger.info(f"Stopping disabled/removed Sentinel group [{gid}]...")
-            try:
-                wrapper.stop()
-            except Exception as e:
-                app_logger.error(f"Error stopping group [{gid}]: {e}")
-            del active_wrappers[gid]
-
-    for gid, cfg in new_groups_by_id.items():
-        if not cfg.enable:
-            continue
-
-        if gid in active_wrappers:
-            app_logger.info(f"Updating configuration for active Sentinel group [{gid}]...")
-            try:
-                active_wrappers[gid].update_config(cfg)
-            except Exception as e:
-                app_logger.error(f"Error updating config for group [{gid}]: {e}")
-        else:
-            app_logger.info(f"Starting new wrapper for Sentinel group [{gid}]...")
-            try:
-                wrapper = GCOWrapper(
-                    gco_class=SentinelGCO,
-                    gco_cfg=cfg,
-                    redis_conf=REDIS_CFG
-                )
-                wrapper.load()
-                wrapper.start()
-                active_wrappers[gid] = wrapper
-            except Exception as e:
-                app_logger.error(f"Failed to start group [{gid}]: {e}")
-
-
-def main():
-    parser = argparse.ArgumentParser(description="Sentinel Runner")
-
-    parser.add_argument(
-        "-c", "--config",
-        type=str,
-        required=False,
-        default=None,
-        help="Path to local config.json. If specified, disables cloud config and runs with local file."
-    )
-    parser.add_argument(
-        "--poll-interval",
-        type=float,
-        required=False,
-        default=30.0,
-        help="Interval in seconds to poll cloud config (default: 30.0s)"
-    )
-
-    args = parser.parse_args()
-
-    # 逻辑 1:默认开启云端配置,除非命令行指定了 -c/--config 本地文件路径
-    if args.config is not None:
-        config_path = args.config
-        use_cloud = False
-    else:
-        config_path = "config/config_sentinel.json"
-        use_cloud = True
-
-    # 逻辑 2:直接从环境变量获取 node_id,默认 node01
-    node_id = os.getenv("NODE_ID") or "node01"
-    config_key = f"sentinel_config:{node_id}"
-    poll_interval = args.poll_interval
-
-    app_logger = setup_app_logger("Sentinel")
-    app_logger.info(f"Sentinel Logger is ready! (Node ID: '{node_id}', Cloud Mode: {use_cloud})")
-
-    groups_conf, current_hash, loaded_from_remote = load_remote_or_cache(
-        config_key=config_key,
-        local_cache_path=config_path,
-        use_cloud=use_cloud,
-        logger=app_logger.info
-    )
-
-    active_wrappers: Dict[str, GCOWrapper] = {}
-
-    sync_sentinel_groups(groups_conf, active_wrappers, app_logger)
-    app_logger.info(
-        f"Successfully initialized Sentinel with {len(active_wrappers)} active group(s)."
-    )
-    if use_cloud:
-        app_logger.info(f"Cloud config active for key '{config_key}'. Polling every {poll_interval}s.")
-
-    last_poll_time = time.time()
-    try:
-        while True:
-            time.sleep(1)
-            now = time.time()
-
-            if use_cloud and (now - last_poll_time >= poll_interval):
-                last_poll_time = now
-                try:
-                    new_conf = fetch_cloud_config(config_key)
-                    if new_conf is not None:
-                        new_hash = compute_config_hash(new_conf)
-
-                        if new_hash != current_hash:
-                            app_logger.info(
-                                f"Cloud config change detected (hash: {current_hash[:8]} -> {new_hash[:8]}). Auto-reloading..."
-                            )
-                            save_local_cache(config_path, new_conf)
-                            sync_sentinel_groups(new_conf, active_wrappers, app_logger)
-                            current_hash = new_hash
-                            app_logger.info(f"Auto-reload completed. Currently {len(active_wrappers)} group(s) running.")
-                except Exception as e:
-                    app_logger.warning(f"Error polling cloud config key '{config_key}': {e}. Retrying next cycle.")
-
-    except KeyboardInterrupt:
-        app_logger.info("Shutting down Sentinels...")
-        for gid, wrapper in list(active_wrappers.items()):
-            try:
-                wrapper.stop()
-            except Exception as e:
-                app_logger.error(f"Error stopping group [{gid}]: {e}")
-
-
-if __name__ == "__main__":
-    main()

+ 0 - 162
main_standalone.py

@@ -1,162 +0,0 @@
-import os
-import sys
-import time
-import json
-import argparse
-from typing import Dict, List, Any
-
-from vs_types import BookerStandaloneConfig
-from gco_wrapper import GCOWrapper
-from logger_setup import setup_app_logger
-from booker_standalone import BookerStandalone
-from configure import REDIS_CFG
-from utils.cloud_config import load_remote_or_cache, compute_config_hash, fetch_cloud_config, save_local_cache
-
-
-def sync_standalone_groups(
-    groups_conf: Any,
-    active_wrappers: Dict[str, GCOWrapper],
-    app_logger
-):
-    """
-    根据最新 groups_conf 对比并管理各个 Standalone Booker 实例的生命周期。
-    支持 JSON List(包含多个 group 数组)或单个 Dict。
-    """
-    if isinstance(groups_conf, dict):
-        conf_list = [groups_conf]
-    elif isinstance(groups_conf, list):
-        conf_list = groups_conf
-    else:
-        conf_list = []
-
-    new_groups_by_id: Dict[str, BookerStandaloneConfig] = {}
-    for idx, item in enumerate(conf_list):
-        cfg = BookerStandaloneConfig.from_json(item)
-        gid = cfg.identifier or f"standalone_{idx}"
-        new_groups_by_id[gid] = cfg
-
-    # 1. 停止已被移除或被禁用的组
-    current_ids = list(active_wrappers.keys())
-    for gid in current_ids:
-        wrapper = active_wrappers[gid]
-        new_cfg = new_groups_by_id.get(gid)
-
-        if not new_cfg or not new_cfg.enable:
-            app_logger.info(f"Stopping disabled/removed Standalone group [{gid}]...")
-            try:
-                wrapper.stop()
-            except Exception as e:
-                app_logger.error(f"Error stopping group [{gid}]: {e}")
-            del active_wrappers[gid]
-
-    # 2. 动态更新现有组,或启动新增组
-    for gid, cfg in new_groups_by_id.items():
-        if not cfg.enable:
-            continue
-
-        if gid in active_wrappers:
-            app_logger.info(f"Updating configuration for active Standalone group [{gid}]...")
-            try:
-                active_wrappers[gid].update_config(cfg)
-            except Exception as e:
-                app_logger.error(f"Error updating config for Standalone group [{gid}]: {e}")
-        else:
-            app_logger.info(f"Starting new wrapper for Standalone group [{gid}]...")
-            try:
-                wrapper = GCOWrapper(
-                    gco_class=BookerStandalone,
-                    gco_cfg=cfg,
-                    redis_conf=REDIS_CFG
-                )
-                wrapper.load()
-                wrapper.start()
-                active_wrappers[gid] = wrapper
-            except Exception as e:
-                app_logger.error(f"Failed to start Standalone group [{gid}]: {e}")
-
-
-def main():
-    parser = argparse.ArgumentParser(description="Standalone Booker Runner")
-    parser.add_argument(
-        "-c", "--config",
-        type=str,
-        required=False,
-        default=None,
-        help="Path to local config.json. If specified, disables cloud config and runs with local file."
-    )
-    parser.add_argument(
-        "--poll-interval",
-        type=float,
-        required=False,
-        default=30.0,
-        help="Interval in seconds to poll cloud config (default: 30.0s)"
-    )
-
-    args = parser.parse_args()
-
-    # 逻辑 1:默认开启云端配置,除非命令行指定了 -c/--config 本地文件路径
-    if args.config is not None:
-        config_path = args.config
-        use_cloud = False
-    else:
-        config_path = "config/config_standalone.json"
-        use_cloud = True
-
-    # 逻辑 2:直接从环境变量获取 node_id,默认 node01
-    node_id = os.getenv("NODE_ID") or "node01"
-    config_key = f"standalone_config:{node_id}"
-    poll_interval = args.poll_interval
-
-    app_logger = setup_app_logger("Booker")
-    app_logger.info(f"Booker Logger is ready! (Node ID: '{node_id}', Cloud Mode: {use_cloud})")
-
-    groups_conf, current_hash, loaded_from_remote = load_remote_or_cache(
-        config_key=config_key,
-        local_cache_path=config_path,
-        use_cloud=use_cloud,
-        logger=app_logger.info
-    )
-
-    active_wrappers: Dict[str, GCOWrapper] = {}
-
-    sync_standalone_groups(groups_conf, active_wrappers, app_logger)
-    app_logger.info(f"Successfully initialized {len(active_wrappers)} Standalone Booker group(s).")
-
-    if use_cloud:
-        app_logger.info(f"Cloud config active for key '{config_key}'. Polling every {poll_interval}s.")
-    
-    last_poll_time = time.time()
-    try:
-        while True:
-            time.sleep(1)
-            now = time.time()
-
-            if use_cloud and (now - last_poll_time >= poll_interval):
-                last_poll_time = now
-                try:
-                    new_conf = fetch_cloud_config(config_key)
-                    if new_conf is not None:
-                        new_hash = compute_config_hash(new_conf)
-
-                        if new_hash != current_hash:
-                            app_logger.info(
-                                f"Cloud config change detected (hash: {current_hash[:8]} -> {new_hash[:8]}). Auto-reloading..."
-                            )
-                            save_local_cache(config_path, new_conf)
-                            sync_standalone_groups(new_conf, active_wrappers, app_logger)
-                            current_hash = new_hash
-                            app_logger.info(f"Auto-reload completed. Currently {len(active_wrappers)} Standalone group(s) running.")
-                except Exception as e:
-                    app_logger.warning(f"Error polling cloud config key '{config_key}': {e}. Retrying next cycle.")
-
-    except KeyboardInterrupt:
-        app_logger.info("Shutting down Bookers...")
-        for gid, wrapper in list(active_wrappers.items()):
-            try:
-                wrapper.stop()
-            except Exception as e:
-                app_logger.error(f"Error stopping Standalone group [{gid}]: {e}")
-
-
-if __name__ == "__main__":
-    main()

+ 150 - 44
plugins/bel_plugin.py

@@ -17,7 +17,7 @@ from DrissionPage import ChromiumPage, ChromiumOptions
 
 
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.proxy_tunnel import ProxyTunnel
 
@@ -50,6 +50,9 @@ class BelPlugin(IVSPlg):
     """
     Belgium (https://visaonweb.diplomatie.be/en) 签证预约插件 (Browser + Tunnel Mode)
     """
+    name = "bel_plugin"
+    version = "1.0.0"
+    description = "比利时签证预约插件 (Visa On Web / 浏览器与隧道模式)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -79,9 +82,9 @@ class BelPlugin(IVSPlg):
         
     def _log(self, message): 
         if self.logger:
-            self.logger(f'[PolPlugin] [{self.group_id}] {message}')
+            self.logger(f'[BelPlugin] [{self.group_id}] {message}')
         else:
-            print(f'[PolPlugin] [{self.group_id}] {message}')
+            print(f'[BelPlugin] [{self.group_id}] {message}')
         
     def set_config(self, config: VSPlgConfig):
         self.config = config
@@ -186,7 +189,12 @@ class BelPlugin(IVSPlg):
     def query(self, apt_type: AppointmentType) -> VSQueryResult:
         res = VSQueryResult()
         res.success = False
-                   
+
+        if not self.applicants:
+            self._log("No submitted applicants available to query appointment.")
+            res.availability_status = AvailabilityStatus.NoneAvailable
+            return res
+
         applicant = random.choice(self.applicants)
         applicant_id = applicant.get('id')
         url = 'https://visaonweb.diplomatie.be/Common/GetEAppointmentUrl'
@@ -200,38 +208,97 @@ class BelPlugin(IVSPlg):
         }
         resp = self._perform_request('GET', url, headers=headers, params=params)
         appointment_url = resp.json().get('url')
-        
-        tab = self.page.new_tab(appointment_url)
-        # solve hcaptcha
-        # sitekey = 5f64399c-14a8-415e-ad1a-7ebccdc4943a
-        
-        token = self.get_captcha_solution(self.free_config.get('capsolver_key'), '5f64399c-14a8-415e-ad1a-7ebccdc4943a', appointment_url)
-        script = f'document.querySelector(\'textarea[name="h-captcha-response"]\').value="{token}";'
-        tab.run_js(script)
-        time.sleep(5)
-        self._log(tab.html)
-        available_dates = []
-        if available_dates:
-            res.success = True
-            res.availability_status = AvailabilityStatus.Available
-            earliest_date = available_dates[0]
-            earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
-            res.earliest_date = earliest_dt
-
-            res.availability = [
-                DateAvailability(
-                    date=datetime.strptime(d, "%Y-%m-%d"),
-                    times=[],
-                )
-                for d in available_dates
-            ]
-        else:
-            res.success = False
+        if not appointment_url:
+            self._log("GetEAppointmentUrl returned empty URL.")
             res.availability_status = AvailabilityStatus.NoneAvailable
-            res.availability = []
+            return res
+
+        tab = self.page.new_tab(appointment_url)
+        try:
+            tab.wait.doc_loaded()
+            site_key = '5f64399c-14a8-415e-ad1a-7ebccdc4943a'
+            capsolver_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '')
+            
+            token = self.get_captcha_solution(capsolver_key, site_key, appointment_url)
+            
+            inject_script = f"""
+            (function() {{
+                var token = "{token}";
+                var textareas = [
+                    document.querySelector('textarea[name="h-captcha-response"]'),
+                    document.querySelector('textarea[name="g-recaptcha-response"]'),
+                    document.querySelector('[name="h-captcha-response"]'),
+                    document.querySelector('[name="g-recaptcha-response"]')
+                ];
+                textareas.forEach(function(el) {{
+                    if (el) {{
+                        el.value = token;
+                        el.innerHTML = token;
+                        el.dispatchEvent(new Event('input', {{ bubbles: true }}));
+                        el.dispatchEvent(new Event('change', {{ bubbles: true }}));
+                    }}
+                }});
+                if (typeof window.hcaptcha !== 'undefined' && typeof window.hcaptcha.setData === 'function') {{
+                    try {{ window.hcaptcha.setData(null, {{ response: token }}); }} catch(e) {{}}
+                }}
+                if (typeof window.onHCaptchaSuccess === 'function') {{
+                    window.onHCaptchaSuccess(token);
+                }}
+            }})();
+            """
+            tab.run_js(inject_script)
+            time.sleep(2)
+
+            btn = tab.ele('tag:button@@type=submit', timeout=2) or tab.ele('tag:input@@type=submit', timeout=2)
+            if btn:
+                btn.click()
+                tab.wait.doc_loaded()
+
+            time.sleep(3)
+            self._log(f"Page title after hCaptcha submit: {tab.title}")
+
+            available_dates = []
+            date_eles = tab.eles('.available-date, .calendar-day-available, [data-date]')
+            for d_ele in date_eles:
+                d_str = d_ele.attr('data-date') or d_ele.text
+                if d_str and re.match(r'^\d{4}-\d{2}-\d{2}$', d_str.strip()):
+                    available_dates.append(d_str.strip())
+
+            if available_dates:
+                res.success = True
+                res.availability_status = AvailabilityStatus.Available
+                earliest_date = available_dates[0]
+                earliest_dt = datetime.strptime(earliest_date, "%Y-%m-%d")
+                res.earliest_date = earliest_dt
+
+                res.availability = [
+                    DateAvailability(
+                        date=datetime.strptime(d, "%Y-%m-%d"),
+                        times=[],
+                    )
+                    for d in available_dates
+                ]
+            else:
+                res.success = False
+                res.availability_status = AvailabilityStatus.NoneAvailable
+                res.availability = []
+        finally:
+            try:
+                tab.close()
+            except Exception:
+                pass
+
         return res
     
-    def get_captcha_solution(self, api_key, site_key, site_url):
+    def get_captcha_solution(self, api_key: str, site_key: str, site_url: str) -> str:
+        """
+        调用 Capsolver 解决 hCaptcha (HCaptchaTaskProxyLess)
+        """
+        if not api_key:
+            api_key = self.free_config.get('capsolver_key') or os.getenv('CAPSOLVER_KEY', '')
+        if not api_key:
+            raise BizLogicError(message="Capsolver API key missing in free_config or environment")
+
         payload = {
             "clientKey": api_key,
             "task": {
@@ -241,21 +308,37 @@ class BelPlugin(IVSPlg):
             }
         }
         
+        self._log("Submitting hCaptcha task to Capsolver...")
         with requests.Session() as session:
-            res = session.post("https://api.capsolver.com/createTask", json=payload)
-            task_id = res.json().get("taskId")
+            res = session.post("https://api.capsolver.com/createTask", json=payload, timeout=20)
+            res_json = res.json()
+            if res_json.get("errorId", 0) != 0:
+                raise BizLogicError(message=f"Failed to create Capsolver task: {res.text}")
+
+            task_id = res_json.get("taskId")
             if not task_id:
-                raise Exception("Failed to create task:", res.text)
+                raise BizLogicError(message=f"No taskId returned from Capsolver: {res.text}")
             
-            print("Waiting for CAPTCHA solution...")
-            while True:
-                time.sleep(5)  # Wait for 5 seconds before checking the result
-                res = session.post("https://api.capsolver.com/getTaskResult", json={"clientKey": api_key, "taskId": task_id})
+            self._log(f"Waiting for hCaptcha solution (TaskId: {task_id})...")
+            start_time = time.time()
+            while time.time() - start_time < 120:
+                time.sleep(3)
+                res = session.post(
+                    "https://api.capsolver.com/getTaskResult",
+                    json={"clientKey": api_key, "taskId": task_id},
+                    timeout=20
+                )
                 result = res.json()
-                if result.get("status") == "ready":
-                    return result["solution"]["gRecaptchaResponse"]
-                if result.get("status") == "failed":
-                    raise Exception("CAPTCHA solve failed:", res.text)
+                status = result.get("status")
+                if status == "ready":
+                    solution = result.get("solution", {})
+                    token = solution.get("gRecaptchaResponse") or solution.get("token") or solution.get("response")
+                    self._log("✅ hCaptcha solved successfully.")
+                    return token
+                if status == "failed":
+                    raise BizLogicError(message=f"hCaptcha solve failed: {res.text}")
+
+            raise BizLogicError(message="Capsolver task timed out (120s)")
 
     def book(self, slot_info: VSQueryResult, user_inputs: Dict) -> VSBookResult:
         res = VSBookResult()
@@ -334,5 +417,28 @@ class BelPlugin(IVSPlg):
             except: pass
             self.tunnel = None
         
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
+
+        return PluginStatus(
+            instance_id=getattr(self, "instance_id", self.group_id),
+            is_healthy=getattr(self, "is_healthy", True),
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=0,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         self.cleanup()

+ 27 - 1
plugins/bls_plugin.py

@@ -23,7 +23,7 @@ from cryptography.hazmat.backends import default_backend
 
 # 框架依赖
 from vs_plg import IVSPlg 
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, TimeSlot, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, TimeSlot, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.ocr_engine import PyTorchEngine
 
@@ -31,6 +31,9 @@ class BlsPlugin(IVSPlg):
     """
     BLS 签证预约插件 (精简版)
     """
+    name = "bls_plugin"
+    version = "1.0.0"
+    description = "西班牙BLS签证预约插件 (支持验证码识别与全流程自动化)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -1075,6 +1078,29 @@ class BlsPlugin(IVSPlg):
             if os.path.exists(self.root_workspace):
                  self._log(f"[WARN] Failed to fully remove workspace: {self.root_workspace}")
         
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        state = "running" if self.is_healthy else "unhealthy"
+
+        return PluginStatus(
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=0,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         """
         析构函数:当对象被垃圾回收时自动调用

+ 27 - 1
plugins/de_plugin.py

@@ -15,7 +15,7 @@ from urllib.parse import urljoin, urlparse, urlencode
 from DrissionPage import ChromiumPage, ChromiumOptions
 
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 from toolkit.vs_cloud_api import VSCloudApi
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from toolkit.proxy_tunnel import ProxyTunnel
@@ -50,6 +50,9 @@ class DePlugin(IVSPlg):
     """
     Germany (Visametric) 签证预约插件 (Browser + Tunnel Mode)
     """
+    name = "de_plugin"
+    version = "1.0.0"
+    description = "德国Visametric签证预约插件 (支持Cloudflare穿透与OCR验证)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -525,5 +528,28 @@ class DePlugin(IVSPlg):
             except: pass
             self.tunnel = None
         
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
+
+        return PluginStatus(
+            instance_id=getattr(self, "instance_id", self.group_id),
+            is_healthy=getattr(self, "is_healthy", True),
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=0,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         self.cleanup()

+ 33 - 2
plugins/grc_plugin.py

@@ -9,7 +9,7 @@ from typing import List, Dict, Any, Callable, Optional, Set, Tuple
 from curl_cffi import requests, const
 
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 
 MODERN_BROWSERS: List[str] = [
     "chrome",
@@ -26,6 +26,9 @@ class GrcPlugin(IVSPlg):
     签证预约插件
     适配爱尔兰希腊签证 (GR) 流程
     """
+    name = "grc_plugin"
+    version = "1.0.0"
+    description = "爱尔兰希腊使馆签证预约插件 (SuperSaaS预约系统适配)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -617,4 +620,32 @@ class GrcPlugin(IVSPlg):
             self.is_healthy = False
             raise RateLimiteddError()
         else:
-            raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
+            raise BizLogicError(message=f"HTTP Error {resp.status_code}: {resp.text[:100]}")
+
+    def cleanup(self):
+        if self.session:
+            try:
+                self.session.close()
+            except Exception:
+                pass
+            self.session = None
+
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
+        state = "running" if self.is_healthy else "unhealthy"
+
+        return PluginStatus(
+            instance_id=self.group_id,
+            is_healthy=self.is_healthy,
+            state=state,
+            current_url="https://www.supersaas.com/schedule/login/GreekEmbassyInDublin/Visas",
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=session_age,
+            last_active_at=utc_now_str(),
+        )
+
+    def __del__(self):
+        self.cleanup()

+ 27 - 1
plugins/ita_plugin.py

@@ -16,7 +16,7 @@ from DrissionPage import ChromiumPage, ChromiumOptions
 
 import configure
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 from toolkit.mihomo_tunnel import MihomoTunnel
 from toolkit.vs_cloud_api import VSCloudApi
 from utils.mouse import HumanMouse
@@ -43,6 +43,9 @@ class BrowserResponse:
 # 2. ItaPlugin 核心逻辑
 # ==========================================
 class ItaPlugin(IVSPlg):
+    name = "ita_plugin"
+    version = "1.0.0"
+    description = "意大利Prenot@Mi领事预约插件 (支持拟人化交互与多领区调度)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -743,6 +746,29 @@ class ItaPlugin(IVSPlg):
             except: pass
             self.tunnel = None
                  
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        state = "running" if self.is_healthy else "unhealthy"
+
+        return PluginStatus(
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=0,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         """
         析构函数:当对象被垃圾回收时自动调用

+ 27 - 1
plugins/pol_plugin.py

@@ -17,7 +17,7 @@ from DrissionPage import ChromiumPage, ChromiumOptions
 
 
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.proxy_tunnel import ProxyTunnel
 
@@ -49,6 +49,9 @@ class PolPlugin(IVSPlg):
     """
     Poland (e-konsulat) 签证预约插件 (Browser + Tunnel Mode)
     """
+    name = "pol_plugin"
+    version = "1.0.0"
+    description = "波兰e-konsulat签证预约插件 (支持验证码识别与隧道代理)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -418,5 +421,28 @@ class PolPlugin(IVSPlg):
             except: pass
             self.tunnel = None
         
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        state = "running" if getattr(self, "is_healthy", True) else "unhealthy"
+
+        return PluginStatus(
+            instance_id=getattr(self, "instance_id", self.group_id),
+            is_healthy=getattr(self, "is_healthy", True),
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=0,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         self.cleanup()

+ 52 - 0
plugins/prt_plugin.py

@@ -0,0 +1,52 @@
+from vs_plg import IVSPlg
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, PluginStatus, utc_now_str
+
+
+class PrtPlugin(IVSPlg):
+    """
+    葡萄牙 (E-Visa / MAE) 签证预约插件
+    """
+    name = "prt_plugin"
+    version = "1.0.0"
+    description = "葡萄牙领事预约插件 (MAE / E-Visa 系统适配)"
+
+    def __init__(self, group_id: str):
+        self.group_id = group_id
+        self.config = None
+        self.logger = None
+
+    def set_config(self, config: VSPlgConfig):
+        self.config = config
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def create_session(self):
+        pass
+
+    def query(self, apt_type: AppointmentType) -> VSQueryResult:
+        return VSQueryResult()
+
+    def book(self, slot_info: VSQueryResult, user_inputs) -> VSBookResult:
+        return VSBookResult()
+
+    def keep_alive(self):
+        pass
+
+    def health_check(self) -> bool:
+        return True
+
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        return PluginStatus(
+            instance_id=self.group_id,
+            is_healthy=True,
+            state="running",
+            current_url="",
+            account=account_name,
+            session_age_sec=0,
+            last_active_at=utc_now_str(),
+        )
+
+    def cleanup(self):
+        pass

+ 28 - 1
plugins/tls_plugin.py

@@ -14,7 +14,7 @@ from DrissionPage import ChromiumPage, ChromiumOptions
 
 import configure
 from vs_plg import IVSPlg
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
 from toolkit.mihomo_tunnel import MihomoTunnel
 from utils.mouse import HumanMouse, MOUSE_PROFILES
@@ -46,6 +46,9 @@ class TlsPlugin(IVSPlg):
     """
     TLSContact 签证预约插件 (DrissionPage 版)
     """
+    name = "tls_plugin"
+    version = "1.0.0"
+    description = "TLSContact欧洲多国签证预约插件 (DrissionPage拟人化与CF挑战破解)"
 
     def __init__(self, group_id: str):
         self.group_id = group_id
@@ -1022,6 +1025,30 @@ class TlsPlugin(IVSPlg):
             except: pass
             self.tunnel = None
         
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        session_age = int(time.time() - self.session_create_time) if hasattr(self, "session_create_time") and self.session_create_time > 0 else 0
+        state = "running" if self.is_healthy else "unhealthy"
+
+        return PluginStatus(
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=session_age,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         """
         析构函数:当对象被垃圾回收时自动调用

+ 28 - 1
plugins/usa_plugin.py

@@ -19,7 +19,7 @@ from toolkit.mihomo_tunnel import MihomoTunnel
 from utils.mouse import HumanMouse
 from utils.keyboard import HumanKeyboard
 from utils.fingerprint_utils import FingerprintGenerator
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, AvailabilityStatus, TimeSlot, DateAvailability, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 
 
 class BrowserResponse:
@@ -44,6 +44,9 @@ class BrowserResponse:
 
 
 class UsaPlugin(IVSPlg):
+    name = "usa_plugin"
+    version = "1.0.0"
+    description = "美签USVisaScheduling预约插件 (B2C认证、流控调度与自动占位)"
     
     LOCATIONS = {
         "SHANGHAI": {"name": "SHANGHAI", "id": "096bf614-b0db-ec11-a7b4-001dd80234f6"},
@@ -591,6 +594,30 @@ class UsaPlugin(IVSPlg):
             except: pass
             self.tunnel = None
         
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        session_age = int(time.time() - self.session_create_time) if hasattr(self, "session_create_time") and self.session_create_time > 0 else 0
+        state = "running" if self.is_healthy else "unhealthy"
+
+        return PluginStatus(
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=session_age,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         """
         析构函数:当对象被垃圾回收时自动调用

+ 31 - 1
plugins/vfs_plugin.py

@@ -20,7 +20,7 @@ from cryptography.hazmat.backends import default_backend
 
 import configure
 from vs_plg import IVSPlg 
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError 
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, DateAvailability, AvailabilityStatus, NotFoundError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError, BizLogicError, PluginStatus, utc_now_str 
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.mihomo_tunnel import MihomoTunnel
 from toolkit.captcha_breaker import recognize_vfs_captcha_with_qwen
@@ -114,6 +114,10 @@ class BrowserResponse:
         return self.text.encode('utf-8')
 
 class VfsPlugin(IVSPlg):
+    name = "vfs_plugin"
+    version = "1.0.0"
+    description = "VFS Global全球多国签证预约插件 (支持多中心、多签证类型与CF破解)"
+
     def __init__(self, group_id: str):
         self.group_id = group_id
         self.config: Optional[VSPlgConfig] = None
@@ -1420,6 +1424,32 @@ class VfsPlugin(IVSPlg):
             except: pass
             self.tunnel = None
                  
+    def get_plugin_status(self) -> PluginStatus:
+        account_name = self.config.account.username if self.config and self.config.account else ""
+        proxy_info = f"{self.config.proxy.ip}:{self.config.proxy.port}" if self.config and self.config.proxy and self.config.proxy.ip else ""
+        current_url = ""
+        if self.page:
+            try:
+                current_url = self.page.url
+            except Exception:
+                pass
+
+        session_age = int(time.time() - self.session_create_time) if self.session_create_time > 0 else 0
+        state = "running" if self.is_healthy else "unhealthy"
+        if not self.jwt_token and self.page:
+            state = "logging_in"
+
+        return PluginStatus(
+            instance_id=self.instance_id,
+            is_healthy=self.is_healthy,
+            state=state,
+            current_url=current_url,
+            account=account_name,
+            proxy=proxy_info,
+            session_age_sec=session_age,
+            last_active_at=utc_now_str(),
+        )
+
     def __del__(self):
         """
         析构函数:当对象被垃圾回收时自动调用

+ 37 - 8
sentinel.py

@@ -6,7 +6,7 @@ import threading
 from datetime import datetime
 from typing import List, Dict, Callable
 
-from vs_types import GroupConfig, VSPlgConfig, Task, QueryWaitMode
+from vs_types import GroupConfig, VSPlgConfig, Task, QueryWaitMode, GroupStatus, PluginStatus, utc_now_str
 from vs_plg_factory import VSPlgFactory 
 from toolkit.vs_cloud_api import VSCloudApi
 from utils.safe_redis_cli import SafeRedisClient
@@ -53,6 +53,32 @@ class SentinelGCO:
                 
             self.m_cfg = new_cfg
 
+    def get_status(self) -> GroupStatus:
+        with self.m_lock:
+            tasks = list(self.m_tasks)
+            gid = self.m_cfg.identifier
+            enable = self.m_cfg.enable
+            plugin_name = self.m_cfg.plugin_config.plugin_name
+
+        plugins_status = []
+        healthy_count = 0
+        for t in tasks:
+            if t and t.instance:
+                st = t.instance.get_plugin_status()
+                if st.is_healthy:
+                    healthy_count += 1
+                plugins_status.append(st)
+
+        return GroupStatus(
+            group_id=gid,
+            enable=enable,
+            plugin_name=plugin_name,
+            total_tasks=len(tasks),
+            healthy_tasks=healthy_count,
+            plugins=plugins_status,
+            updated_at=utc_now_str(),
+        )
+
     def start(self):
         if not self.m_cfg.enable:
             return
@@ -215,6 +241,7 @@ class SentinelGCO:
 
     def _spawn_sentinel_worker(self):
         instance = None
+        task = None
         success = False
         plg_cfg = None
         try:
@@ -237,13 +264,12 @@ class SentinelGCO:
             instance = self.m_factory.create(self.m_cfg.identifier, self.m_cfg.plugin_config.plugin_name)
             instance.set_log(self.m_logger)
             instance.set_config(plg_cfg)
-            instance.create_session()
-            
+            task = Task(instance=instance, qw_cfg=self.m_cfg.sentinel.query_wait, next_run=time.time() + 999999, book_allowed=False)
             with self.m_lock:
-                self.m_tasks.append(
-                    Task(instance=instance, qw_cfg=self.m_cfg.sentinel.query_wait, next_run=time.time(), book_allowed=False)
-                )
+                self.m_tasks.append(task)
 
+            instance.create_session()
+            task.next_run = time.time()
             success = True
             self._log(f"+++ Sentinel spawned: {plg_cfg.account.username}")
         except Exception as e:
@@ -257,5 +283,8 @@ class SentinelGCO:
                 if plg_cfg and plg_cfg.account.username != "Guest":
                     VSCloudApi.lock_account(plg_cfg.account.id, self.m_cfg.login_backoff)
         finally:
-            if not success and instance is not None:
-                instance.cleanup()
+            if not success:
+                if task:
+                    self._remove_task(task, "spawn failed")
+                elif instance is not None:
+                    instance.cleanup()

+ 158 - 87
booker_standalone.py → standalone.py

@@ -1,61 +1,130 @@
 import os
 import time
 import random
+import threading
 from datetime import datetime
-from typing import List, Dict, Callable
+from typing import Dict, Callable, Optional
 
-from vs_types import BookerStandaloneConfig, QueryWaitMode, VSPlgConfig, VSQueryResult, VSBookResult
+from vs_types import BookerStandaloneConfig, QueryWaitMode, VSPlgConfig, VSQueryResult, VSBookResult, GroupStatus, PluginStatus, utc_now_str
 from vs_plg_factory import VSPlgFactory
 from utils.safe_redis_cli import SafeRedisClient
 from toolkit.vs_cloud_api import VSCloudApi
 from toolkit.thread_pool import ThreadPool
 
 
-class BookerStandalone:
-    def __init__(self, config: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
+class StandaloneGCO:
+    """
+    Standalone GCO 实例管理器。
+    遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。
+    """
+    TAG = "STANDALONE"
+
+    def __init__(self, cfg: BookerStandaloneConfig, redis_conf: Dict, logger: Callable[[str], None] = None):
+        self.m_cfg = cfg
         self.m_logger = logger
         self.m_factory = VSPlgFactory()
-        self.m_cfg = config
-        self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
         self.m_instance = None
-        self.m_running = False
-        self.m_next_query_time = 0.0
-        self.m_last_login_time = 0.0
+        self.m_lock = threading.RLock()
+        self.m_stop_event = threading.Event()
+        self.m_last_login_time = 0
+        self.m_next_query_time = 0
         self.m_current_dates = {}
+        self.redis_client = SafeRedisClient(redis_conf, self.m_logger)
 
-    def _log(self, message):
+    def _log(self, message: str):
+        prefix = f"[-] [{self.TAG}] [{self.m_cfg.identifier}]"
         if self.m_logger:
-            self.m_logger(f'[BOOKER] {message}')
+            self.m_logger(f"{prefix} {message}")
         else:
-            print(f'[BOOKER] {message}')
+            print(f"{prefix} {message}")
 
     def _get_wait_interval(self) -> float:
         """根据配置计算下一次查询的等待时间"""
-        if self.m_cfg.query_wait.mode == QueryWaitMode.Loop:
+        mode = self.m_cfg.query_wait.mode
+        if mode == QueryWaitMode.Loop:
             return 1.0
-        elif  self.m_cfg.query_wait.mode == QueryWaitMode.Fixed:
+        elif mode == QueryWaitMode.Fixed:
             return float(self.m_cfg.query_wait.fixed_wait)
-        elif  self.m_cfg.query_wait.mode == QueryWaitMode.Random:
+        elif mode == QueryWaitMode.Random:
             return random.uniform(self.m_cfg.query_wait.random_min, self.m_cfg.query_wait.random_max)
         return 30.0
-    
+
     def _is_within_active_hours(self) -> bool:
-        """
-        判断当前是否在允许创建实例的时间段内
-        """
+        """判断当前是否在允许创建实例和查询的时间段内"""
         start_str = self.m_cfg.active_time_start
         end_str = self.m_cfg.active_time_end
         current_bj_time = datetime.utcnow().time()
         start_time = datetime.strptime(start_str, "%H:%M").time()
         end_time = datetime.strptime(end_str, "%H:%M").time()
         return start_time <= current_bj_time <= end_time
-    
+
     def update_config(self, new_cfg: BookerStandaloneConfig):
-        """
-        动态更新配置
-        """
-        pass
-    
+        """动态更新配置"""
+        with self.m_lock:
+            if self.m_cfg.enable and not new_cfg.enable:
+                self._log("Config dynamically updated: Group DISABLED.")
+            elif not self.m_cfg.enable and new_cfg.enable:
+                self._log("Config dynamically updated: Group ENABLED.")
+            else:
+                self._log("Config dynamically updated: Parameters refreshed.")
+            self.m_cfg = new_cfg
+
+    def get_status(self) -> GroupStatus:
+        with self.m_lock:
+            instance = self.m_instance
+            gid = self.m_cfg.identifier
+            enable = self.m_cfg.enable
+            plugin_name = self.m_cfg.plugin_config.plugin_name
+
+        plugins_status = []
+        healthy_count = 0
+        if instance:
+            st = instance.get_plugin_status()
+            if st.is_healthy:
+                healthy_count += 1
+            plugins_status.append(st)
+
+        return GroupStatus(
+            group_id=gid,
+            enable=enable,
+            plugin_name=plugin_name,
+            total_tasks=1 if instance else 0,
+            healthy_tasks=healthy_count,
+            plugins=plugins_status,
+            updated_at=utc_now_str(),
+        )
+
+    def start(self):
+        """非阻塞启动,注册插件并开启后台工作线程"""
+        if not self.m_cfg.enable:
+            return
+
+        self._log("Starting Standalone GCO...")
+        plugin_name = self.m_cfg.plugin_config.plugin_name
+        class_name = "".join(part.title() for part in plugin_name.split('_'))
+        plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
+        self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
+
+        worker_name = f"Standalone-{self.m_cfg.identifier}"
+        threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
+
+    def stop(self):
+        """优雅停止"""
+        self._log("Stopping Standalone GCO...")
+        self.m_stop_event.set()
+        self._cleanup_instance("standalone stopped")
+
+    def _cleanup_instance(self, reason: str = ""):
+        with self.m_lock:
+            if self.m_instance is not None:
+                try:
+                    self._log(f"🧹 Cleaned up instance. Reason: {reason}")
+                    self.m_instance.cleanup()
+                except Exception as e:
+                    self._log(f"Cleanup failed for instance. Reason: {reason}. Error: {e}")
+                finally:
+                    self.m_instance = None
+
     def _notify_date_changes(self, query_result: VSQueryResult):
         current_earliest_date = query_result.earliest_date
         apt_type = query_result.apt_type
@@ -77,7 +146,7 @@ class BookerStandalone:
                     except Exception as e:
                         self._log(f"Failed to notify to cloud: {e}")
                 ThreadPool.getInstance().enqueue(_push_to_wx)
-    
+
     def _notify_book_result(self, book_result: VSBookResult):
         if book_result.success:
             def _update_cloud_success():
@@ -96,35 +165,19 @@ class BookerStandalone:
                 except Exception as e:
                     self._log(f"Failed to update success state to cloud: {e}")
             ThreadPool.getInstance().enqueue(_update_cloud_success)
-    
-    def _countdown_wait(self, seconds: float, wait_for='') -> bool:
-        """倒计时等待,动态刷新同一行,返回 False 表示被 stop 中断"""
-        end = time.time() + seconds
-        last_remaining = None
-        while self.m_running and time.time() < end:
-            remaining = int(end - time.time())
-            if remaining != last_remaining:
-                print(f"[BOOKER] Next {wait_for} in {remaining} seconds... (stop to exit)", end='\r', flush=True)
-                last_remaining = remaining
-            time.sleep(1)
-        print()
-        return self.m_running    
 
     def _init_instance(self):
         """初始化单实例并进行登录创建会话"""
-        if self.m_instance is not None:
-            self.m_instance.cleanup()
-        
+        self._cleanup_instance("recreating new session")
+
         now = time.time()
         if now < self.m_last_login_time + self.m_cfg.login_interval:
-            wait = self.m_last_login_time + self.m_cfg.login_interval - now
-            self._countdown_wait(wait, wait_for='init instance')
-            
+            wait_time = self.m_last_login_time + self.m_cfg.login_interval - now
+            self._log(f"Waiting {int(wait_time)}s for login interval cooldown...")
+            if self.m_stop_event.wait(wait_time):
+                return
+
         plugin_name = self.m_cfg.plugin_config.plugin_name
-        class_name = "".join(part.title() for part in plugin_name.split('_'))
-        plugin_path = os.path.join(self.m_cfg.plugin_config.lib_path, self.m_cfg.plugin_config.plugin_bin)
-        self.m_factory.register_plugin(plugin_name, plugin_path, class_name)
-        
         plg_cfg = VSPlgConfig()
         plg_cfg.debug = self.m_cfg.debug
         plg_cfg.account = self.m_cfg.account
@@ -132,49 +185,67 @@ class BookerStandalone:
         plg_cfg.proxy = type(plg_cfg.proxy)(**proxy)
         plg_cfg.free_config = self.m_cfg.free_config
         plg_cfg.session_max_life = self.m_cfg.session_max_life
-        
-        self.m_instance = self.m_factory.create("single_task", plugin_name)
-        self.m_instance.set_log(self.m_logger)
-        self.m_instance.set_config(plg_cfg)
-        
-        self.m_next_query_time = time.time() + self._get_wait_interval()
-        self.m_last_login_time = time.time()
-        self.m_instance.create_session()
-        self._log("Session created successfully.")
 
-    def start(self):
+        instance = self.m_factory.create(self.m_cfg.identifier, plugin_name)
+        instance.set_log(self.m_logger)
+        instance.set_config(plg_cfg)
+        with self.m_lock:
+            self.m_instance = instance
+
+        self._log("Creating session...")
+        try:
+            instance.create_session()
+            self.m_last_login_time = time.time()
+            self.m_next_query_time = time.time() + self._get_wait_interval()
+            self._log("Session created successfully.")
+        except Exception:
+            self._cleanup_instance("session creation failed")
+            raise
+
+    def _worker_loop(self):
         """
-        单线程无限循环:心跳保活 -> 时间判定 -> 查询 -> 预定
+        后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定
         """
-        self.m_running = True
-        self._log("Auto Booker Started.")
-        
-        while self.m_running:
-            if not self._is_within_active_hours():
-                continue
-            try:
-                self._init_instance()
-                break
-            except Exception as e:
-                self._log(f"Failed to create session: {e}. Retrying in 10s...")
-                time.sleep(10)
+        self._log("Standalone worker loop started.")
 
-        while self.m_running:
+        while not self.m_stop_event.is_set():
             try:
-                now = time.time()
+                if not self.m_cfg.enable:
+                    self.m_stop_event.wait(1.0)
+                    continue
+
                 if not self._is_within_active_hours():
+                    self.m_stop_event.wait(5.0)
                     continue
-                
-                if not self.m_instance.health_check():
+
+                # 1. 会话初始化
+                if self.m_instance is None:
+                    try:
+                        self._init_instance()
+                    except Exception as e:
+                        self._log(f"Failed to create session: {e}. Retrying in 10s...")
+                        self.m_stop_event.wait(10.0)
+                        continue
+
+                # 2. 健康检查
+                if self.m_instance and not self.m_instance.health_check():
                     self._log("Health check failed. Session dead. Recreating session...")
-                    self._init_instance()
+                    self._cleanup_instance("session health check failed")
                     continue
-                
+
+                # 3. 查询等待
+                now = time.time()
                 if now < self.m_next_query_time:
-                    wait = self.m_next_query_time - now
-                    self._countdown_wait(wait, wait_for="query slot")
+                    wait_sec = min(self.m_next_query_time - now, 1.0)
+                    self.m_stop_event.wait(wait_sec)
+                    continue
 
+                # 4. 随机选取 routing_key 进行查询
                 apt_types = self.m_cfg.appointment_types
+                if not apt_types:
+                    self.m_stop_event.wait(2.0)
+                    continue
+
                 weights = [float(t.weight) for t in apt_types]
                 apt_type = random.choices(apt_types, weights=weights, k=1)[0]
 
@@ -183,17 +254,17 @@ class BookerStandalone:
                 query_result.apt_type = apt_type
                 self.m_next_query_time = time.time() + self._get_wait_interval()
                 self._notify_date_changes(query_result)
+
+                # 5. 发现档期,执行自动预定
                 if query_result.success:
                     self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
-                    # 5. 执行预定
                     book_result = self.m_instance.book(query_result, self.m_cfg.user_preferences)
                     self._notify_book_result(book_result)
                     if book_result.success:
                         self._log(f"🎉 BOOKING SUCCESSFUL for {apt_type.routing_key}!")
-                        break
+                        # 预定成功后可继续或等待后续任务
+                        self.m_stop_event.wait(5.0)
+
             except Exception as e:
-                self._log(f"Loop Exception: {e}")
-                
-    def stop(self):
-        """外部中断时调用"""
-        self.m_running = False
+                self._log(f"Standalone loop exception: {e}")
+                self.m_stop_event.wait(2.0)

+ 161 - 0
utils/plugin_updater.py

@@ -0,0 +1,161 @@
+import os
+import ast
+import py_compile
+import requests
+from typing import Dict, Any, List, Optional
+
+
+from vs_types import PluginMeta
+
+PLUGINS_DIR = "plugins"
+
+# 纯内存缓存,无需落盘
+_IN_MEMORY_PLUGIN_INFO: Dict[str, Dict[str, str]] = {}
+
+
+def _parse_version(v_str: str) -> tuple:
+    """将版本字符串解析为数字元组进行比较,如 '1.2.3' -> (1, 2, 3)"""
+    try:
+        clean_v = str(v_str).strip().lstrip("v")
+        return tuple(int(part) for part in clean_v.split(".") if part.isdigit())
+    except Exception:
+        return (0,)
+
+
+def is_newer_version(cloud_version: str, local_version: str) -> bool:
+    """判断云端版本是否高于本地版本"""
+    return _parse_version(cloud_version) > _parse_version(local_version)
+
+
+def _extract_plugin_meta_from_ast(filepath: str) -> Dict[str, str]:
+    """
+    通过 AST 静态分析插件代码中的 IVSPlg 子类元数据(name, version, description),
+    避免直接 import 产生网络请求或浏览器启动等副作用。
+    """
+    info = {"version": "1.0.0", "name": "", "description": ""}
+    try:
+        with open(filepath, "r", encoding="utf-8") as f:
+            tree = ast.parse(f.read(), filename=filepath)
+
+        for node in tree.body:
+            # 1. 检查模块级变量 (如 __version__ = "1.0.0")
+            if isinstance(node, ast.Assign):
+                for target in node.targets:
+                    if isinstance(target, ast.Name):
+                        if target.id == "__version__" and isinstance(node.value, ast.Constant):
+                            info["version"] = str(node.value.value)
+                        elif target.id == "__description__" and isinstance(node.value, ast.Constant):
+                            info["description"] = str(node.value.value)
+
+            # 2. 检查类定义 (如 class TlsPlugin(IVSPlg): version = "1.0.0")
+            elif isinstance(node, ast.ClassDef):
+                for item in node.body:
+                    if isinstance(item, ast.Assign):
+                        for target in item.targets:
+                            if isinstance(target, ast.Name) and isinstance(item.value, ast.Constant):
+                                if target.id == "version":
+                                    info["version"] = str(item.value.value)
+                                elif target.id == "name":
+                                    info["name"] = str(item.value.value)
+                                elif target.id == "description":
+                                    info["description"] = str(item.value.value)
+    except Exception as e:
+        print(f"[PluginUpdater] AST parse error for {filepath}: {e}")
+
+    return info
+
+
+def scan_plugins(plugins_dir: str = PLUGINS_DIR) -> Dict[str, Dict[str, str]]:
+    """
+    运行时动态扫描 plugins 目录,读取所有插件的基本元数据到内存中(不写文件)
+    """
+    global _IN_MEMORY_PLUGIN_INFO
+    scanned_info: Dict[str, Dict[str, str]] = {}
+
+    if os.path.isdir(plugins_dir):
+        for fname in sorted(os.listdir(plugins_dir)):
+            if fname.endswith(".py") and not fname.startswith("__"):
+                plugin_name = fname[:-3]
+                filepath = os.path.join(plugins_dir, fname)
+                meta = _extract_plugin_meta_from_ast(filepath)
+                meta["filename"] = fname
+                if not meta["name"]:
+                    meta["name"] = plugin_name
+                scanned_info[plugin_name] = meta
+
+    _IN_MEMORY_PLUGIN_INFO = scanned_info
+    return _IN_MEMORY_PLUGIN_INFO
+
+
+def get_installed_plugins(plugins_dir: str = PLUGINS_DIR) -> Dict[str, str]:
+    """
+    获取本地已安装插件名与版本的映射字典
+    返回格式: {"tls_plugin": "1.0.0", "vfs_plugin": "1.0.0"}
+    """
+    all_info = scan_plugins(plugins_dir)
+    return {k: v.get("version", "1.0.0") for k, v in all_info.items()}
+
+
+def get_installed_plugin_metas(plugins_dir: str = PLUGINS_DIR) -> List[PluginMeta]:
+    """
+    获取本地已安装插件的完整元数据对象列表(含 name, version, description, filename)
+    """
+    all_info = scan_plugins(plugins_dir)
+    metas = []
+    for k, v in all_info.items():
+        metas.append(
+            PluginMeta(
+                name=v.get("name", k),
+                version=v.get("version", "1.0.0"),
+                description=v.get("description", ""),
+                filename=v.get("filename", f"{k}.py"),
+            )
+        )
+    return metas
+
+
+def download_and_install_plugin(
+    plugin_name: str,
+    version: str,
+    download_url: Optional[str] = None,
+    code_content: Optional[str] = None,
+    filename: Optional[str] = None,
+    plugins_dir: str = PLUGINS_DIR,
+) -> bool:
+    """
+    下载/写入新版本插件文件,预检语法并原子替换,随后刷新内存中的插件版本信息
+    """
+    target_filename = filename or f"{plugin_name}.py"
+    target_path = os.path.join(plugins_dir, target_filename)
+    tmp_path = target_path + ".tmp"
+
+    try:
+        # 1. 获取代码内容(支持 URL 下载或直接传 code_content)
+        if code_content is not None:
+            with open(tmp_path, "w", encoding="utf-8") as f:
+                f.write(code_content)
+        elif download_url:
+            resp = requests.get(download_url, timeout=30)
+            resp.raise_for_status()
+            with open(tmp_path, "wb") as f:
+                f.write(resp.content)
+        else:
+            raise ValueError(f"Neither download_url nor code_content provided for '{plugin_name}'")
+
+        # 2. 语法预检(防止下载坏代码导致运行时崩溃)
+        py_compile.compile(tmp_path, doraise=True)
+
+        # 3. 原子覆盖替换到 plugins/ 目录
+        os.replace(tmp_path, target_path)
+
+        # 4. 重新触发内存动态扫描,更新内存中的版本数据(不落盘)
+        scan_plugins(plugins_dir)
+
+        return True
+    except Exception as e:
+        if os.path.exists(tmp_path):
+            try:
+                os.remove(tmp_path)
+            except Exception:
+                pass
+        raise RuntimeError(f"Failed to upgrade plugin '{plugin_name}' to {version}: {e}")

+ 23 - 2
vs_plg.py

@@ -1,7 +1,7 @@
 # vs_plg.py
 from typing import Callable, List, Dict
 from abc import ABC, abstractmethod
-from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult
+from vs_types import VSPlgConfig, AppointmentType, VSQueryResult, VSBookResult, PluginStatus
 
 # ================== 接口类 ==================
 class IVSPlg(ABC):
@@ -10,6 +10,20 @@ class IVSPlg(ABC):
     该接口定义了签证系统的基本操作,包括配置、会话管理、查询、预订、
     健康检查以及错误处理等。所有具体的签证 API 实现都需要继承该接口。
     """
+    name: str = ""
+    version: str = "1.0.0"
+    description: str = ""
+
+    @classmethod
+    def get_plugin_info(cls) -> Dict[str, str]:
+        """
+        @brief 获取插件静态元数据信息
+        """
+        return {
+            "name": cls.name or cls.__name__,
+            "version": cls.version,
+            "description": cls.description,
+        }
     
     @abstractmethod
     def set_config(self, config: VSPlgConfig):
@@ -71,4 +85,11 @@ class IVSPlg(ABC):
         """
         @brief 清理实例使用的资源
         """
-        pass
+        pass
+
+    def get_plugin_status(self) -> PluginStatus:
+        """
+        @brief 获取插件实例当前的运行状态快照(默认返回基础状态,插件按需重写)
+        @return PluginStatus
+        """
+        return PluginStatus()

+ 71 - 0
vs_types.py

@@ -1,5 +1,7 @@
 import json
+import time
 from datetime import datetime, timezone
+from dataclasses import dataclass, field, asdict
 from pydantic import BaseModel, Field
 from enum import Enum
 from typing import Optional, List, Any, Dict
@@ -232,3 +234,72 @@ class Task(BaseModel):
         "underscore_attrs_are_private": True,
         "arbitrary_types_allowed": True
     }
+
+
+# ================== 状态监控数据结构 ==================
+def utc_now_str() -> str:
+    """获取当前人类可读的 UTC 时间字符串,格式: YYYY-MM-DD HH:MM:SS"""
+    return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
+
+
+@dataclass
+class PluginStatus:
+    """单个插件实例的运行状态"""
+    instance_id: str = ""
+    is_healthy: bool = True
+    state: str = "idle"            # idle / logging_in / querying / booking / challenge / cooldown / error 等
+    current_url: str = ""
+    account: str = ""
+    proxy: str = ""
+    session_age_sec: int = 0       # 会话存活时长(秒)
+    last_active_at: str = ""       # 上次活跃 UTC 时间(人类可读)
+
+    def to_dict(self) -> Dict[str, Any]:
+        return asdict(self)
+
+
+@dataclass
+class GroupStatus:
+    """单个组(Group/GCO)的状态容器,聚合该组下所有插件实例状态"""
+    group_id: str = ""
+    enable: bool = True
+    plugin_name: str = ""
+    wrapper_state: str = ""        # CREATED / RUNNING / STOPPED / FAILED 等
+    total_tasks: int = 0
+    healthy_tasks: int = 0
+    plugins: List[PluginStatus] = field(default_factory=list)
+    updated_at: str = field(default_factory=utc_now_str)
+
+    def to_dict(self) -> Dict[str, Any]:
+        return asdict(self)
+
+
+@dataclass
+class PluginMeta:
+    """插件静态元数据信息"""
+    name: str = ""                                  # 插件名,如 tls_plugin
+    version: str = "1.0.0"                          # 插件版本号
+    description: str = ""                          # 插件中文功能描述
+    filename: str = ""                             # 插件文件名,如 tls_plugin.py
+
+    def to_dict(self) -> Dict[str, Any]:
+        return asdict(self)
+
+
+@dataclass
+class RoleStatus:
+    """顶层容器:表明是 Standalone / Sentinel / Booker 收集到的全量状态"""
+    role: str = ""                                  # "standalone" / "sentinel" / "booker"
+    node_id: str = ""                               # "node01" 等
+    installed_plugins: List[PluginMeta] = field(default_factory=list) # 本地已安装插件详细列表
+    groups: List[GroupStatus] = field(default_factory=list)
+    collected_at: str = field(default_factory=utc_now_str)
+
+    def to_dict(self) -> Dict[str, Any]:
+        return asdict(self)
+
+
+# 语义化别名
+RunnerStatus = RoleStatus
+CoordinatorStatus = RoleStatus
+