#!/usr/bin/env bash
# installer.sh — Unified installer for loongsuite-pilot
#
# Install (first time):
#   curl -fsSL <URL>/installer.sh | bash
#   curl -fsSL <URL>/installer.sh | bash -s -- install \
#     --sls-endpoint "https://cn-hangzhou.log.aliyuncs.com" \
#     --sls-project "my-project" \
#     --sls-logstore "my-logstore" \
#     --sls-ak-id "your-ak-id" \
#     --sls-ak-secret "your-ak-secret"
#   curl -fsSL <URL>/installer.sh | bash -s -- install \
#     --sls-endpoint "https://cn-hangzhou.log.aliyuncs.com" \
#     --sls-project "my-project" --sls-logstore "my-logstore" \
#     --sls-api-key "your-api-key" \
#     --multimodal-mode all
#   curl -fsSL <URL>/installer.sh | bash -s -- install --mask-mode all
#   curl -fsSL <URL>/installer.sh | bash -s -- install --mask-mode custom --mask-types cloudAccessKey,apiKey
#   curl -fsSL <URL>/installer.sh | bash -s -- install --interceptor-mode all
#   curl -fsSL <URL>/installer.sh | bash -s -- install --hook-tamper-protection true
#   curl -fsSL <URL>/installer.sh | bash -s -- install --dashboard-port 9000
#
#
# Install into a container image (no autostart, no daemon, no auto-update;
# hooks/plugins are deployed synchronously and a missing agent fails the build):
#   RUN curl -fsSL <URL>/installer.sh | bash -s -- install \
#     --mode container --agents hermes-agent
#
# NOTE: --mode container exists only in this installer and installer-inner.sh. The
# publicly published installer.sh is built from deploy/installer-opensource.sh
# (see deploy/release-opensource.sh), which does not accept the flag -- so a
# Dockerfile using --mode container must point at an internal installer URL.
#
# Install from test channel:
#   curl -fsSL <URL>/installer.sh | bash -s -- install --channel test
#   curl -fsSL <URL>/installer.sh | bash -s -- install --channel test-<self> or test/<self>
#
# Upgrade (preserve config, auto-rollback on failure):
#   curl -fsSL <URL>/installer.sh | bash -s -- upgrade
#   curl -fsSL <URL>/installer.sh | bash -s -- upgrade --package-url <url>
# Force a full install even when an AgentShell reporting-only update is possible:
#   curl -fsSL <URL>/installer.sh | bash -s -- install --force-reinstall
#
# Uninstall:
#   curl -fsSL <URL>/installer.sh | bash -s -- uninstall
#   curl -fsSL <URL>/installer.sh | bash -s -- uninstall --purge

set -euo pipefail

# ============================================================
# Constants
# ============================================================
PACKAGE_NAME="loongsuite-pilot"
PERMANENT_DIR="$HOME/.loongsuite-pilot/package"
DEFAULT_DATA_DIR="$HOME/.loongsuite-pilot"

# Channel presets: release (production) vs test (pre-release)
_RELEASE_BASE_URL="https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot"
_TEST_BASE_URL="https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot-dev"

# Managed Node.js runtime + prebuilt node_modules (downloaded from OSS at install time)
NODE_VERSION="${LOONGSUITE_PILOT_NODE_VERSION:-22.22.2}"
NODE_DEPS_BASE="${LOONGSUITE_PILOT_NODE_DEPS_URL:-https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node}"
NODE_MODULES_BASE="${LOONGSUITE_PILOT_NODE_MODULES_URL:-https://aliyun-observability-release-cn-shanghai.oss-cn-shanghai.aliyuncs.com/loongsuite-pilot/deps/node-modules}"

# ============================================================
# Parse sub-command
# ============================================================
COMMAND=""
DEFAULT_CHANNEL="${LOONGSUITE_PILOT_DEFAULT_CHANNEL:-release}"
CHANNEL="${LOONGSUITE_PILOT_CHANNEL:-$DEFAULT_CHANNEL}"
PACKAGE_URL="${LOONGSUITE_PILOT_PACKAGE_URL:-}"
INSTALL_VERSION=""
SLS_ENDPOINT=""
SLS_PROJECT=""
SLS_LOGSTORE=""
SLS_AK_ID=""
SLS_AK_SECRET=""
SLS_API_KEY=""
SLS_AK_ID_SET=0
SLS_AK_SECRET_SET=0
SLS_API_KEY_SET=0
DATA_DIR="$DEFAULT_DATA_DIR"
DASHBOARD_PORT=""
DASHBOARD_PORT_SET=0
LOG_LEVEL=""
USER_ID=""
RESET_USER_ID=0
INSTALL_SOURCE=""
COLLECT_LOG=""
COLLECT_TRACE=""
CMS_LICENSE_KEY=""
CMS_ENDPOINT=""
CMS_WORKSPACE=""
SERVICE_NAME_PREFIX=""
SELECTED_AGENTS=""
AGENT_SELECTION_EXPLICIT=0
# Whether SELECTED_AGENTS came from the caller. select_agents() also writes it from
# auto-detection, and container mode must not mistake "what happened to be detected"
# for "what the build requires".
AGENTS_EXPLICIT=0
ALL_AGENTS=0
MULTIMODAL_MODE=""
MULTIMODAL_MODE_SET=0
# Keep in sync with MULTIMODAL_SUPPORTED_AGENT_IDS.
MULTIMODAL_SUPPORTED_AGENTS="codex,qoder,qwen-work-cn"
MASK_MODE=""
MASK_TYPES=""
MASK_REPLACEMENT_MODE=""
INTERCEPTOR_MODE=""
HOOK_TAMPER_PROTECTION=""
HOOK_TAMPER_PROTECTION_SET=0
SLS_REQUESTED=0
CMS_REQUESTED=0
CMS_LICENSE_KEY_SET=0
CMS_ENDPOINT_SET=0
CMS_WORKSPACE_SET=0
COLLECT_LOG_SET=0
COLLECT_TRACE_SET=0
SERVICE_NAME_PREFIX_SET=0
PACKAGE_SELECTOR_EXPLICIT=0
HAS_SUDO=0
PURGE=0
PREFER_SYSTEM_NODE=0
FORCE_REINSTALL=0
# host: register an init-system service and start the collector daemon (default).
# container: an image build layer — no init system to register with and no process
# that may outlive the RUN step, so deploy hooks/plugins synchronously instead and
# leave starting the collector to the image entrypoint.
INSTALL_MODE="${LOONGSUITE_PILOT_INSTALL_MODE:-host}"
MULTICA_COLLECTION_MODE="${LOONGSUITE_PILOT_MULTICA_COLLECTION_MODE:-}"

# First arg is sub-command (or option -> default to install)
if [[ $# -gt 0 ]]; then
    case "$1" in
        install|upgrade|uninstall)
            COMMAND="$1"; shift ;;
        -*)
            COMMAND="install" ;;
        *)
            COMMAND="install" ;;
    esac
else
    COMMAND="install"
fi

while [[ $# -gt 0 ]]; do
    case "$1" in
        --sls-endpoint)       SLS_ENDPOINT="$2"; SLS_REQUESTED=1; shift 2 ;;
        --sls-endpoint=*)     SLS_ENDPOINT="${1#*=}"; SLS_REQUESTED=1; shift ;;
        --sls-project)        SLS_PROJECT="$2"; SLS_REQUESTED=1; shift 2 ;;
        --sls-project=*)      SLS_PROJECT="${1#*=}"; SLS_REQUESTED=1; shift ;;
        --sls-logstore)       SLS_LOGSTORE="$2"; SLS_REQUESTED=1; shift 2 ;;
        --sls-logstore=*)     SLS_LOGSTORE="${1#*=}"; SLS_REQUESTED=1; shift ;;
        --sls-ak-id)          SLS_AK_ID="$2"; SLS_AK_ID_SET=1; SLS_REQUESTED=1; shift 2 ;;
        --sls-ak-id=*)        SLS_AK_ID="${1#*=}"; SLS_AK_ID_SET=1; SLS_REQUESTED=1; shift ;;
        --sls-ak-secret)      SLS_AK_SECRET="$2"; SLS_AK_SECRET_SET=1; SLS_REQUESTED=1; shift 2 ;;
        --sls-ak-secret=*)    SLS_AK_SECRET="${1#*=}"; SLS_AK_SECRET_SET=1; SLS_REQUESTED=1; shift ;;
        --sls-api-key)        SLS_API_KEY="$2"; SLS_API_KEY_SET=1; SLS_REQUESTED=1; shift 2 ;;
        --sls-api-key=*)      SLS_API_KEY="${1#*=}"; SLS_API_KEY_SET=1; SLS_REQUESTED=1; shift ;;
        --default-sls-override|--default-sls-override=*)
            echo "❌ --default-sls-override is no longer supported. Internal builds always dual-write." >&2
            exit 1 ;;
        --package-url)        PACKAGE_URL="$2"; PACKAGE_SELECTOR_EXPLICIT=1; shift 2 ;;
        --package-url=*)      PACKAGE_URL="${1#--package-url=}"; PACKAGE_SELECTOR_EXPLICIT=1; shift ;;
        --data-dir)           DATA_DIR="$2"; shift 2 ;;
        --data-dir=*)         DATA_DIR="${1#*=}"; shift ;;
        --dashboard-port)
            if [ "$#" -lt 2 ] || [[ "$2" == --* ]]; then
                echo "--dashboard-port requires an integer between 1 and 65535" >&2
                exit 1
            fi
            DASHBOARD_PORT="$2"; DASHBOARD_PORT_SET=1; shift 2 ;;
        --dashboard-port=*)   DASHBOARD_PORT="${1#*=}"; DASHBOARD_PORT_SET=1; shift ;;
        --log-level)          LOG_LEVEL="$2"; shift 2 ;;
        --log-level=*)        LOG_LEVEL="${1#*=}"; shift ;;
        --userId|--user.id)   USER_ID="$2"; shift 2 ;;
        --userId=*|--user.id=*) USER_ID="${1#*=}"; shift ;;
        --reset-user-id)      RESET_USER_ID=1; shift ;;
        --install-source)     INSTALL_SOURCE="$2"; shift 2 ;;
        --install-source=*)   INSTALL_SOURCE="${1#*=}"; shift ;;
        --lang)               export LOONGSUITE_PILOT_LANG="$2"; shift 2 ;;
        --lang=*)             export LOONGSUITE_PILOT_LANG="${1#--lang=}"; shift ;;
        --version)            INSTALL_VERSION="$2"; PACKAGE_SELECTOR_EXPLICIT=1; shift 2 ;;
        --version=*)          INSTALL_VERSION="${1#*=}"; PACKAGE_SELECTOR_EXPLICIT=1; shift ;;
        --channel)            CHANNEL="$2"; PACKAGE_SELECTOR_EXPLICIT=1; shift 2 ;;
        --channel=*)          CHANNEL="${1#*=}"; PACKAGE_SELECTOR_EXPLICIT=1; shift ;;
        --collect-log)        COLLECT_LOG="$2"; COLLECT_LOG_SET=1; shift 2 ;;
        --collect-log=*)      COLLECT_LOG="${1#*=}"; COLLECT_LOG_SET=1; shift ;;
        --collect-trace)      COLLECT_TRACE="$2"; COLLECT_TRACE_SET=1; shift 2 ;;
        --collect-trace=*)    COLLECT_TRACE="${1#*=}"; COLLECT_TRACE_SET=1; shift ;;
        --cms-license-key)    CMS_LICENSE_KEY="$2"; CMS_REQUESTED=1; CMS_LICENSE_KEY_SET=1; shift 2 ;;
        --cms-license-key=*)  CMS_LICENSE_KEY="${1#*=}"; CMS_REQUESTED=1; CMS_LICENSE_KEY_SET=1; shift ;;
        --cms-endpoint)       CMS_ENDPOINT="$2"; CMS_REQUESTED=1; CMS_ENDPOINT_SET=1; shift 2 ;;
        --cms-endpoint=*)     CMS_ENDPOINT="${1#*=}"; CMS_REQUESTED=1; CMS_ENDPOINT_SET=1; shift ;;
        --cms-workspace)      CMS_WORKSPACE="$2"; CMS_REQUESTED=1; CMS_WORKSPACE_SET=1; shift 2 ;;
        --cms-workspace=*)    CMS_WORKSPACE="${1#*=}"; CMS_REQUESTED=1; CMS_WORKSPACE_SET=1; shift ;;
        --service-name-prefix) SERVICE_NAME_PREFIX="$2"; SERVICE_NAME_PREFIX_SET=1; shift 2 ;;
        --service-name-prefix=*) SERVICE_NAME_PREFIX="${1#*=}"; SERVICE_NAME_PREFIX_SET=1; shift ;;
        --agents)             SELECTED_AGENTS="$2"; AGENTS_EXPLICIT=1; AGENT_SELECTION_EXPLICIT=1; shift 2 ;;
        --agents=*)           SELECTED_AGENTS="${1#*=}"; AGENTS_EXPLICIT=1; AGENT_SELECTION_EXPLICIT=1; shift ;;
        --all-agents)         ALL_AGENTS=1; shift ;;
        --multimodal-mode)    MULTIMODAL_MODE="${2-}"; MULTIMODAL_MODE_SET=1; shift 2 || shift ;;
        --multimodal-mode=*)  MULTIMODAL_MODE="${1#*=}"; MULTIMODAL_MODE_SET=1; shift ;;
        --mask-mode)          MASK_MODE="$2"; shift 2 ;;
        --mask-mode=*)        MASK_MODE="${1#*=}"; shift ;;
        --mask-types)         MASK_TYPES="$2"; shift 2 ;;
        --mask-types=*)       MASK_TYPES="${1#*=}"; shift ;;
        --mask-replacement-mode) MASK_REPLACEMENT_MODE="$2"; shift 2 ;;
        --mask-replacement-mode=*) MASK_REPLACEMENT_MODE="${1#*=}"; shift ;;
        --interceptor-mode)   INTERCEPTOR_MODE="$2"; shift 2 ;;
        --interceptor-mode=*) INTERCEPTOR_MODE="${1#*=}"; shift ;;
        --hook-tamper-protection) HOOK_TAMPER_PROTECTION="${2-}"; HOOK_TAMPER_PROTECTION_SET=1; shift 2 || shift ;;
        --hook-tamper-protection=*) HOOK_TAMPER_PROTECTION="${1#*=}"; HOOK_TAMPER_PROTECTION_SET=1; shift ;;
        --mode)               INSTALL_MODE="$2"; shift 2 ;;
        --mode=*)             INSTALL_MODE="${1#*=}"; shift ;;
        --multica-collection-mode)
            if [ -z "${2:-}" ] || [[ "$2" == --* ]]; then
                echo "--multica-collection-mode requires on or off" >&2
                exit 1
            fi
            MULTICA_COLLECTION_MODE="$2"; shift 2 ;;
        --multica-collection-mode=) echo "--multica-collection-mode requires on or off" >&2; exit 1 ;;
        --multica-collection-mode=*) MULTICA_COLLECTION_MODE="${1#*=}"; shift ;;
        --purge)              PURGE=1; shift ;;
        --prefer-system-node) PREFER_SYSTEM_NODE=1; shift ;;
        --prefer-system-node=*) PREFER_SYSTEM_NODE=1; shift ;;
        --force-reinstall)    FORCE_REINSTALL=1; shift ;;
        --system-service)
            echo "⚠️  --system-service is deprecated and ignored. Auto-detection is now the default." >&2
            shift ;;
        *)
            echo "Unknown option: $1" >&2
            exit 1 ;;
    esac
done

case "$INSTALL_SOURCE" in
    ""|qoder-marketplace|agentshell|other) ;;
    *)
        echo "❌ Unknown install source: $INSTALL_SOURCE (use qoder-marketplace, agentshell, or other)" >&2
        exit 1 ;;
esac

if [ "$FORCE_REINSTALL" -eq 1 ] && [ "$COMMAND" != "install" ]; then
    echo "❌ --force-reinstall is only supported with install (got $COMMAND)" >&2
    exit 1
fi

is_blank() {
    [[ "$1" =~ ^[[:space:]]*$ ]]
}

if [ "$DASHBOARD_PORT_SET" -eq 1 ]; then
    if ! [[ "$DASHBOARD_PORT" =~ ^[0-9]{1,5}$ ]] || (( 10#$DASHBOARD_PORT < 1 || 10#$DASHBOARD_PORT > 65535 )); then
        echo "--dashboard-port must be an integer between 1 and 65535" >&2
        exit 1
    fi
fi

case "$MULTICA_COLLECTION_MODE" in
    ""|on|off) ;;
    *) echo "Invalid Multica collection mode: expected on or off" >&2; exit 1 ;;
esac

case "$INSTALL_MODE" in
    host|container) ;;
    *)
        echo "❌ Unknown install mode: $INSTALL_MODE (use 'host' or 'container')" >&2
        exit 1 ;;
esac

if [ -n "$MASK_MODE" ]; then
    case "$MASK_MODE" in
        all|none|custom) ;;
        *)
            echo "❌ Unknown mask mode: $MASK_MODE (use 'all', 'custom', or 'none')" >&2
            exit 1 ;;
    esac
fi
if [ "$MASK_MODE" = "custom" ] && [ -z "$MASK_TYPES" ]; then
    echo "❌ --mask-types is required when --mask-mode custom" >&2
    exit 1
fi
if [ -n "$MASK_TYPES" ] && [ "$MASK_MODE" != "custom" ]; then
    echo "❌ --mask-types can only be used with --mask-mode custom" >&2
    exit 1
fi
if [ -n "$MASK_REPLACEMENT_MODE" ] && [ "$MASK_REPLACEMENT_MODE" != "placeholder" ] && [ "$MASK_REPLACEMENT_MODE" != "preview" ]; then
    echo "❌ Unknown mask replacement mode: $MASK_REPLACEMENT_MODE (use 'placeholder' or 'preview')" >&2
    exit 1
fi
if [ -n "$INTERCEPTOR_MODE" ]; then
    case "$INTERCEPTOR_MODE" in
        all|none) ;;
        *)
            echo "❌ Unknown interceptor mode: $INTERCEPTOR_MODE (use 'all' or 'none')" >&2
            exit 1 ;;
    esac
fi
if [ "$HOOK_TAMPER_PROTECTION_SET" -eq 1 ]; then
    case "$HOOK_TAMPER_PROTECTION" in
        true|false) ;;
        *) echo "--hook-tamper-protection requires true or false" >&2; exit 1 ;;
    esac
    if [ "$COMMAND" != "install" ]; then
        echo "--hook-tamper-protection is only supported with install" >&2
        exit 1
    fi
