version = 24
import ast
import asyncio
import base64
import contextvars
import functools
import fnmatch
import hashlib
import hmac
import ipaddress
import json
import os
import socket
import ssl

try:
    import certifi
except ImportError:
    certifi = None
import subprocess
import sys
import tempfile
import threading
import time
import traceback
import urllib.parse
from collections import deque
from datetime import datetime
from typing import Any, Optional


# =========================
# HOSTER SETTINGS (edit these)
# =========================
#
# Hostish intentionally keeps this file editable.
#
# QUICK START
# -----------
# 1. Set USERNAME and PASSWORD.
# 2. Choose MODE: "static", "proxy", or "hybrid".
# 3. For static/hybrid hosting, set WEBSITE_DIR.
# 4. For proxy/hybrid hosting, set UPSTREAM_BASE (or PORT).
# 5. Run:
#
#      python agent.py
#
# ROOT CUSTOM DOMAINS
# -------------------
# A linked root custom domain such as example.com automatically uses the
# primary-site settings below. You do NOT add example.com to HOST_ROUTES.
#
# EXPLICIT SUBDOMAINS
# -------------------
# A hostname such as api.example.com or dev.username.hostish.site must be
# listed in HOST_ROUTES before it can be linked in Hostish.
#
# LIMITS
# ------
# Numeric settings documented as "0 = unlimited" are controlled locally by
# this agent.
#
# PATH NOTES
# ----------
# Windows:
#     r"C:\Users\you\Desktop\site"
#
# Linux/macOS:
#     r"/home/you/site"
#
# SECURITY
# --------
# Keep UPSTREAM_NETWORK_POLICY = "loopback" unless you intentionally need to
# proxy to another machine. STATIC_SECURITY_MODE = "safe" is recommended.


# ============================================================
# 1) ACCOUNT
# ============================================================

USERNAME = "your_username"
PASSWORD = "your_password"


# ============================================================
# 2) PRIMARY SITE
# ============================================================

# "static"
#     Serve files directly from WEBSITE_DIR.
#
#     Example:
#         MODE = "static"
#         WEBSITE_DIR = r"/home/you/my-site"
#
# "proxy"
#     Forward all requests to a local HTTP application.
#
#     Example:
#         MODE = "proxy"
#         PORT = 5000
#         UPSTREAM_BASE = f"http://127.0.0.1:{PORT}"
#
# "hybrid"
#     Serve files normally, but proxy selected URL prefixes.
#
#     Example:
#         MODE = "hybrid"
#         WEBSITE_DIR = r"/home/you/site"
#         PROXY_PREFIXES = ["api/"]
#         UPSTREAM_BASE = "http://127.0.0.1:5000"
#
MODE = "hybrid"

# Windows example:
# WEBSITE_DIR = r"C:\Users\you\Desktop\website"
#
# Linux/macOS example:
# WEBSITE_DIR = r"/home/you/website"
#
WEBSITE_DIR = r"C:\path\to\site"

# Default local application for proxy requests.
PORT = 5000
UPSTREAM_BASE = f"http://127.0.0.1:{PORT}"

# Send selected URL prefixes to different local applications.
# The longest matching prefix wins.
#
# Example:
#
# UPSTREAM_ROUTES = {
#     # /api/ai/* -> port 8424
#     "api/ai/": "http://127.0.0.1:8424",
#
#     # Other /api/* -> port 5001
#     "api/": "http://127.0.0.1:5001",
#
#     # /socket.io/* -> port 3001
#     "socket.io/": "http://127.0.0.1:3001",
# }
#
# Requests that do not match an entry use UPSTREAM_BASE.
UPSTREAM_ROUTES = {}

# Hybrid mode only: these path prefixes are proxied instead of served from
# WEBSITE_DIR.
#
# Example:
#
# PROXY_PREFIXES = [
#     "api/",
#     "socket.io/",
#     "backend/",
# ]
#
PROXY_PREFIXES = [
    "api/",
]


# ============================================================
# 3) CUSTOM DOMAINS / EXPLICIT SUBDOMAINS
# ============================================================

# ROOT CUSTOM DOMAIN EXAMPLE
# --------------------------
# If example.com is linked in the Hostish dashboard:
#
#     https://example.com/
#
# it automatically uses the PRIMARY SITE settings above.
# Do NOT add example.com to HOST_ROUTES.
#
# EXPLICIT SUBDOMAIN EXAMPLES
# ---------------------------
# HOST_ROUTES is for separately linked hostnames that need their own behavior.
#
# HOST_ROUTES = {
#     # Custom subdomain -> local API
#     "api.example.com": {
#         "mode": "proxy",
#         "upstream": "http://127.0.0.1:5001",
#     },
#
#     # Custom subdomain -> separate static directory
#     "files.example.com": {
#         "mode": "static",
#         "website_dir": r"/home/you/public-files",
#     },
#
#     # Explicit Hostish subdomain -> local development server
#     "dev.yourusername.hostish.site": {
#         "mode": "proxy",
#         "upstream": "http://127.0.0.1:3000",
#     },
#
#     # Subdomain with its own hybrid setup
#     "app.example.com": {
#         "mode": "hybrid",
#         "website_dir": r"/home/you/app/site",
#         "upstream": "http://127.0.0.1:7000",
#         "proxy_prefixes": [
#             "api/",
#             "socket.io/",
#         ],
#         "upstream_routes": {
#             "api/admin/": "http://127.0.0.1:7001",
#             "api/": "http://127.0.0.1:7000",
#             "socket.io/": "http://127.0.0.1:7002",
#         },
#     },
# }
#
# Compact proxy-only form:
#
# HOST_ROUTES = {
#     "api.example.com": "http://127.0.0.1:5001",
# }
#
HOST_ROUTES = {}


# ============================================================
# 4) PROXY SECURITY / CONNECTION REUSE
# ============================================================

# "loopback" -> localhost / 127.0.0.0/8 / ::1 only.
# "private"  -> loopback plus private/link-local LAN targets.
# "any"      -> any intentionally configured DNS/IP target.
UPSTREAM_NETWORK_POLICY = "loopback"

PROXY_KEEPALIVE_ENABLED = True
PROXY_MAX_IDLE_CONNECTIONS = 8
PROXY_IDLE_CONNECTION_SECONDS = 60


# ============================================================
# 5) HOSTER-CONTROLLED LIMITS / TIMEOUTS
# ============================================================

# 0 = unlimited.
MAX_CONCURRENT_REQUESTS = 0
MAX_QUEUED_REQUESTS = 0
MAX_REQUEST_BODY_BYTES = 0
MAX_FILE_BYTES = 0
MAX_PROXY_BYTES = 0

UPSTREAM_CONNECT_TIMEOUT_SECONDS = 30

# 0 = unlimited. Good for long-running APIs, AI generation, and SSE.
UPSTREAM_RESPONSE_TIMEOUT_SECONDS = 0


# ============================================================
# 6) HOSTISH TUNNEL / STREAMING
# ============================================================

WS_URL = "wss://hostish.site/ws/host"

# Current preferred protocol.
TUNNEL_PROTOCOL = 3

# Per-message/read sizes. These are not total transfer limits.
TUNNEL_CHUNK_BYTES = 256 * 1024
WEBSOCKET_MAX_INCOMING_BYTES = 4 * 1024 * 1024
REQUEST_STREAM_BUFFER_CHUNKS = 8

USER_WEBSOCKET_PROXY_ENABLED = True

PROXY_READ_CHUNK_BYTES = 256 * 1024
STATIC_READ_CHUNK_BYTES = 256 * 1024


# ============================================================
# 7) HTTP / CORS
# ============================================================

HANDLE_OPTIONS_LOCALLY = True

ADD_CORS_HEADER_TO_RESPONSES = True
CORS_ALLOW_ORIGIN = "*"
CORS_ALLOW_METHODS = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
CORS_ALLOW_HEADERS = "Content-Type, Authorization, Origin, Accept"

# Restrictive example:
# CORS_ALLOW_ORIGIN = "https://example.com"


# ============================================================
# 8) STATIC FILES / BROWSER CACHING / SECURITY
# ============================================================

# Examples:
# STATIC_CACHE_CONTROL = "no-store"
# STATIC_CACHE_CONTROL = "public, max-age=300"
# STATIC_CACHE_CONTROL = "public, max-age=31536000, immutable"
STATIC_CACHE_CONTROL = "no-store"

# "safe"         -> recommended secret/source-control blocking.
# "custom"       -> use the patterns below.
# "unrestricted" -> any contained file under WEBSITE_DIR.
STATIC_SECURITY_MODE = "safe"

STATIC_ALLOW_PATTERNS = [
    ".well-known/**",
]

STATIC_BLOCK_PATTERNS = [
    ".env",
    ".env.*",
    ".git/**",
    ".svn/**",
    ".hg/**",
    ".ssh/**",
    "**/*.pem",
    "**/*.key",
    "**/id_rsa",
    "**/id_ed25519",
    "**/credentials.json",
]

ALLOW_STATIC_SYMLINK_ESCAPE = False


# ============================================================
# 9) SPECIAL FILE / ERROR BEHAVIOR
# ============================================================

# Example:
# FAVICON_BYPASS_ENABLED = True
# FAVICON_BYPASS_URL = "https://example.com/favicon.ico"
FAVICON_BYPASS_ENABLED = False
FAVICON_BYPASS_URL = ""
FAVICON_MAX_BYTES = 2 * 1024 * 1024

# Example:
# CUSTOM_404_ENABLED = True
# CUSTOM_404_PATH = r"404.html"
CUSTOM_404_ENABLED = False
CUSTOM_404_PATH = r"404.html"


# ============================================================
# 10) TEXTUAL PUBLIC-IP MASKING
# ============================================================

IP_PROTECTION_ENABLED = False
IP_PROTECTION_REFRESH_SECONDS = 300
IP_PROTECTION_REPLACEMENT = "BLOCKED"


# ============================================================
# 11) AUTO-START LOCAL PYTHON SCRIPTS
# ============================================================

# Starts companion .py programs with the same Python interpreter as this
# agent. Each script runs from its own directory and is terminated when the
# Hostish agent exits.
#
# Windows example:
#
# AUTO_START_PYTHON_SCRIPTS_ENABLED = True
# AUTO_START_PYTHON_SCRIPTS = [
#     r"C:\Users\you\Desktop\site\backend.py",
#     r"C:\Users\you\Desktop\site\websocket_server.py",
# ]
#
# Linux/macOS example:
#
# AUTO_START_PYTHON_SCRIPTS_ENABLED = True
# AUTO_START_PYTHON_SCRIPTS = [
#     r"/home/you/site/backend.py",
#     r"/home/you/site/worker.py",
# ]
#
AUTO_START_PYTHON_SCRIPTS_ENABLED = False

AUTO_START_PYTHON_SCRIPTS = [
    # r"C:\path\to\backend.py",
    # r"/home/you/site/backend.py",
]


# ============================================================
# 12) SELF UPDATE
# ============================================================

LATEST_AGENT_URL = "https://hostish.site/downloads/agent.py"

SELF_UPDATE_ENABLED = True
SELF_UPDATE_BACKUP_ENABLED = True
SELF_UPDATE_BACKUP_DIR = ".hostish-agent-backups"
SELF_UPDATE_BACKUP_KEEP = 5

SELF_UPDATE_DOWNLOAD_TIMEOUT_SECONDS = 30
SELF_UPDATE_MAX_DOWNLOAD_BYTES = 10 * 1024 * 1024
SELF_UPDATE_REQUIRE_HTTPS = True
SELF_UPDATE_ALLOW_CROSS_HOST_REDIRECTS = False

# Optional SHA-256 pin for a custom update source.
SELF_UPDATE_EXPECTED_SHA256 = ""

# Optional Ed25519 update signatures. Requires cryptography when enabled.
SELF_UPDATE_ED25519_PUBLIC_KEY_PEM = ""
SELF_UPDATE_SIGNATURE_SUFFIX = ".sig"

SELF_UPDATE_NONINTERACTIVE_ACTION = "continue"

# Assignments inside HOSTER SETTINGS are preserved automatically.
#
# Example:
# SELF_UPDATE_PRESERVE_EXTRA_NAMES = [
#     "MY_CUSTOM_SETTING",
# ]
#
SELF_UPDATE_PRESERVE_EXTRA_NAMES = []


# ============================================================
# 13) LOGGING / DIAGNOSTICS
# ============================================================

PRINT_REQUEST_HEADERS = False
PRINT_REQUEST_BODY_PREVIEW = False
BODY_PREVIEW_BYTES = 120

# WARNING: enabling this may print credentials, cookies, or API tokens.
PRINT_SENSITIVE_HEADERS = False

SENSITIVE_HEADER_NAMES = {
    "authorization",
    "cookie",
    "set-cookie",
    "proxy-authorization",
    "x-api-key",
    "x-auth-token",
}

PERIODIC_SUMMARY_ENABLED = False
PERIODIC_SUMMARY_SECONDS = 60

REPEAT_ERROR_SUMMARY_EVERY = 10


# ============================================================
# 14) IDLE CONNECTION HEALTH CHECK
# ============================================================

# If enabled, an idle agent periodically asks Hostish whether its authenticated
# tunnel is still registered as hosting. It does NOT restart because a status
# request times out/fails. A recovery restart only happens after TWO explicit
# offline responses while the local WebSocket still believes it is connected.
IDLE_STATUS_CHECK_ENABLED = True

# Check after this many seconds without a visitor request.
IDLE_CHECK_INTERVAL_SECONDS = 120


# =========================

# NOTE: This script uses the "websockets" package (not in Python stdlib).
# Install once (host machine):
#   python -m pip install websockets
try:
    import websockets
except ImportError:
    print("Missing dependency: websockets")
    print("Install with: python -m pip install websockets")
    sys.exit(1)


HOP_BY_HOP = {
    "connection",
    "keep-alive",
    "proxy-authenticate",
    "proxy-authorization",
    "te",
    "trailers",
    "transfer-encoding",
    "upgrade",
}


# Runtime stats.
START_TS = time.time()
CONNECT_COUNT = 0
TOTAL_REQS = 0
TOTAL_BYTES_SENT = 0
RECENT_EVENTS = deque(maxlen=50)
CURRENT_REQS = 0
LAST_REQUEST_TS = time.time()
HAS_RECEIVED_REQUEST = False
IS_WS_CONNECTED = False

# Runtime counters.
STATIC_REQS = 0
PROXY_REQS = 0
STATUS_COUNTS = {}
LAST_SUMMARY_SNAPSHOT = {"reqs": 0, "bytes": 0}

# Repeated error suppression.
_REPEAT_ERRORS = {}

# Auto-started companion scripts.
_MANAGED_SCRIPT_PROCS = []
_AUTO_START_ALREADY_RAN = False

# Agent-version cache.
VERSION_CACHE_COOLDOWN_SECONDS = 30

# If the user chooses "continue" when an update is offered, remember that
# choice only for the lifetime of this launched agent session. Internal
# os.execv/subprocess restarts inherit this environment variable, while a
# later manual launch from the user's shell starts clean and prompts again.
_SESSION_UPDATE_SKIP_ENV = "HOSTISH_SESSION_SKIP_UPDATE_VERSION"

_version_cache = {
    "last_fetch_ts": 0.0,
    "newest_version": None,
    "status": "unknown",
    "error": None,
}

# Public-IP cache.
PUBLIC_IP_CHECK_URLS = [
    "https://api.ipify.org",
    "https://checkip.amazonaws.com",
    "https://ipv4.icanhazip.com",
]
_public_ip_cache = {
    "last_fetch_ts": 0.0,
    "ip": None,
    "error": None,
}

# Favicon cache.
_favicon_cache = {
    "body": None,
    "content_type": "image/x-icon",
    "fetched": False,
}

# Per-worker-thread localhost HTTP connection cache. http.client connections are
# used by synchronous proxy work running in asyncio's thread pool, so keeping the
# cache thread-local avoids cross-thread connection races.
_proxy_thread_local = threading.local()


def ts() -> str:
    return datetime.now().strftime("%Y-%m-%d %H:%M:%S")


def log(msg: str) -> None:
    print(f"[{ts()}] {msg}", flush=True)


def log_event(msg: str) -> None:
    RECENT_EVENTS.appendleft(f"[{ts()}] {msg}")
    log(msg)


def make_ssl_context() -> ssl.SSLContext:
    """
    Create a TLS context for HTTPS/WSS.
    certifi is preferred because some Python/OpenSSL installs reject
    browser-valid chains.
    """
    if certifi is not None:
        return ssl.create_default_context(cafile=certifi.where())
    return ssl.create_default_context()


def fmt_bytes(n: int) -> str:
    n = int(n or 0)
    if n < 1024:
        return f"{n} B"
    if n < 1024 * 1024:
        return f"{n / 1024:.1f} KB"
    if n < 1024 * 1024 * 1024:
        return f"{n / (1024 * 1024):.1f} MB"
    return f"{n / (1024 * 1024 * 1024):.2f} GB"


def uptime_s() -> int:
    return int(time.time() - START_TS)


def _status_count_inc(code: int) -> None:
    key = str(int(code))
    STATUS_COUNTS[key] = STATUS_COUNTS.get(key, 0) + 1


def _status_count_top() -> str:
    if not STATUS_COUNTS:
        return "none"

    parts = []
    for key, value in sorted(
        STATUS_COUNTS.items(),
        key=lambda item: (-item[1], item[0]),
    )[:6]:
        parts.append(f"{key}:{value}")

    return ", ".join(parts)


def log_repeatable_error(key: str, message: str) -> None:
    """
    Suppress repeated identical errors. Prints the first occurrence and then
    prints summaries every configured number of repeats.
    """
    now_ts = time.time()
    entry = _REPEAT_ERRORS.get(key)

    if entry is None:
        _REPEAT_ERRORS[key] = {
            "count": 1,
            "last": message,
            "last_ts": now_ts,
        }
        log_event(message)
        return

    if entry["last"] == message:
        entry["count"] += 1
        entry["last_ts"] = now_ts

        if entry["count"] % REPEAT_ERROR_SUMMARY_EVERY == 0:
            log_event(f"[repeat x{entry['count']}] {message}")
    else:
        previous_count = entry["count"]
        previous_message = entry["last"]

        if previous_count > 1:
            log(
                f"Previous repeated error ended after "
                f"{previous_count}x: {previous_message}"
            )

        entry["count"] = 1
        entry["last"] = message
        entry["last_ts"] = now_ts
        log_event(message)


async def run_in_thread(func, *args):
    """Run blocking work while preserving per-request hostname routing context."""
    loop = asyncio.get_running_loop()
    context = contextvars.copy_context()
    call = functools.partial(context.run, func, *args)
    return await loop.run_in_executor(None, call)


