#!/usr/bin/env bash # Advisor Assistant 1-click installer for macOS (Apple Silicon & Intel) and Linux. # Sets up an isolated Python 3.11+ virtual environment via uv (or python3), runs # fail-closed Zero-PII, Ed25519 lease, Fly.io Toronto API health, headless browser # PDF, and ./advisor launcher checks, and writes install_receipt.json. set -eu if (set -o pipefail) 2>/dev/null; then set -o pipefail fi # Resolve script source safely even when piped (cat install.sh | bash or sh). if [ -n "${BASH_VERSION:-}" ]; then eval 'SCRIPT_SOURCE="${BASH_SOURCE[0]:-$0}"' else SCRIPT_SOURCE="$0" fi if [ -n "${SCRIPT_SOURCE}" ] && { [ -f "${SCRIPT_SOURCE}" ] || [ -L "${SCRIPT_SOURCE}" ]; }; then while [ -L "${SCRIPT_SOURCE}" ]; do _LINK_DIR="$(cd -P "$(dirname "${SCRIPT_SOURCE}")" && pwd)" SCRIPT_SOURCE="$(readlink "${SCRIPT_SOURCE}")" case "${SCRIPT_SOURCE}" in /*) ;; *) SCRIPT_SOURCE="${_LINK_DIR}/${SCRIPT_SOURCE}" ;; esac done SCRIPT_DIR="$(cd -P "$(dirname "${SCRIPT_SOURCE}")" && pwd)" else SCRIPT_DIR="$(pwd)" fi # Resolve APP_ROOT: check script dir first, then parent dir when run as Site/install.sh. APP_ROOT="${SCRIPT_DIR}" if [ ! -f "${APP_ROOT}/Backend/Scripts/cli/advisor_cli.py" ] && [ ! -d "${APP_ROOT}/Backend/Scripts" ]; then _PARENT_DIR="$(cd -P "${SCRIPT_DIR}/.." && pwd)" if [ -f "${_PARENT_DIR}/Backend/Scripts/cli/advisor_cli.py" ]; then APP_ROOT="${_PARENT_DIR}" fi fi # Pre-flight check BEFORE creating .venv, ./advisor, or install_receipt.json. if [ ! -d "${APP_ROOT}/Backend/Scripts" ]; then echo "" >&2 echo "Advisor Assistant setup cannot start from this folder:" >&2 echo " ${APP_ROOT}" >&2 echo "" >&2 echo "Expected Advisor Assistant files (Backend/Scripts) were not found here." >&2 echo "Download/unzip the Advisor Assistant folder first, then run ./install.sh inside it." >&2 echo "Nothing was created or modified." >&2 exit 1 fi API_URL="${ADVISOR_API_URL:-https://advisor-assistant-api.fly.dev}" VENV_DIR="${APP_ROOT}/.venv" export PYTHONUTF8=1 export PYTHONIOENCODING=utf-8 echo "== Advisor Assistant Installer (macOS / Linux) ==" echo "Root: ${APP_ROOT}" echo "API: ${API_URL}" resolve_python() { for cand in python3.14 python3.13 python3.12 python3.11 python3; do if command -v "$cand" >/dev/null 2>&1; then if "$cand" -c 'import sys; assert sys.version_info >= (3, 11)' >/dev/null 2>&1; then command -v "$cand" return 0 fi fi done return 1 } describe_found_python() { for cand in python3 python; do if command -v "$cand" >/dev/null 2>&1; then _p="$(command -v "$cand")" _v="$("$cand" -c 'import sys; print(".".join(map(str, sys.version_info[:3])))' 2>/dev/null || true)" if [ -n "${_v}" ]; then printf '%s (Python %s)' "${_p}" "${_v}" else _v="$("$cand" --version 2>&1 | head -n 1 || true)" if [ -n "${_v}" ]; then printf '%s (%s)' "${_p}" "${_v}" else printf '%s (version unknown)' "${_p}" fi fi return 0 fi done return 1 } resolve_constraints_file() { _py="$1" _os_tag="$(uname -s 2>/dev/null | tr '[:upper:]' '[:lower:]')" _py_tag="$("${_py}" -c 'import sys; print(f"{sys.version_info[0]}{sys.version_info[1]}")' 2>/dev/null || true)" if [ -n "${_os_tag}" ] && [ -n "${_py_tag}" ]; then _cfile="${APP_ROOT}/ops/setup/constraints/${_os_tag}-py${_py_tag}.txt" if [ -f "${_cfile}" ]; then printf '%s' "${_cfile}" return 0 fi fi return 1 } write_fail_receipt() { _err_msg="$1" _py_exec="${VENV_PY:-${PY_BIN:-python3}}" if [ -x "${_py_exec}" ] || command -v "${_py_exec}" >/dev/null 2>&1; then APP_ROOT_ENV="${APP_ROOT}" API_URL_ENV="${API_URL}" ERR_MSG_ENV="${_err_msg}" "${_py_exec}" - <<'PY' >/dev/null 2>&1 || true import datetime as dt import json import os import platform from pathlib import Path root = Path(os.environ["APP_ROOT_ENV"]) receipt = { "product": "Advisor Assistant", "status": "FAIL", "installed_at_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "os": platform.system(), "arch": platform.machine(), "python": platform.python_version(), "utf8_mode": os.environ.get("PYTHONUTF8"), "api_url": os.environ["API_URL_ENV"].rstrip("/"), "gates": {}, "error": os.environ["ERR_MSG_ENV"], } (root / "install_receipt.json").write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") PY fi } PY_BIN="" VENV_PY="${VENV_DIR}/bin/python" # Day-1 set: the secrets lock (cryptography), the review sample letters (python-docx) and their PNG previews # (pypdfium2, Pillow), so the first setup step can make its samples without a technical helper. THIN_DEPS="cryptography python-docx pypdfium2 Pillow" THIN_DEPS_IMPORT='import cryptography, docx, pypdfium2, PIL' if command -v uv >/dev/null 2>&1; then UV_BIN="$(command -v uv)" echo "[1/5] Using uv: ${UV_BIN}" if [ ! -x "${VENV_PY}" ] || ! "${VENV_PY}" -c 'import sys; assert sys.version_info >= (3, 11)' >/dev/null 2>&1; then if ! "${UV_BIN}" venv --clear --python 3.12 "${VENV_DIR}"; then echo " Installing managed Python 3.12 via uv..." if ! "${UV_BIN}" python install 3.12 || ! "${UV_BIN}" venv --clear --python 3.12 "${VENV_DIR}"; then write_fail_receipt "Failed to create Python 3.12 virtual environment via uv." echo "ERROR: Failed to create a Python 3.12 virtual environment with uv. Check network/proxy and re-run ./install.sh." >&2 exit 1 fi fi fi echo "[2/5] Installing thin-client dependencies (${THIN_DEPS})..." if "${VENV_PY}" -c "${THIN_DEPS_IMPORT}" >/dev/null 2>&1; then echo " Dependencies already installed in .venv." else CONSTRAINTS_FILE="$(resolve_constraints_file "${VENV_PY}" || true)" if [ -n "${CONSTRAINTS_FILE}" ]; then # shellcheck disable=SC2086 # THIN_DEPS is a word list if ! "${UV_BIN}" pip install --python "${VENV_PY}" -c "${CONSTRAINTS_FILE}" ${THIN_DEPS}; then write_fail_receipt "Failed to install thin-client dependencies (${THIN_DEPS}) via uv." echo "ERROR: Failed to install dependencies (${THIN_DEPS}). Check network/proxy and re-run ./install.sh." >&2 exit 1 fi else # shellcheck disable=SC2086 # THIN_DEPS is a word list if ! "${UV_BIN}" pip install --python "${VENV_PY}" ${THIN_DEPS}; then write_fail_receipt "Failed to install thin-client dependencies (${THIN_DEPS}) via uv." echo "ERROR: Failed to install dependencies (${THIN_DEPS}). Check network/proxy and re-run ./install.sh." >&2 exit 1 fi fi fi else PY_BIN="$(resolve_python || true)" if [ -z "${PY_BIN}" ]; then FOUND_PY="$(describe_found_python || true)" echo "" >&2 echo "ERROR: Python 3.11+ or uv is required to install Advisor Assistant." >&2 if [ -n "${FOUND_PY}" ]; then echo "Found: ${FOUND_PY} (too old; macOS ships Python 3.9 by default)." >&2 else echo "Found: no python3 interpreter on PATH." >&2 fi echo "" >&2 echo "Install Python 3.12+ or uv, then re-run ./install.sh:" >&2 echo " - macOS (Homebrew): brew install python@3.12" >&2 echo " - macOS / direct: https://www.python.org/downloads/" >&2 echo " - Linux (Debian/Ubuntu): sudo apt-get install python3.12 python3.12-venv" >&2 echo " - Linux (Arch/Fedora): install python >= 3.11 with your package manager" >&2 echo " - Cross-platform (uv): curl -LsSf https://astral.sh/uv/install.sh | sh" >&2 exit 1 fi echo "[1/5] Using Python: ${PY_BIN}" if [ ! -x "${VENV_PY}" ] || ! "${VENV_PY}" -c 'import sys; assert sys.version_info >= (3, 11)' >/dev/null 2>&1; then if ! "${PY_BIN}" -m venv --clear "${VENV_DIR}"; then write_fail_receipt "Failed to create Python virtual environment with ${PY_BIN}." echo "ERROR: Failed to create virtual environment with ${PY_BIN}. On Debian/Ubuntu, install python3-venv." >&2 exit 1 fi fi echo "[2/5] Installing thin-client dependencies (${THIN_DEPS})..." if "${VENV_PY}" -c "${THIN_DEPS_IMPORT}" >/dev/null 2>&1; then echo " Dependencies already installed in .venv." else CONSTRAINTS_FILE="$(resolve_constraints_file "${VENV_PY}" || true)" if [ -n "${CONSTRAINTS_FILE}" ]; then # shellcheck disable=SC2086 # THIN_DEPS is a word list if ! "${VENV_PY}" -m pip install --quiet --disable-pip-version-check -c "${CONSTRAINTS_FILE}" ${THIN_DEPS}; then write_fail_receipt "Failed to install thin-client dependencies (${THIN_DEPS}) via pip." echo "ERROR: Failed to install dependencies (${THIN_DEPS}). Check network/proxy and re-run ./install.sh." >&2 exit 1 fi else # shellcheck disable=SC2086 # THIN_DEPS is a word list if ! "${VENV_PY}" -m pip install --quiet --disable-pip-version-check ${THIN_DEPS}; then write_fail_receipt "Failed to install thin-client dependencies (${THIN_DEPS}) via pip." echo "ERROR: Failed to install dependencies (${THIN_DEPS}). Check network/proxy and re-run ./install.sh." >&2 exit 1 fi fi fi fi echo "[3/5] Writing ./advisor UTF-8 smart CLI launcher..." cat > "${APP_ROOT}/advisor" <<'EOF' #!/usr/bin/env bash set -eu if (set -o pipefail) 2>/dev/null; then set -o pipefail fi # Resolve symlinks on $0 so symlinking ./advisor into PATH always finds the vault root. if [ -n "${BASH_VERSION:-}" ]; then eval 'TARGET="${BASH_SOURCE[0]:-$0}"' else TARGET="$0" fi while [ -L "${TARGET}" ]; do LINK_DIR="$(cd -P "$(dirname "${TARGET}")" && pwd)" TARGET="$(readlink "${TARGET}")" case "${TARGET}" in /*) ;; *) TARGET="${LINK_DIR}/${TARGET}" ;; esac done ROOT="$(cd -P "$(dirname "${TARGET}")" && pwd)" export PYTHONUTF8=1 export PYTHONIOENCODING=utf-8 export PYTHONPATH="${ROOT}${PYTHONPATH:+:${PYTHONPATH}}" export VAULT_ROOT="${VAULT_ROOT:-${ROOT}}" export ADVISOR_API_URL="${ADVISOR_API_URL:-https://advisor-assistant-api.fly.dev}" PY_BIN="${ROOT}/.venv/bin/python" if [ ! -x "${PY_BIN}" ]; then echo "ERROR: Advisor Assistant environment missing at ${PY_BIN}. Run ./install.sh first." >&2 exit 1 fi # Preserve Python passthrough for -c, -m, -V, --version, or an existing .py file path. if [ $# -ge 1 ]; then case "$1" in -c|-m|-V|--version) exec "${PY_BIN}" "$@" ;; *.py) if [ -f "$1" ]; then exec "${PY_BIN}" "$@" fi ;; esac fi exec "${PY_BIN}" -m Backend.Scripts.cli.advisor_cli "$@" EOF chmod +x "${APP_ROOT}/advisor" echo "[4/5] Running fail-closed local & Fly.io Toronto acceptance gates..." APP_ROOT_ENV="${APP_ROOT}" API_URL_ENV="${API_URL}" PYTHONPATH="${APP_ROOT}" "${VENV_PY}" - <<'PY' import datetime as dt import json import os import platform import shutil import subprocess import sys import tempfile import time import urllib.error import urllib.parse import urllib.request from pathlib import Path root = Path(os.environ["APP_ROOT_ENV"]) api_url = os.environ["API_URL_ENV"].rstrip("/") receipt = { "product": "Advisor Assistant", "status": "IN_PROGRESS", "installed_at_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "os": platform.system(), "arch": platform.machine(), "python": platform.python_version(), "utf8_mode": os.environ.get("PYTHONUTF8"), "api_url": api_url, "gates": {}, "error": None, } errors = [] partial_reasons = [] try: # Gate 1: PII scrubber, cross-platform file lock, and pii_gate import try: from Backend.Scripts.compliance import pii, pii_gate from Backend.Scripts.utilities import file_lock hits = pii.check("SIN 046-454-286", pii.EXPORT) if not any(h.cls == "sin" for h in hits): raise RuntimeError("SIN detection failed") with tempfile.TemporaryDirectory() as td: lock_file = Path(td) / "test.lock" with file_lock.exclusive_lock(lock_file): pass if not hasattr(pii_gate, "Gate"): raise RuntimeError("pii_gate import incomplete") receipt["gates"]["pii_and_lock"] = "PASS" except Exception as exc: msg = f"Gate 1 (PII guard and file lock) failed: {exc}" receipt["gates"]["pii_and_lock"] = {"status": "FAIL", "error": msg} errors.append(msg) # Gate 2: Ed25519 license lease sign/verify/tamper rejection try: from Backend.Scripts.licensing import license_lease as ll kp = ll.generate_keypair() priv, pub = (kp if isinstance(kp, tuple) else (kp["private_key_b64"], kp["public_key_b64"])) lease = ll.issue_lease( subscriber_id="sub_install_check", tier="pro", seats=1, private_key_b64=priv, valid_days=35, ) res = ll.verify_lease(lease, public_key_b64=pub) if not (res.get("valid") is True and res.get("status") == "active"): raise RuntimeError(f"Lease verify failed: {res}") bad = json.loads(json.dumps(lease)) bad["payload"]["tier"] = "air_gapped_regulator" bad_res = ll.verify_lease(bad, public_key_b64=pub) if bad_res.get("valid"): raise RuntimeError("Tampered lease unexpectedly passed") receipt["gates"]["ed25519_lease"] = "PASS" except Exception as exc: msg = f"Gate 2 (Ed25519 license check) failed: {exc}" receipt["gates"]["ed25519_lease"] = {"status": "FAIL", "error": msg} errors.append(msg) # Gate 3: Live Fly.io Toronto API health check (optional skip via ADVISOR_SKIP_NETWORK=1) if os.environ.get("ADVISOR_SKIP_NETWORK") == "1": receipt["gates"]["api_health"] = "SKIPPED" partial_reasons.append("api_health skipped (ADVISOR_SKIP_NETWORK=1)") else: t0 = time.monotonic() host = urllib.parse.urlparse(api_url).netloc or api_url req = urllib.request.Request( f"{api_url}/v1/health", headers={"User-Agent": "AdvisorAssistant-UnixInstaller/1.0"}, ) try: with urllib.request.urlopen(req, timeout=15) as resp: raw_body = resp.read().decode("utf-8") body = json.loads(raw_body) if resp.status != 200 or body.get("ok") is not True or body.get("zero_pii_enforced") is not True: raise RuntimeError( f"Unexpected API health response from {host} (HTTP {resp.status})." ) receipt["gates"]["api_health"] = { "status": "PASS", "ms": round((time.monotonic() - t0) * 1000, 1), "service": body.get("service"), } except (urllib.error.URLError, TimeoutError, OSError) as exc: reason = getattr(exc, "reason", exc) msg = ( f"Cannot reach {host} ({reason}). " "Check your internet connection, firewall, or proxy settings, then re-run ./install.sh " "(or set ADVISOR_SKIP_NETWORK=1 for an offline check)." ) receipt["gates"]["api_health"] = {"status": "FAIL", "error": msg} errors.append(msg) except Exception as exc: msg = f"API health check against {host} failed: {exc}" receipt["gates"]["api_health"] = {"status": "FAIL", "error": msg} errors.append(msg) # Gate 4: Native headless browser PDF check (Chrome / Chromium / Edge if present) browser_candidates = [ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", "/Applications/Chromium.app/Contents/MacOS/Chromium", shutil.which("google-chrome"), shutil.which("chromium"), shutil.which("chromium-browser"), shutil.which("microsoft-edge"), ] browser = next((b for b in browser_candidates if b and Path(b).exists()), None) if browser: try: with tempfile.TemporaryDirectory() as td: html_p = Path(td) / "check.html" pdf_p = Path(td) / "check.pdf" html_p.write_text( "
PDF check OK.
", encoding="utf-8", ) subprocess.run( [ browser, "--headless=new", "--disable-gpu", "--no-sandbox", "--no-pdf-header-footer", f"--print-to-pdf={pdf_p}", html_p.as_uri(), ], check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=30, ) raw = pdf_p.read_bytes() if not raw.startswith(b"%PDF-"): raise RuntimeError("Rendered PDF missing %PDF- header") receipt["gates"]["pdf_render"] = { "status": "PASS", "browser": Path(browser).name, "bytes": len(raw), } except Exception as exc: msg = f"Gate 4 (headless browser PDF render via {Path(browser).name}) failed: {exc}" receipt["gates"]["pdf_render"] = {"status": "FAIL", "error": msg} errors.append(msg) else: receipt["gates"]["pdf_render"] = "NO_BROWSER_FOUND" partial_reasons.append("pdf_render skipped (no Chrome, Chromium, or Edge browser found)") # Gate 5: Verify ./advisor launcher enforces UTF-8 (-c passthrough) and routes CLI (--help) try: launcher = str(root / "advisor") clean_env = dict(os.environ) clean_env.pop("PYTHONUTF8", None) clean_env.pop("PYTHONIOENCODING", None) clean_env.pop("PYTHONPATH", None) clean_env.pop("VAULT_ROOT", None) py_proc = subprocess.run( [launcher, "-c", "import locale, sys; assert sys.flags.utf8_mode == 1; print(locale.getpreferredencoding(False))"], cwd=tempfile.gettempdir(), env=clean_env, capture_output=True, text=True, timeout=30, check=False, ) if py_proc.returncode != 0 or py_proc.stdout.strip().lower() != "utf-8": raise RuntimeError( f"launcher -c UTF-8 check failed (rc={py_proc.returncode}): {(py_proc.stderr or py_proc.stdout).strip()}" ) cli_proc = subprocess.run( [launcher, "--help"], cwd=tempfile.gettempdir(), env=clean_env, capture_output=True, text=True, timeout=30, check=False, ) if cli_proc.returncode != 0 or "onboard" not in cli_proc.stdout: raise RuntimeError( f"launcher --help CLI check failed (rc={cli_proc.returncode}): {(cli_proc.stderr or cli_proc.stdout).strip()}" ) receipt["gates"]["launcher_utf8"] = { "status": "PASS", "preferred_encoding": py_proc.stdout.strip().lower(), "cli_help": True, } except Exception as exc: msg = f"Gate 5 (./advisor launcher check) failed: {exc}" receipt["gates"]["launcher_utf8"] = {"status": "FAIL", "error": msg} errors.append(msg) finally: if errors: receipt["status"] = "FAIL" receipt["error"] = "; ".join(errors) elif partial_reasons: receipt["status"] = "PARTIAL" receipt["partial_reasons"] = partial_reasons else: receipt["status"] = "PASS" out_path = root / "install_receipt.json" out_path.write_text(json.dumps(receipt, indent=2) + "\n", encoding="utf-8") if errors: print("", file=sys.stderr) print("Advisor Assistant installation checks FAILED:", file=sys.stderr) for err in errors: print(f" - {err}", file=sys.stderr) print(f"Receipt written to: {root / 'install_receipt.json'}", file=sys.stderr) sys.exit(1) print(json.dumps(receipt, indent=2)) PY INSTALL_STATUS="$("${VENV_PY}" -c 'import json, sys; print(json.load(open(sys.argv[1], encoding="utf-8")).get("status", "PASS"))' "${APP_ROOT}/install_receipt.json" 2>/dev/null || echo "PASS")" echo "[5/5] Advisor Assistant install complete (${INSTALL_STATUS})! Receipt written to ${APP_ROOT}/install_receipt.json" echo "Standard starting harness: OMP (CLAUDE.md and AGENTS.md are also supported)." HAS_API_TOKEN=0 if [ -n "${ADVISOR_API_TOKEN:-}" ] || [ -n "${CV_API_TOKEN:-}" ]; then HAS_API_TOKEN=1 else # The one active secrets file (secret_config.resolve_secrets_path, inline: Python is not importable here yet). if [ -n "${ADVISOR_ASSISTANT_SECRETS_FILE:-}" ]; then SECRETS_PATH="${ADVISOR_ASSISTANT_SECRETS_FILE}" elif [ -n "${COMPLIANCEVAULT_SECRETS_FILE:-}" ]; then SECRETS_PATH="${COMPLIANCEVAULT_SECRETS_FILE}" elif [ -e "${HOME}/.advisor_assistant_secrets.json" ]; then SECRETS_PATH="${HOME}/.advisor_assistant_secrets.json" elif [ -e "${HOME}/.compliancevault_secrets.json" ]; then SECRETS_PATH="${HOME}/.compliancevault_secrets.json" else SECRETS_PATH="${HOME}/.advisor_assistant_secrets.json" fi if [ -f "${SECRETS_PATH}" ]; then # Key names are matched case-insensitively: advisor activate writes CV_API_TOKEN, a hand-made file may say api_token. if "${VENV_PY}" -c 'import json, sys; d = json.load(open(sys.argv[1], encoding="utf-8")); keys = {"advisor_api_token", "cv_api_token", "api_token"}; sys.exit(0 if isinstance(d, dict) and any(str(k).lower() in keys and str(v or "").strip() for k, v in d.items()) else 1)' "${SECRETS_PATH}" >/dev/null 2>&1; then HAS_API_TOKEN=1 fi fi fi DROP_BOX="${HOME}/Documents/Advisor Assistant Drop Box" echo "" if [ -d "${DROP_BOX}" ]; then echo "Your Drop Box folder: ${DROP_BOX}" elif mkdir -p "${DROP_BOX}" 2>/dev/null; then echo "Created your Drop Box folder: ${DROP_BOX}" else echo "Could not create your Drop Box folder: ${DROP_BOX} (create it yourself before dropping files)." fi echo " After setup, put client files in that folder and the assistant files them for you." echo "" echo "Next steps:" if [ "${HAS_API_TOKEN}" -eq 0 ]; then echo " 1. Activate your API key: ./advisor activate" echo ' (or export CV_API_TOKEN=... or save {"api_token":"..."} in ~/.advisor_assistant_secrets.json)' echo " 2. Start guided setup: ./advisor onboard" else echo " 1. Start guided setup: ./advisor onboard" echo " 2. Check system health: ./advisor doctor" fi