소스 검색

refactor: translate comments and error messages from Chinese to English across codebase

jerry 1 개월 전
부모
커밋
186c1e4f0d
25개의 변경된 파일과 827개의 추가작업 그리고 665개의 파일을 삭제
  1. 120 69
      booker.py
  2. 19 116
      config/config_sentinel.yaml
  3. 13 13
      configure.py
  4. 119 46
      core_types.py
  5. 10 10
      gco_wrapper.py
  6. 3 3
      log_macros.py
  7. 7 10
      logger_setup.py
  8. 20 20
      main.py
  9. 20 20
      plugin.py
  10. 12 12
      plugin_factory.py
  11. 68 48
      sentinel.py
  12. 82 56
      standalone.py
  13. 124 31
      test/test_metadata_exception.py
  14. 17 17
      test/test_proxy_manager.py
  15. 10 10
      toolkit/backoff.py
  16. 25 25
      toolkit/captcha_breaker.py
  17. 2 3
      toolkit/mihomo_tunnel.py
  18. 4 4
      toolkit/notifier.py
  19. 3 3
      toolkit/ocr_engine.py
  20. 60 59
      toolkit/proxy_manager.py
  21. 32 33
      toolkit/proxy_tunnel.py
  22. 10 10
      toolkit/thread_pool.py
  23. 30 30
      utils/flow_engine.py
  24. 10 10
      utils/redis_stream_logger.py
  25. 7 7
      utils/safe_redis_cli.py

+ 120 - 69
booker.py

@@ -3,14 +3,15 @@ import time
 import json
 import json
 import threading
 import threading
 import random
 import random
-from datetime import datetime
+from datetime import datetime, timedelta, timezone
 from typing import List, Dict, Callable, Optional
 from typing import List, Dict, Callable, Optional
 
 
 from core_types import (
 from core_types import (
     GroupConfig, PluginConfig, Account, Task, BookResult, QueryResult, 
     GroupConfig, PluginConfig, Account, Task, BookResult, QueryResult, 
     AppointmentType, QueryWaitMode, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str,
     AppointmentType, QueryWaitMode, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str,
     BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
     BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
-    NetworkTimeoutError
+    NetworkTimeoutError, BizLogicError, AccountStateError, AccountAuthError,
+    AccountBannedError, AccountIncompleteError, AccountNotFoundError, normalize_error
 )
 )
 from plugin_factory import PluginFactory 
 from plugin_factory import PluginFactory 
 from toolkit.cloud_api import CloudApi
 from toolkit.cloud_api import CloudApi
@@ -22,7 +23,7 @@ from utils.safe_redis_cli import SafeRedisClient
 
 
 class BaseBookerGCO:
 class BaseBookerGCO:
     """
     """
-    Booker 基类,封装公共的基础设施与通用的生命周期管理、逻辑循环等。
+    Base Booker class encapsulating shared infrastructure, lifecycle management, and logic loops.
     """
     """
     TAG = "BOOKER"
     TAG = "BOOKER"
 
 
@@ -86,7 +87,7 @@ class BaseBookerGCO:
         self._start_additional_threads()
         self._start_additional_threads()
 
 
     def _start_additional_threads(self):
     def _start_additional_threads(self):
-        """子类扩展线程的 Hook"""
+        """Hook for subclasses to start additional background threads."""
         pass
         pass
 
 
     def stop(self):
     def stop(self):
@@ -95,7 +96,7 @@ class BaseBookerGCO:
         self._cleanup_all_tasks("booker stop")
         self._cleanup_all_tasks("booker stop")
 
 
     def update_config(self, new_cfg: GroupConfig):
     def update_config(self, new_cfg: GroupConfig):
-        """动态更新配置"""
+        """Dynamically updates the configuration."""
         with self.m_lock:
         with self.m_lock:
             if self.m_cfg.enable and not new_cfg.enable:
             if self.m_cfg.enable and not new_cfg.enable:
                 self._log("Config dynamically updated: Group DISABLED. Will stop creating new tasks.")
                 self._log("Config dynamically updated: Group DISABLED. Will stop creating new tasks.")
@@ -132,7 +133,7 @@ class BaseBookerGCO:
         return removed
         return removed
 
 
     def _on_task_removed(self, task: Task):
     def _on_task_removed(self, task: Task):
-        """子类在 task 被移除时的自定义 Hook(如清理缓存)"""
+        """Hook for subclasses when a task is removed (e.g. cleaning up caches)."""
         pass
         pass
 
 
     def _cleanup_all_tasks(self, reason: str = ""):
     def _cleanup_all_tasks(self, reason: str = ""):
@@ -144,33 +145,14 @@ class BaseBookerGCO:
             self._cleanup_task(task, reason)
             self._cleanup_task(task, reason)
 
 
     def _on_all_tasks_cleaned(self):
     def _on_all_tasks_cleaned(self):
-        """子类在所有 task 被清空时的自定义 Hook"""
+        """Hook for subclasses when all tasks are cleared."""
         pass
         pass
 
 
     def _get_redis_key(self, routing_key: str) -> str:
     def _get_redis_key(self, routing_key: str) -> str:
         return f"vs:signal:{routing_key}"
         return f"vs:signal:{routing_key}"
 
 
-    def _normalize_error(self, err: Exception) -> BizException:
-        """规整化异常为领域异常 BizException,保留对历史特征字符串的兜底兼容"""
-        err_str = str(err)
-        # 如果是底层网络/CORS预检被拒导致的 Fetch 失败或 WAF 阻断,精准提升为 PermissionDeniedError
-        if "Failed to fetch" in err_str or "Status: 0" in err_str or "WAF Blocked" in err_str or "cf-mitigated" in err_str:
-            return PermissionDeniedError(message=err_str)
-        if isinstance(err, BizException):
-            return err
-        if "42901" in err_str or "Rate limited" in err_str:
-            return RateLimiteddError(message=err_str)
-        if "40101" in err_str or "Session expired" in err_str or "session invalid" in err_str.lower():
-            return SessionExpiredOrInvalidError(message=err_str)
-        if "40301" in err_str or "403" in err_str or "Cloudflare Access Denied" in err_str:
-            return PermissionDeniedError(message=err_str)
-        return BizException(
-            code=50000,
-            message=f"Unhandled ({type(err).__name__}): {err_str}",
-        )
-
     def _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
     def _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
-        """安全归还账号:将云端冷却时间重置为 0,避免非账号问题导致账号被误锁 3 小时"""
+        """Safely releases account: resets cloud cooldown to 0 to prevent 3-hour lockouts caused by non-account issues."""
         if acc and acc.id > 0 and acc.username not in ("", "Guest"):
         if acc and acc.id > 0 and acc.username not in ("", "Guest"):
             try:
             try:
                 CloudApi.Instance().lock_account(acc.id, 0)
                 CloudApi.Instance().lock_account(acc.id, 0)
@@ -178,6 +160,35 @@ class BaseBookerGCO:
             except Exception as e:
             except Exception as e:
                 self._log(f"Failed to release account [{acc.username}]: {e}")
                 self._log(f"Failed to release account [{acc.username}]: {e}")
 
 