def _normalize_ip_text(raw: str) -> Optional[str]:
    value = (raw or "").strip()

    if not value:
        return None

    value = value.splitlines()[0].strip().split()[0].strip()

    try:
        ipaddress.ip_address(value)
        return value
    except Exception:
        return None


def fetch_public_ip(force: bool = False) -> Optional[str]:
    """
    Fetch and cache the current public IP.
    """
    now_ts = time.time()
    age = now_ts - float(
        _public_ip_cache.get("last_fetch_ts", 0.0) or 0.0
    )

    if (
        not force
        and age < int(IP_PROTECTION_REFRESH_SECONDS)
    ):
        return _public_ip_cache.get("ip")

    import urllib.request

    last_error = None

    for url in PUBLIC_IP_CHECK_URLS:
        try:
            request = urllib.request.Request(
                url,
                headers={"User-Agent": f"HostishAgent/{version}"},
                method="GET",
            )

            with urllib.request.urlopen(
                request,
                timeout=8,
                context=make_ssl_context(),
            ) as response:
                raw = response.read(256).decode(
                    "utf-8",
                    errors="replace",
                )

            public_ip = _normalize_ip_text(raw)

            if not public_ip:
                raise ValueError("invalid IP response")

            old_ip = _public_ip_cache.get("ip")
            _public_ip_cache["last_fetch_ts"] = now_ts
            _public_ip_cache["ip"] = public_ip
            _public_ip_cache["error"] = None

            if old_ip != public_ip:
                if old_ip is None:
                    log("[INFO] IP protection cached public IP")
                else:
                    log(
                        "[INFO] IP protection detected public IP change "
                        "and refreshed cache"
                    )

            return public_ip
        except Exception as error:
            last_error = f"{type(error).__name__}: {error}"

    _public_ip_cache["last_fetch_ts"] = now_ts
    _public_ip_cache["error"] = last_error
    return _public_ip_cache.get("ip")


def _public_ip_status_text() -> str:
    if not IP_PROTECTION_ENABLED:
        return "IP protection OFF"

    public_ip = _public_ip_cache.get("ip")

    if public_ip:
        return "IP protection ON (public IP cached)"

    return "IP protection ON (public IP not cached yet)"


async def periodic_public_ip_refresh_loop() -> None:
    while True:
        await asyncio.sleep(
            max(30, int(IP_PROTECTION_REFRESH_SECONDS))
        )

        if not IP_PROTECTION_ENABLED:
            continue

        old_ip = _public_ip_cache.get("ip")
        new_ip = await run_in_thread(fetch_public_ip, True)

        if new_ip is None:
            error = _public_ip_cache.get("error") or "unknown error"
            log_repeatable_error(
                "public_ip_refresh",
                f"IP protection refresh failed: {error}",
            )
        elif old_ip != new_ip:
            log_event("[INFO] IP protection cache updated")


def _mask_public_ip_in_bytes(
    data: bytes,
    public_ip: str,
) -> tuple[bytes, int]:
    if not data or not public_ip:
        return data, 0

    source = public_ip.encode("utf-8")

    if not source:
        return data, 0

    count = data.count(source)

    if count <= 0:
        return data, 0

    replacement_string = IP_PROTECTION_REPLACEMENT.ljust(
        len(public_ip)
    )
    replacement = replacement_string.encode("utf-8")

    return data.replace(source, replacement), count


def _mask_public_ip_in_headers(
    headers: dict,
    public_ip: str,
) -> tuple[dict, int]:
    if not headers or not public_ip:
        return headers or {}, 0

    replaced = 0
    output = {}
    replacement = IP_PROTECTION_REPLACEMENT.ljust(len(public_ip))

    for key, value in (headers or {}).items():
        key_string = str(key)
        value_string = str(value)
        count = value_string.count(public_ip)

        if count > 0:
            value_string = value_string.replace(
                public_ip,
                replacement,
            )
            replaced += count

        output[key_string] = value_string

    return output, replaced


def _apply_ip_protection_to_response(
    req_id: Any,
    status: int,
    headers: dict,
    body: bytes,
    meta: dict,
) -> tuple[int, dict, bytes, dict]:
    if not IP_PROTECTION_ENABLED:
        return status, headers, body, meta

    public_ip = fetch_public_ip(force=False)
    if not public_ip:
        return status, headers, body, meta

    content_type = ""
    for key, value in (headers or {}).items():
        if str(key).lower() == "content-type":
            content_type = str(value).split(";", 1)[0].strip().lower()
            break

    textual = (
        content_type.startswith("text/")
        or content_type in {
            "application/json", "application/ld+json", "application/javascript",
            "application/x-javascript", "application/xml", "application/xhtml+xml",
            "application/graphql-response+json", "application/x-www-form-urlencoded",
        }
        or content_type.endswith("+json")
        or content_type.endswith("+xml")
    )

    new_headers, header_hits = _mask_public_ip_in_headers(headers or {}, public_ip)
    if textual:
        new_body, body_hits = _mask_public_ip_in_bytes(body or b"", public_ip)
    else:
        new_body, body_hits = body or b"", 0

    total_hits = header_hits + body_hits
    if total_hits <= 0:
        return status, new_headers, new_body, meta

    for header_key in list(new_headers.keys()):
        if header_key.lower() == "content-length":
            new_headers[header_key] = str(len(new_body))

    new_meta = dict(meta or {})
    new_meta["ip_protection_hits"] = total_hits
    new_meta["ip_protection_body_hits"] = body_hits
    new_meta["ip_protection_header_hits"] = header_hits
    return status, new_headers, new_body, new_meta

def _normalize_script_path(path: str) -> str:
    path = os.path.expanduser(str(path).strip())
    return os.path.abspath(path)


def start_configured_python_scripts_once() -> None:
    """
    Start each configured Python script once when the agent boots.
    """
    global _AUTO_START_ALREADY_RAN

    if _AUTO_START_ALREADY_RAN:
        return

    _AUTO_START_ALREADY_RAN = True

    if not AUTO_START_PYTHON_SCRIPTS_ENABLED:
        return

    scripts = AUTO_START_PYTHON_SCRIPTS

    if not isinstance(scripts, (list, tuple)):
        log(
            "[ERROR] AUTO_START_PYTHON_SCRIPTS "
            "must be a list or tuple"
        )
        return

    if not scripts:
        log(
            "[INFO] Auto start scripts enabled, "
            "but list is empty"
        )
        return

    started_count = 0

    for raw_path in scripts:
        try:
            if raw_path is None:
                continue

            script_path = _normalize_script_path(raw_path)

            if not script_path.lower().endswith(".py"):
                log(
                    f"[INFO] Auto start skipped "
                    f"(not .py): {script_path}"
                )
                continue

            if not os.path.isfile(script_path):
                log(
                    f"[INFO] Auto start skipped "
                    f"(missing file): {script_path}"
                )
                continue

            workdir = os.path.dirname(script_path) or None
            popen_kwargs = {"cwd": workdir}

            if os.name == "nt":
                popen_kwargs["creationflags"] = getattr(
                    subprocess,
                    "CREATE_NO_WINDOW",
                    0,
                )

            process = subprocess.Popen(
                [sys.executable, script_path],
                **popen_kwargs,
            )

            _MANAGED_SCRIPT_PROCS.append(
                {
                    "path": script_path,
                    "proc": process,
                    "started_at": time.time(),
                    "exit_logged": False,
                }
            )

            started_count += 1

            log_event(
                f"[INFO] Auto started Python script "
                f"pid={process.pid} path='{script_path}'"
            )
        except Exception as error:
            log_repeatable_error(
                "auto_start_script",
                f"Auto start failed for script '{raw_path}': "
                f"{type(error).__name__}: {error}",
            )

    log(
        f"[INFO] Auto start complete | started={started_count} "
        f"requested={len(scripts)}"
    )


async def managed_script_monitor_loop() -> None:
    while True:
        await asyncio.sleep(3)

        if not _MANAGED_SCRIPT_PROCS:
            continue

        for entry in list(_MANAGED_SCRIPT_PROCS):
            process = entry.get("proc")

            if process is None:
                continue

            try:
                return_code = process.poll()
            except Exception as error:
                log_repeatable_error(
                    "managed_script_poll",
                    f"Managed script poll failed for "
                    f"'{entry.get('path')}': "
                    f"{type(error).__name__}: {error}",
                )
                continue

            if return_code is None:
                continue

            if not entry.get("exit_logged"):
                entry["exit_logged"] = True
                log_event(
                    f"[WARN] Auto started script exited "
                    f"pid={process.pid} code={return_code} "
                    f"path='{entry.get('path')}'"
                )


def stop_managed_scripts() -> None:
    if not _MANAGED_SCRIPT_PROCS:
        return

    log("[INFO] Stopping auto started scripts...")

    for entry in _MANAGED_SCRIPT_PROCS:
        process = entry.get("proc")

        if not process:
            continue

        try:
            if process.poll() is None:
                process.terminate()
        except Exception:
            pass

    deadline = time.time() + 3.0

    while time.time() < deadline:
        all_done = True

        for entry in _MANAGED_SCRIPT_PROCS:
            process = entry.get("proc")

            if not process:
                continue

            try:
                if process.poll() is None:
                    all_done = False
                    break
            except Exception:
                pass

        if all_done:
            break

        time.sleep(0.1)

    for entry in _MANAGED_SCRIPT_PROCS:
        process = entry.get("proc")

        if not process:
            continue

        try:
            if process.poll() is None:
                process.kill()
        except Exception:
            pass


def print_startup_banner() -> None:
    width = 72
    log("+" + ("-" * (width - 2)) + "+")
    log("|" + "HOSTISH AGENT BOOTING".center(width - 2) + "|")
    log("+" + ("-" * (width - 2)) + "+")
    log(f" - Version         : {version}")
    log(f" - Username        : {USERNAME}")
    log(f" - Mode            : {MODE}")
    log(f" - Website dir     : {WEBSITE_DIR}")
    log(f" - Port            : {PORT}")
    log(
        f" - Idle check      : "
        f"{'ON' if IDLE_STATUS_CHECK_ENABLED else 'OFF'} "
        f"({IDLE_CHECK_INTERVAL_SECONDS}s)"
    )
    log(
        f" - Custom Favicon  : "
        f"{'ON' if FAVICON_BYPASS_ENABLED else 'OFF'}"
    )
    if FAVICON_BYPASS_ENABLED:
        log(f" - Favicon URL     : {FAVICON_BYPASS_URL}")

    log(
        f" - Custom 404      : "
        f"{'ON' if CUSTOM_404_ENABLED else 'OFF'}"
    )
    log(f" - Custom 404 path : {CUSTOM_404_PATH}")
    log(f" - IP protection   : {_public_ip_status_text()}")
    log(
        " - Auto start py   : "
        + ("ON" if AUTO_START_PYTHON_SCRIPTS_ENABLED else "OFF")
        + (
            f" ({len(AUTO_START_PYTHON_SCRIPTS)} configured)"
            if isinstance(AUTO_START_PYTHON_SCRIPTS, (list, tuple))
            else " (0 configured)"
        )
    )

    if MODE in ("proxy", "hybrid"):
        log(f" - Upstream base   : {UPSTREAM_BASE}")
        log(
            f" - Proxy keepalive : "
            f"{'ON' if PROXY_KEEPALIVE_ENABLED else 'OFF'}"
        )
        if isinstance(UPSTREAM_ROUTES, dict) and UPSTREAM_ROUTES:
            log(f" - Upstream routes : {len(UPSTREAM_ROUTES)} configured")

    if isinstance(HOST_ROUTES, dict) and HOST_ROUTES:
        log(f" - Host routes     : {len(HOST_ROUTES)} configured")

    log(f" - Tunnel protocol : v{TUNNEL_PROTOCOL} preferred")
    log(
        " - Concurrency     : "
        + ("unlimited" if int(MAX_CONCURRENT_REQUESTS) <= 0 else str(MAX_CONCURRENT_REQUESTS))
        + " active | queue="
        + ("unlimited" if int(MAX_QUEUED_REQUESTS) <= 0 else str(MAX_QUEUED_REQUESTS))
    )
    log(f" - Static cache    : {STATIC_CACHE_CONTROL}")
    log(f" - Static security : {STATIC_SECURITY_MODE}")
    log(f" - Proxy network   : {UPSTREAM_NETWORK_POLICY}")
    log(
        " - Request limit   : "
        + ("unlimited" if int(MAX_REQUEST_BODY_BYTES) <= 0 else fmt_bytes(MAX_REQUEST_BODY_BYTES))
    )
    log(
        " - Static limit    : "
        + ("unlimited" if int(MAX_FILE_BYTES) <= 0 else fmt_bytes(MAX_FILE_BYTES))
    )
    log(
        " - Proxy limit     : "
        + ("unlimited" if int(MAX_PROXY_BYTES) <= 0 else fmt_bytes(MAX_PROXY_BYTES))
    )
    log(
        " - Response timeout: "
        + (
            "unlimited"
            if float(UPSTREAM_RESPONSE_TIMEOUT_SECONDS) <= 0
            else str(UPSTREAM_RESPONSE_TIMEOUT_SECONDS) + "s"
        )
    )
    log(f" - User WebSockets : {'ON' if USER_WEBSOCKET_PROXY_ENABLED else 'OFF'}")

    if MODE == "hybrid":
        log(f" - Proxy prefixes  : {PROXY_PREFIXES}")

    log(f" - Public site URL : https://{USERNAME}.hostish.site/")
    log(f" - Checked version : {version_status_text()}")
    log(
        " - Self update     : "
        + ("ON" if SELF_UPDATE_ENABLED else "OFF")
        + f" | backups={'ON' if SELF_UPDATE_BACKUP_ENABLED else 'OFF'}"
    )
    log("-" * width)


def print_ascii_art() -> None:
    art = (
        " _   _           _   _     _\n"
        "| | | | ___  ___| |_(_)___| |__\n"
        "| |_| |/ _ \\/ __| __| / __| '_ \\\n"
        "|  _  | (_) \\__ \\ |_| \\__ \\ | | |\n"
        "|_| |_|\\___/|___/\\__|_|___/_| |_|"
    )
    for line in art.splitlines():
        log(line)


def print_summary() -> None:
    log(
        "[STATS] Summary | "
        f"uptime={uptime_s()}s | "
        f"conns={CONNECT_COUNT} | "
        f"reqs={TOTAL_REQS} | "
        f"static={STATIC_REQS} | "
        f"proxy={PROXY_REQS} | "
        f"sent={fmt_bytes(TOTAL_BYTES_SENT)} | "
        f"inflight={CURRENT_REQS} | "
        f"stats=[{_status_count_top()}]"
    )


def print_periodic_delta_summary() -> None:
    previous_requests = LAST_SUMMARY_SNAPSHOT.get(
        "reqs",
        0,
    )
    previous_bytes = LAST_SUMMARY_SNAPSHOT.get(
        "bytes",
        0,
    )

    request_delta = TOTAL_REQS - previous_requests
    byte_delta = TOTAL_BYTES_SENT - previous_bytes

    LAST_SUMMARY_SNAPSHOT["reqs"] = TOTAL_REQS
    LAST_SUMMARY_SNAPSHOT["bytes"] = TOTAL_BYTES_SENT

    log(
        "[STATS] Periodic | "
        f"window={PERIODIC_SUMMARY_SECONDS}s | "
        f"reqs={request_delta} | "
        f"bytes={fmt_bytes(byte_delta)} | "
        f"total_reqs={TOTAL_REQS} | "
        f"inflight={CURRENT_REQS} | "
        f"statuses=[{_status_count_top()}]"
    )


async def periodic_summary_loop() -> None:
    while True:
        await asyncio.sleep(
            max(5, int(PERIODIC_SUMMARY_SECONDS))
        )

        if PERIODIC_SUMMARY_ENABLED:
            print_periodic_delta_summary()


def _extract_version_from_first_line(
    line: str,
) -> Optional[int]:
    """
    Expect the first line to look like: version = 15
    """
    if not isinstance(line, str):
        return None

    value = line.strip()

    if not value.lower().startswith("version"):
        return None

    parts = value.split("=", 1)

    if len(parts) != 2:
        return None

    right_hand_side = parts[1].strip()
    right_hand_side = right_hand_side.strip("\"' ")

    if right_hand_side.isdigit():
        return int(right_hand_side)

    return None


def fetch_latest_agent_version(
    force: bool = False,
) -> Optional[int]:
    """
    Read only the first line of LATEST_AGENT_URL and parse its version.
    """
    now_ts = time.time()
    age = now_ts - _version_cache["last_fetch_ts"]

    if (
        not force
        and age < VERSION_CACHE_COOLDOWN_SECONDS
        and _version_cache["newest_version"] is not None
    ):
        return _version_cache["newest_version"]

    import urllib.request

    try:
        request = urllib.request.Request(
            LATEST_AGENT_URL,
            headers={
                "User-Agent": f"HostishAgent/{version}",
                "Cache-Control": "no-cache",
                "Pragma": "no-cache",
            },
            method="GET",
        )

        with urllib.request.urlopen(
            request,
            timeout=8,
            context=make_ssl_context(),
        ) as response:
            chunk = response.read(256)
            first_line = (
                chunk.splitlines()[0].decode(
                    "utf-8",
                    errors="replace",
                )
                if chunk
                else ""
            )
            newest = _extract_version_from_first_line(
                first_line
            )

        _version_cache["last_fetch_ts"] = now_ts
        _version_cache["newest_version"] = newest
        _version_cache["error"] = None

        if newest is None:
            _version_cache["status"] = "unknown"
        elif newest > version:
            _version_cache["status"] = "outdated"
        else:
            _version_cache["status"] = "up_to_date"

        return newest
    except Exception as error:
        _version_cache["last_fetch_ts"] = now_ts
        _version_cache["error"] = (
            f"{type(error).__name__}: {error}"
        )

        if _version_cache["newest_version"] is None:
            _version_cache["status"] = "unknown"

        return _version_cache["newest_version"]


def version_status_text() -> str:
    newest = _version_cache.get("newest_version")
    status = _version_cache.get("status")

    if newest is None or status == "unknown":
        return f"Check unavailable (current={version})"

    if newest > version:
        return (
            f"Outdated! current={version}, newest={newest}"
        )

    return f"Up to date (version {version})"


# =========================================================
# SAFE SELF-UPDATE IMPLEMENTATION
# =========================================================

def _current_script_path() -> str:
    """
    Return the absolute path to the currently running agent source file.
    """
    candidates = []

    try:
        candidates.append(os.path.abspath(__file__))
    except Exception:
        pass

    if sys.argv and sys.argv[0]:
        candidates.append(os.path.abspath(sys.argv[0]))

    for candidate in candidates:
        if candidate and os.path.isfile(candidate):
            return candidate

    raise RuntimeError(
        "Could not determine the current agent script path"
    )