fi
if [ "$SLS_API_KEY_SET" -eq 1 ] && { [ "$SLS_AK_ID_SET" -eq 1 ] || [ "$SLS_AK_SECRET_SET" -eq 1 ]; }; then
    echo "❌ --sls-api-key cannot be used with --sls-ak-id or --sls-ak-secret" >&2
    exit 1
fi
if [ "$SLS_API_KEY_SET" -eq 1 ] && is_blank "$SLS_API_KEY"; then
    echo "❌ --sls-api-key must be non-empty" >&2
    exit 1
fi
if [ "$SLS_AK_ID_SET" -ne "$SLS_AK_SECRET_SET" ]; then
    echo "❌ --sls-ak-id and --sls-ak-secret must be provided together" >&2
    exit 1
fi
if [ "$SLS_AK_ID_SET" -eq 1 ] && { is_blank "$SLS_AK_ID" || is_blank "$SLS_AK_SECRET"; }; then
    echo "❌ --sls-ak-id and --sls-ak-secret must be non-empty" >&2
    exit 1
fi
if [ "$SLS_REQUESTED" -eq 1 ] && { is_blank "$SLS_ENDPOINT" || is_blank "$SLS_PROJECT" || is_blank "$SLS_LOGSTORE"; }; then
    echo "❌ --sls-endpoint, --sls-project, and --sls-logstore must all be provided and non-empty when any --sls-* option is used" >&2
    exit 1
fi
if [ "$MULTIMODAL_MODE_SET" -eq 1 ]; then
    if [ -z "$MULTIMODAL_MODE" ]; then
        echo "❌ --multimodal-mode requires 'none', 'input', 'output', or 'all'" >&2
        exit 1
    fi
    case "$MULTIMODAL_MODE" in
        none|input|output|all) ;;
        *)
            echo "❌ Unknown multimodal mode: $MULTIMODAL_MODE (use 'none', 'input', 'output', or 'all')" >&2
            exit 1 ;;
    esac
    if [ "$COMMAND" != "install" ]; then
        echo "❌ --multimodal-mode is only supported with install (got $COMMAND)" >&2
        exit 1
    fi
    if [ "$MULTIMODAL_MODE" != "none" ]; then
        if [[ "$SLS_ENDPOINT" != *[![:space:]]* ]] || [[ "$SLS_PROJECT" != *[![:space:]]* ]] \
            || [[ "$SLS_LOGSTORE" != *[![:space:]]* ]] || [[ "$SLS_API_KEY" != *[![:space:]]* ]]; then
            echo "❌ --multimodal-mode $MULTIMODAL_MODE requires --sls-endpoint, --sls-project, --sls-logstore, and --sls-api-key" >&2
            exit 1
        fi
    fi
fi

# Validate current user on Linux
validate_install_user() {
    case "$(uname -s)" in
        Linux)
            local current_user
            current_user=$(whoami)
            if [ "$(id -u)" -eq 0 ]; then
                HAS_SUDO=1
                msg "   ✅ 以 root 身份安装（自动使用系统级服务）" \
                    "   ✅ Installing as root (auto system-level service)"
            else
                msg "   Install user: $current_user（服务类型将在启动时自动检测）" \
                    "   Install user: $current_user (service type auto-detected at start)"
            fi
            ;;
    esac
}

# Resolve PACKAGE_URL from channel + version if not explicitly set
if [ -z "$PACKAGE_URL" ]; then
    _channel_base=""
    case "$CHANNEL" in
        release|prod)
            _channel_base="$_RELEASE_BASE_URL" ;;
        test|pre)
            _channel_base="$_TEST_BASE_URL" ;;
        test-*)
            if [[ "$CHANNEL" =~ ^test-[a-zA-Z0-9]+$ ]]; then
                _channel_base="${_TEST_BASE_URL}/${CHANNEL}"
            else
                echo "❌ Invalid format: requires a single suffix after" >&2
                exit 1
            fi
            ;;
        *)
            echo "❌ Unknown channel: $CHANNEL (use 'release' or 'test')" >&2
            exit 1 ;;
    esac
    if [ -n "$INSTALL_VERSION" ]; then
        PACKAGE_URL="${_channel_base}/${INSTALL_VERSION}/${PACKAGE_NAME}.tar.gz"
    else
        PACKAGE_URL="${_channel_base}/latest/${PACKAGE_NAME}.tar.gz"
    fi
    # Auto-update always checks latest, not a pinned version
    UPDATE_PACKAGE_URL="${_channel_base}/latest/${PACKAGE_NAME}.tar.gz"
else
    # Explicit --package-url: use as-is for both download and auto-update
    UPDATE_PACKAGE_URL="$PACKAGE_URL"
fi

# ============================================================
# Language detection
# ============================================================
detect_lang() {
    if [ -n "${LOONGSUITE_PILOT_LANG:-}" ]; then echo "$LOONGSUITE_PILOT_LANG"; return; fi
    for v in "${LANGUAGE:-}" "${LC_ALL:-}" "${LC_MESSAGES:-}" "${LANG:-}"; do
        if echo "$v" | grep -qi "zh"; then echo "zh"; return; fi
    done
    if [ "$(uname)" = "Darwin" ]; then
        local al
        al=$(defaults read -g AppleLanguages 2>/dev/null | grep -i "zh" | head -1 || true)
        if [ -n "$al" ]; then echo "zh"; return; fi
    fi
    echo "en"
}
LANG_MODE=$(detect_lang)
msg() { [ "$LANG_MODE" = "zh" ] && echo "$1" || echo "$2"; }

# ============================================================
# Common: check dependencies
# ============================================================
_resolve_realpath() {
    realpath "$1" 2>/dev/null || readlink -f "$1" 2>/dev/null || echo "$1"
}

_node_is_app_bundle() {
    local resolved
    resolved=$(_resolve_realpath "$1")
    case "$resolved" in
        /Applications/*.app/Contents/*|/System/Applications/*.app/Contents/*|"$HOME"/Applications/*.app/Contents/*)
            return 0
            ;;
    esac
    return 1
}

_node_is_suitable() {
    local bin="$1"
    [ -x "$bin" ] || return 1
    _node_is_app_bundle "$bin" && return 1
    local ver
    ver="$("$bin" --version 2>/dev/null)" || return 1
    local major="${ver#v}"
    major="${major%%.*}"
    [[ "$major" =~ ^[0-9]+$ ]] && (( major >= 18 )) || return 1
    return 0
}

resolve_node() {
    local _candidates=()

    local _nvm_candidates=("$HOME/.nvm/versions/node"/*/bin/node)
    local i
    for (( i=${#_nvm_candidates[@]}-1; i>=0; i-- )); do
        _candidates+=("${_nvm_candidates[i]}")
    done

    _candidates+=(
        "$HOME/.volta/bin/node"
        "$HOME/.fnm/aliases/default/bin/node"
        /opt/homebrew/bin/node
        /usr/local/bin/node
        "$HOME/.local/bin/node"
    )

    if command -v node >/dev/null 2>&1; then
        _candidates+=("$(command -v node)")
    fi

    for candidate in "${_candidates[@]}"; do
        if _node_is_suitable "$candidate"; then
            _resolve_realpath "$candidate"
            return 0
        fi
    done
    return 1
}

# >>> managed-node-runtime >>>
# Managed Node.js runtime + prebuilt node_modules, downloaded from OSS.
# Everything here logs to stderr only: ensure_managed_node is captured via
# $(...) and must print the node path — and nothing else — on stdout.
_mn_msg() {
    if [ "${LANG_MODE:-en}" = "zh" ]; then echo "$1" >&2; else echo "$2" >&2; fi
}

managed_node_platform() {
    local os arch
    case "$(uname -s)" in
        Darwin) os="darwin" ;;
        Linux) os="linux" ;;
        MINGW*|MSYS*|CYGWIN*) os="win" ;;
        *)
            echo "managed node: unsupported platform $(uname -s)" >&2
            return 1 ;;
    esac
    case "$(uname -m)" in
        arm64|aarch64) arch="arm64" ;;
        x86_64|amd64) arch="x64" ;;
        *)
            echo "managed node: unsupported architecture $(uname -m)" >&2
            return 1 ;;
    esac
    if [ "$os" = "linux" ] && managed_node_is_musl; then
        _mn_msg "managed node: linux musl (Alpine) 无托管产物，回退系统 node + npm install" \
                "managed node: no linux-musl artifact, falling back to system node + npm install"
        return 1
    fi
    echo "$os $arch"
}

managed_node_is_musl() {
    ls /lib/ld-musl-* >/dev/null 2>&1 && return 0
    ldd --version 2>&1 | grep -qi musl && return 0
    return 1
}

managed_node_download() {
    # managed_node_download <url> <dest>
    # Bounded timeouts mirror the .ps1 installer (-TimeoutSec 600); without
    # them a stalled TCP connection hangs the installer indefinitely.
    if command -v curl >/dev/null 2>&1; then
        curl -fsSL --retry 2 --connect-timeout 20 --max-time 600 "$1" -o "$2"
    elif command -v wget >/dev/null 2>&1; then
        wget -q --tries=2 --timeout=20 "$1" -O "$2"
    else
        return 1
    fi
}

managed_node_sha256() {
    if command -v shasum >/dev/null 2>&1; then
        shasum -a 256 "$1" | awk '{print $1}'
    elif command -v sha256sum >/dev/null 2>&1; then
        sha256sum "$1" | awk '{print $1}'
    else
        echo "managed node: neither shasum nor sha256sum available" >&2
        return 1
    fi
}

managed_node_verify() {
    # managed_node_verify <archive> <shasums-file> <archive-basename>
    local expected actual
    # [*]? accepts sha256sum binary-mode lines ("<hash> *<name>"), matching
    # the .ps1 installer's Test-ManagedNodeChecksum.
    expected=$(grep -E "[[:space:]][*]?${3}\$" "$2" 2>/dev/null | awk '{print $1}' | head -1)
    if [ -z "$expected" ]; then
        echo "managed node: SHASUMS256.txt has no entry for $3" >&2
        return 1
    fi
    actual=$(managed_node_sha256 "$1") || return 1
    if [ "$expected" != "$actual" ]; then
        echo "managed node: sha256 mismatch for $3 (expected $expected, got $actual)" >&2
        return 1
    fi
    return 0
}

managed_node_bin() {
    # managed_node_bin <node-dir> <os>
    # Prefer the bin/ layout; official Node.js win zips put node.exe at the root.
    local bin="$1/bin/node"
    [ "$2" = "win" ] && bin="$1/bin/node.exe"
    if [ -x "$bin" ]; then
        echo "$bin"
        return 0
    fi
    if [ "$2" = "win" ] && [ -x "$1/node.exe" ]; then
        echo "$1/node.exe"
        return 0
    fi
    return 1
}

ensure_managed_node() {
    local runtime_dir="$DATA_DIR/runtime"
    local tuple os arch
    tuple=$(managed_node_platform) || return 1
    os="${tuple% *}"; arch="${tuple#* }"

    local ext="tar.gz"
    [ "$os" = "win" ] && ext="zip"
    local archive="node-v${NODE_VERSION}-${os}-${arch}.${ext}"
    local node_dir="$runtime_dir/node-v${NODE_VERSION}-${os}-${arch}"
    local node_bin=""
    node_bin=$(managed_node_bin "$node_dir" "$os") || node_bin=""

    if [ -n "$node_bin" ] && [ "$("$node_bin" --version 2>/dev/null)" = "v${NODE_VERSION}" ]; then
        echo "$node_bin"
        return 0
    fi

    local base="${NODE_DEPS_BASE%/}/${NODE_VERSION}"
    local tmp
    tmp=$(mktemp -d) || return 1

    _mn_msg "==> 下载托管 Node.js v${NODE_VERSION} (${os}-${arch})..." \
            "==> Downloading managed Node.js v${NODE_VERSION} (${os}-${arch})..."
    if ! managed_node_download "$base/$archive" "$tmp/$archive" \
        || ! managed_node_download "$base/SHASUMS256.txt" "$tmp/SHASUMS256.txt" \
        || ! managed_node_verify "$tmp/$archive" "$tmp/SHASUMS256.txt" "$archive"; then
        rm -rf "$tmp"
        return 1
    fi

    mkdir -p "$runtime_dir"
    rm -rf "$node_dir"
    if [ "$ext" = "zip" ]; then
        if ! command -v unzip >/dev/null 2>&1 || ! unzip -q "$tmp/$archive" -d "$runtime_dir"; then
            rm -rf "$tmp" "$node_dir"
            return 1
        fi
    else
        if ! { tar --warning=no-unknown-keyword -xzf "$tmp/$archive" -C "$runtime_dir" 2>/dev/null \
                || tar -xzf "$tmp/$archive" -C "$runtime_dir"; }; then
            rm -rf "$tmp" "$node_dir"
            return 1
        fi
    fi
    rm -rf "$tmp"

    node_bin=$(managed_node_bin "$node_dir" "$os") || node_bin=""
    if [ -z "$node_bin" ]; then
        echo "managed node: extracted archive has no usable node binary under $node_dir (bin/node or node.exe)" >&2
        rm -rf "$node_dir"
        return 1
    fi
    if [ "$os" = "darwin" ] && command -v xattr >/dev/null 2>&1; then
        xattr -dr com.apple.quarantine "$node_dir" 2>/dev/null || true
    fi
    echo "$node_bin"
}

ensure_node_modules() {
    # ensure_node_modules <app-version>  (expects PERMANENT_DIR to point at the deployed version dir)
    local app_version="${1:-latest}"
    local tuple os arch
    tuple=$(managed_node_platform) || return 1
    os="${tuple% *}"; arch="${tuple#* }"

    local modules_dir="$PERMANENT_DIR/node_modules"
    local marker="$modules_dir/.pilot-modules-version"
    local stamp="${app_version} ${os} ${arch}"
    if [ -d "$modules_dir" ] && [ "$(cat "$marker" 2>/dev/null)" = "$stamp" ]; then
        return 0
    fi

    local archive="node-modules-${os}-${arch}.tar.gz"
    local base="${NODE_MODULES_BASE%/}/${app_version}"
    local tmp
    tmp=$(mktemp -d) || return 1

    _mn_msg "==> 下载预编译 node_modules (${os}-${arch}, app v${app_version})..." \
            "==> Downloading prebuilt node_modules (${os}-${arch}, app v${app_version})..."
    if ! managed_node_download "$base/$archive" "$tmp/$archive" \
        || ! managed_node_download "$base/SHASUMS256.txt" "$tmp/SHASUMS256.txt" \
        || ! managed_node_verify "$tmp/$archive" "$tmp/SHASUMS256.txt" "$archive"; then
        rm -rf "$tmp"
        return 1
    fi

    local stage="$tmp/stage"
    mkdir -p "$stage"
    if ! { tar --warning=no-unknown-keyword -xzf "$tmp/$archive" -C "$stage" 2>/dev/null \
            || tar -xzf "$tmp/$archive" -C "$stage"; }; then
        rm -rf "$tmp"
        return 1
    fi
    if [ ! -d "$stage/node_modules" ]; then
        rm -rf "$tmp"
        echo "managed node_modules: archive does not contain node_modules/" >&2
        return 1
    fi
    echo "$stamp" > "$stage/node_modules/.pilot-modules-version"
    rm -rf "$modules_dir"
    if ! mv "$stage/node_modules" "$modules_dir"; then
        rm -rf "$tmp"
        return 1
    fi
    rm -rf "$tmp"
    return 0
}

run_npm() {
    # npm shipped with the managed runtime is a symlink to npm-cli.js, whose
    # `#!/usr/bin/env node` shebang resolves node through PATH. The runtime's bin dir
    # is not on PATH, so calling "$NPM_BIN" directly dies with
    # "env: node: No such file or directory" on hosts without a system node — exactly
    # the hosts the managed runtime exists for. Mirrors the .ps1 npm fallback, which
    # already prepends the node dir.
    PATH="$(dirname "$NODE_BIN"):$PATH" "$NPM_BIN" "$@"
}
# <<< managed-node-runtime <<<

