ODS V3 Pre-Release: Public testing and refinement ahead of the official V3 launch. Turn your PC, Mac, or Linux box into a private AI server.
Python ai-agentsamdcomfyuidockerllama-cppllmlocal-ain8nnvidiaopen-webuiragself-hostedspeech-to-textstrix-halotext-to-speechworkflow-automation
#!/bin/bash
# ============================================================================
# ODS Installer — Phase 12: Health Checks
# ============================================================================
# Part of: installers/phases/
# Purpose: Verify all services are responding, configure Perplexica,
# pre-download STT model
#
# Expects: DRY_RUN, GPU_BACKEND, ENABLE_VOICE, ENABLE_WORKFLOWS, ENABLE_RAG, ENABLE_QDRANT,
# ENABLE_EMBEDDINGS, ENABLE_HERMES, LLM_MODEL,
# LLM_BACKEND and VLLM_SERVED_MODEL (vllm waits on vllm-server),
# LOG_FILE, BGRN, AMB, NC,
# WHISPER_PORT, TTS_PORT,
# PERPLEXICA_PORT (:-3004), COMFYUI_PORT (:-8188),
# show_phase(), check_service(), ai(), ai_ok(), ai_warn(), signal(),
# ui_status_line(), ods_ui_cinematic()
# Provides: Health check results, Perplexica auto-configuration
#
# Modder notes:
# Add new service health checks or auto-configuration here.
# ============================================================================
# Keep standalone phase harnesses usable; production defines this in ui.sh.
if ! declare -F ui_status_line >/dev/null 2>&1; then
ui_status_line() {
local kind="$1" message="$2" label
case "$kind" in ok) label="OK" ;; warn) label="WARN" ;; error) label="ERROR" ;; *) label="INFO" ;; esac
printf ' [%s] %s\n' "$label" "$message"
}
fi
_phase12_cinematic() {
declare -F ods_ui_cinematic >/dev/null 2>&1 && ods_ui_cinematic
}
# Source service registry for port/health resolution
. "$SCRIPT_DIR/lib/service-registry.sh"
sr_load
# Resolve port overrides from .env (SERVICE_PORTS uses manifest defaults
# but .env may override them, e.g. OLLAMA_PORT=11434 on Strix Halo)
if [[ -f "$INSTALL_DIR/.env" ]]; then
. "$SCRIPT_DIR/lib/safe-env.sh" 2>/dev/null || true
load_env_file "$INSTALL_DIR/.env"
sr_resolve_ports
fi
ods_progress 85 "health" "Checking service health"
show_phase 6 6 "Systems Online" "~1-2 minutes"
if $DRY_RUN; then
log "[DRY RUN] Would verify service health:"
if [[ -n "${EXTERNAL_LLM_URL:-}" ]]; then
log "[DRY RUN] - External model through LiteLLM"
elif [[ "${LLM_BACKEND:-}" == "vllm" ]]; then
log "[DRY RUN] - vLLM engine (${VLLM_SERVED_MODEL:-the vLLM model}) and its route through model-router"
else
log "[DRY RUN] - Managed llama-server"
fi
[[ "${ENABLE_OPEN_WEBUI:-true}" != "true" ]] || log "[DRY RUN] - Open WebUI"
log "[DRY RUN] - Auto-configure Perplexica for ${LLM_MODEL:-default model}"
[[ "$ENABLE_HERMES" == "true" ]] && log "[DRY RUN] - Hermes Agent + hermes-proxy"
[[ "${ENABLE_PIXEL_RUNTIME:-false}" == "true" ]] && log "[DRY RUN] - Pixel gateway + private ingress + edge"
[[ "$ENABLE_VOICE" == "true" ]] && log "[DRY RUN] - Whisper (STT), Kokoro (TTS), pre-download STT model"
[[ "$ENABLE_WORKFLOWS" == "true" ]] && log "[DRY RUN] - n8n"
[[ "${ENABLE_QDRANT:-${ENABLE_RAG:-false}}" == "true" ]] && log "[DRY RUN] - Qdrant"
[[ "${ENABLE_EMBEDDINGS:-${ENABLE_RAG:-false}}" == "true" ]] && log "[DRY RUN] - Embeddings (TEI)"
echo ""
signal "Health checks planned. No services were started."
ai_ok "Dry-run simulation complete; runtime health was not tested."
return 0 2>/dev/null || true
fi
ai "Linking services... standby."
sleep 5
# Health checks are best-effort — track failures but don't let set -e kill the install.
# Services may need more startup time; we report all failures at the end.
HEALTH_FAILURES=0
EMBEDDINGS_HEALTH_FAILED=false
_check_health() {
if ! check_service "$@"; then
HEALTH_FAILURES=$((HEALTH_FAILURES + 1))
fi
}
_check_container_health() {
local name=$1
local container_name=$2
local max_attempts=${3:-60}
local docker_cmd="${DOCKER_CMD:-docker}"
local -a docker_cmd_arr=()
read -r -a docker_cmd_arr <<< "$docker_cmd"
[[ ${#docker_cmd_arr[@]} -gt 0 ]] || docker_cmd_arr=(docker)
if _phase12_cinematic; then
printf " ${GRN}...${NC} Waiting for %-20s " "$name"
else
printf " ... Waiting for %s\n" "$name"
fi
for attempt in $(seq 1 "$max_attempts"); do
local state=""
state=$("${docker_cmd_arr[@]}" inspect --format '{{.State.Status}}' "$container_name" 2>/dev/null || echo "missing")
case "$state" in
exited|dead|missing)
ui_status_line error "$name container $state"
ai_warn "$name container is $state; not retrying health probe."
return 1
;;
esac
local health=""
health=$("${docker_cmd_arr[@]}" inspect --format '{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}' "$container_name" 2>/dev/null || echo "missing")
case "$health" in
healthy)
ui_status_line ok "$name healthy"
return 0
;;
running)
# No Docker healthcheck declared. Treat running as good enough.
ui_status_line ok "$name running"
return 0
;;
esac
sleep 5
done
ui_status_line warn "$name delayed (container health not healthy yet)"
ai_warn "$name container health is not healthy yet. I will continue."
return 1
}
_phase12_env_get() {
local key="$1" default="${2:-}" env_file="${INSTALL_DIR:-.}/.env"
if [[ -f "$env_file" ]]; then
local value
value=$(grep -m1 "^${key}=" "$env_file" 2>/dev/null | cut -d= -f2- || true)
[[ -n "$value" ]] && { echo "$value"; return 0; }
fi
echo "$default"
}
# curl with an optional bearer token. The token reaches curl through a header
# file descriptor, never argv, which any local user can read with ps.
_phase12_curl_bearer() {
local token="$1"
shift
if [[ -n "$token" ]]; then
curl -H @<(printf 'Authorization: Bearer %s\n' "$token") "$@"
else
curl "$@"
fi
}
# True when the model runs in a host-native llama-server outside the stack
# (the Windows Portal's llama-server.exe); containers reach it through LiteLLM.
_phase12_host_native_llm() {
[[ -n "${NATIVE_LLM_BASE_URL:-$(_phase12_env_get NATIVE_LLM_BASE_URL "")}" ]]
}
_phase12_external_llm() {
local url model skip
url="${EXTERNAL_LLM_URL:-$(_phase12_env_get EXTERNAL_LLM_URL "")}"
model="${EXTERNAL_LLM_MODEL:-$(_phase12_env_get EXTERNAL_LLM_MODEL "")}"
skip="${SKIP_MODEL_DOWNLOAD:-$(_phase12_env_get SKIP_MODEL_DOWNLOAD false)}"
[[ -n "$url" && -n "$model" && "${skip,,}" == "true" ]]
}
_phase12_model_looks_non_chat() {
local model_lc="${1,,}"
[[ "$model_lc" == *flux* ]] \
|| [[ "$model_lc" == *stable-diffusion* ]] \
|| [[ "$model_lc" == *sdxl* ]] \
|| [[ "$model_lc" == *diffusion* ]] \
|| [[ "$model_lc" == *dall-e* ]] \
|| [[ "$model_lc" == *image* ]] \
|| [[ "$model_lc" == *img2img* ]] \
|| [[ "$model_lc" == *txt2img* ]] \
|| [[ "$model_lc" == *comfy* ]]
}
_phase12_verify_host_native_llm_completion() {
local litellm_port="${SERVICE_PORTS[litellm]:-4000}"
local litellm_key="${LITELLM_KEY:-$(_phase12_env_get LITELLM_KEY "")}"
local model="${GGUF_FILE:-$(_phase12_env_get GGUF_FILE default)}"
local native_url="${NATIVE_LLM_BASE_URL:-$(_phase12_env_get NATIVE_LLM_BASE_URL "")}"
[[ -n "$model" ]] || model="default"
local body response response_file error_file http_status curl_rc curl_error
body='{"model":"default","messages":[{"role":"user","content":"Reply with exactly OK."}],"max_tokens":16,"temperature":0,"stream":false,"chat_template_kwargs":{"enable_thinking":false}}'
ai "Verifying the host-native llama-server completion route through LiteLLM..."
response_file="$(mktemp "${TMPDIR:-/tmp}/ods-native-llm-response.XXXXXX")"
error_file="$(mktemp "${TMPDIR:-/tmp}/ods-native-llm-error.XXXXXX")"
if http_status="$(_phase12_curl_bearer "$litellm_key" -sS --max-time 180 \
-o "$response_file" \
-w '%{http_code}' \
-X POST "http://127.0.0.1:${litellm_port}/v1/chat/completions" \
-H "Content-Type: application/json" \
-d "$body" 2>"$error_file")"; then
curl_rc=0
else
curl_rc=$?
fi
response="$(cat "$response_file" 2>/dev/null || true)"
curl_error="$(cat "$error_file" 2>/dev/null || true)"
rm -f -- "$response_file" "$error_file"
if (( curl_rc != 0 )); then
printf " ${RED}ERR${NC} Host-native llama-server completion failed\n"
ai_warn "LiteLLM request failed before an HTTP response (curl exit ${curl_rc}, model: ${model})."
ai_warn "Check that LiteLLM is running and that llama-server on Windows answers: curl ${native_url:-<NATIVE_LLM_BASE_URL>}/health"
printf 'Host-native llama-server curl failure (exit %s):\n%s\n' "$curl_rc" "$curl_error" >> "$LOG_FILE"
return 1
fi
case "$http_status" in
2??) ;;
*)
printf " ${RED}ERR${NC} Host-native llama-server completion route returned HTTP %s\n" "$http_status"
ai_warn "LiteLLM rejected the host-native llama-server completion (HTTP ${http_status}, model: ${model})."
ai_warn "Inspect the bounded response recorded in ${LOG_FILE}; check the llama-server task in the ODS Portal, then rerun setup from the Portal."
{
printf 'Host-native llama-server completion HTTP %s:\n' "$http_status"
printf '%.*s\n' 4096 "$response"
} >> "$LOG_FILE"
return 1
;;
esac
if printf '%s\n' "$response" | grep -Eq '"content"[[:space:]]*:[[:space:]]*"[^"]+'; then
printf " ${BGRN}OK${NC} Host-native llama-server completion route healthy\n"
return 0
fi
printf " ${RED}ERR${NC} Host-native llama-server returned no assistant content\n"
ai_warn "LiteLLM returned HTTP ${http_status} but did not provide non-empty assistant content (model: ${model})."
if _phase12_model_looks_non_chat "$model"; then
ai_warn "The selected model looks like an image/non-chat model. ODS needs a text/chat model for the LLM route."
fi
ai_warn "Check the model loaded by llama-server on Windows: curl ${native_url:-<NATIVE_LLM_BASE_URL>}/health, then rerun setup from the ODS Portal."
printf '%.*s\n' 4096 "$response" >> "$LOG_FILE"
return 1
}
_phase12_verify_external_llm_completion() {
local host_url container_url provider model dashboard_container response probe_diagnostics
local -a docker_cmd_arr=()
host_url="${EXTERNAL_LLM_URL:-$(_phase12_env_get EXTERNAL_LLM_URL "")}"
container_url="${EXTERNAL_LLM_CONTAINER_URL:-$(_phase12_env_get EXTERNAL_LLM_CONTAINER_URL "")}"
provider="${EXTERNAL_LLM_PROVIDER:-$(_phase12_env_get EXTERNAL_LLM_PROVIDER "")}"
model="${EXTERNAL_LLM_MODEL:-$(_phase12_env_get EXTERNAL_LLM_MODEL "")}"
dashboard_container="$(sr_container dashboard-api 2>/dev/null || echo ods-dashboard-api)"
read -r -a docker_cmd_arr <<< "${DOCKER_CMD:-docker}"
[[ ${#docker_cmd_arr[@]} -gt 0 ]] || docker_cmd_arr=(docker)
if [[ -z "$host_url" || -z "$container_url" || -z "$provider" || -z "$model" ]]; then
ai_bad "External LLM configuration is incomplete."
ai "Re-run with --external-llm-url, --external-llm-provider, and --external-llm-model, or use --no-external-llm."
return 1
fi
ai "Verifying external ${provider} model from the host..."
if ! external_llm_resolve_model "$provider" "$host_url" "$model" "$model" >/dev/null 2>&1; then
ai_bad "External ${provider} no longer exposes model ${model}."
ai "Restore the model/service, or re-run the installer with --no-external-llm."
return 1
fi
if ! probe_diagnostics="$(external_llm_probe_completion "$host_url" "$model" 2>&1)"; then
ai_bad "External ${provider} accepted discovery but failed a real completion for ${model}."
ai "Check the probe diagnostic in ${LOG_FILE} and provider readiness, then re-run the installer."
printf 'External %s completion probe diagnostic:\n%.*s\n' \
"$provider" 2048 "$probe_diagnostics" >> "$LOG_FILE"
return 1
fi
ai "Verifying the external model route from the ODS Docker network..."
response="$(
if [[ -n "${EXTERNAL_LLM_API_KEY_FILE:-}" ]]; then
external_llm_read_api_key "$EXTERNAL_LLM_API_KEY_FILE"
fi | "${docker_cmd_arr[@]}" exec -i "$dashboard_container" python -c '
import json
import sys
import urllib.error
import urllib.request
base = sys.argv[1].rstrip("/")
model = sys.argv[2]
key = sys.stdin.read()
payload = json.dumps({
"model": model,
"messages": [{"role": "user", "content": "Reply with OK."}],
"max_tokens": 1,
"temperature": 0,
"stream": False,
}).encode()
# Some API front ends refuse the default Python User-Agent (Cloudflare
# error 1010), so the probe names ODS.
headers = {"Content-Type": "application/json", "User-Agent": sys.argv[3]}
if key:
headers["Authorization"] = "Bearer " + key
request = urllib.request.Request(
base + "/v1/chat/completions",
data=payload,
headers=headers,
)
try:
with urllib.request.urlopen(request, timeout=90) as result:
body = json.load(result)
except urllib.error.HTTPError as exc:
# The status picks the installer hint; the start of the reply goes to the log.
detail = " ".join(exc.read(300).decode("utf-8", "replace").split())[:200]
raise SystemExit("API answered HTTP %d: %s" % (exc.code, detail))
choices = body.get("choices") if isinstance(body, dict) and not body.get("error") else None
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
raise SystemExit("completion response did not contain a valid choice")
choice = choices[0]
message = choice.get("message")
if not isinstance(message, dict) or message.get("role") != "assistant":
raise SystemExit("completion response did not contain an assistant message")
content = message.get("content")
reasoning = any(
isinstance(message.get(field), str) and message[field].strip()
for field in ("reasoning", "reasoning_content")
)
if isinstance(content, str) and content.strip():
print("assistant token received")
elif content in (None, "") and reasoning and choice.get("finish_reason") == "length":
# This one-token transport probe can end during reasoning. It establishes
# inference connectivity, not a completed answer or Pixel task quality.
print("reasoning token received; one-token probe exhausted")
else:
raise SystemExit("completion response contained no usable inference token")
' "$container_url" "$model" "ODS/${VERSION:-unknown}" 2>&1
)" || {
ai_bad "External ${provider} probe did not return a usable inference token."
if [[ "$response" =~ API\ answered\ HTTP\ ([0-9]{3}) ]]; then
case "${BASH_REMATCH[1]}" in
401|403) ai "The API refused this request from the ODS Docker network (HTTP ${BASH_REMATCH[1]}), although the same key worked from this computer. A firewall or bot filter in front of the API may be blocking it." ;;
429) ai "The API is rate-limiting this key (HTTP 429). Wait a minute, then rerun the installer." ;;
*) ai "The API answered HTTP ${BASH_REMATCH[1]}. Its reply is saved in ${LOG_FILE}." ;;
esac
else
ai "Check the saved probe error for provider response or connectivity problems before changing network settings."
fi
# A LiteLLM proxy in front of the API echoes the end of a refused key
# and the key's hash; neither belongs in a log people share for help.
printf '%s\n' "$response" | sed -E \
-e 's/(Received API Key[[:space:]]*=[[:space:]]*)[^,[:space:]"]+/\1[redacted]/g' \
-e 's/(Key Hash \(Token\)[[:space:]]*=[[:space:]]*)[0-9A-Fa-f]+/\1[redacted]/g' >> "$LOG_FILE"
return 1
}
printf " ${BGRN}OK${NC} External ${provider} inference probe passed (%s)\n" "$response"
ai "A completed user-visible answer still requires a real Pixel turn."
}
# The vLLM engine (LLM_BACKEND=vllm) runs in ods-vllm-server, which has no
# host port. Its compose healthcheck turns healthy once vLLM's /health answers
# 200; a first start reads 130-200 GB of weights and compiles kernels, so the
# wait allows as long as the healthcheck's start period (an hour).
_phase12_vllm_engine() {
[[ "${LLM_BACKEND:-$(_phase12_env_get LLM_BACKEND "")}" == "vllm" ]]
}
# A vLLM failure ends the install with its cause, what to do next and where
# to ask. vLLM's own log is saved to the install log first.
_phase12_vllm_stop() {
local cause="$1" recovery="$2"
local -a docker_cmd_arr=()
read -r -a docker_cmd_arr <<< "${DOCKER_CMD:-docker}"
{
printf '=== docker logs --tail 200 ods-vllm-server\n'
"${docker_cmd_arr[@]}" logs --tail 200 ods-vllm-server 2>&1 \
|| printf '(the vLLM container log is unavailable)\n'
} >> "$LOG_FILE"
ai_bad "$cause"
ai "$recovery"
ai "Need help? Ask on the ODS Discord: ${ODS_HELP_DISCORD_URL:-https://discord.gg/4ntNp9MAwC}"
exit 1
}
# Run in the background under spin_task: returns 0 once vllm-server is
# healthy, 1 when the engine stopped (why goes to REASON_FILE), 2 when the
# wait ran out. A restart counts only when it happens during this wait.
_phase12_poll_vllm_health() {
local reason_file="$1" interval="${ODS_VLLM_POLL_SECONDS:-10}"
local deadline=$((SECONDS + ${ODS_VLLM_READY_TIMEOUT_SECONDS:-3600}))
local state restarts health first_restarts=""
local -a docker_cmd_arr=()
read -r -a docker_cmd_arr <<< "${DOCKER_CMD:-docker}"
while (( SECONDS < deadline )); do
if ! read -r state restarts health < <("${docker_cmd_arr[@]}" inspect \
--format '{{.State.Status}} {{.RestartCount}} {{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' \
ods-vllm-server 2>>"$LOG_FILE"); then
state=missing restarts=0 health=none
fi
[[ "$restarts" =~ ^[0-9]+$ ]] || restarts=0
[[ -n "$first_restarts" ]] || first_restarts="$restarts"
if [[ "$health" == "healthy" ]]; then
return 0
fi
case "$state" in
exited|dead|missing)
printf 'The vLLM container stopped before the model was ready (container %s)' "$state" > "$reason_file"
return 1
;;
esac
if (( restarts > first_restarts )); then
printf 'vLLM stopped while loading the model, and Docker restarted it' > "$reason_file"
return 1
fi
if [[ "$health" == "unhealthy" ]]; then
printf "vLLM's health check failed" > "$reason_file"
return 1
fi
sleep "$interval"
done
return 2
}
_phase12_vllm_wait_status() {
printf 'a first start reads the weights and compiles kernels'
}
_phase12_wait_for_vllm() {
local model="${VLLM_SERVED_MODEL:-the vLLM model}" limit="${ODS_VLLM_READY_TIMEOUT_SECONDS:-3600}"
local reason_file pid rc=0 reason
reason_file="$(mktemp "${TMPDIR:-/tmp}/ods-vllm-wait.XXXXXX")"
ai "vLLM is loading ${model}. A first start reads the whole model into GPU memory and compiles kernels before it answers; later starts are faster."
_phase12_poll_vllm_health "$reason_file" &
pid=$!
spin_task "$pid" "Loading ${model} into GPU memory" "" 0 _phase12_vllm_wait_status || rc=$?
reason="$(cat "$reason_file")"
rm -f -- "$reason_file"
case "$rc" in
0)
ui_status_line ok "vLLM engine ready (${model})"
;;
2)
_phase12_vllm_stop "vLLM did not finish loading ${model} within $((limit / 60)) minutes." \
"See what it is doing with: docker logs --tail 100 ods-vllm-server. Once it reports the model loaded, run the same install command again; the downloaded model is kept."
;;
*)
_phase12_vllm_stop "${reason:-vLLM stopped before ${model} was ready}." \
"vLLM's log says why (docker logs --tail 100 ods-vllm-server; also saved to ${LOG_FILE}). Fix that, for example by freeing the GPU's memory, then run the same install command again; the downloaded model is kept."
;;
esac
}
# True when the chat completion in FILE carries text (an answer, or reasoning
# a short reply can stop in).
_phase12_completion_has_text() {
"${ODS_PYTHON_CMD:-python3}" -c '
import json
import sys
try:
with open(sys.argv[1], encoding="utf-8") as handle:
body = json.load(handle)
except (OSError, ValueError):
sys.exit(1)
choices = body.get("choices") if isinstance(body, dict) else None
first = choices[0] if isinstance(choices, list) and choices else None
message = first.get("message") if isinstance(first, dict) else None
texts = [message.get(key) for key in ("content", "reasoning_content", "reasoning")] if isinstance(message, dict) else []
sys.exit(0 if any(isinstance(text, str) and text.strip() for text in texts) else 1)
' "$1"
}
# Run in the background under spin_task: asks ods/current for a short answer
# through LiteLLM, which sends it to model-router, which routes it to the vLLM
# engine, the path every ODS service uses. Returns 0 once an answer has text,
# 2 when the wait ran out; the last HTTP status goes to STATUS_FILE and the
# last reply to the install log.
_phase12_poll_vllm_route() {
local status_file="$1" interval="${ODS_VLLM_POLL_SECONDS:-10}"
local deadline=$((SECONDS + ${ODS_VLLM_ROUTE_TIMEOUT_SECONDS:-900}))
local port="${SERVICE_PORTS[litellm]:-4000}" key="${LITELLM_KEY:-$(_phase12_env_get LITELLM_KEY "")}"
local body='{"model":"ods/current","messages":[{"role":"user","content":"Reply with exactly OK."}],"max_tokens":64,"temperature":0,"stream":false,"chat_template_kwargs":{"enable_thinking":false}}'
local response_file http_status="000"
response_file="$(mktemp "${TMPDIR:-/tmp}/ods-vllm-route.XXXXXX")"
while (( SECONDS < deadline )); do
if ! http_status="$(_phase12_curl_bearer "$key" -sS --max-time 120 -o "$response_file" -w '%{http_code}' \
-X POST "http://127.0.0.1:${port}/v1/chat/completions" \
-H "Content-Type: application/json" -d "$body" 2>>"$LOG_FILE")"; then
http_status="000"
fi
printf '%s' "$http_status" > "$status_file"
if [[ "$http_status" == 2?? ]] && _phase12_completion_has_text "$response_file"; then
rm -f -- "$response_file"
return 0
fi
sleep "$interval"
done
{
printf 'vLLM model route check, last reply (HTTP %s):\n' "$http_status"
head -c 4096 "$response_file"
printf '\n'
} >> "$LOG_FILE"
rm -f -- "$response_file"
return 2
}
_phase12_vllm_route_status() {
printf 'waiting for the model route'
}
_phase12_verify_vllm_route() {
local model="${VLLM_SERVED_MODEL:-the vLLM model}" limit="${ODS_VLLM_ROUTE_TIMEOUT_SECONDS:-900}"
local status_file pid rc=0 http_status
status_file="$(mktemp "${TMPDIR:-/tmp}/ods-vllm-route-status.XXXXXX")"
_phase12_poll_vllm_route "$status_file" &
pid=$!
spin_task "$pid" "Asking ${model} for a first answer through model-router" "" 0 _phase12_vllm_route_status || rc=$?
http_status="$(cat "$status_file")"
rm -f -- "$status_file"
if [[ "$rc" -eq 0 ]]; then
ui_status_line ok "Model route verified: ods/current answers through model-router (vLLM)"
return 0
fi
_phase12_vllm_stop "vLLM is running, but ${model} did not answer through LiteLLM and model-router within $((limit / 60)) minutes (last HTTP status ${http_status:-none})." \
"The ODS host agent proves the vLLM route once the engine is up. Check ods status, then run the same install command again; the model stays downloaded. The last reply is saved to ${LOG_FILE}."
}
# Core service health checks with adaptive timeouts.
# Cloud mode does not launch local llama-server; LiteLLM/external APIs are the
# LLM surface, so do not wait on a container that intentionally is not running.
if _phase12_external_llm; then
ods_progress 86 "health" "Verifying external LLM route"
if ! _phase12_verify_external_llm_completion; then
exit 1
fi
elif [[ "${ODS_MODE:-local}" == "cloud" ]] || _phase12_host_native_llm; then
ods_progress 86 "health" "Waiting for LiteLLM gateway"
_check_health "LiteLLM" "http://127.0.0.1:${SERVICE_PORTS[litellm]:-4000}${SERVICE_HEALTH[litellm]:-/health/readiness}" 60 10 "$(sr_container litellm)"
if _phase12_host_native_llm; then
ods_progress 87 "health" "Verifying the host-native llama-server route"
if ! _phase12_verify_host_native_llm_completion; then
exit 1
fi
fi
elif _phase12_vllm_engine; then
# No llama-server runs here: wait for the vLLM engine, then for an answer
# through model-router, the route every consumer uses.
ods_progress 86 "health" "Waiting for the vLLM engine"
_phase12_wait_for_vllm
ods_progress 87 "health" "Verifying the model route"
_phase12_verify_vllm_route
else
# Format: _check_health "name" "url" max_attempts timeout_per_request
# llama-server: 150 attempts * adaptive backoff (2s->8s) = up to ~20 minutes (model loading can be slow)
_llm_health_attempts=150
if [[ "${COMPOSE_STARTED_WITH_DELAYED_HEALTH:-false}" == "true" ]]; then
# If phase 11 already saw Docker Compose outlive its own health-gate
# window, keep the installer in the long readiness loop instead of
# failing right as very large GGUFs finish loading after reinstall.
_llm_health_attempts="${ODS_LLM_DELAYED_HEALTH_ATTEMPTS:-300}"
fi
# When a background model upgrade is in progress the bootstrap model is
# already serving and healthy — the full model will hot-swap automatically
# once the download finishes. Blocking here would fail the installer on
# hosts where the full model download + swap exceeds the health window
# (e.g. tower2 with a 24 GB GGUF after a ComfyUI rebuild).
_bootstrap_status_file="${INSTALL_DIR}/data/bootstrap-status.json"
_model_download_active=false
if [[ -f "$_bootstrap_status_file" ]]; then
_bs_status="$(grep -o '"status"[[:space:]]*:[[:space:]]*"[^"]*"' "$_bootstrap_status_file" 2>/dev/null | head -1 | cut -d'"' -f4)"
case "$_bs_status" in
starting|downloading|verifying|swapping)
_model_download_active=true
;;
esac
fi
if [[ "$_model_download_active" != "true" ]] && command -v bg_task_status >/dev/null 2>&1; then
if bg_task_status "full-model-download" >/dev/null 2>&1; then
_model_download_active=true
fi
fi
if [[ "$_model_download_active" == "true" ]]; then
ai_ok "Full model upgrade in progress — skipping blocking LLM health wait"
ai " Monitor progress: tail -f ${INSTALL_DIR}/logs/model-upgrade.log"
else
ods_progress 86 "health" "Waiting for LLM engine"
_check_health "llama-server" "http://127.0.0.1:${SERVICE_PORTS[llama-server]:-8080}${SERVICE_HEALTH[llama-server]:-/health}" "$_llm_health_attempts" 15 "$(sr_container llama-server)"
fi
fi
# ── Pre-warm the LLM slot so the first real chat doesn't 503 ──
#
# /health goes green once the model is mmap'd, but the FIRST chat
# completion still materializes the KV cache, JIT-compiles fused kernels,
# and processes any system prompt the caller injects. While that's in
# flight, llama-server returns `HTTP 503: Loading model` to concurrent
# requests — including from Hermes Agent, which sends a ~14k-token system
# prompt and only retries 3 times within 120s. On big-model + single-GPU
# boxes (DGX Spark with the 45 GB qwen3-coder-next, tested 2026-05-12),
# that 14k prefill alone takes ~54s — fitting inside Hermes's first-call
# window only by luck. Roll the dice the wrong way and Hermes 503s every
# prompt for the rest of the install run.
#
# Pre-warming with a tiny dummy completion forces the slot through its
# cold path inside the installer (where time isn't surprising) so Hermes
# lands on an already-hot slot. Bounded by curl --max-time so a stalled
# llama-server doesn't hang phase 12.
if [[ "${ODS_MODE:-local}" == "cloud" ]] || _phase12_host_native_llm || _phase12_external_llm; then
ai "The LLM runs outside the stack - skipping local llama-server pre-warm"
elif _phase12_vllm_engine; then
log "The vLLM engine already answered the model route check; there is no llama-server to pre-warm"
else
ods_progress 87 "health" "Pre-warming LLM slot"
# llama-server serves the GGUF file name (--alias) under /v1 on every GPU.
_prewarm_model="${GGUF_FILE:-${LLM_MODEL:-default}}"
_prewarm_url="http://127.0.0.1:${SERVICE_PORTS[llama-server]:-8080}/v1/chat/completions"
_prewarm_body="{\"model\":\"${_prewarm_model}\",\"messages\":[{\"role\":\"user\",\"content\":\"hi\"}],\"max_tokens\":1,\"temperature\":0,\"stream\":false}"
if curl -sf --max-time 120 -X POST "$_prewarm_url" \
-H "Content-Type: application/json" \
-d "$_prewarm_body" >/dev/null 2>&1; then
ai_ok "LLM slot pre-warmed (first real chat will be fast)"
else
ai_warn "LLM pre-warm timed out — first Hermes prompt may need a retry or two while the slot finishes warming."
fi
fi
# Open WebUI: 150 attempts * adaptive backoff = up to ~20 minutes
if [[ "${ENABLE_OPEN_WEBUI:-true}" == "true" ]]; then
ods_progress 89 "health" "Waiting for Chat UI"
_check_health "Open WebUI" "http://127.0.0.1:${SERVICE_PORTS[open-webui]:-3000}${SERVICE_HEALTH[open-webui]:-/}" 150 10 "$(sr_container open-webui)"
fi
# Perplexica: 150 attempts * adaptive backoff = up to ~20 minutes
if [[ "${ENABLE_PERPLEXICA:-false}" == "true" ]]; then
ods_progress 91 "health" "Waiting for Research engine"
_check_health "Perplexica" "http://127.0.0.1:${SERVICE_PORTS[perplexica]:-3004}${SERVICE_HEALTH[perplexica]:-/}" 150 10 "$(sr_container perplexica)"
fi
# ComfyUI: 150 attempts * adaptive backoff = up to ~20 minutes.
if [[ "$ENABLE_COMFYUI" == "true" ]]; then
ods_progress 93 "health" "Waiting for Image generation"
_check_health "ComfyUI" "http://127.0.0.1:${SERVICE_PORTS[comfyui]:-8188}${SERVICE_HEALTH[comfyui]:-/}" 150 15 "$(sr_container comfyui)"
fi
# Embeddings (TEI): 150 attempts * adaptive backoff = up to ~20 minutes.
# Matches every other service. The 30-attempt cap (~230s total) used to
# print spurious "embeddings delayed (may still be starting)" warnings on
# fresh installs because TEI downloads its ONNX model from HuggingFace on
# first start (BAAI/bge-base-en-v1.5 is ~440 MB), which can take 3-7 min
# on bufferbloated networks before /health responds.
if [[ "${ENABLE_EMBEDDINGS:-${ENABLE_RAG:-false}}" == "true" ]]; then
ods_progress 94 "health" "Waiting for Embeddings"
if ! check_service "embeddings" "http://127.0.0.1:${SERVICE_PORTS[embeddings]:-8090}${SERVICE_HEALTH[embeddings]:-/health}" 150 10 "$(sr_container embeddings)"; then
HEALTH_FAILURES=$((HEALTH_FAILURES + 1))
EMBEDDINGS_HEALTH_FAILED=true
fi
fi
# Perplexica auto-config: seed chat model + embedding model on first boot.
# The slim-latest image stores config in a database, not just config.json.
# We use the /api/config HTTP endpoint to set values after the service starts.
# Retry up to 5 times with 10s delay — Perplexica may still be starting
# (especially if it was stuck in "Created" state and started late).
if $DOCKER_CMD inspect ods-perplexica &>/dev/null; then
PERPLEXICA_URL="http://127.0.0.1:${SERVICE_PORTS[perplexica]:-3004}"
_perplexica_switchboard_mode="$(printf '%s' "${ODS_MODEL_SWITCHBOARD:-enabled}" | tr '[:upper:]' '[:lower:]')"
PERPLEXICA_MODEL="${LLM_MODEL:-default}"
if [[ -n "${EXTERNAL_LLM_URL:-}" && -n "${EXTERNAL_LLM_MODEL:-}" ]]; then
# Generic external installs intentionally keep the local tier GGUF
# metadata for recommendations. It must not replace the exact model
# selected from the external provider in Perplexica's persisted route.
PERPLEXICA_MODEL="$EXTERNAL_LLM_MODEL"
elif [[ -n "${GGUF_FILE:-}" ]]; then
# llama-server serves the GGUF file name (--alias) on every runtime.
PERPLEXICA_MODEL="$GGUF_FILE"
fi
PERPLEXICA_LLM_BASE_URL="${LLM_API_URL:-http://llama-server:8080}"
if [[ "$_perplexica_switchboard_mode" == "enabled" ]]; then
PERPLEXICA_MODEL="ods/current"
PERPLEXICA_LLM_BASE_URL="http://litellm:4000/v1"
fi
case "$PERPLEXICA_LLM_BASE_URL" in
*/v1|*/api/v1) ;;
*) PERPLEXICA_LLM_BASE_URL="${PERPLEXICA_LLM_BASE_URL%/}/v1" ;;
esac
PERPLEXICA_API_KEY="${LITELLM_KEY:-${OPENAI_API_KEY:-no-key}}"
PYTHON_CMD="python3"
if [[ -f "$SCRIPT_DIR/lib/python-cmd.sh" ]]; then
. "$SCRIPT_DIR/lib/python-cmd.sh"
PYTHON_CMD="$(ods_detect_python_cmd)"
elif command -v python >/dev/null 2>&1; then
PYTHON_CMD="python"
fi
PERPLEXICA_SETUP="skip"
for _attempt in 1 2 3 4 5; do
PERPLEXICA_SETUP=$(curl -sf --max-time 5 "${PERPLEXICA_URL}/api/config" 2>/dev/null | \
PERPLEXICA_MODEL="$PERPLEXICA_MODEL" "$PYTHON_CMD" -c '
import os, sys, json
values = json.load(sys.stdin).get("values", {})
model = os.environ["PERPLEXICA_MODEL"]
providers = values.get("modelProviders", [])
openai_prov = next((p for p in providers if p.get("type") == "openai"), {})
chat_models = openai_prov.get("chatModels") or []
prefs = values.get("preferences") or {}
has_model = any(m.get("key") == model or m.get("name") == model for m in chat_models)
is_ready = bool(values.get("setupComplete")) and has_model and prefs.get("defaultChatModel") == model
print("done" if is_ready else "needed")
' 2>/dev/null || echo "skip")
[[ "$PERPLEXICA_SETUP" != "skip" ]] && break
[[ $_attempt -lt 5 ]] && sleep 10
done
if [[ "$PERPLEXICA_SETUP" == "needed" ]]; then
ai "Configuring Perplexica for ${PERPLEXICA_MODEL}..."
# Query current config to get provider UUIDs, then set model + preferences via API
curl -sf "${PERPLEXICA_URL}/api/config" 2>/dev/null | \
PERPLEXICA_URL="$PERPLEXICA_URL" \
PERPLEXICA_MODEL="$PERPLEXICA_MODEL" \
PERPLEXICA_LLM_BASE_URL="$PERPLEXICA_LLM_BASE_URL" \
PERPLEXICA_API_KEY="$PERPLEXICA_API_KEY" \
"$PYTHON_CMD" -c '
import os
import sys, json, urllib.request
config = json.load(sys.stdin)["values"]
providers = config.get("modelProviders", [])
openai_index = next((i for i, p in enumerate(providers) if p["type"] == "openai"), None)
openai_prov = providers[openai_index] if openai_index is not None else None
transformers_prov = next((p for p in providers if p["type"] == "transformers"), None)
if not openai_prov:
print("no-openai-provider")
sys.exit(1)
url = os.environ["PERPLEXICA_URL"] + "/api/config"
model = os.environ["PERPLEXICA_MODEL"]
base_url = os.environ["PERPLEXICA_LLM_BASE_URL"]
api_key = os.environ["PERPLEXICA_API_KEY"] or "no-key"
def post(key, value):
data = json.dumps({"key": key, "value": value}).encode()
req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
urllib.request.urlopen(req, timeout=10)
def post_setup_complete():
setup_url = os.environ["PERPLEXICA_URL"] + "/api/config/setup-complete"
req = urllib.request.Request(setup_url, data=b"{}", headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=10)
except Exception:
post("setupComplete", True)
# Seed the chat model into the OpenAI provider and set auth config
openai_prov["chatModels"] = [{"key": model, "name": model}]
openai_prov["config"] = {
**(openai_prov.get("config") or {}),
"apiKey": api_key,
"baseURL": base_url,
}
# GET includes Vane-built-in models. Write only route fields for this provider.
post(f"modelProviders.{openai_index}.chatModels", openai_prov["chatModels"])
post(f"modelProviders.{openai_index}.config", openai_prov["config"])
# Set default providers and models
post("preferences", {
"defaultChatProvider": openai_prov["id"],
"defaultChatModel": model,
"defaultEmbeddingProvider": transformers_prov["id"] if transformers_prov else openai_prov["id"],
"defaultEmbeddingModel": "Xenova/all-MiniLM-L6-v2"
})
# Mark setup complete to bypass the wizard
post_setup_complete()
print("ok")
' >> "$LOG_FILE" 2>&1 && \
ui_status_line ok "Perplexica configured (model: ${PERPLEXICA_MODEL})" || \
ui_status_line warn "Perplexica config — complete setup at :${PERPLEXICA_PORT:-3004}"
fi
fi
# Extension service health checks with adaptive timeouts
ods_progress 94 "health" "Checking extension services"
# Hermes is intentionally internal-only: its port is exposed only inside the
# Docker network, not bound to the host. Wait on the container healthcheck
# instead of curling localhost:9119, which would fail on a correct install.
if [[ "$ENABLE_HERMES" == "true" ]]; then
if ! _check_container_health "Hermes Agent" "$(sr_container hermes)" 60; then
HEALTH_FAILURES=$((HEALTH_FAILURES + 1))
fi
fi
# hermes-proxy is the LAN-facing entry and has an anonymous /health endpoint.
[[ "$ENABLE_HERMES" == "true" ]] && _check_health "Hermes Proxy" "http://127.0.0.1:${SERVICE_PORTS[hermes-proxy]:-9120}${SERVICE_HEALTH[hermes-proxy]:-/health}" 60 5 "$(sr_container hermes-proxy)"
if [[ "${ENABLE_PIXEL_RUNTIME:-false}" == "true" ]]; then
_pixel_owner="${PIXEL_SERVICE_USER:-$(ods_pixel_install_owner 2>/dev/null || true)}"
_pixel_home=""
[[ -n "$_pixel_owner" ]] && _pixel_home="$(ods_pixel_owner_home "$_pixel_owner" 2>/dev/null || true)"
if [[ -z "$_pixel_home" ]] \
|| ! systemctl is-active --quiet openclaw-gateway.service pixel-ingress.service \
|| ! ods_pixel_run_as_owner "$_pixel_owner" "$_pixel_home" curl --fail --silent --show-error --max-time 10 \
--unix-socket /run/ods-pixel/pixel-ingress.sock http://localhost/health >/dev/null; then
ai_warn "Pixel gateway or private host ingress did not pass its health check."
HEALTH_FAILURES=$((HEALTH_FAILURES + 1))
else
printf " ${BGRN}OK${NC} %-56s\n" "Pixel private ingress healthy"
fi
if ! _check_container_health "Pixel Edge" "$(sr_container pixel-edge)" 60; then
HEALTH_FAILURES=$((HEALTH_FAILURES + 1))
fi
fi
if [[ "${ENABLE_OPENCODE:-false}" == "true" ]]; then
ods_systemctl_user is-active opencode-web &>/dev/null && _check_health "OpenCode Web" "http://127.0.0.1:3003/" 10 5
fi
# Whisper: 150 attempts * adaptive backoff = up to ~20 minutes (model download on first start)
ods_progress 95 "health" "Checking voice services"
[[ "$ENABLE_VOICE" == "true" ]] && _check_health "Whisper (STT)" "http://127.0.0.1:${SERVICE_PORTS[whisper]:-9000}${SERVICE_HEALTH[whisper]:-/health}" 150 10 "$(sr_container whisper)"
[[ "$ENABLE_VOICE" == "true" ]] && _check_health "Kokoro (TTS)" "http://127.0.0.1:${SERVICE_PORTS[tts]:-8880}${SERVICE_HEALTH[tts]:-/health}" 150 10 "$(sr_container tts)"
# Pre-download the Whisper STT model so first transcription is instant.
# Speaches does NOT auto-download on transcription requests — it returns 404.
# We must trigger the download explicitly here, verify it completed, and
# surface a clear recovery command if anything fails.
if [[ "$ENABLE_VOICE" == "true" ]]; then
# Prefer AUDIO_STT_MODEL from .env (written by Phase 06). Fall back to the
# GPU_BACKEND switch for backward compat with older .env files missing it.
if [[ -n "${AUDIO_STT_MODEL:-}" ]]; then
STT_MODEL="$AUDIO_STT_MODEL"
elif [[ "$GPU_BACKEND" == "nvidia" && "${WHISPER_ACCELERATION:-cuda}" == "cuda" ]]; then
STT_MODEL="deepdml/faster-whisper-large-v3-turbo-ct2"
else
STT_MODEL="Systran/faster-whisper-base"
fi
STT_MODEL_ENCODED="${STT_MODEL//\//%2F}"
WHISPER_PORT_RESOLVED="${SERVICE_PORTS[whisper]:-9000}"
WHISPER_URL="http://127.0.0.1:${WHISPER_PORT_RESOLVED}"
STT_MODEL_URL="${WHISPER_URL}/v1/models/${STT_MODEL_ENCODED}"
STT_TRIGGER_TIMEOUT_SECONDS="${ODS_STT_TRIGGER_TIMEOUT_SECONDS:-30}"
STT_CACHE_WAIT_SECONDS="${ODS_STT_CACHE_WAIT_SECONDS:-900}"
[[ "$STT_TRIGGER_TIMEOUT_SECONDS" =~ ^[1-9][0-9]*$ ]] || STT_TRIGGER_TIMEOUT_SECONDS=30
[[ "$STT_CACHE_WAIT_SECONDS" =~ ^[1-9][0-9]*$ ]] || STT_CACHE_WAIT_SECONDS=900
STT_RECOVERY_CMD="curl --max-time ${STT_TRIGGER_TIMEOUT_SECONDS} -X POST ${STT_MODEL_URL}"
_stt_model_cached() {
local _url="$1"
curl -sf --max-time 10 "$_url" &>/dev/null
}
_trigger_stt_model_download() {
local _url="$1"
local _rc=0
# Speaches can keep downloading after the request is accepted. Keep the
# client bounded, then use the cache endpoint as the strict source of truth.
curl -sS --fail --max-time "${STT_TRIGGER_TIMEOUT_SECONDS}" -X POST "$_url" \
>> "$LOG_FILE" 2>&1 || _rc=$?
if [[ "$_rc" -eq 0 || "$_rc" -eq 28 ]]; then
return 0
fi
ai_warn "STT model download trigger returned curl exit ${_rc}; verifying cache before failing."
return 1
}
_wait_stt_model_cached() {
local _url="$1"
local _deadline=$((SECONDS + STT_CACHE_WAIT_SECONDS))
while (( SECONDS < _deadline )); do
if _stt_model_cached "$_url"; then
return 0
fi
sleep 5
done
_stt_model_cached "$_url"
}
# Step 1: wait briefly for the models API to be ready. Whisper's /health
# endpoint can pass before the models endpoint responds, so we probe
# GET /v1/models with a short retry loop (max 15s total).
_stt_api_ready=false
for _i in $(seq 1 15); do
if curl -sf --max-time 2 "${WHISPER_URL}/v1/models" &>/dev/null; then
_stt_api_ready=true
break
fi
sleep 1
done
if ! $_stt_api_ready; then
ui_status_line warn "STT models API not ready — download manually:"
printf " %s\n" "$STT_RECOVERY_CMD"
# Step 2: skip download if already cached.
elif _stt_model_cached "$STT_MODEL_URL"; then
ui_status_line ok "STT model already cached (${STT_MODEL})"
else
# Step 3: POST to trigger download. Log stdout/stderr to install log.
ai "Downloading STT model (${STT_MODEL})..."
_trigger_stt_model_download "$STT_MODEL_URL" || true
# Step 4: verify the model is actually cached. POST can return 200
# even if the download partially fails, so this GET is the real test.
if _wait_stt_model_cached "$STT_MODEL_URL"; then
ui_status_line ok "STT model cached (${STT_MODEL})"
else
ui_status_line warn "STT model download failed — run manually:"
printf " %s\n" "$STT_RECOVERY_CMD"
printf " %s\n" "See $LOG_FILE for details."
fi
fi
fi
ods_progress 96 "health" "Checking workflow and RAG services"
[[ "$ENABLE_WORKFLOWS" == "true" ]] && _check_health "n8n" "http://127.0.0.1:${SERVICE_PORTS[n8n]:-5678}${SERVICE_HEALTH[n8n]:-/healthz}" 150 10 "$(sr_container n8n)"
[[ "${ENABLE_QDRANT:-${ENABLE_RAG:-false}}" == "true" ]] && _check_health "Qdrant" "http://127.0.0.1:${SERVICE_PORTS[qdrant]:-6333}${SERVICE_HEALTH[qdrant]:-/}" 150 10 "$(sr_container qdrant)"
ods_progress 97 "health" "Health checks complete"
echo ""
if [[ "$HEALTH_FAILURES" -gt 0 ]]; then
ai_warn "${HEALTH_FAILURES} service(s) did not pass health checks."
ai_warn "Some services may still be starting. Check with: ods status"
ai_warn "Logs: docker compose logs <service-name>"
if [[ "$EMBEDDINGS_HEALTH_FAILED" == "true" ]]; then
ai_warn "Embeddings/RAG was selected, but the embeddings service did not become healthy."
ai_warn "This often means text-embeddings-inference stalled while downloading its ONNX model from Hugging Face."
ai_warn "Recovery: cd \"$INSTALL_DIR\" && ./ods-cli logs embeddings"
ai_warn "Then retry after network/CDN recovery: cd \"$INSTALL_DIR\" && ./ods-cli start embeddings"
exit 1
fi
if [[ "${COMPOSE_STARTED_WITH_DELAYED_HEALTH:-false}" == "true" ]]; then
ai_warn "Docker Compose reported delayed LLM health during launch, and the longer health checks did not recover."
exit 1
fi
else
signal "All systems nominal."
ai_ok "Sovereign intelligence is online."
fi