def _read_text_file(path: str) -> str:
    with open(
        path,
        "r",
        encoding="utf-8-sig",
        newline="",
    ) as file:
        return file.read()


def _source_line_byte_offsets(
    source: str,
) -> list[int]:
    """
    AST column offsets are UTF-8 byte offsets. Build absolute byte offsets so
    multiline and non-ASCII setting values can be replaced exactly.
    """
    offsets = []
    total = 0

    for line in source.splitlines(keepends=True):
        offsets.append(total)
        total += len(line.encode("utf-8"))

    if not offsets:
        offsets.append(0)

    return offsets


def _node_byte_span(
    source: str,
    node: ast.AST,
) -> tuple[int, int]:
    if (
        not hasattr(node, "lineno")
        or not hasattr(node, "end_lineno")
    ):
        raise ValueError(
            "Python AST node positions are unavailable"
        )

    offsets = _source_line_byte_offsets(source)
    start_line = int(node.lineno) - 1
    end_line = int(node.end_lineno) - 1

    if start_line < 0 or end_line < 0:
        raise ValueError("Invalid AST node positions")

    if (
        start_line >= len(offsets)
        or end_line >= len(offsets)
    ):
        raise ValueError(
            "AST node position is outside source"
        )

    start = offsets[start_line] + int(node.col_offset)
    end = offsets[end_line] + int(node.end_col_offset)

    return start, end


def _source_segment_bytes(
    source: str,
    node: ast.AST,
) -> bytes:
    raw = source.encode("utf-8")
    start, end = _node_byte_span(source, node)
    return raw[start:end]


def _settings_block_bounds(
    source: str,
) -> Optional[tuple[int, int]]:
    """
    Return inclusive 1-based line bounds for the editable settings block.
    """
    lines = source.splitlines()
    header_index = None

    for index, line in enumerate(lines):
        if "HOSTER SETTINGS (edit these)" in line:
            header_index = index
            break

    if header_index is None:
        return None

    separator_indexes = []

    for index in range(
        header_index + 1,
        len(lines),
    ):
        if (
            lines[index].strip()
            == "# ========================="
        ):
            separator_indexes.append(index)

            if len(separator_indexes) >= 2:
                break

    if len(separator_indexes) < 2:
        return None

    first_content_line = separator_indexes[0] + 2
    last_content_line = separator_indexes[1]

    return first_content_line, last_content_line


def _top_level_assignment_values(
    source: str,
) -> dict[str, ast.AST]:
    """
    Map simple top-level assignment names to their value AST nodes.
    """
    tree = ast.parse(source)
    result = {}

    for node in tree.body:
        if isinstance(node, ast.Assign):
            if len(node.targets) != 1:
                continue

            target = node.targets[0]

            if isinstance(target, ast.Name):
                result[target.id] = node.value

        elif isinstance(node, ast.AnnAssign):
            if (
                isinstance(node.target, ast.Name)
                and node.value is not None
            ):
                result[node.target.id] = node.value

    return result


def _assignment_names_in_settings_block(
    source: str,
) -> set[str]:
    bounds = _settings_block_bounds(source)

    if bounds is None:
        return set()

    first_line, last_line = bounds
    tree = ast.parse(source)
    names = set()

    for node in tree.body:
        if not isinstance(
            node,
            (ast.Assign, ast.AnnAssign),
        ):
            continue

        node_line = int(
            getattr(node, "lineno", 0) or 0
        )

        if not (
            first_line <= node_line <= last_line
        ):
            continue

        if isinstance(node, ast.Assign):
            if (
                len(node.targets) == 1
                and isinstance(
                    node.targets[0],
                    ast.Name,
                )
            ):
                names.add(node.targets[0].id)

        elif (
            isinstance(node.target, ast.Name)
            and node.value is not None
        ):
            names.add(node.target.id)

    return names


def _normalize_preserve_extra_names() -> set[str]:
    raw = SELF_UPDATE_PRESERVE_EXTRA_NAMES

    if not isinstance(raw, (list, tuple, set)):
        return set()

    result = set()

    for item in raw:
        name = str(item or "").strip()

        if name and name.isidentifier():
            result.add(name)

    return result


def _merge_preserved_settings(
    old_source: str,
    new_source: str,
) -> tuple[str, list[str], list[str]]:
    """
    Replace matching assignment values in the downloaded script with values
    from the current script.

    Values are copied as source expressions instead of being converted to
    strings or JSON. This preserves raw strings, f-strings, lists, tuples,
    dictionaries, booleans, None, and multiline settings.
    """
    old_values = _top_level_assignment_values(
        old_source
    )
    new_values = _top_level_assignment_values(
        new_source
    )

    old_setting_names = (
        _assignment_names_in_settings_block(
            old_source
        )
    )
    new_setting_names = (
        _assignment_names_in_settings_block(
            new_source
        )
    )

    candidate_names = (
        old_setting_names
        | new_setting_names
        | _normalize_preserve_extra_names()
    )

    # The new downloaded script controls its own version.
    candidate_names.discard("version")

    transferable = sorted(
        name
        for name in candidate_names
        if name in old_values and name in new_values
    )

    unavailable = sorted(
        name
        for name in candidate_names
        if name in old_values and name not in new_values
    )

    new_bytes = new_source.encode("utf-8")
    replacements = []

    for name in transferable:
        old_value_bytes = _source_segment_bytes(
            old_source,
            old_values[name],
        )

        start, end = _node_byte_span(
            new_source,
            new_values[name],
        )

        replacements.append(
            (
                start,
                end,
                old_value_bytes,
                name,
            )
        )

    for (
        start,
        end,
        value_bytes,
        _name,
    ) in sorted(
        replacements,
        key=lambda item: item[0],
        reverse=True,
    ):
        new_bytes = (
            new_bytes[:start]
            + value_bytes
            + new_bytes[end:]
        )

    merged = new_bytes.decode("utf-8")

    return merged, transferable, unavailable


def _declared_source_version(
    source: str,
) -> Optional[int]:
    """
    Read the module-level integer assigned to version.
    """
    try:
        tree = ast.parse(source)
    except SyntaxError:
        return None

    for node in tree.body:
        if (
            not isinstance(node, ast.Assign)
            or len(node.targets) != 1
        ):
            continue

        target = node.targets[0]

        if (
            not isinstance(target, ast.Name)
            or target.id != "version"
        ):
            continue

        if (
            isinstance(node.value, ast.Constant)
            and isinstance(node.value.value, int)
        ):
            return int(node.value.value)

        return None

    return None


def _download_latest_agent_source() -> tuple[str, str]:
    """
    Download and decode the complete latest agent script with redirect and
    size checks. Returns source text and the final URL.
    """
    import urllib.request

    initial = urllib.parse.urlparse(
        LATEST_AGENT_URL
    )
    initial_scheme = (
        initial.scheme or ""
    ).lower()
    initial_host = (
        initial.hostname or ""
    ).lower()

    if (
        initial_scheme not in ("http", "https")
        or not initial_host
    ):
        raise ValueError(
            "LATEST_AGENT_URL must be a valid HTTP(S) URL"
        )

    if (
        SELF_UPDATE_REQUIRE_HTTPS
        and initial_scheme != "https"
    ):
        raise ValueError(
            "Self-update requires an HTTPS "
            "LATEST_AGENT_URL"
        )

    request = urllib.request.Request(
        LATEST_AGENT_URL,
        headers={
            "User-Agent": f"HostishAgent/{version}",
            "Accept": (
                "text/x-python, text/plain, "
                "application/octet-stream;q=0.9, "
                "*/*;q=0.1"
            ),
            "Cache-Control": "no-cache",
            "Pragma": "no-cache",
        },
        method="GET",
    )

    timeout = max(
        5,
        int(
            SELF_UPDATE_DOWNLOAD_TIMEOUT_SECONDS
        ),
    )
    max_bytes = max(
        1024,
        int(SELF_UPDATE_MAX_DOWNLOAD_BYTES),
    )

    with urllib.request.urlopen(
        request,
        timeout=timeout,
        context=make_ssl_context(),
    ) as response:
        final_url = response.geturl()
        final = urllib.parse.urlparse(final_url)
        final_scheme = (
            final.scheme or ""
        ).lower()
        final_host = (
            final.hostname or ""
        ).lower()

        if (
            SELF_UPDATE_REQUIRE_HTTPS
            and final_scheme != "https"
        ):
            raise ValueError(
                "Self-update redirect did not "
                "remain on HTTPS"
            )

        if (
            not SELF_UPDATE_ALLOW_CROSS_HOST_REDIRECTS
            and final_host != initial_host
        ):
            raise ValueError(
                "Self-update redirect changed host "
                f"from '{initial_host}' "
                f"to '{final_host}'"
            )

        raw = response.read(max_bytes + 1)

    if len(raw) > max_bytes:
        raise ValueError(
            "Downloaded agent exceeds "
            "SELF_UPDATE_MAX_DOWNLOAD_BYTES "
            f"({max_bytes} bytes)"
        )

    if not raw:
        raise ValueError(
            "Downloaded agent file is empty"
        )

    expected_sha = str(SELF_UPDATE_EXPECTED_SHA256 or "").strip().lower()
    if expected_sha:
        actual_sha = hashlib.sha256(raw).hexdigest().lower()
        if not hmac.compare_digest(actual_sha, expected_sha):
            raise ValueError(
                "Downloaded agent SHA-256 did not match SELF_UPDATE_EXPECTED_SHA256"
            )

    public_key_pem = str(SELF_UPDATE_ED25519_PUBLIC_KEY_PEM or "").strip()
    if public_key_pem:
        try:
            from cryptography.hazmat.primitives import serialization
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        except ImportError as error:
            raise ValueError(
                "SELF_UPDATE_ED25519_PUBLIC_KEY_PEM is configured but the optional "
                "'cryptography' package is not installed"
            ) from error

        signature_url = final_url + str(SELF_UPDATE_SIGNATURE_SUFFIX or ".sig")
        parsed_sig = urllib.parse.urlparse(signature_url)
        if SELF_UPDATE_REQUIRE_HTTPS and parsed_sig.scheme.lower() != "https":
            raise ValueError("Update signature URL must use HTTPS")
        if not SELF_UPDATE_ALLOW_CROSS_HOST_REDIRECTS and (parsed_sig.hostname or "").lower() != initial_host:
            raise ValueError("Update signature URL changed host")

        sig_request = urllib.request.Request(
            signature_url,
            headers={"User-Agent": f"HostishAgent/{version}", "Cache-Control": "no-cache"},
            method="GET",
        )
        with urllib.request.urlopen(
            sig_request,
            timeout=timeout,
            context=make_ssl_context(),
        ) as sig_response:
            sig_final = urllib.parse.urlparse(sig_response.geturl())
            if SELF_UPDATE_REQUIRE_HTTPS and sig_final.scheme.lower() != "https":
                raise ValueError("Update signature redirect did not remain on HTTPS")
            if not SELF_UPDATE_ALLOW_CROSS_HOST_REDIRECTS and (sig_final.hostname or "").lower() != initial_host:
                raise ValueError("Update signature redirect changed host")
            signature_raw = sig_response.read(8193)
        if len(signature_raw) > 8192:
            raise ValueError("Update signature file is unexpectedly large")

        signature = signature_raw.strip()
        try:
            decoded = base64.b64decode(signature, validate=True)
            if decoded:
                signature = decoded
        except Exception:
            pass

        key = serialization.load_pem_public_key(public_key_pem.encode("utf-8"))
        if not isinstance(key, Ed25519PublicKey):
            raise ValueError("Configured update public key is not Ed25519")
        try:
            key.verify(signature, raw)
        except Exception as error:
            raise ValueError("Downloaded agent Ed25519 signature verification failed") from error

    try:
        source = raw.decode("utf-8-sig")
    except UnicodeDecodeError as error:
        raise ValueError(
            "Downloaded agent is not valid UTF-8: "
            f"{error}"
        ) from error

    return source, final_url


def _secure_write_bytes(
    path: str,
    data: bytes,
    mode: int = 0o600,
) -> None:
    """
    Write a new file, flush it to disk, and use restrictive permissions where
    supported. Backup files may contain credentials.
    """
    flags = (
        os.O_WRONLY
        | os.O_CREAT
        | os.O_EXCL
    )

    file_descriptor = os.open(
        path,
        flags,
        mode,
    )

    try:
        with os.fdopen(
            file_descriptor,
            "wb",
        ) as file:
            file_descriptor = -1
            file.write(data)
            file.flush()
            os.fsync(file.fileno())
    finally:
        if file_descriptor >= 0:
            os.close(file_descriptor)

    try:
        os.chmod(path, mode)
    except Exception:
        pass


def _make_update_backup(
    script_path: str,
    old_source: str,
) -> Optional[str]:
    if not SELF_UPDATE_BACKUP_ENABLED:
        return None

    script_directory = os.path.dirname(
        script_path
    )
    backup_directory_setting = str(
        SELF_UPDATE_BACKUP_DIR or ""
    ).strip()

    if not backup_directory_setting:
        raise ValueError(
            "SELF_UPDATE_BACKUP_DIR cannot be "
            "empty when backups are enabled"
        )

    if os.path.isabs(
        backup_directory_setting
    ):
        backup_directory = os.path.abspath(
            os.path.expanduser(
                backup_directory_setting
            )
        )
    else:
        backup_directory = os.path.join(
            script_directory,
            backup_directory_setting,
        )

    os.makedirs(
        backup_directory,
        exist_ok=True,
    )

    base_name = os.path.basename(script_path)
    timestamp = datetime.now().strftime(
        "%Y%m%d-%H%M%S"
    )
    nonce = (
        f"{time.time_ns() % 1_000_000_000:09d}"
    )
    backup_name = (
        f"{base_name}.v{version}."
        f"{timestamp}-{nonce}.backup.py"
    )
    backup_path = os.path.join(
        backup_directory,
        backup_name,
    )

    _secure_write_bytes(
        backup_path,
        old_source.encode("utf-8"),
        mode=0o600,
    )

    _prune_update_backups(
        backup_directory,
        base_name,
    )

    return backup_path


def _prune_update_backups(
    backup_directory: str,
    script_base_name: str,
) -> None:
    keep = max(
        1,
        int(SELF_UPDATE_BACKUP_KEEP),
    )
    prefix = f"{script_base_name}.v"
    suffix = ".backup.py"

    try:
        candidates = []

        for name in os.listdir(
            backup_directory
        ):
            if (
                not name.startswith(prefix)
                or not name.endswith(suffix)
            ):
                continue

            path = os.path.join(
                backup_directory,
                name,
            )

            if os.path.isfile(path):
                candidates.append(
                    (
                        os.path.getmtime(path),
                        path,
                    )
                )

        candidates.sort(reverse=True)

        for _modified_time, path in candidates[
            keep:
        ]:
            try:
                os.remove(path)
            except Exception as error:
                log(
                    f"[WARN] Could not remove "
                    f"old update backup '{path}': "
                    f"{error}"
                )
    except Exception as error:
        log(
            f"[WARN] Could not prune update "
            f"backups: "
            f"{type(error).__name__}: {error}"
        )


def _atomic_replace_script(
    script_path: str,
    new_source: str,
) -> None:
    """
    Write the validated replacement beside the current script and atomically
    swap it into place.
    """
    script_directory = os.path.dirname(
        script_path
    )
    script_name = os.path.basename(
        script_path
    )
    old_mode = (
        os.stat(script_path).st_mode
        & 0o777
    )

    file_descriptor, temp_path = (
        tempfile.mkstemp(
            prefix=(
                f".{script_name}.update-"
            ),
            suffix=".tmp",
            dir=script_directory,
        )
    )

    try:
        with os.fdopen(
            file_descriptor,
            "wb",
        ) as file:
            file_descriptor = -1
            file.write(
                new_source.encode("utf-8")
            )
            file.flush()
            os.fsync(file.fileno())

        try:
            os.chmod(temp_path, old_mode)
        except Exception:
            pass

        os.replace(temp_path, script_path)
        temp_path = ""
    finally:
        if file_descriptor >= 0:
            os.close(file_descriptor)

        if temp_path:
            try:
                os.remove(temp_path)
            except Exception:
                pass


def install_latest_agent_update(
    expected_newest: Optional[int] = None,
) -> dict:
    """
    Download, validate, migrate settings, back up the current script, and
    atomically install the newest script.
    """
    script_path = _current_script_path()
    old_source = _read_text_file(script_path)
    new_source, final_url = (
        _download_latest_agent_source()
    )

    downloaded_version = (
        _declared_source_version(new_source)
    )

    if downloaded_version is None:
        raise ValueError(
            "Downloaded script does not declare "
            "an integer 'version'"
        )

    if downloaded_version <= version:
        raise ValueError(
            f"Downloaded script version "
            f"{downloaded_version} is not newer "
            f"than current version {version}"
        )

    if (
        expected_newest is not None
        and downloaded_version
        < int(expected_newest)
    ):
        raise ValueError(
            f"Downloaded script version "
            f"{downloaded_version} is older "
            f"than the advertised version "
            f"{expected_newest}"
        )

    # Validate the untouched official source.
    compile(new_source, final_url, "exec")

    (
        merged_source,
        transferred,
        unavailable,
    ) = _merge_preserved_settings(
        old_source,
        new_source,
    )

    # Validate the exact source that will be installed.
    compile(
        merged_source,
        script_path,
        "exec",
    )

    if not transferred:
        raise RuntimeError(
            "No matching settings could be "
            "transferred; update was stopped "
            "to avoid losing configuration"
        )

    backup_path = _make_update_backup(
        script_path,
        old_source,
    )

    _atomic_replace_script(
        script_path,
        merged_source,
    )

    return {
        "script_path": script_path,
        "backup_path": backup_path,
        "download_url": final_url,
        "downloaded_version": (
            downloaded_version
        ),
        "transferred": transferred,
        "unavailable": unavailable,
    }


def _restart_after_update(
    script_path: str,
) -> None:
    """
    Replace this process with the newly installed agent. A subprocess fallback
    is used if execv is unavailable.
    """
    stop_managed_scripts()

    try:
        sys.stdout.flush()
        sys.stderr.flush()
    except Exception:
        pass

    arguments = [
        sys.executable,
        script_path,
    ] + list(sys.argv[1:])

    try:
        os.execv(
            sys.executable,
            arguments,
        )
    except Exception as exec_error:
        log(
            "[WARN] In-place restart failed; "
            "trying spawned restart: "
            f"{type(exec_error).__name__}: "
            f"{exec_error}"
        )

    try:
        subprocess.Popen(
            arguments,
            cwd=(
                os.path.dirname(script_path)
                or None
            ),
        )
    except Exception as spawn_error:
        raise RuntimeError(
            "Could not restart updated agent: "
            f"{type(spawn_error).__name__}: "
            f"{spawn_error}"
        ) from spawn_error

    os._exit(0)