dump_npm_failure() {
    # dump_npm_failure <file-with-npm-output>
    #
    # npm's own failure report ends in a single line pointing at
    # ~/.npm/_logs/<ts>-debug-0.log. Where this fallback actually runs unattended — a
    # container build layer, a CI runner — that file is discarded before anyone can read
    # it, so the pointer is all that survives and the cause is lost. Print the captured
    # output instead, plus the debug log's error lines while the filesystem still has them.
    local out="$1" log="" logs_dir=""
    if [ -s "$out" ]; then
        msg "    ---- npm 输出（末 40 行）----" "    ---- npm output (last 40 lines) ----"
        tail -n 40 "$out"
    fi
    logs_dir="${npm_config_cache:-$HOME/.npm}/_logs"
    log=$(ls -t "$logs_dir"/*.log 2>/dev/null | head -1 || true)
    if [ -n "$log" ] && [ -f "$log" ]; then
        msg "    ---- npm 调试日志 $log（末 40 条 error 行）----" \
            "    ---- npm debug log $log (last 40 error lines) ----"
        grep -E '^[0-9]+ error' "$log" | tail -n 40 || tail -n 40 "$log"
    fi
}

check_deps() {
    msg "==> 检查依赖..." "==> Checking dependencies..."

    NODE_BIN=""
    if [ "${PREFER_SYSTEM_NODE:-0}" -eq 1 ]; then
        NODE_BIN=$(resolve_node) || NODE_BIN=$(ensure_managed_node) || NODE_BIN=""
    else
        NODE_BIN=$(ensure_managed_node) || NODE_BIN=""
        if [ -z "$NODE_BIN" ]; then
            msg "    ⚠️ 托管 Node.js 不可用（平台不支持或下载失败），回退系统 node" \
                "    ⚠️ Managed Node.js unavailable (unsupported platform or download failed), falling back to system node"
            NODE_BIN=$(resolve_node) || NODE_BIN=""
        fi
    fi
    if [ -z "$NODE_BIN" ]; then
        msg "❌ 缺少依赖: node，请先安装后重试" \
            "❌ Missing dependency: node — please install it first"
        exit 1
    fi

    NODE_MAJOR=$("$NODE_BIN" -e "process.stdout.write(String(process.versions.node.split('.')[0]))")
    if [ "$NODE_MAJOR" -lt 18 ]; then
        msg "❌ 需要 Node.js >= 18，当前版本: $("$NODE_BIN" --version)" \
            "❌ Requires Node.js >= 18, current: $("$NODE_BIN" --version)"
        exit 1
    fi

    # Pin the node binary path
    mkdir -p "$DATA_DIR" 2>/dev/null || true
    echo "$NODE_BIN" > "$DATA_DIR/node-bin"

    # Derive npm from the same installation
    NPM_BIN="$(dirname "$NODE_BIN")/npm"
    if [ ! -x "$NPM_BIN" ]; then
        if command -v npm &>/dev/null; then
            NPM_BIN=$(command -v npm)
        else
            msg "❌ 缺少依赖: npm，请先安装后重试" \
                "❌ Missing dependency: npm — please install it first"
            exit 1
        fi
    fi

    if [ "$(uname)" = "Darwin" ]; then
        local sys_arch; sys_arch=$(uname -m)
        local node_arch; node_arch=$("$NODE_BIN" -e "process.stdout.write(process.arch)")
        if [ "$sys_arch" = "arm64" ] && [ "$node_arch" = "x64" ]; then
            msg "⚠️  架构不匹配: 系统为 arm64 (Apple Silicon)，但 Node.js 为 x64 (Intel)" \
                "⚠️  Architecture mismatch: system is arm64 but Node.js is x64 (Intel)"
            msg "   原生模块可能无法正常加载，建议安装 arm64 版本的 Node.js" \
                "   Native modules may fail to load. Please install arm64 Node.js"
        fi
    fi

    if ! command -v curl &>/dev/null && ! command -v wget &>/dev/null; then
        msg "❌ 需要 curl 或 wget，请先安装" \
            "❌ curl or wget is required — please install one first"
        exit 1
    fi

    msg "    ✅ node $("$NODE_BIN" --version)  npm $(run_npm --version)" \
        "    ✅ node $("$NODE_BIN" --version)  npm $(run_npm --version)"
    msg "    node pinned: $NODE_BIN" "    node pinned: $NODE_BIN"
    echo ""
}

# ============================================================
# Existing install: update reporting config only, then restart
# ============================================================
PILOT_COMMAND=""

detect_existing_pilot() {
    PILOT_COMMAND=""
    if command -v loongsuite-pilot >/dev/null 2>&1; then
        PILOT_COMMAND="$(command -v loongsuite-pilot)"
    elif [ -x "$HOME/.local/bin/loongsuite-pilot" ]; then
        PILOT_COMMAND="$HOME/.local/bin/loongsuite-pilot"
    else
        return 1
    fi

    local status_output=""
    if status_output="$(LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
        LOONGSUITE_PILOT_CACHE_DIR="$DATA_DIR" \
        "$PILOT_COMMAND" status 2>&1)"; then
        :
    else
        :
    fi

    if printf '%s\n' "$status_output" | grep -Eq 'is running|is not running'; then
        return 0
    fi

    msg "❌ loongsuite-pilot status 返回了无法识别的结果，已停止配置" \
        "❌ loongsuite-pilot status returned an unrecognized result; configuration stopped"
    [ -n "$status_output" ] && printf '%s\n' "$status_output" >&2
    return 2
}

is_agentshell_current() {
    local current_file="$DATA_DIR/current"
    [ -r "$current_file" ] || return 1
    LC_ALL=C grep -qi -- '-agentshell' "$current_file" 2>/dev/null
}

resolve_install_source() {
    local current_file="$HOME/.loongsuite-pilot/current"
    if [ -n "$INSTALL_SOURCE" ]; then
        printf '%s\n' "$INSTALL_SOURCE"
        return 0
    fi
    local probe="$INSTALL_VERSION"
    if [ -r "$current_file" ]; then
        probe="$probe $(tr -d '[:space:]' < "$current_file" 2>/dev/null || true)"
    fi
    if printf '%s' "$probe" | LC_ALL=C grep -qi -- '-agentshell'; then
        printf '%s\n' agentshell
        return 0
    fi
    printf '%s\n' other
}

resolve_reconfigure_node() {
    local pinned_file="$DATA_DIR/node-bin"
    if [ -f "$pinned_file" ]; then
        local pinned_node
        pinned_node="$(tr -d '\r\n' < "$pinned_file")"
        if _node_is_suitable "$pinned_node"; then
            printf '%s\n' "$pinned_node"
            return 0
        fi
    fi
    resolve_node
}

restore_reporting_config() {
    local config_file="$1"
    local backup_file="$2"
    local had_config="$3"
    if [ "$had_config" -eq 1 ]; then
        cp "$backup_file" "$config_file"
        chmod 600 "$config_file"
    else
        rm -f "$config_file"
    fi
}

write_existing_reporting_config() {
    local config_file="$DATA_DIR/config.json"
    local backup_file=""
    local had_config=0

    mkdir -p "$DATA_DIR"
    if [ -f "$config_file" ]; then
        had_config=1
        backup_file="$(mktemp "${config_file}.reconfigure-backup.XXXXXX")"
        cp "$config_file" "$backup_file"
        chmod 600 "$backup_file"
    fi

    NODE_BIN="$(resolve_reconfigure_node)" || {
        [ -n "$backup_file" ] && rm -f "$backup_file"
        msg "❌ 无法找到已安装实例可用的 Node.js，配置未修改" \
            "❌ No usable Node.js was found for the existing installation; config unchanged"
        return 1
    }

    INSTALL_SOURCE=$(resolve_install_source)

    if ! LP_CONFIG_PATH="$config_file" \
        LP_DASHBOARD_PORT="$DASHBOARD_PORT" \
        LP_SLS_REQUESTED="$SLS_REQUESTED" \
        LP_SLS_ENDPOINT="$SLS_ENDPOINT" \
        LP_SLS_PROJECT="$SLS_PROJECT" \
        LP_SLS_LOGSTORE="$SLS_LOGSTORE" \
        LP_SLS_AK_ID="$SLS_AK_ID" \
        LP_SLS_AK_SECRET="$SLS_AK_SECRET" \
        LP_SLS_API_KEY="$SLS_API_KEY" \
        LP_CMS_REQUESTED="$CMS_REQUESTED" \
        LP_CMS_LICENSE_KEY_SET="$CMS_LICENSE_KEY_SET" \
        LP_CMS_ENDPOINT_SET="$CMS_ENDPOINT_SET" \
        LP_CMS_WORKSPACE_SET="$CMS_WORKSPACE_SET" \
        LP_CMS_LICENSE_KEY="$CMS_LICENSE_KEY" \
        LP_CMS_ENDPOINT="$CMS_ENDPOINT" \
        LP_CMS_WORKSPACE="$CMS_WORKSPACE" \
        LP_COLLECT_LOG_SET="$COLLECT_LOG_SET" \
        LP_COLLECT_TRACE_SET="$COLLECT_TRACE_SET" \
        LP_SERVICE_NAME_PREFIX_SET="$SERVICE_NAME_PREFIX_SET" \
        LP_COLLECT_LOG="$COLLECT_LOG" \
        LP_COLLECT_TRACE="$COLLECT_TRACE" \
        LP_MULTICA_COLLECTION_MODE="$MULTICA_COLLECTION_MODE" \
        LP_SERVICE_NAME_PREFIX="$SERVICE_NAME_PREFIX" \
        LP_LOG_LEVEL="$LOG_LEVEL" \
        LP_USER_ID="$USER_ID" LP_RESET_USER_ID="$RESET_USER_ID" \
        LP_INSTALL_SOURCE="$INSTALL_SOURCE" \
        LP_MASK_MODE="$MASK_MODE" \
        LP_MASK_TYPES="$MASK_TYPES" \
        LP_MASK_REPLACEMENT_MODE="$MASK_REPLACEMENT_MODE" \
        LP_HOOK_TAMPER_PROTECTION="$HOOK_TAMPER_PROTECTION" \
        "$NODE_BIN" - <<'NODE'
const fs = require('fs');

const configPath = process.env.LP_CONFIG_PATH;
const isPlainObject = value =>
  value !== null && typeof value === 'object' && !Array.isArray(value);
const required = (value, label) => {
  if (typeof value !== 'string' || value.trim() === '') {
    throw new Error(`SLS ${label} is required`);
  }
  return value;
};

let config = {};
if (fs.existsSync(configPath)) {
  config = JSON.parse(fs.readFileSync(configPath, 'utf8').replace(/^\uFEFF/, ''));
  if (!isPlainObject(config)) throw new Error('config.json root must be an object');
}

if (process.env.LP_SLS_REQUESTED === '1') {
  const endpoint = required(process.env.LP_SLS_ENDPOINT, 'endpoint');
  const project = required(process.env.LP_SLS_PROJECT, 'project');
  const logstore = required(process.env.LP_SLS_LOGSTORE, 'logstore');
  const accessKeyId = process.env.LP_SLS_AK_ID || '';
  const accessKeySecret = process.env.LP_SLS_AK_SECRET || '';
  const apiKey = process.env.LP_SLS_API_KEY || '';
  if (!!accessKeyId !== !!accessKeySecret) {
    throw new Error('SLS access key id and secret must be provided together');
  }

  const userSls = {
    name: 'user-sls',
    endpoint,
    project,
    logstore,
    mode: apiKey ? 'apiKey' : (accessKeyId ? 'ak' : 'webtracking'),
  };
  if (apiKey) {
    userSls.apiKey = apiKey;
  } else if (accessKeyId) {
    userSls.accessKeyId = accessKeyId;
    userSls.accessKeySecret = accessKeySecret;
  }

  if (config.sls === undefined) {
    config.sls = [userSls];
  } else if (Array.isArray(config.sls)) {
    if (!config.sls.every(isPlainObject)) {
      throw new Error('config.sls array entries must be objects');
    }
    let replaced = false;
    const merged = [];
    for (const entry of config.sls) {
      if (entry.name !== 'user-sls') {
        merged.push(entry);
      } else if (!replaced) {
        merged.push(userSls);
        replaced = true;
      }
    }
    if (!replaced) merged.push(userSls);
    config.sls = merged;
  } else if (isPlainObject(config.sls)) {
    const legacy = { ...config.sls };
    delete legacy.destinationOverride;
    delete legacy.endpoints;
    legacy.endpoint = endpoint;
    legacy.project = project;
    legacy.logstore = logstore;
    legacy.mode = apiKey ? 'apiKey' : (accessKeyId ? 'ak' : 'webtracking');
    if (apiKey) {
      legacy.apiKey = apiKey;
      delete legacy.accessKeyId;
      delete legacy.accessKeySecret;
    } else if (accessKeyId) {
      legacy.accessKeyId = accessKeyId;
      legacy.accessKeySecret = accessKeySecret;
      delete legacy.apiKey;
    } else {
      delete legacy.apiKey;
      delete legacy.accessKeyId;
      delete legacy.accessKeySecret;
    }
    config.sls = legacy;
  } else {
    throw new Error('config.sls must be an object or array');
  }
}

if (process.env.LP_CMS_REQUESTED === '1') {
  if (config.cms !== undefined && !isPlainObject(config.cms)) {
    throw new Error('config.cms must be an object');
  }
  const cms = { ...(config.cms || {}) };
  if (process.env.LP_CMS_LICENSE_KEY_SET === '1') {
    cms.licenseKey = process.env.LP_CMS_LICENSE_KEY || '';
  }
  if (process.env.LP_CMS_ENDPOINT_SET === '1') {
    cms.endpoint = process.env.LP_CMS_ENDPOINT || '';
  }
  if (process.env.LP_CMS_WORKSPACE_SET === '1') {
    cms.workspace = process.env.LP_CMS_WORKSPACE || '';
  }
  if (typeof cms.licenseKey !== 'string' || cms.licenseKey.trim() === '') {
    throw new Error('CMS license key is required');
  }
  if (typeof cms.endpoint !== 'string' || cms.endpoint.trim() === '') {
    throw new Error('CMS endpoint is required');
  }
  config.cms = cms;
}

if (process.env.LP_COLLECT_LOG_SET === '1') {
  config.collectLog = process.env.LP_COLLECT_LOG === 'true';
}
if (process.env.LP_COLLECT_TRACE_SET === '1') {
  config.collectTrace = process.env.LP_COLLECT_TRACE === 'true';
}
const multicaMode = process.env.LP_MULTICA_COLLECTION_MODE;
if (multicaMode) {
  config.pipeline = config.pipeline || {};
  config.pipeline.multica = config.pipeline.multica || {};
  config.pipeline.multica.mode = multicaMode;
}
if (process.env.LP_SERVICE_NAME_PREFIX_SET === '1') {
  config.serviceNamePrefix = process.env.LP_SERVICE_NAME_PREFIX || '';
}
if (config.userId === undefined && config['user.id'] !== undefined) {
  config.userId = config['user.id'];
}
delete config['user.id'];

const logLevel = process.env.LP_LOG_LEVEL || '';
if (logLevel) config.logLevel = logLevel;

const userId = process.env.LP_USER_ID || '';
if (userId) {
  config.userId = userId;
  delete config.identity;
} else if (process.env.LP_RESET_USER_ID === '1') {
  delete config.userId;
  delete config.identity;
}
const installSource = process.env.LP_INSTALL_SOURCE || '';
if (installSource) config.installSource = installSource;

const maskMode = process.env.LP_MASK_MODE || '';
if (maskMode) {
  config.mask = config.mask || {};
  config.mask.mode = maskMode;
  if (maskMode === 'custom') {
    config.mask.types = (process.env.LP_MASK_TYPES || '')
      .split(',')
      .map(type => type.trim())
      .filter(Boolean);
  } else {
    delete config.mask.types;
  }
}
const maskReplacementMode = process.env.LP_MASK_REPLACEMENT_MODE || '';
if (maskReplacementMode) {
  config.mask = config.mask || {};
  config.mask.replacementMode = maskReplacementMode;
}

const hookTamperProtection = process.env.LP_HOOK_TAMPER_PROTECTION || '';
if (hookTamperProtection) {
  if (!config.hookWatchdog || typeof config.hookWatchdog !== 'object' || Array.isArray(config.hookWatchdog)) {
    config.hookWatchdog = {};
  }
  if (!config.hookWatchdog.tamperProtection || typeof config.hookWatchdog.tamperProtection !== 'object' || Array.isArray(config.hookWatchdog.tamperProtection)) {
    config.hookWatchdog.tamperProtection = {};
  }
  config.hookWatchdog.tamperProtection.enabled = hookTamperProtection === 'true';
}

const dashboardPort = process.env.LP_DASHBOARD_PORT || '';
if (dashboardPort) {
  if (!isPlainObject(config.dashboard)) config.dashboard = {};
  config.dashboard.port = Number(dashboardPort);
}

const tempPath = `${configPath}.tmp-${process.pid}-${Date.now()}`;
try {
  fs.writeFileSync(tempPath, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf8', mode: 0o600, flag: 'wx' });
  fs.chmodSync(tempPath, 0o600);
  fs.renameSync(tempPath, configPath);
} finally {
  if (fs.existsSync(tempPath)) fs.rmSync(tempPath, { force: true });
}
NODE
    then
        [ -n "$backup_file" ] && rm -f "$backup_file"
        msg "❌ config.json 合并失败，原配置已保留" \
            "❌ Failed to merge config.json; original config preserved"
        return 1
    fi

    REPORTING_CONFIG_BACKUP="$backup_file"
    REPORTING_CONFIG_HAD_FILE="$had_config"
    return 0
}

verify_pilot_running() {
    local retries="${LOONGSUITE_PILOT_STATUS_RETRIES:-5}"
    local delay="${LOONGSUITE_PILOT_STATUS_RETRY_DELAY:-1}"
    local attempt status_output
    for ((attempt=1; attempt<=retries; attempt++)); do
        status_output="$(LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
            LOONGSUITE_PILOT_CACHE_DIR="$DATA_DIR" \
            "$PILOT_COMMAND" status 2>&1 || true)"
        if printf '%s\n' "$status_output" | grep -q 'is running'; then
            return 0
        fi
        [ "$attempt" -lt "$retries" ] && sleep "$delay"
    done
    return 1
}

reconfigure_existing_reporting() {
    msg "==> 检测到已安装实例，仅更新用户上报配置..." \
        "==> Existing installation detected; updating user reporting config only..."
    if [ "$PACKAGE_SELECTOR_EXPLICIT" -eq 1 ]; then
        msg "⚠️  本次不会应用 channel/version/package-url，当前版本保持不变；升级请单独执行 upgrade" \
            "⚠️  channel/version/package-url are ignored here; the installed version is unchanged. Run upgrade separately."
    fi

    REPORTING_CONFIG_BACKUP=""
    REPORTING_CONFIG_HAD_FILE=0
    write_existing_reporting_config || return 1

    msg "==> 重启 loongsuite-pilot ..." "==> Restarting loongsuite-pilot ..."
    if LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
        LOONGSUITE_PILOT_CACHE_DIR="$DATA_DIR" \
        "$PILOT_COMMAND" restart && verify_pilot_running; then
        [ -n "$REPORTING_CONFIG_BACKUP" ] && rm -f "$REPORTING_CONFIG_BACKUP"
        msg "✅ 上报配置已更新，loongsuite-pilot 正在运行" \
            "✅ Reporting config updated and loongsuite-pilot is running"
        return 0
    fi

    msg "❌ 重启或状态验证失败，正在恢复旧 config.json ..." \
        "❌ Restart or status verification failed; restoring the previous config.json ..."
    restore_reporting_config "$DATA_DIR/config.json" "$REPORTING_CONFIG_BACKUP" "$REPORTING_CONFIG_HAD_FILE"
    LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
        LOONGSUITE_PILOT_CACHE_DIR="$DATA_DIR" \
        "$PILOT_COMMAND" restart >/dev/null 2>&1 || true
    [ -n "$REPORTING_CONFIG_BACKUP" ] && rm -f "$REPORTING_CONFIG_BACKUP"
    return 1
}

# ============================================================
# Common: download and extract package -> sets INSTALL_SRC
# ============================================================
download_and_extract() {
    TMP_DIR="$(mktemp -d)"
    # TMP_DIR cleanup is handled by the caller's trap

    msg "==> 下载安装包: $PACKAGE_URL" \
        "==> Downloading: $PACKAGE_URL"

    if command -v curl &>/dev/null; then
        curl -fsSL "$PACKAGE_URL" -o "$TMP_DIR/package.tar.gz"
    else
        wget -q "$PACKAGE_URL" -O "$TMP_DIR/package.tar.gz"
    fi
    msg "    ✅ 下载完成" "    ✅ Downloaded"
    echo ""

    msg "==> 解压安装包..." "==> Extracting..."
    if tar --warning=no-unknown-keyword -xzf "$TMP_DIR/package.tar.gz" -C "$TMP_DIR" 2>/dev/null; then
        :
    else
        tar -xzf "$TMP_DIR/package.tar.gz" -C "$TMP_DIR"
    fi

    if [ -d "$TMP_DIR/$PACKAGE_NAME" ]; then
        INSTALL_SRC="$TMP_DIR/$PACKAGE_NAME"
    elif [ -f "$TMP_DIR/package.json" ]; then
        INSTALL_SRC="$TMP_DIR"
    else
        INSTALL_SRC=$(find "$TMP_DIR" -name "package.json" -maxdepth 2 -exec dirname {} \; | head -1 || true)
        if [ -z "$INSTALL_SRC" ]; then
            msg "❌ 解压后未找到 package.json，安装包结构异常" \
                "❌ package.json not found — unexpected package structure"
            exit 1
        fi
    fi
    msg "    ✅ 解压完成" "    ✅ Extracted"
    echo ""
}

# ============================================================
# Agent probe: detect available agents via Node.js CLI probe
# ============================================================
PROBE_RESULT="[]"

probe_agents() {
    # Selection and entry binding are independent: explicit/all-agent installs
    # also need the installer environment to discover and persist OpenClaw.
    msg "==> 探测 AI Agent..." "==> Probing AI Agents..."
    PROBE_RESULT=$("$NODE_BIN" "$INSTALL_SRC/dist/cli-probe.cjs" --installer --config-path "$DATA_DIR/config.json" 2>/dev/null) || {
        msg "    ⚠️  Agent 探测失败，将跳过选择" "    ⚠️  Agent probe failed, skipping selection"
        PROBE_RESULT="[]"
        return 0
    }
    local count
    count=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "const r=JSON.parse(require('fs').readFileSync(0,'utf8'));process.stdout.write(String(r.length))" 2>/dev/null || echo "0")
    msg "    ✅ 探测到 ${count} 个 Agent 定义" "    ✅ Found ${count} agent definitions"
    echo ""
}

# ============================================================
# Agent selection: interactive menu or --agents flag
# ============================================================
select_agents() {
    # --all-agents: collect every agent. Skip selection entirely and leave no
    # enabled gate in config (other agent settings survive), so pilot auto-detects
    # all agents at runtime — including ones installed after this run.
    if [ "$ALL_AGENTS" = "1" ]; then
        if [ -n "$SELECTED_AGENTS" ]; then
            msg "    ⚠️  --all-agents 已启用，忽略 --agents 指定的列表" \
                "    ⚠️  --all-agents is set; ignoring the --agents list"
            SELECTED_AGENTS=""
        fi
        msg "    采集全部 Agent (不写入选择，由 pilot 运行时自动探测)" \
            "    Collecting all agents (no selection written; pilot auto-detects at runtime)"
        echo ""
        return 0
    fi

    if [ -n "$SELECTED_AGENTS" ]; then
        msg "    使用指定的 Agent: $SELECTED_AGENTS" "    Using specified agents: $SELECTED_AGENTS"
        echo ""
        return 0
    fi

    local agent_count
    agent_count=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "const r=JSON.parse(require('fs').readFileSync(0,'utf8'));process.stdout.write(String(r.length))" 2>/dev/null || echo "0")
    if [ "$agent_count" = "0" ]; then
        return 0
    fi

    # Non-interactive: auto-select all detected agents
    if [ ! -t 0 ]; then
        SELECTED_AGENTS=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
const detected = r.filter(a => a.detected).map(a => a.id);
process.stdout.write(detected.join(','));
" 2>/dev/null || true)
        msg "    (非交互模式) 自动选择已检测到的 Agent: $SELECTED_AGENTS" \
            "    (non-interactive) Auto-selected detected agents: $SELECTED_AGENTS"
        echo ""
        return 0
    fi

    # Interactive menu
    printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
const lang = process.argv[1];
const defaults = [];
for (let i = 0; i < r.length; i++) {
  const a = r[i];
  const status = lang === 'zh'
    ? (a.detected ? '已检测到: ' + a.reason : '未检测到' + (a.reason ? ': ' + a.reason : ''))
    : (a.detected ? 'detected: ' + a.reason : 'not detected' + (a.reason ? ': ' + a.reason : ''));
  console.log('    [' + (i+1) + '] ' + a.displayName.padEnd(16) + '(' + status + ')');
  if (a.detected) defaults.push(i+1);
}
console.log('');
if (lang === 'zh') {
  console.log('    默认选择已检测到的 Agent: ' + defaults.join(','));
  console.log('    输入要启用的编号 (逗号分隔)，直接回车使用默认:');
} else {
  console.log('    Default selection (detected): ' + defaults.join(','));
  console.log('    Enter numbers to enable (comma-separated), press Enter for default:');
}
" "$LANG_MODE"

    # Read user input (Node readline handles UTF-8 editing; normalize Chinese punctuation).
    # Prompt must go to stderr so it is visible and not captured by $().
    local select_input
    select_input=$("$NODE_BIN" -e "
const readline = require('readline');
const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
rl.question('    > ', (answer) => {
  const normalized = answer.replace(/[，、；]/g, ',').trim();
  process.stdout.write(normalized);
  rl.close();
});
") || {
        printf "    > " >&2
        read -r select_input
        select_input=$(printf '%s' "$select_input" | sed 's/，/,/g; s/、/,/g; s/；/,/g')
    }

    # Compute final selection: empty input = detected agents, otherwise use exact input
    if [ -n "$select_input" ]; then AGENT_SELECTION_EXPLICIT=1; fi
    SELECTED_AGENTS=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
const r = JSON.parse(require('fs').readFileSync(0, 'utf8'));
const input = (process.argv[1] || '').replace(/[，、；]/g, ',');
let indices;
if (!input.trim()) {
  indices = r.map((a, i) => a.detected ? i : -1).filter(i => i >= 0);
} else {
  indices = [...new Set(input.trim().split(/[\s,]+/).map(Number).filter(n => n >= 1 && n <= r.length))].map(n => n - 1);
}
const ids = indices.sort((a,b) => a-b).map(i => r[i].id);
process.stdout.write(ids.join(','));
" "$select_input" 2>/dev/null || true)

    if [ -n "$SELECTED_AGENTS" ]; then
        msg "    已选择: $SELECTED_AGENTS" "    Selected: $SELECTED_AGENTS"
    else
        msg "    未选择任何 Agent" "    No agents selected"
    fi
    echo ""
}

# ============================================================
# Interactive: prompt for userId (skipped when --userId / --reset-user-id given or non-interactive)
# ============================================================
prompt_user_id() {
    if [ -n "$USER_ID" ] || [ "$RESET_USER_ID" -eq 1 ]; then return 0; fi
    if [ ! -t 0 ]; then return 0; fi

    local existing_uid=""
    local config_file="$DATA_DIR/config.json"
    if [ -f "$config_file" ]; then
        existing_uid=$("$NODE_BIN" -e "
try { const c=JSON.parse(require('fs').readFileSync(process.argv[1],'utf-8')); process.stdout.write(c.userId||''); } catch {}
" -- "$config_file" 2>/dev/null || true)
    fi

    echo ""
    if [ -n "$existing_uid" ]; then
        msg "    当前 userId: $existing_uid" \
            "    Current userId: $existing_uid"
        msg "    直接回车保留，或输入新值:" \
            "    Press Enter to keep, or type a new value:"
    else
        msg "    请输入你的 userId（用于数据归属，可直接回车跳过）:" \
            "    Enter your userId (for data attribution, press Enter to skip):"
    fi
    printf "    > "
    local input
    read -r input
    input=$(echo "$input" | tr -d '[:space:]')
    if [ -n "$input" ]; then
        USER_ID="$input"
    elif [ -n "$existing_uid" ]; then
        USER_ID="$existing_uid"
    fi
}

# ============================================================
# Interactive: confirm config overwrite when key fields differ
# ============================================================
confirm_config_overwrite() {
    local config_file="$DATA_DIR/config.json"
    if [ ! -f "$config_file" ]; then return 0; fi

    local sls_mode_for_diff=""
    if [ -n "$SLS_API_KEY" ]; then
        sls_mode_for_diff="apiKey"
    elif [ -n "$SLS_AK_ID" ] && [ -n "$SLS_AK_SECRET" ]; then
        sls_mode_for_diff="ak"
    elif [ "$SLS_REQUESTED" -eq 1 ]; then
        sls_mode_for_diff="webtracking"
    fi

    local diffs
    diffs=$("$NODE_BIN" -e "
const fs = require('fs');
let old = {};
try { old = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8')); } catch { process.exit(0); }

const newVals = JSON.parse(process.argv[2]);
const normalizeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean).join(',');
const INTERCEPTOR_MASK_TYPES = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
const parseTypeCsv = value => String(value || '').split(',').map(v => v.trim()).filter(Boolean);
const uniqueTypes = list => [...new Set(list)];
const interceptorModeFinal = newVals.interceptorMode || (old.interceptor||{}).mode || '';
const interceptorTypesFinal = interceptorModeFinal === 'all' ? INTERCEPTOR_MASK_TYPES.slice() : [];
const maskModeFinal = newVals.maskMode || (old.mask||{}).mode || '';
const maskTypesFinal = maskModeFinal === 'custom'
  ? parseTypeCsv(newVals.maskMode ? newVals.maskTypes : ((old.mask||{}).types||[]).join(','))
  : [];
const coveredMaskMode = interceptorTypesFinal.length && maskModeFinal !== 'all' ? 'custom' : maskModeFinal;
const coveredMaskTypes = coveredMaskMode === 'custom' ? uniqueTypes(maskTypesFinal.concat(interceptorTypesFinal)) : [];
const slsModeOf = sls => {
  if (!sls) return '';
  if (sls.mode) return sls.mode;
  if (sls.apiKey) return 'apiKey';
  if (sls.accessKeyId || sls.accessKeySecret) return 'ak';
  return '';
};
const checks = [
  { label: 'sls.endpoint',       oldVal: (old.sls||{}).endpoint||'',       newVal: newVals.slsEndpoint },
  { label: 'sls.project',        oldVal: (old.sls||{}).project||'',        newVal: newVals.slsProject },
  { label: 'sls.logstore',       oldVal: (old.sls||{}).logstore||'',       newVal: newVals.slsLogstore },
  { label: 'sls.mode',           oldVal: slsModeOf(old.sls),               newVal: newVals.slsMode },
  { label: 'cms.licenseKey',     oldVal: (old.cms||{}).licenseKey||'',     newVal: newVals.cmsLicenseKey },
  { label: 'cms.endpoint',       oldVal: (old.cms||{}).endpoint||'',       newVal: newVals.cmsEndpoint },
  { label: 'cms.workspace',      oldVal: (old.cms||{}).workspace||'',      newVal: newVals.cmsWorkspace },
  { label: 'serviceNamePrefix',  oldVal: old.serviceNamePrefix||'',        newVal: newVals.serviceNamePrefix },
  { label: 'dashboard.port',     oldVal: (old.dashboard||{}).port||'',    newVal: newVals.dashboardPort ? Number(newVals.dashboardPort) : '' },
  { label: 'mask.mode',          oldVal: (old.mask||{}).mode||'',          newVal: coveredMaskMode },
  { label: 'mask.types',         oldVal: (old.mask||{}).mode === 'custom' && Array.isArray((old.mask||{}).types) ? normalizeCsv(old.mask.types.join(',')) : '', newVal: coveredMaskTypes.join(',') },
  { label: 'mask.replacementMode', oldVal: (old.mask||{}).replacementMode||'', newVal: newVals.maskReplacementMode },
  { label: 'interceptor.mode',   oldVal: (old.interceptor||{}).mode||'',   newVal: newVals.interceptorMode },
  { label: 'multimodal.storage.type', oldVal: (old.multimodal && old.multimodal.storage && old.multimodal.storage.type) || '', newVal: (newVals.multimodalMode && newVals.multimodalMode !== 'none' && newVals.slsEndpoint && newVals.slsProject && newVals.slsLogstore && newVals.slsMode === 'apiKey') ? 'sls' : '' },
];

const changed = checks.filter(c => c.newVal && c.oldVal && c.newVal !== c.oldVal);
if (!changed.length) process.exit(0);

for (const c of changed) {
  console.log(c.label + ': ' + c.oldVal + ' -> ' + c.newVal);
}
" -- "$config_file" "$(printf '{"slsEndpoint":"%s","slsProject":"%s","slsLogstore":"%s","slsMode":"%s","cmsLicenseKey":"%s","cmsEndpoint":"%s","cmsWorkspace":"%s","serviceNamePrefix":"%s","dashboardPort":"%s","maskMode":"%s","maskTypes":"%s","maskReplacementMode":"%s","multimodalMode":"%s","interceptorMode":"%s"}' \
        "$SLS_ENDPOINT" "$SLS_PROJECT" "$SLS_LOGSTORE" "$sls_mode_for_diff" "$CMS_LICENSE_KEY" "$CMS_ENDPOINT" "$CMS_WORKSPACE" "$SERVICE_NAME_PREFIX" "$DASHBOARD_PORT" "$MASK_MODE" "$MASK_TYPES" "$MASK_REPLACEMENT_MODE" "$MULTIMODAL_MODE" "$INTERCEPTOR_MODE")" 2>/dev/null || true)

    if [ -z "$diffs" ]; then return 0; fi

    echo ""
    msg "⚠️  以下配置将被覆盖:" "⚠️  The following config will be overwritten:"
    echo "$diffs" | while IFS= read -r line; do
        echo "    $line"
    done

    if [ -t 0 ]; then
        echo ""
        msg "    确认覆盖? (y/N):" "    Confirm overwrite? (y/N):"
        printf "    > "
        local answer
        read -r answer
        case "$answer" in
            y|Y|yes|YES) ;;
            *)
                msg "已取消安装" "Installation cancelled"
                exit 0
                ;;
        esac
    else
        msg "    (非交互模式) 继续覆盖" \
            "    (non-interactive) Proceeding with overwrite"
    fi
}

# ============================================================
# Common: deploy bootstrap scripts from the current version
# ============================================================
deploy_bootstrap_scripts() {
    local src_dir="$PERMANENT_DIR/scripts"
    local boot_dir="$HOME/.loongsuite-pilot/bin"
    mkdir -p "$boot_dir"
    cp -f "$src_dir/collector-daemon.js" "$boot_dir/"
    cp -f "$src_dir/updater-daemon.js"   "$boot_dir/"
}

# ============================================================
# Common: deploy package to versions/ directory
# ============================================================
deploy_package() {
    local src="$1"
    local cache_dir="$HOME/.loongsuite-pilot"
    local versions_dir="$cache_dir/versions"
    local current_file="$cache_dir/current"
    local previous_file="$cache_dir/previous"

    local ver="" commit=""
    if [ -f "$src/VERSION" ]; then
        ver=$(grep '^version=' "$src/VERSION" | cut -d= -f2)
        commit=$(grep '^git_commit=' "$src/VERSION" | cut -d= -f2)
    fi

    if [ -n "$ver" ] && [ -n "$commit" ]; then
        local dir_name="${ver}_${commit}"
        local target="$versions_dir/$dir_name"

        if [ -f "$current_file" ]; then
            local old_dir
            old_dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
            if [ -n "$old_dir" ] && [ "$old_dir" != "$dir_name" ]; then
                echo "$old_dir" > "$previous_file"
            fi
        fi

        msg "==> 部署到 $target ..." "==> Deploying to $target ..."
        mkdir -p "$versions_dir"
        rm -rf "$target"
        cp -r "$src" "$target"

        PERMANENT_DIR="$target"
    else
        msg "==> 部署到 $PERMANENT_DIR ..." \
            "==> Deploying to $PERMANENT_DIR ..."
        mkdir -p "$(dirname "$PERMANENT_DIR")"
        rm -rf "$PERMANENT_DIR"
        cp -r "$src" "$PERMANENT_DIR"
    fi
    msg "    ✅ 部署完成" "    ✅ Deployed"
    echo ""

    deploy_bootstrap_scripts

    msg "==> 安装依赖..." "==> Installing dependencies..."
    local modules_ver="${ver:-${INSTALL_VERSION:-latest}}"
    if ensure_node_modules "$modules_ver"; then
        msg "    ✅ 依赖安装完成（预编译 node_modules）" "    ✅ Dependencies installed (prebuilt node_modules)"
    else
        msg "    ⚠️ 预编译 node_modules 不可用，回退 npm install" \
            "    ⚠️ Prebuilt node_modules unavailable, falling back to npm install"
        # Retries: this path pulls ~185 packages from the registry, so a single reset
        # connection used to fail the whole install (npm defaults to 2 retries).
        local npm_out
        npm_out=$(mktemp) || npm_out="${TMPDIR:-/tmp}/loongsuite-pilot-npm-install.log"
        if ! (cd "$PERMANENT_DIR" && run_npm install --production --no-optional \
                --fetch-retries 5 --fetch-retry-mintimeout 2000 --fetch-retry-maxtimeout 60000 \
                >"$npm_out" 2>&1); then
            msg "    ❌ 依赖安装失败" "    ❌ Dependency installation failed"
            dump_npm_failure "$npm_out"
            rm -f "$npm_out"
            return 1
        fi
        tail -n 1 "$npm_out"
        rm -f "$npm_out"
        msg "    ✅ 依赖安装完成" "    ✅ Dependencies installed"
    fi
    echo ""

    msg "==> 部署 hook 脚本..." "==> Deploying hook scripts..."
    postinstall_exit=0
    postinstall_out=""
    if [ -f "$PERMANENT_DIR/scripts/postinstall.js" ]; then
        # postinstall.js falls back to $HOME/.loongsuite-pilot when this is unset, so
        # --data-dir would otherwise put hooks/skills/plugins in the default tree while
        # the config lives elsewhere.
        #
        # Captured because two of the three failure modes are only in the output: a per-tree
        # failure and a thrown main() both exit 0 on purpose (a non-zero exit would abort the
        # npm install fallback above), announcing themselves as "N failed asset tree(s)" and
        # "Post-install failed: <reason>" instead. 2>&1 because both go to stderr.
        postinstall_out="$(LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
            "$NODE_BIN" "$PERMANENT_DIR/scripts/postinstall.js" 2>&1)" || postinstall_exit=$?
        # `if`, not `[ -n ... ] && printf`: under set -e the latter aborts the function when
        # the output is empty.
        if [ -n "$postinstall_out" ]; then
            printf '%s\n' "$postinstall_out"
        fi
    fi
    # An install with no hooks/plugins is not an install: the collector finds nothing to load
    # and every collection cycle fails on a plugin that was never written. Give up here so the
    # caller can stop (install) or roll back (upgrade) instead of reporting success.
    if [ "$postinstall_exit" -ne 0 ]; then
        msg "    ❌ Hook 脚本部署失败 (exit=$postinstall_exit)，hooks/plugins 缺失" \
            "    ❌ Hook script deployment failed (exit=$postinstall_exit); hooks/plugins are missing"
        return 1
    fi
    if printf '%s' "$postinstall_out" | grep -qE "failed asset tree|Post-install failed"; then
        msg "    ❌ Hook 脚本部分部署失败（见上方输出），hooks/plugins 缺失" \
            "    ❌ Some hook asset trees failed to deploy (see the output above); hooks/plugins are missing"
        return 1
    fi
    msg "    ✅ Hook 脚本已部署" "    ✅ Hook scripts deployed"
    msg "    如使用 Codex 桌面版，首次启动需在桌面端手动信任 hooks" \
        "    If using Codex desktop app, please manually trust hooks on first launch"
    echo ""

    # Overlay abort restores autostart via `start`. Publish current only after
    # node_modules + postinstall so that start cannot launch a tree with no hooks.
    if [ -n "$ver" ] && [ -n "$commit" ]; then
        echo "$dir_name" > "$current_file.tmp"
        mv -f "$current_file.tmp" "$current_file"
    fi
}

# ============================================================
# Migrate legacy single-directory layout to versions/ layout
# ============================================================
migrate_legacy_layout() {
    local cache_dir="$HOME/.loongsuite-pilot"
    local current_file="$cache_dir/current"
    local legacy_dir="$cache_dir/package"
    local versions_dir="$cache_dir/versions"

    if [ -f "$current_file" ]; then
        return 0
    fi
    if [ ! -d "$legacy_dir" ] || [ ! -f "$legacy_dir/dist/index.js" ]; then
        return 0
    fi

    msg "==> 迁移旧版本目录结构..." "==> Migrating legacy directory layout..."

    local ver="" commit=""
    if [ -f "$legacy_dir/VERSION" ]; then
        ver=$(grep '^version=' "$legacy_dir/VERSION" | cut -d= -f2)
        commit=$(grep '^git_commit=' "$legacy_dir/VERSION" | cut -d= -f2)
    fi
    ver="${ver:-0.0.0}"
    commit="${commit:-legacy}"

    local dir_name="${ver}_${commit}"
    local target="$versions_dir/$dir_name"

    mkdir -p "$versions_dir"
    cp -r "$legacy_dir" "$target"
    echo "$dir_name" > "$current_file"

    PERMANENT_DIR="$target"
    msg "    ✅ 已迁移到 $target" "    ✅ Migrated to $target"
    echo ""
}

# ============================================================
# Common: write / merge config.json
# ============================================================
write_config() {
    # Drop placeholders and values over 128 bytes. An empty result leaves the previous hostSn.
    # Spaces are kept: a VMware serial is "VMware-" plus hex bytes separated by spaces.
    normalize_host_sn() {
        local value lower bytes
        value=$(printf '%s' "${1-}" | tr -d '\r')
        value="${value#"${value%%[![:space:]]*}"}"
        value="${value%"${value##*[![:space:]]}"}"
        [ -n "$value" ] || return 0
        lower=$(printf '%s' "$value" | tr '[:upper:]' '[:lower:]')
        case "$lower" in
            none|default\ string|to\ be\ filled\ by\ o.e.m.|system\ serial\ number|not\ specified|0)
                return 0
                ;;
        esac
        bytes=$(printf '%s' "$value" | wc -c | tr -d '[:space:]')
        [ "$bytes" -le 128 ] || return 0
        case "$value" in
            *[!A-Za-z0-9._:\ -]*) return 0 ;;
        esac
        printf '%s' "$value"
    }

    # Run a command for at most N seconds. On expiry, kill it and return 1.
    # A failed or expired read leaves hostSn unset, so the previous value stays.
    run_bounded() {
        local secs="$1" outfile="$2"
        shift 2
        "$@" >"$outfile" 2>/dev/null &
        local pid=$!
        local i=0
        while [ "$i" -lt "$secs" ] && kill -0 "$pid" 2>/dev/null; do
            sleep 1
            i=$((i + 1))
        done
        if kill -0 "$pid" 2>/dev/null; then
            kill "$pid" 2>/dev/null || true
            sleep 1
            kill -9 "$pid" 2>/dev/null || true
            wait "$pid" 2>/dev/null || true
            return 1
        fi
        wait "$pid" 2>/dev/null || true
        return 0
    }

    read_host_sn() {
        local uname_s raw candidate path raw_file
        uname_s=$(uname -s 2>/dev/null || true)
        if [ "$uname_s" = "Darwin" ]; then
            raw=""
            raw_file=$(mktemp 2>/dev/null) || return 0
            if run_bounded 5 "$raw_file" ioreg -rd1 -c IOPlatformExpertDevice; then
                raw=$(tr -d '\r' < "$raw_file" 2>/dev/null || true)
            fi
            rm -f "$raw_file"
            candidate=$(printf '%s\n' "$raw" | sed -n 's/.*"IOPlatformSerialNumber" *= *"\([^"]*\)".*/\1/p' | head -n 1 || true)
            if [ "${#candidate}" -gt 128 ]; then
                candidate=""
            fi
            normalize_host_sn "$candidate"
            return 0
        fi
        if [ "$uname_s" = "Linux" ]; then
            for path in \
                /sys/class/dmi/id/product_serial \
                /sys/class/dmi/id/board_serial \
                /sys/class/dmi/id/chassis_serial
            do
                [ -r "$path" ] || continue
                raw=$(tr -d '\r' < "$path" 2>/dev/null || true)
                candidate=$(normalize_host_sn "$raw")
                if [ -n "$candidate" ]; then
                    printf '%s' "$candidate"
                    return 0
                fi
            done
        fi
        return 0
    }

    local config_file="$DATA_DIR/config.json"
    INSTALL_SOURCE=$(resolve_install_source)
    msg "==> 写入配置文件 $config_file ..." \
        "==> Writing config to $config_file ..."
    mkdir -p "$DATA_DIR"

    local host_sn=""
    host_sn=$(read_host_sn 2>/dev/null || true)
    printf '%s' "$PROBE_RESULT" | \
        LP_HOST_SN="$host_sn" \
        LP_SLS_API_KEY="$SLS_API_KEY" \
        LP_SELECTED_AGENTS="$SELECTED_AGENTS" \
        LP_AGENT_SELECTION_EXPLICIT="$AGENT_SELECTION_EXPLICIT" \
        LP_MULTIMODAL_MODE="$MULTIMODAL_MODE" \
        LP_MULTIMODAL_SUPPORTED_AGENTS="$MULTIMODAL_SUPPORTED_AGENTS" \
        LP_DASHBOARD_PORT="$DASHBOARD_PORT" \
        LP_HOOK_TAMPER_PROTECTION="$HOOK_TAMPER_PROTECTION" \
        LP_USER_ID="$USER_ID" LP_RESET_USER_ID="$RESET_USER_ID" \
        LP_INSTALL_SOURCE="$INSTALL_SOURCE" \
        "$NODE_BIN" -e "
const fs = require('fs');
const path = '$config_file';

let existing = {};
try {
  existing = JSON.parse(fs.readFileSync(path, 'utf-8').replace(/^\uFEFF/, ''));
} catch (err) {
  if (err && err.code === 'ENOENT') existing = {};
  else {
    throw new Error(err instanceof SyntaxError
      ? 'config.json is not valid JSON'
      : 'cannot read config.json');
  }
}
if (existing === null || typeof existing !== 'object' || Array.isArray(existing)) {
  throw new Error('config.json must be a JSON object');
}

const config = {
  ...existing,
  enabled: true,
  dataDir: '$DATA_DIR',
};
if (!config.dashboard || typeof config.dashboard !== 'object' || Array.isArray(config.dashboard)) {
  config.dashboard = {};
}
const dashboardPort = process.env.LP_DASHBOARD_PORT || '';
if (dashboardPort) config.dashboard.port = Number(dashboardPort);
if (config.dashboard.port === undefined) config.dashboard.port = 8765;
delete config.internal;
if (config.userId === undefined && config['user.id'] !== undefined) {
  config.userId = config['user.id'];
}
delete config['user.id'];

const slsEndpoint = '${SLS_ENDPOINT}';
const slsProject  = '${SLS_PROJECT}';
const slsLogstore = '${SLS_LOGSTORE}';
const slsAkId     = '${SLS_AK_ID}';
const slsAkSecret = '${SLS_AK_SECRET}';
const slsApiKey   = process.env.LP_SLS_API_KEY || '';
const logLevel    = '${LOG_LEVEL}';
const userId      = process.env.LP_USER_ID || '';

if (slsEndpoint || slsProject || slsLogstore || slsApiKey) {
  if (Array.isArray(config.sls)) {
    throw new Error('existing config.sls is an array; full install cannot rewrite it');
  }
  if (config.sls != null && typeof config.sls !== 'object') {
    throw new Error('existing config.sls has an unsupported shape');
  }
  config.sls = config.sls || {};
  delete config.sls.destinationOverride;
  if (slsEndpoint) {
    config.sls.endpoint = slsEndpoint;
  }
  if (slsApiKey) {
    config.sls.mode = 'apiKey';
    config.sls.apiKey = slsApiKey;
    delete config.sls.accessKeyId;
    delete config.sls.accessKeySecret;
  } else if (slsAkId && slsAkSecret) {
    config.sls.mode = 'ak';
    config.sls.accessKeyId = slsAkId;
    config.sls.accessKeySecret = slsAkSecret;
    delete config.sls.apiKey;
  } else if (slsEndpoint || slsProject || slsLogstore) {
    config.sls.mode = 'webtracking';
    delete config.sls.apiKey;
    delete config.sls.accessKeyId;
    delete config.sls.accessKeySecret;
  }
  if (slsProject && slsLogstore) {
    config.sls.project = slsProject;
    config.sls.logstore = slsLogstore;
    delete config.sls.endpoints;
  }
}

if (logLevel) {
  config.logLevel = logLevel;
}

if (userId) {
  config.userId = userId;
  delete config.identity;
} else if (process.env.LP_RESET_USER_ID === '1') {
  delete config.userId;
  delete config.identity;
}

const hostSn = process.env.LP_HOST_SN || '';
if (hostSn) config.hostSn = hostSn;
const installSource = process.env.LP_INSTALL_SOURCE || '';
if (installSource) config.installSource = installSource;

const updateUrl = '${UPDATE_PACKAGE_URL}';
if (updateUrl) {
  config.autoUpdate = config.autoUpdate || {};
  config.autoUpdate.packageUrl = updateUrl;
}

const installMode = '${INSTALL_MODE}';
if (installMode === 'container') {
  // A container is replaced, not patched: an in-place self-update would make the
  // running container diverge from the image it was built from, and there is no
  // init system inside to supervise the swap. The updater process self-exits when
  // this is false, so the entrypoint never needs to know about it.
  config.autoUpdate = config.autoUpdate || {};
  config.autoUpdate.enabled = false;
}

const collectLog = '${COLLECT_LOG}';
const collectTrace = '${COLLECT_TRACE}';
const cmsLicenseKey = '${CMS_LICENSE_KEY}';
const cmsEndpoint = '${CMS_ENDPOINT}';
const cmsWorkspace = '${CMS_WORKSPACE}';
const serviceNamePrefix = '${SERVICE_NAME_PREFIX}';
const selectedAgents = process.env.LP_SELECTED_AGENTS || '';
const allAgentsMode = '${ALL_AGENTS}';
const multimodalMode = process.env.LP_MULTIMODAL_MODE || '';
const maskMode = '${MASK_MODE}';
const maskTypes = '${MASK_TYPES}';
const maskReplacementMode = '${MASK_REPLACEMENT_MODE}';
const interceptorMode = '${INTERCEPTOR_MODE}';

if (collectLog) config.collectLog = collectLog === 'true';
if (collectTrace) config.collectTrace = collectTrace === 'true';
const multicaMode = '${MULTICA_COLLECTION_MODE}';
if (multicaMode) {
  config.pipeline = config.pipeline || {};
  config.pipeline.multica = config.pipeline.multica || {};
  config.pipeline.multica.mode = multicaMode;
}

if (cmsLicenseKey || cmsEndpoint || cmsWorkspace) {
  config.cms = config.cms || {};
  if (cmsLicenseKey) config.cms.licenseKey = cmsLicenseKey;
  if (cmsEndpoint) config.cms.endpoint = cmsEndpoint;
  if (cmsWorkspace) config.cms.workspace = cmsWorkspace;
}

if (serviceNamePrefix) config.serviceNamePrefix = serviceNamePrefix;

if (maskMode) {
  config.mask = config.mask || {};
  config.mask.mode = maskMode;
  if (maskMode === 'custom') {
    config.mask.types = maskTypes
      .split(',')
      .map(type => type.trim())
      .filter(Boolean);
  } else {
    delete config.mask.types;
  }
}
if (maskReplacementMode) {
  config.mask = config.mask || {};
  config.mask.replacementMode = maskReplacementMode;
}

if (interceptorMode) {
  config.interceptor = config.interceptor || {};
  config.interceptor.mode = interceptorMode;
  delete config.interceptor.types;
}

const hookTamperProtection = process.env.LP_HOOK_TAMPER_PROTECTION || '';
if (hookTamperProtection) {
  if (!config.hookWatchdog || typeof config.hookWatchdog !== 'object' || Array.isArray(config.hookWatchdog)) {
    config.hookWatchdog = {};
  }
  if (!config.hookWatchdog.tamperProtection || typeof config.hookWatchdog.tamperProtection !== 'object' || Array.isArray(config.hookWatchdog.tamperProtection)) {
    config.hookWatchdog.tamperProtection = {};
  }
  config.hookWatchdog.tamperProtection.enabled = hookTamperProtection === 'true';
}

const INTERCEPTOR_MASK_TYPES = ['cloudAccessKey', 'apiKey', 'privateKey', 'databaseUrl'];
(function ensureMaskCoversInterceptor(config) {
  const interceptor = config.interceptor || {};
  const extra = interceptor.mode === 'all' ? INTERCEPTOR_MASK_TYPES.slice() : [];
  if (extra.length === 0) return;
  if ((config.mask || {}).mode === 'all') return;
  const current = (config.mask || {}).mode === 'custom' && Array.isArray((config.mask || {}).types)
    ? config.mask.types.filter(type => typeof type === 'string' && type.trim())
    : [];
  config.mask = config.mask && typeof config.mask === 'object' && !Array.isArray(config.mask)
    ? config.mask
    : {};
  config.mask.mode = 'custom';
  config.mask.types = [...new Set(current.concat(extra))];
})(config);

const allAgents = JSON.parse(fs.readFileSync(0, 'utf8') || '[]');
if (allAgentsMode === '1') {
  // Clear enable gates, not metadata such as a persisted OpenClaw entry.
  for (const agent of Object.values(config.agents || {})) delete agent.enabled;
} else if (selectedAgents) {
  config.agents = config.agents || {};
  const previousOpenclaw = config.agents.openclaw;
  const selected = selectedAgents.split(',').map(s => s.trim()).filter(Boolean);
  for (const agent of allAgents) {
    config.agents[agent.id] = config.agents[agent.id] || {};
    // A transient discovery miss is not consent to uninstall a live plugin.
    if (agent.id === 'openclaw' && !agent.detected && process.env.LP_AGENT_SELECTION_EXPLICIT !== '1'
        && previousOpenclaw !== undefined) {
      console.log('OpenClaw: detection unavailable; preserving previous enabled state and entry');
      continue;
    }
    config.agents[agent.id].enabled = selected.includes(agent.id);
  }
}
const openclaw = allAgents.find(agent => agent.id === 'openclaw');
if (openclaw && openclaw.detected && openclaw.openclawCliPath
    && (allAgentsMode === '1' || (config.agents && config.agents.openclaw && config.agents.openclaw.enabled !== false))) {
  config.agents = config.agents || {};
  config.agents.openclaw = config.agents.openclaw || {};
  const previousEntry = config.agents.openclaw.cliPath;
  if (typeof previousEntry === 'string' && previousEntry !== openclaw.openclawCliPath) {
    console.log('OpenClaw: updating launch entry ' + JSON.stringify(previousEntry) + ' -> ' + JSON.stringify(openclaw.openclawCliPath));
  }
  config.agents.openclaw.cliPath = openclaw.openclawCliPath;
}

if (multimodalMode) {
  config.agents = config.agents || {};
  const supported = (process.env.LP_MULTIMODAL_SUPPORTED_AGENTS || '').split(',').map(s => s.trim()).filter(Boolean);
  const selected = new Set(selectedAgents.split(',').map(s => s.trim()).filter(Boolean));
  const allSupported = allAgentsMode === '1' && multimodalMode !== 'none';
  for (const id of supported) {
    if (allSupported) config.agents[id] = config.agents[id] || {};
    else if (!config.agents[id]) continue;
    if (multimodalMode === 'none') {
      delete config.agents[id].multimodal;
      continue;
    }
    const prev = (config.agents[id].multimodal && typeof config.agents[id].multimodal === 'object')
      ? config.agents[id].multimodal
      : {};
    config.agents[id].multimodal = { ...prev, uploadMode: (allSupported || selected.has(id)) ? multimodalMode : 'none' };
  }
}

if (multimodalMode && multimodalMode !== 'none' && slsEndpoint && slsProject && slsLogstore && slsApiKey) {
  config.multimodal = {
    storage: {
      type: 'sls',
      target: { endpoint: slsEndpoint, project: slsProject, logstore: slsLogstore },
    },
  };
}

const tempPath = path + '.tmp-' + process.pid + '-' + Date.now();
try {
  fs.writeFileSync(tempPath, JSON.stringify(config, null, 2) + '\n', { encoding: 'utf8', mode: 0o600, flag: 'wx' });
  fs.chmodSync(tempPath, 0o600);
  fs.renameSync(tempPath, path);
} finally {
  if (fs.existsSync(tempPath)) fs.rmSync(tempPath, { force: true });
}
"
    msg "    ✅ 配置已写入" "    ✅ Config written"
    echo ""
}

