#!/usr/bin/env bash set -euo pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" ROOT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)" log_info() { echo "[finalize] $*"; } log_warn() { echo "[finalize] WARN: $*" >&2; } log_err() { echo "[finalize] ERROR: $*" >&2; } require_cmd() { local cmd="$1" if ! command -v "$cmd" >/dev/null 2>&1; then log_err "Missing required command: $cmd" exit 1 fi } copilot_authed() { copilot auth status >/dev/null 2>&1 } refresh_models() { openclaw models refresh >/dev/null 2>&1 || true } copilot_model_count() { openclaw models list 2>/dev/null \ | awk 'NR>1 && /^github-copilot\// {count++} END {print count+0}' } require_cmd openclaw require_cmd copilot require_cmd jq if ! copilot_authed; then log_warn "Copilot auth is not active." if [[ -t 0 ]]; then log_info "Launching interactive login: copilot auth login" copilot auth login else log_err "Non-interactive shell cannot complete browser login." log_err "Run: copilot auth login" exit 1 fi fi if ! copilot_authed; then log_err "Copilot auth still not active after login." log_err "Run 'copilot auth status' and resolve auth issues, then retry." exit 1 fi log_info "Refreshing model catalog..." refresh_models count="$(copilot_model_count)" if [[ "$count" -eq 0 ]]; then log_warn "No github-copilot models detected yet. Restarting gateway and retrying once." openclaw gateway restart >/dev/null 2>&1 || true sleep 1 refresh_models count="$(copilot_model_count)" fi if [[ "$count" -eq 0 ]]; then log_err "No github-copilot models available to configure." log_err "Check entitlement/auth, then rerun this script." openclaw models list || true exit 1 fi log_info "Detected $count Copilot model(s). Installing guardrails + model profiles..." bash "$SCRIPT_DIR/install_copilot_guardrails.sh" log_info "Enabling recommended hooks..." openclaw hooks enable boot-md >/dev/null 2>&1 || true openclaw hooks enable command-logger >/dev/null 2>&1 || true openclaw hooks enable session-memory >/dev/null 2>&1 || true log_info "Restarting gateway..." openclaw gateway restart >/dev/null 2>&1 || true log_info "Final status checks:" copilot auth status || true openclaw models status || true for label in \ ai.openclaw.model-budget-guard \ ai.openclaw.copilot-policy-guard \ ai.openclaw.copilot-auth-watchdog \ ai.openclaw.copilot-model-schedule-guard; do if launchctl print "gui/$(id -u)/$label" >/dev/null 2>&1; then echo "[finalize] launchd OK: $label" else echo "[finalize] launchd WARN: $label not loaded" fi done log_info "Done. Copilot setup is fully configured."