2
1

7 کامیت‌ها 65afa28f52 ... cf50da0c97

نویسنده SHA1 پیام تاریخ
  zhangweijp cf50da0c97 Merge branch 'codex/italy-cr-cleanup' 2 ماه پیش
  zhangweijp ad4f644d5d update ignore file 2 ماه پیش
  zhangweijp 5941312803 ignore AGENTS.md 2 ماه پیش
  zhangweijp d5cc605ba6 ignore 2 ماه پیش
  zhangweijp df478e42e0 代码优化,无用文件删除 2 ماه پیش
  zhangweijp 9126cf61e4 test(ita): align error contract and boundaries 2 ماه پیش
  zhangweijp e98808182c refactor(ita): use framework error categories 2 ماه پیش
5فایلهای تغییر یافته به همراه180 افزوده شده و 153 حذف شده
  1. 7 1
      .gitignore
  2. 1 2
      config/config_booker.json
  3. 1 2
      config/config_sentinel.json
  4. 1 2
      config/test_conf.json
  5. 170 146
      plugins/ita_plugin.py

+ 7 - 1
.gitignore

@@ -32,6 +32,7 @@ env/
 *.local
 secrets.json
 config/ita_query_account.local.json
+config/test_conf.local.json
 
 # —— Node(若子项目使用) ——
 node_modules/
@@ -81,5 +82,10 @@ data/**/*.png
 *.orig
 *.tmp
 *.temp
-
 downloads
+test/ita
+docs/italy-refactor
+tools/diff_viewer.py
+
+# Agent
+AGENTS.md

+ 1 - 2
config/config_booker.json

@@ -1658,8 +1658,7 @@
           "service_id": 1321,
           "capability": "services_probe_only"
         }
-      },
-      "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+      }
     },
     "version": 2,
     "updated_by": "769858626@qq.com",

+ 1 - 2
config/config_sentinel.json

@@ -1791,8 +1791,7 @@
           "service_id": 1321,
           "capability": "services_probe_only"
         }
-      },
-      "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+      }
     },
     "version": 2,
     "updated_by": "769858626@qq.com",

+ 1 - 2
config/test_conf.json

@@ -320,8 +320,7 @@
               "purpose_labels": ["Turismo", "Tourism"]
             }
           }