def _noninteractive_update_choice() -> str:
    action = str(
        SELF_UPDATE_NONINTERACTIVE_ACTION
        or "continue"
    ).strip().lower()

    if action == "exit":
        return "e"

    return "c"


def startup_version_check_or_prompt() -> None:
    newest = fetch_latest_agent_version(
        force=True
    )

    if newest is None:
        log(
            "[INFO] Could not verify latest "
            "agent version right now "
            "(continuing)"
        )
        return

    if newest <= version:
        log("[INFO] Agent up to date")
        return

    # A reconnect-triggered/internal restart must not repeatedly ask the user
    # about the same update after they already chose "continue" during this
    # launch session. The environment belongs only to this process tree, so a
    # normal stop followed by a fresh manual start asks again.
    skipped_version = str(
        os.environ.get(_SESSION_UPDATE_SKIP_ENV, "")
        or ""
    ).strip()

    if skipped_version == str(newest):
        log(
            "[INFO] Update prompt skipped for this "
            f"running session (version {newest} was "
            "already declined)."
        )
        return

    if not SELF_UPDATE_ENABLED:
        log(
            f"[WARN] Agent is outdated "
            f"(current={version}, newest={newest}), "
            "but SELF_UPDATE_ENABLED is False. "
            "Continuing with current script."
        )
        return

    prompt_text = (
        "\nA newer Hostish agent is available "
        f"(current={version}, newest={newest}).\n"
        "Choose [u] update now, "
        "[c] continue with this version, "
        "or [e] exit.\n> "
    )

    while True:
        try:
            answer = input(
                prompt_text
            ).strip().lower()
        except (EOFError, OSError):
            answer = (
                _noninteractive_update_choice()
            )
            log(
                "[INFO] Interactive update prompt "
                "is unavailable; using "
                "SELF_UPDATE_NONINTERACTIVE_ACTION="
                f"'{SELF_UPDATE_NONINTERACTIVE_ACTION}'"
            )

        if answer in (
            "c",
            "continue",
            "",
        ):
            os.environ[_SESSION_UPDATE_SKIP_ENV] = str(newest)
            log(
                "[INFO] Continuing with outdated "
                f"agent (current={version}, "
                f"newest={newest}). This update "
                "prompt will stay dismissed through "
                "automatic reconnect/restart cycles "
                "until you stop the agent and launch "
                "it again."
            )
            return

        if answer in (
            "e",
            "exit",
            "q",
            "quit",
        ):
            log(
                "[INFO] Exiting at user request "
                "before update."
            )
            sys.exit(0)

        if answer not in ("u", "update"):
            print("Please enter u, c, or e.")
            continue

        warning = (
            "\nWARNING: The updater transfers "
            "only matching editable assignment "
            "values from the HOSTER SETTINGS "
            "section into the new official script. "
            "This includes the username, password, "
            "website path, ports, routes, "
            "auto-start scripts, lists, strings, "
            "numbers, and booleans such as "
            "IDLE_STATUS_CHECK_ENABLED, plus other "
            "matching small settings. Custom "
            "functions or code edits outside that "
            "settings section are not merged. "
            "A full backup of the current script "
            "will be created before replacement "
            "when backups are enabled.\n"
        )

        print(warning)

        try:
            confirmation = input(
                'Type "UPDATE" to install and '
                "automatically restart, or press "
                "Enter to cancel:\n> "
            )
        except (EOFError, OSError):
            confirmation = ""

        if confirmation.strip() != "UPDATE":
            log(
                "[INFO] Update cancelled; "
                "returning to version choice."
            )
            continue

        try:
            log(
                f"[UPDATE] Downloading and "
                f"validating agent version "
                f"{newest}..."
            )

            result = install_latest_agent_update(
                expected_newest=newest
            )

            transferred = result["transferred"]
            unavailable = result["unavailable"]

            log(
                f"[UPDATE] Installed version "
                f"{result['downloaded_version']} | "
                f"transferred_settings="
                f"{len(transferred)}"
            )

            log(
                "[UPDATE] Preserved settings: "
                + ", ".join(transferred)
            )

            if unavailable:
                log(
                    "[WARN] These old settings do "
                    "not exist in the new script "
                    "and could not be injected: "
                    + ", ".join(unavailable)
                )

            if result["backup_path"]:
                log(
                    "[UPDATE] Backup saved "
                    "securely at: "
                    f"{result['backup_path']}"
                )
            else:
                log(
                    "[WARN] Update backup was "
                    "disabled by configuration"
                )

            log(
                "[UPDATE] Restarting into the "
                "updated agent now..."
            )

            os.environ.pop(
                _SESSION_UPDATE_SKIP_ENV,
                None,
            )

            _restart_after_update(
                result["script_path"]
            )

        except Exception as error:
            log(
                "[UPDATE] Update failed safely; "
                "current running process was not "
                "restarted: "
                f"{type(error).__name__}: {error}"
            )
            traceback.print_exc()

            print(
                "\nThe update did not complete. "
                "Your current process is still "
                "running. Choose whether to retry, "
                "continue, or exit.\n"
            )


def _norm_prefix(prefix: str) -> str:
    prefix = (prefix or "").lstrip("/")

    if prefix and not prefix.endswith("/"):
        prefix += "/"

    return prefix


PROXY_PREFIXES = [
    _norm_prefix(prefix)
    for prefix in PROXY_PREFIXES
    if prefix
]

# Per-request hostname route. ContextVars keep concurrent requests isolated and
# are propagated into Hostish's blocking worker calls.
_CURRENT_HOST_ROUTE = contextvars.ContextVar("hostish_host_route", default=None)


def _host_only_for_route(value: str) -> str:
    host = (value or "").strip().lower().rstrip(".")
    if host.startswith("["):
        end = host.find("]")
        return host[: end + 1] if end >= 0 else host
    if ":" in host:
        host = host.split(":", 1)[0]
    return host


def _normalize_host_routes_for_auth() -> list[str]:
    routes = globals().get("HOST_ROUTES")
    if not isinstance(routes, dict):
        return []
    out = []
    for raw in routes.keys():
        host = str(raw or "").strip().lower().rstrip(".")
        if not host or len(host) > 253:
            continue
        if host.startswith("*."):
            suffix = _host_only_for_route(host[2:])
            host = "*." + suffix if suffix else ""
        else:
            host = _host_only_for_route(host)
        if host and host not in out:
            out.append(host)
    return out


def _host_route_for_headers(headers: dict):
    routes = globals().get("HOST_ROUTES")
    if not isinstance(routes, dict):
        return None
    host = ""
    for key, value in (headers or {}).items():
        if str(key).lower() == "host":
            host = _host_only_for_route(str(value))
            break
    if not host:
        return None

    selected = None
    selected_pattern = ""
    # Normalize route keys while matching so cosmetic case/trailing-dot choices
    # in an editable agent never make the advertised route differ from runtime.
    for raw_pattern, config in routes.items():
        pattern = str(raw_pattern or "").strip().lower().rstrip(".")
        if not pattern:
            continue
        if pattern.startswith("*."):
            suffix = _host_only_for_route(pattern[2:])
            if suffix and host.endswith("." + suffix) and host != suffix:
                if len(suffix) > len(selected_pattern):
                    selected = config
                    selected_pattern = suffix
            continue
        normalized = _host_only_for_route(pattern)
        if normalized == host:
            selected = config
            selected_pattern = normalized
            break

    if selected is None:
        return None
    if isinstance(selected, str):
        return {"mode": "proxy", "upstream": selected, "matched_host": host}
    if selected is True:
        return {"matched_host": host}
    if not isinstance(selected, dict):
        return {"matched_host": host}
    result = dict(selected)
    result["matched_host"] = host
    return result


def _route_setting(name: str, default):
    route = _CURRENT_HOST_ROUTE.get()
    if not isinstance(route, dict):
        return default
    aliases = {
        "mode": ("mode",),
        "website_dir": ("website_dir", "root"),
        "upstream": ("upstream", "upstream_base"),
        "proxy_prefixes": ("proxy_prefixes",),
        "upstream_routes": ("upstream_routes",),
    }
    for key in aliases.get(name, (name,)):
        if key in route and route[key] is not None:
            return route[key]
    return default


def _effective_mode() -> str:
    return str(_route_setting("mode", MODE) or MODE).strip().lower()


def _effective_website_dir() -> str:
    return os.path.expanduser(str(_route_setting("website_dir", WEBSITE_DIR) or WEBSITE_DIR))


def _effective_upstream_base() -> str:
    return str(_route_setting("upstream", UPSTREAM_BASE) or UPSTREAM_BASE)


def _effective_proxy_prefixes():
    raw = _route_setting("proxy_prefixes", PROXY_PREFIXES)
    if not isinstance(raw, (list, tuple)):
        return PROXY_PREFIXES
    return [_norm_prefix(str(prefix)) for prefix in raw if str(prefix or "").strip()]


def _effective_upstream_routes():
    raw = _route_setting("upstream_routes", UPSTREAM_ROUTES)
    return raw if isinstance(raw, dict) else UPSTREAM_ROUTES


def safe_join(root: str, rel_path: str) -> str:
    """Canonical containment check with optional explicit symlink escape."""
    rel_path = urllib.parse.unquote(rel_path or "")
    # Decode a second time only to catch common double-encoded traversal. Do not
    # repeatedly decode attacker-controlled input forever.
    second = urllib.parse.unquote(rel_path)
    if second != rel_path:
        rel_path = second
    rel_path = rel_path.replace("\\", "/").lstrip("/")
    if "\x00" in rel_path:
        raise ValueError("NUL byte blocked")

    root_abs = os.path.abspath(root)
    joined_abs = os.path.abspath(os.path.join(root_abs, rel_path))
    try:
        if os.path.commonpath([root_abs, joined_abs]) != root_abs:
            raise ValueError("path traversal blocked")
    except ValueError:
        raise ValueError("path traversal blocked")

    if ALLOW_STATIC_SYMLINK_ESCAPE:
        return joined_abs

    root_real = os.path.realpath(root_abs)
    full_real = os.path.realpath(joined_abs)
    try:
        if os.path.commonpath([root_real, full_real]) != root_real:
            raise ValueError("symlink escape blocked")
    except ValueError:
        raise ValueError("symlink escape blocked")
    return full_real

def should_proxy(rel_path: str) -> bool:
    rel_path = (
        rel_path or ""
    ).lstrip("/").lower()

    mode = _effective_mode()
    if mode == "proxy":
        return True

    if mode == "static":
        return False

    for prefix in _effective_proxy_prefixes():
        normalized_prefix = (
            prefix.lower().strip("/")
        )

        if not normalized_prefix:
            continue

        if (
            rel_path == normalized_prefix
            or rel_path.startswith(
                normalized_prefix + "/"
            )
        ):
            return True

    return False


def guess_content_type(path: str) -> str:
    import mimetypes

    content_type, _ = mimetypes.guess_type(
        path
    )

    return (
        content_type
        or "application/octet-stream"
    )


def _preview_bytes(
    data: bytes,
    length: int = BODY_PREVIEW_BYTES,
) -> str:
    if not data:
        return ""

    sample = data[:length]

    try:
        text = sample.decode(
            "utf-8",
            errors="replace",
        )
        text = (
            text.replace("\n", "\\n")
            .replace("\r", "\\r")
        )

        if len(data) > length:
            text += "..."

        return text
    except Exception:
        return f"<{len(sample)} bytes binary>"


def _metadata_version_response() -> tuple[int, dict, bytes, dict]:
    """Legacy reserved path. Version details are private dashboard diagnostics now."""
    body = b"Not Found"
    return (
        404,
        {
            "content-type": "text/plain; charset=utf-8",
            "cache-control": "no-store",
        },
        body,
        {
            "source": "agent-meta",
            "endpoint": "/__hostish/version",
            "size": len(body),
        },
    )

def _hostish_default_404_redirect() -> tuple[
    int,
    dict,
    bytes,
    dict,
]:
    body = b""
    headers = {
        "location": "https://hostish.site/404/",
        "cache-control": "no-store",
    }

    return (
        302,
        headers,
        body,
        {
            "source": "agent-404-redirect",
            "target": (
                "https://hostish.site/404/"
            ),
        },
    )


def _resolve_custom_404_full_path() -> Optional[str]:
    path = (CUSTOM_404_PATH or "").strip()

    if not path:
        return None

    if os.path.isabs(path):
        return os.path.abspath(path)

    return safe_join(_effective_website_dir(), path)


def _serve_custom_404_if_configured() -> Optional[
    tuple[int, dict, bytes, dict]
]:
    if not CUSTOM_404_ENABLED:
        return None

    try:
        full_path = (
            _resolve_custom_404_full_path()
        )
    except Exception:
        return None

    if (
        not full_path
        or not os.path.isfile(full_path)
    ):
        return None

    try:
        size = os.path.getsize(full_path)

        if int(MAX_FILE_BYTES) > 0 and size > int(MAX_FILE_BYTES):
            return None

        with open(full_path, "rb") as file:
            body = file.read()

        headers = {
            "content-type": (
                guess_content_type(full_path)
            ),
            "cache-control": "no-store",
        }

        return (
            404,
            headers,
            body,
            {
                "source": "custom-404",
                "served_rel": CUSTOM_404_PATH,
                "full_path": full_path,
                "size": len(body),
            },
        )
    except Exception:
        return None


def fetch_custom_favicon() -> Optional[bytes]:
    """
    Retrieve and cache the custom external favicon.
    """
    if (
        not FAVICON_BYPASS_ENABLED
        or not FAVICON_BYPASS_URL
    ):
        return None

    if (
        _favicon_cache["fetched"]
        and _favicon_cache["body"] is not None
    ):
        return _favicon_cache["body"]

    import urllib.request

    try:
        request = urllib.request.Request(
            FAVICON_BYPASS_URL,
            headers={
                "User-Agent": (
                    f"HostishAgent/{version}"
                )
            },
            method="GET",
        )

        with urllib.request.urlopen(
            request,
            timeout=10,
            context=make_ssl_context(),
        ) as response:
            favicon_body = response.read(max(1, int(FAVICON_MAX_BYTES)) + 1)
            if len(favicon_body) > max(1, int(FAVICON_MAX_BYTES)):
                raise ValueError("custom favicon exceeds FAVICON_MAX_BYTES")
            _favicon_cache["body"] = favicon_body
            _favicon_cache["content_type"] = (
                response.headers.get(
                    "Content-Type",
                    "image/x-icon",
                )
            )

        _favicon_cache["fetched"] = True

        log(
            "[INFO] Downloaded and cached "
            "custom favicon from: "
            f"{FAVICON_BYPASS_URL}"
        )

        return _favicon_cache["body"]
    except Exception as error:
        log_repeatable_error(
            "favicon_fetch_failed",
            "Failed to retrieve custom favicon "
            f"from URL: {error}",
        )
        return None


def _sensitive_static_path(rel_path: str) -> bool:
    mode = str(STATIC_SECURITY_MODE or "safe").strip().lower()
    if mode == "unrestricted":
        return False

    normalized = urllib.parse.unquote(rel_path or "").replace("\\", "/").lstrip("/")
    normalized_lower = normalized.lower()
    if not normalized_lower:
        return False

    def matches(patterns) -> bool:
        for pattern in patterns or []:
            p = str(pattern or "").replace("\\", "/").lstrip("/").lower()
            if p and fnmatch.fnmatch(normalized_lower, p):
                return True
        return False

    if matches(STATIC_ALLOW_PATTERNS):
        return False

    if mode == "custom":
        return matches(STATIC_BLOCK_PATTERNS)

    # Safe mode combines user patterns with conservative built-ins.
    if matches(STATIC_BLOCK_PATTERNS):
        return True
    segments = [segment for segment in normalized_lower.split("/") if segment]
    for segment in segments:
        if segment in {".git", ".svn", ".hg", ".ssh", ".env"}:
            return True
        if segment.startswith(".env."):
            return True
    return False

class StaticRangeNotSatisfiable(Exception):
    pass


def _parse_single_byte_range(range_header: str, size: int):
    """Parse one HTTP bytes range. Returns (start, end) or None when absent/unsupported."""
    value = str(range_header or "").strip()
    if not value:
        return None
    if not value.lower().startswith("bytes="):
        # RFC behavior: unsupported range units may be ignored.
        return None

    spec = value[6:].strip()
    if not spec or "," in spec:
        # Hostish static media currently supports the single ranges browsers use
        # for audio/video seeking. Multipart ranges are deliberately rejected.
        raise StaticRangeNotSatisfiable("multiple/invalid byte ranges are unsupported")
    if size <= 0 or "-" not in spec:
        raise StaticRangeNotSatisfiable("range cannot be satisfied")

    first, last = spec.split("-", 1)
    first = first.strip()
    last = last.strip()

    try:
        if first == "":
            # Suffix range: bytes=-500 means the final 500 bytes.
            suffix = int(last)
            if suffix <= 0:
                raise ValueError
            if suffix >= size:
                return 0, size - 1
            return size - suffix, size - 1

        start = int(first)
        if start < 0 or start >= size:
            raise StaticRangeNotSatisfiable("range start is outside the file")

        if last == "":
            end = size - 1
        else:
            end = int(last)
            if end < start:
                raise StaticRangeNotSatisfiable("range end precedes range start")
            end = min(end, size - 1)
        return start, end
    except StaticRangeNotSatisfiable:
        raise
    except (TypeError, ValueError):
        raise StaticRangeNotSatisfiable("invalid byte range")


def _static_entity_headers(full_path: str, size: int) -> dict:
    """Headers useful for browsers, media seeking, and validators."""
    import email.utils

    stat_result = os.stat(full_path)
    etag = f'"{int(stat_result.st_mtime_ns):x}-{int(size):x}"'
    last_modified = email.utils.formatdate(
        stat_result.st_mtime,
        usegmt=True,
    )
    return {
        "content-type": guess_content_type(full_path),
        "cache-control": str(STATIC_CACHE_CONTROL or "no-store"),
        "accept-ranges": "bytes",
        "etag": etag,
        "last-modified": last_modified,
    }


def _should_honor_if_range(headers: dict, entity_headers: dict) -> bool:
    """Return False when If-Range asks us to send the complete representation."""
    if_range = ""
    for key, value in (headers or {}).items():
        if str(key).lower() == "if-range":
            if_range = str(value).strip()
            break
    if not if_range:
        return True
    return if_range in {
        str(entity_headers.get("etag", "")),
        str(entity_headers.get("last-modified", "")),
    }