# ============================================================
# Common: install/update the loongsuite-pilot service management script
# ============================================================
install_loongsuite_pilot_command() {
    msg "==> 安装服务管理脚本..." "==> Installing service management script..."
    local global_bin_dir="$HOME/.local/bin"
    mkdir -p "$global_bin_dir"

    local loongsuite_pilot_cmd="$global_bin_dir/loongsuite-pilot"
    cp -f "$PERMANENT_DIR/scripts/loongsuite-pilot.sh" "$loongsuite_pilot_cmd"
    chmod +x "$loongsuite_pilot_cmd"
    msg "    ✅ 已安装: $loongsuite_pilot_cmd" "    ✅ Installed: $loongsuite_pilot_cmd"

    ensure_path_block() {
        local file="$1"
        if [ ! -f "$file" ]; then
            touch "$file" 2>/dev/null || return 0
        fi
        if [ ! -w "$file" ]; then
            msg "    ⚠️  $file 不可写，跳过" "    ⚠️  $file is not writable, skipping"
            return 0
        fi
        if grep -q '\.local/bin' "$file" 2>/dev/null; then return 0; fi
        # Ensure file ends with a newline before appending
        [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
        cat >> "$file" << 'PATHBLOCK'

# loongsuite-pilot: add ~/.local/bin to PATH
export PATH="$HOME/.local/bin:$PATH"
PATHBLOCK
        msg "    已将 ~/.local/bin 添加到 PATH ($file)" \
            "    Added ~/.local/bin to PATH ($file)"
    }

    # Append the installer PATH export to the login file bash will read.
    # Return 0 only when that exact export line is present.
    migrate_installer_path_export() {
        local file="$HOME/.profile"
        if [ -f "$HOME/.bash_login" ]; then
            file="$HOME/.bash_login"
        fi
        local export_line='export PATH="$HOME/.local/bin:$PATH"'
        if [ -f "$file" ] && grep -qxF -- "$export_line" "$file"; then
            return 0
        fi
        if [ -e "$file" ] && [ ! -w "$file" ]; then
            return 1
        fi
        if [ ! -e "$file" ]; then
            touch "$file" 2>/dev/null || return 1
        fi
        if [ ! -w "$file" ]; then
            return 1
        fi
        # Ensure file ends with a newline before appending
        [ -s "$file" ] && [ "$(tail -c1 "$file" | wc -l)" -eq 0 ] && echo "" >> "$file"
        cat >> "$file" << 'PATHBLOCK'

# loongsuite-pilot: add ~/.local/bin to PATH
export PATH="$HOME/.local/bin:$PATH"
PATHBLOCK
        grep -qxF -- "$export_line" "$file"
    }

    # Remove ~/.bash_profile when every non-blank line is the installer PATH block
    # and the login file bash will read contains that PATH export.
    remove_installer_created_bash_profile() {
        local file="$HOME/.bash_profile"
        [ -f "$file" ] || return 0
        [ -L "$file" ] && return 0
        [ -w "$file" ] || return 0
        local line=""
        local trimmed=""
        local nonempty=0
        while IFS= read -r line || [ -n "${line}" ]; do
            line="${line%$'\r'}"
            trimmed="${line#"${line%%[![:space:]]*}"}"
            trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
            [ -n "$trimmed" ] || continue
            nonempty=1
            case "$trimmed" in
                '# loongsuite-pilot: add ~/.local/bin to PATH') ;;
                'export PATH="$HOME/.local/bin:$PATH"') ;;
                *) return 0 ;;
            esac
        done < "$file"
        [ "$nonempty" -eq 1 ] || return 0
        migrate_installer_path_export || return 0
        local backup="$file.bak.$(date '+%Y%m%d%H%M%S')"
        local n=1
        while [ -e "$backup" ]; do
            backup="$file.bak.$(date '+%Y%m%d%H%M%S').$n"
            n=$((n + 1))
        done
        cp -a "$file" "$backup" || return 0
        rm -f "$file" || return 0
        [ ! -e "$file" ] || return 0
        msg "    已移除仅含 PATH 的 ~/.bash_profile（备份 ${backup}）" \
            "    Removed ~/.bash_profile that contained only the PATH block (backup $backup)"
    }

    case "${SHELL:-/bin/bash}" in
        */bash)
            remove_installer_created_bash_profile || true
            ;;
    esac

    # If /usr/local/bin is writable (root), create a symlink for immediate PATH access
    if [ -d /usr/local/bin ] && [ -w /usr/local/bin ]; then
        ln -sf "$loongsuite_pilot_cmd" /usr/local/bin/loongsuite-pilot
        msg "    ✅ 已链接到 /usr/local/bin/loongsuite-pilot" "    ✅ Linked to /usr/local/bin/loongsuite-pilot"
    else
        case "${SHELL:-/bin/bash}" in
            */zsh)
                ensure_path_block "$HOME/.zshrc" || true
                ;;
            */bash)
                ensure_path_block "$HOME/.bashrc" || true
                # Do not create ~/.bash_profile just to add PATH. On Debian/Ubuntu
                # style accounts, its mere presence prevents bash login shells from
                # reading ~/.profile, which often sources ~/.bashrc and user aliases.
                if [ -f "$HOME/.bash_profile" ]; then
                    ensure_path_block "$HOME/.bash_profile" || true
                elif [ -f "$HOME/.bash_login" ]; then
                    ensure_path_block "$HOME/.bash_login" || true
                else
                    ensure_path_block "$HOME/.profile" || true
                fi
                ;;
            *)
                ensure_path_block "$HOME/.bashrc" || true
                ;;
        esac
    fi
    echo ""

    # Ensure loongsuite-pilot is on PATH for the rest of this script
    export PATH="$global_bin_dir:$PATH"
}