+    def _disable_account_safely(self, acc: Optional[Account], reason: str = "") -> None:
+        """Safely disables account in cloud: sets status='disable', locks for 10 years, and records extra_data."""
+        if not acc or acc.id <= 0 or acc.username in ("", "Guest"):
+            return
+
+        try:
+            cloud = CloudApi.Instance()
+            url = f"{cloud.base_url}/api/account/update"
+            params = {"account_id": acc.id}
+            far_future = (datetime.now(timezone.utc) + timedelta(days=3650)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
+            payload = {
+                "status": "disable",
+                "next_use_time": far_future,
+                "extra_data": {
+                    "disable_reason": reason,
+                    "disabled_at": int(time.time()),
+                    "module": self.TAG,
+                    "group": getattr(self.m_cfg, "identifier", "")
+                }
+            }
+            cloud._perform_request('PUT', url, params=params, json_data=payload, headers=cloud._get_headers(), timeout=10)
+            self._log(f"🚫 [Account Disabled] Account [{acc.username}] (ID={acc.id}) permanently marked as 'disable' in Cloud API. Reason: {reason}")
+        except Exception as e:
+            self._log(f"Failed to set account status to disable via cloud API: {e}. Falling back to 10-year lock...")
+            try:
+                CloudApi.Instance().lock_account(acc.id, 86400 * 3650)
+            except Exception as lock_err:
+                self._log(f"Fallback 10-year lock also failed: {lock_err}")
+
     def _dispatch_error_policy(
     def _dispatch_error_policy(
         self,
         self,
         action: str,
         action: str,
@@ -187,20 +198,53 @@ class BaseBookerGCO:
         task_id: Optional[int] = None
         task_id: Optional[int] = None
     ) -> None:
     ) -> None:
         """
         """
-        Booker 错误调度与自愈策略引擎 (Policy Engine):
-        基于 (Action, 异常事实类型) 矩阵 + Booker 模式闭环执行自愈动作:
-        - spawn/login 时 429:判定为账号级限流,锁定账号,更新 Redis 订单/任务追踪器与生成冷却;
-        - book 时 429:档期提交频控或出口 IP 限制,不锁定账号,移除任务以轮换代理或重试;
-        - session expired / 401:会话失效,移除任务;
-        - 403 Forbidden / WAF:判定为 IP 受阻,移除任务以轮换代理;在 spawn 时立即安全释放账号;
-        - 内部直接完成日志输出与定时器维护,调用方无需感知具体冷却数值。
+        Booker error dispatch and self-healing policy engine:
+        Executes self-healing actions based on the (action, error type) matrix:
+        - AccountStateError (invalid credentials, banned, incomplete): Permanently disables pool account or fails order task, never releases back to pool.
+        - 429 during spawn/login: Account-level rate limit. Locks account, updates tracker & cooldown.
+        - 429 during book: Booking slot rate limit or egress IP throttle. Preserves account, removes task to rotate proxy.
+        - 401 / session expired: Session invalidated. Removes task.
+        - 403 Forbidden / WAF: IP blocked. Removes task to rotate proxy; safely releases account during spawn.
+        - Handles logging and timer backoffs internally.
         """
         """
-        biz_err = self._normalize_error(err)
+        biz_err = normalize_error(err)
         active_plg_cfg = plg_cfg or (task.instance.config if task else None)
         active_plg_cfg = plg_cfg or (task.instance.config if task else None)
         acc = active_plg_cfg.account if active_plg_cfg else None
         acc = active_plg_cfg.account if active_plg_cfg else None
 
 
-        # 1. 目标站限流 / 429
-        if isinstance(biz_err, RateLimiteddError):
+        # 0. Fatal Account State Error (credentials invalid, banned, incomplete, not found)
+        if isinstance(biz_err, AccountStateError):
+            self._log(f"🚨 [Account Fatal Error] {biz_err.__class__.__name__} during {action}: {biz_err.message} (code={biz_err.code})")
+            effective_task_id = task_id if task_id is not None else (task.task_ref if task else None)
+
+            # If bound order task, update VAS task status to failed
+            if effective_task_id is not None:
+                try:
+                    CloudApi.Instance().update_vas_task(str(effective_task_id), {
+                        "status": "failed",
+                        "fail_reason": f"Account fatal error: {biz_err.message} (code={biz_err.code})"
+                    })
+                    self._log(f"📋 VAS task [{effective_task_id}] marked as 'failed' due to account error: {biz_err.message}")
+                except Exception as update_err:
+                    self._log(f"Failed to update VAS task status: {update_err}")
+
+                try:
+                    self.redis_client.zrem(self.m_tracker_key, effective_task_id)
+                except Exception as zrem_err:
+                    self._log(f"Failed to remove task from tracker: {zrem_err}")
+
+            # If pool account, permanently disable it in cloud
+            if acc and acc.id > 0 and acc.username not in ("", "Guest"):
+                self._disable_account_safely(acc, reason=f"{biz_err.__class__.__name__}: {biz_err.message}")
+
+            # Never release account back to pool
+            if task:
+                self._remove_task(task, f"account fatal error: {biz_err.message}")
+
+            if action in ("spawn", "login", "create_session"):
+                self.m_spawn_cooldown_until = time.time() + 5.0
+
+        # 1. Target site rate limit / 429
+        elif isinstance(biz_err, RateLimiteddError):
             if action in ("spawn", "login", "create_session"):
             if action in ("spawn", "login", "create_session"):
                 backoff = float(self.m_cfg.login_backoff)
                 backoff = float(self.m_cfg.login_backoff)
                 self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
                 self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
@@ -220,7 +264,7 @@ class BaseBookerGCO:
                     self._remove_task(task, "spawn account rate limited")
                     self._remove_task(task, "spawn account rate limited")
 
 
             elif action == "book":
             elif action == "book":
-                # 预订提交时 429:接口频控或 IP 限制,绝不锁账号,移除实例以更换代理重试
+                # 429 during booking: slot rate limit or IP restriction, preserve account and remove task to rotate proxy
                 self._log("🔄 [Booking Rate Limited] 429 during booking (Slot/IP throttled, Account preserved). Removing task to rotate proxy...")
                 self._log("🔄 [Booking Rate Limited] 429 during booking (Slot/IP throttled, Account preserved). Removing task to rotate proxy...")
                 if task:
                 if task:
                     self._remove_task(task, "booking rate limited")
                     self._remove_task(task, "booking rate limited")
@@ -229,7 +273,7 @@ class BaseBookerGCO:
                 if task:
                 if task:
                     self._remove_task(task, f"{action} rate limited")
                     self._remove_task(task, f"{action} rate limited")
 
 
-        # 2. 会话过期 / 401
+        # 2. Session expired / 401
         elif isinstance(biz_err, SessionExpiredOrInvalidError):
         elif isinstance(biz_err, SessionExpiredOrInvalidError):
             if action in ("spawn", "login", "create_session"):
             if action in ("spawn", "login", "create_session"):
                 self._log(f"❌ [Auth Failed] Booker spawn failed (401). Cooling down spawn for 5s...")
                 self._log(f"❌ [Auth Failed] Booker spawn failed (401). Cooling down spawn for 5s...")
@@ -239,7 +283,7 @@ class BaseBookerGCO:
                 if task:
                 if task:
                     self._remove_task(task, f"{action} session expired")
                     self._remove_task(task, f"{action} session expired")
 
 
-        # 3. 权限被拒 / WAF 拦截 / 403
+        # 3. Permission denied / WAF blocked / 403
         elif isinstance(biz_err, PermissionDeniedError):
         elif isinstance(biz_err, PermissionDeniedError):
             proxy_cd = float(self.m_cfg.proxy_cd or 60.0)
             proxy_cd = float(self.m_cfg.proxy_cd or 60.0)
             self._log(f"🛡️ [WAF Blocked] 403 Forbidden during {action}. Removing task to rotate proxy...")
             self._log(f"🛡️ [WAF Blocked] 403 Forbidden during {action}. Removing task to rotate proxy...")
@@ -249,7 +293,7 @@ class BaseBookerGCO:
                 self._release_account_safely(acc, reason="WAF Blocked")
                 self._release_account_safely(acc, reason="WAF Blocked")
                 self.m_spawn_cooldown_until = time.time() + proxy_cd
                 self.m_spawn_cooldown_until = time.time() + proxy_cd
 
 
-        # 4. 网络或浏览器超时
+        # 4. Network or browser timeout
         elif isinstance(biz_err, NetworkTimeoutError):
         elif isinstance(biz_err, NetworkTimeoutError):
             self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
             self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
             if task:
             if task:
@@ -258,7 +302,7 @@ class BaseBookerGCO:
                 self._release_account_safely(acc, reason="Network Timeout")
                 self._release_account_safely(acc, reason="Network Timeout")
                 self.m_spawn_cooldown_until = time.time() + 10.0
                 self.m_spawn_cooldown_until = time.time() + 10.0
 
 
-        # 5. 兜底策略
+        # 5. Fallback policy
         else:
         else:
             self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
             self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
             if action in ("spawn", "login", "create_session"):
             if action in ("spawn", "login", "create_session"):
@@ -267,24 +311,19 @@ class BaseBookerGCO:
             elif task:
             elif task:
                 task.next_run = time.time() + 10.0
                 task.next_run = time.time() + 10.0
 
 
-        # 6. 统一代理健康指标埋点
+        # 6. Proxy health metrics recording
         if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
         if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
-            err_type = biz_err.message
-            if isinstance(biz_err, PermissionDeniedError):
-                if "403202" in err_type or "cf-mitigated" in err_type.lower() or "waf blocked" in err_type.lower():
-                    err_type = "cf-mitigated (403202)"
-
             ProxyManager.Instance().mark_proxy_result(
             ProxyManager.Instance().mark_proxy_result(
                 proxy=active_plg_cfg.proxy.model_dump(),
                 proxy=active_plg_cfg.proxy.model_dump(),
                 plugin_name=self.m_cfg.plugin_config.plugin_name,
                 plugin_name=self.m_cfg.plugin_config.plugin_name,
                 action=action,
                 action=action,
                 success=False,
                 success=False,
                 http_code=biz_err.http_status,
                 http_code=biz_err.http_status,
-                error_type=err_type
+                error_type=biz_err.message
             )
             )
 
 
     def _is_within_active_hours(self) -> bool:
     def _is_within_active_hours(self) -> bool:
-        """判断当前是否在允许创建实例的时间段内"""
+        """Checks if current time is within allowed operating hours."""
         start_str = self.m_cfg.active_time_start
         start_str = self.m_cfg.active_time_start
         end_str = self.m_cfg.active_time_end
         end_str = self.m_cfg.active_time_end
         current_bj_time = datetime.utcnow().time()
         current_bj_time = datetime.utcnow().time()
@@ -333,11 +372,11 @@ class BaseBookerGCO:
                 self._log(f'Maintain loop exception: {e}')
                 self._log(f'Maintain loop exception: {e}')
 
 
     def _on_maintain_ping(self, healthy_tasks: List[Task], dead_tasks: List[Task]):
     def _on_maintain_ping(self, healthy_tasks: List[Task], dead_tasks: List[Task]):
-        """子类维护循环中对于健康/异常 Task 的额外处理"""
+        """Subclass hook for additional handling of healthy/dead tasks during maintenance."""
         pass
         pass
 
 
     def _is_date_of_interest(self, task: Task, query_result: QueryResult) -> bool:
     def _is_date_of_interest(self, task: Task, query_result: QueryResult) -> bool:
-        """判断 query_result 中的可用日期是否在 task 意向范围内(默认 True,Order 模式重写)"""
+        """Checks if available dates in query_result match task preferences (defaults to True)."""
         return True
         return True
 
 
     def _booking_trigger_loop(self):
     def _booking_trigger_loop(self):
@@ -394,7 +433,7 @@ class BaseBookerGCO:
         raise NotImplementedError
         raise NotImplementedError
 
 
     def _push_success_notification(self, task_id, order_id, book_res):
     def _push_success_notification(self, task_id, order_id, book_res):
-        """成功落单后同步云端与推送微信通知的公共方法"""
+        """Shared helper to sync booking success state to cloud and dispatch notifications."""
         grab_info = {
         grab_info = {
             "account": book_res.account,
             "account": book_res.account,
             "session_id": book_res.session_id,
             "session_id": book_res.session_id,
@@ -418,9 +457,9 @@ class BaseBookerGCO:
 
 
 class BuiltinBookerGCO(BaseBookerGCO):
 class BuiltinBookerGCO(BaseBookerGCO):
     """
     """
-    非绑定模式 (公共内置账号池):
-    - 只维护全局 target_instances 数量的实例。
-    - 所有实例热机等待,发现信号后临时去云端 Pop 订单。
+    Unbound mode (shared built-in account pool):
+    - Maintains target_instances count of instances globally.
+    - Instances stay warm; when a slot signal is detected, orders are popped on-demand from the cloud queue.
     """
     """
     TAG = "BUILTIN-BOOKER"
     TAG = "BUILTIN-BOOKER"
 
 
@@ -500,17 +539,24 @@ class BuiltinBookerGCO(BaseBookerGCO):
     def _execute_book_job(self, task: Task, query_result: QueryResult):
     def _execute_book_job(self, task: Task, query_result: QueryResult):
         queue_name = f"auto.{query_result.apt_type.routing_key}"
         queue_name = f"auto.{query_result.apt_type.routing_key}"
 
 
-        task_id = None
         task_data = None
         task_data = None
-        
         try:
         try:
             task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
             task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
-            if not task_data:
-                return 
-            task_id = task_data['id']
-            order_id = task_data.get('order_id')
-            self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + 30.0})
-                        
+        except BizLogicError:
+            # Queue has no pending tasks, return normally
+            return
+        except Exception as e:
+            self._log(f"⚠️ [CloudApi] Failed to pop task from {queue_name}: {e}")
+            return
+
+        if not task_data:
+            return 
+
+        task_id = task_data.get('id')
+        order_id = task_data.get('order_id')
+        self.redis_client.zadd(self.m_tracker_key, {str(task_id): time.time() + 30.0})
+                    
+        try:
             user_input = task_data.get('user_inputs', {})
             user_input = task_data.get('user_inputs', {})
             book_res = task.instance.book(query_result, user_input)
             book_res = task.instance.book(query_result, user_input)
             
             
@@ -531,10 +577,10 @@ class BuiltinBookerGCO(BaseBookerGCO):
 
 
 class OrderBookerGCO(BaseBookerGCO):
 class OrderBookerGCO(BaseBookerGCO):
     """
     """
-    绑定模式 (订单自带账号):
-    - 按城市队列维护热机配额。
-    - 绝对的 1 对 1 关系:一个实例绑定一个云端订单。
-    - 预订成功后,实例立即销毁。
+    Bound mode (order provides its own account credentials):
+    - Maintains warm-up quotas per routing queue.
+    - Strict 1:1 binding: one instance per cloud order.
+    - Instance is destroyed immediately after booking completes.
     """
     """
     TAG = "ORDER-BOOKER"
     TAG = "ORDER-BOOKER"
 
 
@@ -660,7 +706,12 @@ class OrderBookerGCO(BaseBookerGCO):
         plg_cfg = None
         plg_cfg = None
         try:
         try:
             queue_name = f"auto.{target_routing_key}"
             queue_name = f"auto.{target_routing_key}"
-            task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
+            try:
+                task_data = CloudApi.Instance().get_vas_task_pop(queue_name)
+            except BizLogicError:
+                # Queue has no pending tasks, return directly
+                return
+
             if not task_data:
             if not task_data:
                 return 
                 return 
             
             

+ 19 - 116
config/config_sentinel.yaml

@@ -1,6 +1,6 @@
-- id: 10
-  node_id: Jerry Win11 PC
-  identifier: vfs.ie.hu
+- id: 8
+  node_id: jerry_macos
+  identifier: vfs.ie.dk
   enable: 1
   enable: 1
   debug: 0
   debug: 0
   need_account: 1
   need_account: 1
@@ -11,7 +11,7 @@
   session_max_life: 1800
   session_max_life: 1800
   active_time_start: 00:00
   active_time_start: 00:00
   active_time_end: '23:59'
   active_time_end: '23:59'
-  website: https://visa.vfsglobal.com/irl/en/hun/login
+  website: https://visa.vfsglobal.com/irl/en/dnk/login
   sentinel:
   sentinel:
     account_cd: 10800
     account_cd: 10800
     query_wait:
     query_wait:
@@ -21,7 +21,7 @@
       random_min: 60
       random_min: 60
     signal_ttl: 30
     signal_ttl: 30
     account_source: built-in
     account_source: built-in
-    account_pool_id: ie.hu.sentinel
+    account_pool_id: ie.dk.sentinel
     target_instances: 1
     target_instances: 1
   plugin_config:
   plugin_config:
     lib_path: plugins
     lib_path: plugins
@@ -31,123 +31,26 @@
   appointment_types:
   appointment_types:
   - city: Dublin
   - city: Dublin
     weight: 10
     weight: 10
-    country: Hungary
+    country: Denmark
     visa_type: Tourist
     visa_type: Tourist
-    routing_key: slot.dub.hu.tourist
+    routing_key: slot.dub.dk.tourist
   free_config:
   free_config:
     language: en
     language: en
     apt_configs:
     apt_configs:
-      slot.dub.hu.tourist:
-        address: Cunningham House, 130 Francis Street Dublin
-        vac_code: DUB
-        center_name: Ireland Visa Application Center,Dublin
-        category_code: SS
-        category_name: Short Stay
-        subcategory_code: Schengen Visa
-        subcategory_name: Schengen Visa
+      slot.dub.dk.tourist:
+        address: Cunningham House, 130 Francis Street, Dublin 8 D08 H48R
+        vac_code: DIDUB
+        center_name: 'Denmark Visa Application Center, Dublin '
+        category_code: SV
+        category_name: Schengen Visa
+        subcategory_code: TV
+        subcategory_name: Tourism
     country_code: irl
     country_code: irl
     country_name: Ireland
     country_name: Ireland
     culture_code: en-US
     culture_code: en-US
-    mission_code: hun
-    mission_name: Hungary
+    mission_code: dnk
+    mission_name: Denmark
   version: 7
   version: 7
   updated_by: 769858626@qq.com
   updated_by: 769858626@qq.com
-  created_at: '2026-08-23T15:08:19'
-  updated_at: '2026-09-23T09:58:24'
-- id: 27
-  node_id: Jerry Win11 PC
-  identifier: greekemba.ie.gr
-  enable: 1
-  debug: 0
-  need_account: 1
-  need_proxy: 1
-  proxy_pool:
-  - local:local_multi_pool
-  proxy_cd: 0
-  session_max_life: 86400
-  active_time_start: 00:00
-  active_time_end: '23:59'
-  website: https://www.supersaas.com/schedule/GreekEmbassyInDublin/Visas
-  sentinel:
-    account_cd: 10800
-    query_wait:
-      mode: Random
-      fixed_wait: 10
-      random_max: 300
-      random_min: 60
-    signal_ttl: 30
-    account_source: built-in
-    account_pool_id: ie.gr.sentinel
-    target_instances: 2
-  plugin_config:
-    lib_path: plugins
-    plugin_bin: grc_plugin.py
-    plugin_name: grc_plugin
-    plugin_proto: IVSPlg
-  appointment_types:
-  - city: Dublin
-    weight: 10
-    country: Greece
-    visa_type: Tourist
-    routing_key: slot.dub.gr.tourist
-  free_config: {}
-  version: 9
-  updated_by: 769858626@qq.com
-  created_at: '2026-08-23T15:08:26'
-  updated_at: '2026-09-22T15:07:50'
-- id: 1
-  node_id: Jerry Win11 PC
-  identifier: vfs.ie.nl
-  enable: 1
-  debug: 0
-  need_account: 1
-  need_proxy: 1
-  proxy_pool:
-  - local:local_multi_pool
-  proxy_cd: 60
-  session_max_life: 1800
-  active_time_start: 00:00
-  active_time_end: '23:59'
-  website: https://visa.vfsglobal.com/irl/en/nld/login
-  sentinel:
-    account_cd: 10800
-    query_wait:
-      mode: Random
-      fixed_wait: 10
-      random_max: 300
-      random_min: 60
-    signal_ttl: 30
-    account_source: built-in
-    account_pool_id: ie.nl.sentinel
-    target_instances: 1
-  plugin_config:
-    lib_path: plugins
-    plugin_bin: vfs_plugin.py
-    plugin_name: vfs_plugin
-    plugin_proto: IVSPlg
-  appointment_types:
-  - city: Dublin
-    weight: 10
-    country: Netherlands
-    visa_type: Tourist
-    routing_key: slot.dub.nl.tourist
-  free_config:
-    language: en
-    apt_configs:
-      slot.dub.nl.tourist:
-        address: Cunningham House, 130 Francis Street, Dublin 8  D08 H48R
-        vac_code: NTDB
-        center_name: Netherlands Visa Application Center - Dublin
-        category_code: TA
-        category_name: All Short stay Categories
-        subcategory_code: To
-        subcategory_name: Tourist
-    country_code: irl
-    country_name: Ireland
-    culture_code: en-US
-    mission_code: nld
-    mission_name: Netherlands
-  version: 9
-  updated_by: 769858626@qq.com
-  created_at: '2026-08-23T15:08:15'
-  updated_at: '2026-09-17T15:25:52'
+  created_at: '2026-08-23T15:08:18'
+  updated_at: '2026-10-03T18:18:47'

+ 13 - 13
configure.py

@@ -1,4 +1,4 @@
-# 大模型通用验证码识别配置 (支持 Qwen、OpenAI、DeepSeek 等兼容接口)
+# LLM General Captcha recognition config (supports OpenAI, Qwen, DeepSeek compatible endpoints)
 CAPTCHA_LLM_CONFIG = None
 CAPTCHA_LLM_CONFIG = None
 CAPTCHA_LLM_CONFIG = {
 CAPTCHA_LLM_CONFIG = {
     "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
     "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
@@ -14,7 +14,7 @@ REDIS_CFG = {
     "password": "STEs2x6ML0U1HlpE9SojM6YU7QPhqzY8"
     "password": "STEs2x6ML0U1HlpE9SojM6YU7QPhqzY8"
 }
 }
 
 
-# 测试任务,这里配置以后任务轮转函数直接使用这个任务
+# Test task: when configured, task rotation directly uses this task
 TEST_TASK = None
 TEST_TASK = None
 # TEST_TASK = {
 # TEST_TASK = {
 #     "status": "running",
 #     "status": "running",
@@ -50,7 +50,7 @@ TEST_TASK = None
 # }
 # }
 
 
 
 
-# 测试账号,这里配置以后账号轮转函数直接使用这个账号
+# Test account: when configured, account rotation directly uses this account
 TEST_ACCOUNT = None
 TEST_ACCOUNT = None
 # TEST_ACCOUNT = {
 # TEST_ACCOUNT = {
 #     "pool_name": "tls.gb.fr.sentinel",
 #     "pool_name": "tls.gb.fr.sentinel",
@@ -65,7 +65,7 @@ TEST_ACCOUNT = None
 # }
 # }
 
 
 
 
-# 测试代理,这里配置以后ip轮转函数直接使用这个代理
+# Test proxy: when configured, proxy rotation directly uses this proxy
 TEST_PROXY = None
 TEST_PROXY = None
 # TEST_PROXY = {
 # TEST_PROXY = {
 #     "pool_name": "local",
 #     "pool_name": "local",
@@ -78,22 +78,22 @@ TEST_PROXY = None
 # }
 # }
 
 
 
 
-# 节点 ID 配置, 这个优先级最高,其次 NODE_ID 的环境变量,最后系统默认值 "node01"
+# Node ID config: highest priority, then NODE_ID env var, then default "node01"
 NODE_ID = None
 NODE_ID = None
-# NODE_ID = "Jerry Win11 PC"
+NODE_ID = "jerry_macos"
 
 
 
 
-# Chrome bin 的路径, 这个优先级最高,其次CHROME_BIN 的环境变量,最后系统默认值
+# Chrome binary path: highest priority, then CHROME_BIN env var, then default
 CHROME_PATH = None
 CHROME_PATH = None
 # CHROME_PATH = "E:/ungoogled-chromium_144.0.7559.132-1.1_windows_x64/chrome.exe"
 # CHROME_PATH = "E:/ungoogled-chromium_144.0.7559.132-1.1_windows_x64/chrome.exe"
 
 
 
 
-# Mohomo bin 的路径, 这个优先级最高,其次MIHOMO_BIN 的环境变量,最后系统默认值
+# Mihomo binary path: highest priority, then MIHOMO_BIN env var, then default
 MIHOMO_BIN_PATH = None
 MIHOMO_BIN_PATH = None
 MIHOMO_BIN_PATH = 'downloads/mihomo'
 MIHOMO_BIN_PATH = 'downloads/mihomo'
 
 
 
 
-# proxy tunnel 中继节点, 列表中随机选择
+# Proxy tunnel relay nodes, randomly chosen from list
 MIHOMO_RELAY_NODES = None                 
 MIHOMO_RELAY_NODES = None                 
 # MIHOMO_RELAY_NODES = [
 # MIHOMO_RELAY_NODES = [
 #   {
 #   {
@@ -111,7 +111,7 @@ MIHOMO_RELAY_NODES = None
 #     "udp": True
 #     "udp": True
 #   },
 #   },
 #   {
 #   {
-#     "name": "RelayNode hk 01丨1x",
+#     "name": "RelayNode hk 01 | 1x",
 #     "type": "ss",
 #     "type": "ss",
 #     "server": "e0405950-3002-4dc8-860b-8fac3ffdd76c.drive-glicloudccp.com",
 #     "server": "e0405950-3002-4dc8-860b-8fac3ffdd76c.drive-glicloudccp.com",
 #     "port": 12022,
 #     "port": 12022,
@@ -125,7 +125,7 @@ MIHOMO_RELAY_NODES = None
 #     "udp": True
 #     "udp": True
 #   },
 #   },
 #   {
 #   {
-#     "name": "RelayNode hk 02丨1x",
+#     "name": "RelayNode hk 02 | 1x",
 #     "type": "ss",
 #     "type": "ss",
 #     "server": "e0405950-3002-4dc8-860b-8fac3ffdd76c.drive-glicloudccp.com",
 #     "server": "e0405950-3002-4dc8-860b-8fac3ffdd76c.drive-glicloudccp.com",
 #     "port": 12023,
 #     "port": 12023,
@@ -139,7 +139,7 @@ MIHOMO_RELAY_NODES = None
 #     "udp": True
 #     "udp": True
 #   },
 #   },
 #   {
 #   {
-#     "name": "RelayNode hk 03丨1x",
+#     "name": "RelayNode hk 03 | 1x",
 #     "type": "ss",
 #     "type": "ss",
 #     "server": "e0405950-3002-4dc8-860b-8fac3ffdd76c.drive-glicloudccp.com",
 #     "server": "e0405950-3002-4dc8-860b-8fac3ffdd76c.drive-glicloudccp.com",
 #     "port": 12024,
 #     "port": 12024,
@@ -155,5 +155,5 @@ MIHOMO_RELAY_NODES = None
 # ]
 # ]
 
 
 
 
-# 临时测试预约提交
+# Temporary test for booking submission
 TLS_TEST_BOOK_AFTER_QUERY = False
 TLS_TEST_BOOK_AFTER_QUERY = False

+ 119 - 46
core_types.py

@@ -1,5 +1,6 @@
 import json
 import json
 import time
 import time
+import socket
 from datetime import datetime, timezone
 from datetime import datetime, timezone
 from dataclasses import dataclass, field, asdict
 from dataclasses import dataclass, field, asdict
 from pydantic import BaseModel, Field
 from pydantic import BaseModel, Field
@@ -41,14 +42,14 @@ class RateLimiteddError(BizException):
     def __init__(self, message="Rate limited", extra: Optional[Dict[str, Any]] = None):
     def __init__(self, message="Rate limited", extra: Optional[Dict[str, Any]] = None):
         super().__init__(code=42901, message=message, http_status=429, extra=extra)
         super().__init__(code=42901, message=message, http_status=429, extra=extra)
 
 
-# 语义别名(兼顾拼写纠正与向后兼容)
+# Semantic alias (for typo tolerance and backwards compatibility)
 RateLimitedError = RateLimiteddError
 RateLimitedError = RateLimiteddError
         
         
 class SessionExpiredOrInvalidError(BizException):
 class SessionExpiredOrInvalidError(BizException):
     def __init__(self, message="Session expired or invalid", extra: Optional[Dict[str, Any]] = None):
     def __init__(self, message="Session expired or invalid", extra: Optional[Dict[str, Any]] = None):
         super().__init__(code=40101, message=message, http_status=401, extra=extra)
         super().__init__(code=40101, message=message, http_status=401, extra=extra)
 
 
-# 语义别名
+# Semantic alias
 SessionExpiredError = SessionExpiredOrInvalidError
 SessionExpiredError = SessionExpiredOrInvalidError
 
 
 class PermissionDeniedError(BizException):
 class PermissionDeniedError(BizException):
@@ -63,9 +64,81 @@ class NetworkTimeoutError(BizException):
     def __init__(self, message="Network or browser timeout", extra: Optional[Dict[str, Any]] = None):
     def __init__(self, message="Network or browser timeout", extra: Optional[Dict[str, Any]] = None):
         super().__init__(code=50401, message=message, http_status=504, extra=extra)
         super().__init__(code=50401, message=message, http_status=504, extra=extra)
 
 
-# 语义别名:调度层与插件层统一使用 PluginError
+class AccountStateError(BizException):
+    """Base exception for fatal account states (invalid credentials, banned, incomplete, deleted)"""
+    pass
+
+class AccountAuthError(AccountStateError):
+    """Account or password incorrect (code=40102)"""
+    def __init__(self, message="Account credentials invalid", extra: Optional[Dict[str, Any]] = None):
+        super().__init__(code=40102, message=message, http_status=401, extra=extra)
+
+class AccountBannedError(AccountStateError):
+    """Account banned, disabled, or suspended (code=40302)"""
+    def __init__(self, message="Account banned or suspended", extra: Optional[Dict[str, Any]] = None):
+        super().__init__(code=40302, message=message, http_status=403, extra=extra)
+
+class AccountIncompleteError(AccountStateError):
+    """Account profile incomplete or requires activation/verification (code=42201)"""
+    def __init__(self, message="Account registration incomplete or requires activation", extra: Optional[Dict[str, Any]] = None):
+        super().__init__(code=42201, message=message, http_status=422, extra=extra)
+
+class AccountNotFoundError(AccountStateError):
+    """Account does not exist or was deleted (code=40402)"""
+    def __init__(self, message="Account not found or deleted", extra: Optional[Dict[str, Any]] = None):
+        super().__init__(code=40402, message=message, http_status=404, extra=extra)
+
+# Semantic alias: unified PluginError across scheduling and plugin layers
 PluginError = BizException
 PluginError = BizException
 
 
+
+def normalize_error(err: Exception) -> BizException:
+    """
+    Normalizes any exception into a domain BizException.
+    Deterministically determined based on exception type and structured status codes (HTTP status / code), avoiding brittle string matching.
+    """
+    if isinstance(err, BizException):
+        return err
+
+    # Network layer or standard timeout exceptions
+    if isinstance(err, (TimeoutError, socket.timeout)):
+        return NetworkTimeoutError(message=str(err))
+
+    # Extract structured HTTP status code or business error code
+    status_code = getattr(err, "status_code", None)
+    if status_code is None:
+        status_code = getattr(err, "http_status", None)
+    if status_code is None and hasattr(err, "response") and hasattr(err.response, "status_code"):
+        status_code = err.response.status_code
+
+    code = getattr(err, "code", None)
+
+    # Specific account fatal codes
+    if code == 40102:
+        return AccountAuthError(message=str(err))
+    if code == 40302:
+        return AccountBannedError(message=str(err))
+    if code == 42201:
+        return AccountIncompleteError(message=str(err))
+    if code == 40402:
+        return AccountNotFoundError(message=str(err))
+
+    if status_code == 401 or code == 40101:
+        return SessionExpiredOrInvalidError(message=str(err))
+    if status_code in (403, 0) or code == 40301:
+        return PermissionDeniedError(message=str(err))
+    if status_code == 404 or code == 40401:
+        return NotFoundError(message=str(err))
+    if status_code == 429 or code == 42901:
+        return RateLimiteddError(message=str(err))
+    if status_code in (408, 502, 503, 504) or code == 50401:
+        return NetworkTimeoutError(message=str(err))
+
+    return BizException(
+        code=50000,
+        message=f"Unhandled ({type(err).__name__}): {err}",
+    )
+
 class AvailabilityStatus(str, Enum):
 class AvailabilityStatus(str, Enum):
     NoneAvailable = "NoAvailable"
     NoneAvailable = "NoAvailable"
     Available = "Available"
     Available = "Available"
@@ -95,23 +168,23 @@ class AppointmentType(BaseModel):
     city: str = ''
     city: str = ''
     visa_type: str = ''
     visa_type: str = ''
 
 
-# === 哨兵配置 ===
+# === Sentinel Config ===
 class SentinelConfig(BaseModel):
 class SentinelConfig(BaseModel):
     account_source: str = "built-in"
     account_source: str = "built-in"
     account_pool_id: str = ""
     account_pool_id: str = ""
     target_instances: int = 1
     target_instances: int = 1
-    account_cd: int = 180*60        # 单位 秒
-    signal_ttl: int = 180           # 单位 秒
+    account_cd: int = 180*60        # unit: seconds
+    signal_ttl: int = 180           # unit: seconds
     query_wait: QueryWaitConfig = Field(default_factory=QueryWaitConfig)
     query_wait: QueryWaitConfig = Field(default_factory=QueryWaitConfig)
 
 
-# === Booker配置 ===
+# === Booker Config ===
 class BookerConfig(BaseModel):
 class BookerConfig(BaseModel):
-    account_source: str = "built-in" # "built-in" 或 "order"
-    account_pool_id: str = ""        # 仅在 built-in 模式下使用 账号池名字
-    account_cd: int = 180*60         # 仅在 built-in 模式下使用 账号冷却时间 单位 秒
-    target_instances: int = 1        # built-in下为全局限制; order下为单队列限制
-    keep_alive: int = 60             # 每60秒保活一次
-    booking_cooldown: float = 10.0   # 单位 秒
+    account_source: str = "built-in" # "built-in" or "order"
+    account_pool_id: str = ""        # Account pool name (used in built-in mode only)
+    account_cd: int = 180*60         # Account cooldown in seconds (used in built-in mode only)
+    target_instances: int = 1        # Global limit in built-in mode; per-queue limit in order mode
+    keep_alive: int = 60             # Keepalive interval in seconds
+    booking_cooldown: float = 10.0   # unit: seconds
     max_bookings_per_account: int = 1
     max_bookings_per_account: int = 1
 
 
 class GroupConfig(BaseModel):
 class GroupConfig(BaseModel):
@@ -121,11 +194,11 @@ class GroupConfig(BaseModel):
     need_account: bool = False
     need_account: bool = False
     need_proxy: bool = False
     need_proxy: bool = False
     proxy_pool: List[str] = Field(default_factory=list)
     proxy_pool: List[str] = Field(default_factory=list)
-    proxy_cd: int = 5*60                # 单位 秒
-    active_time_start: str = "00:00"    # 默认执行起始时间
-    active_time_end: str = "23:59"      # 默认执行结束时间
-    session_max_life: int = 30*60       # 单位 秒
-    login_backoff: int = 1800           # 创建会话Rate limited 后账号自动退避 秒
+    proxy_cd: int = 5*60                # unit: seconds
+    active_time_start: str = "00:00"    # Default execution start time
+    active_time_end: str = "23:59"      # Default execution end time
+    session_max_life: int = 30*60       # unit: seconds
+    login_backoff: int = 1800           # Cooldown seconds after session creation rate limit
     sentinel: SentinelConfig = Field(default_factory=SentinelConfig)
     sentinel: SentinelConfig = Field(default_factory=SentinelConfig)
     booker: BookerConfig = Field(default_factory=BookerConfig)
     booker: BookerConfig = Field(default_factory=BookerConfig)
     plugin_config: PluginConfig = Field(default_factory=PluginConfig)
     plugin_config: PluginConfig = Field(default_factory=PluginConfig)
@@ -156,12 +229,12 @@ class BookerStandaloneConfig(BaseModel):
     debug: bool = False
     debug: bool = False
     account: Account = Field(default_factory=Account)
     account: Account = Field(default_factory=Account)
     proxy_pool: List[str] = Field(default_factory=list)
     proxy_pool: List[str] = Field(default_factory=list)
-    active_time_start: str = "00:00"    # 默认执行起始时间
-    active_time_end: str = "23:59"      # 默认执行结束时间
-    session_max_life: int = 30*60       # 单位 秒
-    keep_alive: int = 60                # 保活间隔 单位 秒
+    active_time_start: str = "00:00"    # Default execution start time
+    active_time_end: str = "23:59"      # Default execution end time
+    session_max_life: int = 30*60       # unit: seconds
+    keep_alive: int = 60                # Keepalive interval in seconds
     query_wait: QueryWaitConfig = Field(default_factory=QueryWaitConfig)
     query_wait: QueryWaitConfig = Field(default_factory=QueryWaitConfig)
-    login_interval: int = 1800          # 登录间隔
+    login_interval: int = 1800          # Login interval in seconds
     plugin_config: PluginConfig = Field(default_factory=PluginConfig)
     plugin_config: PluginConfig = Field(default_factory=PluginConfig)
     appointment_types: List[AppointmentType] = Field(default_factory=list)
     appointment_types: List[AppointmentType] = Field(default_factory=list)
     user_preferences: Dict[str, Any] = Field(default_factory=dict)
     user_preferences: Dict[str, Any] = Field(default_factory=dict)
@@ -176,7 +249,7 @@ class PluginConfig(BaseModel):
     account: Account = Field(default_factory=Account)
     account: Account = Field(default_factory=Account)
     proxy: Proxy = Field(default_factory=Proxy)
     proxy: Proxy = Field(default_factory=Proxy)
     free_config: dict = Field(default_factory=dict)
     free_config: dict = Field(default_factory=dict)
-    session_max_life: int = 30*60       # 单位 秒
+    session_max_life: int = 30*60       # unit: seconds
 
 
 class TimeSlot(BaseModel):
 class TimeSlot(BaseModel):
     time: str = ""     # "hh:mm"
     time: str = ""     # "hh:mm"
@@ -228,20 +301,20 @@ class BookResult(BaseModel):
     book_time: str = ""
     book_time: str = ""
     payment_link: str = ""
     payment_link: str = ""
 
 
-# === 内部任务对象 ===
+# === Internal Task Object ===
 class Task(BaseModel):
 class Task(BaseModel):
     instance: Any              
     instance: Any              
     qw_cfg: Optional[QueryWaitConfig] = None,
     qw_cfg: Optional[QueryWaitConfig] = None,
     next_run: float = 0.0      
     next_run: float = 0.0      
     book_allowed: bool = True
     book_allowed: bool = True
-    # 订单模式下,保存绑定的 Task ID
+    # Bound Task ID in order mode
     task_ref: Optional[int] = None
     task_ref: Optional[int] = None
-    # 允许预订的 routing_key 列表
+    # List of routing_keys allowed for booking
     acceptable_routing_keys: List[str] = Field(default_factory=list)
     acceptable_routing_keys: List[str] = Field(default_factory=list)
-    # 来源标识(用于配额统计)
+    # Source queue identifier (for quota accounting)
     source_queue: str = ""
     source_queue: str = ""
     successful_bookings: int = 0
     successful_bookings: int = 0
-    # 下一次允许心跳时间
+    # Next allowed remote ping timestamp
     next_remote_ping: float = 0.0
     next_remote_ping: float = 0.0
     
     
     model_config = {
     model_config = {
@@ -249,23 +322,23 @@ class Task(BaseModel):
     }
     }
 
 
 
 
-# ================== 状态监控数据结构 ==================
+# ================== Status Monitoring Data Structures ==================
 def utc_now_str() -> str:
 def utc_now_str() -> str:
-    """获取当前人类可读的 UTC 时间字符串,格式: YYYY-MM-DD HH:MM:SS"""
+    """Returns human-readable UTC timestamp string, format: YYYY-MM-DD HH:MM:SS"""
     return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
     return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 @dataclass
 @dataclass
 class PluginStatus:
 class PluginStatus:
-    """单个插件实例的运行状态"""
+    """Runtime status of an individual plugin instance"""
     instance_id: str = ""
     instance_id: str = ""
     is_healthy: bool = True
     is_healthy: bool = True
-    state: str = "idle"            # idle / logging_in / querying / booking / challenge / cooldown / error 等
+    state: str = "idle"            # idle / logging_in / querying / booking / challenge / cooldown / error, etc.
     current_url: str = ""
     current_url: str = ""
     account: str = ""
     account: str = ""
     proxy: str = ""
     proxy: str = ""
-    session_age_sec: int = 0       # 会话存活时长(秒)
-    last_active_at: str = ""       # 上次活跃 UTC 时间(人类可读)
+    session_age_sec: int = 0       # Session age in seconds
+    last_active_at: str = ""       # Last active UTC timestamp (human-readable)
 
 
     def to_dict(self) -> Dict[str, Any]:
     def to_dict(self) -> Dict[str, Any]:
         return asdict(self)
         return asdict(self)
@@ -273,11 +346,11 @@ class PluginStatus:
 
 
 @dataclass
 @dataclass
 class GroupStatus:
 class GroupStatus:
-    """单个组(Group/GCO)的状态容器,聚合该组下所有插件实例状态"""
+    """Status container for a single group (GCO), aggregating all plugin instances under it"""
     group_id: str = ""
     group_id: str = ""
     enable: bool = True
     enable: bool = True
     plugin_name: str = ""
     plugin_name: str = ""
-    wrapper_state: str = ""        # CREATED / RUNNING / STOPPED / FAILED 等
+    wrapper_state: str = ""        # CREATED / RUNNING / STOPPED / FAILED, etc.
     total_tasks: int = 0
     total_tasks: int = 0
     healthy_tasks: int = 0
     healthy_tasks: int = 0
     plugins: List[PluginStatus] = field(default_factory=list)
     plugins: List[PluginStatus] = field(default_factory=list)
@@ -289,11 +362,11 @@ class GroupStatus:
 
 
 @dataclass
 @dataclass
 class PluginMeta:
 class PluginMeta:
-    """插件静态元数据信息"""
-    name: str = ""                                  # 插件名,如 tls_plugin
-    version: str = "1.0.0"                          # 插件版本号
-    description: str = ""                          # 插件中文功能描述
-    filename: str = ""                             # 插件文件名,如 tls_plugin.py
+    """Plugin static metadata information"""
+    name: str = ""                                  # Plugin name, e.g. tls_plugin
+    version: str = "1.0.0"                          # Plugin version
+    description: str = ""                          # Plugin description
+    filename: str = ""                             # Plugin filename, e.g. tls_plugin.py
 
 
     def to_dict(self) -> Dict[str, Any]:
     def to_dict(self) -> Dict[str, Any]:
         return asdict(self)
         return asdict(self)
@@ -301,10 +374,10 @@ class PluginMeta:
 
 
 @dataclass
 @dataclass
 class RoleStatus:
 class RoleStatus:
-    """顶层容器:表明是 Standalone / Sentinel / Booker 收集到的全量状态"""
+    """Top-level container: aggregates full status collected by Standalone / Sentinel / Booker"""
     role: str = ""                                  # "standalone" / "sentinel" / "booker"
     role: str = ""                                  # "standalone" / "sentinel" / "booker"
-    node_id: str = ""                               # "node01" 等
-    installed_plugins: List[PluginMeta] = field(default_factory=list) # 本地已安装插件详细列表
+    node_id: str = ""                               # "node01", etc.
+    installed_plugins: List[PluginMeta] = field(default_factory=list) # List of locally installed plugins
     groups: List[GroupStatus] = field(default_factory=list)
     groups: List[GroupStatus] = field(default_factory=list)
     collected_at: str = field(default_factory=utc_now_str)
     collected_at: str = field(default_factory=utc_now_str)
 
 
@@ -312,6 +385,6 @@ class RoleStatus:
         return asdict(self)
         return asdict(self)
 
 
 
 
-# 语义化别名
+# Semantic aliases
 RunnerStatus = RoleStatus
 RunnerStatus = RoleStatus
 CoordinatorStatus = RoleStatus
 CoordinatorStatus = RoleStatus

+ 10 - 10
gco_wrapper.py

@@ -16,9 +16,9 @@ class State(Enum):
 class GCOWrapper:
 class GCOWrapper:
     def __init__(self, gco_class: Type[Any], gco_cfg: GroupConfig, redis_conf: Dict[str, Any]):
     def __init__(self, gco_class: Type[Any], gco_cfg: GroupConfig, redis_conf: Dict[str, Any]):
         """
         """
-        @param gco_class: 传入你要包装的具体类 (SentinelGCO 或 BookerGCO)
-        @param gco_cfg: 分组配置
-        @param redis_conf: Redis 连接配置 (字典)
+        @param gco_class: Specific GCO class to wrap (SentinelGCO or BookerGCO)
+        @param gco_cfg: Group configuration
+        @param redis_conf: Redis connection configuration dictionary
         """
         """
         self.gco_class = gco_class
         self.gco_class = gco_class
         self.m_cfg = gco_cfg
         self.m_cfg = gco_cfg
@@ -44,7 +44,7 @@ class GCOWrapper:
                     sub(msg)
                     sub(msg)
                 except Exception:
                 except Exception:
                     pass
                     pass
-        # 原有 push callback
+        # Legacy push callback
         self._push_callback("LOG", msg.encode(), self._state)
         self._push_callback("LOG", msg.encode(), self._state)
         
         
     def get_logs(self, last_n=50):
     def get_logs(self, last_n=50):
@@ -70,9 +70,9 @@ class GCOWrapper:
     def start(self):
     def start(self):
         self._transition(State.LOADED, State.RUNNING)
         self._transition(State.LOADED, State.RUNNING)
         try:
         try:
-            # 动态实例化传入的类,并传入 Redis 配置
+            # Dynamically instantiate class with Redis configuration
             self._gco = self.gco_class(self.m_cfg, self.redis_conf, logger=self._log)
             self._gco = self.gco_class(self.m_cfg, self.redis_conf, logger=self._log)
-            self._gco.start()  # 调用 Sentinel 或 Booker 的 start
+            self._gco.start()  # Call Sentinel or Booker start
         except Exception:
         except Exception:
             self._state = State.FAILED
             self._state = State.FAILED
             raise
             raise
@@ -83,14 +83,14 @@ class GCOWrapper:
         self._transition(State.RUNNING, State.STOPPING)
         self._transition(State.RUNNING, State.STOPPING)
         try:
         try:
             if self._gco:
             if self._gco:
-                self._gco.stop()  # 调用 Sentinel 或 Booker 的 stop
+                self._gco.stop()  # Call Sentinel or Booker stop
         finally:
         finally:
             self._transition(State.STOPPING, State.STOPPED)
             self._transition(State.STOPPING, State.STOPPED)
             
             
-    # ================= 新增热更新方法 =================
+    # ================= Hot Reloading Methods =================
     def update_config(self, new_cfg: GroupConfig):
     def update_config(self, new_cfg: GroupConfig):
         """
         """
-        动态更新当前 Group 的配置,并透传给底层具体执行的 GCO 实例
+        Dynamically updates current Group configuration and propagates to underlying GCO instance.
         """
         """
         with self._lock:
         with self._lock:
             self.m_cfg = new_cfg
             self.m_cfg = new_cfg
@@ -100,7 +100,7 @@ class GCOWrapper:
 
 
     def get_status(self) -> GroupStatus:
     def get_status(self) -> GroupStatus:
         """
         """
-        获取当前 GCOWrapper 及其内部 GCO 实例的聚合状态
+        Returns aggregated status of current GCOWrapper and underlying GCO instance.
         """
         """
         with self._lock:
         with self._lock:
             state_name = self._state.name
             state_name = self._state.name

+ 3 - 3
log_macros.py

@@ -1,14 +1,14 @@
 import logging
 import logging
 
 
-# 内部持有一个 logger 实例,默认是 Root Logger(防止在没初始化前报错)
+# Holds internal logger instance, defaults to Root Logger to avoid uninitialized errors
 _active_logger = logging.getLogger()
 _active_logger = logging.getLogger()
 
 
 def set_active_logger(logger: logging.Logger):
 def set_active_logger(logger: logging.Logger):
-    """供外部日志配置工具调用,用于重定向所有宏的输出"""
+    """Called by external logging configuration utilities to redirect all macro output."""
     global _active_logger
     global _active_logger
     _active_logger = logger
     _active_logger = logger
 
 
-# --- 宏定义 (调用签名完全保持原样,额外支持 group_id 结构化透传) ---
+# --- Macro definitions (supports group_id structured extra metadata) ---
 
 
 def VSC_INFO(tag, message, *args, group_id: str = ""):
 def VSC_INFO(tag, message, *args, group_id: str = ""):
     _active_logger.info(f"[{tag}] {message}", *args, extra={"group_id": group_id})
     _active_logger.info(f"[{tag}] {message}", *args, extra={"group_id": group_id})

+ 7 - 10
logger_setup.py

@@ -2,11 +2,11 @@ import os
 import logging
 import logging
 from logging.handlers import RotatingFileHandler
 from logging.handlers import RotatingFileHandler
 
 
-import log_macros  # 导入你的宏模块
+import log_macros
 
 
 def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None) -> logging.Logger:
 def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None) -> logging.Logger:
     """
     """
