#!/usr/bin/env bash # shellcheck shell=bash # # AI assistant integration. # # Design rule: the LLM NEVER manipulates disks and NEVER runs privileged # commands. It may only produce a structured proposal (a flat JSON object). # The deterministic backend validates every field, the change is previewed and # the user must confirm. Most assistant features work with no LLM at all. # # Secrets (API keys, passphrases, passwords) are never passed to the model and # never written to the installation log. # --------------------------------------------------------------------------- # Deterministic (offline) assistance # --------------------------------------------------------------------------- ai_explain_hardware() { { printf 'Detected hardware\n' printf '=================\n\n' hw_report printf '\nRecommended kernel profile: %s\n' "$(hw_recommended_kernel_profile)" printf 'Suggested VIDEO_CARDS: %s\n' "$(portage_detect_video_cards)" } 2>&1 } ai_explain_disks() { { printf 'Disk summary\n' printf '============\n\n' local d for d in "${DISK_LIST[@]}"; do printf '%s\n' "$(disk_display_line "$d")" done printf '\nReading (read-only):\n' if [[ -n "$(config_get TARGET_DISK)" && -b "$(config_get TARGET_DISK)" ]]; then disk_layout_text "$(config_get TARGET_DISK)" else printf ' no target disk selected yet\n' fi } 2>&1 } ai_explain_plan() { plan_generate plan_render } ai_explain_encryption() { cat <<'EOF' Encryption and filesystem choices ================================= LUKS2 (default) The whole root partition is encrypted. Unlocking happens at boot with a passphrase. TPM2 enrollment is planned but not required. Btrfs subvolumes @ the root filesystem @home /home, snapshotted independently @var /var, kept separate so root snapshots stay small @snapshots /.snapshots, where rollback snapshots live @swap holds the swapfile Separate subvolumes let snapshots and rollbacks target only the parts of the system you care about, and keep user data out of root snapshots. zstd compression Transparent compression at level 3. A good balance of CPU and space. EOF } # ai_offline_response QUERY - small deterministic help based on keywords ai_offline_response() { local q q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" case "$q" in *partition*|*disk*|*layout*) ai_explain_disks ;; *encrypt*|*luks*|*btrfs*|*filesystem*) ai_explain_encryption ;; *hardware*|*cpu*|*gpu*|*wifi*|*bluetooth*) ai_explain_hardware ;; *kernel*) printf 'Kernel policy\n=============\n\nProfile: %s\nPackage: %s\n\n%s\n' \ "$(config_get KERNEL_PROFILE)" "$(kernel_select_package)" \ "The distribution kernel is used as a stable, complete base. The installer applies conservative config fragments; it never generates a minimal kernel that only boots the current hardware." ;; *package*|*compile*|*binary*) pkgpolicy_report ;; *plan*|*summary*) ai_explain_plan ;; *log*|*error*|*fail*) log_tail 60 ;; *network*|*internet*) network_status_text ;; *desktop*|*wayland*|*dwl*) printf 'Desktop\n=======\nProfile: %s\n\nBase: dwl (Wayland tiling). Audio: PipeWire + Wireplumber.\nFlatpak: %s\n' \ "$(config_get DESKTOP_PROFILE)" "$(config_get FLATPAK)" ;; *) printf 'I can explain (offline, no model required):\n' printf ' - hardware: detected CPU/GPU/storage/network\n' printf ' - disks: devices and read-only layout\n' printf ' - encryption: LUKS2 and Btrfs subvolumes\n' printf ' - kernel: kernel policy\n' printf ' - packages: compile vs binary policy\n' printf ' - plan: the generated installation plan\n' printf ' - logs: recent installer log lines\n' printf '\nAsk about any of these, or configure a model for free-form help.\n' ;; esac } # --------------------------------------------------------------------------- # Structured proposals # --------------------------------------------------------------------------- # Only these keys may be changed by an AI proposal, and every value is # validated by validation.sh before it is accepted. AI_PROPOSAL_KEYS=(TARGET_DISK ENCRYPTION FILESYSTEM DESKTOP_PROFILE PACKAGE_POLICY KERNEL_PROFILE HOSTNAME TIMEZONE LOCALE KEYMAP USERNAME) # ai_parse_json_kv TEXT - flatten a flat JSON object into key=value lines ai_parse_json_kv() { local text="$1" match while IFS= read -r match; do [[ -z "$match" ]] && continue if [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*\"([^\"]*)\"$ ]]; then printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" elif [[ "$match" =~ ^\"([A-Za-z_][A-Za-z0-9_]*)\"[[:space:]]*:[[:space:]]*([0-9]+|true|false)$ ]]; then printf '%s=%s\n' "${BASH_REMATCH[1]}" "${BASH_REMATCH[2]}" fi done < <(grep -oE '"[A-Za-z_][A-Za-z0-9_]*"[[:space:]]*:[[:space:]]*("[^"]*"|[0-9]+|true|false)' <<<"$text") } ai_key_allowed() { local key="$1" k for k in "${AI_PROPOSAL_KEYS[@]}"; do [[ "$k" == "$key" ]] && return 0 done return 1 } # ai_validate_field KEY VALUE - non-empty error string when invalid ai_validate_field() { local key="$1" value="$2" case "$key" in TARGET_DISK) validate_target_disk "$value" ;; ENCRYPTION) [[ "$value" =~ ^(none|luks2)$ ]] || printf 'encryption must be none or luks2\n' ;; FILESYSTEM) [[ "$value" =~ ^(btrfs|ext4)$ ]] || printf 'filesystem must be btrfs or ext4\n' ;; DESKTOP_PROFILE) [[ " $(desktop_profiles) " == *" $value "* ]] || printf 'unknown desktop profile\n' ;; PACKAGE_POLICY) [[ "$value" =~ ^(source_first|balanced|binary_first)$ ]] || printf 'unknown package policy\n' ;; KERNEL_PROFILE) [[ "$value" =~ ^(safe|optimized|aggressive)$ ]] || printf 'unknown kernel profile\n' ;; HOSTNAME) validate_hostname "$value" ;; TIMEZONE) validate_timezone "$value" ;; LOCALE) validate_locale "$value" ;; KEYMAP) validate_keymap "$value" ;; USERNAME) validate_username "$value" ;; *) printf 'key not permitted\n' ;; esac } # ai_apply_proposal TEXT - validate and apply; print accepted/rejected lines. # Nothing is executed; only configuration state is changed. ai_apply_proposal() { local text="$1" line key value err accepted=0 rejected=0 printf 'AI proposal review\n==================\n\n' while IFS= read -r line; do key="${line%%=*}"; value="${line#*=}" key="${key^^}" if ! ai_key_allowed "$key"; then printf 'REJECTED %-16s %s (not a permitted setting)\n' "$key" "$value" rejected=$((rejected+1)); continue fi err="$(ai_validate_field "$key" "$value")" if [[ -n "$err" ]]; then printf 'REJECTED %-16s %s (%s)\n' "$key" "$value" "${err%%$'\n'*}" rejected=$((rejected+1)); continue fi printf 'ACCEPTED %-16s %s\n' "$key" "$value" config_set "$key" "$value" accepted=$((accepted+1)) done < <(ai_parse_json_kv "$text") printf '\n%d accepted, %d rejected.\n' "$accepted" "$rejected" log_info "AI proposal applied: $accepted accepted, $rejected rejected" ((rejected == 0)) } # ai_propose_offline QUERY - deterministic translator for common requests ai_propose_offline() { local q q="$(printf '%s' "$1" | tr '[:upper:]' '[:lower:]')" local json="{" local sep="" if [[ "$q" == *encrypt* || "$q" == *luks* ]]; then json+="${sep}\"encryption\":\"luks2\""; sep="," fi if [[ "$q" == *btrfs* ]]; then json+="${sep}\"filesystem\":\"btrfs\""; sep="," fi if [[ "$q" == *desktop* ]]; then json+="${sep}\"desktop_profile\":\"dwl\""; sep="," elif [[ "$q" == *minimal* ]]; then json+="${sep}\"desktop_profile\":\"minimal\""; sep="," fi local disk disk="$(printf '%s' "$q" | grep -oE '/dev/(nvme[0-9]+n[0-9]+|[sv]d[a-z])' | head -n1)" if [[ -n "$disk" ]]; then if disks_is_protected "$disk"; then printf 'Offline assistant: %s looks protected, not proposing it.\n' "$disk" >&2 else json+="${sep}\"target_disk\":\"$disk\""; sep="," fi fi json+="}" printf '%s\n' "$json" } # ai_propose_llm QUERY - ask OpenCode for a flat JSON proposal. # The result is only ever fed to ai_apply_proposal, which validates everything. ai_propose_llm() { local query="$1" bin prompt out bin="$(opencode_detect)" || { log_warn "OpenCode not available"; return 1; } prompt="You are the Phoebus OS installer assistant. Reply with ONLY a flat JSON object of installer settings. Allowed keys: ${AI_PROPOSAL_KEYS[*]}. Allowed values: encryption=none|luks2, filesystem=btrfs|ext4, desktop_profile=none|minimal|dwl|full, package_policy=source_first|balanced|binary_first, kernel_profile=safe|optimized|aggressive. Do not include markdown, explanations, commands, shell code or secrets. User request: $query" log_info "AI: requesting structured proposal from OpenCode" out="$("$bin" run --pure "$prompt" 2>>"$PHOEBUS_LOG_FILE")" || { log_error "OpenCode run failed"; return 1; } printf '%s\n' "$out" } # ai_propose_interactive - choose engine, then apply validated proposal ai_propose_interactive() { local query engine text if declare -F ui_inputbox >/dev/null 2>&1; then ui_inputbox "AI proposal" "Describe the installation you want (e.g. 'whole nvme, encrypt everything, desktop')." "" || return 1 query="$UI_RESULT" else printf 'Describe the installation you want: ' >&2 read -r query || return 1 fi [[ -n "$query" ]] || return 1 engine="offline" if opencode_available && config_bool AI_ENABLED; then if declare -F ui_menu >/dev/null 2>&1; then ui_menu "AI proposal" "Which engine should translate the request?" 10 60 2 \ offline "Deterministic rules (no model)" \ model "OpenCode model (validated proposal)" || return 1 engine="$UI_RESULT" fi fi if [[ "$engine" == "model" ]]; then text="$(ai_propose_llm "$query")" || return 1 else text="$(ai_propose_offline "$query")" fi log_info "AI proposal text: $text" ai_apply_proposal "$text" || log_warn "some proposed settings were rejected" return 0 } # ai_store_api_key KEY - store a provider key with restrictive permissions ai_store_api_key() { local key="$1" dir file dir="${STATE_DIR:-/tmp/ai-installer}/ai" file="$dir/credentials" mkdir -p "$dir" secret_register "$key" umask 077 printf '%s\n' "$key" >"$file" chmod 0600 "$file" log_info "API credential stored at $file (value not logged)" } # ai_configure - provider/model setup; secrets never logged ai_configure() { local provider model endpoint key if declare -F ui_inputbox >/dev/null 2>&1; then ui_inputbox "AI configuration" "Provider (e.g. anthropic, openai, ollama):" "$(config_get AI_PROVIDER)" || return 1 provider="$UI_RESULT" ui_inputbox "AI configuration" "Model (e.g. claude-sonnet-4, gpt-5, llama3):" "$(config_get AI_MODEL)" || return 1 model="$UI_RESULT" ui_inputbox "AI configuration" "Custom endpoint / base URL (optional, for local models):" "$(config_get AI_ENDPOINT)" || return 1 endpoint="$UI_RESULT" config_set AI_PROVIDER "$provider" config_set AI_MODEL "$model" config_set AI_ENDPOINT "$endpoint" config_set AI_ENABLED "yes" opencode_write_config if declare -F ui_yesno >/dev/null 2>&1; then if ui_yesno "AI credentials" "Store an API key now? It is saved with mode 0600 and never logged."; then ui_passwordbox "AI credentials" "Paste API key (input hidden):" || return 0 key="$UI_RESULT" ai_store_api_key "$key" fi fi else printf 'AI configuration requires the TUI or a config file.\n' fi return 0 } # ai_status_text ai_status_text() { printf 'AI assistant: %s\n' "$(config_bool AI_ENABLED && echo enabled || echo disabled)" printf 'OpenCode: %s\n' "$(opencode_detect || echo 'not installed')" printf 'Provider: %s\n' "$(config_get AI_PROVIDER)" printf 'Model: %s\n' "$(config_get AI_MODEL)" printf 'Endpoint: %s\n' "$(config_get AI_ENDPOINT)" }