Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

25.9 KB
Raw Blame
#!/usr/bin/env bash
# One-click install for the apps MSO can own: Hermes and OpenClaw.
#
# WHY A SCRIPT, not an argv assembled in TypeScript. Each install is a SEQUENCE —
# fetch the installer, run it, configure it, install its service — while the job
# layer spawns exactly one child and never a shell (lib/managed-apps/job-child.ts).
# Keeping the sequence here honours that contract, puts the steps under version
# control where they can be read and diffed, and keeps the argv that ends up in the
# persisted job record down to two elements.
#
# SECRETS. Provider keys arrive in the ENVIRONMENT and never in argv. Hermes reads
# its provider env directly. OpenClaw non-interactive onboarding uses its reviewed
# environment SecretRef mode, so the transient child also never exposes provider
# keys through /proc/<pid>/cmdline. Keys are never echoed or persisted in MSO jobs.
#
# Everything here must be NON-INTERACTIVE. The job layer gives its child no stdin
# (JOB_STDIO), so a prompt does not hang — it gets EOF and the install dies
# halfway, which is worse than not starting.
set -euo pipefail
umask 077

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
ARTIFACT_LOCK="$ROOT/security/managed-app-artifacts.env"
[ -r "$ARTIFACT_LOCK" ] || { echo "missing managed-app artifact lock: $ARTIFACT_LOCK" >&2; exit 2; }
# shellcheck source=security/managed-app-artifacts.env
. "$ARTIFACT_LOCK"

validate_artifact_lock() {
  [[ "$HERMES_INSTALLER_URL" == "https://raw.githubusercontent.com/NousResearch/hermes-agent/$HERMES_INSTALLER_TAG/scripts/install.sh" ]] || return 1
  [[ "$HERMES_INSTALLER_COMMIT" =~ ^[0-9a-f]{40}$ ]] || return 1
  [[ "$HERMES_INSTALLER_SHA256" =~ ^[0-9a-f]{64}$ ]] || return 1
  [[ "$HERMES_IMAGE_REF" =~ ^nousresearch/hermes-agent@sha256:[0-9a-f]{64}$ ]] || return 1
  [[ "$OPENCLAW_VERSION" =~ ^[0-9][0-9A-Za-z.-]*$ ]] || return 1
  [[ "$OPENCLAW_TARBALL_SHA512" =~ ^[0-9a-f]{128}$ ]] || return 1
}
validate_artifact_lock || { echo "invalid managed-app artifact lock" >&2; exit 2; }

APP="${1:-}"
# loopback by default, deliberately. This runs on machines that are not mine: a
# gateway bound to the LAN on someone's first install is an exposure they never
# asked for. This host overrides it because Traefik has to reach the gateway.
BIND="${MSO_INSTALL_GATEWAY_BIND:-loopback}"
PROVIDER="${MSO_INSTALL_PROVIDER:-}"
KEY="${MSO_INSTALL_API_KEY:-}"
# The origin MSO will frame this app's dashboard from (lib/managed-apps/origin.ts:
# https://<id>.mso.example.com). Empty in single-origin deployments.
APP_ORIGIN="${MSO_INSTALL_APP_ORIGIN:-}"

log() { printf '\n=== %s\n' "$*"; }

case "$APP" in
hermes | openclaw | 9router | orca) ;;
*)
  echo "usage: managed-app-install <hermes|openclaw|9router|orca>" >&2
  exit 2
  ;;
esac

# MSO installs the Docker/server distribution of 9Router (upstream also has an npm
# CLI, but Docker is the documented VPS path). It needs no systemd user unit, so
# the user-bus preflight below would only create a false install dependency. Hand
# off to the Docker adapter and stop here.
if [ "$APP" = "9router" ]; then
  exec "$(dirname "$0")/managed-app-9router" install
fi

# Orca is the MSO-owned web/Node runtime installed as `mso-orca.service`. Its
# adapter verifies the pinned release, the user bus (without enabling linger or
# any other access change), the fixed loopback port and the configured split
# origin itself, so it must NOT run through the Hermes/OpenClaw preflight below
# (which calls `loginctl enable-linger`). Dispatch before it and stop here.
if [ "$APP" = "orca" ]; then
  exec "$(dirname "$0")/managed-app-orca" install
fi