# ============================================================
# Common: read VERSION file fields
# ============================================================
get_installed_version() {
    local cache_dir="$HOME/.loongsuite-pilot"
    local current_file="$cache_dir/current"
    local versions_dir="$cache_dir/versions"

    if [ -f "$current_file" ]; then
        local dir
        dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
        if [ -n "$dir" ] && [ -f "$versions_dir/$dir/VERSION" ]; then
            grep '^version=' "$versions_dir/$dir/VERSION" | cut -d= -f2
            return 0
        fi
    fi

    local vf="$PERMANENT_DIR/VERSION"
    if [ -f "$vf" ]; then
        grep '^version=' "$vf" | cut -d= -f2
    else
        echo ""
    fi
}

get_installed_commit() {
    local cache_dir="$HOME/.loongsuite-pilot"
    local current_file="$cache_dir/current"
    local versions_dir="$cache_dir/versions"

    if [ -f "$current_file" ]; then
        local dir
        dir=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
        if [ -n "$dir" ] && [ -f "$versions_dir/$dir/VERSION" ]; then
            local commit
            commit=$(grep '^git_commit=' "$versions_dir/$dir/VERSION" | cut -d= -f2) || commit=""
            if [ -n "$commit" ]; then
                printf '%s\n' "$commit"
                return 0
            fi
        fi
    fi

    get_commit_from_dir "$PERMANENT_DIR"
}