-        },
-        "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+        }
       },
       "user_inputs": {
         "first_name": "SAN",

+ 170 - 146
plugins/ita_plugin.py

@@ -20,7 +20,7 @@ from DrissionPage import ChromiumPage
 import vs_plg as _ita_host
 from vs_plg import IVSPlg
 from vs_types import (
-    AvailabilityStatus, BizLogicError,
+    AvailabilityStatus, BizException, BizLogicError, NotFoundError,
     DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
     SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
 )
@@ -325,18 +325,15 @@ TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
 DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
 
 
-class CalendarGateError(RuntimeError): pass
-class CalendarAuthenticationExpiredError(CalendarGateError): pass
-class CalendarRateLimitedError(CalendarGateError): pass
-class CalendarAccessDeniedError(CalendarGateError): pass
-class CalendarTransientError(CalendarGateError): pass
-class CalendarBookError(CalendarGateError): pass
-
-
 def same_origin_path(raw_url):
-    parsed = urlparse(str(raw_url or ""))
-    if parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it":
-        raise CalendarGateError("Italy request left the expected origin")
+    try:
+        parsed = urlparse(str(raw_url or ""))
+        port = parsed.port
+    except ValueError:
+        raise BizLogicError("Italy request left the expected origin") from None
+    if (parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it"
+            or port not in (None, 443) or parsed.username is not None):
+        raise BizLogicError("Italy request left the expected origin")
     return parsed.path
 
 
@@ -374,9 +371,11 @@ selected = Boolean(candidateReady && slot.classList.contains('act'));
 return {contextReady, candidateCount: matches.length, candidateReady, selected, clicked};
 """
 def _runtime_id(value):
+    if value is None or isinstance(value, bool):
+        raise BizLogicError("Italy Calendar service id is invalid")
     value = str(value).strip()
-    if not value or len(value) > 128:
-        raise CalendarBookError("Italy Calendar service id is invalid")
+    if not re.fullmatch(r"[1-9]\d{0,127}", value):
+        raise BizLogicError("Italy Calendar service id is invalid")
     return value
 
 
@@ -384,64 +383,71 @@ def _request_day(value):
     try:
         return date.fromisoformat(str(value))
     except ValueError:
-        raise CalendarBookError("Italy Calendar date format changed") from None
+        raise BizLogicError("Italy Calendar date format changed") from None
 
 
 def read_calendar_context(page):
     if same_origin_path(page.url) != CALENDAR_PATH:
-        raise CalendarBookError("Italy Calendar page is not current")
+        raise BizLogicError("Italy Calendar page is not current")
     raw = page.run_js(CALENDAR_DOM_SCRIPT, "context", "", "", "", "", 0, False)
     if not isinstance(raw, dict) or raw.get("path") != CALENDAR_PATH:
-        raise CalendarBookError("Italy Calendar context is not ready")
+        raise BizLogicError("Italy Calendar context is not ready")
     return _runtime_id(raw.get("service")), _request_day(raw.get("day"))
 
-
-def read_calendar_service(page):
-    return read_calendar_context(page)[0]
-
-
 def wait_for_calendar_service(page, *, session_is_current, expected_service=None, timeout=5):
     deadline = time.monotonic() + timeout
     while time.monotonic() < deadline:
         if session_is_current() is not True:
-            raise CalendarBookError("Italy applicant Session changed")
+            raise SessionExpiredOrInvalidError("Italy applicant Session changed")
         try:
-            service = read_calendar_service(page)
-        except CalendarBookError:
+            service = read_calendar_context(page)[0]
+        except BizLogicError:
             time.sleep(0.1)
             continue
         if expected_service and service != _runtime_id(expected_service):
-            raise CalendarBookError("Italy Calendar service changed")
+            raise BizLogicError("Italy Calendar service changed")
         return service
-    raise CalendarBookError("Italy Calendar service did not initialize")
+    raise BizLogicError("Italy Calendar service did not initialize")
 
 
-def _calendar_post(page, path, payload, parser):
-    response = perform_browser_fetch(page, "POST", path, json_data=payload, timeout=30)
+def _calendar_post(page, path, payload, parser, *, form=False):
+    try:
+        response = perform_browser_fetch(
+            page, "POST", path, **{"data" if form else "json_data": payload}, timeout=30)
+    except BizException:
+        raise
+    except Exception as exc:
+        raise BizLogicError(f"Italy Calendar request failed: {type(exc).__name__}") from exc
     status, host = response.status_code, urlparse(str(response.url or "")).hostname
     if host == "iam.esteri.it" or status == 401:
-        raise CalendarAuthenticationExpiredError("Italy Calendar authentication expired")
+        raise SessionExpiredOrInvalidError("Italy Calendar authentication expired")
     if status == 403:
-        raise CalendarAccessDeniedError("Italy Calendar access denied")
+        raise PermissionDeniedError("Italy Calendar access denied")
     if status == 429:
-        raise CalendarRateLimitedError("Italy Calendar rate limited")
+        raise RateLimiteddError("Italy Calendar rate limited")
+    if status == 404:
+        raise NotFoundError("Italy Calendar endpoint is unavailable")
     if status in {0, 408, 502, 503, 504}:
-        raise CalendarTransientError("Italy Calendar temporarily unavailable")
+        raise BizLogicError("Italy Calendar temporarily unavailable")
     if status != 200 or same_origin_path(response.url) != path:
-        raise CalendarGateError("Italy Calendar returned an unexpected response")
+        raise BizLogicError("Italy Calendar returned an unexpected response")
     try:
         return parser(response.text)
-    except ItaProtocolError as exc:
-        raise CalendarGateError(f"Italy Calendar response rejected ({exc.code})") from exc
+    except (ValueError, TypeError) as exc:
+        raise BizLogicError(
+            f"Italy Calendar response rejected ({getattr(exc, 'code', type(exc).__name__)})") from exc
 
 
 def fetch_calendar_month(page, service, selected_day):
     selected = selected_day.strftime("%d/%m/%Y")
-    return _calendar_post(
+    days = _calendar_post(
         page, AVAILABILITY_PATH,
         {"_Servizio": _runtime_id(service), "selectedDay": selected},
         parse_calendar_availability,
     )
+    if any(item.day.replace(day=1) != selected_day.replace(day=1) for item in days):
+        raise BizLogicError("Italy Calendar returned dates for another month")
+    return days
 
 
 def fetch_calendar_slots(page, service, selected_day):
@@ -451,12 +457,12 @@ def fetch_calendar_slots(page, service, selected_day):
         parse_time_slots,
     )
     if any(slot.day != selected_day for slot in slots):
-        raise CalendarBookError("Italy Calendar returned slots for another day")
+        raise BizLogicError("Italy Calendar returned slots for another day")
     return slots
 
 
 def scan_until_first_available_month(
-    page, *, lookahead_months, log=None,
+    page, *, lookahead_months, log=None, check_current=None,
     month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
 ):
     service, anchor = read_calendar_context(page)
@@ -464,7 +470,11 @@ def scan_until_first_available_month(
     for index, month in enumerate(month_starts(anchor, lookahead_months)):
         if index and month_click_interval_seconds:
             time.sleep(month_click_interval_seconds)
+        if check_current:
+            check_current()
         days = fetch_calendar_month(page, service, month)
+        if check_current:
+            check_current()
         scans.append(days)
         available = available_calendar_days(days)
         if log:
@@ -474,10 +484,10 @@ def scan_until_first_available_month(
     return tuple(scans)
 
 
-def click_next_month(page, *, timeout=10, diagnostic=None):
+def click_next_month(page, *, timeout=10):
     control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
     if not control:
-        raise CalendarBookError("Italy Calendar next-month control is unavailable")
+        raise NotFoundError("Italy Calendar next-month control is unavailable")
     control.click(by_js=True)
 
 
@@ -487,16 +497,22 @@ def _snapshot(page, mode, service, day, candidate=None, click=False):
         CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
         candidate.time_label, candidate.slots_free, click,
     )
-    if not isinstance(raw, dict) or not raw.get("contextReady") or raw.get("candidateCount") != 1:
-        raise CalendarBookError("Italy Calendar selection context changed")
+    if (not isinstance(raw, dict) or type(raw.get("candidateCount")) is not int
+            or any(type(raw.get(key)) is not bool for key in (
+                "contextReady", "candidateReady", "selected", "clicked"))
+            or not raw["contextReady"] or raw["candidateCount"] not in (0, 1)
+            or (raw["candidateCount"] == 0 and (mode != "slot" or click
+                or raw["candidateReady"] or raw["selected"] or raw["clicked"]))):
+        raise BizLogicError("Italy Calendar selection context changed")
     return raw
 
 
 def verify_precommit_selection(page, *, runtime_service, candidate):
     raw = _snapshot(
         page, "slot", runtime_service, candidate.day, candidate, False)
-    if not raw.get("candidateReady") or not raw.get("selected"):
-        raise CalendarBookError("Italy Calendar selected slot changed")
+    if (not candidate.is_available or raw["candidateCount"] != 1
+            or not raw["candidateReady"] or not raw["selected"]):
+        raise BizLogicError("Italy Calendar selected slot changed")
     return candidate
 
 
@@ -509,10 +525,12 @@ def select_slot_before_final(
     if not inventory or not candidates:
         return None
     candidate, deadline = candidates[0], time.monotonic() + dom_timeout
+    if session_is_current and session_is_current() is not True:
+        raise SessionExpiredOrInvalidError("Italy applicant Session changed")
     _snapshot(page, "date", runtime_service, target_day, click=True)
     while time.monotonic() < deadline:
         if session_is_current and session_is_current() is not True:
-            raise CalendarBookError("Italy applicant Session changed")
+            raise SessionExpiredOrInvalidError("Italy applicant Session changed")
         date_state = _snapshot(page, "date", runtime_service, target_day)
         slot_state = _snapshot(page, "slot", runtime_service, target_day, candidate)
         if date_state.get("selected") and slot_state.get("candidateReady"):
@@ -521,7 +539,7 @@ def select_slot_before_final(
             return verify_precommit_selection(
                 page, runtime_service=runtime_service, candidate=candidate)
         time.sleep(0.1)
-    raise CalendarBookError("Italy Calendar slot did not finish loading")
+    raise BizLogicError("Italy Calendar slot did not finish loading")
 
 
 def book_date_preferences(user_inputs):
@@ -531,9 +549,9 @@ def book_date_preferences(user_inputs):
         try:
             values.append(date.fromisoformat(user_inputs.get(key, default)))
         except (AttributeError, TypeError, ValueError):
-            raise CalendarBookError(f"Italy {key} must use YYYY-MM-DD") from None
+            raise BizLogicError(f"Italy {key} must use YYYY-MM-DD") from None
     if values[0] > values[1]:
-        raise CalendarBookError("Italy date preference is inverted")
+        raise BizLogicError("Italy date preference is inverted")
     return tuple(values)
 
 
@@ -546,14 +564,14 @@ def _move_to_month(page, service, target, timeout):
         while time.monotonic() < deadline:
             actual_service, current = read_calendar_context(page)
             if actual_service != service:
-                raise CalendarBookError("Italy Calendar service changed")
+                raise BizLogicError("Italy Calendar service changed")
             if (current.year, current.month) == expected:
                 break
             time.sleep(0.1)
         else:
-            raise CalendarBookError("Italy Calendar month did not load")
+            raise BizLogicError("Italy Calendar month did not load")
     if (current.year, current.month) != target:
-        raise CalendarBookError("Italy Calendar cannot navigate backwards")
+        raise BizLogicError("Italy Calendar cannot navigate backwards")
 
 
 def recheck_calendar_before_final(
@@ -564,7 +582,7 @@ def recheck_calendar_before_final(
     service, anchor = read_calendar_context(page)
     for index, month_start in enumerate(month_starts(anchor, lookahead_months)):
         if session_is_current() is not True:
-            raise CalendarBookError("Italy applicant Session changed")
+            raise SessionExpiredOrInvalidError("Italy applicant Session changed")
         if index and month_click_interval_seconds:
             time.sleep(month_click_interval_seconds)
         inventory = fetch_calendar_month(page, service, month_start)
@@ -594,36 +612,37 @@ FINAL_ACCEPTED_LABEL = "italy-final-accepted"
 
 
 def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
+    result = VSBookResult(success=False, label=FINAL_FAILED_LABEL)
     try:
         page = plugin.page
         username = plugin.config.account.username.strip().casefold()
         prepared = plugin._require_calendar_context(route, role="book", username=username)
         if (not username or not isinstance(slot, SlotCandidate)
                 or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
-            raise CalendarBookError("Italy final context is not current")
+            raise BizLogicError("Italy final context is not current")
         verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
-        response = perform_browser_fetch(page, "POST", FINAL_PATH, data={
+        data = _calendar_post(page, FINAL_PATH, {
             "idCalendarioGiornaliero": slot.daily_calendar_id,
             "selectedDay": slot.day.isoformat(),
             "selectedHour": f"{slot.time_label}\n({slot.slots_free})",
-        })
-        data = response.json()
-        if (response.status_code == 200 and same_origin_path(response.url) == FINAL_PATH
-                and isinstance(data, dict) and not str(data.get("errorMessage", "")).strip()
-                and isinstance(data.get("url"), str) and data["url"].strip()):
-            same_origin_path(urljoin("https://prenotami.esteri.it", data["url"]))
-            return VSBookResult(
-                success=True,
-                account=username,
-                label=FINAL_ACCEPTED_LABEL,
-                book_date=slot.day.isoformat(),
-                book_time=slot.time_label,
-            )
-    except Exception as exc:
-        plugin._log(f"Italy final submission failed: {type(exc).__name__}")
-    # The next Booker signal must re-enter the form and obtain fresh IDs.
-    plugin._reset_calendar_state()
-    return VSBookResult(success=False, label=FINAL_FAILED_LABEL)
+        }, json.loads, form=True)
+        if not isinstance(data, dict) or not isinstance(data.get("errorMessage"), str):
+            raise BizLogicError("Italy final response is missing its result")
+        if data["errorMessage"].strip():
+            return result
+        destination = data.get("url")
+        if not isinstance(destination, str) or not destination.strip():
+            raise BizLogicError("Italy final response is missing its receipt URL")
+        path = same_origin_path(urljoin("https://prenotami.esteri.it", destination.strip()))
+        if not re.fullmatch(r"/Reservation/?|/ReservationDetail/Index/[^/]+/?", path):
+            raise BizLogicError("Italy final response did not lead to a receipt")
+        result = VSBookResult(success=True, account=username, label=FINAL_ACCEPTED_LABEL,
+                              book_date=slot.day.isoformat(), book_time=slot.time_label)
+        return result
+    finally:
+        if not result.success:
+            # The next Booker signal must prepare again and obtain fresh IDs.
+            plugin._reset_calendar_state()
 
 
 _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
@@ -632,7 +651,7 @@ _OTP_INPUT_LOCK = vars(_ita_host).setdefault("_coordinate_ita_otp_input_lock", L
 
 def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
     if not route.booking_type or not route.purpose:
-        raise CalendarGateError("Italy route is missing form controls")
+        raise BizLogicError("Italy route is missing form controls")
     config = {"path": booking_path, "booking": asdict(route.booking_type),
               "purpose": asdict(route.purpose)}
     return f"""
@@ -667,20 +686,20 @@ return {{
 
 def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
     if type(after_otp) is not bool or type(allow_pending) is not bool:
-        raise CalendarGateError("Italy booking preflight policy is invalid")
+        raise BizLogicError("Italy booking preflight policy is invalid")
     if not isinstance(raw, dict) or any(type(raw.get(key)) is not bool for key in (
             "formReady", "turnstileReady", "otpValuePresent", "otpSendEnabled", "avantiEnabled")):
-        raise CalendarGateError("Italy booking form structure changed")
+        raise BizLogicError("Italy booking form structure changed")
     if raw["otpValuePresent"] is not after_otp:
-        raise CalendarGateError("Italy booking OTP stage changed")
+        raise BizLogicError("Italy booking OTP stage changed")
     ready = (raw["formReady"] and (after_otp or raw["otpSendEnabled"]) and
              raw["turnstileReady"] and raw["avantiEnabled"])
     if not allow_pending and not ready:
-        raise CalendarGateError("Italy booking verification is not ready")
+        raise BizLogicError("Italy booking verification is not ready")
 
 
 def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
-                               diagnostic=None, wait_action=None, check_current=None):
+                               check_current=None):
     deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
     while time.monotonic() < deadline:
         if check_current:
@@ -701,20 +720,20 @@ def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
     reason = ("form_pending" if not raw or not raw["formReady"] else
               "otp_send_disabled" if not after_otp and not raw["otpSendEnabled"] else
               "turnstile_token_pending" if not raw["turnstileReady"] else "avanti_disabled")
-    raise CalendarGateError(f"Italy booking verification timed out: {reason}")
+    raise BizLogicError(f"Italy booking verification timed out: {reason}")
 
 
 def _element_or_fail(page, selector):
     element = page.ele(selector, timeout=5)
     if not element:
-        raise CalendarGateError(f"Italy booking element is missing: {selector}")
+        raise NotFoundError(f"Italy booking element is missing: {selector}")
     return element
 
 
 def _read_manual_otp():
     value = input("Italy booking OTP: ").strip()
     if not re.fullmatch(r"[0-9]{4,12}", value):
-        raise CalendarGateError("Italy OTP format rejected")
+        raise BizLogicError("Italy OTP format rejected")
     return value
 
 
@@ -723,14 +742,14 @@ def _enter_otp(plugin, otp):
     plugin.mouse.human_click_ele(field)
     field.input(otp, clear=True)
     if field.run_js("return this.value === arguments[0];", otp) is not True:
-        raise CalendarGateError("Italy OTP write failed")
+        raise BizLogicError("Italy OTP write failed")
 
 
 def validate_cloud_otp_environment(mail_config, recipient):
     if not isinstance(mail_config, OtpMailConfig):
-        raise CalendarGateError("Italy OTP mail configuration is missing")
+        raise BizLogicError("Italy OTP mail configuration is missing")
     if not isinstance(recipient, str) or not _EMAIL_PATTERN.fullmatch(recipient.strip()):
-        raise CalendarGateError("Italy OTP recipient is invalid")
+        raise BizLogicError("Italy OTP recipient is invalid")
     mail_config.mailbox_for(recipient)
     return recipient.strip()
 
@@ -740,7 +759,7 @@ def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
     try:
         datetime.strptime(sent_at, _SENT_AT_FORMAT)
     except (TypeError, ValueError):
-        raise CalendarGateError("Italy OTP sent time is invalid") from None
+        raise BizLogicError("Italy OTP sent time is invalid") from None
     try:
         body = (api or VSCloudApi.Instance()).fetch_mail_content(
             email=mail_config.mailbox_for(recipient), sender=PRENOTAMI_OTP_SENDER, recipient=recipient,
@@ -748,9 +767,25 @@ def fetch_otp_from_cloud(mail_config, *, recipient, sent_at, api=None):
             sent_date=sent_at, expiry=mail_config.expiry_seconds, only_text=True,
         )
         return parse_otp_body(body)
-    except Exception as exc:
-        message = "not permitted" if isinstance(exc, PermissionDeniedError) else "read failed"
-        raise CalendarGateError(f"Italy OTP mailbox {message}") from None
+    except ItaProtocolError as exc:
+        raise BizLogicError(f"Italy OTP body invalid ({exc.code})") from None
+    except PermissionDeniedError:
+        raise PermissionDeniedError("Italy OTP mailbox not permitted") from None
+    except SessionExpiredOrInvalidError:
+        raise SessionExpiredOrInvalidError("Italy OTP mailbox session expired") from None
+    except RateLimiteddError:
+        raise RateLimiteddError("Italy OTP mailbox rate limited") from None
+    except NotFoundError:
+        raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
+    except BizLogicError as exc:
+        status = re.search(r"\bHTTP Error (\d{3})\b", str(getattr(exc, "message", "")))
+        if status and int(status.group(1)) == 404:
+            raise NotFoundError("Italy OTP email not found or mailbox not authorized") from None
+        if status and int(status.group(1)) in {408, 502, 503, 504}:
+            raise BizLogicError("Italy OTP mailbox provider timed out") from None
+        raise BizLogicError("Italy OTP mailbox read failed") from None
+    except Exception:
+        raise BizLogicError("Italy OTP mailbox read failed") from None
 
 
 def _wait_for_calendar(page, timeout=30):
@@ -760,7 +795,7 @@ def _wait_for_calendar(page, timeout=30):
             page.wait.doc_loaded()
             return
         time.sleep(0.25)
-    raise CalendarGateError("Italy AVANTI did not reach Calendar")
+    raise BizLogicError("Italy AVANTI did not reach Calendar")
 
 
 def prepare_calendar(plugin, route, *, role):
@@ -776,7 +811,7 @@ def prepare_calendar(plugin, route, *, role):
 
     def current(path):
         if plugin.page is not page or same_origin_path(page.url) != path:
-            raise CalendarGateError("Italy preparation page changed")
+            raise SessionExpiredOrInvalidError("Italy preparation page changed")
 
     def click(selector):
         current(booking_path)
@@ -814,11 +849,6 @@ SERVICES_PROBE_QUERY_MODE = "services_probe"
 CALENDAR_QUERY_MODE = "calendar"
 
 
-class ItaAuthenticationChallengeError(BizLogicError): pass
-class ItaTargetServiceLinkMissingError(BizLogicError): pass
-class ItaCalendarTransientError(BizLogicError): pass
-
-
 @dataclass(frozen=True, repr=False, eq=False)
 class _PreparedCalendar:
     username: str
@@ -842,7 +872,7 @@ class ItaLoginFlow(BaseFlow):
 
     @guard(predicate=lambda f: urlparse(f.page.url).hostname in RADWARE_VALIDATION_HOSTS, priority=1)
     def radware(self):
-        raise ItaAuthenticationChallengeError(
+        raise PermissionDeniedError(
             "Italy authentication requires Radware browser validation; automatic retry is disabled")
 
     @guard(predicate=lambda f: urlparse(f.page.url).scheme != "https" or
@@ -854,7 +884,7 @@ class ItaLoginFlow(BaseFlow):
     @guard(predicate=lambda f: any(value in f.page.html for value in (
         "Sorry, you have been blocked", "You are being rate limited", "error 1020")), priority=3)
     def blocked(self):
-        raise ItaAuthenticationChallengeError("Italy authentication was blocked; automatic retry is disabled")
+        raise PermissionDeniedError("Italy authentication was blocked; automatic retry is disabled")
 
     @guard(predicate=lambda f: any(value in f.page.html for value in (
         "502 Bad Gateway", "503 Service Temporarily Unavailable")), priority=4)
@@ -905,7 +935,7 @@ class ItaLoginFlow(BaseFlow):
 
 class ItaPlugin(IVSPlg):
     name = "ita_plugin"
-    version = "1.0.2"
+    version = "1.0.3"
     description = "意大利 Prenot@Mi 查询与预约插件"
 
     def __init__(self, group_id):
@@ -987,7 +1017,7 @@ class ItaPlugin(IVSPlg):
         try:
             self._prepared_calendar = _PreparedCalendar(
                 self.config.account.username.strip().casefold(), route.routing_key,
-                read_calendar_service(self.page), self.page.tab_id, role)
+                read_calendar_context(self.page)[0], self.page.tab_id, role)
         except Exception:
             self._prepared_calendar = None
             raise BizLogicError("Italy Calendar identity is unavailable") from None
@@ -995,7 +1025,7 @@ class ItaPlugin(IVSPlg):
     def _require_calendar_context(self, route, *, role, username=None):
         if not self._calendar_context_matches(route, role=role, username=username):
             raise BizLogicError("Italy Calendar Session changed")
-        if read_calendar_service(self.page) != self._prepared_calendar.runtime_service:
+        if read_calendar_context(self.page)[0] != self._prepared_calendar.runtime_service:
             raise BizLogicError("Italy Calendar service changed")
         return self._prepared_calendar
 
@@ -1003,21 +1033,6 @@ class ItaPlugin(IVSPlg):
         self.is_healthy = False
         self._prepared_calendar = None
 
-    def _calendar_failure(self, exc, role):
-        self._prepared_calendar = None
-        kinds = (
-            (CalendarAuthenticationExpiredError, SessionExpiredOrInvalidError, "Session expired"),
-            (CalendarRateLimitedError, RateLimiteddError, "rate limited"),
-            (CalendarAccessDeniedError, PermissionDeniedError, "access denied"),
-            (CalendarTransientError, ItaCalendarTransientError, "temporarily unavailable"),
-        )
-        for source, target, message in kinds:
-            if isinstance(exc, source):
-                if role == "Query" or source is CalendarAuthenticationExpiredError:
-                    self.is_healthy = False
-                return target(f"Italy {role} {message}")
-        return BizLogicError(f"Italy {role} failed: {exc}")
-
     def keep_alive(self):
         pass
 
@@ -1038,6 +1053,11 @@ class ItaPlugin(IVSPlg):
     def create_session(self):
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._invalidate_query_session()
+        account = getattr(self.config, "account", None)
+        username, password = getattr(account, "username", None), getattr(account, "password", None)
+        if (not isinstance(username, str) or not username.strip()
+                or not isinstance(password, str) or not password):
+            raise BizLogicError("Italy website username and password are required")
         options, self.tunnel = init_chromium_options(
             user_data_path=self.user_data_path,
             username_seed=self.config.account.username,
@@ -1054,27 +1074,27 @@ class ItaPlugin(IVSPlg):
         flow = ItaLoginFlow(self)
         try:
             flow.run(max_steps=40, timeout=120)
-        except BizLogicError:
+        except BizException:
             raise
         except Exception as exc:
             raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
 
     def query(self, apt_type):
-        if not self.health_check() or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
+        if self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
+            raise BizLogicError("Italy Query requires query_mode=calendar")
+        if not self.health_check():
             raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
         route = self._resolve_route(apt_type)
-        try:
-            if same_origin_path(self.page.url) != CALENDAR_PATH:
-                entry = self._enter_service(apt_type, route=route)
-                if not entry.success:
-                    return entry
-                self._reset_calendar_state()
-                prepare_calendar(self, route, role="query")
-            self._require_calendar_context(route, role="query")
-            probes = scan_until_first_available_month(
-                self.page, lookahead_months=route.lookahead_months, log=self._log)
-        except CalendarGateError as exc:
-            raise self._calendar_failure(exc, "Query") from None
+        if same_origin_path(self.page.url) != CALENDAR_PATH:
+            entry = self._enter_service(apt_type, route=route)
+            if not entry.success:
+                return entry
+            self._reset_calendar_state()
+            prepare_calendar(self, route, role="query")
+        self._require_calendar_context(route, role="query")
+        probes = scan_until_first_available_month(
+            self.page, lookahead_months=route.lookahead_months, log=self._log,
+            check_current=lambda: self._require_calendar_context(route, role="query"))
         available = available_calendar_days(probes[-1])
         if not available:
             return VSQueryResult(
@@ -1097,7 +1117,7 @@ class ItaPlugin(IVSPlg):
             raise BizLogicError("Italy service list is unavailable")
         link = self.page.ele(f"tag:a@@href={booking_path}", timeout=SERVICE_LINK_WAIT_SECONDS)
         if not link:
-            raise ItaTargetServiceLinkMissingError(f"Italy service link is missing: {booking_path}")
+            raise NotFoundError(f"Italy service link is missing: {booking_path}")
         self.mouse.human_click_ele(link)
         self.page.wait.load_start()
         self.page.wait.doc_loaded()
@@ -1132,19 +1152,16 @@ class ItaPlugin(IVSPlg):
             if not entry.success:
                 return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
             prepare_calendar(self, route, role="book")
-        try:
-            start, end = book_date_preferences(inputs)
-            slot = recheck_calendar_before_final(
-                self.page,
-                lookahead_months=route.lookahead_months,
-                start_day=start,
-                end_day=end,
-                session_is_current=lambda: self._calendar_context_matches(
-                    route, role="book", username=username),
-                log=self._log,
-            )
-        except CalendarGateError as exc:
-            raise self._calendar_failure(exc, "Book") from None
+        start, end = book_date_preferences(inputs)
+        slot = recheck_calendar_before_final(
+            self.page,
+            lookahead_months=route.lookahead_months,
+            start_day=start,
+            end_day=end,
+            session_is_current=lambda: self._calendar_context_matches(
+                route, role="book", username=username),
+            log=self._log,
+        )
         if not slot:
             return VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
         self._log(f"Italy Book selected {slot.day} {slot.time_label}")
@@ -1160,14 +1177,21 @@ class ItaPlugin(IVSPlg):
 
     def get_plugin_status(self):
         proxy = self.config.proxy if self.config else None
+        current_url = ""
+        if self.page:
+            try:
+                current_url = str(self.page.url)
+            except Exception:
+                pass  # Status reporting must still work after browser disconnection.
         return PluginStatus(
             instance_id=self.instance_id,
             is_healthy=self.is_healthy,
             state="running" if self.is_healthy else "unhealthy",
-            current_url=str(self.page.url if self.page else ""),
+            current_url=current_url,
             account=self.config.account.username if self.config else "",
             proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
-            session_age_sec=0,
+            session_age_sec=max(0, int(time.time() - self.session_create_time))
+                if self.session_create_time > 0 else 0,
             last_active_at=utc_now_str(),
         )