# Both apps are installed as systemd USER units, and `systemctl --user` finds the
# user's systemd instance through XDG_RUNTIME_DIR. MSO may be running as a systemd
# SYSTEM unit with `User=`, which inherits no login session and therefore no such
# variable; every `systemctl --user` then answers
#
#     Failed to connect to bus: No medium found
#
# and, under `set -e`, kills this script outright.
#
# That is not hypothetical. It aborted real installs inside
# install_hermes_dashboard() — AFTER the upstream installer had already fetched
# uv, a Python, the git checkout and 80 skills — leaving a unit file on disk that
# nothing had ever enabled, and reporting only "exited with code 1".
ensure_user_bus() {
  [ -n "${XDG_RUNTIME_DIR:-}" ] && [ -S "${XDG_RUNTIME_DIR}/bus" ] && return 0
  # Linger is what keeps /run/user/<uid> alive without a login session — and
  # enabling it CREATES that directory here and now. A user may enable their own
  # linger without root.
  loginctl enable-linger "$(id -un)" >/dev/null 2>&1 || true
  local uid
  uid="$(id -u)"
  if [ -S "/run/user/${uid}/bus" ]; then
    export XDG_RUNTIME_DIR="/run/user/${uid}"
    return 0
  fi
  return 1
}


# Hosted/systemd-less installs may expose Docker only through passwordless sudo.
docker_cli() {
  if docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then
    DOCKER=(docker)
    return 0
  fi
  if sudo -n docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then
    DOCKER=(sudo -n docker)
    return 0
  fi
  return 1
}

HERMES_RUNTIME=native

# Checked HERE, before ~20 minutes of downloading and compiling, because the last
# step is the most expensive place to discover a missing environment variable.
if command -v systemctl >/dev/null 2>&1; then
  if ensure_user_bus; then
    log "user systemd bus: ${XDG_RUNTIME_DIR}/bus"
  elif [ "$APP" = "hermes" ] && docker_cli; then
    HERMES_RUNTIME=docker
    log "user systemd unavailable; Hermes will use its pinned Docker runtime"
  else
    cat >&2 <<MSG
cannot reach the systemd user bus for $(id -un), so $APP's service could not be
installed even if everything else succeeded. Nothing has been changed.

On a normal systemd host, enable user linger and give MSO the user's runtime dir.
On a systemd-less/container host, Hermes can instead use the reviewed Docker
runtime when Docker is available to the MSO service account.
MSG
    exit 1
  fi
else
  if [ "$APP" = "hermes" ] && docker_cli; then
    HERMES_RUNTIME=docker
    log "systemd is unavailable; Hermes will use its pinned Docker runtime"
  else
    echo "no usable systemd user bus or Docker runtime for $APP" >&2
    exit 1
  fi
fi

# ---------------------------------------------------------------- hermes ----
hermes_provider_env_name() {
  case "$PROVIDER" in
    anthropic) echo ANTHROPIC_API_KEY ;;
    openai) echo OPENAI_API_KEY ;;
    openrouter) echo OPENROUTER_API_KEY ;;
    nous) echo NOUS_API_KEY ;;
    "") return 1 ;;
    *) echo "unsupported Hermes provider '$PROVIDER'" >&2; return 2 ;;
  esac
}

persist_hermes_provider_key() {
  [ -n "$KEY" ] || return 0
  local env_name env_file tmp
  env_name="$(hermes_provider_env_name)" || return 1
  case "$KEY" in
    *$'\n'*|*$'\r'*) echo "Hermes provider key contains a control character" >&2; return 1 ;;
  esac
  mkdir -p "$HOME/.hermes"
  env_file="$HOME/.hermes/.env"
  tmp="$(mktemp "$HOME/.hermes/.env.mso.XXXXXX")"
  if [ -f "$env_file" ]; then
    grep -v "^${env_name}=" "$env_file" >"$tmp" || true
  fi
  printf '%s=%s\n' "$env_name" "$KEY" >>"$tmp"
  chmod 600 "$tmp"
  mv "$tmp" "$env_file"
}

hermes_flat_image_ref() {
  printf 'mso/hermes-agent:%s-vfs-flat' "${HERMES_INSTALLER_TAG#v}"
}