get_version_from_dir() {
    local vf="$1/VERSION"
    if [ -f "$vf" ]; then
        grep '^version=' "$vf" | cut -d= -f2
    else
        echo ""
    fi
}

get_commit_from_dir() {
    local vf="$1/VERSION"
    if [ -f "$vf" ]; then
        grep '^git_commit=' "$vf" | cut -d= -f2
    else
        echo ""
    fi
}

show_version_info() {
    local dir="$1"
    local vf="$dir/VERSION"
    if [ -f "$vf" ]; then
        local v; v=$(grep '^version=' "$vf" | cut -d= -f2)
        local c; c=$(grep '^git_commit=' "$vf" | cut -d= -f2)
        local t; t=$(grep '^build_time=' "$vf" | cut -d= -f2)
        echo "v${v} (${c}, ${t})"
    else
        echo "unknown"
    fi
}

# ============================================================
# Common: print summary
# ============================================================
# ============================================================
# Remove legacy Claude OTel plugin
# ============================================================
remove_otel_plugin() {
    local OTEL_CLAUDE_DIR="$HOME/.cache/opentelemetry.instrumentation.claude"

    # Prevent NODE_OPTIONS --require intercept.js from breaking node commands
    # after the Claude plugin directory (and intercept.js) is deleted
    unset NODE_OPTIONS 2>/dev/null || true

    if [ -f "$OTEL_CLAUDE_DIR/package/scripts/uninstall.sh" ]; then
        bash "$OTEL_CLAUDE_DIR/package/scripts/uninstall.sh" 2>/dev/null || true
        msg "    ✅ Claude Code 插件 hooks 和 alias 已清理" \
            "    ✅ Claude Code plugin hooks and alias cleaned"
    else
        for rc in "$HOME/.bashrc" "$HOME/.zshrc" "$HOME/.bash_profile"; do
            [ -f "$rc" ] || continue
            if grep -q "# BEGIN otel-claude-hook" "$rc" 2>/dev/null; then
                sed -i.bak '/# BEGIN otel-claude-hook/,/# END otel-claude-hook/d' "$rc"
                rm -f "${rc}.bak"
            fi
            if grep -q "# BEGIN otel-claude-hook-env" "$rc" 2>/dev/null; then
                sed -i.bak '/# BEGIN otel-claude-hook-env/,/# END otel-claude-hook-env/d' "$rc"
                rm -f "${rc}.bak"
            fi
        done
        msg "    ✅ claude alias 已清理" "    ✅ claude alias cleaned"

        # Clean settings.json hooks (fallback when uninstall.sh is unavailable)
        local claude_settings="$HOME/.claude/settings.json"
        if [ -f "$claude_settings" ] && grep -qE "otel-claude-hook|hook-entry\.sh" "$claude_settings" 2>/dev/null && command -v node &>/dev/null; then
            node -e "
const fs = require('fs');
const f = process.argv[1];
const isOurs = c => c.includes('otel-claude-hook') || c.includes('hook-entry.sh');
try {
  const d = JSON.parse(fs.readFileSync(f, 'utf-8'));
  if (d && d.hooks) {
    for (const ev of Object.keys(d.hooks)) {
      if (!Array.isArray(d.hooks[ev])) continue;
      d.hooks[ev] = d.hooks[ev].map(m => {
        if (!Array.isArray(m.hooks)) return m;
        m.hooks = m.hooks.filter(h => !(h.command && isOurs(h.command)));
        return m.hooks.length > 0 ? m : null;
      }).filter(Boolean);
      if (d.hooks[ev].length === 0) delete d.hooks[ev];
    }
    if (Object.keys(d.hooks).length === 0) delete d.hooks;
    fs.writeFileSync(f, JSON.stringify(d, null, 2) + '\n');
  }
} catch {}
" "$claude_settings" 2>/dev/null || true
            msg "    ✅ settings.json hooks 已清理" "    ✅ settings.json hooks cleaned"
        fi
    fi

    local otel_config="$HOME/.claude/otel-config.json"
    if [ -f "$otel_config" ] && command -v node &>/dev/null; then
        node -e "
const fs = require('fs');
try {
  const cfg = JSON.parse(fs.readFileSync(process.argv[1], 'utf-8'));
  delete cfg.log_enabled;
  delete cfg.log_dir;
  delete cfg.log_filename_format;
  fs.writeFileSync(process.argv[1], JSON.stringify(cfg, null, 2) + '\n');
} catch {}
" "$otel_config" 2>/dev/null || true
    fi

    if [ -d "$OTEL_CLAUDE_DIR" ]; then
        if [ "$PURGE" -eq 1 ]; then
            rm -rf "$OTEL_CLAUDE_DIR"
            msg "    ✅ 插件目录已完全删除 (--purge): $OTEL_CLAUDE_DIR" \
                "    ✅ Plugin directory fully removed (--purge): $OTEL_CLAUDE_DIR"
        else
            find "$OTEL_CLAUDE_DIR" -maxdepth 1 \
              ! -name sessions \
              ! -name "$(basename "$OTEL_CLAUDE_DIR")" \
              -exec rm -rf {} + 2>/dev/null || true
            msg "    ✅ 插件文件已删除（sessions/ 已保留）" \
                "    ✅ Plugin files removed (sessions/ preserved)"
        fi
    fi

}

print_summary() {
    local action="$1"  # install / upgrade
    local config_file="$DATA_DIR/config.json"
    echo "============================================================"
    local ver; ver=$(show_version_info "$PERMANENT_DIR")
    case "$action" in
        install)
            msg "✅ 安装完成！版本: $ver" "✅ Installation complete! Version: $ver" ;;
        upgrade)
            msg "✅ 升级完成！版本: $ver" "✅ Upgrade complete! Version: $ver" ;;
    esac
    echo ""
    msg "配置文件: $config_file" "Config file: $config_file"
    msg "数据目录: $DATA_DIR" "Data directory: $DATA_DIR"
    msg "Hook 目录: $DATA_DIR/hooks" "Hooks directory: $DATA_DIR/hooks"
    echo ""

    if [ -n "$SLS_ENDPOINT" ]; then
        msg "SLS 后端: $SLS_ENDPOINT" "SLS backend: $SLS_ENDPOINT"
        [ -n "$SLS_PROJECT" ]  && msg "   项目: $SLS_PROJECT" "   Project: $SLS_PROJECT"
        [ -n "$SLS_LOGSTORE" ] && msg "   日志库: $SLS_LOGSTORE" "   Logstore: $SLS_LOGSTORE"
        echo ""
    fi

    if [ "$INSTALL_MODE" = "container" ]; then
        msg "模式: container (未注册开机自启，未启动守护进程，已关闭自动更新)" \
            "Mode: container (no autostart registered, no daemon started, auto-update disabled)"
        echo ""
        msg "采集器要由镜像 entrypoint 前台启动 (loongsuite-pilot run)，参考实现已随安装落地:" \
            "The collector must be started by your image entrypoint (loongsuite-pilot run); the reference one is installed:"
        echo "   ENTRYPOINT [\"$DATA_DIR/entrypoint.sh\"]"
        echo "============================================================"
        return 0
    fi

    msg "命令:" "Commands:"
    echo "   loongsuite-pilot          # 查看状态 / Status"
    echo "   loongsuite-pilot info     # 版本与配置 / Version & config"
    echo "============================================================"
}

# ============================================================
# Container mode: synchronous deployment instead of starting a daemon
# ============================================================

# Warn about credentials that would be frozen into the image layer. Anyone who can
# pull the image can read them back out of config.json, and `docker history` keeps
# the build args too — so the recommendation is to inject them at container start.
container_warn_baked_secrets() {
    local baked=""
    [ -n "$CMS_LICENSE_KEY" ] && baked="${baked} --cms-license-key"
    [ -n "$SLS_AK_ID" ] && baked="${baked} --sls-ak-id"
    [ -n "$SLS_AK_SECRET" ] && baked="${baked} --sls-ak-secret"
    [ -n "$SLS_API_KEY" ] && baked="${baked} --sls-api-key"
    [ -z "$baked" ] && return 0

    msg "    ⚠️  凭证已写入镜像层:${baked}" \
        "    ⚠️  Credentials baked into the image layer:${baked}"
    msg "        任何能拉取该镜像的人都能读到它们。建议改为容器启动时注入环境变量:" \
        "        Anyone who can pull the image can read them. Prefer runtime env vars:"
    # These are the names config-loader.ts actually reads (LOONGSUITE_PILOT_CMS_LICENSE_KEY
    # at cms build time, LOONGSUITE_SLS_ACCESS_KEY_* in buildSlsConfig). Do NOT list the
    # LP_* names here: those are consumed by this installer's embedded node at build time
    # and mean nothing to the collector at runtime.
    echo "        LOONGSUITE_PILOT_CMS_LICENSE_KEY"
    echo "        LOONGSUITE_SLS_ACCESS_KEY_ID / LOONGSUITE_SLS_ACCESS_KEY_SECRET"
    echo "        LOONGSUITE_SLS_API_KEY"
    # The SLS env override only applies to the single-object config.sls form, which is
    # what this installer writes. Keep that caveat visible so nobody carries the advice
    # over to a config that stores endpoints as an array.
    msg "        (SLS 环境变量仅对单对象形态的 config.sls 生效——本安装器写的就是该形态)" \
        "        (the SLS env vars only apply to the single-object config.sls form, which is what this installer writes)"
    echo ""
}

# Remove build-time runtime residue. A pid/lock file baked into the image points at
# a pid from the build host, which makes the first `loongsuite-pilot status` inside a
# container lie, and a stale lock can make the collector refuse to start. Build logs
# have no reason to ship either. The deployment state file is deliberately KEPT: the
# hook/plugin targets it describes are in the same image, so re-deploying at each
# container start would be pure duplication risk.
container_clean_build_residue() {
    msg "==> 清理构建期残留..." "==> Cleaning build-time residue..."
    rm -f "$DATA_DIR/loongsuite-pilot.pid" \
          "$DATA_DIR/loongsuite-pilot-updater.pid" \
          "$DATA_DIR/loongsuite-pilot-monitor.pid" \
          "$DATA_DIR/loongsuite-pilot-dashboard.pid" \
          "$DATA_DIR/collector.lock" \
          "$DATA_DIR/last-startup-crash.json" 2>/dev/null || true
    rm -rf "$DATA_DIR/logs" "$DATA_DIR/tmp" 2>/dev/null || true
    # Plugin-probe workers keep their pid under <destDir>/.agent-worker/worker.pid, not
    # in $DATA_DIR itself. A build-host pid left there can collide with an unrelated live
    # pid in the container's fresh PID namespace, and isWorkerRunning() would then report
    # a worker that does not exist — so the collector never starts one and telemetry is
    # silently missing. Sweep them by name rather than listing every destDir.
    find "$DATA_DIR" -type d -name '.agent-worker' -prune -exec rm -rf {} + 2>/dev/null || true
    msg "    ✅ 已清理" "    ✅ Cleaned"
    echo ""
}