def read_static_file(
    rel_path: str,
    method: str = "GET",
    request_headers: Optional[dict] = None,
) -> tuple[int, dict, bytes, dict]:
    requested_rel = rel_path
    request_headers = dict(request_headers or {})
    method_upper = str(method or "GET").upper()

    if _sensitive_static_path(rel_path):
        return (
            404,
            {"content-type": "text/plain; charset=utf-8", "cache-control": "no-store"},
            b"Not Found",
            {
                "source": "static",
                "served_rel": rel_path,
                "requested_rel": requested_rel,
                "full_path": None,
                "error": "sensitive static path blocked",
            },
        )

    if rel_path == "" or rel_path.endswith("/"):
        rel_path += "index.html"

    try:
        full_path = safe_join(_effective_website_dir(), rel_path)
    except ValueError:
        return (
            403,
            {"content-type": "text/plain; charset=utf-8"},
            b"Forbidden" if method_upper != "HEAD" else b"",
            {
                "source": "static",
                "served_rel": rel_path,
                "requested_rel": requested_rel,
                "full_path": None,
                "error": "path traversal blocked",
            },
        )

    if not os.path.isfile(full_path):
        return (
            404,
            {"content-type": "text/plain; charset=utf-8"},
            b"Not Found" if method_upper != "HEAD" else b"",
            {
                "source": "static",
                "served_rel": rel_path,
                "requested_rel": requested_rel,
                "full_path": full_path,
                "error": "not found",
            },
        )

    size = os.path.getsize(full_path)
    if _limit_exceeded(MAX_FILE_BYTES, size):
        return (
            413,
            {"content-type": "text/plain; charset=utf-8"},
            b"File too large" if method_upper != "HEAD" else b"",
            {
                "source": "static",
                "served_rel": rel_path,
                "requested_rel": requested_rel,
                "full_path": full_path,
                "error": "too large",
            },
        )

    output_headers = _static_entity_headers(full_path, size)
    range_header = ""
    for key, value in request_headers.items():
        if str(key).lower() == "range":
            range_header = str(value)
            break

    byte_range = None
    if method_upper in {"GET", "HEAD"} and range_header and _should_honor_if_range(request_headers, output_headers):
        try:
            byte_range = _parse_single_byte_range(range_header, size)
        except StaticRangeNotSatisfiable as error:
            output_headers["content-range"] = f"bytes */{size}"
            output_headers["content-length"] = "0"
            return (
                416,
                output_headers,
                b"",
                {
                    "source": "static",
                    "served_rel": rel_path,
                    "requested_rel": requested_rel,
                    "full_path": full_path,
                    "error": str(error),
                    "size": size,
                },
            )

    if byte_range is not None:
        range_start, range_end = byte_range
        range_length = range_end - range_start + 1
        output_headers["content-range"] = f"bytes {range_start}-{range_end}/{size}"
        output_headers["content-length"] = str(range_length)
        if method_upper == "HEAD":
            body = b""
        else:
            with open(full_path, "rb") as file:
                file.seek(range_start)
                body = file.read(range_length)
        status = 206
    else:
        output_headers["content-length"] = str(size)
        if method_upper == "HEAD":
            body = b""
        else:
            with open(full_path, "rb") as file:
                body = file.read()
        status = 200

    return (
        status,
        output_headers,
        body,
        {
            "source": "static",
            "served_rel": rel_path,
            "requested_rel": requested_rel,
            "full_path": full_path,
            "size": size,
            "range": byte_range,
        },
    )


def _select_upstream(rel_path: str) -> str:
    """Choose the longest matching path route within the active hostname route."""
    normalized_rel = (rel_path or "").lstrip("/").lower()
    best_target = _effective_upstream_base()
    best_len = -1
    for prefix, target in (_effective_upstream_routes() or {}).items():
        normalized_prefix = str(prefix or "").lstrip("/").lower().rstrip("/")
        if not normalized_prefix:
            continue
        if normalized_rel == normalized_prefix or normalized_rel.startswith(normalized_prefix + "/"):
            if len(normalized_prefix) > best_len:
                best_len = len(normalized_prefix)
                best_target = str(target)
    return best_target


def _redacted_headers_for_log(headers: dict) -> dict:
    if PRINT_SENSITIVE_HEADERS:
        return dict(headers or {})
    result = {}
    sensitive = {str(name).lower() for name in (SENSITIVE_HEADER_NAMES or set())}
    for key, value in (headers or {}).items():
        if str(key).lower() in sensitive:
            result[str(key)] = "[REDACTED]"
        else:
            result[str(key)] = value
    return result


def _limit_exceeded(limit: int, value: int) -> bool:
    try:
        limit_value = int(limit)
    except Exception:
        limit_value = 0
    return limit_value > 0 and int(value) > limit_value


def parse_upstream_base(upstream: str):
    from urllib.parse import urlparse

    parsed = urlparse(upstream)

    if parsed.scheme not in ("http", "https"):
        raise ValueError(
            "UPSTREAM_BASE must start with "
            "http:// or https://"
        )

    host = parsed.hostname or "127.0.0.1"
    port = parsed.port or (
        443
        if parsed.scheme == "https"
        else 80
    )
    base_path = parsed.path or ""

    if base_path.endswith("/"):
        base_path = base_path[:-1]

    return (
        parsed.scheme,
        host,
        port,
        base_path,
    )


def _upstream_host_allowed(host: str) -> bool:
    """Resolve the target and enforce the hoster's declared network policy."""
    policy = str(UPSTREAM_NETWORK_POLICY or "loopback").strip().lower()
    if policy == "any":
        return True
    if policy not in {"loopback", "private"}:
        return False

    host_text = (host or "").strip().strip("[]")
    if not host_text:
        return False

    addresses = []
    try:
        addresses.append(ipaddress.ip_address(host_text))
    except ValueError:
        try:
            infos = socket.getaddrinfo(host_text, None, type=socket.SOCK_STREAM)
        except OSError:
            return False
        seen = set()
        for info in infos:
            raw = info[4][0]
            try:
                address = ipaddress.ip_address(raw)
            except ValueError:
                continue
            if address not in seen:
                seen.add(address)
                addresses.append(address)

    if not addresses:
        return False

    def allowed(address):
        if address.is_loopback:
            return True
        if policy == "private":
            return bool(address.is_private or address.is_link_local)
        return False

    # ALL current DNS answers must fit the policy. This avoids accepting a name
    # that mixes an allowed address with an external one (DNS rebinding surface).
    return all(allowed(address) for address in addresses)

def _proxy_cache() -> dict:
    cache = getattr(_proxy_thread_local, "connections", None)
    if cache is None:
        cache = {}
        _proxy_thread_local.connections = cache
    return cache

def _new_proxy_connection(scheme: str, host: str, port: int):
    import http.client

    if scheme == "https":
        return http.client.HTTPSConnection(
            host,
            port,
            timeout=(None if int(UPSTREAM_CONNECT_TIMEOUT_SECONDS) <= 0 else float(UPSTREAM_CONNECT_TIMEOUT_SECONDS)),
        )
    return http.client.HTTPConnection(
        host,
        port,
        timeout=(None if int(UPSTREAM_CONNECT_TIMEOUT_SECONDS) <= 0 else float(UPSTREAM_CONNECT_TIMEOUT_SECONDS)),
    )


def _get_proxy_connection(scheme: str, host: str, port: int):
    key = (scheme, host, port)
    if not PROXY_KEEPALIVE_ENABLED:
        return key, _new_proxy_connection(scheme, host, port)

    cache = _proxy_cache()
    timestamp = time.time()
    # Values are (connection, last_used). Accept old bare connection objects if
    # a user hot-reloads/customizes this script during development.
    entry = cache.get(key)
    connection = None
    if isinstance(entry, tuple) and len(entry) == 2:
        candidate, last_used = entry
        if float(PROXY_IDLE_CONNECTION_SECONDS) > 0 and timestamp - float(last_used) > float(PROXY_IDLE_CONNECTION_SECONDS):
            try:
                candidate.close()
            except Exception:
                pass
            cache.pop(key, None)
        else:
            connection = candidate
    elif entry is not None:
        connection = entry

    if connection is None:
        connection = _new_proxy_connection(scheme, host, port)
    cache[key] = (connection, timestamp)

    max_idle = int(PROXY_MAX_IDLE_CONNECTIONS)
    if max_idle > 0 and len(cache) > max_idle:
        ordered = sorted(
            cache.items(),
            key=lambda item: item[1][1] if isinstance(item[1], tuple) else 0,
        )
        for stale_key, stale_entry in ordered[: max(0, len(cache) - max_idle)]:
            if stale_key == key:
                continue
            stale_conn = stale_entry[0] if isinstance(stale_entry, tuple) else stale_entry
            cache.pop(stale_key, None)
            try:
                stale_conn.close()
            except Exception:
                pass
    return key, connection

def _drop_proxy_connection(key, connection=None) -> None:
    cache = _proxy_cache()
    cached = cache.pop(key, None)
    if isinstance(cached, tuple):
        cached = cached[0]
    target = cached if cached is not None else connection
    if target is not None:
        try:
            target.close()
        except Exception:
            pass

def proxy_request(
    method: str,
    rel_path: str,
    query: str,
    headers: dict,
    body: bytes,
):
    """
    Forward one request to the selected local backend.

    Optimizations versus the previous implementation:
    - localhost keep-alive connections are reused per worker thread
    - the raw query string isn't pointlessly quote/dequote-copied
    - stale connections are discarded safely
    - response reads are chunked to reduce large temporary allocations
    - loopback validation supports all loopback IPs while remaining secure
    """
    import urllib.parse

    upstream_url = _select_upstream(rel_path)

    scheme, host, port, base_path = parse_upstream_base(upstream_url)

    if not _upstream_host_allowed(host):
        return (
            400,
            {"content-type": "text/plain; charset=utf-8"},
            b"UPSTREAM blocked by network policy",
            {
                "source": "proxy",
                "error": f"UPSTREAM blocked by UPSTREAM_NETWORK_POLICY={UPSTREAM_NETWORK_POLICY!r}",
                "upstream": f"{scheme}://{host}:{port}",
            },
        )

    # rel_path arrives decoded from the VPS. Quote unsafe path characters while
    # preserving normal URL path syntax and existing percent escapes.
    encoded_rel = urllib.parse.quote(
        (rel_path or "").lstrip("/"),
        safe="/%:@-._~!$&'()*+,;=",
    )
    clean_query = (query or "").replace("\r", "").replace("\n", "")

    path = "/" + encoded_rel
    if base_path:
        path = base_path + path
    if clean_query:
        path += "?" + clean_query

    output_headers = {}
    for key, value in (headers or {}).items():
        lower_key = str(key).lower()
        if lower_key in HOP_BY_HOP or lower_key in {"host", "content-length"}:
            continue
        safe_key = str(key).replace("\r", "").replace("\n", "")
        safe_value = str(value).replace("\r", "").replace("\n", "")
        if safe_key:
            output_headers[safe_key] = safe_value

    # Local backend Host header must describe the local upstream. The original
    # public host remains available as X-Forwarded-Host from the VPS.
    host_header = host
    if (scheme == "http" and port != 80) or (scheme == "https" and port != 443):
        host_header = f"{host}:{port}"
    output_headers["Host"] = host_header
    output_headers["Content-Length"] = str(len(body))

    key, connection = _get_proxy_connection(scheme, host, port)
    reusable = PROXY_KEEPALIVE_ENABLED

    try:
        connection.request(
            method,
            path,
            body=body,
            headers=output_headers,
        )
        if connection.sock is not None:
            connection.sock.settimeout(
                None if float(UPSTREAM_RESPONSE_TIMEOUT_SECONDS) <= 0
                else float(UPSTREAM_RESPONSE_TIMEOUT_SECONDS)
            )
        response = connection.getresponse()
        status = int(response.status)

        chunks = []
        total = 0
        read_size = max(16 * 1024, int(PROXY_READ_CHUNK_BYTES))
        while True:
            chunk = response.read(read_size)
            if not chunk:
                break
            total += len(chunk)
            if int(MAX_PROXY_BYTES) > 0 and total > int(MAX_PROXY_BYTES):
                _drop_proxy_connection(key, connection)
                return (
                    502,
                    {"content-type": "text/plain; charset=utf-8"},
                    b"Upstream response too large",
                    {
                        "source": "proxy",
                        "error": "response too large",
                        "upstream": upstream_url,
                        "upstream_path": path,
                        "status": status,
                    },
                )
            chunks.append(chunk)

        response_body = b"".join(chunks)
        response_headers = {}
        for header_key, header_value in response.getheaders():
            if header_key.lower() in HOP_BY_HOP:
                continue
            response_headers[header_key] = header_value

        if getattr(response, "will_close", False):
            reusable = False

        if not reusable:
            _drop_proxy_connection(key, connection)
        elif PROXY_KEEPALIVE_ENABLED:
            _proxy_cache()[key] = (connection, time.time())

        return (
            status,
            response_headers,
            response_body,
            {
                "source": "proxy",
                "upstream": upstream_url,
                "upstream_path": path,
                "status": status,
                "resp_len": len(response_body),
                "connection_reused": bool(PROXY_KEEPALIVE_ENABLED and reusable),
            },
        )
    except Exception as error:
        _drop_proxy_connection(key, connection)
        message = (
            f"[PROXY] Failed upstream='{upstream_url}' "
            f"path='{path}' error={type(error).__name__}: {error}"
        )
        log_repeatable_error("proxy_request", message)
        return (
            502,
            {
                "content-type": "text/plain; charset=utf-8",
                "access-control-allow-origin": "*",
                "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
                "access-control-allow-headers": "Content-Type, Authorization, Origin, Accept",
            },
            f"Upstream error: {type(error).__name__}: {error}".encode("utf-8", errors="replace"),
            {
                "source": "proxy",
                "error": f"{type(error).__name__}: {error}",
                "upstream": upstream_url,
                "upstream_path": path,
            },
        )




def _build_tunnel_response(
    req_id: Any,
    status: int,
    headers: dict,
    body: bytes,
    encode_body: bool,
) -> dict:
    response = {
        "type": "resp",
        "id": req_id,
        "status": int(status),
        "headers": dict(headers or {}),
    }
    if encode_body:
        response["body_b64"] = base64.b64encode(body or b"").decode("ascii")
    else:
        response["_body_raw"] = body or b""
    return response