prepare_hermes_runtime_image() {
  HERMES_RUNTIME_IMAGE="$HERMES_IMAGE_REF"

  local driver flat source_label tmp
  driver="$("${DOCKER[@]}" info --format '{{.Driver}}' 2>/dev/null || true)"
  flat="$(hermes_flat_image_ref)"
  if [ "$driver" = "vfs" ]; then
    # Reuse an already-derived image BEFORE pulling upstream again. On VFS, merely
    # pulling the multi-layer source can consume tens of GB because each layer is
    # a full snapshot. The source label binds this local representation to the
    # exact reviewed digest in managed-app-artifacts.env.
    source_label="$("${DOCKER[@]}" image inspect --format '{{index .Config.Labels "io.mso.source-image"}}' "$flat" 2>/dev/null || true)"
    if [ "$source_label" = "$HERMES_IMAGE_REF" ]; then
      HERMES_RUNTIME_IMAGE="$flat"
      log "reusing flattened Hermes image for Docker VFS storage"
      return 0
    fi
  fi

  log "pulling pinned Hermes image ($HERMES_INSTALLER_TAG)"
  "${DOCKER[@]}" pull "$HERMES_IMAGE_REF"
  [ "$driver" = "vfs" ] || return 0

  # Docker's VFS driver deep-copies every cumulative image layer. The upstream
  # Hermes image has many layers, so its ~2.7 GB logical rootfs can consume tens
  # of GB physically. Flatten ONLY the already-reviewed pinned source image into
  # one local layer; the source digest remains recorded as a label and is checked
  # before reuse. This is a storage representation change, not a different build.
  source_label="$("${DOCKER[@]}" image inspect --format '{{index .Config.Labels "io.mso.source-image"}}' "$flat" 2>/dev/null || true)"
  if [ "$source_label" != "$HERMES_IMAGE_REF" ]; then
    tmp="mso-hermes-flatten-$$"
    "${DOCKER[@]}" rm -f "$tmp" >/dev/null 2>&1 || true
    "${DOCKER[@]}" create --name "$tmp" "$HERMES_IMAGE_REF" >/dev/null
    log "flattening Hermes for Docker VFS storage"
    if ! "${DOCKER[@]}" export "$tmp" | "${DOCKER[@]}" import \
      --change 'ENV PATH=/opt/hermes/bin:/opt/hermes/.venv/bin:/opt/data/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin' \
      --change 'ENV PYTHONUNBUFFERED=1' \
      --change 'ENV PYTHONDONTWRITEBYTECODE=1' \
      --change 'ENV PLAYWRIGHT_BROWSERS_PATH=/opt/hermes/.playwright' \
      --change 'ENV npm_config_install_links=false' \
      --change 'ENV HERMES_WEB_DIST=/opt/hermes/hermes_cli/web_dist' \
      --change 'ENV HERMES_TUI_DIR=/opt/hermes/ui-tui' \
      --change 'ENV HERMES_HOME=/opt/data' \
      --change 'ENV HERMES_WRITE_SAFE_ROOT=/opt/data' \
      --change 'ENV HERMES_DISABLE_LAZY_INSTALLS=1' \
      --change 'ENV HERMES_LAZY_INSTALL_TARGET=/opt/data/lazy-packages' \
      --change 'WORKDIR /opt/hermes' \
      --change 'VOLUME ["/opt/data"]' \
      --change 'ENTRYPOINT ["/opt/hermes/docker/entrypoint-dispatch.sh"]' \
      --change "LABEL org.opencontainers.image.revision=$HERMES_INSTALLER_COMMIT" \
      --change "LABEL io.mso.source-image=$HERMES_IMAGE_REF" \
      - "$flat" >/dev/null; then
      "${DOCKER[@]}" rm -f "$tmp" >/dev/null 2>&1 || true
      return 1
    fi
    "${DOCKER[@]}" rm -f "$tmp" >/dev/null 2>&1 || true
  fi
  HERMES_RUNTIME_IMAGE="$flat"
}