-    配置并返回一个标准的 Logger,支持终端输出和文件滚动保存。
+    Configures and returns a standard Logger with console and rotating file handlers.
     """
     """
     if not os.path.exists(log_dir):
     if not os.path.exists(log_dir):
         os.makedirs(log_dir)
         os.makedirs(log_dir)
@@ -14,21 +14,21 @@ def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None)
     logger = logging.getLogger(app_name)
     logger = logging.getLogger(app_name)
     logger.setLevel(logging.INFO)
     logger.setLevel(logging.INFO)
     
     
-    # 避免重复添加 Handler
+    # Avoid adding duplicate handlers
     if not logger.handlers:
     if not logger.handlers:
         log_file = os.path.join(log_dir, f"{app_name.lower()}.log")
         log_file = os.path.join(log_dir, f"{app_name.lower()}.log")
         
         
-        # 1. 终端输出
+        # 1. Console handler
         console_handler = logging.StreamHandler()
         console_handler = logging.StreamHandler()
         console_handler.setLevel(logging.INFO)
         console_handler.setLevel(logging.INFO)
         
         
-        # 2. 文件输出
+        # 2. File handler
         file_handler = RotatingFileHandler(
         file_handler = RotatingFileHandler(
             log_file, maxBytes=10 * 1024 * 1024, backupCount=10, encoding='utf-8'
             log_file, maxBytes=10 * 1024 * 1024, backupCount=10, encoding='utf-8'
         )
         )
         file_handler.setLevel(logging.INFO)
         file_handler.setLevel(logging.INFO)
         
         
-        # 设置格式
+        # Formatter
         formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
         formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
         console_handler.setFormatter(formatter)
         console_handler.setFormatter(formatter)
         file_handler.setFormatter(formatter)
         file_handler.setFormatter(formatter)
@@ -41,10 +41,7 @@ def setup_app_logger(app_name: str, log_dir: str = "logs", extra_handlers=None)
             if h not in logger.handlers:
             if h not in logger.handlers:
                 logger.addHandler(h)
                 logger.addHandler(h)
 
 
-    # ==========================================
-    # 核心:将这个专属 Logger 注入到宏!
-    # 这样整个系统里所有的 VSC_INFO 都会输出到你的 app_name.log 里!
-    # ==========================================
+    # Inject logger into log_macros
     log_macros.set_active_logger(logger)
     log_macros.set_active_logger(logger)
 
 
     return logger
     return logger

+ 20 - 20
main.py

@@ -30,12 +30,12 @@ from utils.plugin_updater import (
 )
 )
 from utils.redis_stream_logger import RedisStreamLogger, RedisStreamLogHandler
 from utils.redis_stream_logger import RedisStreamLogger, RedisStreamLogHandler
 
 
-# 升级指令队列(由 Redis PubSub 线程推送)
+# Upgrade command queue (populated by Redis PubSub listener)
 upgrade_queue = queue.Queue()
 upgrade_queue = queue.Queue()
 
 
 
 
 def get_gco_class(role: str, cfg: Any):
 def get_gco_class(role: str, cfg: Any):
-    """根据角色与配置决定具体的 GCO 实现类"""
+    """Determines specific GCO implementation class based on role and configuration."""
     if role == "sentinel":
     if role == "sentinel":
         return SentinelGCO
         return SentinelGCO
     if role == "standalone":
     if role == "standalone":
@@ -48,7 +48,7 @@ def get_gco_class(role: str, cfg: Any):
 
 
 
 
 def parse_group_configs(role: str, raw_conf: Any) -> Dict[str, Any]:
 def parse_group_configs(role: str, raw_conf: Any) -> Dict[str, Any]:
-    """统一解析组配置为字典 {identifier: config_obj}"""
+    """Uniformly parses group configs into dict {identifier: config_obj}."""
     items = raw_conf if isinstance(raw_conf, list) else ([raw_conf] if isinstance(raw_conf, dict) else [])
     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
     cfg_cls = BookerStandaloneConfig if role == "standalone" else GroupConfig
 
 
@@ -60,7 +60,7 @@ def parse_group_configs(role: str, raw_conf: Any) -> Dict[str, Any]:
 
 
 
 
 def collect_role_status(role: str, node_id: str, wrappers: Dict[str, GCOWrapper]) -> RoleStatus:
 def collect_role_status(role: str, node_id: str, wrappers: Dict[str, GCOWrapper]) -> RoleStatus:
-    """收集当前节点下所有 GroupWrapper 的聚合状态及本地已安装插件完整元数据列表"""
+    """Collects aggregated status of all GroupWrappers on current node and metadata of locally installed plugins."""
     groups_status = [wrapper.get_status() for wrapper in wrappers.values()]
     groups_status = [wrapper.get_status() for wrapper in wrappers.values()]
     installed = get_installed_plugin_metas()
     installed = get_installed_plugin_metas()
 
 
@@ -79,7 +79,7 @@ def reload_wrappers_for_plugin(
     gco_classes: Dict[str, type],
     gco_classes: Dict[str, type],
     logger,
     logger,
 ):
 ):
-    """找到正在使用该插件的 Wrapper 并进行动态热重载"""
+    """Finds wrappers utilizing the plugin and dynamically hot-reloads them."""
     for gid, wrapper in list(wrappers.items()):
     for gid, wrapper in list(wrappers.items()):
         if wrapper.m_cfg.plugin_config.plugin_name == plugin_name:
         if wrapper.m_cfg.plugin_config.plugin_name == plugin_name:
             logger.info(f"Hot-reloading group [{gid}] for upgraded plugin '{plugin_name}'...")
             logger.info(f"Hot-reloading group [{gid}] for upgraded plugin '{plugin_name}'...")
@@ -88,7 +88,7 @@ def reload_wrappers_for_plugin(
             except Exception as e:
             except Exception as e:
                 logger.error(f"Error stopping group [{gid}] during reload: {e}")
                 logger.error(f"Error stopping group [{gid}] during reload: {e}")
 
 
-            # 清除旧模块缓存以加载最新代码
+            # Clear old module cache to load new code
             sys.modules.pop(plugin_name, None)
             sys.modules.pop(plugin_name, None)
 
 
             try:
             try:
@@ -109,13 +109,13 @@ def handle_plugin_upgrades(
     logger,
     logger,
 ) -> bool:
 ) -> bool:
     """
     """
-    检查并执行插件升级列表
-    支持格式:
+    Checks and executes plugin upgrade list.
+    Supported format:
     [
     [
         {
         {
             "plugin_name": "tls_plugin",
             "plugin_name": "tls_plugin",
             "version": "1.1.0",
             "version": "1.1.0",
-            "download_url": "https://...",  # 或 "code": "..."
+            "download_url": "https://...",  # or "code": "..."
             "filename": "tls_plugin.py"
             "filename": "tls_plugin.py"
         }
         }
     ]
     ]
@@ -154,7 +154,7 @@ def handle_plugin_upgrades(
 
 
 
 
 def start_upgrade_listener(redis_conf: Dict, node_id: str, logger):
 def start_upgrade_listener(redis_conf: Dict, node_id: str, logger):
-    """启动 Redis PubSub 后台线程,秒级监听云端下发的即时升级指令"""
+    """Starts Redis PubSub thread to listen for instant upgrade commands dispatched from cloud."""
     def _listen():
     def _listen():
         import redis
         import redis
         while True:
         while True:
@@ -190,10 +190,10 @@ def sync_groups(
     gco_classes: Dict[str, type],
     gco_classes: Dict[str, type],
     logger,
     logger,
 ):
 ):
-    """根据最新配置同步 GCOWrapper 实例的生命周期(停止、重启、更新、新增)"""
+    """Synchronizes GCOWrapper lifecycle (stop, restart, update, start) according to latest config."""
     new_groups = parse_group_configs(role, raw_conf)
     new_groups = parse_group_configs(role, raw_conf)
 
 
-    # 1. 停止已被移除或禁用的组
+    # 1. Stop removed or disabled groups
     for gid in list(wrappers.keys()):
     for gid in list(wrappers.keys()):
         cfg = new_groups.get(gid)
         cfg = new_groups.get(gid)
         if not cfg or not cfg.enable:
         if not cfg or not cfg.enable:
@@ -205,7 +205,7 @@ def sync_groups(
             del wrappers[gid]
             del wrappers[gid]
             gco_classes.pop(gid, None)
             gco_classes.pop(gid, None)
 
 
-    # 2. 处理现有组更新或新增组
+    # 2. Update existing groups or start new groups
     for gid, cfg in new_groups.items():
     for gid, cfg in new_groups.items():
         if not cfg.enable:
         if not cfg.enable:
             continue
             continue
@@ -260,7 +260,7 @@ def main():
     node_id = getattr(configure, "NODE_ID", None) or os.getenv("NODE_ID", "node01")
     node_id = getattr(configure, "NODE_ID", None) or os.getenv("NODE_ID", "node01")
     status_key = f"vs:status:{role}:{node_id}"
     status_key = f"vs:status:{role}:{node_id}"
 
 
-    # 初始化 Redis Stream 日志器并挂载到主 Logger
+    # Initialize Redis Stream logger and attach to main Logger
     stream_logger = RedisStreamLogger.initialize(
     stream_logger = RedisStreamLogger.initialize(
         redis_conf=REDIS_CFG,
         redis_conf=REDIS_CFG,
         node_id=node_id,
         node_id=node_id,
@@ -273,7 +273,7 @@ def main():
 
 
     redis_client = SafeRedisClient(REDIS_CFG, logger.info)
     redis_client = SafeRedisClient(REDIS_CFG, logger.info)
 
 
-    # 启动云端指令实时监听(响应云端下发的升级指令)
+    # Start real-time cloud command listener (handles upgrade commands)
     start_upgrade_listener(REDIS_CFG, node_id, logger)
     start_upgrade_listener(REDIS_CFG, node_id, logger)
 
 
     groups_conf, current_hash, _ = load_remote_or_cache(
     groups_conf, current_hash, _ = load_remote_or_cache(
@@ -290,7 +290,7 @@ def main():
     sync_groups(role, groups_conf, wrappers, gco_classes, logger)
     sync_groups(role, groups_conf, wrappers, gco_classes, logger)
     logger.info(f"Successfully initialized {len(wrappers)} active group(s).")
     logger.info(f"Successfully initialized {len(wrappers)} active group(s).")
 
 
-    # 打印本地已安装插件列表与初始 RoleStatus 摘要
+    # Print locally installed plugins and initial RoleStatus summary
     initial_status = collect_role_status(role, node_id, wrappers)
     initial_status = collect_role_status(role, node_id, wrappers)
     installed_count = len(initial_status.installed_plugins)
     installed_count = len(initial_status.installed_plugins)
     active_count = len(wrappers)
     active_count = len(wrappers)
@@ -313,7 +313,7 @@ def main():
             time.sleep(1)
             time.sleep(1)
             now = time.time()
             now = time.time()
 
 
-            # 1. 响应云端下发的即时升级指令 (PubSub)
+            # 1. Process instant upgrade commands from cloud (PubSub)
             while not upgrade_queue.empty():
             while not upgrade_queue.empty():
                 try:
                 try:
                     payload = upgrade_queue.get_nowait()
                     payload = upgrade_queue.get_nowait()
@@ -329,7 +329,7 @@ def main():
 
 
                     if plugins_items:
                     if plugins_items:
                         if handle_plugin_upgrades(plugins_items, wrappers, gco_classes, logger):
                         if handle_plugin_upgrades(plugins_items, wrappers, gco_classes, logger):
-                            # 升级成功,立即刷新并上报最新 RoleStatus
+                            # Upgrade succeeded; immediately refresh and report latest RoleStatus
                             new_status = collect_role_status(role, node_id, wrappers)
                             new_status = collect_role_status(role, node_id, wrappers)
                             status_dict = new_status.to_dict()
                             status_dict = new_status.to_dict()
                             redis_client.setex(status_key, report_ttl, json.dumps(status_dict))
                             redis_client.setex(status_key, report_ttl, json.dumps(status_dict))
@@ -337,7 +337,7 @@ def main():
                 except queue.Empty:
                 except queue.Empty:
                     break
                     break
 
 
-            # 2. 定时上报包含 installed_plugins 的 RoleStatus
+            # 2. Periodically report RoleStatus containing installed_plugins
             if now - last_status_report_time >= args.status_interval:
             if now - last_status_report_time >= args.status_interval:
                 last_status_report_time = now
                 last_status_report_time = now
                 try:
                 try:
@@ -348,7 +348,7 @@ def main():
                 except Exception as e:
                 except Exception as e:
                     logger.warning(f"Error reporting RoleStatus to Redis '{status_key}': {e}")
                     logger.warning(f"Error reporting RoleStatus to Redis '{status_key}': {e}")
 
 
-            # 3. 云端分组配置定时轮询与热更新
+            # 3. Periodically poll cloud group configuration for hot updates
             if use_cloud and (now - last_poll_time >= args.poll_interval):
             if use_cloud and (now - last_poll_time >= args.poll_interval):
                 last_poll_time = now
                 last_poll_time = now
                 try:
                 try:

+ 20 - 20
plugin.py

@@ -3,12 +3,12 @@ from typing import Callable, List, Dict
 from abc import ABC, abstractmethod
 from abc import ABC, abstractmethod
 from core_types import PluginConfig, AppointmentType, QueryResult, BookResult, PluginStatus
 from core_types import PluginConfig, AppointmentType, QueryResult, BookResult, PluginStatus
 
 
-# ================== 接口类 ==================
+# ================== Interface Class ==================
 class IPlugin(ABC):
 class IPlugin(ABC):
     """
     """
-    @brief 签证 API 接口类
-    该接口定义了签证系统的基本操作,包括配置、会话管理、查询、预订、
-    健康检查以及错误处理等。所有具体的签证 API 实现都需要继承该接口。
+    @brief Plugin API interface class
+    Defines core operations for visa automation plugins, including configuration, session management,
+    querying, booking, health checks, and resource cleanup. All concrete plugin implementations must inherit from this interface.
     """
     """
     name: str = ""
     name: str = ""
     version: str = "1.0.0"
     version: str = "1.0.0"
@@ -17,7 +17,7 @@ class IPlugin(ABC):
     @classmethod
     @classmethod
     def get_plugin_info(cls) -> Dict[str, str]:
     def get_plugin_info(cls) -> Dict[str, str]:
         """
         """
-        @brief 获取插件静态元数据信息
+        @brief Gets plugin static metadata information.
         """
         """
         return {
         return {
             "name": cls.name or cls.__name__,
             "name": cls.name or cls.__name__,
@@ -28,68 +28,68 @@ class IPlugin(ABC):
     @abstractmethod
     @abstractmethod
     def set_config(self, config: PluginConfig):
     def set_config(self, config: PluginConfig):
         """
         """
-        @brief 设置 API 的配置信息
-        @param config 签证 API 配置对象
+        @brief Sets API configuration.
+        @param config PluginConfig configuration object
         """
         """
         pass
         pass
     
     
     @abstractmethod
     @abstractmethod
     def set_log(self, logger: Callable[[str], None]) -> None:
     def set_log(self, logger: Callable[[str], None]) -> None:
         """
         """
-        @brief 设置日志输出工具, 该函数不允许抛异常
+        @brief Sets logging function. Must not raise exceptions.
         """
         """
         pass
         pass
 
 
     @abstractmethod
     @abstractmethod
     def create_session(self) -> None:
     def create_session(self) -> None:
         """
         """
-        @brief 创建一个新的会话, 抛异常则创建失败
+        @brief Creates a new session. Raises exception on failure.
         """
         """
         pass
         pass
 
 
     @abstractmethod
     @abstractmethod
     def query(self, apt_type: AppointmentType) -> QueryResult:
     def query(self, apt_type: AppointmentType) -> QueryResult:
         """
         """
-        @brief 查询可用的签证预约信息, 抛异常则查询失败
-        @return QueryResult 查询结果
+        @brief Queries available appointment slots. Raises exception on failure.
+        @return QueryResult object containing query results
         """
         """
         pass
         pass
 
 
     @abstractmethod
     @abstractmethod
     def book(self, slot_info: QueryResult, user_inputs) -> BookResult:
     def book(self, slot_info: QueryResult, user_inputs) -> BookResult:
         """
         """
-        @brief 进行预约操作, 抛异常则预定失败
-        @param slot_info 查询得到的可用时段信息
-        @param user_inputs 用户输入的预约信息
-        @return BookResult 预约结果
+        @brief Executes booking attempt. Raises exception on failure.
+        @param slot_info QueryResult slot information
+        @param user_inputs User inputs for the booking
+        @return BookResult object representing booking result
         """
         """
         pass
         pass
     
     
     @abstractmethod
     @abstractmethod
     def keep_alive(self):
     def keep_alive(self):
         """
         """
-        @brief 会话保活, 如果会定时调用query则不需要调用该函数, 该函数不允许抛异常
+        @brief Keeps session alive. Must not raise exceptions.
         """
         """
         pass
         pass
 
 
     @abstractmethod
     @abstractmethod
     def health_check(self) -> bool:
     def health_check(self) -> bool:
         """
         """
-        @brief 健康检查,用于检测 API 服务是否正常, 该函数不允许抛异常
-        @return true 表示健康状态良好,false 表示存在问题
+        @brief Performs health check to test API service status. Must not raise exceptions.
+        @return True if healthy, False if issues exist
         """
         """
         pass
         pass
     
     
     @abstractmethod
     @abstractmethod
     def cleanup(self) -> None:
     def cleanup(self) -> None:
         """
         """
-        @brief 清理实例使用的资源
+        @brief Cleans up resources held by the plugin instance.
         """
         """
         pass
         pass
 
 
     def get_plugin_status(self) -> PluginStatus:
     def get_plugin_status(self) -> PluginStatus:
         """
         """
-        @brief 获取插件实例当前的运行状态快照(默认返回基础状态,插件按需重写)
+        @brief Gets snapshot of plugin instance runtime status.
         @return PluginStatus
         @return PluginStatus
         """
         """
         return PluginStatus()
         return PluginStatus()

+ 12 - 12
plugin_factory.py

@@ -7,28 +7,28 @@ from log_macros import VSC_ERROR, VSC_INFO
 
 
 class PluginFactory:
 class PluginFactory:
     """
     """
-    @brief 签证插件工厂类
-    负责动态加载和创建 IPlugin 接口的实现实例。
+    @brief Plugin factory class
+    Responsible for dynamically loading and creating IPlugin implementation instances.
     """
     """
     def __init__(self):
     def __init__(self):
         self._registered_plugins = {} # {plugin_name: (module_name, class_name)}
         self._registered_plugins = {} # {plugin_name: (module_name, class_name)}
 
 
     def register_plugin(self, plugin_name: str, module_path: str, class_name: str):
     def register_plugin(self, plugin_name: str, module_path: str, class_name: str):
         """
         """
-        @brief 注册插件
-        @param plugin_name 插件的逻辑名称
-        @param module_path 插件模块的 Python 文件路径 (e.g., "plugins/concrete_plugin.py")
-        @param class_name 插件实现类的名称 (e.g., "ConcretePlugin")
+        @brief Registers a plugin
+        @param plugin_name Logical name of plugin
+        @param module_path Python file path of plugin module (e.g. "plugins/concrete_plugin.py")
+        @param class_name Name of plugin implementation class (e.g. "ConcretePlugin")
         """
         """
         self._registered_plugins[plugin_name] = (module_path, class_name)
         self._registered_plugins[plugin_name] = (module_path, class_name)
         VSC_INFO("factory", "Registered plugin '%s' from '%s' class '%s'", plugin_name, module_path, class_name)
         VSC_INFO("factory", "Registered plugin '%s' from '%s' class '%s'", plugin_name, module_path, class_name)
 
 
     def create(self, group_id: str, plugin_name: str) -> IPlugin:
     def create(self, group_id: str, plugin_name: str) -> IPlugin:
         """
         """
-        @brief 创建一个 IPlugin 实例
-        @param group_id 实例所属的分组 ID
-        @param plugin_name 要创建的插件的注册名称
-        @return IPlugin 实例
+        @brief Creates an IPlugin instance
+        @param group_id Group ID to which instance belongs
+        @param plugin_name Registered name of plugin to instantiate
+        @return IPlugin instance
         """
         """
         if plugin_name not in self._registered_plugins:
         if plugin_name not in self._registered_plugins:
             VSC_ERROR("factory", "Plugin '%s' not registered.", plugin_name)
             VSC_ERROR("factory", "Plugin '%s' not registered.", plugin_name)
@@ -37,7 +37,7 @@ class PluginFactory:
         module_path, class_name = self._registered_plugins[plugin_name]
         module_path, class_name = self._registered_plugins[plugin_name]
         
         
         try:
         try:
-            # 动态加载模块
+            # Dynamically load module
             spec = importlib.util.spec_from_file_location(plugin_name, module_path)
             spec = importlib.util.spec_from_file_location(plugin_name, module_path)
             if spec is None:
             if spec is None:
                 VSC_ERROR("factory", "Failed to find module spec for '%s' at '%s'", plugin_name, module_path)
                 VSC_ERROR("factory", "Failed to find module spec for '%s' at '%s'", plugin_name, module_path)
@@ -47,7 +47,7 @@ class PluginFactory:
             sys.modules[plugin_name] = module
             sys.modules[plugin_name] = module
             spec.loader.exec_module(module)
             spec.loader.exec_module(module)
             
             
-            # 获取类并实例化
+            # Fetch class and instantiate
             plugin_class = getattr(module, class_name)
             plugin_class = getattr(module, class_name)
             instance = plugin_class(group_id)
             instance = plugin_class(group_id)
             
             

+ 68 - 48
sentinel.py

@@ -3,13 +3,14 @@ import time
 import json
 import json
 import random
 import random
 import threading
 import threading
-from datetime import datetime
+from datetime import datetime, timedelta, timezone
 from typing import List, Dict, Callable, Optional
 from typing import List, Dict, Callable, Optional
 
 
 from core_types import (
 from core_types import (
     GroupConfig, PluginConfig, Account, Task, QueryWaitMode, GroupStatus, PluginStatus, utc_now_str,
     GroupConfig, PluginConfig, Account, Task, QueryWaitMode, GroupStatus, PluginStatus, utc_now_str,
     BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
     BizException, RateLimiteddError, SessionExpiredOrInvalidError, PermissionDeniedError,
-    NetworkTimeoutError
+    NetworkTimeoutError, AccountStateError, AccountAuthError, AccountBannedError,
+    AccountIncompleteError, AccountNotFoundError, normalize_error
 )
 )
 from plugin_factory import PluginFactory 
 from plugin_factory import PluginFactory 
 from toolkit.cloud_api import CloudApi
 from toolkit.cloud_api import CloudApi
@@ -37,7 +38,7 @@ class SentinelGCO:
             print(f'[SENTINEL] [{self.m_cfg.identifier}] {message}')
             print(f'[SENTINEL] [{self.m_cfg.identifier}] {message}')
             
             
     def _get_average_interval(self) -> float:
     def _get_average_interval(self) -> float:
-        """计算当前组平均的查询间隔(秒)"""
+        """Calculates the average query interval (in seconds) for the current group."""
         mode = self.m_cfg.sentinel.query_wait.mode
         mode = self.m_cfg.sentinel.query_wait.mode
         if mode == QueryWaitMode.Loop:
         if mode == QueryWaitMode.Loop:
             return 1.0
             return 1.0
@@ -49,7 +50,7 @@ class SentinelGCO:
     
     
     def update_config(self, new_cfg: GroupConfig):
     def update_config(self, new_cfg: GroupConfig):
         """
         """
-        动态更新配置
+        Dynamically updates the configuration.
         """
         """
         with self.m_lock:
         with self.m_lock:
             if self.m_cfg.enable and not new_cfg.enable:
             if self.m_cfg.enable and not new_cfg.enable:
@@ -131,27 +132,8 @@ class SentinelGCO:
     def _get_redis_key(self, routing_key: str) -> str:
     def _get_redis_key(self, routing_key: str) -> str:
         return f"vs:signal:{routing_key}"
         return f"vs:signal:{routing_key}"
 
 
-    def _normalize_error(self, err: Exception) -> BizException:
-        """规整化异常为领域异常 BizException,保留对历史特征字符串的兜底兼容"""
-        err_str = str(err)
-        # 如果是底层网络/CORS预检被拒导致的 Fetch 失败或 WAF 阻断,精准提升为 PermissionDeniedError
-        if "Failed to fetch" in err_str or "Status: 0" in err_str or "WAF Blocked" in err_str or "cf-mitigated" in err_str:
-            return PermissionDeniedError(message=err_str)
-        if isinstance(err, BizException):
-            return err
-        if "42901" in err_str or "Rate limited" in err_str:
-            return RateLimiteddError(message=err_str)
-        if "40101" in err_str or "Session expired" in err_str or "session invalid" in err_str.lower():
-            return SessionExpiredOrInvalidError(message=err_str)
-        if "40301" in err_str or "403" in err_str or "Cloudflare Access Denied" in err_str:
-            return PermissionDeniedError(message=err_str)
-        return BizException(
-            code=50000,
-            message=f"Unhandled ({type(err).__name__}): {err_str}",
-        )
-
     def _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
     def _release_account_safely(self, acc: Optional[Account], reason: str = "spawn failed") -> None:
-        """安全归还账号:将云端冷却时间重置为 0,避免非账号问题导致账号被误锁 3 小时"""
+        """Safely releases account: resets cloud cooldown to 0 to prevent 3-hour lockouts caused by non-account issues."""
         if acc and acc.id > 0 and acc.username not in ("", "Guest"):
         if acc and acc.id > 0 and acc.username not in ("", "Guest"):
             try:
             try:
                 CloudApi.Instance().lock_account(acc.id, 0)
                 CloudApi.Instance().lock_account(acc.id, 0)
@@ -159,6 +141,35 @@ class SentinelGCO:
             except Exception as e:
             except Exception as e:
                 self._log(f"Failed to release account [{acc.username}]: {e}")
                 self._log(f"Failed to release account [{acc.username}]: {e}")
 
 
+    def _disable_account_safely(self, acc: Optional[Account], reason: str = "") -> None:
+        """Safely disables account in cloud: sets status='disable', locks for 10 years, and records extra_data."""
+        if not acc or acc.id <= 0 or acc.username in ("", "Guest"):
+            return
+
+        try:
+            cloud = CloudApi.Instance()
+            url = f"{cloud.base_url}/api/account/update"
+            params = {"account_id": acc.id}
+            far_future = (datetime.now(timezone.utc) + timedelta(days=3650)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
+            payload = {
+                "status": "disable",
+                "next_use_time": far_future,
+                "extra_data": {
+                    "disable_reason": reason,
+                    "disabled_at": int(time.time()),
+                    "module": "SENTINEL",
+                    "group": getattr(self.m_cfg, "identifier", "")
+                }
+            }
+            cloud._perform_request('PUT', url, params=params, json_data=payload, headers=cloud._get_headers(), timeout=10)
+            self._log(f"🚫 [Account Disabled] Account [{acc.username}] (ID={acc.id}) permanently marked as 'disable' in Cloud API. Reason: {reason}")
+        except Exception as e:
+            self._log(f"Failed to set account status to disable via cloud API: {e}. Falling back to 10-year lock...")
+            try:
+                CloudApi.Instance().lock_account(acc.id, 86400 * 3650)
+            except Exception as lock_err:
+                self._log(f"Fallback 10-year lock also failed: {lock_err}")
+
     def _dispatch_error_policy(
     def _dispatch_error_policy(
         self,
         self,
         action: str,
         action: str,
@@ -167,20 +178,34 @@ class SentinelGCO:
         plg_cfg: Optional[PluginConfig] = None
         plg_cfg: Optional[PluginConfig] = None
     ) -> None:
     ) -> None:
         """
         """
-        Sentinel 错误调度与自愈策略引擎 (Policy Engine):
-        基于 (Action, 异常事实类型) 矩阵 + 哨兵池模式闭环执行自愈动作:
-        - spawn/login 时 429:判定为账号级限流,锁定账号并设置 m_spawn_cooldown_until 退避;
-        - query 时 429:会话已登录,判定为出口 IP 频率超限,不锁定账号,移除任务以触发 creator 换代理生成新实例;
-        - session expired / 401:移除故障任务;
-        - 403 Forbidden / WAF:判定为出口 IP 被风控,移除任务以轮换代理;在 spawn 时立即安全释放账号;
-        - 内部直接完成日志输出与定时器维护,调用方无需感知具体冷却数值。
+        Sentinel error dispatch and self-healing policy engine:
+        Executes self-healing actions based on the (action, error type) matrix:
+        - AccountStateError (invalid credentials, banned, incomplete): Permanently disables pool account, never releases back to pool.
+        - 429 during spawn/login: Account-level rate limit. Locks account and sets m_spawn_cooldown_until backoff.
+        - 429 during query: Session is valid; egress IP frequency limit. Preserves account, removes task to trigger creator spawning a new instance with a fresh proxy.
+        - 401 / session expired: Removes broken task.
+        - 403 Forbidden / WAF: IP blocked. Removes task to rotate proxy; safely releases account during spawn.
+        - Handles logging and timer backoffs internally.
         """
         """
-        biz_err = self._normalize_error(err)
+        biz_err = normalize_error(err)
         active_plg_cfg = plg_cfg or (task.instance.config if task else None)
         active_plg_cfg = plg_cfg or (task.instance.config if task else None)
         acc = active_plg_cfg.account if active_plg_cfg else None
         acc = active_plg_cfg.account if active_plg_cfg else None
 
 
-        # 1. 目标站限流 / 429
-        if isinstance(biz_err, RateLimiteddError):
+        # 0. Fatal Account State Error (credentials invalid, banned, incomplete, not found)
+        if isinstance(biz_err, AccountStateError):
+            self._log(f"🚨 [Account Fatal Error] {biz_err.__class__.__name__} during {action}: {biz_err.message} (code={biz_err.code})")
+            if acc and acc.id > 0 and acc.username not in ("", "Guest"):
+                self._disable_account_safely(acc, reason=f"{biz_err.__class__.__name__}: {biz_err.message}")
+
+            # Never release account back to pool
+            if task:
+                self._remove_task(task, f"account fatal error: {biz_err.message}")
+
+            if action in ("spawn", "login", "create_session"):
+                self.m_spawn_cooldown_until = time.time() + 5.0
+
+        # 1. Target site rate limit / 429
+        elif isinstance(biz_err, RateLimiteddError):
             if action in ("spawn", "login", "create_session"):
             if action in ("spawn", "login", "create_session"):
                 backoff = float(self.m_cfg.login_backoff)
                 backoff = float(self.m_cfg.login_backoff)
                 self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
                 self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
@@ -194,7 +219,7 @@ class SentinelGCO:
                 if task:
                 if task:
                     self._remove_task(task, "spawn account rate limited")
                     self._remove_task(task, "spawn account rate limited")
             elif action == "query":
             elif action == "query":
-                # 查询时 429:出口 IP 限流,绝不锁账号,移除当前 task 触发自动换新代理!
+                # 429 during query: egress IP throttled, preserve account, remove current task to trigger auto-rotation to a new proxy
                 self._log("🔄 [Proxy Rate Limited] Sentinel query hit 429 (IP throttled, Account preserved). Removing task to rotate proxy...")
                 self._log("🔄 [Proxy Rate Limited] Sentinel query hit 429 (IP throttled, Account preserved). Removing task to rotate proxy...")
                 if task:
                 if task:
                     self._remove_task(task, "query ip rate limited")
                     self._remove_task(task, "query ip rate limited")
@@ -203,7 +228,7 @@ class SentinelGCO:
                 if task:
                 if task:
                     task.next_run = time.time() + 10.0
                     task.next_run = time.time() + 10.0
 
 
-        # 2. 会话过期 / 401
+        # 2. Session expired / 401
         elif isinstance(biz_err, SessionExpiredOrInvalidError):
         elif isinstance(biz_err, SessionExpiredOrInvalidError):
             if action in ("spawn", "login", "create_session"):
             if action in ("spawn", "login", "create_session"):
                 self._log(f"❌ [Auth Failed] Sentinel spawn failed (401). Cooling down spawn for 5s...")
                 self._log(f"❌ [Auth Failed] Sentinel spawn failed (401). Cooling down spawn for 5s...")
@@ -213,7 +238,7 @@ class SentinelGCO:
                 if task:
                 if task:
                     self._remove_task(task, f"{action} session expired")
                     self._remove_task(task, f"{action} session expired")
 
 
-        # 3. 权限被拒 / WAF 拦截 / 403
+        # 3. Permission denied / WAF blocked / 403
         elif isinstance(biz_err, PermissionDeniedError):
         elif isinstance(biz_err, PermissionDeniedError):
             proxy_cd = float(self.m_cfg.proxy_cd or 60.0)
             proxy_cd = float(self.m_cfg.proxy_cd or 60.0)
             self._log(f"🛡️ [WAF Blocked] 403 Forbidden during {action}. Removing task to rotate proxy...")
             self._log(f"🛡️ [WAF Blocked] 403 Forbidden during {action}. Removing task to rotate proxy...")
@@ -223,7 +248,7 @@ class SentinelGCO:
                 self._release_account_safely(acc, reason="WAF Blocked")
                 self._release_account_safely(acc, reason="WAF Blocked")
                 self.m_spawn_cooldown_until = time.time() + proxy_cd
                 self.m_spawn_cooldown_until = time.time() + proxy_cd
 
 
-        # 4. 网络或浏览器超时
+        # 4. Network or browser timeout
         elif isinstance(biz_err, NetworkTimeoutError):
         elif isinstance(biz_err, NetworkTimeoutError):
             self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
             self._log(f"⏱️ [Timeout] Network/browser timeout during {action}.")
             if task:
             if task:
@@ -232,7 +257,7 @@ class SentinelGCO:
                 self._release_account_safely(acc, reason="Network Timeout")
                 self._release_account_safely(acc, reason="Network Timeout")
                 self.m_spawn_cooldown_until = time.time() + 10.0
                 self.m_spawn_cooldown_until = time.time() + 10.0
 
 
-        # 5. 兜底策略
+        # 5. Fallback policy
         else:
         else:
             self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
             self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
             if action in ("spawn", "login", "create_session"):
             if action in ("spawn", "login", "create_session"):
@@ -241,25 +266,20 @@ class SentinelGCO:
             elif task:
             elif task:
                 task.next_run = time.time() + 10.0
                 task.next_run = time.time() + 10.0
 
 
-        # 6. 统一代理健康指标埋点
+        # 6. Proxy health metrics recording
         if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
         if active_plg_cfg and isinstance(active_plg_cfg.proxy.port, int) and active_plg_cfg.proxy.port > 0:
-            err_type = biz_err.message
-            if isinstance(biz_err, PermissionDeniedError):
-                if "403202" in err_type or "cf-mitigated" in err_type.lower() or "waf blocked" in err_type.lower():
-                    err_type = "cf-mitigated (403202)"
-
             ProxyManager.Instance().mark_proxy_result(
             ProxyManager.Instance().mark_proxy_result(
                 proxy=active_plg_cfg.proxy.model_dump(),
                 proxy=active_plg_cfg.proxy.model_dump(),
                 plugin_name=self.m_cfg.plugin_config.plugin_name,
                 plugin_name=self.m_cfg.plugin_config.plugin_name,
                 action=action,
                 action=action,
                 success=False,
                 success=False,
                 http_code=biz_err.http_status,
                 http_code=biz_err.http_status,
-                error_type=err_type
+                error_type=biz_err.message
             )
             )
 
 
     def _is_within_active_hours(self) -> bool:
     def _is_within_active_hours(self) -> bool:
         """
         """
-        判断当前是否在允许创建实例的时间段内
+        Checks if current time is within allowed operating hours.
         """
         """
         start_str = self.m_cfg.active_time_start
         start_str = self.m_cfg.active_time_start
         end_str = self.m_cfg.active_time_end
         end_str = self.m_cfg.active_time_end
@@ -348,7 +368,7 @@ class SentinelGCO:
                             redis_key = self._get_redis_key(apt_type.routing_key)
                             redis_key = self._get_redis_key(apt_type.routing_key)
                             self.redis_client.setex(redis_key, ttl, json.dumps(payload))
                             self.redis_client.setex(redis_key, ttl, json.dumps(payload))
                         task.next_run = time.time() + interval
                         task.next_run = time.time() + interval
-                        # 埋点上报 query 成功
+                        # Record successful query metrics for proxy
                         if task.instance.config.proxy.port > 0:
                         if task.instance.config.proxy.port > 0:
                             ProxyManager.Instance().mark_proxy_result(
                             ProxyManager.Instance().mark_proxy_result(
                                 proxy=task.instance.config.proxy.model_dump(),
                                 proxy=task.instance.config.proxy.model_dump(),

+ 82 - 56
standalone.py

@@ -2,13 +2,14 @@ import os
 import time
 import time
 import random
 import random
 import threading
 import threading
-from datetime import datetime
+from datetime import datetime, timedelta, timezone
 from typing import Dict, Callable, Optional
 from typing import Dict, Callable, Optional
 
 
 from core_types import (
 from core_types import (
     BookerStandaloneConfig,
     BookerStandaloneConfig,
     QueryWaitMode,
     QueryWaitMode,
     PluginConfig,
     PluginConfig,
+    Account,
     QueryResult,
     QueryResult,
     BookResult,
     BookResult,
     GroupStatus,
     GroupStatus,
@@ -18,19 +19,25 @@ from core_types import (
     RateLimiteddError,
     RateLimiteddError,
     SessionExpiredOrInvalidError,
     SessionExpiredOrInvalidError,
     PermissionDeniedError,
     PermissionDeniedError,
-    NetworkTimeoutError
+    NetworkTimeoutError,
+    AccountStateError,
+    AccountAuthError,
+    AccountBannedError,
+    AccountIncompleteError,
+    AccountNotFoundError,
+    normalize_error
 )
 )
 from plugin_factory import PluginFactory
 from plugin_factory import PluginFactory
+from toolkit.cloud_api import CloudApi
 from utils.safe_redis_cli import SafeRedisClient
 from utils.safe_redis_cli import SafeRedisClient
 from toolkit.proxy_manager import ProxyManager
 from toolkit.proxy_manager import ProxyManager
-from toolkit.cloud_api import CloudApi
 from toolkit.notifier import notify_date_changes, notify_book_result
 from toolkit.notifier import notify_date_changes, notify_book_result
 
 
 
 
 class StandaloneGCO:
 class StandaloneGCO:
     """
     """
-    Standalone GCO 实例管理器。
-    遵循 SentinelGCO / BookerGCO 的统一生命周期契约 (start / stop / update_config)。
+    Standalone GCO Instance Manager.
+    Adheres to the unified lifecycle contract of SentinelGCO / BookerGCO (start / stop / update_config).
     """
     """
     TAG = "STANDALONE"
     TAG = "STANDALONE"
 
 
@@ -56,7 +63,7 @@ class StandaloneGCO:
             print(f"{prefix} {message}")
             print(f"{prefix} {message}")
 
 
     def _get_wait_interval(self) -> float:
     def _get_wait_interval(self) -> float:
-        """根据配置计算下一次查询的等待时间"""
+        """Calculate wait interval for next query based on configuration."""
         mode = self.m_cfg.query_wait.mode
         mode = self.m_cfg.query_wait.mode
         if mode == QueryWaitMode.Loop:
         if mode == QueryWaitMode.Loop:
             return 1.0
             return 1.0
@@ -67,7 +74,7 @@ class StandaloneGCO:
         return 30.0
         return 30.0
 
 
     def _is_within_active_hours(self) -> bool:
     def _is_within_active_hours(self) -> bool:
-        """判断当前是否在允许创建实例和查询的时间段内"""
+        """Determine if current time is within active operating window for instances and queries."""
         start_str = self.m_cfg.active_time_start
         start_str = self.m_cfg.active_time_start
         end_str = self.m_cfg.active_time_end
         end_str = self.m_cfg.active_time_end
         current_bj_time = datetime.utcnow().time()
         current_bj_time = datetime.utcnow().time()
@@ -76,7 +83,7 @@ class StandaloneGCO:
         return start_time <= current_bj_time <= end_time
         return start_time <= current_bj_time <= end_time
 
 
     def update_config(self, new_cfg: BookerStandaloneConfig):
     def update_config(self, new_cfg: BookerStandaloneConfig):
-        """动态更新配置"""
+        """Dynamically update group configuration."""
         with self.m_lock:
         with self.m_lock:
             if self.m_cfg.enable and not new_cfg.enable:
             if self.m_cfg.enable and not new_cfg.enable:
                 self._log("Config dynamically updated: Group DISABLED.")
                 self._log("Config dynamically updated: Group DISABLED.")
@@ -112,7 +119,7 @@ class StandaloneGCO:
         )
         )
 
 
     def start(self):
     def start(self):
-        """非阻塞启动,注册插件并开启后台工作线程"""
+        """Non-blocking start: registers plugin and starts background worker thread."""
         if not self.m_cfg.enable:
         if not self.m_cfg.enable:
             return
             return
 
 
@@ -126,7 +133,7 @@ class StandaloneGCO:
         threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
         threading.Thread(target=self._worker_loop, daemon=True, name=worker_name).start()
 
 
     def stop(self):
     def stop(self):
-        """优雅停止"""
+        """Gracefully stop background worker and clean up resources."""
         self._log("Stopping Standalone GCO...")
         self._log("Stopping Standalone GCO...")
         self.m_stop_event.set()
         self.m_stop_event.set()
         self._cleanup_instance("standalone stopped")
         self._cleanup_instance("standalone stopped")
@@ -143,7 +150,7 @@ class StandaloneGCO:
                     self.m_instance = None
                     self.m_instance = None
 
 
     def _init_instance(self):
     def _init_instance(self):
-        """初始化单实例并进行登录创建会话"""
+        """Initialize single instance and log in to create a session."""
         self._cleanup_instance("recreating new session")
         self._cleanup_instance("recreating new session")
 
 
         now = time.time()
         now = time.time()
@@ -176,46 +183,65 @@ class StandaloneGCO:
         self.m_next_keepalive_time = time.time() + 10.0
         self.m_next_keepalive_time = time.time() + 10.0
         self._log(f"Session created successfully. Initial query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')}).")
         self._log(f"Session created successfully. Initial query scheduled in {interval:.1f}s (at {datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')}).")
 
 
-    def _normalize_error(self, err: Exception) -> BizException:
-        """
-        将任意异常规整化为领域异常 BizException。
-        保留对未结构化历史异常字符串特征的兜底兼容识别。
-        """
-        if isinstance(err, BizException):
-            return err
-
-        err_str = str(err)
-        if "42901" in err_str or "Rate limited" in err_str:
-            return RateLimiteddError(message=err_str)
-        if "40101" in err_str or "Session expired" in err_str or "session invalid" in err_str.lower():
-            return SessionExpiredOrInvalidError(message=err_str)
-        if "40301" in err_str or "403" in err_str or "Cloudflare Access Denied" in err_str:
-            return PermissionDeniedError(message=err_str)
-
-        return BizException(
-            code=50000,
-            message=f"Unhandled ({type(err).__name__}): {err_str}",
-        )
+    def _disable_account_safely(self, acc: Optional[Account], reason: str = "") -> None:
+        """Safely disables account in cloud: sets status='disable', locks for 10 years, and records extra_data."""
+        if not acc or acc.id <= 0 or acc.username in ("", "Guest"):
+            return
+
+        try:
+            cloud = CloudApi.Instance()
+            url = f"{cloud.base_url}/api/account/update"
+            params = {"account_id": acc.id}
+            far_future = (datetime.now(timezone.utc) + timedelta(days=3650)).isoformat(timespec="milliseconds").replace("+00:00", "Z")
+            payload = {
+                "status": "disable",
+                "next_use_time": far_future,
+                "extra_data": {
+                    "disable_reason": reason,
+                    "disabled_at": int(time.time()),
+                    "module": "STANDALONE",
+                    "group": getattr(self.m_cfg, "identifier", "")
+                }
+            }
+            cloud._perform_request('PUT', url, params=params, json_data=payload, headers=cloud._get_headers(), timeout=10)
+            self._log(f"🚫 [Account Disabled] Account [{acc.username}] (ID={acc.id}) permanently marked as 'disable' in Cloud API. Reason: {reason}")
+        except Exception as e:
+            self._log(f"Failed to set account status to disable via cloud API: {e}. Falling back to 10-year lock...")
+            try:
+                CloudApi.Instance().lock_account(acc.id, 86400 * 3650)
+            except Exception as lock_err:
+                self._log(f"Fallback 10-year lock also failed: {lock_err}")
 
 
     def _dispatch_error_policy(self, action: str, err: Exception) -> None:
     def _dispatch_error_policy(self, action: str, err: Exception) -> None:
         """
         """
-        Standalone 错误调度与自愈策略引擎 (Policy Engine):
-        基于 (Action, 异常事实类型) 矩阵 + Standalone 单机模式 + 本组配置闭环执行自愈动作:
-        - create_session/login 时 429:判定为账号级限流,锁定账号,执行 login_interval 退避等待;
-        - query 时 429:会话已建立,判定为出口 IP 频率超限,不锁定账号,销毁实例触发下轮代理轮换;
-        - session expired / 401:销毁当前实例,重置下一次查询时间为 5s 后以触发重新登录;
-        - 403 Forbidden / WAF:判定为 IP 被封,清理实例换 IP 并退避;
-        - 内部直接完成日志输出与定时器维护,调用方无需感知具体冷却数值。
+        Standalone Error Recovery & Dispatch Policy Engine:
+        Executes self-healing actions based on (Action, Exception Domain Type) matrix:
+        - AccountStateError (invalid credentials, banned, incomplete): Permanently disables account, backs off.
+        - 429 on create_session/login: Account-level rate limit. Lock account and back off.
+        - 429 on query: Session alive, egress IP throttled. Do not lock account; rotate proxy.
+        - session expired / 401: Destroy instance and reschedule re-login in 5s.
+        - 403 Forbidden / WAF: IP blocked. Rotate proxy and back off.
+        - Directly maintains logs and timers internally.
         """
         """
-        biz_err = self._normalize_error(err)
+        biz_err = normalize_error(err)
         acc = self.m_cfg.account if (self.m_cfg.account and self.m_cfg.account.username not in ("", "Guest")) else None
         acc = self.m_cfg.account if (self.m_cfg.account and self.m_cfg.account.username not in ("", "Guest")) else None
 
 
-        # 1. 目标站限流 / 429
-        if isinstance(biz_err, RateLimiteddError):
+        # 0. Fatal Account State Error (credentials invalid, banned, incomplete, not found)
+        if isinstance(biz_err, AccountStateError):
+            self._log(f"🚨 [Account Fatal Error] {biz_err.__class__.__name__} during {action}: {biz_err.message} (code={biz_err.code})")
+            if acc and acc.id > 0 and acc.username not in ("", "Guest"):
+                self._disable_account_safely(acc, reason=f"{biz_err.__class__.__name__}: {biz_err.message}")
+
+            self._cleanup_instance(f"{action} account fatal error: {biz_err.message}")
+            self.m_last_login_time = time.time()
+            self.m_next_query_time = time.time() + 3600.0
+
+        # 1. Target site rate limit / 429
+        elif isinstance(biz_err, RateLimiteddError):
             if action in ("create_session", "login", "spawn"):
             if action in ("create_session", "login", "spawn"):
                 backoff = float(self.m_cfg.login_interval)
                 backoff = float(self.m_cfg.login_interval)
                 self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
                 self._log(f"🔒 [Account Rate Limited] 429 throttled during {action} (Account credential/frequency restricted).")
-                if acc and getattr(acc, "id", 0):
+                if acc and acc.id > 0:
                     try:
                     try:
                         CloudApi.Instance().lock_account(acc.id, int(backoff))
                         CloudApi.Instance().lock_account(acc.id, int(backoff))
                         self._log(f"🔒 Account [{acc.username}] locked for {int(backoff)}s via Cloud API.")
                         self._log(f"🔒 Account [{acc.username}] locked for {int(backoff)}s via Cloud API.")
@@ -224,7 +250,7 @@ class StandaloneGCO:
                 self.m_last_login_time = time.time()
                 self.m_last_login_time = time.time()
                 self._cleanup_instance(f"{action} account rate limited")
                 self._cleanup_instance(f"{action} account rate limited")
             elif action == "query":
             elif action == "query":
-                # 查询时 429:出口 IP 限流,绝不锁账号,换 IP 即可!
+                # 429 during query: Egress IP rate-limited, do not lock account, rotate proxy
                 self._log("🔄 [Proxy Rate Limited] Query hit 429 (IP throttled, Account preserved). Cleaning instance to rotate proxy...")
                 self._log("🔄 [Proxy Rate Limited] Query hit 429 (IP throttled, Account preserved). Cleaning instance to rotate proxy...")
                 self._cleanup_instance("query ip rate limited")
                 self._cleanup_instance("query ip rate limited")
                 self.m_next_query_time = time.time() + 10.0
                 self.m_next_query_time = time.time() + 10.0
@@ -232,7 +258,7 @@ class StandaloneGCO:
                 self._log(f"⚠️ [Rate Limited] 429 encountered during {action}.")
                 self._log(f"⚠️ [Rate Limited] 429 encountered during {action}.")
                 self.m_next_query_time = time.time() + 10.0
                 self.m_next_query_time = time.time() + 10.0
 
 
-        # 2. 会话过期 / 401
+        # 2. Session expired / 401
         elif isinstance(biz_err, SessionExpiredOrInvalidError):
         elif isinstance(biz_err, SessionExpiredOrInvalidError):
             if action in ("create_session", "login", "spawn"):
             if action in ("create_session", "login", "spawn"):
                 self._log(f"❌ [Auth Failed] Session creation failed (401 invalid credentials or challenge). Backing off for 10s...")
                 self._log(f"❌ [Auth Failed] Session creation failed (401 invalid credentials or challenge). Backing off for 10s...")
@@ -243,18 +269,18 @@ class StandaloneGCO:
                 self._cleanup_instance(f"{action} session expired")
                 self._cleanup_instance(f"{action} session expired")
                 self.m_next_query_time = time.time() + 5.0
                 self.m_next_query_time = time.time() + 5.0
 
 
-        # 3. 权限被拒 / WAF 拦截 / 403
+        # 3. Permission denied / WAF blocked / 403
         elif isinstance(biz_err, PermissionDeniedError):
         elif isinstance(biz_err, PermissionDeniedError):
             self._log(f"🛡️ [WAF Blocked] 403 Forbidden detected during {action}. Cleaning instance to rotate proxy (60s cooldown)...")
             self._log(f"🛡️ [WAF Blocked] 403 Forbidden detected during {action}. Cleaning instance to rotate proxy (60s cooldown)...")
             self._cleanup_instance(f"{action} waf blocked")
             self._cleanup_instance(f"{action} waf blocked")
             self.m_next_query_time = time.time() + 60.0
             self.m_next_query_time = time.time() + 60.0
 
 
-        # 4. 网络或浏览器超时
+        # 4. Network or browser timeout
         elif isinstance(biz_err, NetworkTimeoutError):
         elif isinstance(biz_err, NetworkTimeoutError):
             self._log(f"⏱️ [Timeout] Network/browser timeout during {action}. Retrying in 5s...")
             self._log(f"⏱️ [Timeout] Network/browser timeout during {action}. Retrying in 5s...")
             self.m_next_query_time = time.time() + 5.0
             self.m_next_query_time = time.time() + 5.0
 
 
-        # 5. 兜底策略
+        # 5. Fallback policy
         else:
         else:
             self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
             self._log(f"⚠️ [{action}] Unexpected error: {biz_err.message} (code={biz_err.code})")
             if action in ("create_session", "worker_loop"):
             if action in ("create_session", "worker_loop"):
@@ -264,7 +290,7 @@ class StandaloneGCO:
 
 
     def _worker_loop(self):
     def _worker_loop(self):
         """
         """
-        后台守护循环:心跳保活 -> 时间判定 -> 查询 -> 预定
+        Background worker daemon loop: keepalive -> schedule check -> query -> booking
         """
         """
         self._log("Standalone worker loop started.")
         self._log("Standalone worker loop started.")
 
 
@@ -278,7 +304,7 @@ class StandaloneGCO:
                     self.m_stop_event.wait(5.0)
                     self.m_stop_event.wait(5.0)
                     continue
                     continue
 
 
-                # 1. 会话初始化与自愈
+                # 1. Session initialization and self-healing
                 if self.m_instance is None:
                 if self.m_instance is None:
                     try:
                     try:
                         self._init_instance()
                         self._init_instance()
@@ -286,27 +312,27 @@ class StandaloneGCO:
                         self._dispatch_error_policy("create_session", e)
                         self._dispatch_error_policy("create_session", e)
                         continue
                         continue
 
 
-                # 2. 健康检查
+                # 2. Health check
                 if self.m_instance and not self.m_instance.health_check():
                 if self.m_instance and not self.m_instance.health_check():
                     self._log("Health check failed. Session dead. Recreating session...")
                     self._log("Health check failed. Session dead. Recreating session...")
                     self._cleanup_instance("session health check failed")
                     self._cleanup_instance("session health check failed")
                     continue
                     continue
 
 
-                # 3. 查询等待与周期性保活
+                # 3. Query interval wait and periodic keepalive
                 now = time.time()
                 now = time.time()
                 if now < self.m_next_query_time:
                 if now < self.m_next_query_time:
                     remaining = self.m_next_query_time - now
                     remaining = self.m_next_query_time - now
                     next_query_str = datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')
                     next_query_str = datetime.fromtimestamp(self.m_next_query_time).strftime('%H:%M:%S')
                     keep_alive_sec = self.m_cfg.keep_alive
                     keep_alive_sec = self.m_cfg.keep_alive
 
 
-                    # 周期性保活
+                    # Periodic keepalive
                     if self.m_instance and now >= self.m_next_keepalive_time:
                     if self.m_instance and now >= self.m_next_keepalive_time:
                         self.m_instance.keep_alive()
                         self.m_instance.keep_alive()
                         self.m_next_keepalive_time = now + keep_alive_sec
                         self.m_next_keepalive_time = now + keep_alive_sec
                         self._log(f"Session keepalive sent. Next query at {next_query_str} (remaining: {remaining:.0f}s)...")
                         self._log(f"Session keepalive sent. Next query at {next_query_str} (remaining: {remaining:.0f}s)...")
                         self.m_last_wait_log_time = now
                         self.m_last_wait_log_time = now
 
 
-                    # 周期性显示等待倒计时(每隔 15 秒提示一次)
+                    # Periodic wait countdown (logged every 15s)
                     elif now - self.m_last_wait_log_time >= 15.0 and remaining > 3.0:
                     elif now - self.m_last_wait_log_time >= 15.0 and remaining > 3.0:
                         self.m_last_wait_log_time = now
                         self.m_last_wait_log_time = now
                         self._log(f"Waiting for next query at {next_query_str} (remaining: {remaining:.0f}s)...")
                         self._log(f"Waiting for next query at {next_query_str} (remaining: {remaining:.0f}s)...")
@@ -315,7 +341,7 @@ class StandaloneGCO:
                     self.m_stop_event.wait(wait_sec)
                     self.m_stop_event.wait(wait_sec)
                     continue
                     continue
 
 
-                # 4. 随机选取 routing_key 进行查询
+                # 4. Randomly pick a routing_key for query
                 apt_types = self.m_cfg.appointment_types
                 apt_types = self.m_cfg.appointment_types
                 if not apt_types:
                 if not apt_types:
                     self.m_stop_event.wait(2.0)
                     self.m_stop_event.wait(2.0)
@@ -336,7 +362,7 @@ class StandaloneGCO:
                     self._dispatch_error_policy("query", e)
                     self._dispatch_error_policy("query", e)
                     continue
                     continue
 
 
-                # 5. 发现档期,执行自动预定
+                # 5. Slot found: trigger auto-booking
                 if query_result.success:
                 if query_result.success:
                     self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
                     self._log("🔥 SLOT FOUND! Initiating AUTO-BOOKING...")
                     try:
                     try:
@@ -348,7 +374,7 @@ class StandaloneGCO:
                     except Exception as e:
                     except Exception as e:
                         self._dispatch_error_policy("book", e)
                         self._dispatch_error_policy("book", e)
 
 
-                # 6. 在所有操作(包括抢单流程)执行完毕后,再统一计算并调度下一次查询时间与保活时间
+                # 6. Recompute and schedule next query and keepalive times
                 interval = self._get_wait_interval()
                 interval = self._get_wait_interval()
                 now = time.time()
                 now = time.time()
                 self.m_next_query_time = now + interval
                 self.m_next_query_time = now + interval

+ 124 - 31
test/test_metadata_exception.py

@@ -11,16 +11,22 @@ from core_types import (
     NotFoundError,
     NotFoundError,
     BizLogicError,
     BizLogicError,
     NetworkTimeoutError,
     NetworkTimeoutError,
+    AccountStateError,
+    AccountAuthError,
+    AccountBannedError,
+    AccountIncompleteError,
+    AccountNotFoundError,
     PluginError,
     PluginError,
     BookerStandaloneConfig,
     BookerStandaloneConfig,
     PluginConfig,
     PluginConfig,
+    normalize_error
 )
 )
 from standalone import StandaloneGCO
 from standalone import StandaloneGCO
 
 
 
 
 class TestMetadataExceptions(unittest.TestCase):
 class TestMetadataExceptions(unittest.TestCase):
     def test_exception_pure_facts(self):
     def test_exception_pure_facts(self):
-        """验证异常仅表达领域事实(状态码、HTTP状态、信息),不携带调度器执行策略"""
+        """Verifies exception expresses pure domain facts without coupling scheduler policies."""
         # 1. RateLimiteddError
         # 1. RateLimiteddError
         err_rate = RateLimiteddError("Too fast")
         err_rate = RateLimiteddError("Too fast")
         self.assertEqual(err_rate.code, 42901)
         self.assertEqual(err_rate.code, 42901)
@@ -31,7 +37,7 @@ class TestMetadataExceptions(unittest.TestCase):
         self.assertFalse(hasattr(err_rate, "cooldown_sec"))
         self.assertFalse(hasattr(err_rate, "cooldown_sec"))
         self.assertFalse(hasattr(err_rate, "rotate_proxy"))
         self.assertFalse(hasattr(err_rate, "rotate_proxy"))
 
 
-        # 别名验证
+        # Semantic aliases verification
         self.assertIs(RateLimitedError, RateLimiteddError)
         self.assertIs(RateLimitedError, RateLimiteddError)
         self.assertIs(SessionExpiredError, SessionExpiredOrInvalidError)
         self.assertIs(SessionExpiredError, SessionExpiredOrInvalidError)
         self.assertIs(PluginError, BizException)
         self.assertIs(PluginError, BizException)
@@ -51,27 +57,58 @@ class TestMetadataExceptions(unittest.TestCase):
         self.assertEqual(err_perm.code, 40301)
         self.assertEqual(err_perm.code, 40301)
         self.assertEqual(err_perm.http_status, 403)
         self.assertEqual(err_perm.http_status, 403)
 
 
-    def test_standalone_normalize_error(self):
-        cfg = BookerStandaloneConfig(identifier="test_group")
-        gco = StandaloneGCO(cfg=cfg, redis_conf={})
-
-        # 已是规范异常
+        # 5. AccountStateError subclasses
+        auth_err = AccountAuthError("Bad credentials")
+        self.assertEqual(auth_err.code, 40102)
+        self.assertEqual(auth_err.http_status, 401)
+        self.assertIsInstance(auth_err, AccountStateError)
+
+        banned_err = AccountBannedError("Account banned")
+        self.assertEqual(banned_err.code, 40302)
+        self.assertEqual(banned_err.http_status, 403)
+        self.assertIsInstance(banned_err, AccountStateError)
+
+        incomplete_err = AccountIncompleteError("No applicant")
+        self.assertEqual(incomplete_err.code, 42201)
+        self.assertEqual(incomplete_err.http_status, 422)
+        self.assertIsInstance(incomplete_err, AccountStateError)
+
+        not_found_err = AccountNotFoundError("Account deleted")
+        self.assertEqual(not_found_err.code, 40402)
+        self.assertEqual(not_found_err.http_status, 404)
+        self.assertIsInstance(not_found_err, AccountStateError)
+
+    def test_normalize_error(self):
+        # Already standardized exception
         rate_err = RateLimiteddError()
         rate_err = RateLimiteddError()
-        self.assertIs(gco._normalize_error(rate_err), rate_err)
+        self.assertIs(normalize_error(rate_err), rate_err)
 
 
-        # 历史遗留字符串 "42901" 兼容识别
-        raw_429 = Exception("Request failed with 42901 code")
-        normalized_429 = gco._normalize_error(raw_429)
+        # Structured status code recognition (status_code / code)
+        class MockHttpError(Exception):
+            def __init__(self, status_code):
+                self.status_code = status_code
+
+        raw_429 = MockHttpError(429)
+        normalized_429 = normalize_error(raw_429)
         self.assertIsInstance(normalized_429, RateLimiteddError)
         self.assertIsInstance(normalized_429, RateLimiteddError)
 
 
-        # 历史遗留字符串 "Session expired" 兼容识别
-        raw_sess = Exception("Error: Session expired on server")
-        normalized_sess = gco._normalize_error(raw_sess)
+        class MockCodeError(Exception):
+            def __init__(self, code):
+                self.code = code
+
+        raw_sess = MockCodeError(40101)
+        normalized_sess = normalize_error(raw_sess)
         self.assertIsInstance(normalized_sess, SessionExpiredOrInvalidError)
         self.assertIsInstance(normalized_sess, SessionExpiredOrInvalidError)
 
 
-        # 未知异常保底
+        # Account state fatal codes
+        self.assertIsInstance(normalize_error(MockCodeError(40102)), AccountAuthError)
+        self.assertIsInstance(normalize_error(MockCodeError(40302)), AccountBannedError)
+        self.assertIsInstance(normalize_error(MockCodeError(42201)), AccountIncompleteError)
+        self.assertIsInstance(normalize_error(MockCodeError(40402)), AccountNotFoundError)
+
+        # Fallback for unknown exceptions
         raw_unknown = KeyError("element_not_found")
         raw_unknown = KeyError("element_not_found")
-        normalized_unknown = gco._normalize_error(raw_unknown)
+        normalized_unknown = normalize_error(raw_unknown)
         self.assertIsInstance(normalized_unknown, BizException)
         self.assertIsInstance(normalized_unknown, BizException)
         self.assertEqual(normalized_unknown.code, 50000)
         self.assertEqual(normalized_unknown.code, 50000)
 
 
@@ -89,14 +126,14 @@ class TestMetadataExceptions(unittest.TestCase):
         mock_inst = MagicMock()
         mock_inst = MagicMock()
         gco.m_instance = mock_inst
         gco.m_instance = mock_inst
 
 
-        # 场景 A: 登录/建连时 429 -> 账号受限,锁账号
+        # Scenario A: 429 during login/session creation -> account throttled, lock account
         err = RateLimiteddError()
         err = RateLimiteddError()
         gco._dispatch_error_policy("create_session", err)
         gco._dispatch_error_policy("create_session", err)
         mock_cloud.lock_account.assert_called_once_with(12345, 1200)
         mock_cloud.lock_account.assert_called_once_with(12345, 1200)
         mock_inst.cleanup.assert_called_once()
         mock_inst.cleanup.assert_called_once()
         self.assertIsNone(gco.m_instance)
         self.assertIsNone(gco.m_instance)
 
 
-        # 场景 B: 查询时 429 -> 会话已登录,属出口 IP 频率超限,绝不锁账号,换 IP 即可!
+        # Scenario B: 429 during query -> session valid, egress IP throttled, never lock account, rotate IP
         mock_cloud.reset_mock()
         mock_cloud.reset_mock()
         mock_inst2 = MagicMock()
         mock_inst2 = MagicMock()
         gco.m_instance = mock_inst2
         gco.m_instance = mock_inst2
@@ -106,6 +143,16 @@ class TestMetadataExceptions(unittest.TestCase):
         self.assertIsNone(gco.m_instance)
         self.assertIsNone(gco.m_instance)
         self.assertGreater(gco.m_next_query_time, time.time())
         self.assertGreater(gco.m_next_query_time, time.time())
 
 
+        # Scenario C: AccountAuthError -> permanently disable account, do not alert WeChat, do not retry soon
+        mock_cloud.reset_mock()
+        mock_inst3 = MagicMock()
+        gco.m_instance = mock_inst3
+        auth_err = AccountAuthError("Invalid credentials")
+        gco._dispatch_error_policy("create_session", auth_err)
+        mock_cloud._perform_request.assert_called_once()
+        mock_cloud.push_weixin_text.assert_not_called()
+        self.assertIsNone(gco.m_instance)
+
     def test_standalone_dispatch_session_expired_policy(self):
     def test_standalone_dispatch_session_expired_policy(self):
         cfg = BookerStandaloneConfig(identifier="test_group")
         cfg = BookerStandaloneConfig(identifier="test_group")
         gco = StandaloneGCO(cfg=cfg, redis_conf={})
         gco = StandaloneGCO(cfg=cfg, redis_conf={})
@@ -113,11 +160,11 @@ class TestMetadataExceptions(unittest.TestCase):
         mock_inst = MagicMock()
         mock_inst = MagicMock()
         gco.m_instance = mock_inst
         gco.m_instance = mock_inst
 
 
-        # 触发 SessionExpiredOrInvalidError
+        # Trigger SessionExpiredOrInvalidError
         err = SessionExpiredOrInvalidError()
         err = SessionExpiredOrInvalidError()
         gco._dispatch_error_policy("query", err)
         gco._dispatch_error_policy("query", err)
 
 
-        # 验证会话已销毁,并排期 5s 后重连
+        # Verify session destroyed and scheduled retry after 5s
         mock_inst.cleanup.assert_called_once()
         mock_inst.cleanup.assert_called_once()
         self.assertIsNone(gco.m_instance)
         self.assertIsNone(gco.m_instance)
         self.assertGreater(gco.m_next_query_time, time.time())
         self.assertGreater(gco.m_next_query_time, time.time())
@@ -135,7 +182,7 @@ class TestMetadataExceptions(unittest.TestCase):
         cfg.proxy_cd = 300
         cfg.proxy_cd = 300
         gco = SentinelGCO(cfg=cfg, redis_conf={})
         gco = SentinelGCO(cfg=cfg, redis_conf={})
 
 
-        # 场景 1: spawn 时 429 -> 账号被限,锁账号
+        # Scenario 1: 429 during spawn -> account throttled, lock account
         plg_cfg = PluginConfig()
         plg_cfg = PluginConfig()
         plg_cfg.account.id = 999
         plg_cfg.account.id = 999
         plg_cfg.account.username = "sentinel_user"
         plg_cfg.account.username = "sentinel_user"
@@ -143,7 +190,7 @@ class TestMetadataExceptions(unittest.TestCase):
         mock_cloud.lock_account.assert_called_once_with(999, 1800)
         mock_cloud.lock_account.assert_called_once_with(999, 1800)
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
 
 
-        # 场景 2: query 时 429 -> IP 被限,不锁账号,移除 task 换代理
+        # Scenario 2: 429 during query -> IP throttled, do not lock account, remove task to rotate proxy
         mock_cloud.reset_mock()
         mock_cloud.reset_mock()
         mock_inst = MagicMock()
         mock_inst = MagicMock()
         mock_inst.config = plg_cfg
         mock_inst.config = plg_cfg
@@ -155,11 +202,11 @@ class TestMetadataExceptions(unittest.TestCase):
         self.assertNotIn(task, gco.m_tasks)
         self.assertNotIn(task, gco.m_tasks)
         mock_inst.cleanup.assert_called_once()
         mock_inst.cleanup.assert_called_once()
 
 
-        # 场景 3: spawn 触发 SessionExpiredOrInvalidError
+        # Scenario 3: spawn triggers SessionExpiredOrInvalidError
         gco._dispatch_error_policy("spawn", SessionExpiredOrInvalidError(), plg_cfg=plg_cfg)
         gco._dispatch_error_policy("spawn", SessionExpiredOrInvalidError(), plg_cfg=plg_cfg)
         self.assertGreater(gco.m_spawn_cooldown_until, 0)
         self.assertGreater(gco.m_spawn_cooldown_until, 0)
 
 
-        # 场景 4: 模拟 PermissionDeniedError
+        # Scenario 4: query triggers PermissionDeniedError
         mock_inst2 = MagicMock()
         mock_inst2 = MagicMock()
         mock_inst2.config = plg_cfg
         mock_inst2.config = plg_cfg
         task2 = Task(instance=mock_inst2)
         task2 = Task(instance=mock_inst2)
@@ -167,20 +214,34 @@ class TestMetadataExceptions(unittest.TestCase):
         gco._dispatch_error_policy("query", PermissionDeniedError(), task=task2)
         gco._dispatch_error_policy("query", PermissionDeniedError(), task=task2)
         self.assertNotIn(task2, gco.m_tasks)
         self.assertNotIn(task2, gco.m_tasks)
 
 
-        # 场景 5: spawn 触发 PermissionDeniedError (如 WAF 拦截或 Status: 0 / Failed to fetch) -> 立即释放账号(lock=0),并按 proxy_cd 冷却
+        # Scenario 5: spawn triggers PermissionDeniedError -> safely release account (lock=0) and cool down spawn
         mock_cloud.reset_mock()
         mock_cloud.reset_mock()
         gco._dispatch_error_policy("spawn", PermissionDeniedError("Network Error (Fetch Failed / WAF Blocked)"), plg_cfg=plg_cfg)
         gco._dispatch_error_policy("spawn", PermissionDeniedError("Network Error (Fetch Failed / WAF Blocked)"), plg_cfg=plg_cfg)
         mock_cloud.lock_account.assert_called_once_with(999, 0)
         mock_cloud.lock_account.assert_called_once_with(999, 0)
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
 
 
-        # 场景 6: spawn 触发原始字符串包含 Failed to fetch -> 自动规整并安全释放账号
+        # Scenario 6: spawn triggers error with status_code=0 -> normalizes to PermissionDeniedError and safely releases account
         mock_cloud.reset_mock()
         mock_cloud.reset_mock()
-        gco._dispatch_error_policy("spawn", Exception("TypeError: Failed to fetch"), plg_cfg=plg_cfg)
+        class MockWafFetchError(Exception):
+            status_code = 0
+        gco._dispatch_error_policy("spawn", MockWafFetchError(), plg_cfg=plg_cfg)
         mock_cloud.lock_account.assert_called_once_with(999, 0)
         mock_cloud.lock_account.assert_called_once_with(999, 0)
 
 
+        # Scenario 7: spawn triggers AccountBannedError -> disable in cloud, no WeChat alert, never release back with lock=0
+        mock_cloud.reset_mock()
+        gco._dispatch_error_policy("spawn", AccountBannedError("User banned"), plg_cfg=plg_cfg)
+        mock_cloud._perform_request.assert_called_once()
+        put_call_args = mock_cloud._perform_request.call_args
+        self.assertEqual(put_call_args[0][0], "PUT")
+        self.assertIn("/api/account/update", put_call_args[0][1])
+        self.assertEqual(put_call_args[1]["json_data"]["status"], "disable")
+        mock_cloud.push_weixin_text.assert_not_called()
+        # Verify lock_account(..., 0) was NOT called
+        mock_cloud.lock_account.assert_not_called()
+
     @patch("toolkit.cloud_api.CloudApi.Instance")
     @patch("toolkit.cloud_api.CloudApi.Instance")
     def test_booker_error_dispatch(self, mock_cloud_instance):
     def test_booker_error_dispatch(self, mock_cloud_instance):
-        from booker import BuiltinBookerGCO
+        from booker import BuiltinBookerGCO, OrderBookerGCO
         from core_types import GroupConfig, Task
         from core_types import GroupConfig, Task
 
 
         mock_cloud = MagicMock()
         mock_cloud = MagicMock()
@@ -196,7 +257,7 @@ class TestMetadataExceptions(unittest.TestCase):
         task = Task(instance=mock_inst)
         task = Task(instance=mock_inst)
         gco.m_tasks.append(task)
         gco.m_tasks.append(task)
 
 
-        # 场景 1: 模拟 booking 触发 RateLimiteddError -> 接口/IP频控,不锁账号,移除 task
+        # Scenario 1: booking triggers RateLimiteddError -> slot throttled, preserve account, remove task
         err = RateLimiteddError()
         err = RateLimiteddError()
         gco._dispatch_error_policy("book", err, task=task)
         gco._dispatch_error_policy("book", err, task=task)
 
 
@@ -204,7 +265,7 @@ class TestMetadataExceptions(unittest.TestCase):
         self.assertNotIn(task, gco.m_tasks)
         self.assertNotIn(task, gco.m_tasks)
         mock_inst.cleanup.assert_called_once()
         mock_inst.cleanup.assert_called_once()
 
 
-        # 场景 2: 模拟 spawn 触发 RateLimiteddError -> 账号受限,锁账号
+        # Scenario 2: spawn triggers RateLimiteddError -> account throttled, lock account
         mock_cloud.reset_mock()
         mock_cloud.reset_mock()
         plg_cfg = PluginConfig()
         plg_cfg = PluginConfig()
         plg_cfg.account.id = 777
         plg_cfg.account.id = 777
@@ -213,12 +274,44 @@ class TestMetadataExceptions(unittest.TestCase):
         mock_cloud.lock_account.assert_called_once_with(777, 900)
         mock_cloud.lock_account.assert_called_once_with(777, 900)
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
 
 
-        # 场景 3: 模拟 spawn 触发 PermissionDeniedError (WAF / Status: 0) -> 立即归还账号(lock=0)
+        # Scenario 3: spawn triggers PermissionDeniedError -> safely release account (lock=0)
         mock_cloud.reset_mock()
         mock_cloud.reset_mock()
         gco._dispatch_error_policy("spawn", PermissionDeniedError("WAF Blocked"), plg_cfg=plg_cfg)
         gco._dispatch_error_policy("spawn", PermissionDeniedError("WAF Blocked"), plg_cfg=plg_cfg)
         mock_cloud.lock_account.assert_called_once_with(777, 0)
         mock_cloud.lock_account.assert_called_once_with(777, 0)
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
         self.assertGreater(gco.m_spawn_cooldown_until, time.time())
 
 
+        # Scenario 4: Built-in Booker hits AccountAuthError -> permanently disable in cloud, no WeChat alert, never release with lock=0
+        mock_cloud.reset_mock()
+        gco._dispatch_error_policy("spawn", AccountAuthError("Invalid credentials"), plg_cfg=plg_cfg)
+        mock_cloud._perform_request.assert_called_once()
+        put_call_args = mock_cloud._perform_request.call_args
+        self.assertEqual(put_call_args[0][0], "PUT")
+        self.assertEqual(put_call_args[1]["json_data"]["status"], "disable")
+        mock_cloud.push_weixin_text.assert_not_called()
+        mock_cloud.lock_account.assert_not_called()
+
+        # Scenario 5: Order Booker hits AccountIncompleteError -> mark VAS task failed, remove from tracker, no WeChat alert
+        mock_cloud.reset_mock()
+        order_gco = OrderBookerGCO(cfg=cfg, redis_conf={})
+        order_gco.redis_client = MagicMock()
+        order_plg_cfg = PluginConfig()
+        order_plg_cfg.account.username = "order_user"
+        order_plg_cfg.account.id = 0  # Order-provided account, not pool account
+        order_task_id = 88888
+        
+        order_gco._dispatch_error_policy(
+            "spawn", 
+            AccountIncompleteError("No applicant added"), 
+            plg_cfg=order_plg_cfg, 
+            task_id=order_task_id
+        )
+        mock_cloud.update_vas_task.assert_called_once_with("88888", {
+            "status": "failed",
+            "fail_reason": "Account fatal error: No applicant added (code=42201)"
+        })
+        order_gco.redis_client.zrem.assert_called_once_with(order_gco.m_tracker_key, order_task_id)
+        mock_cloud.push_weixin_text.assert_not_called()
+
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     unittest.main()
     unittest.main()

+ 17 - 17
test/test_proxy_manager.py

@@ -18,11 +18,11 @@ from toolkit.cloud_api import CloudApi
 class TestProxyManager(unittest.TestCase):
 class TestProxyManager(unittest.TestCase):
     def setUp(self):
     def setUp(self):
         self.pm = ProxyManager.Instance()
         self.pm = ProxyManager.Instance()
-        # 清理可能存在的隔离状态
+        # Clear potential quarantine state
         self.pm._quarantine.clear()
         self.pm._quarantine.clear()
         self.pm._sliding_history.clear()
         self.pm._sliding_history.clear()
         self.pm._reputation_cache.clear()
         self.pm._reputation_cache.clear()
-        # Mock 掉耗时的真实外部探测与云端 HTTP 调用
+        # Mock out time-consuming external probe and cloud HTTP calls
         self.patcher_probe = patch.object(self.pm, "_async_probe_egress_ip", return_value=None)
         self.patcher_probe = patch.object(self.pm, "_async_probe_egress_ip", return_value=None)
         self.patcher_probe.start()
         self.patcher_probe.start()
         self.patcher_rep = patch.object(CloudApi.Instance(), "get_proxy_reputation_map", return_value={})
         self.patcher_rep = patch.object(CloudApi.Instance(), "get_proxy_reputation_map", return_value={})
@@ -36,7 +36,7 @@ class TestProxyManager(unittest.TestCase):
         self.patcher_report.stop()
         self.patcher_report.stop()
 
 
     def test_local_proxy_single(self):
     def test_local_proxy_single(self):
-        # 测试 local 池 (单端口)
+        # Test local pool (single port)
         res = self.pm.get_next_proxy(["local:local"])
         res = self.pm.get_next_proxy(["local:local"])
         self.assertIsInstance(res, dict)
         self.assertIsInstance(res, dict)
         self.assertEqual(res["ip"], "127.0.0.1")
         self.assertEqual(res["ip"], "127.0.0.1")
@@ -45,7 +45,7 @@ class TestProxyManager(unittest.TestCase):
         self.assertEqual(proxy_obj.port, 7897)
         self.assertEqual(proxy_obj.port, 7897)
 
 
     def test_local_proxy_multi_pool(self):
     def test_local_proxy_multi_pool(self):
-        # 测试 local_multi_pool
+        # Test local_multi_pool
         res = self.pm.get_next_proxy(["local:local_multi_pool"])
         res = self.pm.get_next_proxy(["local:local_multi_pool"])
         self.assertIsInstance(res, dict)
         self.assertIsInstance(res, dict)
         self.assertEqual(res["ip"], "127.0.0.1")
         self.assertEqual(res["ip"], "127.0.0.1")
@@ -54,25 +54,25 @@ class TestProxyManager(unittest.TestCase):
         self.assertTrue(proxy_obj.port >= 10000)
         self.assertTrue(proxy_obj.port >= 10000)
 
 
     def test_invalid_prefix(self):
     def test_invalid_prefix(self):
-        # 测试未带前缀的非法格式,必须抛出 BizLogicError
+        # Test invalid prefix format without local: or cloud:, must raise BizLogicError
         with self.assertRaises(BizLogicError) as ctx:
         with self.assertRaises(BizLogicError) as ctx:
             self.pm.get_next_proxy(["proxy-cheap"])
             self.pm.get_next_proxy(["proxy-cheap"])
         self.assertIn("Must start with 'local:' or 'cloud:'", str(ctx.exception))
         self.assertIn("Must start with 'local:' or 'cloud:'", str(ctx.exception))
 
 
     def test_nonexistent_local_pool(self):
     def test_nonexistent_local_pool(self):
-        # 测试不存在的本地池
+        # Test non-existent local pool
         with self.assertRaises(BizLogicError) as ctx:
         with self.assertRaises(BizLogicError) as ctx:
             self.pm.get_next_proxy(["local:non_existent_pool_12345"])
             self.pm.get_next_proxy(["local:non_existent_pool_12345"])
         self.assertIn("No proxies found in local pools", str(ctx.exception))
         self.assertIn("No proxies found in local pools", str(ctx.exception))
 
 
     def test_reputation_quarantine_and_revival(self):
     def test_reputation_quarantine_and_revival(self):
-        """测试专属 WAF 阻断进入隔离名单,以及成功后自愈复活"""
+        """Tests WAF block enters quarantine list, and revives on success."""
         plugin = "vfs_plugin"
         plugin = "vfs_plugin"
         proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
         proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
         port = proxy["port"]
         port = proxy["port"]
         egress_ip = proxy["egress_ip"]
         egress_ip = proxy["egress_ip"]
 
 
-        # 模拟一次 403202 cf-mitigated 专属阻断
+        # Simulate a 403202 cf-mitigated block
         self.pm.mark_proxy_result(
         self.pm.mark_proxy_result(
             proxy=proxy,
             proxy=proxy,
             plugin_name=plugin,
             plugin_name=plugin,
@@ -82,10 +82,10 @@ class TestProxyManager(unittest.TestCase):
             error_type="cf-mitigated (403202)"
             error_type="cf-mitigated (403202)"
         )
         )
 
 
-        # 验证该 IP 已进入隔离名单
+        # Verify that IP entered quarantine
         self.assertIn(egress_ip, self.pm._quarantine.get(plugin, {}))
         self.assertIn(egress_ip, self.pm._quarantine.get(plugin, {}))
 
 
-        # 模拟下一次该 IP 执行成功,验证自愈复活
+        # Simulate subsequent success on the IP, verifying half-open revival
         self.pm.mark_proxy_result(
         self.pm.mark_proxy_result(
             proxy=proxy,
             proxy=proxy,
             plugin_name=plugin,
             plugin_name=plugin,
@@ -96,9 +96,9 @@ class TestProxyManager(unittest.TestCase):
         self.assertNotIn(egress_ip, self.pm._quarantine.get(plugin, {}))
         self.assertNotIn(egress_ip, self.pm._quarantine.get(plugin, {}))
 
 
     def test_site_outage_freeze(self):
     def test_site_outage_freeze(self):
-        """测试 Layer 1: 全站故障时冻结扣分与隔离"""
+        """Tests Layer 1: Site-wide outage freezes penalty and quarantine."""
         plugin = "vfs_plugin"
         plugin = "vfs_plugin"
-        # 构造跨多个不同 IP 的连续系统级故障 (502 / 503)
+        # Construct continuous server errors (502/503) across multiple distinct IPs
         for i in range(6):
         for i in range(6):
             fake_proxy = {"port": 16000 + i, "egress_ip": f"104.28.1.{i}", "name": f"node_{i}"}
             fake_proxy = {"port": 16000 + i, "egress_ip": f"104.28.1.{i}", "name": f"node_{i}"}
             self.pm.mark_proxy_result(
             self.pm.mark_proxy_result(
@@ -110,10 +110,10 @@ class TestProxyManager(unittest.TestCase):
                 error_type="Bad Gateway"
                 error_type="Bad Gateway"
             )
             )
 
 
-        # 此时全站故障已触发
+        # Site-wide outage triggered
         self.assertTrue(self.pm._is_site_outage(plugin))
         self.assertTrue(self.pm._is_site_outage(plugin))
 
 
-        # 在全站故障状态下,即使有节点发生 WAF 阻断,也不会被拉黑隔离
+        # Under site outage, nodes with WAF blocks should not be quarantined
         new_proxy = {"port": 16099, "egress_ip": "104.28.99.99", "name": "node_99"}
         new_proxy = {"port": 16099, "egress_ip": "104.28.99.99", "name": "node_99"}
         self.pm.mark_proxy_result(
         self.pm.mark_proxy_result(
             proxy=new_proxy,
             proxy=new_proxy,
@@ -126,14 +126,14 @@ class TestProxyManager(unittest.TestCase):
         self.assertNotIn("104.28.99.99", self.pm._quarantine.get(plugin, {}))
         self.assertNotIn("104.28.99.99", self.pm._quarantine.get(plugin, {}))
 
 
     def test_minimum_viable_pool_anti_starvation(self):
     def test_minimum_viable_pool_anti_starvation(self):
-        """测试 Layer 3: 最低可用保底池防雪崩,过度拉黑时强制重置隔离名单"""
+        """Tests Layer 3: Anti-avalanche floor guarantee resets quarantine when over-filtered."""
         plugin = "test_plugin"
         plugin = "test_plugin"
-        # 人为把隔离名单填满
+        # Artificially fill quarantine list
         self.pm._quarantine[plugin] = {
         self.pm._quarantine[plugin] = {
             f"port_{16000 + i}": time.time() + 1800 for i in range(1000)
             f"port_{16000 + i}": time.time() + 1800 for i in range(1000)
         }
         }
 
 
-        # 获取下一个代理,不应该抛出异常,应该触发防雪崩重置并成功返回代理
+        # Should not raise exception; triggers anti-avalanche reset and returns proxy
         proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
         proxy = self.pm.get_next_proxy(["local:local_multi_pool"], plugin_name=plugin)
         self.assertIsInstance(proxy, dict)
         self.assertIsInstance(proxy, dict)
         self.assertTrue(proxy["port"] >= 10000)
         self.assertTrue(proxy["port"] >= 10000)

+ 10 - 10
toolkit/backoff.py

@@ -2,14 +2,14 @@ import random
 
 
 class ExponentialBackoff:
 class ExponentialBackoff:
     """
     """
-    通用指数退避计算工具
+    General exponential backoff calculation utility.
     """
     """
     def __init__(self, base_delay: float, max_delay: float, factor: float = 2.0, jitter_range: tuple = (10.0, 45.0)):
     def __init__(self, base_delay: float, max_delay: float, factor: float = 2.0, jitter_range: tuple = (10.0, 45.0)):
         """
         """
-        :param base_delay: 基础退避时间(秒)
-        :param max_delay: 最大退避时间(秒)
-        :param factor: 指数乘数 (默认 2.0 即翻倍)
-        :param jitter_range: 随机抖动范围(最小秒数,最大秒数)
+        :param base_delay: Base delay in seconds
+        :param max_delay: Maximum delay in seconds
+        :param factor: Exponential multiplier (default 2.0 for doubling)
+        :param jitter_range: Random jitter range (min seconds, max seconds)
         """
         """
         self.base_delay = base_delay
         self.base_delay = base_delay
         self.max_delay = max_delay
         self.max_delay = max_delay
@@ -18,20 +18,20 @@ class ExponentialBackoff:
 
 
     def calculate(self, failure_count: int) -> float:
     def calculate(self, failure_count: int) -> float:
         """
         """
-        根据连续失败次数计算下一次的冷却时间
-        :param failure_count: 连续失败次数 (1开始)
+        Calculates cooldown delay based on consecutive failure count.
+        :param failure_count: Consecutive failure count (1-based)
         """
         """
         if failure_count <= 0:
         if failure_count <= 0:
             return 0.0
             return 0.0
             
             
-        # 核心公式: 基础延迟 * (乘数 ^ (失败次数 - 1))
+        # Core formula: base_delay * (factor ^ (failure_count - 1))
         multiplier = self.factor ** (failure_count - 1)
         multiplier = self.factor ** (failure_count - 1)
         delay = self.base_delay * multiplier
         delay = self.base_delay * multiplier
         
         
-        # 限制上限
+        # Clamp to max_delay
         delay = min(delay, self.max_delay)
         delay = min(delay, self.max_delay)
         
         
-        # 增加随机抖动
+        # Add random jitter
         if self.jitter_range:
         if self.jitter_range:
             delay += random.uniform(self.jitter_range[0], self.jitter_range[1])
             delay += random.uniform(self.jitter_range[0], self.jitter_range[1])
             
             

+ 25 - 25
toolkit/captcha_breaker.py

@@ -8,7 +8,7 @@ from openai import OpenAI
 from configure import CAPTCHA_LLM_CONFIG
 from configure import CAPTCHA_LLM_CONFIG
 
 
 class CaptchaBreakerError(Exception):
 class CaptchaBreakerError(Exception):
-    """验证码识别异常基类"""
+    """Base exception for captcha breaking."""
     pass
     pass
 
 
 def normalize_image_to_data_url(
 def normalize_image_to_data_url(
@@ -16,8 +16,8 @@ def normalize_image_to_data_url(
     default_mime_type: str = "image/png"
     default_mime_type: str = "image/png"
 ) -> str:
 ) -> str:
     """
     """
-    将多种图片输入形式(文件路径、字节数据、BytesIO、Base64字符串、Data URL)
-    标准化为可供多模态模型接收的 Data URL (data:<mime-type>;base64,<data>)
+    Normalizes multiple image input types (file path, raw bytes, BytesIO, Base64 string, Data URL)
+    into standard Data URL format (data:<mime-type>;base64,<data>) acceptable by multimodal models.
     """
     """
     if isinstance(image_input, (bytes, bytearray)):
     if isinstance(image_input, (bytes, bytearray)):
         b64_str = base64.b64encode(image_input).decode("utf-8")
         b64_str = base64.b64encode(image_input).decode("utf-8")
@@ -28,11 +28,11 @@ def normalize_image_to_data_url(
         return f"data:{default_mime_type};base64,{b64_str}"
         return f"data:{default_mime_type};base64,{b64_str}"
 
 
     if isinstance(image_input, str):
     if isinstance(image_input, str):
-        # 已经是标准 Data URL
+        # Already a standard Data URL
         if image_input.startswith("data:image/"):
         if image_input.startswith("data:image/"):
             return image_input
             return image_input
 
 
-        # 如果是本地存在的文件路径
+        # Local file path
         if os.path.isfile(image_input):
         if os.path.isfile(image_input):
             mime_type, _ = mimetypes.guess_type(image_input)
             mime_type, _ = mimetypes.guess_type(image_input)
             mime_type = mime_type or default_mime_type
             mime_type = mime_type or default_mime_type
@@ -40,7 +40,7 @@ def normalize_image_to_data_url(
                 b64_str = base64.b64encode(f.read()).decode("utf-8")
                 b64_str = base64.b64encode(f.read()).decode("utf-8")
             return f"data:{mime_type};base64,{b64_str}"
             return f"data:{mime_type};base64,{b64_str}"
 
 
-        # 尝试作为纯 Base64 字符串处理
+        # Attempt to process as pure Base64 string
         clean_b64 = image_input.strip()
         clean_b64 = image_input.strip()
         return f"data:{default_mime_type};base64,{clean_b64}"
         return f"data:{default_mime_type};base64,{clean_b64}"
 
 
@@ -49,10 +49,10 @@ def normalize_image_to_data_url(
 
 
 class CaptchaBreaker:
 class CaptchaBreaker:
     """
     """
-    通用大模型验证码识别器
-    支持基于 OpenAI 兼容协议的多模态大模型端点(如 Qwen-VL, GPT-4o, DeepSeek-VL, OneAPI 等)
+    General LLM Captcha Breaker
+    Supports multimodal LLM endpoints based on OpenAI compatible protocol (e.g. Qwen-VL, GPT-4o, DeepSeek-VL, OneAPI, etc.)
     """
     """
-    DEFAULT_PROMPT = "你是一个精确的OCR机器人。请识别图片中的验证码字符。只输出验证码本身的内容,不要任何多余的汉字或标点符号。"
+    DEFAULT_PROMPT = "You are a precise OCR agent. Please recognize the captcha characters in the image. Output only the captcha text itself, without any explanations or extra characters."
 
 
     def __init__(
     def __init__(
         self,
         self,
@@ -62,10 +62,10 @@ class CaptchaBreaker:
         timeout: Optional[float] = None,
         timeout: Optional[float] = None,
         client: Optional[OpenAI] = None
         client: Optional[OpenAI] = None
     ):
     ):
-        # 配置读取逻辑:
-        # 1. 优先使用构造函数传入的参数
-        # 2. 如果 CAPTCHA_LLM_CONFIG 是字典,从中读取
-        # 3. 如果 CAPTCHA_LLM_CONFIG 为 None 或未提供,从环境变量读取
+        # Config resolution logic:
+        # 1. Prefer explicit constructor parameters
+        # 2. If CAPTCHA_LLM_CONFIG is a dict, read from it
+        # 3. If CAPTCHA_LLM_CONFIG is None or not provided, read from environment variables
         cfg = CAPTCHA_LLM_CONFIG if isinstance(CAPTCHA_LLM_CONFIG, dict) else {}
         cfg = CAPTCHA_LLM_CONFIG if isinstance(CAPTCHA_LLM_CONFIG, dict) else {}
 
 
         self.api_key = api_key or cfg.get("api_key") or os.getenv("CAPTCHA_LLM_API_KEY")
         self.api_key = api_key or cfg.get("api_key") or os.getenv("CAPTCHA_LLM_API_KEY")
@@ -87,7 +87,7 @@ class CaptchaBreaker:
 
 
     @property
     @property
     def client(self) -> OpenAI:
     def client(self) -> OpenAI:
-        """获取或延迟初始化 OpenAI 客户端"""
+        """Gets or lazily initializes OpenAI client."""
         if self._client is None:
         if self._client is None:
             if not self.api_key:
             if not self.api_key:
                 raise CaptchaBreakerError(
                 raise CaptchaBreakerError(
@@ -102,14 +102,14 @@ class CaptchaBreaker:
         return self._client
         return self._client
 
 
     def _clean_result(self, text: str) -> str:
     def _clean_result(self, text: str) -> str:
-        """清理大模型返回的验证码文本,去除 markdown 代码块标记与前后符号"""
+        """Cleans LLM response text, stripping markdown code blocks and surrounding quotes."""
         result = text.strip()
         result = text.strip()
-        # 移除 markdown 代码块包裹 (如 ``` 或 ```text ... ```)
+        # Strip markdown code block wrappers (e.g. ``` or ```text ... ```)
         if result.startswith("```"):
         if result.startswith("```"):
             lines = result.splitlines()
             lines = result.splitlines()
             if len(lines) >= 2 and lines[-1].strip() == "```":
             if len(lines) >= 2 and lines[-1].strip() == "```":
                 result = "\n".join(lines[1:-1]).strip()
                 result = "\n".join(lines[1:-1]).strip()
-        # 去除首尾常见的引号
+        # Strip surrounding quotes
         if (result.startswith('"') and result.endswith('"')) or (result.startswith("'") and result.endswith("'")):
         if (result.startswith('"') and result.endswith('"')) or (result.startswith("'") and result.endswith("'")):
             result = result[1:-1].strip()
             result = result[1:-1].strip()
         return result
         return result
@@ -122,13 +122,13 @@ class CaptchaBreaker:
         **kwargs: Any
         **kwargs: Any
     ) -> str:
     ) -> str:
         """
         """
-        识别验证码
-        :param image: 图片输入,支持文件路径、二进制字节、BytesIO 或 Base64 / Data URL 字符串
-        :param prompt: 提示词,默认使用通用字符 OCR 提示词
-        :param temperature: 采样温度,默认为 0.0 以保证确定性
-        :param kwargs: 透传给 chat.completions.create 的额外参数
-        :return: 识别出的验证码文本
-        :raises CaptchaBreakerError: 调用失败或无法解析时抛出
+        Recognizes captcha from image.
+        :param image: Image input (path, raw bytes, BytesIO, or Base64 / Data URL string)
+        :param prompt: Prompt text, defaults to general OCR prompt
+        :param temperature: Sampling temperature, default 0.0 for determinism
+        :param kwargs: Extra parameters forwarded to chat.completions.create
+        :return: Recognized captcha text
+        :raises CaptchaBreakerError: Raised when call fails or cannot be parsed
         """
         """
         data_url = normalize_image_to_data_url(image)
         data_url = normalize_image_to_data_url(image)
         used_prompt = prompt or self.DEFAULT_PROMPT
         used_prompt = prompt or self.DEFAULT_PROMPT
@@ -166,7 +166,7 @@ class CaptchaBreaker:
         prompt: Optional[str] = None,
         prompt: Optional[str] = None,
         **kwargs: Any
         **kwargs: Any
     ) -> str:
     ) -> str:
-        """支持将实例作为函数直接调用"""
+        """Enables calling instance directly as a function."""
         return self.break_captcha(image, prompt=prompt, **kwargs)
         return self.break_captcha(image, prompt=prompt, **kwargs)
 
 
 
 

+ 2 - 3
toolkit/mihomo_tunnel.py

@@ -111,9 +111,8 @@ class MihomoTunnel:
 
 
     def cut_all_connections(self):
     def cut_all_connections(self):
         """
         """
-        [新增方法]
-        通过 Mihomo API 强制切断当前代理池的所有活跃连接。
-        常用于检测到 IP 被封锁或切换代理线路时,立即打断正在卡死/挂起的旧请求。
+        Forces termination of all active connections in the proxy pool via Mihomo API.
+        Commonly used when an IP block is detected or switching proxy routes to immediately interrupt hung requests.
         """
         """
         if not self.process or self.process.poll() is not None:
         if not self.process or self.process.poll() is not None:
             return False
             return False

+ 4 - 4
toolkit/notifier.py

@@ -10,8 +10,8 @@ def notify_date_changes(
     logger: Optional[Callable[[str], None]] = None
     logger: Optional[Callable[[str], None]] = None
 ) -> bool:
 ) -> bool:
     """
     """
-    档期变化微信通知。
-    若提供了 cache 字典(如 {routing_key: earliest_date}),仅在最早档期发生变化时推送并更新 cache。
+    Slot availability change WeChat notification.
+    If a cache dict is provided (e.g. {routing_key: earliest_date}), only pushes and updates cache when earliest date changes.
     """
     """
     current_earliest_date = query_result.earliest_date
     current_earliest_date = query_result.earliest_date
     apt_type = query_result.apt_type
     apt_type = query_result.apt_type
@@ -49,8 +49,8 @@ def notify_book_result(
     logger: Optional[Callable[[str], None]] = None
     logger: Optional[Callable[[str], None]] = None
 ) -> bool:
 ) -> bool:
     """
     """
-    预定成功微信通知。
-    仅在 book_result.success 为 True 时进行推送。
+    Booking success WeChat notification.
+    Only sends push notification when book_result.success is True.
     """
     """
     if not book_result.success:
     if not book_result.success:
         return False
         return False

+ 3 - 3
toolkit/ocr_engine.py

@@ -1,6 +1,6 @@
 import os
 import os
 
 
-# 屏蔽 ONNX Runtime 警告
+# Suppress ONNX Runtime warnings
 os.environ["ORT_LOGGING_LEVEL"] = "3"
 os.environ["ORT_LOGGING_LEVEL"] = "3"
 import string
 import string
 import io
 import io
@@ -12,7 +12,7 @@ from torchvision import transforms
 from PIL import Image, ImageFilter
 from PIL import Image, ImageFilter
 from io import BytesIO
 from io import BytesIO
 
 
-# ================= PyTorch 模型结构 (保留原有逻辑) =================
+# ================= PyTorch Model Architecture =================
 class Model(nn.Module):
 class Model(nn.Module):
     def __init__(self, n_classes, input_shape=(3, 64, 128)):
     def __init__(self, n_classes, input_shape=(3, 64, 128)):
         super(Model, self).__init__()
         super(Model, self).__init__()
@@ -55,7 +55,7 @@ class Model(nn.Module):
         x = self.fc(x)
         x = self.fc(x)
         return x
         return x
 
 
-# ================= 引擎封装 =================
+# ================= Engine Wrapper =================
 class PyTorchEngine:
 class PyTorchEngine:
     def __init__(self, model_path):
     def __init__(self, model_path):
         self.num_classes = 12
         self.num_classes = 12

+ 60 - 59
toolkit/proxy_manager.py

@@ -17,13 +17,13 @@ from log_macros import VSC_INFO, VSC_WARN, VSC_ERROR, VSC_DEBUG
 
 
 class ProxyManager:
 class ProxyManager:
     """
     """
-    统一代理调度与信誉管理中心。
-    支持:
-      - 显式前缀区分:"local:<pool_name>" / "cloud:<pool_name>"
-      - 出口 IP 探针与缓存机制 (Egress Resolver & Cache)
-      - 本地通道与云端信誉库求交加权调度 (85% 优选 + 15% 探索)
-      - 五层防雪崩护栏 (全站故障冻结、20% 最低保底池、半开自愈、底层硬兜底)
-      - 异步指标埋点与上报 (Fail-Silent)
+    Unified proxy scheduling and reputation management hub.
+    Supports:
+      - Explicit prefix routing: "local:<pool_name>" / "cloud:<pool_name>"
+      - Egress IP resolver and cache
+      - Local channel and cloud reputation intersection weighted scheduling (85% preferred + 15% exploration)
+      - Five-layer avalanche guardrails (site-wide outage freezing, 20% minimum pool guarantee, half-open revival, hard fallback)
+      - Asynchronous metric tracking and upstream reporting (fail-silent)
     """
     """
     _instance = None
     _instance = None
 
 
@@ -43,19 +43,19 @@ class ProxyManager:
 
 
         self._lock = threading.RLock()
         self._lock = threading.RLock()
 
 
-        # 端口 -> 公网出口 IP 缓存与节点名称缓存
+        # Port -> public egress IP cache and node name cache
         self._port_to_egress: Dict[int, str] = {}
         self._port_to_egress: Dict[int, str] = {}
         self._port_to_name: Dict[int, str] = {}
         self._port_to_name: Dict[int, str] = {}
         self._probing_ports = set()
         self._probing_ports = set()
 
 
-        # 插件维度本地临时隔离黑名单: { plugin_name: { egress_ip: expire_ts } }
+        # Per-plugin local temporary quarantine blacklist: { plugin_name: { egress_ip: expire_ts } }
         self._quarantine: Dict[str, Dict[str, float]] = {}
         self._quarantine: Dict[str, Dict[str, float]] = {}
 
 
-        # 插件维度云端信誉缓存: { plugin_name: { "last_fetch": float, "map": { egress_ip: {...} } } }
+        # Per-plugin cloud reputation cache: { plugin_name: { "last_fetch": float, "map": { egress_ip: {...} } } }
         self._reputation_cache: Dict[str, Dict[str, Any]] = {}
         self._reputation_cache: Dict[str, Dict[str, Any]] = {}
         self._fetching_reputation = set()
         self._fetching_reputation = set()
 
 
-        # 插件维度滑动调用历史 (用于全站故障判定): { plugin_name: collections.deque(maxlen=30) }
+        # Per-plugin sliding call history (for site-wide outage determination): { plugin_name: collections.deque(maxlen=30) }
         self._sliding_history: Dict[str, collections.deque] = {}
         self._sliding_history: Dict[str, collections.deque] = {}
 
 
     def _load_local_proxies(self) -> Dict[str, List[Dict[str, Any]]]:
     def _load_local_proxies(self) -> Dict[str, List[Dict[str, Any]]]:
@@ -68,7 +68,7 @@ class ProxyManager:
             raise BizLogicError(message=f"Failed to parse {self.local_proxies_file}: {e}")
             raise BizLogicError(message=f"Failed to parse {self.local_proxies_file}: {e}")
 
 
     # ==========================================
     # ==========================================
-    # 出口 IP 探针与缓存 (Egress Resolver)
+    # Egress IP probe and cache (Egress Resolver)
     # ==========================================
     # ==========================================
 
 
     def get_cached_egress_ip(self, port: int) -> Optional[str]:
     def get_cached_egress_ip(self, port: int) -> Optional[str]:
@@ -76,14 +76,14 @@ class ProxyManager:
             return self._port_to_egress.get(port)
             return self._port_to_egress.get(port)
 
 
     def invalidate_egress_cache(self, port: int):
     def invalidate_egress_cache(self, port: int):
-        """当节点疑似漂移时清除缓存"""
+        """Clears cache when node egress is suspected to have drifted."""
         with self._lock:
         with self._lock:
             if port in self._port_to_egress:
             if port in self._port_to_egress:
                 old_ip = self._port_to_egress.pop(port, None)
                 old_ip = self._port_to_egress.pop(port, None)
                 VSC_DEBUG("vs_proxy", f"[invalidate_egress_cache] Invalidated port {port} (old egress: {old_ip})")
                 VSC_DEBUG("vs_proxy", f"[invalidate_egress_cache] Invalidated port {port} (old egress: {old_ip})")
 
 
     def _async_probe_egress_ip(self, port: int, proto: str = "http"):
     def _async_probe_egress_ip(self, port: int, proto: str = "http"):
-        """后台异步探测端口的真实公网出口 IP,不阻塞主调度"""
+        """Asynchronously probes the true public egress IP of the port in background, non-blocking."""
         with self._lock:
         with self._lock:
             if port in self._port_to_egress or port in self._probing_ports:
             if port in self._port_to_egress or port in self._probing_ports:
                 return
                 return
@@ -93,7 +93,7 @@ class ProxyManager:
             try:
             try:
                 proxy_url = f"{proto}://127.0.0.1:{port}"
                 proxy_url = f"{proto}://127.0.0.1:{port}"
                 proxies = {"http": proxy_url, "https": proxy_url}
                 proxies = {"http": proxy_url, "https": proxy_url}
-                # 尝试轻量公网 IP 端点
+                # Try lightweight public IP endpoint
                 resp = requests.get("http://api.ipify.org", proxies=proxies, timeout=2.5)
                 resp = requests.get("http://api.ipify.org", proxies=proxies, timeout=2.5)
                 if resp.status_code == 200 and resp.text.strip():
                 if resp.status_code == 200 and resp.text.strip():
                     ip = resp.text.strip()
                     ip = resp.text.strip()
@@ -110,7 +110,7 @@ class ProxyManager:
         t.start()
         t.start()
 
 
     def _resolve_ip_identifier(self, node: Dict[str, Any], trigger_probe: bool = False) -> str:
     def _resolve_ip_identifier(self, node: Dict[str, Any], trigger_probe: bool = False) -> str:
-        """获取节点的 IP 标识符(优先真实出口 IP,未解析则使用端口锚点)"""
+        """Gets the IP identifier of the node (prefers true egress IP; falls back to port anchor if unparsed)."""
         port = int(node.get("port", 0))
         port = int(node.get("port", 0))
         configured_egress = node.get("egress_ip")
         configured_egress = node.get("egress_ip")
         if configured_egress:
         if configured_egress:
@@ -128,11 +128,11 @@ class ProxyManager:
         return f"port_{port}"
         return f"port_{port}"
 
 
     # ==========================================
     # ==========================================
-    # 云端信誉同步与防雪崩护栏
+    # Cloud reputation sync and avalanche guardrails
     # ==========================================
     # ==========================================
 
 
     def _get_reputation_map(self, plugin_name: str) -> Dict[str, Dict[str, Any]]:
     def _get_reputation_map(self, plugin_name: str) -> Dict[str, Dict[str, Any]]:
-        """获取云端信誉字典 (绝不同步阻塞主流程,后台异步刷新)"""
+        """Gets cloud reputation mapping (asynchronously refreshed in background without blocking)."""
         now = time.time()
         now = time.time()
         with self._lock:
         with self._lock:
             cache_entry = self._reputation_cache.get(plugin_name)
             cache_entry = self._reputation_cache.get(plugin_name)
@@ -163,8 +163,9 @@ class ProxyManager:
 
 
     def _is_site_outage(self, plugin_name: str) -> bool:
     def _is_site_outage(self, plugin_name: str) -> bool:
         """
         """
-        Layer 1 防护:全站故障判决
-        过去 180s 内,跨至少 2 个不同 IP 且样本 >= 5,若失败率 >= 90% 或均报 502/503/520~526,判定为全站故障
+        Layer 1 protection: Site-wide outage determination
+        Within the past 180s, across >= 2 distinct IPs with sample size >= 5:
+        if failure rate >= 90% or >= 70% 502/503/520~526 errors, judge as site-wide outage.
         """
         """
         with self._lock:
         with self._lock:
             history = self._sliding_history.get(plugin_name)
             history = self._sliding_history.get(plugin_name)
@@ -183,7 +184,7 @@ class ProxyManager:
             failures = [e for e in recent_events if not e["success"]]
             failures = [e for e in recent_events if not e["success"]]
             fail_rate = len(failures) / len(recent_events)
             fail_rate = len(failures) / len(recent_events)
 
 
-            # 严重系统级错误数量
+            # Count of severe server-side errors
             server_errors = [e for e in failures if e["http_code"] in (500, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526)]
             server_errors = [e for e in failures if e["http_code"] in (500, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526)]
 
 
             if fail_rate >= 0.90 or (len(server_errors) / len(recent_events) >= 0.70):
             if fail_rate >= 0.90 or (len(server_errors) / len(recent_events) >= 0.70):
@@ -192,7 +193,7 @@ class ProxyManager:
             return False
             return False
 
 
     # ==========================================
     # ==========================================
-    # 核心调度逻辑 (求交加权 + 五层护栏)
+    # Core scheduling logic (intersection weighting + 5 guardrails)
     # ==========================================
     # ==========================================
 
 
     def get_next_proxy(
     def get_next_proxy(
@@ -202,11 +203,11 @@ class ProxyManager:
         plugin_name: Optional[str] = None
         plugin_name: Optional[str] = None
     ) -> Dict[str, Any]:
     ) -> Dict[str, Any]:
         """
         """
-        根据 pools 列表解析并获取下一个代理。
-        @param pools: 代理池列表,例如 ["local:local_multi_pool"] 或 ["cloud:proxy-cheap"]
-        @param proxy_cd: 代理冷却时间(云端使用)
-        @param plugin_name: 插件名称(如 'vfs_plugin'),用于结合信誉分和隔离策略
-        @return dict 格式标准代理信息 (包含 id, proto, ip, port, username, password, egress_ip, name)
+        Resolves and acquires the next proxy based on pools list.
+        @param pools: Proxy pool list, e.g. ["local:local_multi_pool"] or ["cloud:proxy-cheap"]
+        @param proxy_cd: Proxy cooldown time (used for cloud)
+        @param plugin_name: Plugin name (e.g. 'vfs_plugin'), used for reputation scoring and quarantine
+        @return dict Standard proxy info (contains id, proto, ip, port, username, password, egress_ip, name)
         """
         """
         if getattr(configure, "TEST_PROXY", None):
         if getattr(configure, "TEST_PROXY", None):
             return configure.TEST_PROXY
             return configure.TEST_PROXY
@@ -260,62 +261,62 @@ class ProxyManager:
                     message=f"No proxies found in local pools: {local_targets} from {self.local_proxies_file}"
                     message=f"No proxies found in local pools: {local_targets} from {self.local_proxies_file}"
                 )
                 )
 
 
-            # 记录节点名称缓存
+            # Record node name cache
             for node in candidate_proxies:
             for node in candidate_proxies:
                 port = int(node.get("port", 0))
                 port = int(node.get("port", 0))
                 if port and "name" in node:
                 if port and "name" in node:
                     self._port_to_name[port] = node["name"]
                     self._port_to_name[port] = node["name"]
 
 
-            # 如果没有指定 plugin_name,退化为经典随机轮询
+            # If no plugin_name is specified, fallback to classic random round-robin
             if not plugin_name:
             if not plugin_name:
                 chosen = random.choice(candidate_proxies)
                 chosen = random.choice(candidate_proxies)
                 return self._format_proxy_dict(chosen)
                 return self._format_proxy_dict(chosen)
 
 
             # ------------------------------------------------------------------
             # ------------------------------------------------------------------
-            # 智能信誉分级调度 (求交 + 梯队路由 + 五层护栏)
+            # Intelligent tiered scheduling (reputation + tiered routing + 5 guardrails)
             # ------------------------------------------------------------------
             # ------------------------------------------------------------------
             now = time.time()
             now = time.time()
             rep_map = self._get_reputation_map(plugin_name)
             rep_map = self._get_reputation_map(plugin_name)
 
 
             with self._lock:
             with self._lock:
                 quarantine_map = self._quarantine.setdefault(plugin_name, {})
                 quarantine_map = self._quarantine.setdefault(plugin_name, {})
-                # 清理过期隔离节点
+                # Clean up expired quarantine entries
                 expired_ips = [ip for ip, exp in quarantine_map.items() if now > exp]
                 expired_ips = [ip for ip, exp in quarantine_map.items() if now > exp]
                 for ip in expired_ips:
                 for ip in expired_ips:
                     quarantine_map.pop(ip, None)
                     quarantine_map.pop(ip, None)
 
 
-                # Layer 3 防护:最低可用保底池检查 (保底 20% 或至少 5 个可用节点)
+                # Layer 3 protection: Minimum available pool guarantee (20% or at least 5 nodes)
                 total_nodes_count = len(candidate_proxies)
                 total_nodes_count = len(candidate_proxies)
                 quarantined_count = sum(
                 quarantined_count = sum(
                     1 for node in candidate_proxies
                     1 for node in candidate_proxies
                     if self._resolve_ip_identifier(node) in quarantine_map
                     if self._resolve_ip_identifier(node) in quarantine_map
                 )
                 )
 
 
-                # 如果隔离比例超 70% 或剩余可用节点 < 20% (且小于 5),触发熔断重置
+                # If quarantine ratio > 70% or available nodes < 20% (and < 5), trigger circuit-breaker reset
                 if total_nodes_count > 0:
                 if total_nodes_count > 0:
                     available_ratio = (total_nodes_count - quarantined_count) / total_nodes_count
                     available_ratio = (total_nodes_count - quarantined_count) / total_nodes_count
                     if available_ratio < 0.20 or (total_nodes_count - quarantined_count) < min(5, total_nodes_count):
                     if available_ratio < 0.20 or (total_nodes_count - quarantined_count) < min(5, total_nodes_count):
-                        VSC_WARN("vs_proxy", f"【代理防雪崩】插件 {plugin_name} 可用节点低于保底阈值(可用率 {available_ratio:.1%}),强制清空临时隔离名单!")
+                        VSC_WARN("vs_proxy", f"[Proxy Anti-Avalanche] Plugin {plugin_name} available nodes below floor threshold (availability {available_ratio:.1%}). Clearing quarantine list!")
                         quarantine_map.clear()
                         quarantine_map.clear()
 
 
-            # 划分三梯队
+            # Divide into tiers
             trusted_tier: List[Dict[str, Any]] = []
             trusted_tier: List[Dict[str, Any]] = []
             explore_tier: List[Dict[str, Any]] = []
             explore_tier: List[Dict[str, Any]] = []
 
 
             for node in candidate_proxies:
             for node in candidate_proxies:
                 ip_id = self._resolve_ip_identifier(node)
                 ip_id = self._resolve_ip_identifier(node)
-                # 检查是否在隔离名单中
+                # Check if in quarantine
                 if ip_id in quarantine_map:
                 if ip_id in quarantine_map:
                     continue
                     continue
 
 
-                # 检查云端信誉
+                # Check cloud reputation
                 rep_info = rep_map.get(ip_id)
                 rep_info = rep_map.get(ip_id)
                 if rep_info and rep_info.get("score", 0) >= 75 and rep_info.get("state") == "trusted":
                 if rep_info and rep_info.get("score", 0) >= 75 and rep_info.get("state") == "trusted":
                     trusted_tier.append(node)
                     trusted_tier.append(node)
                 else:
                 else:
                     explore_tier.append(node)
                     explore_tier.append(node)
 
 
-            # 梯队加权调度:85% 优选,15% 探索
+            # Tier weighted scheduling: 85% preferred, 15% exploration
             chosen = None
             chosen = None
             if trusted_tier and explore_tier:
             if trusted_tier and explore_tier:
                 if random.random() < 0.85:
                 if random.random() < 0.85:
@@ -327,9 +328,9 @@ class ProxyManager:
             elif explore_tier:
             elif explore_tier:
                 chosen = random.choice(explore_tier)
                 chosen = random.choice(explore_tier)
 
 
-            # Layer 5 防护:本地代码硬保底 (如果过滤后为空,回退全池随机)
+            # Layer 5 protection: Hard fallback (if empty after filtering, fallback to full pool random)
             if not chosen:
             if not chosen:
-                VSC_WARN("vs_proxy", f"【代理硬保底】插件 {plugin_name} 经过信誉过滤后无可用节点,触发全量随机兜底!")
+                VSC_WARN("vs_proxy", f"[Proxy Hard Fallback] Plugin {plugin_name} has no available nodes after reputation filter. Triggering full random fallback!")
                 chosen = random.choice(candidate_proxies)
                 chosen = random.choice(candidate_proxies)
 
 
             return self._format_proxy_dict(chosen)
             return self._format_proxy_dict(chosen)
@@ -340,7 +341,7 @@ class ProxyManager:
         raise BizLogicError(message=f"No valid local or cloud proxy pool specified in {pools}")
         raise BizLogicError(message=f"No valid local or cloud proxy pool specified in {pools}")
 
 
     def _format_proxy_dict(self, chosen: Dict[str, Any]) -> Dict[str, Any]:
     def _format_proxy_dict(self, chosen: Dict[str, Any]) -> Dict[str, Any]:
-        """规范化代理字典"""
+        """Formats and normalizes the proxy dictionary."""
         port = int(chosen.get("port", 80))
         port = int(chosen.get("port", 80))
         egress_ip = self._resolve_ip_identifier(chosen, trigger_probe=True)
         egress_ip = self._resolve_ip_identifier(chosen, trigger_probe=True)
         return {
         return {
@@ -355,7 +356,7 @@ class ProxyManager:
         }
         }
 
 
     # ==========================================
     # ==========================================
-    # 指标埋点打桩与实时反馈 (Telemetry Upstream)
+    # Telemetry upstream and real-time feedback
     # ==========================================
     # ==========================================
 
 
     def mark_proxy_result(
     def mark_proxy_result(
@@ -369,12 +370,12 @@ class ProxyManager:
         latency_ms: int = 0
         latency_ms: int = 0
     ):
     ):
         """
         """
-        标记代理使用结果并异步上报。
-        内置:
-          - 全站故障判决 (Site Outage)
-          - 针对性阻断识别与临时隔离 (Quarantine)
-          - 半开自愈复活 (Half-Open Revival)
-          - 漂移检测 (Drift Detection)
+        Marks proxy usage outcome and reports asynchronously.
+        Includes:
+          - Site-wide outage determination
+          - Targeted block detection and temporary quarantine
+          - Half-open revival
+          - Drift detection
         """
         """
         if not proxy or not plugin_name:
         if not proxy or not plugin_name:
             return
             return
@@ -383,7 +384,7 @@ class ProxyManager:
         egress_ip = proxy.get("egress_ip") or self._resolve_ip_identifier(proxy)
         egress_ip = proxy.get("egress_ip") or self._resolve_ip_identifier(proxy)
         node_name = proxy.get("name") or self._port_to_name.get(port, "")
         node_name = proxy.get("name") or self._port_to_name.get(port, "")
 
 
-        # 1. 记入滑动调用历史
+        # 1. Record into sliding call history
         now = time.time()
         now = time.time()
         with self._lock:
         with self._lock:
             history = self._sliding_history.setdefault(plugin_name, collections.deque(maxlen=30))
             history = self._sliding_history.setdefault(plugin_name, collections.deque(maxlen=30))
@@ -395,23 +396,23 @@ class ProxyManager:
                 "error_type": error_type
                 "error_type": error_type
             })
             })
 
 
-        # 2. 判断是否处于全站故障期
+        # 2. Check if currently in site-wide outage
         is_outage = self._is_site_outage(plugin_name)
         is_outage = self._is_site_outage(plugin_name)
 
 
         with self._lock:
         with self._lock:
             quarantine_map = self._quarantine.setdefault(plugin_name, {})
             quarantine_map = self._quarantine.setdefault(plugin_name, {})
 
 
             if success:
             if success:
-                # 成功事件:若在隔离期或半开期,立刻解除隔离并复活
+                # Success event: If quarantined or half-open, immediately revive and unquarantine
                 if egress_ip in quarantine_map:
                 if egress_ip in quarantine_map:
                     quarantine_map.pop(egress_ip, None)
                     quarantine_map.pop(egress_ip, None)
-                    VSC_INFO("vs_proxy", f"【代理自愈复活】出口 IP {egress_ip} (Port {port}) 在插件 {plugin_name} 验证成功,已移出隔离名单!")
+                    VSC_INFO("vs_proxy", f"[Proxy Half-Open Revival] Egress IP {egress_ip} (Port {port}) succeeded for plugin {plugin_name}. Removed from quarantine!")
             else:
             else:
-                # 失败事件
+                # Failure event
                 if is_outage:
                 if is_outage:
-                    VSC_WARN("vs_proxy", f"【全站故障保护】目标网站疑似出现全站级故障,已冻结对出口 IP {egress_ip} 的扣分与隔离!")
+                    VSC_WARN("vs_proxy", f"[Site Outage Protection] Target site suspected of site-wide outage. Freezing penalties and quarantine for egress IP {egress_ip}!")
                 else:
                 else:
-                    # Layer 2: 错误精细分类判定
+                    # Layer 2: Detailed error classification
                     is_waf_block = (
                     is_waf_block = (
                         "cf-mitigated" in error_type.lower() or
                         "cf-mitigated" in error_type.lower() or
                         "403202" in error_type or
                         "403202" in error_type or
@@ -419,13 +420,13 @@ class ProxyManager:
                         (http_code == 403 and "mitigated" in error_type.lower())
                         (http_code == 403 and "mitigated" in error_type.lower())
                     )
                     )
                     if is_waf_block:
                     if is_waf_block:
-                        # 针对性阻断:进入隔离名单(默认 1800 秒)
+                        # Targeted block: enter quarantine list (default 1800s)
                         quarantine_map[egress_ip] = now + 1800
                         quarantine_map[egress_ip] = now + 1800
-                        VSC_WARN("vs_proxy", f"【节点临时隔离】出口 IP {egress_ip} (Port {port}) 触发针对性 WAF 阻断,临时隔离 30 分钟!")
-                        # 触发潜在漂移检测:清除缓存以便重新探查真实公网 IP 是否已变
+                        VSC_WARN("vs_proxy", f"[Node Quarantined] Egress IP {egress_ip} (Port {port}) triggered targeted WAF block. Quarantined for 30 minutes!")
+                        # Trigger potential drift detection: invalidate cache to re-probe true public IP
                         self.invalidate_egress_cache(port)
                         self.invalidate_egress_cache(port)
 
 
-        # 3. 异步上报埋点指标至云端 (Fail-Silent)
+        # 3. Asynchronously report telemetry metrics to cloud (Fail-Silent)
         metric_payload = {
         metric_payload = {
             "client_id": getattr(configure, "NODE_ID", "local_node"),
             "client_id": getattr(configure, "NODE_ID", "local_node"),
             "plugin_name": plugin_name,
             "plugin_name": plugin_name,

+ 32 - 33
toolkit/proxy_tunnel.py

@@ -6,10 +6,10 @@ import time
 
 
 class ProxyTunnel:
 class ProxyTunnel:
     """
     """
-    【修复优化版】管理本地代理隧道
-    1. 启用 TCP_NODELAY 消除握手延迟 (关键修复)
-    2. 开启 KeepAlive 防止链路中断
-    3. 修复非阻塞模式下 sendall 导致的数据丢失问题
+    Local proxy tunnel manager
+    1. Enables TCP_NODELAY to eliminate handshake latency.
+    2. Enables KeepAlive to prevent idle disconnection.
+    3. Uses blocking sendall with select polling to prevent data loss.
     """
     """
     def __init__(self, upstream_ip, upstream_port, username, password):
     def __init__(self, upstream_ip, upstream_port, username, password):
         self.upstream_ip = upstream_ip
         self.upstream_ip = upstream_ip
@@ -17,7 +17,7 @@ class ProxyTunnel:
         self.username = username
         self.username = username
         self.password = password
         self.password = password
         
         
-        # 预先计算 Proxy-Authorization 头
+        # Pre-compute Proxy-Authorization header
         auth_str = f"{username}:{password}"
         auth_str = f"{username}:{password}"
         b64_auth = base64.b64encode(auth_str.encode()).decode()
         b64_auth = base64.b64encode(auth_str.encode()).decode()
         self.auth_header = f"Proxy-Authorization: Basic {b64_auth}\r\n"
         self.auth_header = f"Proxy-Authorization: Basic {b64_auth}\r\n"
@@ -34,7 +34,7 @@ class ProxyTunnel:
             
             
             self.server_socket.bind(('127.0.0.1', 0))
             self.server_socket.bind(('127.0.0.1', 0))
             self.local_port = self.server_socket.getsockname()[1]
             self.local_port = self.server_socket.getsockname()[1]
-            self.server_socket.listen(128) # 增加连接队列长度
+            self.server_socket.listen(128) # Increase listen backlog
             
             
             self.running = True
             self.running = True
             
             
@@ -59,7 +59,7 @@ class ProxyTunnel:
         while self.running:
         while self.running:
             try:
             try:
                 if self.server_socket:
                 if self.server_socket:
-                    # 使用 select 替代 settimeout,减少 CPU 空转
+                    # Use select instead of settimeout to reduce CPU idle spinning
                     r, _, _ = select.select([self.server_socket], [], [], 1.0)
                     r, _, _ = select.select([self.server_socket], [], [], 1.0)
                     if r:
                     if r:
                         try:
                         try:
@@ -72,16 +72,16 @@ class ProxyTunnel:
                 continue
                 continue
 
 
     def _optimize_socket(self, sock):
     def _optimize_socket(self, sock):
-        """核心优化:设置 Socket 选项"""
+        """Socket options optimization"""
         try:
         try:
-            # 1. 禁用 Nagle 算法:数据包立即发送,不等待填满缓冲区
-            # 这是解决 "HttpClient Timeout" 的关键
+            # 1. Disable Nagle's algorithm: packets sent immediately without buffer delay
+            # Crucial for preventing HttpClient timeouts
             sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
             sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
             
             
-            # 2. 开启 KeepAlive:防止防火墙切断空闲连接
+            # 2. Enable KeepAlive: prevent firewalls from terminating idle connections
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
             
             
-            # 3. 增大缓冲区 (Linux/Mac 可选,Windows 一般自动管理)
+            # 3. Increase buffer sizes
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 32*1024)
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32*1024)
             sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 32*1024)
         except Exception:
         except Exception:
@@ -93,27 +93,27 @@ class ProxyTunnel:
             self._optimize_socket(client_sock)
             self._optimize_socket(client_sock)
             client_sock.settimeout(30) 
             client_sock.settimeout(30) 
             
             
-            # 1. 读取首包 (32KB 缓冲区)
+            # 1. Read first packet (32KB buffer)
             try:
             try:
                 first_packet = client_sock.recv(32768)
                 first_packet = client_sock.recv(32768)
             except socket.timeout:
             except socket.timeout:
-                return # 客户端连上但不发数据
+                return # Client connected without sending data
                 
                 
             if not first_packet:
             if not first_packet:
                 return
                 return
 
 
-            # 2. 连接上游
+            # 2. Connect to upstream
             upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
             upstream_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
-            self._optimize_socket(upstream_sock) # 同样优化上游 Socket
+            self._optimize_socket(upstream_sock) # Optimize upstream socket
             
             
-            upstream_sock.settimeout(10) # 连接超时 10s
+            upstream_sock.settimeout(10) # Connect timeout: 10s
             upstream_sock.connect((self.upstream_ip, self.upstream_port))
             upstream_sock.connect((self.upstream_ip, self.upstream_port))
             
             
-            # 连接建立后,将超时设为 None (阻塞模式),交由 select 控制
+            # Switch to blocking mode once connected; multiplexing handled by select
             upstream_sock.settimeout(None)
             upstream_sock.settimeout(None)
             client_sock.settimeout(None)
             client_sock.settimeout(None)
             
             
-            # 3. 注入 Header
+            # 3. Inject Header
             sep = b'\r\n'
             sep = b'\r\n'
             idx = first_packet.find(sep)
             idx = first_packet.find(sep)
             if idx != -1:
             if idx != -1:
@@ -121,10 +121,10 @@ class ProxyTunnel:
             else:
             else:
                 new_packet = first_packet
                 new_packet = first_packet
 
 
-            # 4. 发送首包 (阻塞式发送,保证数据完整)
+            # 4. Send first packet (blocking sendall to guarantee integrity)
             upstream_sock.sendall(new_packet)
             upstream_sock.sendall(new_packet)
             
             
-            # 5. 双向转发
+            # 5. Bi-directional proxy forwarding
             self._pipe_sockets(client_sock, upstream_sock)
             self._pipe_sockets(client_sock, upstream_sock)
 
 
         except Exception:
         except Exception:
@@ -135,19 +135,19 @@ class ProxyTunnel:
 
 
     def _pipe_sockets(self, sock1, sock2):
     def _pipe_sockets(self, sock1, sock2):
         """
         """
-        修复后的转发逻辑:
-        保持 Socket 为阻塞模式,利用 select 监听可读状态。
+        Forwarding logic:
+        Maintains blocking socket mode while using select to poll readable state.
         """
         """
         sockets = [sock1, sock2]
         sockets = [sock1, sock2]
         last_activity = time.time()
         last_activity = time.time()
-        IDLE_TIMEOUT = 120 # 延长空闲超时
+        IDLE_TIMEOUT = 120 # Extended idle timeout
         
         
         while self.running:
         while self.running:
             try:
             try:
-                # 监听可读事件
+                # Listen for readable sockets
                 r, _, x = select.select(sockets, [], sockets, 1.0)
                 r, _, x = select.select(sockets, [], sockets, 1.0)
                 
                 
-                if x: break # Socket 异常
+                if x: break # Socket exception
                 
                 
                 if not r:
                 if not r:
                     if time.time() - last_activity > IDLE_TIMEOUT:
                     if time.time() - last_activity > IDLE_TIMEOUT:
@@ -156,19 +156,18 @@ class ProxyTunnel:
                 
                 
                 for s in r:
                 for s in r:
                     try:
                     try:
-                        # 尝试读取
+                        # Attempt read
                         data = s.recv(32768)
                         data = s.recv(32768)
                     except ConnectionResetError:
                     except ConnectionResetError:
                         data = None
                         data = None
                     
                     
                     if not data:
                     if not data:
-                        return # 连接关闭
+                        return # Connection closed
                     
                     
-                    # 确定发送目标
+                    # Determine forwarding destination
                     target = sock2 if s is sock1 else sock1
                     target = sock2 if s is sock1 else sock1
                     
                     
-                    # 关键修改:使用阻塞式 sendall
-                    # 如果网络卡顿,线程会在这里暂停等待,而不是抛出错误或丢包
+                    # Blocking sendall: pauses thread if network is congested without packet drops
                     try:
                     try:
                         target.sendall(data)
                         target.sendall(data)
                     except BrokenPipeError:
                     except BrokenPipeError:
@@ -180,10 +179,10 @@ class ProxyTunnel:
                 break
                 break
 
 
     def _close_socket(self, sock):
     def _close_socket(self, sock):
-        """优雅关闭 Socket"""
+        """Gracefully closes socket."""
         if sock:
         if sock:
             try:
             try:
-                # 发送 FIN 包,通知对端数据发送完毕
+                # Send FIN packet to signal completion
                 sock.shutdown(socket.SHUT_RDWR)
                 sock.shutdown(socket.SHUT_RDWR)
             except Exception:
             except Exception:
                 pass
                 pass

+ 10 - 10
toolkit/thread_pool.py

@@ -5,8 +5,8 @@ from log_macros import VSC_INFO, VSC_ERROR
 
 
 class ThreadPool:
 class ThreadPool:
     """
     """
-    @brief 线程池单例类
-    模拟C++的ThreadPool,使用Python的ThreadPoolExecutor。
+    @brief ThreadPool singleton class
+    Simulates C++ ThreadPool using Python's ThreadPoolExecutor.
     """
     """
     _instance = None
     _instance = None
     _lock = threading.Lock()
     _lock = threading.Lock()
@@ -21,16 +21,16 @@ class ThreadPool:
 
 
     @staticmethod
     @staticmethod
     def getInstance(max_workers: int = 10):
     def getInstance(max_workers: int = 10):
-        """获取线程池单例实例。"""
+        """Gets ThreadPool singleton instance."""
         return ThreadPool(max_workers)
         return ThreadPool(max_workers)
 
 
     def enqueue(self, func, *args, **kwargs) -> Future:
     def enqueue(self, func, *args, **kwargs) -> Future:
         """
         """
-        @brief 提交任务到线程池。
-        @param func 要执行的函数
-        @param args 函数的位置参数
-        @param kwargs 函数的关键字参数
-        @return Future 对象,表示异步操作的结果
+        @brief Enqueues a task to the thread pool.
+        @param func Function to execute
+        @param args Positional arguments for the function
+        @param kwargs Keyword arguments for the function
+        @return Future object representing execution result
         """
         """
         try:
         try:
             future = self._executor.submit(func, *args, **kwargs)
             future = self._executor.submit(func, *args, **kwargs)
@@ -41,8 +41,8 @@ class ThreadPool:
 
 
     def shutdown(self, wait: bool = True):
     def shutdown(self, wait: bool = True):
         """
         """
-        @brief 关闭线程池。
-        @param wait 如果为True,则等待所有待处理的future完成。
+        @brief Shuts down the thread pool.
+        @param wait If True, waits for all pending futures to complete.
         """
         """
         if self._executor:
         if self._executor:
             VSC_INFO("thread_pool", "Shutting down ThreadPool (wait=%s)...", wait)
             VSC_INFO("thread_pool", "Shutting down ThreadPool (wait=%s)...", wait)

+ 30 - 30
utils/flow_engine.py

@@ -1,5 +1,5 @@
 """
 """
-flow_engine.py - 极简声明式注解流引擎 (基于 DrissionPage 原生 API)
+flow_engine.py - Declarative annotated flow engine (based on DrissionPage native API)
 """
 """
 
 
 import time
 import time
@@ -14,7 +14,7 @@ def on(url: Optional[str] = None,
        not_ele: Optional[str] = None, 
        not_ele: Optional[str] = None, 
        predicate: Optional[Callable[['BaseFlow'], bool]] = None,
        predicate: Optional[Callable[['BaseFlow'], bool]] = None,
        priority: int = 100):
        priority: int = 100):
-    """主匹配注解:页面满足条件时触发对应动作方法(支持同一方法堆叠多个注解,形成 OR 关系)"""
+    """Main matching decorator: triggers method when page satisfies conditions (supports stacking for OR relationships)"""
     def decorator(func: Callable):
     def decorator(func: Callable):
         rule_spec = {
         rule_spec = {
             "url": url, 
             "url": url, 
@@ -39,7 +39,7 @@ def on(url: Optional[str] = None,
 
 
 
 
 def done(func: Callable):
 def done(func: Callable):
-    """终态注解:执行完后退出并标记成功"""
+    """Done state decorator: exits and marks flow successful upon execution"""
     func._is_done = True
     func._is_done = True
     for r in getattr(func, "_flow_rules", []):
     for r in getattr(func, "_flow_rules", []):
         r["is_done"] = True
         r["is_done"] = True
@@ -47,7 +47,7 @@ def done(func: Callable):
 
 
 
 
 def fatal(error_msg: str, exception_cls: Type[Exception] = BizLogicError):
 def fatal(error_msg: str, exception_cls: Type[Exception] = BizLogicError):
-    """致命错误注解:命中时抛出异常终止流程"""
+    """Fatal error decorator: aborts flow with an exception when matched"""
     def decorator(func: Callable):
     def decorator(func: Callable):
         func._fatal_msg = error_msg
         func._fatal_msg = error_msg
         func._exception_cls = exception_cls
         func._exception_cls = exception_cls
@@ -65,13 +65,13 @@ def guard(url: Optional[str] = None,
           not_ele: Optional[str] = None, 
           not_ele: Optional[str] = None, 
           predicate: Optional[Callable[['BaseFlow'], bool]] = None,
           predicate: Optional[Callable[['BaseFlow'], bool]] = None,
           priority: int = 10):
           priority: int = 10):
-    """高优先级异常守卫注解"""
+    """High-priority exception guard decorator"""
     return on(url=url, title=title, text=text, ele=ele, not_ele=not_ele, predicate=predicate, priority=priority)
     return on(url=url, title=title, text=text, ele=ele, not_ele=not_ele, predicate=predicate, priority=priority)
 
 
 
 
 class BaseFlow:
 class BaseFlow:
     """
     """
-    轻量注解状态机驱动引擎
+    Lightweight annotated state machine driver engine.
     """
     """
     def __init__(self, 
     def __init__(self, 
                  page, 
                  page, 
@@ -93,7 +93,7 @@ class BaseFlow:
         self.stuck_count = 0
         self.stuck_count = 0
         self.max_stuck_cycles = max_stuck_cycles
         self.max_stuck_cycles = max_stuck_cycles
         
         
-        # 收集注解方法并按 priority 升序排序
+        # Collect annotated methods and sort by priority ascending
         self._rules = []
         self._rules = []
         for attr_name in dir(self):
         for attr_name in dir(self):
             try:
             try:
@@ -125,8 +125,8 @@ class BaseFlow:
             print(f"[{self.__class__.__name__}] [{level.upper()}] {msg}")
             print(f"[{self.__class__.__name__}] [{level.upper()}] {msg}")
 
 
     def _matches(self, rule: Dict[str, Any]) -> bool:
     def _matches(self, rule: Dict[str, Any]) -> bool:
-        """根据 URL、Title、Text、Ele 及自定义 Predicate 判定是否命中规则"""
-        # 防呆机制:如果没有任何匹配条件,直接视为不匹配,防止无条件空转造成死循环
+        """Determines whether a rule is matched based on URL, Title, Text, Ele and custom Predicate"""
+        # Guard: if no matching condition is specified, treat as unmatched
         if not any([
         if not any([
             rule.get("url"),
             rule.get("url"),
             rule.get("title"),
             rule.get("title"),
@@ -173,7 +173,7 @@ class BaseFlow:
                 if not rule["predicate"](self):
                 if not rule["predicate"](self):
                     return False
                     return False
             except Exception as e:
             except Exception as e:
-                self.log(f"[WARN] 规则 @{rule.get('name', 'unknown')} 的 predicate 执行异常: {e}", level="warning")
+                self.log(f"[WARN] Rule @{rule.get('name', 'unknown')} predicate evaluation exception: {e}", level="warning")
                 return False
                 return False
 
 
         return True
         return True
@@ -183,10 +183,10 @@ class BaseFlow:
             timeout: Optional[float] = None, 
             timeout: Optional[float] = None, 
             max_stuck_cycles: Optional[int] = None) -> Any:
             max_stuck_cycles: Optional[int] = None) -> Any:
         """
         """
-        执行扫描调度循环,支持步数与超时时间双重限制
-        :param max_steps: 最大循环步数限制,为 None 时表示不限制步数
-        :param timeout: 最大执行超时时间(秒),为 None 时表示不限制时间
-        :param max_stuck_cycles: 页面停滞自愈刷新周期,若提供则覆盖实例配置,为 None 则关闭停滞刷新
+        Executes scanning dispatch loop, supporting both step count and timeout limits.
+        :param max_steps: Maximum loop steps limit; None means unlimited.
+        :param timeout: Maximum execution timeout (seconds); None means unlimited.
+        :param max_stuck_cycles: Stuck cycles before refresh self-healing; None to disable.
         """
         """
         if max_stuck_cycles is not None:
         if max_stuck_cycles is not None:
             self.max_stuck_cycles = max_stuck_cycles
             self.max_stuck_cycles = max_stuck_cycles
@@ -194,33 +194,33 @@ class BaseFlow:
         start_time = time.time()
         start_time = time.time()
         step = 0
         step = 0
 
 
-        # 构建展示信息
+        # Construct display info
         limits_desc = []
         limits_desc = []
         if max_steps is not None:
         if max_steps is not None:
             limits_desc.append(f"max_steps={max_steps}")
             limits_desc.append(f"max_steps={max_steps}")
         if timeout is not None:
         if timeout is not None:
             limits_desc.append(f"timeout={timeout}s")
             limits_desc.append(f"timeout={timeout}s")
-        limits_str = f" (限制: {', '.join(limits_desc)})" if limits_desc else " (无限制模式)"
+        limits_str = f" (Limits: {', '.join(limits_desc)})" if limits_desc else " (Unlimited mode)"
 
 
-        self.log(f"🚀 启动流程状态机,加载了 {len(self._rules)} 条规则{limits_str}")
+        self.log(f"🚀 Flow state machine started with {len(self._rules)} rule(s){limits_str}")
 
 
         while True:
         while True:
             step += 1
             step += 1
             elapsed = time.time() - start_time
             elapsed = time.time() - start_time
 
 
-            # 1. 检查步数限制
+            # 1. Check step limit
             if max_steps is not None and step > max_steps:
             if max_steps is not None and step > max_steps:
                 raise BizLogicError(
                 raise BizLogicError(
-                    f"流程步数耗尽(已执行 {step - 1} 步 / 上限 {max_steps} 步,耗时 {elapsed:.1f}s),最后停留在: {getattr(self.page, 'url', '')}"
+                    f"Flow steps exhausted (Executed {step - 1} steps / limit {max_steps}, elapsed {elapsed:.1f}s), last URL: {getattr(self.page, 'url', '')}"
                 )
                 )
 
 
-            # 2. 检查超时限制
+            # 2. Check timeout limit
             if timeout is not None and elapsed > timeout:
             if timeout is not None and elapsed > timeout:
                 raise BizLogicError(
                 raise BizLogicError(
-                    f"流程执行超时(已耗时 {elapsed:.1f}s / 上限 {timeout:.1f}s,已执行 {step - 1} 步),最后停留在: {getattr(self.page, 'url', '')}"
+                    f"Flow execution timed out (Elapsed {elapsed:.1f}s / limit {timeout:.1f}s, executed {step - 1} steps), last URL: {getattr(self.page, 'url', '')}"
                 )
                 )
 
 
-            # 格式化步骤标识前缀
+            # Format step prefix
             if max_steps is not None and timeout is not None:
             if max_steps is not None and timeout is not None:
                 step_prefix = f"[{step}/{max_steps} | {elapsed:.1f}s/{timeout:.1f}s]"
                 step_prefix = f"[{step}/{max_steps} | {elapsed:.1f}s/{timeout:.1f}s]"
             elif max_steps is not None:
             elif max_steps is not None:
@@ -238,41 +238,41 @@ class BaseFlow:
             time.sleep(self.interval)
             time.sleep(self.interval)
 
 
             curr_url = getattr(self.page, "url", "")
             curr_url = getattr(self.page, "url", "")
-            # 停滞检测与刷新自愈(若启用)
+            # Stuck detection and refresh self-healing
             if self.max_stuck_cycles is not None and self.max_stuck_cycles > 0:
             if self.max_stuck_cycles is not None and self.max_stuck_cycles > 0:
                 if curr_url and curr_url == self.last_url:
                 if curr_url and curr_url == self.last_url:
                     self.stuck_count += 1
                     self.stuck_count += 1
                     if self.stuck_count >= self.max_stuck_cycles:
                     if self.stuck_count >= self.max_stuck_cycles:
-                        self.log(f"{step_prefix} [WARN] 页面停滞达 {self.stuck_count} 周期,执行刷新自愈...", level="warning")
+                        self.log(f"{step_prefix} [WARN] Page stuck for {self.stuck_count} cycles, executing refresh...", level="warning")
                         try:
                         try:
                             self.page.refresh()
                             self.page.refresh()
                             self.page.wait.load_start(timeout=5)
                             self.page.wait.load_start(timeout=5)
                         except Exception as e:
                         except Exception as e:
-                            self.log(f"[ERROR] 刷新页面失败: {e}", level="error")
+                            self.log(f"[ERROR] Failed to refresh page: {e}", level="error")
                         self.stuck_count = 0
                         self.stuck_count = 0
                         continue
                         continue
                 else:
                 else:
                     self.last_url, self.stuck_count = curr_url, 0
                     self.last_url, self.stuck_count = curr_url, 0
 
 
-            # 按优先级匹配规则
+            # Match rules by priority
             matched_rule = None
             matched_rule = None
             for rule in self._rules:
             for rule in self._rules:
                 if self._matches(rule):
                 if self._matches(rule):
                     matched_rule = rule
                     matched_rule = rule
-                    self.log(f"{step_prefix} 🎯 命中规则: @{rule['name']} (priority={rule['priority']})")
+                    self.log(f"{step_prefix} 🎯 Matched rule: @{rule['name']} (priority={rule['priority']})")
                     
                     
                     if rule["fatal_msg"]:
                     if rule["fatal_msg"]:
-                        self.log(f"💥 触发致命错误中断: {rule['fatal_msg']}", level="error")
+                        self.log(f"💥 Fatal error interruption triggered: {rule['fatal_msg']}", level="error")
                         exc_cls = rule.get("exception_cls", BizLogicError)
                         exc_cls = rule.get("exception_cls", BizLogicError)
                         raise exc_cls(rule["fatal_msg"])
                         raise exc_cls(rule["fatal_msg"])
                     
                     
                     rule["method"]()
                     rule["method"]()
                     
                     
                     if rule["is_done"]:
                     if rule["is_done"]:
-                        self.log(f"✨ 目标达成,流程完成!(耗时 {time.time() - start_time:.1f}s,共执行 {step} 步)")
+                        self.log(f"✨ Goal achieved, flow complete! (Elapsed {time.time() - start_time:.1f}s, executed {step} steps)")
                         return self.result if self.result is not None else True
                         return self.result if self.result is not None else True
                     
                     
                     break
                     break
 
 
             if not matched_rule:
             if not matched_rule:
-                self.log(f"{step_prefix} ⏳ 未匹配到注解规则 (URL: {curr_url}),等待下一周期...")
+                self.log(f"{step_prefix} ⏳ No rules matched (URL: {curr_url}), waiting for next cycle...")

+ 10 - 10
utils/redis_stream_logger.py

@@ -10,9 +10,9 @@ import redis
 
 
 class RedisStreamLogger:
 class RedisStreamLogger:
     """
     """
-    负责将节点/角色/分组运行日志异步缓冲并通过 Redis Stream 传输到后端。
-    内部采用无锁内存 Queue + 后台批处理 Daemon 线程,
-    保证网络抖动或 Redis 延迟完全不阻塞主业务逻辑(抢号/巡检)。
+    Asynchronously buffers node/role/group logs and streams them to backend via Redis Stream.
+    Uses an in-memory lock-free Queue and background batch daemon thread,
+    ensuring Redis latency or network jitter never blocks core operations.
     """
     """
     _instance: Optional["RedisStreamLogger"] = None
     _instance: Optional["RedisStreamLogger"] = None
     _lock = threading.Lock()
     _lock = threading.Lock()
@@ -37,7 +37,7 @@ class RedisStreamLogger:
         self._stopped = False
         self._stopped = False
         self._redis_client: Optional[redis.Redis] = None
         self._redis_client: Optional[redis.Redis] = None
         
         
-        # 启动后台守护工作线程
+        # Start background daemon worker thread
         self._worker_thread = threading.Thread(
         self._worker_thread = threading.Thread(
             target=self._flusher_loop,
             target=self._flusher_loop,
             daemon=True,
             daemon=True,
@@ -74,7 +74,7 @@ class RedisStreamLogger:
         group_id: str = "",
         group_id: str = "",
         timestamp: Optional[str] = None,
         timestamp: Optional[str] = None,
     ):
     ):
-        """非阻塞压入待发送队列。若队列满载则丢弃旧日志,决不挂起调用方"""
+        """Non-blocking enqueue. Drops oldest log entry if queue is full, never hanging caller."""
         if self._stopped:
         if self._stopped:
             return
             return
         if not timestamp:
         if not timestamp:
@@ -93,7 +93,7 @@ class RedisStreamLogger:
             self.queue.put_nowait(payload)
             self.queue.put_nowait(payload)
         except queue.Full:
         except queue.Full:
             try:
             try:
-                # 丢弃一条最旧的,重新入队
+                # Drop oldest item and re-enqueue
                 _ = self.queue.get_nowait()
                 _ = self.queue.get_nowait()
                 self.queue.put_nowait(payload)
                 self.queue.put_nowait(payload)
             except Exception:
             except Exception:
@@ -105,7 +105,7 @@ class RedisStreamLogger:
 
 
         while not self._stopped:
         while not self._stopped:
             try:
             try:
-                # 尽可能凑批,最高等待 0.2 秒
+                # Batch items up to 0.2s
                 try:
                 try:
                     item = self.queue.get(timeout=0.2)
                     item = self.queue.get(timeout=0.2)
                     batch.append(item)
                     batch.append(item)
@@ -115,7 +115,7 @@ class RedisStreamLogger:
                     pass
                     pass
 
 
                 now = time.time()
                 now = time.time()
-                # 满批或超时刷新
+                # Flush if full batch or timeout
                 if batch and (len(batch) >= 20 or (now - last_flush_time >= 0.5)):
                 if batch and (len(batch) >= 20 or (now - last_flush_time >= 0.5)):
                     self._flush_batch(batch)
                     self._flush_batch(batch)
                     batch = []
                     batch = []
@@ -139,7 +139,7 @@ class RedisStreamLogger:
                 )
                 )
             pipe.execute()
             pipe.execute()
         except Exception:
         except Exception:
-            # 异常时释放连接供重试
+            # Release client connection on error to allow reconnection
             self._redis_client = None
             self._redis_client = None
 
 
     def close(self):
     def close(self):
@@ -148,7 +148,7 @@ class RedisStreamLogger:
 
 
 class RedisStreamLogHandler(logging.Handler):
 class RedisStreamLogHandler(logging.Handler):
     """
     """
-    Python logging 标准 Handler,用于透明接管 logger.info / warning / error 等日志
+    Standard Python logging Handler to transparently forward log records to Redis Stream.
     """
     """
     def __init__(self, logger_instance: Optional[RedisStreamLogger] = None):
     def __init__(self, logger_instance: Optional[RedisStreamLogger] = None):
         super().__init__()
         super().__init__()

+ 7 - 7
utils/safe_redis_cli.py

@@ -6,10 +6,10 @@ from typing import List, Dict, Callable, Any
 class SafeRedisClient:
 class SafeRedisClient:
     def __init__(self, redis_conf: Dict, logger: Callable[[str], None] = None):
     def __init__(self, redis_conf: Dict, logger: Callable[[str], None] = None):
         safe_conf = dict(redis_conf)
         safe_conf = dict(redis_conf)
-        safe_conf.setdefault('socket_timeout', 5.0)          # 读写超时防死等
-        safe_conf.setdefault('socket_connect_timeout', 5.0)  # 建连超时防死等
-        safe_conf.setdefault('socket_keepalive', True)       # TCP 操作系统级保活
-        safe_conf.setdefault('health_check_interval', 30)    # 自动探测断连并重连
+        safe_conf.setdefault('socket_timeout', 5.0)          # Read/write timeout
+        safe_conf.setdefault('socket_connect_timeout', 5.0)  # Connection timeout
+        safe_conf.setdefault('socket_keepalive', True)       # TCP OS-level keepalive
+        safe_conf.setdefault('health_check_interval', 30)    # Auto disconnect detection & reconnect
         
         
         self._client = redis.Redis(**safe_conf)
         self._client = redis.Redis(**safe_conf)
         self._logger = logger
         self._logger = logger
@@ -21,7 +21,7 @@ class SafeRedisClient:
             print(f"[Safe-Redis] {msg}")
             print(f"[Safe-Redis] {msg}")
 
 
     def _safe_execute(self, func, default_return, *args, **kwargs):
     def _safe_execute(self, func, default_return, *args, **kwargs):
-        """通用安全执行器:遇错自动重试一次,彻底失败返回安全默认值"""
+        """General safe executor: auto-retries once on error, returns safe fallback on total failure."""
         try:
         try:
             return func(*args, **kwargs)
             return func(*args, **kwargs)
         except Exception as e:
         except Exception as e:
@@ -51,7 +51,7 @@ class SafeRedisClient:
         return self._safe_execute(self._client.delete, 0, *names)
         return self._safe_execute(self._client.delete, 0, *names)
 
 
     def incr(self, name, amount=1) -> int:
     def incr(self, name, amount=1) -> int:
-        # 如果增加失败,默认返回 1,防止触发外部数学运算崩溃(同时保证退避策略能生效)
+        # Fallback to 1 on failure to avoid calculation crashes while preserving backoff
         return self._safe_execute(self._client.incr, 1, name, amount=amount)
         return self._safe_execute(self._client.incr, 1, name, amount=amount)
 
 
     def zadd(self, name, mapping) -> int:
     def zadd(self, name, mapping) -> int:
@@ -63,7 +63,7 @@ class SafeRedisClient:
         return self._safe_execute(self._client.zrem, 0, name, *values)
         return self._safe_execute(self._client.zrem, 0, name, *values)
 
 
     def bulk_zadd(self, name, mapping) -> bool:
     def bulk_zadd(self, name, mapping) -> bool:
-        """封装 Pipeline,用于一次性安全地写入大量 zset 元素"""
+        """Wraps Pipeline to safely batch write zset elements."""
         if not mapping:
         if not mapping:
             return True
             return True
         def _op():
         def _op():