async def handle_req(msg: dict, encode_body: bool = True) -> dict:
    global TOTAL_REQS
    global TOTAL_BYTES_SENT
    global CURRENT_REQS
    global STATIC_REQS
    global PROXY_REQS
    global LAST_REQUEST_TS
    global HAS_RECEIVED_REQUEST

    LAST_REQUEST_TS = time.time()
    HAS_RECEIVED_REQUEST = True

    req_id = msg.get("id")
    method = msg.get("method", "GET")
    rel_path = msg.get("path", "")
    query = msg.get("query", "")
    headers = msg.get("headers", {}) or {}
    body_base64 = msg.get("body_b64", "") or ""
    route_token = _CURRENT_HOST_ROUTE.set(_host_route_for_headers(headers))

    if str(method).upper() == "OPTIONS" and HANDLE_OPTIONS_LOCALLY:
        _CURRENT_HOST_ROUTE.reset(route_token)
        return _build_tunnel_response(
            req_id,
            200,
            {
                "access-control-allow-origin": str(CORS_ALLOW_ORIGIN),
                "access-control-allow-methods": str(CORS_ALLOW_METHODS),
                "access-control-allow-headers": str(CORS_ALLOW_HEADERS),
                "access-control-max-age": "86400",
            },
            b"",
            encode_body,
        )

    request_start = time.time()
    CURRENT_REQS += 1

    try:
        try:
            body = (
                base64.b64decode(
                    body_base64.encode("ascii")
                )
                if body_base64
                else b""
            )
        except Exception:
            body = b""

        if _limit_exceeded(MAX_REQUEST_BODY_BYTES, len(body)):
            return _build_tunnel_response(
                req_id,
                413,
                {"content-type": "text/plain; charset=utf-8"},
                b"Request body exceeds this agent's configured limit",
                encode_body,
            )

        host_header = headers.get("host", "")
        normalized_rel = (
            rel_path or ""
        ).lstrip("/")
        normalized_rel_lower = (
            normalized_rel.lower()
        )

        if (
            FAVICON_BYPASS_ENABLED
            and normalized_rel_lower
            in ("favicon.ico", "favicon.ico/")
        ):
            route_mode = "custom-favicon"
        else:
            route_mode = (
                "proxy"
                if should_proxy(rel_path)
                else "static"
            )

        if (
            normalized_rel_lower
            == "__hostish/version"
        ):
            (
                status,
                output_headers,
                output_body,
                meta,
            ) = _metadata_version_response()
            route_mode = "agent-meta"
        else:
            log_event(
                f"[REQ] START | ID: {req_id} | "
                f"Method: {method} | "
                f"Path: /{rel_path}"
                + (
                    f" query='{query}'"
                    if query
                    else ""
                )
                + (
                    f" host='{host_header}'"
                    if host_header
                    else ""
                )
                + (
                    f" | Body Size: "
                    f"{fmt_bytes(len(body))} "
                    f"| Mode: {route_mode}"
                )
            )

            if (
                PRINT_REQUEST_HEADERS
                and headers
            ):
                log(
                    "   -> headers: "
                    + json.dumps(
                        _redacted_headers_for_log(headers),
                        ensure_ascii=False,
                    )
                )

            if (
                PRINT_REQUEST_BODY_PREVIEW
                and body
            ):
                log(
                    "   -> body preview: "
                    + _preview_bytes(body)
                )

            if route_mode == "custom-favicon":
                favicon_body = await run_in_thread(
                    fetch_custom_favicon
                )

                if favicon_body is not None:
                    status = 200
                    output_headers = {
                        "content-type": (
                            _favicon_cache.get(
                                "content_type",
                                "image/x-icon",
                            )
                        ),
                        "cache-control": (
                            "public, max-age=86400"
                        ),
                        "access-control-allow-origin": "*",
                    }
                    output_body = favicon_body
                    meta = {
                        "source": "custom-favicon",
                        "endpoint": f"/{rel_path}",
                        "size": len(favicon_body),
                    }
                else:
                    route_mode = (
                        "proxy"
                        if should_proxy(rel_path)
                        else "static"
                    )

                    if route_mode == "proxy":
                        (
                            status,
                            output_headers,
                            output_body,
                            meta,
                        ) = await run_in_thread(
                            proxy_request,
                            method,
                            rel_path,
                            query,
                            headers,
                            body,
                        )
                    else:
                        (
                            status,
                            output_headers,
                            output_body,
                            meta,
                        ) = await run_in_thread(
                            read_static_file,
                            rel_path,
                            method,
                            headers,
                        )

            elif route_mode == "proxy":
                (
                    status,
                    output_headers,
                    output_body,
                    meta,
                ) = await run_in_thread(
                    proxy_request,
                    method,
                    rel_path,
                    query,
                    headers,
                    body,
                )
            else:
                (
                    status,
                    output_headers,
                    output_body,
                    meta,
                ) = await run_in_thread(
                    read_static_file,
                    rel_path,
                    method,
                    headers,
                )

        if (
            status == 404
            and meta.get("source")
            not in (
                "agent-meta",
                "agent-404-redirect",
                "custom-favicon",
            )
        ):
            if CUSTOM_404_ENABLED:
                custom_404 = await run_in_thread(
                    _serve_custom_404_if_configured
                )

                if custom_404 is not None:
                    (
                        status,
                        output_headers,
                        output_body,
                        meta,
                    ) = custom_404
            else:
                (
                    status,
                    output_headers,
                    output_body,
                    meta,
                ) = _hostish_default_404_redirect()

        (
            status,
            output_headers,
            output_body,
            meta,
        ) = await run_in_thread(
            _apply_ip_protection_to_response,
            req_id,
            status,
            output_headers,
            output_body,
            meta,
        )

        output_headers = dict(
            output_headers or {}
        )
        if ADD_CORS_HEADER_TO_RESPONSES:
            output_headers.setdefault(
                "access-control-allow-origin",
                str(CORS_ALLOW_ORIGIN),
            )

        elapsed_ms = int(
            (time.time() - request_start)
            * 1000
        )

        TOTAL_REQS += 1
        TOTAL_BYTES_SENT += len(output_body)
        _status_count_inc(status)

        if route_mode == "proxy":
            PROXY_REQS += 1
        elif route_mode == "static":
            STATIC_REQS += 1

        source = meta.get("source")

        if source == "static":
            served_rel = meta.get(
                "served_rel",
                rel_path,
            )
            full_path = meta.get("full_path")

            if full_path:
                log_event(
                    f"[REQ] SERVED | "
                    f"ID: {req_id} | "
                    f"Status: {status} | "
                    f"File: '{served_rel}' | "
                    f"Size: "
                    f"{fmt_bytes(len(output_body))} | "
                    f"Type: "
                    f"'{output_headers.get('content-type', '?')}' | "
                    f"Time: {elapsed_ms}ms"
                )
                log(
                    f"   -> local file: "
                    f"{full_path}"
                )
            else:
                log_event(
                    f"[REQ] FAILED | "
                    f"ID: {req_id} | "
                    f"Status: {status} | "
                    f"File: '{served_rel}' | "
                    f"Reason: "
                    f"'{meta.get('error', 'unknown')}' | "
                    f"Time: {elapsed_ms}ms"
                )

        elif source == "proxy":
            log_event(
                f"[PROXY] DONE | "
                f"ID: {req_id} | "
                f"Status: {status} | "
                f"Upstream: "
                f"'{meta.get('upstream', '?')}' | "
                f"Path: "
                f"'{meta.get('upstream_path', '?')}' | "
                f"Size: "
                f"{fmt_bytes(len(output_body))} | "
                f"Time: {elapsed_ms}ms"
            )

            if meta.get("error"):
                log(
                    "   -> proxy info: "
                    f"{meta['error']}"
                )

        elif source == "custom-favicon":
            log_event(
                f"[REQ] FAVICON | "
                f"ID: {req_id} | "
                f"Status: {status} | "
                "Served custom remote favicon | "
                f"Size: "
                f"{fmt_bytes(len(output_body))} | "
                f"Time: {elapsed_ms}ms"
            )

        elif source == "custom-404":
            log_event(
                f"[REQ] 404 CUSTOM | "
                f"ID: {req_id} | "
                f"Served: "
                f"'{meta.get('served_rel')}' | "
                f"Size: "
                f"{fmt_bytes(len(output_body))} | "
                f"Time: {elapsed_ms}ms"
            )
            log(
                f"   -> custom 404 file: "
                f"{meta.get('full_path')}"
            )

        elif source == "agent-404-redirect":
            log_event(
                f"[REQ] 404 REDIRECT | "
                f"ID: {req_id} -> "
                f"{meta.get('target')} | "
                f"Time: {elapsed_ms}ms"
            )

        else:
            log(
                f"[REQ] META | "
                f"ID: {req_id} | "
                f"Endpoint: "
                f"{meta.get('endpoint')} | "
                f"Size: "
                f"{fmt_bytes(len(output_body))} | "
                f"Time: {elapsed_ms}ms"
            )

        print_summary()

        return _build_tunnel_response(
            req_id,
            status,
            output_headers,
            output_body,
            encode_body,
        )

    except Exception as error:
        elapsed_ms = int(
            (time.time() - request_start)
            * 1000
        )

        message = (
            f"[REQ] ERROR | ID: {req_id} | "
            f"{type(error).__name__}: {error} | "
            f"Time: {elapsed_ms}ms"
        )

        log_repeatable_error(
            "handle_req",
            message,
        )
        traceback.print_exc()

        return _build_tunnel_response(
            req_id,
            500,
            {
                "content-type": "text/plain; charset=utf-8",
                "access-control-allow-origin": "*",
                "access-control-allow-methods": "GET, POST, PUT, PATCH, DELETE, OPTIONS",
                "access-control-allow-headers": "Content-Type, Authorization, Origin, Accept",
            },
            b"Internal agent error",
            encode_body,
        )
    finally:
        CURRENT_REQS = max(
            0,
            CURRENT_REQS - 1,
        )
        _CURRENT_HOST_ROUTE.reset(route_token)



# =========================================================
# PROTOCOL v3: FULL REQUEST/RESPONSE STREAMING
# =========================================================
class RequestBodyLimitExceeded(Exception):
    pass


class V3ResponseAborted(Exception):
    """Raised after resp_start when a streaming response can no longer continue."""
    pass


class ProxyTargetBlocked(Exception):
    pass


def _response_is_textual(headers: dict) -> bool:
    content_type = ""
    for key, value in (headers or {}).items():
        if str(key).lower() == "content-type":
            content_type = str(value).split(";", 1)[0].strip().lower()
            break
    return (
        content_type.startswith("text/")
        or content_type in {
            "application/json", "application/ld+json", "application/javascript",
            "application/x-javascript", "application/xml", "application/xhtml+xml",
            "application/graphql-response+json", "application/x-www-form-urlencoded",
        }
        or content_type.endswith("+json")
        or content_type.endswith("+xml")
    )


def _prepare_static_stream(
    rel_path: str,
    method: str = "GET",
    request_headers: Optional[dict] = None,
):
    requested_rel = rel_path
    request_headers = dict(request_headers or {})
    method_upper = str(method or "GET").upper()

    if _sensitive_static_path(rel_path):
        return 404, {"content-type": "text/plain; charset=utf-8"}, None, {
            "source": "static", "served_rel": rel_path, "requested_rel": requested_rel,
            "full_path": None, "error": "sensitive static path blocked",
        }
    if rel_path == "" or rel_path.endswith("/"):
        rel_path += "index.html"
    try:
        full_path = safe_join(_effective_website_dir(), rel_path)
    except ValueError as error:
        return 403, {"content-type": "text/plain; charset=utf-8"}, None, {
            "source": "static", "served_rel": rel_path, "requested_rel": requested_rel,
            "full_path": None, "error": str(error),
        }
    if not os.path.isfile(full_path):
        return 404, {"content-type": "text/plain; charset=utf-8"}, None, {
            "source": "static", "served_rel": rel_path, "requested_rel": requested_rel,
            "full_path": full_path, "error": "not found",
        }

    size = os.path.getsize(full_path)
    if _limit_exceeded(MAX_FILE_BYTES, size):
        return 413, {"content-type": "text/plain; charset=utf-8"}, None, {
            "source": "static", "served_rel": rel_path, "requested_rel": requested_rel,
            "full_path": full_path, "error": "file exceeds this agent's configured limit",
            "size": size,
        }

    output_headers = _static_entity_headers(full_path, size)
    range_header = ""
    for key, value in request_headers.items():
        if str(key).lower() == "range":
            range_header = str(value)
            break

    byte_range = None
    if method_upper in {"GET", "HEAD"} and range_header and _should_honor_if_range(request_headers, output_headers):
        try:
            byte_range = _parse_single_byte_range(range_header, size)
        except StaticRangeNotSatisfiable as error:
            output_headers["content-range"] = f"bytes */{size}"
            output_headers["content-length"] = "0"
            return 416, output_headers, None, {
                "source": "static", "served_rel": rel_path, "requested_rel": requested_rel,
                "full_path": full_path, "error": str(error), "size": size,
                "head_only": True,
            }

    if byte_range is not None:
        range_start, range_end = byte_range
        range_length = range_end - range_start + 1
        output_headers["content-range"] = f"bytes {range_start}-{range_end}/{size}"
        output_headers["content-length"] = str(range_length)
        status = 206
    else:
        range_start = 0
        range_length = size
        output_headers["content-length"] = str(size)
        status = 200

    return status, output_headers, full_path, {
        "source": "static", "served_rel": rel_path, "requested_rel": requested_rel,
        "full_path": full_path, "size": size, "range": byte_range,
        "range_start": range_start, "range_length": range_length,
        "head_only": method_upper == "HEAD",
    }


async def _file_chunks(full_path: str, start: int = 0, length: Optional[int] = None):
    file_obj = await asyncio.to_thread(open, full_path, "rb")
    try:
        if int(start or 0) > 0:
            await asyncio.to_thread(file_obj.seek, int(start))
        remaining = None if length is None else max(0, int(length))
        read_size = max(16 * 1024, int(STATIC_READ_CHUNK_BYTES))
        while remaining is None or remaining > 0:
            amount = read_size if remaining is None else min(read_size, remaining)
            chunk = await asyncio.to_thread(file_obj.read, amount)
            if not chunk:
                break
            if remaining is not None:
                remaining -= len(chunk)
            yield chunk
    finally:
        await asyncio.to_thread(file_obj.close)


async def _single_body_chunks(body: bytes):
    if body:
        yield body


async def _mask_stream_chunks(chunks, headers: dict):
    """Length-preserving streaming IP replacement, including chunk boundaries."""
    if not IP_PROTECTION_ENABLED or not _response_is_textual(headers):
        async for chunk in chunks:
            yield chunk
        return

    public_ip = await asyncio.to_thread(fetch_public_ip, False)
    if not public_ip:
        async for chunk in chunks:
            yield chunk
        return

    needle = public_ip.encode("utf-8")
    replacement = IP_PROTECTION_REPLACEMENT.ljust(len(public_ip)).encode("utf-8")
    keep = max(0, len(needle) - 1)
    carry = b""
    async for chunk in chunks:
        data = carry + (chunk or b"")
        if keep and len(data) > keep:
            emit, carry = data[:-keep], data[-keep:]
        elif keep:
            carry = data
            continue
        else:
            emit, carry = data, b""
        yield emit.replace(needle, replacement)
    if carry:
        yield carry.replace(needle, replacement)


def _proxy_target_details(rel_path: str, query: str, headers: dict):
    upstream_url = _select_upstream(rel_path)
    scheme, host, port, base_path = parse_upstream_base(upstream_url)
    if not _upstream_host_allowed(host):
        raise ProxyTargetBlocked(
            f"UPSTREAM {host!r} blocked by UPSTREAM_NETWORK_POLICY={UPSTREAM_NETWORK_POLICY!r}"
        )

    encoded_rel = urllib.parse.quote(
        (rel_path or "").lstrip("/"), safe="/%:@-._~!$&'()*+,;="
    )
    clean_query = (query or "").replace("\r", "").replace("\n", "")
    path = "/" + encoded_rel
    if base_path:
        path = base_path + path
    if clean_query:
        path += "?" + clean_query

    output_headers = {}
    for key, value in (headers or {}).items():
        lower = str(key).lower()
        if lower in HOP_BY_HOP or lower == "host":
            continue
        safe_key = str(key).replace("\r", "").replace("\n", "")
        safe_value = str(value).replace("\r", "").replace("\n", "")
        if safe_key:
            output_headers[safe_key] = safe_value

    host_header = host
    if ":" in host and not host.startswith("["):
        host_header = f"[{host}]"
    if (scheme == "http" and port != 80) or (scheme == "https" and port != 443):
        host_header = f"{host_header}:{port}"
    output_headers["Host"] = host_header
    return upstream_url, scheme, host, port, path, output_headers


def _new_stream_proxy_connection(scheme: str, host: str, port: int):
    import http.client
    timeout = None if float(UPSTREAM_CONNECT_TIMEOUT_SECONDS) <= 0 else float(UPSTREAM_CONNECT_TIMEOUT_SECONDS)
    if scheme == "https":
        return http.client.HTTPSConnection(host, port, timeout=timeout)
    return http.client.HTTPConnection(host, port, timeout=timeout)


async def _proxy_stream_v3(method: str, rel_path: str, query: str, headers: dict, body_chunks):
    """Stream the browser request into the local HTTP server, then stream back."""
    upstream_url, scheme, host, port, path, output_headers = _proxy_target_details(
        rel_path, query, headers
    )

    # Reject known oversized bodies before connecting. Unknown/chunked bodies are
    # checked incrementally while they cross the agent.
    content_length = None
    for key, value in output_headers.items():
        if str(key).lower() == "content-length":
            try:
                content_length = max(0, int(value))
            except (TypeError, ValueError):
                content_length = None
            break
    if content_length is not None and _limit_exceeded(MAX_REQUEST_BODY_BYTES, content_length):
        raise RequestBodyLimitExceeded("request body exceeds this agent's configured limit")

    connection = _new_stream_proxy_connection(scheme, host, port)
    response = None
    total_in = 0
    total_out = 0
    chunked_request = content_length is None and str(method).upper() not in {"GET", "HEAD"}

    def begin_request():
        connection.putrequest(str(method).upper(), path, skip_host=True, skip_accept_encoding=True)
        for key, value in output_headers.items():
            lower = str(key).lower()
            if lower in HOP_BY_HOP:
                continue
            if lower == "content-length" and chunked_request:
                continue
            connection.putheader(str(key), str(value))
        if chunked_request:
            connection.putheader("Transfer-Encoding", "chunked")
        connection.endheaders()
        if connection.sock is not None:
            timeout = None if float(UPSTREAM_RESPONSE_TIMEOUT_SECONDS) <= 0 else float(UPSTREAM_RESPONSE_TIMEOUT_SECONDS)
            connection.sock.settimeout(timeout)

    try:
        await asyncio.to_thread(begin_request)
        async for chunk in body_chunks:
            if not chunk:
                continue
            total_in += len(chunk)
            if _limit_exceeded(MAX_REQUEST_BODY_BYTES, total_in):
                raise RequestBodyLimitExceeded("request body exceeds this agent's configured limit")
            if chunked_request:
                framed = f"{len(chunk):X}\r\n".encode("ascii") + chunk + b"\r\n"
                await asyncio.to_thread(connection.send, framed)
            else:
                await asyncio.to_thread(connection.send, chunk)
        if chunked_request:
            await asyncio.to_thread(connection.send, b"0\r\n\r\n")

        response = await asyncio.to_thread(connection.getresponse)
        status = int(response.status)
        response_headers = {}
        for key, value in response.getheaders():
            if key.lower() in HOP_BY_HOP:
                continue
            # Preserve the last value, matching Hostish's existing dict protocol.
            response_headers[key] = value

        async def response_chunks():
            nonlocal total_out
            read_size = max(16 * 1024, int(PROXY_READ_CHUNK_BYTES))
            try:
                while True:
                    chunk = await asyncio.to_thread(response.read, read_size)
                    if not chunk:
                        break
                    total_out += len(chunk)
                    if _limit_exceeded(MAX_PROXY_BYTES, total_out):
                        raise RuntimeError("upstream response exceeds this agent's configured limit")
                    yield chunk
            finally:
                try:
                    await asyncio.to_thread(connection.close)
                except Exception:
                    pass

        return status, response_headers, response_chunks(), {
            "source": "proxy", "upstream": upstream_url, "upstream_path": path,
            "request_bytes": total_in,
        }
    except Exception:
        try:
            await asyncio.to_thread(connection.close)
        except Exception:
            pass
        raise


async def _send_v3_response(
    request_id: str,
    status: int,
    headers: dict,
    chunks,
    send_text_locked,
    send_bytes_locked,
    wait_response_credit,
):
    global TOTAL_BYTES_SENT

    output_headers = dict(headers or {})
    if ADD_CORS_HEADER_TO_RESPONSES:
        output_headers.setdefault("access-control-allow-origin", str(CORS_ALLOW_ORIGIN))

    if IP_PROTECTION_ENABLED:
        public_ip = await asyncio.to_thread(fetch_public_ip, False)
        if public_ip:
            output_headers, _ = _mask_public_ip_in_headers(output_headers, public_ip)

    await send_text_locked(
        {
            "type": "resp_start",
            "id": request_id,
            "status": int(status),
            "headers": output_headers,
        }
    )

    prefix = b"R3" + bytes.fromhex(request_id)
    total = 0
    chunk_size = max(16 * 1024, int(TUNNEL_CHUNK_BYTES))
    try:
        masked = _mask_stream_chunks(chunks, output_headers)
        async for original in masked:
            if not original:
                continue
            view = memoryview(original)
            for offset in range(0, len(view), chunk_size):
                chunk = bytes(view[offset : offset + chunk_size])
                await wait_response_credit(request_id)
                await send_bytes_locked(prefix + chunk)
                total += len(chunk)
                TOTAL_BYTES_SENT += len(chunk)
    except asyncio.CancelledError:
        # Browser cancellation is normal; no need to manufacture a second HTTP response.
        raise
    except Exception as error:
        try:
            await send_text_locked(
                {
                    "type": "resp_abort",
                    "id": request_id,
                    "error": f"{type(error).__name__}: {error}"[:512],
                }
            )
        except Exception:
            pass
        raise V3ResponseAborted(str(error)) from error

    await send_text_locked({"type": "resp_end", "id": request_id})
    return total