install_hermes_cli_wrapper() {
  local wrapper="$HOME/.local/bin/hermes"
  mkdir -p "$(dirname "$wrapper")"
  cat >"$wrapper" <<'WRAPPER'
#!/usr/bin/env bash
set -euo pipefail
cwd="$PWD"
case "$cwd" in
  "$HOME"|"$HOME"/*) ;;
  *) cwd="$HOME" ;;
esac
runner=(docker)
if ! docker version --format '{{.Server.Version}}' >/dev/null 2>&1; then runner=(sudo -n docker); fi
args=(exec --user "$(id -u):$(id -g)" -w "$cwd")
if [ -t 0 ] && [ -t 1 ]; then args+=(-it); else args+=(-i); fi
exec "${runner[@]}" "${args[@]}" hermes /opt/hermes/hermes "$@"
WRAPPER
  chmod 755 "$wrapper"
}

install_hermes_docker() {
  docker_cli || { echo "Docker is unavailable to $(id -un)" >&2; return 1; }
  mkdir -p "$HOME/.hermes"
  persist_hermes_provider_key
  prepare_hermes_runtime_image

  log "configuring Hermes in the persistent data volume"
  "${DOCKER[@]}" run --rm --network host \
    -v "$HOME/.hermes:/opt/data" \
    -v "$HOME:$HOME" \
    -e "HERMES_UID=$(id -u)" -e "HERMES_GID=$(id -g)" \
    "$HERMES_RUNTIME_IMAGE" setup --non-interactive
  "${DOCKER[@]}" run --rm \
    -v "$HOME/.hermes:/opt/data" -v "$HOME:$HOME" \
    -e "HERMES_UID=$(id -u)" -e "HERMES_GID=$(id -g)" \
    "$HERMES_RUNTIME_IMAGE" config set terminal.cwd "$HOME" >/dev/null
  install_hermes_cli_wrapper

  if "${DOCKER[@]}" container inspect hermes >/dev/null 2>&1; then
    local source_label configured_image
    configured_image="$("${DOCKER[@]}" inspect --format '{{.Config.Image}}' hermes 2>/dev/null || true)"
    source_label="$("${DOCKER[@]}" inspect --format '{{index .Config.Labels "io.mso.source-image"}}' hermes 2>/dev/null || true)"
    if [ "$configured_image" != "$HERMES_IMAGE_REF" ] && [ "$configured_image" != "$HERMES_RUNTIME_IMAGE" ] && [ "$source_label" != "$HERMES_IMAGE_REF" ]; then
      echo "a container named 'hermes' already exists with an unrelated image; refusing to replace it" >&2
      return 1
    fi
    log "reconciling existing Hermes container"
    "${DOCKER[@]}" rm -f hermes >/dev/null
  fi

  log "starting Hermes gateway + dashboard on loopback"
  "${DOCKER[@]}" run -d \
    --name hermes \
    --restart unless-stopped \
    --network host \
    --label "io.mso.source-image=$HERMES_IMAGE_REF" \
    -v "$HOME/.hermes:/opt/data" \
    -v "$HOME:$HOME" \
    -e "HERMES_UID=$(id -u)" \
    -e "HERMES_GID=$(id -g)" \
    -e HERMES_DASHBOARD=1 \
    -e HERMES_DASHBOARD_HOST=127.0.0.1 \
    "$HERMES_RUNTIME_IMAGE" gateway run >/dev/null

  # The flattened VFS image supersedes the multi-layer source locally. Removing
  # the reviewed source image after the container is on the derived image frees
  # the duplicated VFS layer trees; a future update pulls the pinned source again.
  if [ "$HERMES_RUNTIME_IMAGE" != "$HERMES_IMAGE_REF" ]; then
    "${DOCKER[@]}" image rm "$HERMES_IMAGE_REF" >/dev/null 2>&1 || true
  fi

  local i running
  for i in $(seq 1 90); do
    if curl -fsS -o /dev/null --max-time 3 "http://127.0.0.1:${HERMES_DASHBOARD_PORT:-9119}/api/health"; then
      log "Hermes Docker dashboard is answering on ${HERMES_DASHBOARD_PORT:-9119}"
      return 0
    fi
    running="$("${DOCKER[@]}" inspect --format '{{.State.Running}}' hermes 2>/dev/null || true)"
    if [ "$running" != "true" ]; then
      echo "Hermes container exited before the dashboard became healthy" >&2
      "${DOCKER[@]}" logs --tail 80 hermes >&2 || true
      return 1
    fi
    sleep 2
  done
  echo "Hermes container is running but /api/health did not answer within 180s" >&2
  "${DOCKER[@]}" logs --tail 80 hermes >&2 || true
  return 1
}

install_hermes() {
  if [ "$HERMES_RUNTIME" = docker ]; then
    install_hermes_docker
    return
  fi
  local tmp
  tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' RETURN

  # Downloaded, then run from a file — not `curl | bash`. The bytes that execute
  # are the bytes on disk, a truncated download fails at curl instead of running
  # half a script, and the job transcript can name what it fetched.
  log "downloading the pinned Hermes installer ($HERMES_INSTALLER_TAG)"
  curl -fsSL --proto '=https' --tlsv1.2 --max-time 300 "$HERMES_INSTALLER_URL" -o "$tmp/install.sh"
  printf '%s  %s
' "$HERMES_INSTALLER_SHA256" "$tmp/install.sh" | sha256sum -c - >/dev/null || {
    echo "Hermes installer integrity check failed" >&2
    return 1
  }
  printf 'installer: %s bytes, verified sha256 %s
' "$(wc -c <"$tmp/install.sh")" "${HERMES_INSTALLER_SHA256:0:16}"

  # The upstream installer is NOT safely re-runnable against a live install: on a
  # second pass it prints "Virtual environment already exists, recreating…" and
  # unlinks the interpreter that the RUNNING hermes-gateway.service is executing
  # from (its ExecStart is …/venv/bin/python). The process survives on deleted
  # inodes — observed holding 18 `(deleted)` .so mappings, including
  # cryptography/_rust and nacl/_sodium — until something makes it import a module
  # it has not already loaded, and then it dies in a way nothing here reported.
  #
  # This mattered because a FAILED install invites a retry, and the retry is what
  # does the damage. So: if a working Hermes is already present, do not re-run the
  # installer. Everything after it (`setup`, `gateway install`, the dashboard unit)
  # is idempotent by upstream's own design — "Service already installed … Use
  # --force", "config.yaml already exists, keeping it" — so the button still works
  # as a REPAIR for the steps that actually failed.
  #
  # Tested by running the launcher, not by stat-ing the venv: a half-built venv
  # has an executable python and imports nothing.
  if hermes_cmd 2>/dev/null && "${HERMES_CMD[@]}" --version >/dev/null 2>&1; then
    log "hermes is already installed and runnable — skipping the upstream installer"
    printf 'found: %s\n' "$("${HERMES_CMD[@]}" --version 2>/dev/null | head -1)"
  else
    log "running the installer (non-interactive)"
    # --non-interactive makes it skip every stage that would ask (install.sh:3211).
    # It pulls uv, Python, Node and ffmpeg itself; sudo is used only to apt-get git
    # and degrades to a no-op without it.
    # Installer bytes and checkout are independently pinned. --force-commit
    # prevents a broken pre-existing checkout from keeping unreviewed source.
    bash "$tmp/install.sh" --non-interactive --branch main \
      --commit "$HERMES_INSTALLER_COMMIT" --force-commit
  fi

  hermes_cmd
  persist_hermes_provider_key
  log "configuring from the environment"
  # `setup --non-interactive` is documented as "use defaults/env vars", and Hermes
  # reads ANTHROPIC_API_KEY / OPENAI_API_KEY / OPENROUTER_API_KEY / NOUS_API_KEY —
  # so for Hermes the key never becomes an argv at all.
  "${HERMES_CMD[@]}" setup --non-interactive

  log "installing the gateway service"
  "${HERMES_CMD[@]}" gateway install --start-now --start-on-login

  install_hermes_dashboard
}

# The gateway is NOT the dashboard, and shipping only the gateway is what made a
# fresh install look broken: `hermes gateway install` creates hermes-gateway.service
# (Telegram/Discord/WhatsApp plumbing) and binds nothing on 9119, so the MSO iframe —
# pointed at HERMES_DASHBOARD_URL, default http://127.0.0.1:9119 — got ECONNREFUSED and
# rendered the proxy's own {"error":"managed application upstream unavailable"}.
# This box hid the gap for months because its 9119 unit was written by hand.
#
# There is no `hermes dashboard install`, so the unit is ours. `hermes serve` is NOT a
# substitute: it answers /api/* but replies 404 {"error":"Headless backend (hermes serve):
# web UI disabled"} at /, which is a dead iframe with extra steps.
#
# No --skip-build on purpose. The first start runs `npm install && vite build` into
# hermes_cli/web_dist (~1 min); every later start finds it current and comes up in 2s.
# --skip-build would shave nothing off the warm path and turn a missing dist into a
# permanently broken service instead of a slow first boot.
install_hermes_dashboard() {
  local unit="$HOME/.config/systemd/user/hermes-dashboard.service"
  log "installing the dashboard service (127.0.0.1:${HERMES_DASHBOARD_PORT:-9119})"
  mkdir -p "$(dirname "$unit")"
  cat >"$unit" <<UNIT
[Unit]
Description=Hermes Agent Dashboard (web UI)
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
ExecStart=${HERMES_CMD[*]} dashboard --no-open --host 127.0.0.1 --port ${HERMES_DASHBOARD_PORT:-9119}
WorkingDirectory=$HOME/.hermes
Environment="HERMES_HOME=$HOME/.hermes"
Restart=always
RestartSec=5
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=default.target
UNIT

  # Without linger a user unit dies with the last session, so the dashboard would
  # vanish on logout and never return after a reboot. ensure_user_bus enables it
  # and exports XDG_RUNTIME_DIR; both are idempotent and need no sudo. It ran in
  # preflight already — repeated here so this function is correct on its own, and
  # because `$USER` (which this used to read) is not guaranteed to be set in a
  # systemd child, while `id -un` always is.
  ensure_user_bus || {
    echo "cannot reach the user systemd bus — see the preflight message above" >&2
    return 1
  }
  systemctl --user daemon-reload
  systemctl --user enable --now hermes-dashboard.service

  # Wait for the FIRST build rather than declaring victory at spawn: an install that
  # reports success while the iframe is still refused is the bug this whole function
  # exists to fix. Not fatal — the unit keeps building after the job ends.
  local i
  for i in $(seq 1 90); do
    if curl -fsS -o /dev/null --max-time 3 "http://127.0.0.1:${HERMES_DASHBOARD_PORT:-9119}/api/health"; then
      log "dashboard is answering on 9119"
      return 0
    fi
    sleep 2
  done

  # Falling out of this loop used to return 0 — the exit status of the `echo`
  # below — so the job was recorded as SUCCEEDED with nothing listening on 9119.
  # That is precisely the failure this function was written to prevent ("an
  # install that reports success while the iframe is still refused"), reintroduced
  # through the back door by a missing return.
  #
  # "Timed out" is still two different outcomes, so ask which one before deciding:
  # a first start compiles the web UI with vite and can genuinely outrun 180 s on a
  # small VPS, and failing that install would be just as wrong as passing a dead one.
  if systemctl --user is-active --quiet hermes-dashboard.service; then
    echo "dashboard has not answered within 180s but its service is running — it is still building." >&2
    echo "watch it with: journalctl --user -u hermes-dashboard -f" >&2
    return 0
  fi
  echo "dashboard service is not running after install: $(systemctl --user is-active hermes-dashboard.service 2>&1)" >&2
  echo "diagnose with: systemctl --user status hermes-dashboard --no-pager" >&2
  return 1
}

# Sets HERMES_CMD. An ARRAY, because the last candidate is two words.
#
# Order matters and cost three consecutive failed installs to learn. The installer's own
# launcher at ~/.local/bin/hermes is a bash wrapper that unsets PYTHONPATH/PYTHONHOME and
# execs the VENV python — that is the one that works. But `~/.local/bin` is NOT on the PATH
# a systemd service inherits (mso gets
# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/snap/bin), so `command -v hermes`
# misses it, and the next candidate down — ~/.hermes/hermes-agent/hermes — carries a
# `#!/usr/bin/env python3` shebang. That runs the SYSTEM python, which has no `dotenv`, and
# every install died on
#   ModuleNotFoundError: No module named 'dotenv'   (env_loader.py:11)
# with the venv sitting right there fully populated. So: explicit paths before PATH, and
# the venv interpreter as the floor. Never the bare hermes-agent/hermes.
hermes_cmd() {
  local candidate
  for candidate in "$HOME/.local/bin/hermes" "$HOME/.hermes/bin/hermes"; do
    if [ -x "$candidate" ]; then
      HERMES_CMD=("$candidate")
      return 0
    fi
  done
  if command -v hermes >/dev/null 2>&1; then
    HERMES_CMD=("$(command -v hermes)")
    return 0
  fi
  # What the working hermes-gateway.service unit used before any of this existed.
  if [ -x "$HOME/.hermes/hermes-agent/venv/bin/python" ]; then
    HERMES_CMD=("$HOME/.hermes/hermes-agent/venv/bin/python" -m hermes_cli.main)
    return 0
  fi
  echo "hermes: installed, but no launcher and no venv found under ~/.hermes" >&2
  return 1
}

# -------------------------------------------------------------- openclaw ----
install_openclaw() {
  local tmp tarball actual openclaw installed_version
  tmp="$(mktemp -d)"
  trap 'rm -rf "$tmp"' RETURN

  log "installing the pinned OpenClaw CLI ($OPENCLAW_VERSION)"
  # Verify the exact package bytes before npm can execute lifecycle hooks.
  tarball="$(cd "$tmp" && npm pack "openclaw@$OPENCLAW_VERSION" --silent)"
  [ -n "$tarball" ] && [ -f "$tmp/$tarball" ] || { echo "OpenClaw package download failed" >&2; return 1; }
  actual="$(sha512sum "$tmp/$tarball" | awk '{print $1}')"
  [ "$actual" = "$OPENCLAW_TARBALL_SHA512" ] || {
    echo "OpenClaw tarball integrity check failed" >&2
    return 1
  }
  npm install -g "$tmp/$tarball"

  openclaw="$(openclaw_bin)"
  installed_version="$("$openclaw" --version 2>/dev/null | head -1)"
  printf '%s' "$installed_version" | grep -Fq "$OPENCLAW_VERSION" || {
    echo "installed OpenClaw version does not match lock: $installed_version" >&2
    return 1
  }

  local -a auth=(--auth-choice skip)
  if [ -n "$KEY" ]; then
    # The provider-specific environment variable was already exported by MSO.
    # OpenClaw's non-interactive SecretRef mode validates it and stores only the
    # env reference. No provider key is copied into this process's argv.
    case "$PROVIDER" in
    anthropic) auth=(--auth-choice apiKey --secret-input-mode ref) ;;
    openai) auth=(--auth-choice openai-api-key --secret-input-mode ref) ;;
    openrouter) auth=(--auth-choice openrouter-api-key --secret-input-mode ref) ;;
    google) auth=(--auth-choice gemini-api-key --secret-input-mode ref) ;;
    groq) auth=(--auth-choice groq-api-key --secret-input-mode ref) ;;
    xai) auth=(--auth-choice xai-api-key --secret-input-mode ref) ;;
    deepseek) auth=(--auth-choice deepseek-api-key --secret-input-mode ref) ;;
    *)
      echo "unknown provider '$PROVIDER' — refusing credentialed install" >&2
      return 1
      ;;
    esac
  fi

  log "running onboard (non-interactive) and installing the gateway service"
  # --accept-risk is REQUIRED by --non-interactive: it is the acknowledgement that
  # an agent with system access is a loaded gun. The skips drop the parts that are
  # a conversation (channels, search, skills, hooks) — all addable later from the
  # app's own UI, none of them needed for the gateway to come up healthy.
  "$openclaw" onboard \
    --non-interactive \
    --accept-risk \
    --flow quickstart \
    --gateway-auth token \
    --gateway-bind "$BIND" \
    --install-daemon \
    --skip-channels \
    --skip-search \
    --skip-skills \
    --skip-hooks \
    "${auth[@]}"

  # OpenClaw's Control UI refuses a WebSocket whose browser origin is not on this
  # list, and the page it refuses is the one MSO frames — "Browser origin not
  # allowed", a working gateway behind a dead dashboard. onboard has no flag for it,
  # so set it here. Origin only, never a wildcard: this list is what stops any other
  # page in a browser from driving the agent.
  if [ -n "$APP_ORIGIN" ]; then
    log "allowing the MSO app origin on the Control UI"
    "$openclaw" config set gateway.controlUi.allowedOrigins "[\"$APP_ORIGIN\"]" --strict-json
    "$openclaw" gateway restart >/dev/null 2>&1 || true
  fi
}

openclaw_bin() {
  if command -v openclaw >/dev/null 2>&1; then
    command -v openclaw
  else
    # `npm i -g` lands in a prefix that a non-login child's PATH may not carry.
    echo "$(npm config get prefix)/bin/openclaw"
  fi
}

case "$APP" in
hermes) install_hermes ;;
openclaw) install_openclaw ;;
esac

log "$APP install finished"