phoebus_os/installer-rs/crates/phoebus-installer/src/main.rs
Phoebus 3d43f8c6c8 feat(executor): add an OpenCode server capability probe
OpenCode is an agent application, not an OpenAI-compatible endpoint. Add
a typed probe over /global/health and /config/providers that distinguishes
disconnected, authentication required, incompatible, reachable-no-model and
ready, and never returns provider credentials. Expose it as
phoebus-installer --opencode-probe. Document the four components, host and
tunnelled remote workflows, and the Phoebus assistant boundary (ADR 0011).
2026-09-21 20:01:44 -07:00

482 lines
16 KiB
Rust

//! Phoebus OS installer CLI.
//!
//! With no mode flags on a terminal, the text UI starts. The deterministic
//! backend is available directly with `--plan`, `--dry-run` and `--install`.
//! Secrets are supplied through files, never on the command line.
use std::io::Write;
use std::path::PathBuf;
use std::process::ExitCode;
use clap::Parser;
use phoebus_ai::provider::ProviderKind;
use phoebus_core::{InstallConfig, Redactor, SecretString};
use phoebus_executor::{
authorize, AutoConfirm, Confirmation, DestructiveAuthorization, Exec, Logger, RealRunner,
Result,
};
use phoebus_installer::Installer;
use phoebus_tui::TuiOutcome;
/// Pinned OpenCode release manifest. Embedded so the static binary needs no
/// runtime resources. See `resources/opencode.manifest`.
const OPENCODE_MANIFEST: &str = include_str!("../resources/opencode.manifest");
/// Resolve the manifest text. `PHOEBUS_OPENCODE_MANIFEST` overrides the
/// embedded copy so a fixture can be verified end to end (tests, mirrors).
fn opencode_manifest() -> std::io::Result<String> {
match std::env::var("PHOEBUS_OPENCODE_MANIFEST") {
Ok(path) if !path.is_empty() => std::fs::read_to_string(path),
_ => Ok(OPENCODE_MANIFEST.to_string()),
}
}
#[derive(Parser, Debug)]
#[command(
name = "phoebus-installer",
version,
about = "Phoebus OS installer (deterministic backend + TUI)"
)]
struct Cli {
/// Load configuration from a file (TOML or the legacy flat format).
#[arg(long)]
config: Option<PathBuf>,
/// Render the installation plan and exit.
#[arg(long)]
plan: bool,
/// Do not execute commands or modify the target.
#[arg(long)]
dry_run: bool,
/// Run the deterministic backend without the TUI.
#[arg(long)]
install: bool,
/// Skip interactive confirmations (for unattended installs).
#[arg(long, short = 'y')]
yes: bool,
/// Read the LUKS passphrase from a 0600 file.
#[arg(long)]
luks_passphrase_file: Option<PathBuf>,
/// Read the user password from a 0600 file.
#[arg(long)]
user_password_file: Option<PathBuf>,
/// Read the root password from a 0600 file.
#[arg(long)]
root_password_file: Option<PathBuf>,
/// Write the effective configuration as TOML and exit.
#[arg(long)]
save_config: Option<PathBuf>,
/// Fetch and verify the pinned OpenCode release, then exit.
#[arg(long)]
bootstrap_opencode: bool,
/// Enable AI-assisted optimization (opt-in). The facts sent are shown first.
#[arg(long)]
ai: bool,
/// AI provider: `deepseek`, `openai`/`chatgpt`, or `none`.
#[arg(long, value_name = "PROVIDER")]
ai_provider: Option<String>,
/// Model name override for the selected provider.
#[arg(long, value_name = "MODEL")]
ai_model: Option<String>,
/// Read the provider API key from a mode-0600 file (never stored in config).
#[arg(long, value_name = "FILE")]
ai_api_key_file: Option<PathBuf>,
/// Apply a proposal from a file (a chat response or a bare proposal JSON).
#[arg(long, value_name = "FILE")]
ai_proposal_file: Option<PathBuf>,
/// Print the system facts that would be sent to the model, then exit.
#[arg(long)]
ai_facts: bool,
/// Override the provider endpoint (self-hosted/local models).
#[arg(long, value_name = "URL")]
ai_endpoint: Option<String>,
/// Install without AI (break-glass for recovery/automation). Also
/// `--legacy` or `PHOEBUS_NO_AI=1`.
#[arg(long, alias = "legacy")]
no_ai: bool,
/// Print a named desktop asset (session scripts, config, entries) and exit.
/// Used by the live ISO build so it reuses the installer's exact assets.
#[arg(long, value_name = "NAME", hide = true)]
emit_asset: Option<String>,
/// Speak the typed JSON protocol used by the graphical installer frontend
/// (stdin/stdout). Not intended for direct interactive use.
#[arg(long, hide = true)]
gui_bridge: bool,
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
/// its capability as JSON. Read-only; exits nonzero unless a model is
/// available. Never prints provider credentials.
#[arg(long, value_name = "URL")]
opencode_probe: Option<String>,
}
struct TerminalConfirm;
impl Confirmation for TerminalConfirm {
fn confirm_erase(&self, preview: &str) -> Result<bool> {
println!("\n{preview}");
print!("\nType ERASE to continue: ");
std::io::stdout().flush().ok();
let mut line = String::new();
std::io::stdin().read_line(&mut line).map_err(|e| {
phoebus_executor::ExecError::operation("confirm", "erase", e.to_string())
})?;
Ok(line.trim() == "ERASE")
}
fn confirm_final(&self, message: &str) -> Result<bool> {
print!("{message} [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("confirm", "final", e.to_string())
})?;
Ok(matches!(
line.trim().to_ascii_lowercase().as_str(),
"y" | "yes"
))
}
}
fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
let value = std::fs::read_to_string(path)?;
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
}
/// The provider selected on the command line, or the one the TUI/config chose.
fn resolve_provider(
cli: &Cli,
config: &InstallConfig,
) -> std::result::Result<ProviderKind, Box<dyn std::error::Error>> {
let raw = cli
.ai_provider
.as_deref()
.unwrap_or(config.ai.provider.as_str());
ProviderKind::parse(raw).ok_or_else(|| {
format!("unknown AI provider `{raw}` (use deepseek, openai, local or none)").into()
})
}
/// Whether the user explicitly asked for a deterministic, no-AI run.
fn no_ai_requested(cli: &Cli) -> bool {
cli.no_ai
|| std::env::var("PHOEBUS_NO_AI")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
.unwrap_or(false)
}
/// Installing Phoebus requires a connected model. `--no-ai`/`--legacy` is the
/// explicit, documented break-glass for recovery or automation.
fn require_ai_for_install(
cli: &Cli,
provider: ProviderKind,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
if no_ai_requested(cli) || provider != ProviderKind::None {
return Ok(());
}
Err("installing Phoebus requires a connected AI model.\n\
Connect a provider (--ai-provider deepseek|openai|local, with \
--ai-api-key-file and/or --ai-endpoint), or pass --no-ai (alias \
--legacy) for a deterministic install."
.into())
}
/// Apply AI guidance to the configuration before the plan is shown or install
/// runs. The model never sees secrets and never executes anything: its response
/// is reviewed with mandatory evidence and applied atomically.
fn run_ai_guidance(
cli: &Cli,
installer: &mut Installer,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let provider = resolve_provider(cli, &installer.config)?;
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
if !wants_ai {
return Ok(());
}
if let Some(path) = &cli.ai_proposal_file {
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
println!("{}", outcome.render());
return Ok(());
}
if provider == ProviderKind::None {
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
return Ok(());
}
// Opt-in: show exactly what leaves the machine before sending it.
let facts = installer.system_facts();
eprintln!(
"Sending these system facts to {} (no passwords, passphrases or files):",
provider.as_str()
);
eprintln!("{}", facts.render());
let endpoint = cli
.ai_endpoint
.clone()
.unwrap_or_else(|| provider.endpoint().to_string());
let api_key = match (&cli.ai_api_key_file, provider.requires_key()) {
(Some(path), _) => Some(phoebus_executor::ai::load_api_key(path)?),
(None, true) => {
return Err(format!(
"--ai-api-key-file is required for provider `{}`",
provider.as_str()
)
.into());
}
// A self-hosted local model usually needs no key.
(None, false) => None,
};
let model = cli.ai_model.clone().unwrap_or_default();
let transport = phoebus_executor::ai::CurlTransport::new(&installer.exec, api_key);
match phoebus_installer::ai_guide::generate_and_review_at(
&mut installer.config,
&facts,
provider,
&endpoint,
&model,
&transport,
) {
Ok(outcome) => println!("{}", outcome.render()),
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
}
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
Err(e) => {
eprintln!("error: {e}");
ExitCode::FAILURE
}
}
}
fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
let cli = Cli::parse();
if cli.gui_bridge {
phoebus_installer::gui_bridge::run_stdio()?;
return Ok(ExitCode::SUCCESS);
}
if let Some(url) = &cli.opencode_probe {
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint};
let endpoint =
Endpoint::parse(url).map_err(|e| format!("invalid OpenCode endpoint `{url}`: {e}"))?;
let capability = probe(&endpoint, std::time::Duration::from_secs(5));
println!("{}", serde_json::to_string_pretty(&capability)?);
return Ok(if capability.state == ConnectionState::Ready {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
});
}
if let Some(name) = &cli.emit_asset {
return match phoebus_core::system::desktop_asset(name) {
Some(text) => {
print!("{text}");
Ok(ExitCode::SUCCESS)
}
None => {
eprintln!("unknown desktop asset: {name}");
Ok(ExitCode::FAILURE)
}
};
}
let mut config = if let Some(path) = &cli.config {
InstallConfig::load_from_path(path)?
} else {
InstallConfig::default()
};
if cli.dry_run {
config.runtime.dry_run = true;
}
if cli.yes {
config.runtime.assume_yes = true;
}
// Secrets may come from CLI files or the TUI.
let mut luks = cli
.luks_passphrase_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut user_pw = cli
.user_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let root_pw = cli
.root_password_file
.as_ref()
.map(read_secret)
.transpose()?;
let mut tui_confirmed = false;
let mut do_install = cli.install;
// TUI when no explicit mode and a terminal is present.
if !cli.plan && !cli.install && !cli.dry_run && !cli.bootstrap_opencode && phoebus_tui::is_tty()
{
match phoebus_tui::run(config.clone())? {
TuiOutcome::Exit => return Ok(ExitCode::SUCCESS),
TuiOutcome::Save(saved) => {
let path = cli
.config
.clone()
.unwrap_or_else(|| PathBuf::from("phoebus-install.toml"));
std::fs::write(&path, saved.to_toml_string()?)?;
println!("wrote {}", path.display());
return Ok(ExitCode::SUCCESS);
}
TuiOutcome::Install(saved, tui_luks, tui_user) => {
config = saved;
if luks.is_none() {
luks = tui_luks;
}
if user_pw.is_none() {
user_pw = tui_user;
}
do_install = true;
tui_confirmed = true;
}
}
}
let mut state_dir = PathBuf::from(&config.runtime.state_dir);
if std::fs::create_dir_all(&state_dir).is_err() {
state_dir = PathBuf::from("/tmp/phoebus-installer");
std::fs::create_dir_all(&state_dir).ok();
}
let log_path = state_dir.join("install.log");
let echo = std::env::var("PHOEBUS_LOG_ECHO")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "yes" | "1" | "true"))
.unwrap_or(false);
let logger = Logger::open(&log_path, Redactor::new(), echo);
let root = if config.runtime.dry_run {
let sandbox = state_dir.join("dry-run-root");
std::fs::create_dir_all(&sandbox).ok();
sandbox
} else {
PathBuf::from(&config.storage.install_root)
};
let exec = Exec::new(
Box::new(RealRunner),
logger,
config.runtime.dry_run,
root,
state_dir.clone(),
);
for secret in [&luks, &user_pw, &root_pw].into_iter().flatten() {
exec.register_secret(secret);
}
if cli.bootstrap_opencode {
let manifest = phoebus_executor::opencode::Manifest::parse(&opencode_manifest()?);
let dest = phoebus_executor::opencode::bin_dir(&state_dir);
let installed = phoebus_executor::opencode::ensure(&exec, &manifest, &dest)?;
println!("OpenCode ready at {}", installed.display());
return Ok(ExitCode::SUCCESS);
}
let mut installer = Installer::new(config, exec);
if cli.ai_facts {
println!("{}", installer.system_facts().render());
return Ok(ExitCode::SUCCESS);
}
run_ai_guidance(&cli, &mut installer)?;
// AI is mandatory to install; a deterministic no-AI run needs the explicit
// break-glass. Dry-run and plan modes are exempt.
if do_install && !installer.config.runtime.dry_run {
require_ai_for_install(&cli, resolve_provider(&cli, &installer.config)?)?;
}
if let Some(path) = &cli.save_config {
std::fs::write(path, installer.config.to_toml_string()?)?;
println!("wrote {}", path.display());
}
// Plan / default mode.
if cli.plan || !do_install {
print!("{}", installer.render_plan());
let issues = installer.validate();
println!("\nValidation:");
if issues.is_empty() {
println!(" OK");
} else {
for issue in &issues {
println!(" - {issue}");
}
}
return Ok(ExitCode::SUCCESS);
}
// Install mode.
let issues = installer.validate();
if !issues.is_empty() {
eprintln!("configuration is incomplete:");
for issue in &issues {
eprintln!(" - {issue}");
}
return Ok(ExitCode::FAILURE);
}
print!("{}", installer.render_plan());
let auth: DestructiveAuthorization = if tui_confirmed || installer.config.runtime.assume_yes {
authorize(
&AutoConfirm,
&installer.destructive_preview(),
"Start installation?",
)?
} else {
let preview = installer.destructive_preview();
authorize(
&TerminalConfirm,
&preview,
"Start the installation now? This can take a long time.",
)?
};
installer.install(&auth, luks.as_ref(), user_pw.as_ref(), root_pw.as_ref())?;
if installer.config.runtime.dry_run {
println!(
"dry-run complete; log: {}",
installer.exec.log_path().display()
);
} else {
println!(
"installation complete; log: {}",
installer.exec.log_path().display()
);
}
Ok(ExitCode::SUCCESS)
}