async def handle_req_v3(
    msg: dict,
    body_chunks,
    send_text_locked,
    send_bytes_locked,
    wait_response_credit,
):
    """Protocol-v3 handler preserving Hostish features while streaming bodies."""
    global TOTAL_REQS, CURRENT_REQS, STATIC_REQS, PROXY_REQS, LAST_REQUEST_TS, HAS_RECEIVED_REQUEST

    LAST_REQUEST_TS = time.time()
    HAS_RECEIVED_REQUEST = True
    request_id = str(msg.get("id", ""))
    method = str(msg.get("method", "GET")).upper()
    rel_path = str(msg.get("path", ""))
    query = str(msg.get("query", ""))
    headers = dict(msg.get("headers", {}) or {})
    request_start = time.time()
    CURRENT_REQS += 1
    route_token = _CURRENT_HOST_ROUTE.set(_host_route_for_headers(headers))

    try:
        normalized_rel = rel_path.lstrip("/")
        normalized_lower = normalized_rel.lower()
        host_header = headers.get("host", "")

        if PRINT_REQUEST_HEADERS and headers:
            log("   -> headers: " + json.dumps(_redacted_headers_for_log(headers), ensure_ascii=False))

        route_mode = "proxy" if should_proxy(rel_path) else "static"
        if FAVICON_BYPASS_ENABLED and normalized_lower in {"favicon.ico", "favicon.ico/"}:
            route_mode = "custom-favicon"

        log_event(
            f"[REQ] START | ID: {request_id} | Method: {method} | Path: /{rel_path}"
            + (f" query='{query}'" if query else "")
            + (f" host='{host_header}'" if host_header else "")
            + f" | Mode: {route_mode}"
        )

        if method == "OPTIONS" and HANDLE_OPTIONS_LOCALLY:
            status = 200
            output_headers = {
                "access-control-allow-origin": str(CORS_ALLOW_ORIGIN),
                "access-control-allow-methods": str(CORS_ALLOW_METHODS),
                "access-control-allow-headers": str(CORS_ALLOW_HEADERS),
                "access-control-max-age": "86400",
            }
            chunks = _single_body_chunks(b"")
            meta = {"source": "options"}

        elif normalized_lower == "__hostish/version":
            status, output_headers, output_body, meta = _metadata_version_response()
            chunks = _single_body_chunks(output_body)
            route_mode = "agent-meta"

        elif route_mode == "custom-favicon":
            favicon_body = await asyncio.to_thread(fetch_custom_favicon)
            if favicon_body is not None:
                status = 200
                output_headers = {
                    "content-type": _favicon_cache.get("content_type", "image/x-icon"),
                    "cache-control": "public, max-age=86400",
                    "content-length": str(len(favicon_body)),
                }
                chunks = _single_body_chunks(b"" if method == "HEAD" else favicon_body)
                meta = {"source": "custom-favicon", "size": len(favicon_body)}
            else:
                route_mode = "proxy" if should_proxy(rel_path) else "static"
                if route_mode == "proxy":
                    status, output_headers, chunks, meta = await _proxy_stream_v3(
                        method, rel_path, query, headers, body_chunks
                    )
                else:
                    status, output_headers, full_path, meta = await asyncio.to_thread(
                        _prepare_static_stream, rel_path, method, headers
                    )
                    if full_path and not meta.get("head_only"):
                        chunks = _file_chunks(
                            full_path,
                            meta.get("range_start", 0),
                            meta.get("range_length"),
                        )
                    else:
                        chunks = _single_body_chunks(
                            b"" if meta.get("head_only") else (b"Forbidden" if status == 403 else b"Not Found")
                        )

        elif route_mode == "proxy":
            status, output_headers, chunks, meta = await _proxy_stream_v3(
                method, rel_path, query, headers, body_chunks
            )
        else:
            status, output_headers, full_path, meta = await asyncio.to_thread(
                _prepare_static_stream, rel_path, method, headers
            )
            if full_path and not meta.get("head_only"):
                chunks = _file_chunks(
                    full_path,
                    meta.get("range_start", 0),
                    meta.get("range_length"),
                )
            else:
                chunks = _single_body_chunks(
                    b"" if meta.get("head_only") else (b"Forbidden" if status == 403 else b"Not Found")
                )

        if status == 404 and meta.get("source") not in {
            "agent-meta", "agent-404-redirect", "custom-favicon"
        }:
            if CUSTOM_404_ENABLED:
                custom = await asyncio.to_thread(_serve_custom_404_if_configured)
                if custom is not None:
                    status, output_headers, output_body, meta = custom
                    chunks = _single_body_chunks(output_body)
            else:
                status, output_headers, output_body, meta = _hostish_default_404_redirect()
                chunks = _single_body_chunks(output_body)

        total = await _send_v3_response(
            request_id, status, output_headers, chunks,
            send_text_locked, send_bytes_locked, wait_response_credit,
        )
        TOTAL_REQS += 1
        _status_count_inc(status)
        if route_mode == "proxy":
            PROXY_REQS += 1
        elif route_mode == "static":
            STATIC_REQS += 1

        elapsed_ms = int((time.time() - request_start) * 1000)
        source = meta.get("source", route_mode)
        if source == "proxy":
            log_event(
                f"[PROXY] DONE | ID: {request_id} | Status: {status} | "
                f"Upstream: '{meta.get('upstream', '?')}' | Bytes: {fmt_bytes(total)} | Time: {elapsed_ms}ms"
            )
        elif source == "static":
            log_event(
                f"[REQ] SERVED | ID: {request_id} | Status: {status} | "
                f"File: '{meta.get('served_rel', rel_path)}' | Bytes: {fmt_bytes(total)} | Time: {elapsed_ms}ms"
            )
        else:
            log_event(
                f"[REQ] DONE | ID: {request_id} | Status: {status} | "
                f"Source: {source} | Bytes: {fmt_bytes(total)} | Time: {elapsed_ms}ms"
            )
        print_summary()

    except RequestBodyLimitExceeded as error:
        await _send_v3_response(
            request_id, 413, {"content-type": "text/plain; charset=utf-8"},
            _single_body_chunks(str(error).encode()),
            send_text_locked, send_bytes_locked, wait_response_credit,
        )
    except ProxyTargetBlocked as error:
        await _send_v3_response(
            request_id, 400, {"content-type": "text/plain; charset=utf-8"},
            _single_body_chunks(str(error).encode()),
            send_text_locked, send_bytes_locked, wait_response_credit,
        )
    except V3ResponseAborted as error:
        log_repeatable_error(
            "handle_req_v3_stream_abort",
            f"[REQ] STREAM ABORT | ID: {request_id} | {error}",
        )
        return
    except asyncio.CancelledError:
        raise
    except Exception as error:
        log_repeatable_error(
            "handle_req_v3",
            f"[REQ] ERROR | ID: {request_id} | {type(error).__name__}: {error}",
        )
        try:
            await _send_v3_response(
                request_id, 502,
                {"content-type": "text/plain; charset=utf-8"},
                _single_body_chunks(
                    f"Upstream error: {type(error).__name__}: {error}".encode("utf-8", errors="replace")
                ),
                send_text_locked, send_bytes_locked, wait_response_credit,
            )
        except Exception:
            pass
    finally:
        CURRENT_REQS = max(0, CURRENT_REQS - 1)
        _CURRENT_HOST_ROUTE.reset(route_token)


def _websocket_upstream_url(rel_path: str, query: str):
    upstream = _select_upstream(rel_path)
    scheme, host, port, base_path = parse_upstream_base(upstream)
    if not _upstream_host_allowed(host):
        raise ProxyTargetBlocked(
            f"WebSocket upstream blocked by UPSTREAM_NETWORK_POLICY={UPSTREAM_NETWORK_POLICY!r}"
        )
    ws_scheme = "wss" if scheme == "https" else "ws"
    encoded_rel = urllib.parse.quote(
        (rel_path or "").lstrip("/"), safe="/%:@-._~!$&'()*+,;="
    )
    path = "/" + encoded_rel
    if base_path:
        path = base_path + path
    if query:
        path += "?" + query.replace("\r", "").replace("\n", "")
    host_text = f"[{host}]" if ":" in host and not host.startswith("[") else host
    default_port = 443 if ws_scheme == "wss" else 80
    authority = host_text if port == default_port else f"{host_text}:{port}"
    return f"{ws_scheme}://{authority}{path}"


async def handle_user_websocket_bridge(
    msg: dict,
    inbound_queue: asyncio.Queue,
    send_text_locked,
    send_bytes_locked,
):
    request_id = str(msg.get("id", ""))
    rel_path = str(msg.get("path", ""))
    query = str(msg.get("query", ""))
    headers = dict(msg.get("headers", {}) or {})
    subprotocols = [str(x) for x in (msg.get("subprotocols") or []) if x]
    route_token = _CURRENT_HOST_ROUTE.set(_host_route_for_headers(headers))

    if not USER_WEBSOCKET_PROXY_ENABLED or not should_proxy(rel_path):
        _CURRENT_HOST_ROUTE.reset(route_token)
        await send_text_locked(
            {
                "type": "user_ws_accept", "id": request_id, "ok": False,
                "code": 1008, "reason": "WebSocket path is not configured for proxying",
            }
        )
        return

    try:
        target = _websocket_upstream_url(rel_path, query)
        extra_headers = []
        for key, value in headers.items():
            lower = str(key).lower()
            if lower in HOP_BY_HOP or lower in {"host", "content-length", "sec-websocket-key", "sec-websocket-version", "sec-websocket-extensions", "sec-websocket-protocol"}:
                continue
            extra_headers.append((str(key), str(value)))

        # websockets renamed extra_headers -> additional_headers in newer releases.
        connect_kwargs = {"subprotocols": subprotocols or None, "open_timeout": None if float(UPSTREAM_CONNECT_TIMEOUT_SECONDS) <= 0 else float(UPSTREAM_CONNECT_TIMEOUT_SECONDS)}
        try:
            import inspect
            if "additional_headers" in inspect.signature(websockets.connect).parameters:
                connect_kwargs["additional_headers"] = extra_headers
            else:
                connect_kwargs["extra_headers"] = extra_headers
        except Exception:
            connect_kwargs["extra_headers"] = extra_headers

        async with websockets.connect(target, **connect_kwargs) as local_ws:
            await send_text_locked(
                {
                    "type": "user_ws_accept", "id": request_id, "ok": True,
                    "subprotocol": getattr(local_ws, "subprotocol", None),
                }
            )

            async def local_to_vps():
                prefix = b"WR" + bytes.fromhex(request_id)
                async for payload in local_ws:
                    if isinstance(payload, bytes):
                        await send_bytes_locked(prefix + payload)
                    else:
                        await send_text_locked(
                            {"type": "user_ws_text", "id": request_id, "data": str(payload)}
                        )

            async def vps_to_local():
                while True:
                    event = await inbound_queue.get()
                    kind = event[0]
                    if kind == "text":
                        await local_ws.send(event[1])
                    elif kind == "bytes":
                        await local_ws.send(event[1])
                    elif kind == "close":
                        await local_ws.close(code=int(event[1] or 1000))
                        return

            tasks = {asyncio.create_task(local_to_vps()), asyncio.create_task(vps_to_local())}
            done, rest = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
            for task in rest:
                task.cancel()
            await asyncio.gather(*rest, return_exceptions=True)
            for task in done:
                task.result()
    except Exception as error:
        log_repeatable_error(
            "user_ws_proxy",
            f"[USER-WS] {request_id} failed: {type(error).__name__}: {error}",
        )
        try:
            await send_text_locked(
                {
                    "type": "user_ws_accept", "id": request_id, "ok": False,
                    "code": 1011, "reason": "Local WebSocket connection failed",
                }
            )
        except Exception:
            pass
    finally:
        try:
            await send_text_locked(
                {"type": "user_ws_close", "id": request_id, "code": 1000, "reason": ""}
            )
        except Exception:
            pass
        _CURRENT_HOST_ROUTE.reset(route_token)


def _check_status_sync():
    """
    Check Hostish's public status API.

    Returns:
        True:
            Hostish confirms this username is currently hosting.

        False:
            Hostish successfully answered and explicitly confirms the account
            is not hosting.

        None:
            The status request itself failed, returned malformed data, or used
            an unknown schema. A network/API failure must never be treated as
            proof that the site is offline.

    Current Hostish status responses use the "hosting" field. "online" is
    retained as a backwards-compatible fallback for older VPS builds.
    """
    import urllib.request

    url = (
        "https://hostish.site/api/status/"
        f"{USERNAME}"
    )

    try:
        request = urllib.request.Request(
            url,
            headers={
                "User-Agent": (
                    "Mozilla/5.0 "
                    "(Windows NT 10.0; Win64; x64) "
                    f"HostishAgent/{version}"
                ),
                "Accept": "application/json",
            },
            method="GET",
        )

        with urllib.request.urlopen(
            request,
            timeout=10,
            context=make_ssl_context(),
        ) as response:
            raw = response.read()
            data = json.loads(
                raw.decode("utf-8")
            )

        if not isinstance(data, dict):
            log(
                "[MONITOR] Status endpoint returned "
                "unexpected non-object JSON; ignoring "
                "this health check."
            )
            return None

        # Current public API schema.
        if isinstance(data.get("hosting"), bool):
            return data["hosting"]

        # Backwards compatibility with older Hostish status responses.
        if isinstance(data.get("online"), bool):
            return data["online"]

        # Some builds also include a textual state. Only consume values whose
        # meaning is unambiguous; otherwise fail open and keep the tunnel.
        status_value = str(
            data.get("status", "")
            or ""
        ).strip().lower()

        if status_value in {
            "online",
            "hosting",
            "live",
            "connected",
        }:
            return True

        if status_value in {
            "offline",
            "not_hosting",
            "not-hosting",
            "disconnected",
        }:
            return False

        log(
            "[MONITOR] Status endpoint did not include "
            "a recognized hosting/online field; "
            "ignoring this health check."
        )
        return None

    except Exception as error:
        log(
            "[MONITOR] Status check request "
            "encountered issues; keeping the current "
            "tunnel alive instead of treating the "
            "request failure as offline: "
            f"{type(error).__name__}: {error}"
        )
        return None


async def status_checker_loop() -> None:
    """
    When the public site has been idle, confirm that Hostish still sees this
    agent as hosting.

    Important behavior:
    - The public status API uses "hosting", not just the legacy "online" key.
    - A timeout/DNS/API parsing failure is NOT considered offline.
    - One isolated "offline" response is NOT enough to restart the process.
    - The tunnel must still believe it is connected before and after the
      confirmation check.
    """
    global LAST_REQUEST_TS
    global HAS_RECEIVED_REQUEST
    global IS_WS_CONNECTED

    while True:
        try:
            await asyncio.sleep(
                max(
                    1,
                    float(
                        IDLE_CHECK_INTERVAL_SECONDS
                    ),
                )
            )

            if not IS_WS_CONNECTED:
                continue

            now = time.time()
            time_since_last_request = (
                now - LAST_REQUEST_TS
            )

            should_check = (
                not HAS_RECEIVED_REQUEST
                or time_since_last_request
                >= float(
                    IDLE_CHECK_INTERVAL_SECONDS
                )
            )

            if not should_check:
                continue

            log(
                "[MONITOR] Idle check: no requests "
                "received recently. Confirming tunnel "
                "status with Hostish..."
            )

            first_status = await run_in_thread(
                _check_status_sync
            )

            if first_status is True:
                log(
                    "[MONITOR] Idle check: Hostish "
                    "confirms this agent is hosting."
                )
                continue

            if first_status is None:
                log(
                    "[MONITOR] Idle check: status "
                    "could not be confirmed. No restart "
                    "will occur from an inconclusive "
                    "health check."
                )
                continue

            # Hostish explicitly reported offline once. Do not restart on a
            # single stale/racing status response. Give the control plane a
            # brief chance to settle and confirm a second time.
            log(
                "[MONITOR] Idle check: Hostish "
                "reported offline once. Rechecking "
                "before taking any action..."
            )

            await asyncio.sleep(3)

            # If the WebSocket disconnected naturally while waiting, the main
            # reconnect loop is already handling it. There is nothing for the
            # idle monitor to restart.
            if not IS_WS_CONNECTED:
                log(
                    "[MONITOR] Idle check: tunnel "
                    "disconnected during confirmation; "
                    "normal reconnect logic will handle "
                    "it."
                )
                continue

            second_status = await run_in_thread(
                _check_status_sync
            )

            if second_status is not False:
                if second_status is True:
                    log(
                        "[MONITOR] Idle check: second "
                        "check confirms the site is "
                        "online. No restart needed."
                    )
                else:
                    log(
                        "[MONITOR] Idle check: second "
                        "check was inconclusive. No "
                        "restart will occur."
                    )
                continue

            # Both public checks explicitly reported offline while this process
            # still believes the authenticated tunnel is connected. This is
            # the narrow case the recovery restart is intended to repair.
            log_event(
                "[MONITOR] ALERT: Hostish explicitly "
                "reported this agent offline twice "
                "while its WebSocket still appears "
                "connected. Restarting the agent "
                "process to rebuild the tunnel..."
            )

            try:
                stop_managed_scripts()
            except Exception as error:
                log(
                    "[ERROR] Error stopping managed "
                    "scripts during restart: "
                    f"{error}"
                )

            arguments = [
                sys.executable
            ] + sys.argv

            # os.execv keeps this launched process session alive. Environment
            # state, including a user's temporary decision to skip an offered
            # update, is therefore preserved across this recovery restart.
            os.execv(
                sys.executable,
                arguments,
            )

        except asyncio.CancelledError:
            raise
        except Exception as error:
            log_repeatable_error(
                "status_checker_loop_err",
                "Error in status checker loop: "
                f"{error}",
            )


