//! `sys ` - Phoebus unified system interface. //! //! Natural language is the default interaction: a connected model investigates //! the request, recommends a validated plan, and explains it. //! Deterministic operation without a model is explicitly selected with `--legacy`. //! All operations execute typed, validated actions through the privileged broker; //! the model never receives a shell or privilege. use std::io::Write; use std::path::{Path, PathBuf}; use std::process::ExitCode; use clap::Parser; use phoebus_ai::provider::SystemFacts; use phoebus_core::action::{parse_action, parse_natural, SystemAction}; use phoebus_core::selection::Backend; use phoebus_core::transaction::{TransactionOutcome, TransactionRecord}; use phoebus_core::{AiBackend, InstallConfig, Redactor}; use phoebus_executor::install::{AiInstall, ExecutorSession, InstallRequest}; use phoebus_executor::{ actions, authorize, chooser, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner, Result, }; use phoebus_installer::approval; use phoebus_installer::conversation::{self, ConversationTurn, FollowupResolution}; use phoebus_installer::service::{self, PreparedPlan}; #[derive(Parser, Debug)] #[command( name = "sys", about = "Phoebus system interface", version, group(clap::ArgGroup::new("backend").args([ "portage", "flatpak", "nix", "snap", "appimage", "ebuild" ]).multiple(false)) )] struct Cli { /// Natural-language instruction, e.g. `enable sshd` or `install firefox`. text: Vec, /// Explicit deterministic administration without contacting a model. #[arg(long)] legacy: bool, /// Internal broker invocation by Phoebus OS application layer. #[arg(long)] broker: bool, /// Start the desktop assistant JSON-RPC bridge on stdio. #[arg(long)] assistant_bridge: bool, /// A typed action as JSON, e.g. '{"action":"enable_service","name":"sshd"}'. #[arg(long)] action: Option, /// Read a typed action from a JSON file (used by the AI path or internal broker). #[arg(long)] action_file: Option, /// Execute a prepared plan by identifier (internal broker invocation). #[arg(long, value_name = "PLAN_ID")] execute_plan: Option, /// The uid that reviewed and approved the plan (internal broker only). #[arg(long, value_name = "UID")] plan_uid: Option, /// The independently preserved approval digest shown to the user at review /// (internal broker only). The broker binds execution to this exact plan. #[arg(long, value_name = "SHA256")] approval_digest: Option, /// Auto-approve (unattended); still requires root. #[arg(long, short = 'y')] yes: bool, /// Root directory of the target system. #[arg(long, default_value = "/")] root: PathBuf, /// Constrain to Portage (or in --legacy mode, install through Portage). #[arg(long)] portage: bool, /// Constrain to Flatpak (or in --legacy mode, install from Flatpak). #[arg(long)] flatpak: bool, /// Constrain to Nix (or in --legacy mode, install from Nix). #[arg(long)] nix: bool, /// Constrain to Snap (or in --legacy mode, install from Snap). #[arg(long)] snap: bool, /// Constrain to AppImage (or in --legacy mode, install managed AppImage). #[arg(long)] appimage: bool, /// Constrain to staged custom ebuild (or in --legacy mode, build staged ebuild). #[arg(long)] ebuild: bool, /// AI provider for `sys ask`: deepseek, openai, or local. #[arg(long, value_name = "PROVIDER")] ai_provider: Option, /// Model override for the assistant. #[arg(long, value_name = "MODEL")] ai_model: Option, /// Provider endpoint override (local models). #[arg(long, value_name = "URL")] ai_endpoint: Option, /// Read the provider API key from a mode-0600 file. #[arg(long, value_name = "FILE")] ai_api_key_file: Option, /// Run the assistant without the OS-level sandbox (development only). #[arg(long)] no_sandbox: bool, /// AI backend for `sys ask`: `direct` (default) or `opencode`. #[arg(long, value_name = "BACKEND")] ai_backend: Option, /// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`. #[arg(long, value_name = "URL")] opencode_server: Option, /// OpenCode provider id (e.g. `deepseek`). #[arg(long, value_name = "PROVIDER")] opencode_provider: Option, /// OpenCode model id (e.g. `deepseek-chat`). #[arg(long, value_name = "MODEL")] opencode_model: Option, /// Read the OpenCode server password from a mode-0600 file. #[arg(long, value_name = "FILE")] opencode_password_file: Option, } struct SysConfirm { action: SystemAction, assume_yes: bool, } impl Confirmation for SysConfirm { fn confirm_erase(&self, preview: &str) -> Result { if self.assume_yes { println!("{preview}"); return Ok(true); } println!("\n{preview}"); print!("\nProceed? [y/N] "); std::io::stdout().flush().ok(); let mut line = String::new(); std::io::stdin() .read_line(&mut line) .map_err(|e| phoebus_executor::ExecError::operation("sys", "confirm", e.to_string()))?; Ok(matches!( line.trim().to_ascii_lowercase().as_str(), "y" | "yes" )) } fn confirm_final(&self, _message: &str) -> Result { let _ = &self.action; Ok(true) } } fn now_unix() -> u64 { std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) } fn record_transaction( exec: &Exec, root: &Path, record: TransactionRecord, ) -> std::result::Result<(), Box> { transaction::append(exec, root, record).map_err(|e| { format!("the action completed but its transaction could not be recorded: {e}").into() }) } fn effective_uid() -> u32 { std::process::Command::new("id") .arg("-u") .output() .ok() .and_then(|o| String::from_utf8_lossy(&o.stdout).trim().parse().ok()) .unwrap_or(1) } /// Persist a minimized conversation turn with the process redactor, surfacing a /// storage failure instead of silently losing it. fn record_turn(exec: &Exec, path: &Path, turn: ConversationTurn) { if let Err(e) = conversation::save_turn(path, exec.redactor(), turn) { eprintln!("sys: warning: could not persist conversation context: {e}"); } } fn main() -> ExitCode { match run() { Ok(()) => ExitCode::SUCCESS, Err(e) => { eprintln!("sys: {e}"); ExitCode::FAILURE } } } fn run() -> std::result::Result<(), Box> { let cli = Cli::parse(); let mut state_dir = PathBuf::from("/run/phoebus-installer"); if std::fs::create_dir_all(&state_dir).is_err() { state_dir = std::env::temp_dir().join("phoebus-installer"); std::fs::create_dir_all(&state_dir).ok(); } let logger = Logger::open(state_dir.join("sys.log"), Redactor::new(), false); let exec = Exec::new( Box::new(RealRunner::new()), logger, false, cli.root.clone(), state_dir, ); let plans = service::PlanStore::for_current_user(); // 1. Assistant Bridge if cli.assistant_bridge { return phoebus_installer::assistant_bridge::run_stdio(&exec, &cli.root); } // 2. Broker execute plan if let Some(plan_id) = &cli.execute_plan { if !cli.broker { return Err("--execute-plan requires --broker for privileged invocation".into()); } if effective_uid() != 0 { return Err("privileged plan execution requires root".into()); } // The initiating identity comes from the authenticated caller context // (PKEXEC_UID), never from an untrusted --plan-uid alone. let initiator_uid = approval::broker_initiator_uid(cli.plan_uid, effective_uid())?; let expected_digest = cli .approval_digest .ok_or("--execute-plan requires --approval-digest (the digest the user approved)")?; // Root-owned ledger: a crash leaves a terminal 'interrupted' record and // a replay cannot proceed after the user deletes their own plan files. let approvals = approval::ApprovalLedger::for_broker(); let reconciled = approvals.reconcile_interrupted().unwrap_or(0); if reconciled > 0 { eprintln!("sys: recorded {reconciled} interrupted operation(s) from a previous run"); } // The broker resolves storage from the initiating uid, never from an // arbitrary path, and repeats the full validation itself. let plans = service::PlanStore::for_uid(initiator_uid); let outcome = service::execute_plan_privileged( &exec, &cli.root, &plans, &approvals, plan_id, &expected_digest, initiator_uid, true, )?; println!("{}", serde_json::to_string(&outcome)?); return Ok(()); } // 3. Audit JSON/action-file entry points if cli.action.is_some() || cli.action_file.is_some() { if !cli.legacy && !cli.broker { return Err( "typed actions via --action/--action-file require --legacy for deterministic \ administration or --broker for internal broker invocation" .into(), ); } let action = if let Some(json) = &cli.action { parse_action(json)? } else if let Some(path) = &cli.action_file { let text = std::fs::read_to_string(path)?; parse_action(&text)? } else { unreachable!(); }; return execute_action(&cli, &exec, action); } let backend = backend_flag(&cli); let full_phrase = cli.text.join(" "); // 4. Explicit legacy mode (--legacy) if cli.legacy { if let Some(application) = parse_install_text(&full_phrase) { if let Some(b) = backend { let mut request = InstallRequest::new(&application); request.backend = Some(b); let plan = service::plan_legacy_install(&plans, &exec, &cli.root, &request)?; return render_and_execute_plan(&cli, &exec, &plans, plan); } else { eprintln!("sys: legacy install requires an explicit package source flag."); eprintln!("Specify one of:"); eprintln!(" sys install {application} --legacy --flatpak"); eprintln!(" sys install {application} --legacy --portage"); eprintln!(" sys install {application} --legacy --nix"); eprintln!(" sys install {application} --legacy --snap"); eprintln!(" sys install {application} --legacy --appimage"); eprintln!(" sys install {application} --legacy --ebuild"); return Err("legacy install requires an explicit package source flag (--flatpak, --portage, --nix, --snap, --appimage, --ebuild)".into()); } } if let Some(application) = parse_removal_text(&full_phrase) { let plan = service::plan_removal(&plans, &exec, &cli.root, &application, backend)?; return render_and_execute_plan(&cli, &exec, &plans, plan); } if backend.is_some() { return Err( "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ `sys install ` or `sys remove `" .into(), ); } if full_phrase.trim().is_empty() { return Err("usage: sys --legacy".into()); } return match parse_natural(&full_phrase) { Some(action) => execute_action(&cli, &exec, action), None => { eprintln!("sys: could not parse `{full_phrase}` in legacy mode."); eprintln!( "Legacy mode grammar: sys install --legacy -- | \ sys remove --legacy [--] | \ sys history --legacy | sys undo --legacy | sys enable --legacy | \ sys disable --legacy | sys choose --legacy" ); Err("unsupported instruction in legacy mode".into()) } }; } // 5. Default AI mode (natural language) if cli.text.is_empty() { eprintln!("sys: no instruction provided."); eprintln!("Natural language administration is the default:"); eprintln!(" sys install "); eprintln!(" sys please install "); eprintln!(" sys remove "); eprintln!(" sys ask \"\""); eprintln!("Or select deterministic legacy administration:"); eprintln!(" sys install --legacy --"); eprintln!(" sys remove --legacy [--]"); eprintln!(" sys history --legacy"); eprintln!(" sys undo --legacy"); return Err("missing instruction".into()); } // Conversational `sys ask ` if cli.text.first().map(String::as_str) == Some("ask") { let instruction = cli.text[1..].join(" "); if instruction.trim().is_empty() { return Err("usage: sys ask ".into()); } return run_ask(&cli, &exec, &plans, &instruction, backend); } // Natural `sys install ` / `sys please install ` if let Some(application) = parse_install_text(&full_phrase) { return run_install(&cli, &exec, &plans, &application, backend); } // Natural `sys remove ` / `sys please remove ` if let Some(application) = parse_removal_text(&full_phrase) { return run_remove(&cli, &exec, &plans, &application, backend); } if backend.is_some() { return Err( "--portage/--flatpak/--nix/--snap/--appimage/--ebuild only apply to \ `sys install ` or `sys remove `" .into(), ); } // Other natural language instructions enter the AI workflow by default run_ask(&cli, &exec, &plans, &full_phrase, None) } fn execute_action( cli: &Cli, exec: &Exec, action: SystemAction, ) -> std::result::Result<(), Box> { println!("{}", actions::preview(&action)); let approved = match actions::resolve_effects(exec, &action, &cli.root) { Ok(plan) if !plan.effects.is_empty() => { println!("{}", plan.render()); Some(plan) } Ok(_) => None, Err(e) => { eprintln!("sys: could not resolve effects ({e}); refusing to proceed unreviewed"); return Err("effect resolution failed".into()); } }; // Only genuinely privileged actions require root. A personal package // preference is mutable user state and is written by the invoking account. if action.requires_root() && effective_uid() != 0 { return Err("mutating actions require root; run `sudo sys ...`".into()); } let auth: Option = if action.requires_root() { let confirmation = SysConfirm { action: action.clone(), assume_yes: cli.yes, }; Some(authorize( &confirmation, &actions::preview(&action), "execute", )?) } else { None }; let outcome = actions::execute_checked(exec, &action, auth.as_ref(), &cli.root, approved.as_ref())?; if let Some(id) = &outcome.snapshot { println!("protective snapshot: {id}"); } println!("{}", outcome.output); if action.is_mutating() { let described = action.describe(); let record = TransactionRecord { id: 0, created_unix: now_unix(), origin: "sys-legacy".into(), summary: described.clone(), actions: vec![described.clone()], result: "ok".into(), snapshot: outcome.snapshot.clone(), digest: approved.as_ref().map(|p| p.digest.clone()), outcomes: vec![TransactionOutcome::completed(described)], }; record_transaction(exec, &cli.root, record)?; } Ok(()) } /// A caller-provided question/answer function for the AI install loop. type AskFn = dyn Fn(&str) -> Option; /// Map the explicit backend flags to a lane. The clap arg group forbids more /// than one, so at most one is set. fn backend_flag(cli: &Cli) -> Option { if cli.portage { Some(Backend::PortageSource) } else if cli.flatpak { Some(Backend::Flatpak) } else if cli.nix { Some(Backend::Nix) } else if cli.snap { Some(Backend::Snap) } else if cli.appimage { Some(Backend::AppImage) } else if cli.ebuild { Some(Backend::CustomEbuild) } else { None } } fn backend_flag_name(backend: Backend) -> &'static str { match backend { Backend::PortageSource | Backend::PortageBinary | Backend::PortageVendor => "portage", Backend::Flatpak => "flatpak", Backend::Nix => "nix", Backend::Snap => "snap", Backend::AppImage => "appimage", Backend::CustomEbuild => "ebuild", } } /// Parse `install ` / `add ` / `please install `. fn parse_install_text(text: &str) -> Option { let mut trimmed = text.trim(); for prefix in ["please ", "Please "] { if let Some(rest) = trimmed.strip_prefix(prefix) { trimmed = rest.trim(); break; } } let lower = trimmed.to_ascii_lowercase(); for prefix in ["install ", "add "] { if lower.starts_with(prefix) { let app = trimmed[prefix.len()..].trim(); if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { return Some(app.to_string()); } } } None } /// Parse `remove ` / `uninstall ` / `delete ` / `please remove `. fn parse_removal_text(text: &str) -> Option { let mut trimmed = text.trim(); for prefix in ["please ", "Please "] { if let Some(rest) = trimmed.strip_prefix(prefix) { trimmed = rest.trim(); break; } } let lower = trimmed.to_ascii_lowercase(); for prefix in ["remove ", "uninstall ", "delete "] { if lower.starts_with(prefix) { let app = trimmed[prefix.len()..].trim(); if !app.is_empty() && !app.contains(char::is_whitespace) && !app.starts_with('-') { return Some(app.to_string()); } } } None } /// Load the installed system's configuration instead of assuming defaults. fn load_installed_config(root: &Path) -> InstallConfig { let path = root.join("etc/phoebus/install.toml"); std::fs::read_to_string(&path) .ok() .and_then(|text| InstallConfig::from_toml(&text).ok()) .unwrap_or_default() } fn install_asker(cli: &Cli) -> Option> { use std::io::IsTerminal; if cli.yes || !std::io::stdin().is_terminal() { return None; } Some(Box::new(|question: &str| { println!("\nThe assistant needs to know: {question}"); eprint!("> "); use std::io::Write; std::io::stdout().flush().ok(); let mut line = String::new(); match std::io::stdin().read_line(&mut line) { Ok(n) if n > 0 => { let t = line.trim(); if t.is_empty() { None } else { Some(t.to_string()) } } _ => None, } })) } /// Explain that an unqualified install needs a model, and show the /// deterministic candidate selection without installing it. fn print_install_offer(cli: &Cli, exec: &Exec, application: &str) { let need = InstallRequest::new(application).need(); match chooser::choose(exec, &cli.root, &need) { Ok(selection) => println!("{}", selection.render()), Err(e) => eprintln!("sys: the deterministic selector also found no candidate: {e}"), } eprintln!(); eprintln!("No connected model is available for an unqualified install, so Phoebus will"); eprintln!("not choose a lane for you. Install explicitly with legacy mode, for example:"); eprintln!(" sys install {application} --legacy --flatpak"); eprintln!(" sys install {application} --legacy --portage"); eprintln!(" sys install {application} --legacy --nix"); eprintln!(" sys install {application} --legacy --snap"); eprintln!(" sys install {application} --legacy --appimage"); eprintln!(" sys install {application} --legacy --ebuild"); } /// `sys install `: the shared installation workflow. fn run_install( cli: &Cli, exec: &Exec, plans: &service::PlanStore, application: &str, backend: Option, ) -> std::result::Result<(), Box> { let mut request = InstallRequest::new(application); request.backend = backend; let resolved = resolve_ai(cli); let facts = gather_facts(exec); if !resolved.is_configured() { if let Some(b) = backend { eprintln!("sys: no AI model is configured for this request."); eprintln!("Run deterministically without a model using legacy mode:"); eprintln!( " sys install {application} --legacy --{}", backend_flag_name(b) ); } else { print_install_offer(cli, exec, application); } return Err("no AI provider configured".into()); } let transport = match resolved.transport(exec) { Ok(t) => t, Err(e) => { if let Some(b) = backend { eprintln!("sys: {e}"); eprintln!("Run deterministically without a model using legacy mode:"); eprintln!( " sys install {application} --legacy --{}", backend_flag_name(b) ); } else { print_install_offer(cli, exec, application); } return Err(e.to_string().into()); } }; let provider = resolved.provider; let endpoint = if resolved.backend == AiBackend::OpenCode { resolved.opencode_server.clone() } else { resolved.endpoint.clone() }; let model = if resolved.backend == AiBackend::OpenCode { resolved.opencode_model.clone() } else { resolved.model.clone() }; if let Some(b) = backend { eprintln!( "Investigating `{application}` (constrained to {}) with {} (bounded, read-only evidence only)...", b.as_str(), provider.as_str() ); } else { eprintln!( "Investigating `{application}` with {} (bounded, read-only evidence only)...", provider.as_str() ); } let ai = AiInstall { provider, endpoint, model, transport: transport.as_ref(), limits: phoebus_ai::install::Limits::default(), }; let asker = install_asker(cli); let session = ExecutorSession { exec, root: &cli.root, ask: asker.as_deref(), }; let plan = match service::plan_install( plans, exec, &cli.root, &request, &session, Some(&ai), &facts, ) { Ok(plan) => plan, Err(e) => { // The model failed: offer the actionable legacy alternative and stop; // do not install through any backend. if let Some(b) = backend { eprintln!("sys: the AI investigation did not produce a plan ({e})."); eprintln!("Run deterministically without a model using legacy mode:"); eprintln!( " sys install {application} --legacy --{}", backend_flag_name(b) ); } else { print_install_offer(cli, exec, application); } return Err(format!("the AI investigation did not produce a plan: {e}").into()); } }; let conv_path = conversation::history_path(); record_turn( exec, &conv_path, ConversationTurn { timestamp_unix: now_unix(), query: format!("install {application}"), response_kind: "install".into(), application: Some(application.to_string()), chosen_candidate: plan.candidate.clone(), alternatives: plan.alternatives.clone(), plan_id: Some(plan.id.clone()), plan_digest: Some(plan.digest.clone()), rationale: plan.rationale.clone(), }, ); render_and_execute_plan(cli, exec, plans, plan) } /// `sys remove `: the shared AI-first removal workflow. Default /// removal goes through the connected model; only `--legacy` bypasses it. The /// deterministic ownership discovery and policy validation run underneath in /// both modes. fn run_remove( cli: &Cli, exec: &Exec, plans: &service::PlanStore, application: &str, backend: Option, ) -> std::result::Result<(), Box> { let plan = match run_remove_plan(cli, exec, plans, application, backend) { Ok(plan) => plan, Err(e) => { // The model failed: offer the actionable legacy alternative and // stop; do not silently remove deterministically. eprintln!("sys: the AI-assisted removal did not produce a plan ({e})."); eprintln!("Run deterministically without a model using legacy mode:"); let lane = backend .map(|b| format!(" --{}", backend_flag_name(b))) .unwrap_or_default(); eprintln!(" sys remove {application} --legacy{lane}"); return Err(format!("the AI-assisted removal did not produce a plan: {e}").into()); } }; let conv_path = conversation::history_path(); record_turn( exec, &conv_path, ConversationTurn { timestamp_unix: now_unix(), query: format!("remove {application}"), response_kind: "removal".into(), application: Some(application.to_string()), chosen_candidate: None, alternatives: Vec::new(), plan_id: Some(plan.id.clone()), plan_digest: Some(plan.digest.clone()), rationale: plan.rationale.clone(), }, ); render_and_execute_plan(cli, exec, plans, plan) } /// Build a removal plan through the connected model (default) or the /// deterministic selector (legacy). The model only chooses/confirms among /// copies the deterministic discovery already found. fn run_remove_plan( cli: &Cli, exec: &Exec, plans: &service::PlanStore, application: &str, backend: Option, ) -> std::result::Result> { if cli.legacy { return Ok(service::plan_removal( plans, exec, &cli.root, application, backend, )?); } let resolved = resolve_ai(cli); if !resolved.is_configured() { return Err("no AI provider configured".into()); } let transport = resolved.transport(exec).map_err(|e| e.to_string())?; let ai = AiInstall { provider: resolved.provider, endpoint: if resolved.backend == AiBackend::OpenCode { resolved.opencode_server.clone() } else { resolved.endpoint.clone() }, model: if resolved.backend == AiBackend::OpenCode { resolved.opencode_model.clone() } else { resolved.model.clone() }, transport: transport.as_ref(), limits: phoebus_ai::install::Limits::default(), }; let facts = gather_facts(exec); service::plan_removal_with_ai(plans, exec, &cli.root, application, backend, &ai, &facts) .map_err(Into::into) } fn render_and_execute_plan( cli: &Cli, exec: &Exec, plans: &service::PlanStore, plan: PreparedPlan, ) -> std::result::Result<(), Box> { println!("{}", plan.render()); if plan.requires_root && effective_uid() != 0 { return Err("mutating actions require root; run `sudo sys ...`".into()); } if plan.requires_root && !cli.yes { let confirmation = SysConfirm { action: plan .actions .first() .cloned() .unwrap_or(SystemAction::History), assume_yes: false, }; authorize(&confirmation, &plan.summary, "execute")?; } let outcome = service::execute_plan(exec, &cli.root, plans, &plan.id, &plan.digest, true)?; if let Some(snapshot) = outcome.snapshot { println!("protective snapshot: {snapshot}"); } for line in &outcome.output { if !line.trim().is_empty() { println!("{line}"); } } if !outcome.verification.is_empty() { println!("{}", outcome.verification); } Ok(()) } /// Bounded system facts for the assistant: hardware, selected profile and /// measured compile times. No personal files, credentials or command history. fn gather_facts(exec: &Exec) -> SystemFacts { let config = load_installed_config(&exec.root); let hardware = probe::probe_hardware(exec.runner.as_ref()); let history = phoebus_core::load_history(&exec.root.join("var/lib/phoebus/compile-times.tsv")); let binhost = exec.root.join("etc/portage/binrepos.conf").exists(); let mut facts = SystemFacts::from_system(&config, &hardware, &history, binhost, None); let hw = chooser::hardware_facts(exec, &exec.root); facts.storage_free_mib = hw.storage_free_mib; facts.wayland = hw.wayland; facts.available_backends = hw .available_backends .iter() .map(|b| b.as_str().to_string()) .collect(); let prefs = chooser::load_preferences(&exec.root); facts.saved_preferences = prefs .per_app .iter() .map(|(app, backend)| (app.clone(), backend.as_str().to_string())) .collect(); facts.recovery_snapshots = exec .root .join(phoebus_executor::snapshot::SNAPSHOT_DIR) .is_dir(); facts } fn load_installed_ai_config(root: &Path) -> Option { let conf_path = root.join("etc/phoebus/assistant.conf"); let text = std::fs::read_to_string(&conf_path).ok()?; toml::from_str(&text).ok() } /// Resolve provider configuration and credential references through the shared /// setup module, so the CLI and the GUI cannot diverge. fn resolve_ai(cli: &Cli) -> phoebus_installer::ai_setup::ResolvedAi { let conf = load_installed_ai_config(&cli.root); let overrides = phoebus_installer::ai_setup::AiOverrides { backend: cli.ai_backend.clone(), provider: cli.ai_provider.clone(), model: cli.ai_model.clone(), endpoint: cli.ai_endpoint.clone(), api_key_file: cli.ai_api_key_file.clone(), opencode_server: cli.opencode_server.clone(), opencode_provider: cli.opencode_provider.clone(), opencode_model: cli.opencode_model.clone(), opencode_password_file: cli.opencode_password_file.clone(), no_sandbox: cli.no_sandbox, use_environment: true, }; phoebus_installer::ai_setup::resolve(&cli.root, &overrides, conf.as_ref()) } fn deterministic_fallback(instruction: &str) { eprintln!("No connected model is available. The deterministic legacy interface still works:"); match parse_natural(instruction) { Some(action) => { eprintln!(" sys {} --legacy", action.describe()); eprintln!("Run it as: sys {} --legacy", instruction.trim()); } None => { eprintln!( " Examples: sys enable sshd --legacy | sys install vim --legacy -- | \ sys history --legacy | sys undo --legacy" ); eprintln!(" A model only makes this easier; it is never required."); } } } /// The assistant loop: gather facts -> propose validated actions -> show /// effects -> approve/authenticate -> execute deterministically -> record. fn run_ask( cli: &Cli, exec: &Exec, plans: &service::PlanStore, instruction: &str, backend: Option, ) -> std::result::Result<(), Box> { // An explicit application reference takes precedence over any inferred // conversational reference: "install vlc using flatpak" concerns VLC even // right after a conversation about Firefox. if let Some((application, source)) = conversation::parse_explicit_install(instruction) { return run_install(cli, exec, plans, &application, source.or(backend)); } if let Some(application) = parse_removal_text(instruction) { return run_remove(cli, exec, plans, &application, backend); } let conv_path = conversation::history_path(); let history = conversation::load_history(&conv_path); if let Some(followup) = conversation::resolve_followup(instruction, &history) { match followup { FollowupResolution::Comparison { explanation, .. } => { println!("{explanation}"); return Ok(()); } FollowupResolution::SwitchBackend { application, target_backend, } => { return run_install(cli, exec, plans, &application, Some(target_backend)); } FollowupResolution::ConfirmPlan { plan_id, digest } => { // Conversational confirmation never bypasses normal plan // validation or authentication: it references a reviewed plan // and goes through the same execution boundary. let plan = plans.load(&plan_id)?; if plan.digest != digest { return Err("plan digest mismatch".into()); } return render_and_execute_plan(cli, exec, plans, plan); } } } let resolved = resolve_ai(cli); if !resolved.is_configured() { deterministic_fallback(instruction); return Err("no AI provider configured".into()); } let transport = match resolved.transport(exec) { Ok(t) => t, Err(e) => { deterministic_fallback(instruction); return Err(e.to_string().into()); } }; let facts = gather_facts(exec); let provider = resolved.provider; let endpoint = if resolved.backend == AiBackend::OpenCode { resolved.opencode_server.clone() } else { resolved.endpoint.clone() }; let model = if resolved.backend == AiBackend::OpenCode { resolved.opencode_model.clone() } else { resolved.model.clone() }; let ai = AiInstall { provider, endpoint, model, transport: transport.as_ref(), limits: phoebus_ai::install::Limits::default(), }; let plan = match service::plan_general(plans, exec, &cli.root, instruction, &facts, &ai) { Ok(plan) => plan, Err(e) => { eprintln!("The model is unavailable or returned an unusable plan: {e}"); deterministic_fallback(instruction); return Err("model unavailable".into()); } }; record_turn( exec, &conv_path, ConversationTurn { timestamp_unix: now_unix(), // Persist the plan's own summary, not the raw request: structured // context is sufficient for follow-ups and minimizes exposure. query: plan.summary.clone(), response_kind: "plan".into(), application: None, chosen_candidate: None, alternatives: Vec::new(), plan_id: Some(plan.id.clone()), plan_digest: Some(plan.digest.clone()), rationale: plan.rationale.clone(), }, ); render_and_execute_plan(cli, exec, plans, plan) } #[allow(dead_code)] fn _auto() -> AutoConfirm { AutoConfirm }