Files
persistent-chat-plugin/scripts/ensure-hub.sh
2026-06-26 19:05:14 +08:00

66 lines
1.8 KiB
Bash
Executable File

#!/usr/bin/env bash
# 启动 MCP 前确保 Hub 在 13458 运行(全局唯一)
set -eo pipefail
INSTALL="$(cd "$(dirname "$0")" && pwd)"
PORT="${PCHAT_HTTP_PORT:-13458}"
HUB_HOST="${PCHAT_HUB_HOST:-127.0.0.1}"
LOG="$INSTALL/logs/hub.log"
NODE="${PCHAT_NODE:-$(command -v node 2>/dev/null || true)}"
[[ -z "$NODE" ]] && NODE="/usr/local/opt/node@22/bin/node"
mkdir -p "$INSTALL/logs"
if [[ ! -x "$NODE" ]]; then
echo "[ensure-hub] FATAL: node not found: $NODE" >&2
exit 1
fi
hub_health() {
curl -sf -m 2 "http://${HUB_HOST}:${PORT}/api/health" >/dev/null 2>&1
}
start_hub() {
if hub_health; then return 0; fi
if [[ "$HUB_HOST" != "127.0.0.1" && "$HUB_HOST" != "localhost" ]]; then
echo "[ensure-hub] remote hub not ready: http://${HUB_HOST}:${PORT}; fallback to local :${PORT}" >> "$LOG"
HUB_HOST="127.0.0.1"
export PCHAT_HUB_HOST="$HUB_HOST"
hub_health && return 0
fi
echo "[ensure-hub] starting hub on :${PORT}" >> "$LOG"
nohup "$NODE" "$INSTALL/hub.js" >> "$INSTALL/logs/hub.stdout.log" 2>&1 &
local i=0
while [[ $i -lt 80 ]]; do
hub_health && return 0
sleep 0.15
i=$((i + 1))
done
return 1
}
if ! start_hub; then
echo "[ensure-hub] FATAL: Hub not ready on ${HUB_HOST}:${PORT} (waited ~12s). Run: bash 卡若AI/.../Cursor持久对话/脚本/sync-runtime.sh" >&2
exit 1
fi
# Cursor 无工作区时 ${workspaceFolder} 可能为空/none/未替换字面量 → 兜底 HOME
ARGS=()
for a in "$@"; do
case "$a" in
--workspace=|--workspace=none|--workspace=\$\{workspaceFolder\})
ARGS+=("--workspace=$HOME")
;;
--workspace=*)
ARGS+=("$a")
;;
*)
ARGS+=("$a")
;;
esac
done
if [[ ${#ARGS[@]} -eq 0 ]] || ! printf '%s\n' "${ARGS[@]}" | grep -q '^--workspace='; then
ARGS+=("--workspace=${PWD:-$HOME}")
fi
exec "$NODE" "$INSTALL/server.js" "${ARGS[@]}"