# Install the reference entrypoint that starts the collector at container start.
#
# It ships in the package rather than being COPYed by the Dockerfile: the customer's
# build context is their own repo, not this one, so there is nothing there to copy from
# — and the script drives this exact CLI, so shipping the two together is what keeps
# them in step.
#
# $DATA_DIR, not ~/.local/bin: nobody types this, it is a fixed path an image's
# ENTRYPOINT refers to, and $DATA_DIR is already the one path container mode prints.
container_install_entrypoint() {
    msg "==> 安装容器 entrypoint..." "==> Installing container entrypoint..."
    local src="$PERMANENT_DIR/scripts/container-entrypoint.sh"
    local dest="$DATA_DIR/entrypoint.sh"

    # Fail the build rather than ship an image whose ENTRYPOINT does not exist: with no
    # daemon and no init service, this file is the only thing that starts the collector.
    if [ ! -f "$src" ]; then
        msg "    ❌ 安装包中缺少 scripts/container-entrypoint.sh" \
            "    ❌ scripts/container-entrypoint.sh is missing from the package"
        return 1
    fi

    mkdir -p "$DATA_DIR"
    cp -f "$src" "$dest"
    chmod +x "$dest"
    msg "    ✅ 已安装: $dest" "    ✅ Installed: $dest"
    # Exec-form ENTRYPOINT is not run through a shell, so $HOME is never expanded there.
    msg "        在 Dockerfile 中写绝对路径: ENTRYPOINT [\"$dest\"]" \
        "        Use the absolute path in your Dockerfile: ENTRYPOINT [\"$dest\"]"
    echo ""
}

container_write_agents() {
    local agents=""
    # --all-agents deliberately keeps runtime deployment in auto scope so agents
    # installed after image build are still discovered. Persisting the build-time
    # probe result would make entrypoint run a named hook install and switch the
    # daemon to recorded scope, silently changing --all-agents semantics.
    if [ "${ALL_AGENTS:-0}" != "1" ]; then
        agents="$SELECTED_AGENTS"
    fi
    if [ "${ALL_AGENTS:-0}" != "1" ] && [ -z "$agents" ]; then
        agents=$(printf '%s' "$PROBE_RESULT" | "$NODE_BIN" -e "
const rows = JSON.parse(require('fs').readFileSync(0, 'utf8') || '[]');
process.stdout.write(rows.filter(row => row && row.detected).map(row => row.id).join(','));
" 2>/dev/null || true)
    fi

    local dest="$DATA_DIR/container-agents"
    local tmp="${dest}.$$"
    mkdir -p "$DATA_DIR"
    if ! printf '%s\n' "$agents" > "$tmp" || ! mv -f "$tmp" "$dest"; then
        rm -f "$tmp"
        msg "    ❌ 无法写入容器 Agent 列表: $dest" \
            "    ❌ Could not write container agent list: $dest"
        return 1
    fi
    msg "    ✅ 容器 Agent 列表: ${agents:-<empty>}" \
        "    ✅ Container agent list: ${agents:-<empty>}"
}

container_finalize_install() {
    container_warn_baked_secrets
    container_install_entrypoint || return 1

    msg "==> 部署 Hook / 插件 (容器模式，不启动守护进程)..." \
        "==> Deploying hooks/plugins (container mode, no daemon started)..."

    # --require turns "the agent was not detected" from a silent skip into a non-zero
    # exit, so a `RUN` layer fails instead of producing an image that merely looks
    # instrumented.
    #
    # The gate deliberately reads AGENTS_EXPLICIT, not SELECTED_AGENTS: in a
    # non-interactive build select_agents() fills SELECTED_AGENTS with whatever it just
    # DETECTED, so requiring that list asserts nothing — the agent that failed to make
    # it into the layer is exactly the one missing from the probe result. Only a list the
    # caller typed is a declared expectation.
    # Two explicit invocations rather than an args array: bash 3.2 (still the system
    # bash on macOS) treats "${arr[@]}" on an empty array as unbound under `set -u`.
    local deploy_ok=0
    if [ "$AGENTS_EXPLICIT" = "1" ] && [ -n "$SELECTED_AGENTS" ]; then
        loongsuite-pilot deploy --require "$SELECTED_AGENTS" && deploy_ok=1
    else
        msg "    ⚠️  未显式指定 --agents，构建不会因缺少埋点而失败 (建议加 --agents <ids>)" \
            "    ⚠️  No explicit --agents; the build will not fail on missing instrumentation (consider --agents <ids>)"
        loongsuite-pilot deploy && deploy_ok=1
    fi

    if [ "$deploy_ok" -ne 1 ]; then
        msg "❌ Hook / 插件部署失败" "❌ Hook/plugin deployment failed"
        msg "    请确认目标 Agent 已在同一构建层中安装完成" \
            "    Make sure the target agent is already installed in the same build layer"
        return 1
    fi
    echo ""

    container_write_agents || return 1
    container_clean_build_residue
}

# >>> pilot-stop-for-deploy >>>
# Overlay `install` used to SIGTERM only the collector pid file. The updater
# stayed up, and gcOldVersions() deletes any versions/<dir> that is not
# current/previous -- including the directory this deploy just copied, before
# current is published. installer-opensource.sh writes current after
# node_modules + postinstall, so that window is minutes. `loongsuite-pilot stop`
# unloads LaunchAgent / disables systemd (autostart_remove) so neither process
# comes back mid-deploy. That is the Unix counterpart of Disable-ScheduledTask.
#
# stop deletes the unit files. restore_pilot_after_deploy (EXIT trap) is the
# counterpart of Enable-ScheduledTask in finally: it re-registers autostart
# via start. Container installs must not start a daemon in the build layer.
#
# Fresh install has no CLI yet. Fall back to both pid files so a leftover
# collector or updater still goes down.
# All CLI after stop must go through run_pilot_cli so --data-dir matches.
PILOT_HELD_FOR_DEPLOY=0

resolve_pilot_cli() {
    if command -v loongsuite-pilot &>/dev/null; then
        command -v loongsuite-pilot
    elif [ -f "$HOME/.local/bin/loongsuite-pilot" ]; then
        printf '%s\n' "$HOME/.local/bin/loongsuite-pilot"
    fi
}

run_pilot_cli() {
    local cli
    cli="$(resolve_pilot_cli)"
    [ -n "$cli" ] || return 1
    # deploy_package writes versions/current under $HOME/.loongsuite-pilot
    # (the CLI cache default). Do not point CACHE_DIR at DATA_DIR.
    LOONGSUITE_PILOT_DATA_DIR="$DATA_DIR" \
        "$cli" "$@"
}

stop_one_pilot_pid_file() {
    local pid_file="$1"
    [ -f "$pid_file" ] || return 0
    local old_pid
    old_pid=$(cat "$pid_file")
    if kill -0 "$old_pid" 2>/dev/null; then
        kill "$old_pid" 2>/dev/null || true
        local count=0
        while kill -0 "$old_pid" 2>/dev/null && [ $count -lt 10 ]; do
            sleep 1
            count=$((count + 1))
        done
        if kill -0 "$old_pid" 2>/dev/null; then
            kill -9 "$old_pid" 2>/dev/null || true
        fi
        rm -f "$pid_file"
    else
        rm -f "$pid_file"
    fi
}

stop_pilot_for_deploy() {
    PILOT_HELD_FOR_DEPLOY=0
    local cli
    cli="$(resolve_pilot_cli)"

    if [ -z "$cli" ] && [ ! -f "$DATA_DIR/loongsuite-pilot.pid" ] && [ ! -f "$DATA_DIR/loongsuite-pilot-updater.pid" ]; then
        return 0
    fi

    msg "==> 停止服务..." "==> Stopping service..."
    if [ -n "$cli" ]; then
        PILOT_HELD_FOR_DEPLOY=1
        if ! run_pilot_cli stop; then
            msg "    ⚠️  无法停止服务，覆盖安装期间 updater 可能仍会 GC" \
                "    ⚠️  Could not stop the service; updater may still GC during this overlay"
        fi
    fi
    # Leftovers: no CLI on PATH, or an updater the CLI did not track.
    stop_one_pilot_pid_file "$DATA_DIR/loongsuite-pilot.pid"
    stop_one_pilot_pid_file "$DATA_DIR/loongsuite-pilot-updater.pid"
    echo ""
}

restore_pilot_after_deploy() {
    [ "${PILOT_HELD_FOR_DEPLOY:-0}" -eq 1 ] || return 0
    [ "${INSTALL_MODE:-host}" = "container" ] && return 0
    PILOT_HELD_FOR_DEPLOY=0
    if ! run_pilot_cli start; then
        msg "    ⚠️  无法恢复自启，请手动运行: loongsuite-pilot start" \
            "    ⚠️  Could not restore autostart, run manually: loongsuite-pilot start"
    fi
}
# <<< pilot-stop-for-deploy <<<

# Full install writes config.sls as a single object. Refuse before deploy when
# this run declared --sls-* and the existing file cannot be rewritten that way.
# A reporting-only AgentShell shortcut still merges arrays; a reinstall without
# --sls-* leaves the existing block untouched.
validate_existing_sls_for_full_install() {
    [ "$SLS_REQUESTED" -eq 1 ] || return 0
    local config_file="$DATA_DIR/config.json"
    [ -f "$config_file" ] || return 0
    local reason
    reason="$("$NODE_BIN" -e '
const fs = require("fs");
const path = process.argv[1];
let raw;
try {
  raw = fs.readFileSync(path, "utf8").replace(/^\uFEFF/, "");
} catch {
  console.log("unreadable");
  process.exit(1);
}
let config;
try {
  config = JSON.parse(raw);
} catch {
  console.log("invalid-json");
  process.exit(1);
}
if (config === null || typeof config !== "object" || Array.isArray(config)) {
  console.log("root-not-object");
  process.exit(1);
}
if (config.sls === undefined) process.exit(0);
if (Array.isArray(config.sls)) {
  console.log("sls-array");
  process.exit(1);
}
if (config.sls === null || typeof config.sls !== "object") {
  console.log("sls-shape");
  process.exit(1);
}
' "$config_file")" || {
        case "$reason" in
            unreadable)
                msg "❌ 无法读取 config.json，拒绝改写 SLS" \
                    "❌ cannot read config.json; refusing to rewrite SLS" ;;
            invalid-json)
                msg "❌ config.json 不是合法 JSON，拒绝改写 SLS" \
                    "❌ config.json is not valid JSON; refusing to rewrite SLS" ;;
            root-not-object)
                msg "❌ config.json 必须是 JSON 对象，拒绝改写 SLS" \
                    "❌ config.json must be a JSON object; refusing to rewrite SLS" ;;
            sls-array)
                msg "❌ 现有 config.sls 是数组，完整安装无法改写" \
                    "❌ existing config.sls is an array; full install cannot rewrite it" ;;
            sls-shape)
                msg "❌ 现有 config.sls 形状不受支持，拒绝改写 SLS" \
                    "❌ existing config.sls has an unsupported shape; refusing to rewrite SLS" ;;
            *)
                msg "❌ 现有 SLS 配置无法被完整安装改写" \
                    "❌ existing config.sls cannot be rewritten by a full install" ;;
        esac
        return 1
    }
}

# ============================================================
# CMD: install
# ============================================================
cmd_install() {
    msg "==> 开始安装 $PACKAGE_NAME ..." \
        "==> Installing $PACKAGE_NAME ..."
    echo ""

    # Reporting-only rewrites SLS/CMS and returns. --agents / --all-agents /
    # --multimodal-mode need write_config, so they must take the full install.
    # --hook-tamper-protection is applied by that same reporting merge.
    if [ "$FORCE_REINSTALL" -eq 0 ] && { [ "$SLS_REQUESTED" -eq 1 ] || [ "$CMS_REQUESTED" -eq 1 ]; }; then
        if [ "$MULTIMODAL_MODE_SET" -eq 0 ] && [ "$ALL_AGENTS" -eq 0 ] && [ "$AGENTS_EXPLICIT" -eq 0 ]; then
            local detect_result=0
            if detect_existing_pilot; then
                if is_agentshell_current; then
                    reconfigure_existing_reporting
                    return $?
                fi
            else
                detect_result=$?
            fi
            if [ "$detect_result" -eq 2 ]; then
                return 1
            fi
        fi
    fi

    validate_install_user
    check_deps
    validate_existing_sls_for_full_install

    # Migrate legacy layout if needed
    migrate_legacy_layout

    # Check if already installed
    local cur_ver; cur_ver=$(get_installed_version)
    if [ -n "$cur_ver" ]; then
        msg "⚠️  检测到已安装版本 v${cur_ver}，将执行重新安装" \
            "⚠️  Existing installation v${cur_ver} detected, re-installing"
        echo ""
    fi

    # Stop collector AND updater, and unload launchd / disable systemd so GC
    # cannot delete the in-flight versions dir. See stop_pilot_for_deploy.
    # Arm restore before stop: autostart_remove is not reversible if we die
    # between stop and trap.
    trap 'restore_pilot_after_deploy; rm -rf "${TMP_DIR:-}"' EXIT
    stop_pilot_for_deploy
    download_and_extract
    probe_agents
    select_agents
    prompt_user_id
    confirm_config_overwrite
    # set -e would end the install here anyway; saying why beats an exit code on its own.
    if ! deploy_package "$INSTALL_SRC"; then
        echo ""
        msg "❌ 安装中止：hook 脚本部署失败，请检查上方输出后重试" \
            "❌ Install aborted: hook script deployment failed; check the output above and retry"
        exit 1
    fi
    write_config
    install_loongsuite_pilot_command

    if [ "$INSTALL_MODE" = "container" ]; then
        container_finalize_install || return $?
        print_summary "install"
        return 0
    fi

    msg "==> 启动服务..." "==> Starting service..."
    if run_pilot_cli start; then
        sleep 2
        local _status_out
        _status_out="$(run_pilot_cli status 2>/dev/null || true)"
        if echo "$_status_out" | grep -q "is running"; then
            PILOT_HELD_FOR_DEPLOY=0
            msg "    ✅ 服务已启动" "    ✅ Service started"
        else
            msg "    ⚠️  服务可能尚未就绪，请检查: loongsuite-pilot status" \
                "    ⚠️  Service may not be ready. Check: loongsuite-pilot status"
        fi
    else
        msg "    ⚠️  服务启动失败，请手动运行: loongsuite-pilot start" \
            "    ⚠️  Service failed to start, run manually: loongsuite-pilot start"
    fi
    echo ""

    print_summary "install"
}

# ============================================================
# CMD: upgrade
# ============================================================
cmd_upgrade() {
    msg "==> 开始升级 $PACKAGE_NAME ..." \
        "==> Upgrading $PACKAGE_NAME ..."
    echo ""

    validate_install_user

    # Migrate legacy layout if needed
    migrate_legacy_layout

    # Must have an existing installation
    local old_ver; old_ver=$(get_installed_version)
    if [ -z "$old_ver" ]; then
        msg "❌ 未检测到已安装的 loongsuite-pilot，请先执行 install" \
            "❌ No existing installation found. Please run install first."
        exit 1
    fi

    msg "   当前版本: ${old_ver:-unknown}" "   Current version: ${old_ver:-unknown}"
    echo ""

    check_deps

    trap 'restore_pilot_after_deploy; rm -rf "${TMP_DIR:-}"' EXIT
    download_and_extract

    local new_ver; new_ver=$(get_version_from_dir "$INSTALL_SRC")
    local new_commit; new_commit=$(get_commit_from_dir "$INSTALL_SRC")
    local old_commit; old_commit=$(get_installed_commit)

    if [ -n "$new_ver" ] && [ "$new_ver" = "$old_ver" ] && [ "$new_commit" = "$old_commit" ]; then
        msg "✅ 已是最新版本 v${new_ver} (${new_commit})，无需升级" \
            "✅ Already at latest version v${new_ver} (${new_commit}), nothing to do"
        exit 0
    fi

    msg "   新版本: ${new_ver:-unknown} (${new_commit:-unknown})" \
        "   New version: ${new_ver:-unknown} (${new_commit:-unknown})"
    echo ""

    stop_pilot_for_deploy

    # Deploy new version to versions/<ver>_<commit>/
    # Old version stays untouched; deploy_package writes current/previous pointers
    if ! deploy_package "$INSTALL_SRC"; then
        echo ""
        msg "⚠️  部署失败，正在回滚到旧版本..." \
            "⚠️  Deployment failed, rolling back to old version..."
        local _rollback_ok=1
        run_pilot_cli rollback 2>/dev/null || _rollback_ok=0
        if [ "$_rollback_ok" -eq 1 ]; then
            if run_pilot_cli start; then
                PILOT_HELD_FOR_DEPLOY=0
            else
                _rollback_ok=0
            fi
        fi
        if [ "$_rollback_ok" -eq 1 ]; then
            msg "❌ 升级失败（部署/依赖安装出错），已回滚到 v${old_ver:-unknown} 并重启服务" \
                "❌ Upgrade failed (deploy/dependency error), rolled back to v${old_ver:-unknown} and restarted"
        else
            msg "❌ 升级失败且自动回滚未成功，请手动恢复:" \
                "❌ Upgrade failed and auto-rollback did not succeed. Manual recovery:"
            msg "   loongsuite-pilot rollback && loongsuite-pilot start" \
                "   loongsuite-pilot rollback && loongsuite-pilot start"
        fi
        exit 1
    fi
    install_loongsuite_pilot_command

    # Start the new version
    msg "==> 启动新版本..." "==> Starting new version..."
    if run_pilot_cli start; then
        sleep 2
        local _status_out
        _status_out="$(run_pilot_cli status 2>/dev/null || true)"
        if echo "$_status_out" | grep -q "is running"; then
            PILOT_HELD_FOR_DEPLOY=0
            msg "    ✅ 新版本启动成功" "    ✅ New version started successfully"
            echo ""

            # GC: remove old versions beyond current + previous
            gc_old_versions

            print_summary "upgrade"
            return 0
        fi
    fi

    # --- Rollback via version pointer ---
    echo ""
    msg "⚠️  新版本启动失败，正在回滚..." \
        "⚠️  New version failed to start, rolling back..."

    run_pilot_cli stop 2>/dev/null || true
    local _rb_ok=1
    run_pilot_cli rollback 2>/dev/null || _rb_ok=0

    if [ "$_rb_ok" -eq 1 ]; then
        if run_pilot_cli start; then
            PILOT_HELD_FOR_DEPLOY=0
            msg "❌ 升级失败，已回滚到 v${old_ver:-unknown}" \
                "❌ Upgrade failed, rolled back to v${old_ver:-unknown}"
            msg "   请检查日志: loongsuite-pilot log" "   Check logs: loongsuite-pilot log"
        else
            msg "❌ 升级失败，已回滚但未能重启服务" \
                "❌ Upgrade failed, rolled back but could not restart"
            msg "   请手动运行: loongsuite-pilot start" \
                "   Run manually: loongsuite-pilot start"
        fi
    else
        msg "❌ 升级失败且回滚未成功，请手动恢复:" \
            "❌ Upgrade failed and rollback did not succeed. Manual recovery:"
        msg "   loongsuite-pilot rollback && loongsuite-pilot start" \
            "   loongsuite-pilot rollback && loongsuite-pilot start"
    fi
    exit 1
}