def validate_configuration() -> list[str]:
    errors = []
    mode = str(MODE or "").strip().lower()
    if mode not in {"static", "proxy", "hybrid"}:
        errors.append(f"MODE={MODE!r} is invalid; use static, proxy, or hybrid")

    if mode in {"static", "hybrid"} and not os.path.isdir(WEBSITE_DIR):
        errors.append(f"WEBSITE_DIR does not exist or is not a directory: {WEBSITE_DIR!r}")

    security_mode = str(STATIC_SECURITY_MODE or "").strip().lower()
    if security_mode not in {"safe", "custom", "unrestricted"}:
        errors.append(
            f"STATIC_SECURITY_MODE={STATIC_SECURITY_MODE!r} is invalid; use safe, custom, or unrestricted"
        )

    network_policy = str(UPSTREAM_NETWORK_POLICY or "").strip().lower()
    if network_policy not in {"loopback", "private", "any"}:
        errors.append(
            f"UPSTREAM_NETWORK_POLICY={UPSTREAM_NETWORK_POLICY!r} is invalid; use loopback, private, or any"
        )

    for label, value in {
        "MAX_CONCURRENT_REQUESTS": MAX_CONCURRENT_REQUESTS,
        "MAX_QUEUED_REQUESTS": MAX_QUEUED_REQUESTS,
        "MAX_REQUEST_BODY_BYTES": MAX_REQUEST_BODY_BYTES,
        "MAX_FILE_BYTES": MAX_FILE_BYTES,
        "MAX_PROXY_BYTES": MAX_PROXY_BYTES,
        "UPSTREAM_CONNECT_TIMEOUT_SECONDS": UPSTREAM_CONNECT_TIMEOUT_SECONDS,
        "UPSTREAM_RESPONSE_TIMEOUT_SECONDS": UPSTREAM_RESPONSE_TIMEOUT_SECONDS,
        "TUNNEL_CHUNK_BYTES": TUNNEL_CHUNK_BYTES,
        "REQUEST_STREAM_BUFFER_CHUNKS": REQUEST_STREAM_BUFFER_CHUNKS,
    }.items():
        try:
            if float(value) < 0:
                errors.append(f"{label} cannot be negative; use 0 for unlimited")
        except (TypeError, ValueError):
            errors.append(f"{label} must be numeric")

    if int(TUNNEL_PROTOCOL) not in {1, 2, 3}:
        errors.append("TUNNEL_PROTOCOL must be 1, 2, or 3")

    # Validate all configured upstream URLs and declared network policy at boot.
    if mode in {"proxy", "hybrid"}:
        targets = [("UPSTREAM_BASE", UPSTREAM_BASE)] + [
            (f"UPSTREAM_ROUTES[{prefix!r}]", target)
            for prefix, target in (UPSTREAM_ROUTES or {}).items()
        ]
        for label, target in targets:
            try:
                _scheme, host, _port, _path = parse_upstream_base(str(target))
                if not _upstream_host_allowed(host):
                    errors.append(
                        f"{label} target {target!r} is blocked by UPSTREAM_NETWORK_POLICY={UPSTREAM_NETWORK_POLICY!r}"
                    )
            except Exception as error:
                errors.append(f"{label}={target!r} is invalid: {error}")

    if CUSTOM_404_ENABLED:
        try:
            resolved = _resolve_custom_404_full_path()
            if not resolved or not os.path.isfile(resolved):
                errors.append(f"CUSTOM_404_PATH was enabled but cannot be read: {CUSTOM_404_PATH!r}")
        except Exception as error:
            errors.append(f"CUSTOM_404_PATH is invalid: {error}")

    if FAVICON_BYPASS_ENABLED:
        parsed = urllib.parse.urlparse(str(FAVICON_BYPASS_URL or ""))
        if parsed.scheme not in {"http", "https"} or not parsed.netloc:
            errors.append("FAVICON_BYPASS_URL must be a valid http:// or https:// URL")

    return errors


async def main():
    global CONNECT_COUNT, IS_WS_CONNECTED

    errors = validate_configuration()
    if errors:
        print("Hostish agent configuration errors:")
        for error in errors:
            print(f" - {error}")
        return

    if IP_PROTECTION_ENABLED:
        public_ip = fetch_public_ip(force=True)
        if public_ip:
            log("[INFO] IP protection initialized")
        else:
            error = _public_ip_cache.get("error") or "unknown error"
            log(f"[WARN] IP protection could not fetch public IP at startup (will retry): {error}")

    # Updater remains before managed scripts, preserving existing safe behavior.
    startup_version_check_or_prompt()
    print_startup_banner()
    start_configured_python_scripts_once()

    if PERIODIC_SUMMARY_ENABLED:
        asyncio.create_task(periodic_summary_loop())
    if IP_PROTECTION_ENABLED:
        asyncio.create_task(periodic_public_ip_refresh_loop())
    if AUTO_START_PYTHON_SCRIPTS_ENABLED:
        asyncio.create_task(managed_script_monitor_loop())
    if IDLE_STATUS_CHECK_ENABLED:
        asyncio.create_task(status_checker_loop())

    ssl_context = make_ssl_context()
    backoff = 2

    while True:
        try:
            log(f"[WS] Connecting to Hostish VPS WebSocket: {WS_URL}")
            async with websockets.connect(
                WS_URL,
                ssl=(ssl_context if str(WS_URL).lower().startswith("wss://") else None),
                max_size=max(1_500_000, int(WEBSOCKET_MAX_INCOMING_BYTES)),
                ping_interval=20,
                ping_timeout=20,
                open_timeout=15,
                close_timeout=5,
            ) as websocket:
                CONNECT_COUNT += 1
                log_event(f"[WS] WebSocket connected (connection #{CONNECT_COUNT})")

                capabilities = ["cancel"]
                advertised_host_routes = _normalize_host_routes_for_auth()
                if isinstance(globals().get("HOST_ROUTES"), dict):
                    capabilities.append("host_routes")
                if int(TUNNEL_PROTOCOL) >= 2:
                    capabilities.append("stream_response")
                if int(TUNNEL_PROTOCOL) >= 3:
                    capabilities.append("stream_request")
                    if USER_WEBSOCKET_PROXY_ENABLED:
                        capabilities.append("user_websocket")

                await websocket.send(
                    json.dumps(
                        {
                            "username": USERNAME,
                            "password": PASSWORD,
                            "protocol": int(TUNNEL_PROTOCOL),
                            "agent_version": int(version),
                            "capabilities": capabilities,
                            "host_routes": advertised_host_routes,
                        },
                        separators=(",", ":"),
                    )
                )
                log("[AUTH] Sent authentication credentials")

                raw = await websocket.recv()
                authentication = json.loads(raw)
                if authentication.get("type") != "auth" or not authentication.get("ok"):
                    detail = authentication.get("error") or "bad credentials"
                    log_repeatable_error(
                        "auth_failed",
                        f"[AUTH] Authentication failed ({detail}; check USERNAME/PASSWORD in agent.py)",
                    )
                    await asyncio.sleep(3)
                    continue

                backoff = 2
                IS_WS_CONNECTED = True
                log_event(f"[AUTH] Authenticated as '{USERNAME}' | Mode: {MODE}")
                print_ascii_art()
                log(f"[LIVE] PUBLIC URL IS LIVE: https://{USERNAME}.hostish.site/")
                log(f"[LIVE] {version_status_text()}")
                log(f"[LIVE] {_public_ip_status_text()}")
                log("--------------------------------------------------------------------------------")

                server_protocol = int(authentication.get("protocol", 1) or 1)
                negotiated_protocol = min(max(1, server_protocol), max(1, int(TUNNEL_PROTOCOL)))
                if negotiated_protocol >= 3:
                    negotiated_protocol = 3
                elif negotiated_protocol >= 2:
                    negotiated_protocol = 2
                else:
                    negotiated_protocol = 1
                log(f"[WS] Tunnel protocol negotiated: v{negotiated_protocol}")

                send_lock = asyncio.Lock()
                request_tasks: dict[str, asyncio.Task] = {}
                incoming_bodies: dict[str, asyncio.Queue] = {}
                response_credits: dict[str, dict] = {}
                user_ws_queues: dict[str, asyncio.Queue] = {}
                user_ws_tasks: dict[str, asyncio.Task] = {}

                max_active = int(MAX_CONCURRENT_REQUESTS)
                request_semaphore = asyncio.Semaphore(max_active) if max_active > 0 else None

                def over_agent_capacity() -> bool:
                    # 0 means unlimited for both settings. When concurrency is
                    # bounded but queue is unlimited, the semaphore naturally
                    # holds as many waiting tasks as the hoster requested.
                    if max_active <= 0:
                        return False
                    max_queue = int(MAX_QUEUED_REQUESTS)
                    if max_queue <= 0:
                        return False
                    return len(request_tasks) >= max_active + max_queue

                async def send_text_locked(payload: dict) -> None:
                    async with send_lock:
                        await websocket.send(
                            json.dumps(payload, separators=(",", ":"), ensure_ascii=False)
                        )

                async def send_bytes_locked(payload: bytes) -> None:
                    async with send_lock:
                        await websocket.send(payload)

                async def send_response_v2(response: dict) -> None:
                    body_raw = response.pop("_body_raw", b"") or b""
                    request_id = str(response.get("id", ""))
                    try:
                        request_id_raw = bytes.fromhex(request_id)
                    except ValueError:
                        request_id_raw = b""
                    if len(request_id_raw) != 16:
                        await send_text_locked(
                            _build_tunnel_response(
                                request_id, 500,
                                {"content-type": "text/plain; charset=utf-8"},
                                b"Invalid request id", True,
                            )
                        )
                        return
                    await send_text_locked(
                        {
                            "type": "resp_start", "id": request_id,
                            "status": int(response.get("status", 502)),
                            "headers": dict(response.get("headers", {}) or {}),
                            "size": len(body_raw),
                        }
                    )
                    prefix = b"H2" + request_id_raw
                    chunk_size = max(16 * 1024, int(TUNNEL_CHUNK_BYTES))
                    view = memoryview(body_raw)
                    for offset in range(0, len(view), chunk_size):
                        await send_bytes_locked(prefix + bytes(view[offset : offset + chunk_size]))
                    await send_text_locked({"type": "resp_end", "id": request_id})

                async def send_busy_response(message_payload: dict) -> None:
                    request_id = str(message_payload.get("id", ""))
                    body = b"Host is busy. Try again shortly."
                    if negotiated_protocol >= 3:
                        # Create temporary unlimited credits because this is an
                        # agent-originated policy response before VPS credits.
                        response_credits[request_id] = {"credit": 1, "event": asyncio.Event()}
                        response_credits[request_id]["event"].set()
                        await _send_v3_response(
                            request_id, 503,
                            {"content-type": "text/plain; charset=utf-8", "retry-after": "1"},
                            _single_body_chunks(body), send_text_locked, send_bytes_locked,
                            wait_response_credit,
                        )
                        response_credits.pop(request_id, None)
                    elif negotiated_protocol >= 2:
                        await send_response_v2(
                            _build_tunnel_response(
                                request_id, 503,
                                {"content-type": "text/plain; charset=utf-8", "retry-after": "1"},
                                body, False,
                            )
                        )
                    else:
                        await send_text_locked(
                            _build_tunnel_response(
                                request_id, 503,
                                {"content-type": "text/plain; charset=utf-8", "retry-after": "1"},
                                body, True,
                            )
                        )

                async def wait_response_credit(request_id: str) -> None:
                    state = response_credits.setdefault(
                        request_id, {"credit": 0, "event": asyncio.Event()}
                    )
                    while int(state["credit"]) <= 0:
                        state["event"].clear()
                        if int(state["credit"]) > 0:
                            state["event"].set()
                            break
                        await state["event"].wait()
                    state["credit"] = int(state["credit"]) - 1

                async def body_iterator(request_id: str, queue: asyncio.Queue):
                    total = 0
                    while True:
                        item = await queue.get()
                        if item is None:
                            return
                        total += len(item)
                        # Return one unit of receive credit as soon as the agent
                        # consumes this chunk from its bounded transport buffer.
                        await send_text_locked(
                            {"type": "req_credit", "id": request_id, "credit": 1}
                        )
                        if _limit_exceeded(MAX_REQUEST_BODY_BYTES, total):
                            raise RequestBodyLimitExceeded(
                                "request body exceeds this agent's configured limit"
                            )
                        if PRINT_REQUEST_BODY_PREVIEW and total <= max(1, int(BODY_PREVIEW_BYTES)):
                            log("   -> body preview chunk: " + _preview_bytes(item[:BODY_PREVIEW_BYTES]))
                        yield item

                async def run_request_task(message_payload: dict, queue: Optional[asyncio.Queue] = None):
                    request_id = str(message_payload.get("id", ""))
                    try:
                        if request_semaphore is None:
                            if negotiated_protocol >= 3:
                                await handle_req_v3(
                                    message_payload,
                                    body_iterator(request_id, queue),
                                    send_text_locked,
                                    send_bytes_locked,
                                    wait_response_credit,
                                )
                            else:
                                response = await handle_req(
                                    message_payload, encode_body=(negotiated_protocol < 2)
                                )
                                if negotiated_protocol >= 2:
                                    await send_response_v2(response)
                                else:
                                    await send_text_locked(response)
                        else:
                            async with request_semaphore:
                                if negotiated_protocol >= 3:
                                    await handle_req_v3(
                                        message_payload,
                                        body_iterator(request_id, queue),
                                        send_text_locked,
                                        send_bytes_locked,
                                        wait_response_credit,
                                    )
                                else:
                                    response = await handle_req(
                                        message_payload, encode_body=(negotiated_protocol < 2)
                                    )
                                    if negotiated_protocol >= 2:
                                        await send_response_v2(response)
                                    else:
                                        await send_text_locked(response)
                    except asyncio.CancelledError:
                        log(f"[REQ] cancelled | id={request_id}")
                        raise
                    except Exception as error:
                        log_repeatable_error(
                            "task_error",
                            f"Error in request task {request_id}: {type(error).__name__}: {error}",
                        )
                    finally:
                        incoming_bodies.pop(request_id, None)
                        response_credits.pop(request_id, None)

                def attach_request_task(request_id: str, task: asyncio.Task) -> None:
                    request_tasks[request_id] = task

                    def done_callback(done_task, rid=request_id):
                        request_tasks.pop(rid, None)
                        incoming_bodies.pop(rid, None)
                        response_credits.pop(rid, None)
                        try:
                            done_task.exception()
                        except (asyncio.CancelledError, Exception):
                            pass

                    task.add_done_callback(done_callback)

                def attach_user_ws_task(request_id: str, task: asyncio.Task) -> None:
                    user_ws_tasks[request_id] = task

                    def done_callback(done_task, rid=request_id):
                        user_ws_tasks.pop(rid, None)
                        user_ws_queues.pop(rid, None)
                        try:
                            done_task.exception()
                        except (asyncio.CancelledError, Exception):
                            pass

                    task.add_done_callback(done_callback)

                try:
                    while True:
                        raw = await websocket.recv()

                        if isinstance(raw, bytes):
                            if len(raw) < 18:
                                continue
                            magic = raw[:2]
                            request_id = raw[2:18].hex()
                            payload = raw[18:]
                            if magic == b"Q3" and negotiated_protocol >= 3:
                                queue = incoming_bodies.get(request_id)
                                if queue is not None:
                                    # VPS only sends chunks for granted credits;
                                    # awaiting here is a final safety net, not a
                                    # total-size or traffic quota.
                                    await queue.put(payload)
                                continue
                            if magic == b"WQ" and negotiated_protocol >= 3:
                                queue = user_ws_queues.get(request_id)
                                if queue is not None:
                                    await queue.put(("bytes", payload))
                                continue
                            log("[WS] Ignoring unknown binary tunnel frame")
                            continue

                        message = json.loads(raw)
                        message_type = message.get("type")
                        if message_type in {"ping", "pong"}:
                            continue

                        if message_type == "server_restart":
                            log("[WS] Hostish server is restarting; reconnecting automatically...")
                            await websocket.close()
                            break

                        if message_type == "cancel":
                            request_id = str(message.get("id", ""))
                            task = request_tasks.get(request_id)
                            if task is not None and not task.done():
                                task.cancel()
                            continue

                        if message_type == "resp_credit" and negotiated_protocol >= 3:
                            request_id = str(message.get("id", ""))
                            state = response_credits.setdefault(
                                request_id, {"credit": 0, "event": asyncio.Event()}
                            )
                            try:
                                credit = max(0, int(message.get("credit", 0)))
                            except (TypeError, ValueError):
                                credit = 0
                            if credit:
                                state["credit"] = int(state["credit"]) + credit
                                state["event"].set()
                            continue

                        if message_type == "req_end" and negotiated_protocol >= 3:
                            request_id = str(message.get("id", ""))
                            queue = incoming_bodies.get(request_id)
                            if queue is not None:
                                await queue.put(None)
                            continue

                        if message_type == "req_start" and negotiated_protocol >= 3:
                            request_id = str(message.get("id", ""))
                            if over_agent_capacity():
                                # Agent-controlled only. VPS itself applies no site
                                # concurrency/queue limit.
                                await send_busy_response(message)
                                continue
                            queue = asyncio.Queue(maxsize=max(1, int(REQUEST_STREAM_BUFFER_CHUNKS)))
                            incoming_bodies[request_id] = queue
                            response_credits[request_id] = {"credit": 0, "event": asyncio.Event()}
                            # Credits bound instantaneous RAM but not total upload.
                            await send_text_locked(
                                {
                                    "type": "req_credit", "id": request_id,
                                    "credit": max(1, int(REQUEST_STREAM_BUFFER_CHUNKS)),
                                }
                            )
                            task = asyncio.create_task(run_request_task(message, queue))
                            attach_request_task(request_id, task)
                            continue

                        if message_type == "req":
                            request_id = str(message.get("id", ""))
                            if over_agent_capacity():
                                await send_busy_response(message)
                                continue
                            task = asyncio.create_task(run_request_task(message, None))
                            attach_request_task(request_id, task)
                            continue

                        if message_type == "user_ws_open" and negotiated_protocol >= 3:
                            request_id = str(message.get("id", ""))
                            if not USER_WEBSOCKET_PROXY_ENABLED:
                                await send_text_locked(
                                    {
                                        "type": "user_ws_accept", "id": request_id, "ok": False,
                                        "code": 1008, "reason": "User WebSocket proxy disabled by hoster",
                                    }
                                )
                                continue
                            queue = asyncio.Queue(maxsize=max(2, int(REQUEST_STREAM_BUFFER_CHUNKS)))
                            user_ws_queues[request_id] = queue
                            task = asyncio.create_task(
                                handle_user_websocket_bridge(
                                    message, queue, send_text_locked, send_bytes_locked
                                )
                            )
                            attach_user_ws_task(request_id, task)
                            continue

                        if message_type == "user_ws_text" and negotiated_protocol >= 3:
                            request_id = str(message.get("id", ""))
                            queue = user_ws_queues.get(request_id)
                            if queue is not None:
                                await queue.put(("text", str(message.get("data", ""))))
                            continue

                        if message_type == "user_ws_close" and negotiated_protocol >= 3:
                            request_id = str(message.get("id", ""))
                            queue = user_ws_queues.get(request_id)
                            if queue is not None:
                                await queue.put(("close", int(message.get("code", 1000) or 1000)))
                            continue

                        log(f"[WS] Ignoring unknown message type: {message_type!r}")
                finally:
                    IS_WS_CONNECTED = False
                    for task in tuple(request_tasks.values()) + tuple(user_ws_tasks.values()):
                        if not task.done():
                            task.cancel()
                    all_tasks = list(request_tasks.values()) + list(user_ws_tasks.values())
                    if all_tasks:
                        await asyncio.gather(*all_tasks, return_exceptions=True)

        except KeyboardInterrupt:
            raise
        except Exception as error:
            IS_WS_CONNECTED = False
            log_repeatable_error(
                "main_disconnect",
                f"[WS] Connection/auth failed: {type(error).__name__}: {error}",
            )
            log(f"[WS] Reconnecting in {backoff} seconds...")
            await asyncio.sleep(backoff)
            backoff = min(backoff * 2, 15)


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        log("[INFO] Stopped by user")
    except Exception:
        traceback.print_exc()
    finally:
        stop_managed_scripts()