#!/usr/bin/env bash # Bootstrap OmniRoute management auth and provider connections. # This script intentionally never prints secret values. set -euo pipefail INSTALL_DIR="${LAB_AI_STACK_INSTALL_DIR:-/data/homelab-ai-stack}" ENV_FILE="${LAB_AI_STACK_ENV_FILE:-${INSTALL_DIR}/.env}" PORT="${LAB_OMNIROUTE_PORT:-20128}" BASE_URL="${LAB_AI_STACK_OMNIROUTE_BASE_URL:-http://127.0.0.1:${PORT}}" OPENROUTER_URL="${LAB_AI_STACK_OPENROUTER_URL:-https://openrouter.ai/api/v1}" NVIDIA_URL="${LAB_AI_STACK_NVIDIA_URL:-https://integrate.api.nvidia.com/v1}" MODEL_ROUTES_FILE="${LAB_AI_STACK_MODEL_ROUTES_FILE:-${INSTALL_DIR}/models.env}" OMNIROUTE_BOOTSTRAP_TMP_DIR="" if [[ ! -s "${ENV_FILE}" ]]; then echo "Missing ${ENV_FILE}; run seed-secrets.sh first." >&2 exit 1 fi env_value() { local key="$1" awk -F= -v key="${key}" '$1 == key { sub(/^[^=]*=/, ""); print; found = 1 } END { exit found ? 0 : 1 }' "${ENV_FILE}" } cleanup() { if [[ -n "${OMNIROUTE_BOOTSTRAP_TMP_DIR}" && -d "${OMNIROUTE_BOOTSTRAP_TMP_DIR}" ]]; then rm -rf "${OMNIROUTE_BOOTSTRAP_TMP_DIR}" fi } trap cleanup EXIT wait_for_omniroute() { local status for _ in $(seq 1 30); do status="$(curl -sS -o /dev/null -w '%{http_code}' --connect-timeout 2 --max-time 5 "${BASE_URL}/api/auth/status" 2>/dev/null || true)" case "${status}" in 200 | 401 | 403) return 0 ;; esac sleep 2 done echo "OmniRoute did not become reachable at ${BASE_URL}." >&2 exit 1 } login_omniroute() { local password="$1" local cookie_jar="$2" local body_file="$3" local headers_file="$4" local status status="$( PASSWORD="${password}" python3 - <<'PY' | import json import os print(json.dumps({"password": os.environ["PASSWORD"]})) PY curl -sS \ -D "${headers_file}" \ -c "${cookie_jar}" \ -o "${body_file}" \ -w '%{http_code}' \ -H 'Content-Type: application/json' \ -X POST \ --data-binary @- \ "${BASE_URL}/api/auth/login" )" if [[ "${status}" != "200" ]]; then echo "OmniRoute management login failed with HTTP ${status}." >&2 sed -n '1,3p' "${body_file}" >&2 || true exit 1 fi } extract_auth_header() { local body_file="$1" local token token="$( python3 - "${body_file}" <<'PY' 2>/dev/null || true import json import sys with open(sys.argv[1], encoding="utf-8") as fh: data = json.load(fh) for key in ("token", "accessToken", "jwt", "authToken"): value = data.get(key) if isinstance(value, str) and value: print(value) break PY )" if [[ -n "${token}" ]]; then printf 'Authorization: Bearer %s\n' "${token}" fi } provider_id_for() { local cookie_jar="$1" local auth_header="$2" local provider="$3" local name="$4" local body_file="$5" if [[ -n "${auth_header}" ]]; then curl -fsS -b "${cookie_jar}" -H "${auth_header}" "${BASE_URL}/api/providers" -o "${body_file}" else curl -fsS -b "${cookie_jar}" "${BASE_URL}/api/providers" -o "${body_file}" fi python3 - "${body_file}" "${provider}" "${name}" <<'PY' import json import sys path, provider, name = sys.argv[1:4] with open(path, encoding="utf-8") as fh: data = json.load(fh) for item in data.get("connections", []) or []: if item.get("provider") == provider and item.get("name") == name: print(item.get("id", "")) sys.exit(0) sys.exit(1) PY } create_provider() { local cookie_jar="$1" local auth_header="$2" local provider="$3" local name="$4" local url="$5" local api_key="$6" local body_file="$7" local status status="$( PROVIDER="${provider}" NAME="${name}" URL="${url}" API_KEY="${api_key}" python3 - <<'PY' | import json import os print(json.dumps({ "provider": os.environ["PROVIDER"], "name": os.environ["NAME"], "url": os.environ["URL"], "apiKey": os.environ["API_KEY"], "isActive": True, "maxConcurrent": 2, })) PY if [[ -n "${auth_header}" ]]; then curl -sS -b "${cookie_jar}" -H "${auth_header}" -o "${body_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @- "${BASE_URL}/api/providers" else curl -sS -b "${cookie_jar}" -o "${body_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @- "${BASE_URL}/api/providers" fi )" if [[ "${status}" != "201" && "${status}" != "200" ]]; then echo "Failed to create OmniRoute provider ${provider} (${name}); HTTP ${status}." >&2 sed -n '1,3p' "${body_file}" >&2 || true exit 1 fi } upsert_provider() { local cookie_jar="$1" local auth_header="$2" local provider="$3" local name="$4" local url="$5" local api_key="$6" local body_file="$7" if [[ -z "${api_key}" ]]; then echo "OmniRoute provider ${provider}: skipped; key missing" return 0 fi if provider_id_for "${cookie_jar}" "${auth_header}" "${provider}" "${name}" "${body_file}" >/dev/null 2>&1; then echo "OmniRoute provider ${provider}: already configured" return 0 fi create_provider "${cookie_jar}" "${auth_header}" "${provider}" "${name}" "${url}" "${api_key}" "${body_file}" echo "OmniRoute provider ${provider}: configured" } api_get() { local cookie_jar="$1" local auth_header="$2" local path="$3" local output_file="$4" if [[ -n "${auth_header}" ]]; then curl -fsS -b "${cookie_jar}" -H "${auth_header}" "${BASE_URL}${path}" -o "${output_file}" else curl -fsS -b "${cookie_jar}" "${BASE_URL}${path}" -o "${output_file}" fi } api_post_json() { local cookie_jar="$1" local auth_header="$2" local path="$3" local payload_file="$4" local output_file="$5" if [[ -n "${auth_header}" ]]; then curl -sS -b "${cookie_jar}" -H "${auth_header}" -o "${output_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @"${payload_file}" "${BASE_URL}${path}" else curl -sS -b "${cookie_jar}" -o "${output_file}" -w '%{http_code}' -H 'Content-Type: application/json' -X POST --data-binary @"${payload_file}" "${BASE_URL}${path}" fi } discover_model_routes() { local openrouter_key="$1" local nvidia_key="$2" local output_json="$3" OPENROUTER_KEY="${openrouter_key}" NVIDIA_KEY="${nvidia_key}" OPENROUTER_URL="${OPENROUTER_URL}" NVIDIA_URL="${NVIDIA_URL}" python3 - "${output_json}" <<'PY' import json import os import sys import urllib.error import urllib.request output_path = sys.argv[1] openrouter_key = os.environ.get("OPENROUTER_KEY", "") nvidia_key = os.environ.get("NVIDIA_KEY", "") openrouter_url = os.environ["OPENROUTER_URL"].rstrip("/") nvidia_url = os.environ["NVIDIA_URL"].rstrip("/") def fetch_json(url, token=""): headers = {"Accept": "application/json"} if token: headers["Authorization"] = f"Bearer {token}" request = urllib.request.Request(url, headers=headers) try: with urllib.request.urlopen(request, timeout=20) as response: return json.load(response) except (OSError, urllib.error.HTTPError, json.JSONDecodeError): return {} def as_float(value): try: return float(value) except (TypeError, ValueError): return None def priority(model): lower = model.lower() scores = [ ("qwen", 0), ("llama-3.1-8b", 1), ("llama-3", 2), ("mistral", 3), ("gemma", 4), ("deepseek", 5), ] for needle, score in scores: if needle in lower: return score return 99 openrouter_models = [] if openrouter_key: for item in fetch_json(f"{openrouter_url}/models", openrouter_key).get("data", []) or []: model_id = item.get("id") if not isinstance(model_id, str) or not model_id: continue pricing = item.get("pricing") or {} prompt = as_float(pricing.get("prompt")) completion = as_float(pricing.get("completion")) zero_priced = prompt == 0.0 and completion == 0.0 if model_id.endswith(":free") or zero_priced: openrouter_models.append(f"openrouter/{model_id}") openrouter_models = sorted(set(openrouter_models), key=lambda value: (priority(value), value)) nvidia_models = [] if nvidia_key: for item in fetch_json(f"{nvidia_url}/models", nvidia_key).get("data", []) or []: model_id = item.get("id") if isinstance(model_id, str) and model_id: nvidia_models.append(model_id if model_id.startswith("nvidia/") else f"nvidia/{model_id}") nvidia_models = sorted(set(nvidia_models), key=lambda value: (priority(value), value)) fast = (openrouter_models[:4] + nvidia_models[:2])[:6] smart = (nvidia_models[:4] + openrouter_models[:4])[:8] with open(output_path, "w", encoding="utf-8") as fh: json.dump({ "openrouter_free": openrouter_models, "nvidia": nvidia_models, "agent_fast_models": fast, "agent_smart_models": smart, }, fh, indent=2, sort_keys=True) fh.write("\n") PY } combo_id_for() { local cookie_jar="$1" local auth_header="$2" local combo_name="$3" local body_file="$4" api_get "${cookie_jar}" "${auth_header}" "/api/combos" "${body_file}" python3 - "${body_file}" "${combo_name}" <<'PY' import json import sys path, combo_name = sys.argv[1:3] with open(path, encoding="utf-8") as fh: data = json.load(fh) if isinstance(data, dict): candidates = data.get("combos") or data.get("items") or data.get("data") or [] else: candidates = data for item in candidates or []: if isinstance(item, dict) and item.get("name") == combo_name: print(item.get("id", "")) sys.exit(0) sys.exit(1) PY } create_combo() { local cookie_jar="$1" local auth_header="$2" local combo_name="$3" local models_json_file="$4" local payload_file="$5" local body_file="$6" local status python3 - "${combo_name}" "${models_json_file}" "${payload_file}" <<'PY' import json import sys combo_name, models_path, payload_path = sys.argv[1:4] with open(models_path, encoding="utf-8") as fh: models = json.load(fh) with open(payload_path, "w", encoding="utf-8") as fh: json.dump({ "name": combo_name, "models": models, "strategy": "priority", }, fh) PY status="$(api_post_json "${cookie_jar}" "${auth_header}" "/api/combos" "${payload_file}" "${body_file}")" if [[ "${status}" != "201" && "${status}" != "200" ]]; then echo "Failed to create OmniRoute combo ${combo_name}; HTTP ${status}." >&2 sed -n '1,3p' "${body_file}" >&2 || true return 1 fi } upsert_combo() { local cookie_jar="$1" local auth_header="$2" local combo_name="$3" local models_json_file="$4" local body_file="$5" local payload_file="$6" local model_count model_count="$(python3 - "${models_json_file}" <<'PY' import json import sys with open(sys.argv[1], encoding="utf-8") as fh: print(len(json.load(fh))) PY )" if [[ "${model_count}" == "0" ]]; then echo "OmniRoute combo ${combo_name}: skipped; no eligible models discovered" return 0 fi if combo_id_for "${cookie_jar}" "${auth_header}" "${combo_name}" "${body_file}" >/dev/null 2>&1; then echo "OmniRoute combo ${combo_name}: already configured" return 0 fi create_combo "${cookie_jar}" "${auth_header}" "${combo_name}" "${models_json_file}" "${payload_file}" "${body_file}" echo "OmniRoute combo ${combo_name}: configured with ${model_count} free/quota model(s)" } write_model_routes_file() { local routes_json="$1" local fast_json="$2" local smart_json="$3" local output_file="$4" python3 - "${routes_json}" "${fast_json}" "${smart_json}" "${output_file}" <<'PY' import json import sys routes_path, fast_path, smart_path, output_path = sys.argv[1:5] with open(routes_path, encoding="utf-8") as fh: routes = json.load(fh) with open(fast_path, encoding="utf-8") as fh: fast = json.load(fh) with open(smart_path, encoding="utf-8") as fh: smart = json.load(fh) fast_model = "agent-fast-free" if fast else "" smart_model = "agent-smart-free" if smart else fast_model direct_fast = fast[0] if fast else "" direct_smart = smart[0] if smart else direct_fast with open(output_path, "w", encoding="utf-8") as fh: fh.write("# Generated by jeannie deploy-ai-stack. Do not commit.\n") fh.write(f"AI_STACK_AGENT_FAST_MODEL={fast_model}\n") fh.write(f"AI_STACK_AGENT_SMART_MODEL={smart_model}\n") fh.write(f"AI_STACK_AGENT_FAST_DIRECT_MODEL={direct_fast}\n") fh.write(f"AI_STACK_AGENT_SMART_DIRECT_MODEL={direct_smart}\n") fh.write(f"AI_STACK_OPENROUTER_FREE_COUNT={len(routes.get('openrouter_free') or [])}\n") fh.write(f"AI_STACK_NVIDIA_MODEL_COUNT={len(routes.get('nvidia') or [])}\n") PY chmod 0600 "${output_file}" } configure_free_model_routes() { local cookie_jar="$1" local auth_header="$2" local openrouter_key="$3" local nvidia_key="$4" local routes_json="$5" local fast_json="$6" local smart_json="$7" local payload_file="$8" local body_file="$9" discover_model_routes "${openrouter_key}" "${nvidia_key}" "${routes_json}" python3 - "${routes_json}" "${fast_json}" "${smart_json}" <<'PY' import json import sys routes_path, fast_path, smart_path = sys.argv[1:4] with open(routes_path, encoding="utf-8") as fh: routes = json.load(fh) with open(fast_path, "w", encoding="utf-8") as fh: json.dump(routes.get("agent_fast_models") or [], fh) with open(smart_path, "w", encoding="utf-8") as fh: json.dump(routes.get("agent_smart_models") or [], fh) PY upsert_combo "${cookie_jar}" "${auth_header}" "agent-fast-free" "${fast_json}" "${body_file}" "${payload_file}" upsert_combo "${cookie_jar}" "${auth_header}" "agent-smart-free" "${smart_json}" "${body_file}" "${payload_file}" write_model_routes_file "${routes_json}" "${fast_json}" "${smart_json}" "${MODEL_ROUTES_FILE}" echo "OmniRoute model route hints written to ${MODEL_ROUTES_FILE}" } main() { local password openrouter_key nvidia_key cookie_jar headers_file body_file auth_header routes_json fast_json smart_json payload_file password="$(env_value INITIAL_PASSWORD)" openrouter_key="$(env_value OPENROUTER_API_KEY 2>/dev/null || true)" nvidia_key="$(env_value NVIDIA_API_KEY 2>/dev/null || true)" wait_for_omniroute OMNIROUTE_BOOTSTRAP_TMP_DIR="$(mktemp -d)" cookie_jar="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/cookies.txt" headers_file="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/headers.txt" body_file="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/body.json" routes_json="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/routes.json" fast_json="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/fast.json" smart_json="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/smart.json" payload_file="${OMNIROUTE_BOOTSTRAP_TMP_DIR}/payload.json" login_omniroute "${password}" "${cookie_jar}" "${body_file}" "${headers_file}" auth_header="$(extract_auth_header "${body_file}")" upsert_provider "${cookie_jar}" "${auth_header}" "openrouter" "openrouter-seeded" "${OPENROUTER_URL}" "${openrouter_key}" "${body_file}" upsert_provider "${cookie_jar}" "${auth_header}" "nvidia" "nvidia-seeded" "${NVIDIA_URL}" "${nvidia_key}" "${body_file}" configure_free_model_routes "${cookie_jar}" "${auth_header}" "${openrouter_key}" "${nvidia_key}" "${routes_json}" "${fast_json}" "${smart_json}" "${payload_file}" "${body_file}" } main "$@"