# ============================================================
# GC: remove old version directories beyond current + previous
# ============================================================
gc_old_versions() {
    local cache_dir="$HOME/.loongsuite-pilot"
    local versions_dir="$cache_dir/versions"
    local current_file="$cache_dir/current"
    local previous_file="$cache_dir/previous"

    [ -d "$versions_dir" ] || return 0

    local keep_current="" keep_previous=""
    if [ -f "$current_file" ]; then
        keep_current=$(cat "$current_file" 2>/dev/null | tr -d '[:space:]')
    fi
    if [ -f "$previous_file" ]; then
        keep_previous=$(cat "$previous_file" 2>/dev/null | tr -d '[:space:]')
    fi

    for d in "$versions_dir"/*/; do
        [ -d "$d" ] || continue
        local name
        name=$(basename "$d")
        if [ "$name" = "$keep_current" ] || [ "$name" = "$keep_previous" ]; then
            continue
        fi
        rm -rf "$d"
    done
}

# ============================================================
# Remove hook entries injected into tool config files
# ============================================================
remove_hook_configs() {
    local HOOK_MARKER=".loongsuite-pilot"
    local configs=(
        "$HOME/.cursor/hooks.json"
        "$HOME/.trae-cn/hooks.json"
        "$HOME/.qoder/settings.json"
        "$HOME/.qoderwork/settings.json"
        "$HOME/.claude/settings.json"
        "$HOME/.codex/hooks.json"
    )

    local _node_bin=""
    _node_bin=$(resolve_node 2>/dev/null) || true

    for cfg in "${configs[@]}"; do
        [ -f "$cfg" ] || continue
        local short="${cfg/#$HOME/\~}"

        local ok=0
        if [ -n "$_node_bin" ]; then
            "$_node_bin" -e "
const fs = require('fs');
const cfg = process.argv[1];
const marker = process.argv[2];
try {
  const data = JSON.parse(fs.readFileSync(cfg, 'utf-8'));
  const hooks = data.hooks;
  if (!hooks || typeof hooks !== 'object') process.exit(0);
  let changed = false;
  const isTrae = cfg.split(String.fromCharCode(92)).join('/').endsWith('/.trae-cn/hooks.json');
  const isPilotTrae = command => typeof command === 'string' &&
    /[/]hooks[/]trae-cn-loongsuite-pilot-hook[.](sh|ps1)(?=[\x22'\s]|$)/i.test(command.split(String.fromCharCode(92)).join('/'));
  const isCodex = cfg.endsWith('/.codex/hooks.json');
  const isPilotCodex = c => typeof c === 'string' && c.includes(marker)
    && new RegExp('(^|[ /])codex-loongsuite-pilot-hook[.](sh|mjs|ps1)([^A-Za-z0-9_.-]|$)', 'i').test(c);
  for (const [event, entries] of Object.entries(hooks)) {
    if (!Array.isArray(entries)) continue;
    if (isTrae) {
      const remaining = entries.flatMap(entry => {
        if (isPilotTrae(entry?.command)) { changed = true; return []; }
        if (!Array.isArray(entry?.hooks)) return [entry];
        const nested = entry.hooks.filter(hook => !isPilotTrae(hook?.command));
        if (nested.length === entry.hooks.length) return [entry];
        changed = true;
        return nested.length ? [{ ...entry, hooks: nested }] : [];
      });
      if (remaining.length) hooks[event] = remaining;
      else if (entries.length) delete hooks[event];
      continue;
    }
    const candidates = isCodex ? entries.flatMap(e => {
      if (!e || typeof e !== 'object') return [e];
      if (isPilotCodex(e.command)) { changed = true; return []; }
      if (!Array.isArray(e.hooks)) return [e];
      const nested = e.hooks.filter(h => !isPilotCodex(h && h.command));
      if (nested.length === e.hooks.length) return [e];
      changed = true;
      return nested.length ? [{ ...e, hooks: nested }] : [];
    }) : entries;
    const filtered = isCodex ? candidates : candidates.filter(e => {
      const cmd = e.command || '';
      const nested = Array.isArray(e.hooks) ? e.hooks : [];
      const hasMarker = cmd.includes(marker) || nested.some(h => (h.command || '').includes(marker));
      if (hasMarker) changed = true;
      return !hasMarker;
    });
    if (filtered.length === 0) { delete hooks[event]; changed = true; }
    else hooks[event] = filtered;
  }
  if (changed) {
    fs.writeFileSync(cfg, JSON.stringify(data, null, 2) + '\n', 'utf-8');
    process.stdout.write('cleaned');
  } else {
    process.stdout.write('skip');
  }
} catch(e) { process.stderr.write(e.message); process.exit(1); }
" "$cfg" "$HOOK_MARKER" && ok=1
        fi

        if [ "$ok" -eq 1 ]; then
            msg "    ✅ 已清理: $short" "    ✅ Cleaned: $short"
        else
            msg "    ⚠️  跳过: $short (需手动清理)" "    ⚠️  Skipped: $short (manual cleanup needed)"
        fi
    done
}

# ============================================================
# Remove the Pilot-owned DeepSeek Harness YAML patch before plugin assets.
# The same helper is invoked by the PowerShell installer.
# ============================================================
remove_dsh_yaml_patch() {
    local plugin_dir="$DATA_DIR/plugins/dsh"
    local cleanup_script="$plugin_dir/cleanup.mjs"
    local node_bin=""
    for pin_file in "$DATA_DIR/node-bin" "$HOME/.loongsuite-pilot/node-bin"; do
        if [ -f "$pin_file" ]; then
            local pinned
            pinned=$(tr -d '\r\n' < "$pin_file")
            if _node_is_suitable "$pinned"; then node_bin="$pinned"; break; fi
        fi
    done
    if [ -z "$node_bin" ]; then node_bin=$(resolve_node) || node_bin=""; fi
    if [ -z "$node_bin" ]; then
        msg "    ❌ 无可用 Node.js，无法安全清理 DSH YAML patch" \
            "    ❌ No usable Node.js; cannot safely remove the DSH YAML patch"
        return 1
    fi

    # DSH_HOME may differ between install and uninstall. Prefer the exact path
    # recorded when Pilot deployed the block, then fall back for legacy state.
    local dsh_home="${DSH_HOME:-$HOME/.dsh}"
    local patch_path="$dsh_home/cordis.patch.yml"
    local state_file="$DATA_DIR/deployed-agents.json"
    if [ -f "$state_file" ]; then
        local persisted_patch
        persisted_patch=$("$node_bin" -e '
const fs = require("fs");
const path = require("path");
try {
  const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
  const value = state?.dsh?.dshPatchPath;
  if (typeof value === "string" && path.isAbsolute(value)) process.stdout.write(value);
} catch {}
' "$state_file")
        if [ -n "$persisted_patch" ]; then patch_path="$persisted_patch"; fi
    fi

    if [ ! -f "$cleanup_script" ]; then
        if [ -f "$patch_path" ] && grep -Fq '# BEGIN PILOT-OBSERVABILITY-MANAGED' "$patch_path"; then
            msg "    ❌ DSH 清理脚本缺失，拒绝删除仍被 YAML 引用的插件资产" \
                "    ❌ DSH cleanup helper is missing; refusing to remove plugin assets still referenced by YAML"
            return 1
        fi
        return 0
    fi

    if ! "$node_bin" "$cleanup_script" --patch "$patch_path" --plugin-dir "$plugin_dir"; then
        msg "    ❌ DSH YAML patch 清理失败；卸载已停止，Pilot 资产保持不变" \
            "    ❌ DSH YAML patch cleanup failed; uninstall stopped and Pilot assets were preserved"
        return 1
    fi
    msg "    ✅ 已清理 DSH YAML patch" "    ✅ Cleaned DSH YAML patch"
}

# ============================================================
# Remove OpenClaw's nested plugin entry and load path.
# ============================================================
# OpenClaw stores injected plugins under plugins.load.paths plus
# plugins.entries. The generic hook cleanup does not cover this shape, and
# leaving either value behind makes OpenClaw load a path that uninstall is
# about to remove. Only Pilot-owned values are removed; unrelated plugins and
# their configuration remain semantically unchanged.
resolve_installed_package_dir() {
    local cache_dir="$HOME/.loongsuite-pilot"
    local current_file="$cache_dir/current"
    local current_name=""
    local candidate=""

    if [ -r "$current_file" ]; then
        current_name=$(tr -d '\r\n' < "$current_file")
        case "$current_name" in
            ""|"."|".."|*/*|*\\*) ;;
            *)
                candidate="$cache_dir/versions/$current_name"
                if [ -d "$candidate" ]; then
                    printf '%s\n' "$candidate"
                    return 0
                fi
                ;;
        esac
    fi

    if [ -d "$cache_dir/package" ]; then
        printf '%s\n' "$cache_dir/package"
        return 0
    fi
    return 1
}

remove_openclaw_plugin() {
    local state_dir="${OPENCLAW_STATE_DIR:-$HOME/.openclaw}"
    local managed_path="$DATA_DIR/plugins/openclaw"
    local default_managed_path="$HOME/.loongsuite-pilot/plugins/openclaw"
    local configs=()
    [ -n "${OPENCLAW_CONFIG_PATH:-}" ] && configs+=("$OPENCLAW_CONFIG_PATH")
    configs+=(
        "$state_dir/openclaw.json"
        "$state_dir/config.json"
        "$HOME/.openclaw/openclaw.json"
        "$HOME/.openclaw/config.json"
    )

    local _node_bin=""
    _node_bin="$(resolve_reconfigure_node 2>/dev/null)" || true
    local package_dir=""
    package_dir="$(resolve_installed_package_dir 2>/dev/null)" || true
    local cleanup_script="$package_dir/scripts/cleanup-openclaw-config.cjs"
    local json5_module="$package_dir/node_modules/json5"

    local seen="|"
    local all_clean=1
    for cfg in "${configs[@]}"; do
        [ -f "$cfg" ] || continue
        case "$seen" in *"|$cfg|"*) continue ;; esac
        seen="${seen}${cfg}|"
        local short="${cfg/#$HOME/\~}"

        if [ -z "$_node_bin" ]; then
            msg "    ⚠️  跳过: $short (无 node,需手动清理)" "    ⚠️  Skipped: $short (node unavailable, manual cleanup needed)"
            all_clean=0
            continue
        fi
        if [ ! -f "$cleanup_script" ] || [ ! -d "$json5_module" ]; then
            msg "    ⚠️  跳过: $short (清理组件不可用,需手动清理)" "    ⚠️  Skipped: $short (cleanup component unavailable, manual cleanup needed)"
            all_clean=0
            continue
        fi

        local result
        result=$(PILOT_OC_CONFIG="$cfg" \
            PILOT_OC_MANAGED="$managed_path" \
            PILOT_OC_DEFAULT_MANAGED="$default_managed_path" \
            PILOT_OC_JSON5="$json5_module" \
            "$_node_bin" < "$cleanup_script" 2>/dev/null) || {
            all_clean=0
            result="error"
        }

        case "$result" in
            cleaned)
                msg "    ✅ 已清理: $short" "    ✅ Cleaned: $short" ;;
            nochange)
                : ;;
            *)
                all_clean=0
                msg "    ⚠️  跳过: $short (需手动清理)" "    ⚠️  Skipped: $short (manual cleanup needed)" ;;
        esac
    done

    [ "$all_clean" -eq 1 ]
}

# ============================================================
# CMD: uninstall
# ============================================================
cmd_uninstall() {
    msg "🗑️  开始卸载 $PACKAGE_NAME ..." \
        "🗑️  Uninstalling $PACKAGE_NAME ..."
    echo ""

    # Stop service (also removes autostart)
    msg "==> 停止服务..." "==> Stopping service..."
    if command -v loongsuite-pilot &>/dev/null; then
        loongsuite-pilot stop 2>/dev/null || true
    elif [ -f "$HOME/.local/bin/loongsuite-pilot" ]; then
        "$HOME/.local/bin/loongsuite-pilot" stop 2>/dev/null || true
    else
        local pid_file="$DATA_DIR/loongsuite-pilot.pid"
        if [ -f "$pid_file" ]; then
            local pid; pid=$(cat "$pid_file")
            kill "$pid" 2>/dev/null || true
            sleep 2
            kill -9 "$pid" 2>/dev/null || true
            rm -f "$pid_file"
        fi
        # Manual autostart cleanup when loongsuite-pilot is unavailable
        case "$(uname -s)" in
            Darwin)
                local _plist="$HOME/Library/LaunchAgents/com.loongsuite-pilot.plist"
                local _uplist="$HOME/Library/LaunchAgents/com.loongsuite-pilot.updater.plist"
                for f in "$_uplist" "$_plist"; do
                    if [ -f "$f" ]; then
                        launchctl unload -w "$f" 2>/dev/null || true
                        rm -f "$f"
                    fi
                done
                ;;
            Linux)
                local _run_user
                _run_user="$(whoami)"

                # Clean up user-level systemd units
                local _user_unit_dir="$HOME/.config/systemd/user"
                if [ -f "$_user_unit_dir/loongsuite-pilot.service" ]; then
                    systemctl --user disable --now loongsuite-pilot.service &>/dev/null || true
                    systemctl --user disable --now loongsuite-pilot-updater.service &>/dev/null || true
                    rm -f "$_user_unit_dir/loongsuite-pilot.service"
                    rm -f "$_user_unit_dir/loongsuite-pilot-updater.service"
                    systemctl --user daemon-reload &>/dev/null || true
                fi

                # Clean up system-level systemd units
                local _sys_unit="/etc/systemd/system/loongsuite-pilot-${_run_user}.service"
                local _sys_uunit="/etc/systemd/system/loongsuite-pilot-updater-${_run_user}.service"
                for f in "$_sys_uunit" "$_sys_unit"; do
                    if [ -f "$f" ]; then
                        sudo systemctl disable --now "$(basename "$f")" &>/dev/null || true
                        sudo rm -f "$f"
                    fi
                done
                sudo systemctl daemon-reload &>/dev/null || true

                # Clean up init.d scripts
                local _initd="/etc/init.d/loongsuite-pilot-${_run_user}"
                local _initd_u="/etc/init.d/loongsuite-pilot-updater-${_run_user}"
                for f in "$_initd_u" "$_initd"; do
                    if [ -f "$f" ]; then
                        sudo "$f" stop &>/dev/null || true
                        local _name; _name=$(basename "$f")
                        if command -v chkconfig &>/dev/null; then sudo chkconfig --del "$_name" &>/dev/null || true
                        elif command -v update-rc.d &>/dev/null; then sudo update-rc.d "$_name" remove &>/dev/null || true; fi
                        sudo rm -f "$f"
                    fi
                done
                ;;
        esac
    fi
    msg "    ✅ 服务已停止" "    ✅ Service stopped"
    echo ""

    # Clean hooks/plugins BEFORE removing install dir (node-bin pin lives there)
    msg "==> 清理 DSH YAML patch..." "==> Cleaning up DSH YAML patch..."
    local dsh_cleanup_ok=1
    remove_dsh_yaml_patch || dsh_cleanup_ok=0
    echo ""

    msg "==> 清理 OpenClaw 插件配置..." "==> Cleaning up OpenClaw plugin config..."
    local openclaw_cleanup_ok=1
    remove_openclaw_plugin || openclaw_cleanup_ok=0
    echo ""

    msg "==> 清理 hook 配置..." "==> Cleaning up hook configs..."
    remove_hook_configs
    echo ""

    msg "==> 清理 Claude 旧插件..." "==> Cleaning up legacy Claude plugin..."
    remove_otel_plugin
    echo ""

    if [ "$dsh_cleanup_ok" -ne 1 ]; then
        msg "❌ DSH YAML patch 清理失败，已保留安装文件以避免悬空插件引用" \
            "❌ DSH YAML patch cleanup failed; installation files were preserved to avoid a dangling plugin reference"
    fi
    if [ "$openclaw_cleanup_ok" -ne 1 ]; then
        msg "❌ OpenClaw 配置清理失败，已保留安装文件以避免悬空插件引用" \
            "❌ OpenClaw config cleanup failed; installation files were preserved to avoid a dangling plugin reference"
    fi
    if [ "$dsh_cleanup_ok" -ne 1 ] || [ "$openclaw_cleanup_ok" -ne 1 ]; then
        return 1
    fi

    # Remove package directory
    msg "==> 删除安装目录..." "==> Removing installation..."
    rm -rf "$HOME/.loongsuite-pilot"
    msg "    ✅ 已删除 $HOME/.loongsuite-pilot" \
        "    ✅ Removed $HOME/.loongsuite-pilot"

    # Remove loongsuite-pilot command
    msg "==> 删除 loongsuite-pilot 命令..." "==> Removing loongsuite-pilot command..."
    rm -f "$HOME/.local/bin/loongsuite-pilot"
    rm -f /usr/local/bin/loongsuite-pilot 2>/dev/null || true
    # The container-mode entrypoint wraps the command just removed. Unlike config and
    # logs it is not data worth preserving without --purge — all it can do now is fail.
    rm -f "$DATA_DIR/entrypoint.sh"
    msg "    ✅ loongsuite-pilot 命令已删除" "    ✅ loongsuite-pilot command removed"
    echo ""

    # Data directory
    if [ "$PURGE" -eq 1 ]; then
        msg "==> 删除数据目录 (--purge)..." "==> Removing data directory (--purge)..."
        rm -rf "$DATA_DIR"
        msg "    ✅ 已删除 $DATA_DIR" "    ✅ Removed $DATA_DIR"
    else
        msg "📁 数据目录已保留: $DATA_DIR" \
            "📁 Data directory preserved: $DATA_DIR"
        msg "   (包含配置和日志，如需彻底删除请加 --purge)" \
            "   (contains config and logs, add --purge to remove)"
    fi
    echo ""

    echo "============================================================"
    msg "✅ 卸载完成！" "✅ Uninstallation complete!"
    echo "============================================================"
}

# ============================================================
# Main dispatcher
# ============================================================
case "$COMMAND" in
    install)   cmd_install ;;
    upgrade)   cmd_upgrade ;;
    uninstall) cmd_uninstall ;;
    *)
        echo "Usage: $0 {install|upgrade|uninstall} [options]"
        exit 1 ;;
esac
