1820 lines
65 KiB
Rust
1820 lines
65 KiB
Rust
//! The single [`Bridge`] owning the installer: request dispatch, installation
|
|
//! support, secret handling, progress events, and the stdio entry point.
|
|
|
|
use std::io::{self, BufRead, Write};
|
|
|
|
use crate::{ai_guide, Installer};
|
|
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
|
use phoebus_core::{AiBackend, InstallConfig, InstallStep, SecretString};
|
|
use phoebus_executor::ai::CurlTransport;
|
|
use phoebus_executor::auth::authorize;
|
|
use phoebus_executor::Exec;
|
|
|
|
use serde_json::{json, Value};
|
|
|
|
use super::protocol::{
|
|
disk_change_report, step_meta, write_json, BridgeConfirm, DiskPhase, JsonObserver, Request,
|
|
MAX_LINE_BYTES, MAX_LOG_TAIL, MAX_SECRET_BYTES, PROTOCOL_VERSION,
|
|
};
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Bridge
|
|
// ---------------------------------------------------------------------------
|
|
|
|
pub struct Bridge {
|
|
pub(super) installer: Installer,
|
|
luks: Option<SecretString>,
|
|
user_password: Option<SecretString>,
|
|
root_password: Option<SecretString>,
|
|
pub(super) api_key: Option<SecretString>,
|
|
opencode_password: Option<SecretString>,
|
|
pub(super) approved_digest: Option<String>,
|
|
/// Set only after a real, validated AI interaction (a proposal reviewed for
|
|
/// the direct path, or a validated model response for OpenCode). A mere
|
|
/// provider name never satisfies the mandatory-AI gate.
|
|
validated_ai: Option<String>,
|
|
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
|
last_stage: std::rc::Rc<std::cell::Cell<Option<InstallStep>>>,
|
|
/// One destructive transaction at a time. An approval is single-use: it is
|
|
/// consumed when the install starts so a replay, a second frontend or a
|
|
/// reconnected client cannot start a second overlapping installation.
|
|
installing: bool,
|
|
pub(super) installed: bool,
|
|
quit: bool,
|
|
}
|
|
|
|
impl Bridge {
|
|
pub fn new(config: InstallConfig, exec: Exec) -> Self {
|
|
let installer = Installer::new(config, exec);
|
|
Self {
|
|
installer,
|
|
luks: None,
|
|
user_password: None,
|
|
root_password: None,
|
|
api_key: None,
|
|
opencode_password: None,
|
|
approved_digest: None,
|
|
validated_ai: None,
|
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::Before)),
|
|
last_stage: std::rc::Rc::new(std::cell::Cell::new(None)),
|
|
installing: false,
|
|
installed: false,
|
|
quit: false,
|
|
}
|
|
}
|
|
|
|
/// Build directly on an installer (tests, embedded callers).
|
|
pub fn with_installer(installer: Installer) -> Self {
|
|
Self {
|
|
installer,
|
|
luks: None,
|
|
user_password: None,
|
|
root_password: None,
|
|
api_key: None,
|
|
opencode_password: None,
|
|
approved_digest: None,
|
|
validated_ai: None,
|
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::Before)),
|
|
last_stage: std::rc::Rc::new(std::cell::Cell::new(None)),
|
|
installing: false,
|
|
installed: false,
|
|
quit: false,
|
|
}
|
|
}
|
|
|
|
/// Whether the caller asked the bridge to stop.
|
|
pub fn should_quit(&self) -> bool {
|
|
self.quit
|
|
}
|
|
|
|
/// Parse and dispatch one request line, writing events/responses to `out`.
|
|
pub fn handle_line(&mut self, line: &str, out: &mut (dyn Write + Send)) -> io::Result<()> {
|
|
let line = line.trim();
|
|
if line.is_empty() {
|
|
return Ok(());
|
|
}
|
|
if line.len() > MAX_LINE_BYTES {
|
|
return write_json(
|
|
out,
|
|
&json!({
|
|
"ok": false,
|
|
"error": format!("request too large ({} bytes)", line.len()),
|
|
}),
|
|
);
|
|
}
|
|
let request: Request = match serde_json::from_str(line) {
|
|
Ok(request) => request,
|
|
Err(e) => {
|
|
return write_json(
|
|
out,
|
|
&json!({ "ok": false, "error": format!("bad request: {e}") }),
|
|
)
|
|
}
|
|
};
|
|
self.dispatch(request, out)
|
|
}
|
|
|
|
fn dispatch(&mut self, request: Request, out: &mut (dyn Write + Send)) -> io::Result<()> {
|
|
let id = request.id;
|
|
let op = request.op.clone();
|
|
let result = match request.op.as_str() {
|
|
"handshake" => self.handshake(),
|
|
"readiness" => self.readiness(),
|
|
"options" => self.options(),
|
|
"ai_catalog" => self.ai_catalog(),
|
|
"disks" => self.disks(),
|
|
"set_config" => self.set_config(&request),
|
|
"set_secrets" => self.set_secrets(&request),
|
|
"validate" => self.validate(),
|
|
"plan" => self.plan(),
|
|
"destructive_preview" => self.destructive_preview(),
|
|
"ai_check" => self.ai_check(),
|
|
"ai_test" => self.ai_test(),
|
|
"approve" => self.approve(&request),
|
|
"start_install" => return self.start_install(id, &request, out),
|
|
"log_tail" => self.log_tail(&request),
|
|
"quit" => {
|
|
self.quit = true;
|
|
Ok(json!({ "bye": true }))
|
|
}
|
|
other => Err(format!("unknown op `{other}`")),
|
|
};
|
|
|
|
match result {
|
|
Ok(data) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": true, "op": op, "data": data }),
|
|
),
|
|
Err(error) => {
|
|
// AI connection failures carry a stable, machine-readable kind
|
|
// so the frontend can distinguish an authentication failure
|
|
// from an unreachable server, a missing model or bad transport.
|
|
// The human message stays authoritative and redacted.
|
|
let mut payload = json!({ "id": id, "ok": false, "op": op, "error": error });
|
|
if matches!(
|
|
op.as_str(),
|
|
"ai_catalog" | "ai_check" | "ai_test" | "readiness"
|
|
) {
|
|
payload["error_kind"] = json!(connection_error_kind(
|
|
payload["error"].as_str().unwrap_or("")
|
|
));
|
|
}
|
|
write_json(out, &payload)
|
|
}
|
|
}
|
|
}
|
|
|
|
// -- read-only ops ------------------------------------------------------
|
|
|
|
fn handshake(&self) -> Result<Value, String> {
|
|
let facts = self.installer.system_facts();
|
|
let network = network_ready();
|
|
let mut defaults = self.installer.config.clone();
|
|
let detected_tz = live_timezone();
|
|
if defaults.system.timezone == "UTC" && detected_tz != "UTC" {
|
|
defaults.system.timezone = detected_tz;
|
|
}
|
|
let detected_km = live_keymap();
|
|
if defaults.system.keymap == "us" && detected_km != "us" {
|
|
defaults.system.keymap = detected_km;
|
|
}
|
|
defaults.desktop.profile = phoebus_core::config::DesktopProfile::Mango;
|
|
defaults.storage.filesystem = phoebus_core::config::Filesystem::Btrfs;
|
|
defaults.desktop.flatpak = true;
|
|
defaults.packages.nix = true;
|
|
defaults.packages.binary_packages = true;
|
|
Ok(json!({
|
|
"protocol": PROTOCOL_VERSION,
|
|
"version": phoebus_core::VERSION,
|
|
"iso_version": iso_version(),
|
|
"build_id": std::env::var("PHOEBUS_BUILD_ID").unwrap_or_else(|_| "dev".into()),
|
|
"live": std::path::Path::new("/etc/phoebus/live").exists(),
|
|
"defaults": defaults,
|
|
"readiness": {
|
|
"network": network,
|
|
"firmware": self.installer.hardware.firmware_str(),
|
|
"memory_mib": self.installer.hardware.memory_mib,
|
|
"cpu_cores": self.installer.hardware.cpu.cores,
|
|
"cpu_model": self.installer.hardware.cpu.model,
|
|
"desktop": defaults.desktop.profile.as_str(),
|
|
"keymap_live": live_keymap(),
|
|
},
|
|
"facts": facts,
|
|
}))
|
|
}
|
|
|
|
/// A deeper, on-demand readiness probe. Unlike [`Self::handshake`] this may
|
|
/// make one bounded network request, so the frontend calls it when the
|
|
/// network step is shown or the user asks to re-check. It never changes
|
|
/// configuration or state, so refreshing readiness cannot reset the wizard.
|
|
fn readiness(&self) -> Result<Value, String> {
|
|
let link = network_ready();
|
|
let services = service_reachability(&self.installer);
|
|
Ok(json!({
|
|
"network": link,
|
|
"network_services": services.reachable,
|
|
"network_detail": services.detail,
|
|
"network_target": services.target,
|
|
"firmware": self.installer.hardware.firmware_str(),
|
|
"memory_mib": self.installer.hardware.memory_mib,
|
|
"cpu_cores": self.installer.hardware.cpu.cores,
|
|
"cpu_model": self.installer.hardware.cpu.model,
|
|
"desktop": self.installer.config.desktop.profile.as_str(),
|
|
"keymap_live": live_keymap(),
|
|
}))
|
|
}
|
|
|
|
/// Selectable options for the language/region step. Reading these from the
|
|
/// live system means the user picks from the real timezones, locales and
|
|
/// keymaps instead of typing them from memory.
|
|
fn options(&self) -> Result<Value, String> {
|
|
Ok(json!({
|
|
"timezones": labeled_options(system_timezones(), humanize_timezone),
|
|
"locales": labeled_options(system_locales(), humanize_locale),
|
|
"keymaps": system_keymap_options(),
|
|
// The live session's own layout, so the frontend can be truthful
|
|
// about whether a selection affects the running graphical session.
|
|
"keymap_live": live_keymap(),
|
|
}))
|
|
}
|
|
|
|
/// The providers and models the configured AI connection actually offers:
|
|
/// the OpenCode catalog, or an OpenAI-compatible `/models` list. Read-only;
|
|
/// never returns provider credentials.
|
|
fn ai_catalog(&self) -> Result<Value, String> {
|
|
use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, OpenCodeClient};
|
|
use phoebus_executor::opencode_server::Endpoint;
|
|
|
|
let redact = self.installer.exec.redactor();
|
|
match self.installer.config.ai.backend {
|
|
AiBackend::OpenCode => {
|
|
// The catalog only needs the server; the model is optional.
|
|
let server = self.installer.config.ai.opencode_server.trim().to_string();
|
|
if server.is_empty() {
|
|
return Err("OpenCode requires a server URL".into());
|
|
}
|
|
let provider = self
|
|
.installer
|
|
.config
|
|
.ai
|
|
.opencode_provider
|
|
.trim()
|
|
.to_string();
|
|
let model = self.installer.config.ai.opencode_model.trim().to_string();
|
|
let endpoint = Endpoint::parse(&server)
|
|
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
|
|
let target = endpoint
|
|
.checked_target()
|
|
.map_err(|e| redact.redact(&e.to_string()))?;
|
|
let http = CurlHttpClient::new(&self.installer.exec);
|
|
// The provider catalog can be several MiB on a busy server.
|
|
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model)
|
|
.with_auth(self.opencode_password.clone())
|
|
.with_max_body(16 * 1024 * 1024)
|
|
.with_resolve(Some((endpoint.host.clone(), endpoint.port, target.ip())));
|
|
match client.catalog() {
|
|
Ok(catalog) => {
|
|
let providers: Vec<Value> = catalog
|
|
.providers
|
|
.iter()
|
|
.map(
|
|
|p| json!({ "id": p.id, "name": p.name, "connected": p.connected }),
|
|
)
|
|
.collect();
|
|
let models: Vec<Value> = catalog
|
|
.providers
|
|
.iter()
|
|
.find(|p| p.id == provider)
|
|
.or_else(|| catalog.providers.iter().find(|p| !p.models.is_empty()))
|
|
.map(|p| {
|
|
p.models
|
|
.iter()
|
|
.map(|m| {
|
|
let label = if m.name != m.id {
|
|
format!("{} ({})", m.name, m.id)
|
|
} else {
|
|
m.name.clone()
|
|
};
|
|
json!({
|
|
"id": m.id,
|
|
"name": m.name,
|
|
"label": label,
|
|
"value": m.id,
|
|
"variants": m.variants,
|
|
})
|
|
})
|
|
.collect()
|
|
})
|
|
.unwrap_or_default();
|
|
Ok(json!({
|
|
"backend": "opencode",
|
|
"providers": providers,
|
|
"models": models,
|
|
}))
|
|
}
|
|
Err(e) => Err(redact.redact(&e.to_string())),
|
|
}
|
|
}
|
|
AiBackend::Direct => {
|
|
let raw = self.installer.config.ai.provider.clone();
|
|
let provider = ProviderKind::parse(&raw)
|
|
.ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
|
|
if provider == ProviderKind::None {
|
|
return Err("no AI provider selected".into());
|
|
}
|
|
let endpoint = if self.installer.config.ai.endpoint.is_empty() {
|
|
provider.endpoint().to_string()
|
|
} else {
|
|
self.installer.config.ai.endpoint.clone()
|
|
};
|
|
let url = models_url(&endpoint);
|
|
let mut request = phoebus_executor::opencode_client::HttpRequest::get(url);
|
|
request.auth_user = String::new(); // OpenAI-compatible: Bearer
|
|
request.auth = self.api_key.clone();
|
|
let http = CurlHttpClient::new(&self.installer.exec);
|
|
match http.request(&request) {
|
|
Ok(response) if response.is_success() => {
|
|
let models: Vec<Value> = parse_model_ids(&response.body)
|
|
.into_iter()
|
|
.map(|id| {
|
|
json!({
|
|
"id": id,
|
|
"name": id,
|
|
"label": id,
|
|
"value": id,
|
|
"variants": ["default"],
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({
|
|
"backend": "direct",
|
|
"providers": [ { "id": provider.as_str(), "name": provider.as_str(), "connected": true } ],
|
|
"models": models,
|
|
}))
|
|
}
|
|
Ok(response) => Err(format!("model list returned HTTP {}", response.status)),
|
|
Err(e) => Err(redact.redact(&e.to_string())),
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
fn disks(&mut self) -> Result<Value, String> {
|
|
self.installer.disks =
|
|
phoebus_executor::probe::probe_disks(self.installer.exec.runner.as_ref());
|
|
let runner = self.installer.exec.runner.as_ref();
|
|
let disks: Vec<Value> = self
|
|
.installer
|
|
.disks
|
|
.iter()
|
|
.map(|d| {
|
|
let partitions = phoebus_executor::probe::disk_partitions(runner, &d.path);
|
|
json!({
|
|
"path": d.path,
|
|
"identifier": d.path,
|
|
"model": d.model.clone().unwrap_or_else(|| "Unknown disk".into()),
|
|
"size_bytes": d.size_bytes,
|
|
"size_human": d.size_human(),
|
|
"transport": d.transport.clone().unwrap_or_else(|| "unknown".into()),
|
|
"removable": d.removable,
|
|
"protected": d.is_protected(),
|
|
"protection": d.protection().map(|r| r.describe()),
|
|
"live_medium": d.live_media,
|
|
"kind": format!("{:?}", d.kind).to_lowercase(),
|
|
"partitions": partitions,
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({ "disks": disks }))
|
|
}
|
|
|
|
fn validate(&self) -> Result<Value, String> {
|
|
let issues = self.installer.validate();
|
|
let complete = issues.is_empty();
|
|
Ok(json!({
|
|
"complete": complete,
|
|
"issues": issues.iter().map(|i| json!({
|
|
"field": i.field,
|
|
"message": i.message,
|
|
})).collect::<Vec<_>>(),
|
|
}))
|
|
}
|
|
|
|
fn plan(&self) -> Result<Value, String> {
|
|
let issues = self.installer.validate();
|
|
let plan = self.installer.plan();
|
|
Ok(json!({
|
|
"human": self.installer.render_plan(),
|
|
"plan_digest": self.plan_digest(),
|
|
"steps": plan.steps.iter().map(|s| json!({
|
|
"stage": s.name(),
|
|
"category": step_meta(*s).0,
|
|
"label": step_meta(*s).1,
|
|
})).collect::<Vec<_>>(),
|
|
"validation": issues.iter().map(|i| json!({
|
|
"field": i.field,
|
|
"message": i.message,
|
|
})).collect::<Vec<_>>(),
|
|
"review": self.review(),
|
|
}))
|
|
}
|
|
|
|
fn destructive_preview(&self) -> Result<Value, String> {
|
|
Ok(json!({
|
|
"text": self.installer.destructive_preview(),
|
|
"plan_digest": self.plan_digest(),
|
|
}))
|
|
}
|
|
|
|
fn log_tail(&self, request: &Request) -> Result<Value, String> {
|
|
let path = self.installer.exec.log_path().to_path_buf();
|
|
let text = std::fs::read_to_string(&path).unwrap_or_default();
|
|
let want = request.lines.unwrap_or(40).min(MAX_LOG_TAIL);
|
|
// The logger already redacted, but re-redact on read so a rotated or
|
|
// externally-written file can never leak a registered secret.
|
|
let redacted = self.installer.exec.redactor().redact(&text);
|
|
let lines: Vec<&str> = redacted.lines().rev().take(want).collect();
|
|
let tail: Vec<&str> = lines.into_iter().rev().collect();
|
|
Ok(json!({
|
|
"path": path.display().to_string(),
|
|
"lines": tail,
|
|
}))
|
|
}
|
|
|
|
// -- configuration ------------------------------------------------------
|
|
|
|
fn set_config(&mut self, request: &Request) -> Result<Value, String> {
|
|
let mut config: InstallConfig = serde_json::from_value(
|
|
request
|
|
.config
|
|
.clone()
|
|
.ok_or_else(|| "set_config requires a `config` object".to_string())?,
|
|
)
|
|
.map_err(|e| format!("invalid configuration: {e}"))?;
|
|
|
|
// Secrets never live in the configuration. Reject an attempt to smuggle
|
|
// one in, rather than silently persisting it.
|
|
if config
|
|
.to_toml_string()
|
|
.map(|t| contains_secret_marker(&t))
|
|
.unwrap_or(false)
|
|
{
|
|
return Err("configuration must not contain secret material".into());
|
|
}
|
|
// The bridge is an installer for this machine; the dry-run/log paths are
|
|
// backend concerns and not user-selectable from the GUI.
|
|
config.runtime.dry_run = self.installer.config.runtime.dry_run;
|
|
|
|
let ai_before = ai_digest(&self.installer.config);
|
|
self.installer.reconfigure(config);
|
|
self.approved_digest = None;
|
|
// Only a change to the AI connection settings invalidates the AI
|
|
// validation. Choosing a disk, typing a hostname or similar must not
|
|
// throw away a successful model interaction.
|
|
if ai_digest(&self.installer.config) != ai_before {
|
|
self.validated_ai = None;
|
|
}
|
|
let issues = self.installer.validate();
|
|
Ok(json!({
|
|
"accepted": true,
|
|
"plan_digest": self.plan_digest(),
|
|
"complete": issues.is_empty(),
|
|
"issues": issues.iter().map(|i| json!({
|
|
"field": i.field,
|
|
"message": i.message,
|
|
})).collect::<Vec<_>>(),
|
|
}))
|
|
}
|
|
|
|
fn set_secrets(&mut self, request: &Request) -> Result<Value, String> {
|
|
let patch = request
|
|
.secrets
|
|
.as_ref()
|
|
.ok_or_else(|| "set_secrets requires a `secrets` object".to_string())?;
|
|
for value in [
|
|
&patch.luks,
|
|
&patch.user_password,
|
|
&patch.root_password,
|
|
&patch.ai_api_key,
|
|
&patch.opencode_password,
|
|
]
|
|
.into_iter()
|
|
.flatten()
|
|
{
|
|
if value.len() > MAX_SECRET_BYTES {
|
|
return Err("secret value is too large".into());
|
|
}
|
|
}
|
|
if let Some(v) = &patch.luks {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.luks = Some(s);
|
|
}
|
|
if let Some(v) = &patch.user_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.user_password = Some(s);
|
|
}
|
|
if let Some(v) = &patch.root_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.root_password = Some(s);
|
|
}
|
|
let mut ai_credential_changed = false;
|
|
if let Some(v) = &patch.ai_api_key {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.api_key = Some(s);
|
|
ai_credential_changed = true;
|
|
}
|
|
if let Some(v) = &patch.opencode_password {
|
|
let s = SecretString::new(v.clone());
|
|
self.installer.exec.register_secret(&s);
|
|
self.opencode_password = Some(s);
|
|
ai_credential_changed = true;
|
|
}
|
|
// Only an AI credential change invalidates the AI validation; account
|
|
// and disk secrets do not.
|
|
if ai_credential_changed {
|
|
self.validated_ai = None;
|
|
}
|
|
// Report only presence, never values.
|
|
Ok(json!({
|
|
"luks_set": self.luks.is_some(),
|
|
"user_password_set": self.user_password.is_some(),
|
|
"root_password_set": self.root_password.is_some(),
|
|
"ai_api_key_set": self.api_key.is_some(),
|
|
"opencode_password_set": self.opencode_password.is_some(),
|
|
}))
|
|
}
|
|
|
|
// -- AI -----------------------------------------------------------------
|
|
|
|
fn ai_check(&mut self) -> Result<Value, String> {
|
|
let facts = self.installer.system_facts();
|
|
let backend = self.installer.config.ai.backend;
|
|
let api_key = self.api_key.clone();
|
|
let opencode_password = self.opencode_password.clone();
|
|
let value = {
|
|
let Installer { exec, config, .. } = &mut self.installer;
|
|
let redactor = exec.redactor();
|
|
match backend {
|
|
AiBackend::OpenCode => {
|
|
let transport = opencode_transport(exec, config, opencode_password)?;
|
|
review_opencode(config, redactor, facts, &transport)?
|
|
}
|
|
AiBackend::Direct => {
|
|
let transport = CurlTransport::new(exec, api_key.clone());
|
|
review_proposal(config, redactor, facts, api_key.is_some(), &transport)?
|
|
}
|
|
}
|
|
};
|
|
self.approved_digest = None;
|
|
// Bind the validated interaction to the exact configuration it was
|
|
// validated against; any later change clears it.
|
|
self.validated_ai = Some(ai_digest(&self.installer.config));
|
|
Ok(value)
|
|
}
|
|
|
|
/// A real, minimal model interaction that obtains and validates a JSON model
|
|
/// response without changing the configuration. This is "Test connection".
|
|
fn ai_test(&mut self) -> Result<Value, String> {
|
|
use phoebus_ai::provider::{build_request, extract_content};
|
|
let backend = self.installer.config.ai.backend;
|
|
let facts = self.installer.system_facts();
|
|
let redactor = self.installer.exec.redactor();
|
|
let (kind, endpoint, model, label) = match backend {
|
|
AiBackend::OpenCode => {
|
|
let (server, provider, model, _) = opencode_parts(&self.installer.config)?;
|
|
(ProviderKind::Local, server, model, provider)
|
|
}
|
|
AiBackend::Direct => {
|
|
let raw = self.installer.config.ai.provider.clone();
|
|
let provider = ProviderKind::parse(&raw)
|
|
.ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
|
|
if provider == ProviderKind::None {
|
|
return Err("no AI provider selected".into());
|
|
}
|
|
let endpoint = if self.installer.config.ai.endpoint.is_empty() {
|
|
provider.endpoint().to_string()
|
|
} else {
|
|
self.installer.config.ai.endpoint.clone()
|
|
};
|
|
let model = if self.installer.config.ai.model.is_empty() {
|
|
provider.default_model().to_string()
|
|
} else {
|
|
self.installer.config.ai.model.clone()
|
|
};
|
|
(provider, endpoint, model, provider.as_str().to_string())
|
|
}
|
|
};
|
|
let request = build_request(kind, &model, &facts);
|
|
let body = serde_json::to_string(&request)
|
|
.map_err(|e| format!("could not build the test request: {e}"))?;
|
|
let response = match backend {
|
|
AiBackend::OpenCode => {
|
|
let transport = opencode_transport(
|
|
&self.installer.exec,
|
|
&self.installer.config,
|
|
self.opencode_password.clone(),
|
|
)?;
|
|
transport.send(kind, &endpoint, &body)
|
|
}
|
|
AiBackend::Direct => {
|
|
let transport = CurlTransport::new(&self.installer.exec, self.api_key.clone());
|
|
transport.send(kind, &endpoint, &body)
|
|
}
|
|
}
|
|
.map_err(|e| format!("connection failed: {}", redactor.redact(&e.to_string())))?;
|
|
let content = extract_content(&response).map_err(|e| {
|
|
format!(
|
|
"model response was not usable: {}",
|
|
redactor.redact(&e.to_string())
|
|
)
|
|
})?;
|
|
serde_json::from_str::<serde_json::Value>(&content)
|
|
.map_err(|_| "model response was not JSON".to_string())?;
|
|
Ok(json!({
|
|
"connected": true,
|
|
"backend": backend.as_str(),
|
|
"provider": label,
|
|
"model": model,
|
|
"response": content,
|
|
}))
|
|
}
|
|
|
|
/// Validate the provider connection and review the proposal (fail-closed).
|
|
/// Exposed so tests can drive it with a canned transport.
|
|
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
|
let facts = self.installer.system_facts();
|
|
let api_key_present = self.api_key.is_some();
|
|
let value = {
|
|
let Installer { exec, config, .. } = &mut self.installer;
|
|
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
|
|
};
|
|
self.approved_digest = None;
|
|
self.validated_ai = Some(ai_digest(&self.installer.config));
|
|
Ok(value)
|
|
}
|
|
|
|
// -- authorization and install ------------------------------------------
|
|
|
|
fn approve(&mut self, request: &Request) -> Result<Value, String> {
|
|
let phrase = request.erase.clone().unwrap_or_default();
|
|
if phrase != "ERASE" {
|
|
return Err("type ERASE exactly to authorize disk changes".into());
|
|
}
|
|
if request.final_confirm != Some(true) {
|
|
return Err("the final confirmation is required".into());
|
|
}
|
|
let digest = self.plan_digest();
|
|
self.approved_digest = Some(digest.clone());
|
|
Ok(json!({ "approved": true, "plan_digest": digest }))
|
|
}
|
|
|
|
fn start_install(
|
|
&mut self,
|
|
id: u64,
|
|
request: &Request,
|
|
out: &mut (dyn Write + Send),
|
|
) -> io::Result<()> {
|
|
let result = self.run_install(id, request, out);
|
|
match result {
|
|
Ok(data) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": true, "op": "start_install", "data": data }),
|
|
),
|
|
Err(error) => write_json(
|
|
out,
|
|
&json!({ "id": id, "ok": false, "op": "start_install", "error": error }),
|
|
),
|
|
}
|
|
}
|
|
|
|
fn run_install(
|
|
&mut self,
|
|
id: u64,
|
|
request: &Request,
|
|
out: &mut (dyn Write + Send),
|
|
) -> Result<Value, String> {
|
|
if self.installing {
|
|
return Err("an installation is already in progress".into());
|
|
}
|
|
if self.installed {
|
|
return Err(
|
|
"this session has already installed Phoebus; start a new session to \
|
|
install again"
|
|
.into(),
|
|
);
|
|
}
|
|
// The plan may not have changed since the user approved it.
|
|
let current = self.plan_digest();
|
|
match (&self.approved_digest, &request.plan_digest) {
|
|
(Some(approved), Some(presented)) if approved == presented && presented == ¤t => {
|
|
}
|
|
_ => {
|
|
return Err(
|
|
"the installation plan is not approved (or changed since approval); \
|
|
review the plan and click 'Install now' again"
|
|
.into(),
|
|
)
|
|
}
|
|
}
|
|
|
|
// AI is mandatory to install unless this is a dry run or an explicit
|
|
// break-glass. A validated interaction is required: merely naming a
|
|
// provider is not enough. The validation is bound to the current
|
|
// configuration, so a change since validation invalidates it.
|
|
let dry_run = self.installer.config.runtime.dry_run;
|
|
if !dry_run {
|
|
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
|
.unwrap_or(false);
|
|
let validated =
|
|
self.validated_ai.as_deref() == Some(ai_digest(&self.installer.config).as_str());
|
|
if !validated && !break_glass {
|
|
return Err(
|
|
"installing Phoebus requires a successful, validated AI interaction for \
|
|
the current configuration; connect and validate a model, or set \
|
|
PHOEBUS_NO_AI=1 for a deterministic install"
|
|
.into(),
|
|
);
|
|
}
|
|
}
|
|
|
|
let issues = self.installer.validate();
|
|
if !issues.is_empty() {
|
|
let text = issues
|
|
.iter()
|
|
.map(|i| i.to_string())
|
|
.collect::<Vec<_>>()
|
|
.join("; ");
|
|
return Err(format!("configuration is incomplete: {text}"));
|
|
}
|
|
|
|
let preview = self.installer.destructive_preview();
|
|
let confirm = BridgeConfirm {
|
|
erase: request.erase.as_deref() == Some("ERASE"),
|
|
final_ok: request.final_confirm == Some(true),
|
|
};
|
|
let auth = authorize(&confirm, &preview, "Start the installation now?")
|
|
.map_err(|e| self.installer.exec.redactor().redact(&e.to_string()))?;
|
|
|
|
let (tx, rx) = std::sync::mpsc::channel::<Value>();
|
|
let tx_log = tx.clone();
|
|
let log_listener = std::sync::Arc::new(move |chunk: &str| {
|
|
for line in chunk.lines() {
|
|
let line = line.trim();
|
|
if !line.is_empty() {
|
|
let _ = tx_log.send(json!({
|
|
"event": "log",
|
|
"line": line,
|
|
}));
|
|
}
|
|
}
|
|
});
|
|
self.installer.exec.logger.add_listener(log_listener);
|
|
|
|
self.phase.set(DiskPhase::Before);
|
|
// Consume the approval and mark the session busy before any destructive
|
|
// work: a replay or a second frontend can never reach storage_prepare.
|
|
self.approved_digest = None;
|
|
self.validated_ai = None;
|
|
self.installing = true;
|
|
let outcome = std::thread::scope(|s| {
|
|
s.spawn(move || {
|
|
while let Ok(event) = rx.recv() {
|
|
let _ = write_json(out, &event);
|
|
}
|
|
});
|
|
|
|
// Hand the validated installer-time credential to finalization
|
|
// (in memory only; never in InstallConfig). When
|
|
// `reuse_ai_connection` is selected (default), finalize writes a
|
|
// direct-provider key into the new user's ~/.config/phoebus/ai.key
|
|
// (0700/0600, user-owned, symlink-safe) and stores only the path.
|
|
self.installer
|
|
.set_pending_ai_credentials(self.api_key.clone(), self.opencode_password.clone());
|
|
let res = {
|
|
let mut observer = JsonObserver {
|
|
tx: tx.clone(),
|
|
id,
|
|
phase: self.phase.clone(),
|
|
last_stage: self.last_stage.clone(),
|
|
};
|
|
self.installer.install_observed(
|
|
&auth,
|
|
self.luks.as_ref(),
|
|
self.user_password.as_ref(),
|
|
self.root_password.as_ref(),
|
|
&mut observer,
|
|
)
|
|
};
|
|
|
|
self.installer.exec.logger.clear_listeners();
|
|
drop(tx);
|
|
res
|
|
});
|
|
self.installing = false;
|
|
|
|
match outcome {
|
|
Ok(()) => {
|
|
self.installed = true;
|
|
Ok(json!({
|
|
"complete": true,
|
|
"dry_run": dry_run,
|
|
"log_path": self.installer.exec.log_path().display().to_string(),
|
|
"next_actions": [
|
|
"Remove the installation medium.",
|
|
"Restart the computer and boot Phoebus OS.",
|
|
],
|
|
}))
|
|
}
|
|
Err(e) => {
|
|
let message = self.installer.exec.redactor().redact(&e.to_string());
|
|
let (disk_changed, next_actions) = disk_change_report(self.phase.get());
|
|
let log_path = self.installer.exec.log_path().display().to_string();
|
|
let failed_stage = self
|
|
.last_stage
|
|
.get()
|
|
.map(|s| s.name().to_string())
|
|
.unwrap_or_else(|| "pre-install".to_string());
|
|
Err(format!(
|
|
"installation failed at stage [{failed_stage}]: {message}\n\
|
|
log: {log_path}\n\
|
|
disk_changed: {disk_changed}\n\
|
|
next: {}",
|
|
next_actions.join(" ")
|
|
))
|
|
}
|
|
}
|
|
}
|
|
|
|
// -- helpers ------------------------------------------------------------
|
|
|
|
/// A stable digest binding an approval to the exact plan shown. Any change
|
|
/// to the configuration (including AI-applied changes) changes it.
|
|
pub(super) fn plan_digest(&self) -> String {
|
|
config_digest(&self.installer.config)
|
|
}
|
|
|
|
fn review(&self) -> Value {
|
|
let c = &self.installer.config;
|
|
let mut subsystems = vec![c.system.init_system.clone()];
|
|
if c.desktop.profile.is_desktop() {
|
|
subsystems.push(c.desktop.audio_stack.clone());
|
|
if c.desktop.flatpak {
|
|
subsystems.push("flatpak".into());
|
|
}
|
|
}
|
|
if c.packages.nix {
|
|
subsystems.push("nix".into());
|
|
}
|
|
if c.storage.filesystem == phoebus_core::Filesystem::Btrfs {
|
|
subsystems.push("btrfs snapshots".into());
|
|
}
|
|
json!({
|
|
"target_disk": c.storage.disk,
|
|
"erase": self.installer.destructive_preview(),
|
|
"filesystem": c.storage.filesystem.as_str(),
|
|
"encryption": c.encryption.mode.as_str(),
|
|
"desktop": c.desktop.profile.as_str(),
|
|
"subvolumes": c.storage.subvols,
|
|
"subsystems": subsystems,
|
|
"hostname": c.system.hostname,
|
|
"username": c.user.username,
|
|
"timezone": c.system.timezone,
|
|
"locale": c.system.locale,
|
|
"keymap": c.system.keymap,
|
|
})
|
|
}
|
|
}
|
|
|
|
fn contains_secret_marker(toml: &str) -> bool {
|
|
let lower = toml.to_ascii_lowercase();
|
|
["passphrase", "password", "api_key", "secret"]
|
|
.iter()
|
|
.any(|m| lower.contains(m))
|
|
}
|
|
|
|
/// True when a default route exists. Read-only, no privileges.
|
|
fn network_ready() -> bool {
|
|
let Ok(text) = std::fs::read_to_string("/proc/net/route") else {
|
|
return false;
|
|
};
|
|
text.lines().skip(1).any(|line| {
|
|
let mut fields = line.split_whitespace();
|
|
let _iface = fields.next();
|
|
matches!(fields.next(), Some("00000000"))
|
|
})
|
|
}
|
|
|
|
/// The result of a bounded reachability check against the configured
|
|
/// installation source. A default route proves a local link; only a completed
|
|
/// request proves the installation services are actually reachable.
|
|
struct ServiceReachability {
|
|
reachable: bool,
|
|
detail: String,
|
|
target: String,
|
|
}
|
|
|
|
fn service_reachability(installer: &Installer) -> ServiceReachability {
|
|
use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, HttpRequest};
|
|
|
|
let config = &installer.config;
|
|
let target = if !config.stage3.url.trim().is_empty() {
|
|
config.stage3.url.trim().to_string()
|
|
} else {
|
|
config.stage3.mirror.trim().to_string()
|
|
};
|
|
if target.is_empty() {
|
|
return ServiceReachability {
|
|
reachable: false,
|
|
detail: "No installation source is configured.".into(),
|
|
target,
|
|
};
|
|
}
|
|
let mut request = HttpRequest::get(target.clone());
|
|
// Keep the check snappy: the user is waiting on it.
|
|
request.timeout = std::time::Duration::from_secs(8);
|
|
request.connect_timeout = std::time::Duration::from_secs(5);
|
|
request.max_body = 64 * 1024;
|
|
let http = CurlHttpClient::new(&installer.exec);
|
|
match http.request(&request) {
|
|
Ok(_) => ServiceReachability {
|
|
reachable: true,
|
|
detail: "Installation services are reachable.".into(),
|
|
target,
|
|
},
|
|
Err(e) => ServiceReachability {
|
|
reachable: false,
|
|
detail: installer.exec.redactor().redact(&e.to_string()),
|
|
target,
|
|
},
|
|
}
|
|
}
|
|
|
|
/// The live medium's console keymap, read without privileges. Used to tell the
|
|
/// truth about whether choosing a layout changes the running session.
|
|
fn live_keymap() -> String {
|
|
if let Ok(text) = std::fs::read_to_string("/etc/vconsole.conf") {
|
|
for line in text.lines() {
|
|
if let Some(value) = line.trim().strip_prefix("KEYMAP=") {
|
|
let value = value.trim().trim_matches('"');
|
|
if !value.is_empty() {
|
|
return value.to_string();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
std::env::var("XKB_DEFAULT_LAYOUT")
|
|
.ok()
|
|
.filter(|v| !v.trim().is_empty())
|
|
.unwrap_or_else(|| "us".into())
|
|
}
|
|
|
|
/// The live medium's timezone, read from /etc/localtime symlink or /etc/timezone.
|
|
fn live_timezone() -> String {
|
|
if let Ok(dest) = std::fs::read_link("/etc/localtime") {
|
|
let path = dest.display().to_string();
|
|
if let Some(pos) = path.find("zoneinfo/") {
|
|
let tz = &path[pos + "zoneinfo/".len()..];
|
|
if !tz.is_empty() {
|
|
return tz.to_string();
|
|
}
|
|
}
|
|
}
|
|
if let Ok(text) = std::fs::read_to_string("/etc/timezone") {
|
|
let trimmed = text.trim();
|
|
if !trimmed.is_empty() {
|
|
return trimmed.to_string();
|
|
}
|
|
}
|
|
"UTC".to_string()
|
|
}
|
|
|
|
/// Classify a connection error into a stable kind. The frontend uses this to
|
|
/// show an actionable recovery instead of a raw transport string.
|
|
pub(super) fn connection_error_kind(message: &str) -> &'static str {
|
|
let m = message.to_ascii_lowercase();
|
|
if m.contains("authentication required")
|
|
|| m.contains("requires authentication")
|
|
|| m.contains("no api key")
|
|
|| m.contains("requires an api key")
|
|
{
|
|
"authentication_required"
|
|
} else if m.contains("authentication rejected")
|
|
|| m.contains("rejected the supplied")
|
|
|| m.contains("http 401")
|
|
|| m.contains("http 403")
|
|
{
|
|
"authentication_rejected"
|
|
} else if m.contains("insecure_transport")
|
|
|| m.contains("plain http")
|
|
|| m.contains("must use https")
|
|
{
|
|
"insecure_transport"
|
|
} else if m.contains("http 404")
|
|
|| m.contains("model not found")
|
|
|| m.contains("unknown model")
|
|
|| m.contains("no such model")
|
|
{
|
|
"model_unavailable"
|
|
} else if m.contains("timed out")
|
|
|| m.contains("timeout")
|
|
|| m.contains("connection refused")
|
|
|| m.contains("could not connect")
|
|
|| m.contains("failed to connect")
|
|
|| m.contains("transport")
|
|
|| m.contains("unreachable")
|
|
{
|
|
"unreachable"
|
|
} else {
|
|
"error"
|
|
}
|
|
}
|
|
|
|
/// Turn a plain value list into `{value, label}` pairs so the frontend can show
|
|
/// human-readable names while the backend keeps validating the real identifier.
|
|
fn labeled_options(values: Vec<String>, label: fn(&str) -> String) -> Vec<Value> {
|
|
values
|
|
.into_iter()
|
|
.map(|value| {
|
|
let text = label(&value);
|
|
json!({ "value": value, "label": text })
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
pub(super) fn humanize_timezone(zone: &str) -> String {
|
|
match zone {
|
|
"UTC" => "UTC — Coordinated Universal Time".to_string(),
|
|
_ => zone.replace('_', " ").replace('/', " / "),
|
|
}
|
|
}
|
|
|
|
/// A friendly language (and region, when known) name for a POSIX locale, with
|
|
/// the technical identifier kept at the end for advanced users.
|
|
pub(super) fn humanize_locale(locale: &str) -> String {
|
|
let base = locale.split('.').next().unwrap_or(locale);
|
|
let mut parts = base.split('_');
|
|
let language = parts.next().unwrap_or("");
|
|
let region = parts.next();
|
|
match (language_name(language), region.and_then(region_name)) {
|
|
(Some(lang), Some(region)) => format!("{lang} ({region}) — {locale}"),
|
|
(Some(lang), None) => format!("{lang} — {locale}"),
|
|
_ => locale.to_string(),
|
|
}
|
|
}
|
|
|
|
fn language_name(code: &str) -> Option<&'static str> {
|
|
Some(match code {
|
|
"en" => "English",
|
|
"de" => "German",
|
|
"fr" => "French",
|
|
"es" => "Spanish",
|
|
"it" => "Italian",
|
|
"pt" => "Portuguese",
|
|
"nl" => "Dutch",
|
|
"pl" => "Polish",
|
|
"ru" => "Russian",
|
|
"uk" => "Ukrainian",
|
|
"cs" => "Czech",
|
|
"sk" => "Slovak",
|
|
"sv" => "Swedish",
|
|
"nb" | "no" => "Norwegian",
|
|
"da" => "Danish",
|
|
"fi" => "Finnish",
|
|
"el" => "Greek",
|
|
"tr" => "Turkish",
|
|
"hu" => "Hungarian",
|
|
"ro" => "Romanian",
|
|
"bg" => "Bulgarian",
|
|
"hr" => "Croatian",
|
|
"sr" => "Serbian",
|
|
"sl" => "Slovenian",
|
|
"et" => "Estonian",
|
|
"lv" => "Latvian",
|
|
"lt" => "Lithuanian",
|
|
"ja" => "Japanese",
|
|
"ko" => "Korean",
|
|
"zh" => "Chinese",
|
|
"hi" => "Hindi",
|
|
"bn" => "Bengali",
|
|
"ar" => "Arabic",
|
|
"he" => "Hebrew",
|
|
"fa" => "Persian",
|
|
"th" => "Thai",
|
|
"vi" => "Vietnamese",
|
|
"id" => "Indonesian",
|
|
"ms" => "Malay",
|
|
"sw" => "Swahili",
|
|
"ca" => "Catalan",
|
|
"gl" => "Galician",
|
|
"eu" => "Basque",
|
|
"is" => "Icelandic",
|
|
"ga" => "Irish",
|
|
"cy" => "Welsh",
|
|
"sq" => "Albanian",
|
|
"mk" => "Macedonian",
|
|
"be" => "Belarusian",
|
|
"az" => "Azerbaijani",
|
|
"kk" => "Kazakh",
|
|
"uz" => "Uzbek",
|
|
"ka" => "Georgian",
|
|
"hy" => "Armenian",
|
|
"af" => "Afrikaans",
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
fn region_name(code: &str) -> Option<&'static str> {
|
|
Some(match code.to_ascii_uppercase().as_str() {
|
|
"US" => "United States",
|
|
"GB" => "United Kingdom",
|
|
"DE" => "Germany",
|
|
"FR" => "France",
|
|
"ES" => "Spain",
|
|
"IT" => "Italy",
|
|
"PT" => "Portugal",
|
|
"BR" => "Brazil",
|
|
"NL" => "Netherlands",
|
|
"BE" => "Belgium",
|
|
"AT" => "Austria",
|
|
"CH" => "Switzerland",
|
|
"PL" => "Poland",
|
|
"RU" => "Russia",
|
|
"UA" => "Ukraine",
|
|
"CZ" => "Czechia",
|
|
"SK" => "Slovakia",
|
|
"SE" => "Sweden",
|
|
"NO" => "Norway",
|
|
"DK" => "Denmark",
|
|
"FI" => "Finland",
|
|
"GR" => "Greece",
|
|
"TR" => "Türkiye",
|
|
"HU" => "Hungary",
|
|
"RO" => "Romania",
|
|
"BG" => "Bulgaria",
|
|
"HR" => "Croatia",
|
|
"RS" => "Serbia",
|
|
"SI" => "Slovenia",
|
|
"EE" => "Estonia",
|
|
"LV" => "Latvia",
|
|
"LT" => "Lithuania",
|
|
"JP" => "Japan",
|
|
"KR" => "South Korea",
|
|
"CN" => "China",
|
|
"TW" => "Taiwan",
|
|
"IN" => "India",
|
|
"SG" => "Singapore",
|
|
"AU" => "Australia",
|
|
"NZ" => "New Zealand",
|
|
"CA" => "Canada",
|
|
"MX" => "Mexico",
|
|
"AR" => "Argentina",
|
|
"ZA" => "South Africa",
|
|
"IE" => "Ireland",
|
|
"IL" => "Israel",
|
|
"AE" => "United Arab Emirates",
|
|
"SA" => "Saudi Arabia",
|
|
"TH" => "Thailand",
|
|
"VN" => "Vietnam",
|
|
"ID" => "Indonesia",
|
|
"MY" => "Malaysia",
|
|
"PH" => "Philippines",
|
|
_ => return None,
|
|
})
|
|
}
|
|
|
|
/// A friendly keyboard name for a console keymap identifier, with the technical
|
|
/// name kept so an advanced user can still see exactly what will be set.
|
|
#[allow(dead_code)]
|
|
pub(super) fn humanize_keymap(name: &str) -> String {
|
|
let base = name.split('-').next().unwrap_or(name);
|
|
let language = match base {
|
|
"us" => "English (US)",
|
|
"gb" | "uk" => "English (UK)",
|
|
"au" => "English (Australia)",
|
|
"nz" => "English (New Zealand)",
|
|
"za" => "English (South Africa)",
|
|
"de" => "German",
|
|
"fr" => "French",
|
|
"es" => "Spanish",
|
|
"it" => "Italian",
|
|
"pt" => "Portuguese",
|
|
"br" | "br-abnt2" => "Portuguese (Brazil)",
|
|
"latam" => "Spanish (Latin America)",
|
|
"nl" => "Dutch",
|
|
"be" => "Belgian",
|
|
"dk" => "Danish",
|
|
"no" => "Norwegian",
|
|
"se" => "Swedish",
|
|
"fi" => "Finnish",
|
|
"is" => "Icelandic",
|
|
"pl" => "Polish",
|
|
"cz" => "Czech",
|
|
"sk" => "Slovak",
|
|
"hu" => "Hungarian",
|
|
"ro" => "Romanian",
|
|
"bg" => "Bulgarian",
|
|
"gr" => "Greek",
|
|
"ru" => "Russian",
|
|
"ua" => "Ukrainian",
|
|
"tr" => "Turkish",
|
|
"il" => "Hebrew",
|
|
"ara" => "Arabic",
|
|
"in" => "Indian",
|
|
"jp" | "jp106" => "Japanese",
|
|
"kr" => "Korean",
|
|
"cn" => "Chinese",
|
|
"tw" => "Chinese (Taiwan)",
|
|
"ca" => "Canadian",
|
|
"cf" => "Canadian (French)",
|
|
"ch" => "Swiss",
|
|
"at" => "German (Austria)",
|
|
"ie" => "Irish",
|
|
"si" => "Slovenian",
|
|
"hr" => "Croatian",
|
|
"ee" => "Estonian",
|
|
"lt" => "Lithuanian",
|
|
"lv" => "Latvian",
|
|
"mk" => "Macedonian",
|
|
"rs" => "Serbian",
|
|
"by" => "Belarusian",
|
|
"kz" => "Kazakh",
|
|
"al" => "Albanian",
|
|
"ba" => "Bosnian",
|
|
"ph" => "Filipino",
|
|
"id" => "Indonesian",
|
|
"my" => "Malay",
|
|
"mt" => "Maltese",
|
|
"np" => "Nepali",
|
|
"pk" => "Urdu",
|
|
"uz" => "Uzbek",
|
|
"et" => "Amharic",
|
|
"bd" => "Bangla",
|
|
"af" => "Dari",
|
|
"dz" => "Berber",
|
|
"kh" => "Khmer",
|
|
"la" => "Lao",
|
|
"me" => "Montenegrin",
|
|
"mn" => "Mongolian",
|
|
"us-dvorak" | "dvorak" => "Dvorak",
|
|
"colemak" => "Colemak",
|
|
"mac-us" => "Mac (US)",
|
|
"sg" => "Swiss German",
|
|
"th" => "Thai",
|
|
"vn" => "Vietnamese",
|
|
"ir" | "fa" => "Persian",
|
|
"az" => "Azerbaijani",
|
|
"ge" => "Georgian",
|
|
"am" => "Armenian",
|
|
_ => "",
|
|
};
|
|
if language.is_empty() {
|
|
name.to_string()
|
|
} else if language == name {
|
|
language.to_string()
|
|
} else {
|
|
format!("{language} — {name}")
|
|
}
|
|
}
|
|
|
|
fn iso_version() -> String {
|
|
if let Ok(text) = std::fs::read_to_string("/etc/phoebus/version") {
|
|
let t = text.trim();
|
|
if !t.is_empty() {
|
|
return t.to_string();
|
|
}
|
|
}
|
|
phoebus_core::VERSION.to_string()
|
|
}
|
|
|
|
/// A deterministic digest of the configuration plus the step sequence. Any
|
|
/// material change to the plan changes the digest, invalidating an approval.
|
|
fn config_digest(config: &InstallConfig) -> String {
|
|
use sha2::{Digest, Sha256};
|
|
let mut hasher = Sha256::new();
|
|
hasher.update(config.to_toml_string().unwrap_or_default().as_bytes());
|
|
for step in InstallStep::sequence() {
|
|
hasher.update(step.name().as_bytes());
|
|
}
|
|
format!("{:x}", hasher.finalize())
|
|
}
|
|
|
|
/// The OpenCode server URL, provider id, model id and variant, validated for presence.
|
|
fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String, String), String> {
|
|
let server = config.ai.opencode_server.trim().to_string();
|
|
let provider = config.ai.opencode_provider.trim().to_string();
|
|
let model = config.ai.opencode_model.trim().to_string();
|
|
let variant = config.ai.opencode_variant().to_string();
|
|
if server.is_empty() {
|
|
return Err("OpenCode requires a server URL".into());
|
|
}
|
|
if provider.is_empty() {
|
|
return Err("OpenCode requires a provider".into());
|
|
}
|
|
if model.is_empty() {
|
|
return Err("OpenCode requires a model".into());
|
|
}
|
|
// Fail fast on an unsafe endpoint, before any request is attempted.
|
|
phoebus_executor::opencode_server::Endpoint::parse(&server)
|
|
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
|
|
Ok((server, provider, model, variant))
|
|
}
|
|
|
|
/// Time zones offered by the live system, from the zoneinfo database.
|
|
fn system_timezones() -> Vec<String> {
|
|
let mut zones: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
if let Ok(text) = std::fs::read_to_string("/usr/share/zoneinfo/zone.tab") {
|
|
for line in text.lines() {
|
|
let line = line.trim();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
continue;
|
|
}
|
|
if let Some(tz) = line.split_whitespace().nth(2) {
|
|
zones.insert(tz.to_string());
|
|
}
|
|
}
|
|
}
|
|
if zones.is_empty() {
|
|
for zone in [
|
|
"UTC",
|
|
"Europe/London",
|
|
"Europe/Berlin",
|
|
"Europe/Paris",
|
|
"America/New_York",
|
|
"America/Chicago",
|
|
"America/Denver",
|
|
"America/Los_Angeles",
|
|
"Asia/Tokyo",
|
|
"Asia/Shanghai",
|
|
"Asia/Kolkata",
|
|
"Australia/Sydney",
|
|
] {
|
|
zones.insert(zone.to_string());
|
|
}
|
|
}
|
|
zones.into_iter().take(2000).collect()
|
|
}
|
|
|
|
/// Locales from the system's i18n database (or a common fallback set).
|
|
fn system_locales() -> Vec<String> {
|
|
let mut locales: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
if let Ok(text) = std::fs::read_to_string("/usr/share/i18n/SUPPORTED") {
|
|
for line in text.lines() {
|
|
let line = line.trim();
|
|
if line.is_empty() || line.starts_with('#') {
|
|
continue;
|
|
}
|
|
if let Some(locale) = line.split_whitespace().next() {
|
|
if locale.contains("UTF-8") {
|
|
locales.insert(locale.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if locales.is_empty() {
|
|
for locale in [
|
|
"en_US.UTF-8",
|
|
"en_GB.UTF-8",
|
|
"de_DE.UTF-8",
|
|
"fr_FR.UTF-8",
|
|
"es_ES.UTF-8",
|
|
"it_IT.UTF-8",
|
|
"pt_BR.UTF-8",
|
|
"pt_PT.UTF-8",
|
|
"ja_JP.UTF-8",
|
|
"zh_CN.UTF-8",
|
|
"zh_TW.UTF-8",
|
|
"ko_KR.UTF-8",
|
|
"ru_RU.UTF-8",
|
|
"nl_NL.UTF-8",
|
|
"pl_PL.UTF-8",
|
|
"sv_SE.UTF-8",
|
|
"da_DK.UTF-8",
|
|
"nb_NO.UTF-8",
|
|
"fi_FI.UTF-8",
|
|
"cs_CZ.UTF-8",
|
|
"uk_UA.UTF-8",
|
|
"tr_TR.UTF-8",
|
|
] {
|
|
locales.insert(locale.to_string());
|
|
}
|
|
}
|
|
|
|
const TOP_LOCALES: &[&str] = &[
|
|
"en_US.UTF-8",
|
|
"en_GB.UTF-8",
|
|
"de_DE.UTF-8",
|
|
"fr_FR.UTF-8",
|
|
"es_ES.UTF-8",
|
|
"es_MX.UTF-8",
|
|
"it_IT.UTF-8",
|
|
"pt_BR.UTF-8",
|
|
"pt_PT.UTF-8",
|
|
"nl_NL.UTF-8",
|
|
"pl_PL.UTF-8",
|
|
"ru_RU.UTF-8",
|
|
"uk_UA.UTF-8",
|
|
"ja_JP.UTF-8",
|
|
"zh_CN.UTF-8",
|
|
"zh_TW.UTF-8",
|
|
"ko_KR.UTF-8",
|
|
"sv_SE.UTF-8",
|
|
"nb_NO.UTF-8",
|
|
"da_DK.UTF-8",
|
|
"fi_FI.UTF-8",
|
|
"tr_TR.UTF-8",
|
|
"el_GR.UTF-8",
|
|
"cs_CZ.UTF-8",
|
|
];
|
|
|
|
let mut result = Vec::new();
|
|
let mut seen = std::collections::BTreeSet::new();
|
|
|
|
for &loc in TOP_LOCALES {
|
|
if locales.contains(loc) {
|
|
result.push(loc.to_string());
|
|
seen.insert(loc.to_string());
|
|
}
|
|
}
|
|
|
|
let mut remaining: Vec<String> = locales.into_iter().filter(|l| !seen.contains(l)).collect();
|
|
remaining.sort_by_key(|a| humanize_locale(a));
|
|
|
|
result.extend(remaining);
|
|
result.into_iter().take(2000).collect()
|
|
}
|
|
|
|
/// Structured keyboard layout options with human-readable labels from XKB rules.
|
|
fn system_keymap_options() -> Vec<Value> {
|
|
let mut map: std::collections::BTreeMap<String, String> = std::collections::BTreeMap::new();
|
|
for path in [
|
|
"/usr/share/X11/xkb/rules/evdev.lst",
|
|
"/usr/share/X11/xkb/rules/base.lst",
|
|
] {
|
|
if let Ok(content) = std::fs::read_to_string(path) {
|
|
let mut in_layout = false;
|
|
for line in content.lines() {
|
|
let trimmed = line.trim();
|
|
if trimmed.starts_with('!') {
|
|
if trimmed == "! layout" {
|
|
in_layout = true;
|
|
} else if in_layout {
|
|
break;
|
|
}
|
|
continue;
|
|
}
|
|
if in_layout && !trimmed.is_empty() {
|
|
let mut parts = trimmed.split_whitespace();
|
|
if let Some(code) = parts.next() {
|
|
if code != "custom" {
|
|
let desc = parts.collect::<Vec<_>>().join(" ");
|
|
if !desc.is_empty() {
|
|
map.insert(code.to_string(), desc);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if !map.is_empty() {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
const TOP_KEYMAPS: &[(&str, &str)] = &[
|
|
("us", "English (US)"),
|
|
("gb", "English (UK)"),
|
|
("de", "German"),
|
|
("fr", "French"),
|
|
("es", "Spanish"),
|
|
("latam", "Spanish (Latin America)"),
|
|
("it", "Italian"),
|
|
("pt", "Portuguese"),
|
|
("br", "Portuguese (Brazil)"),
|
|
("nl", "Dutch"),
|
|
("pl", "Polish"),
|
|
("ru", "Russian"),
|
|
("ua", "Ukrainian"),
|
|
("jp", "Japanese"),
|
|
("cn", "Chinese"),
|
|
("kr", "Korean"),
|
|
("se", "Swedish"),
|
|
("no", "Norwegian"),
|
|
("dk", "Danish"),
|
|
("fi", "Finnish"),
|
|
("cz", "Czech"),
|
|
("sk", "Slovak"),
|
|
("hu", "Hungarian"),
|
|
("ro", "Romanian"),
|
|
("tr", "Turkish"),
|
|
("gr", "Greek"),
|
|
("ara", "Arabic"),
|
|
("il", "Hebrew"),
|
|
("in", "Indian"),
|
|
("dvorak", "English (Dvorak)"),
|
|
("colemak", "English (Colemak)"),
|
|
];
|
|
|
|
let mut result = Vec::new();
|
|
let mut seen = std::collections::BTreeSet::new();
|
|
|
|
for &(code, default_desc) in TOP_KEYMAPS {
|
|
let desc = map.get(code).map(|s| s.as_str()).unwrap_or(default_desc);
|
|
result.push(json!({
|
|
"value": code,
|
|
"label": format!("{desc} — {code}"),
|
|
}));
|
|
seen.insert(code.to_string());
|
|
}
|
|
|
|
let mut remaining: Vec<(String, String)> = map
|
|
.into_iter()
|
|
.filter(|(code, _)| !seen.contains(code))
|
|
.collect();
|
|
remaining.sort_by(|a, b| a.1.cmp(&b.1));
|
|
|
|
for (code, desc) in remaining {
|
|
result.push(json!({
|
|
"value": code.clone(),
|
|
"label": format!("{desc} — {code}"),
|
|
}));
|
|
}
|
|
|
|
result
|
|
}
|
|
|
|
/// Keyboard layout codes from XKB rules (or a standard desktop fallback set).
|
|
#[allow(dead_code)]
|
|
fn system_keymaps() -> Vec<String> {
|
|
system_keymap_options()
|
|
.into_iter()
|
|
.filter_map(|v| v["value"].as_str().map(String::from))
|
|
.collect()
|
|
}
|
|
|
|
/// The OpenAI-compatible model-list URL for a chat-completions endpoint.
|
|
pub(super) fn models_url(endpoint: &str) -> String {
|
|
let trimmed = endpoint.trim().trim_end_matches('/');
|
|
if let Some(base) = trimmed.strip_suffix("/chat/completions") {
|
|
format!("{base}/models")
|
|
} else {
|
|
format!("{trimmed}/models")
|
|
}
|
|
}
|
|
|
|
/// Extract model ids from an OpenAI-compatible `/models` response.
|
|
pub(super) fn parse_model_ids(body: &str) -> Vec<String> {
|
|
let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
|
|
if let Ok(value) = serde_json::from_str::<Value>(body) {
|
|
if let Some(data) = value.get("data").and_then(|d| d.as_array()) {
|
|
for item in data {
|
|
if let Some(id) = item.get("id").and_then(|v| v.as_str()) {
|
|
ids.insert(id.to_string());
|
|
}
|
|
}
|
|
}
|
|
if ids.is_empty() {
|
|
if let Some(models) = value.get("models").and_then(|m| m.as_array()) {
|
|
for item in models {
|
|
if let Some(id) = item
|
|
.get("id")
|
|
.and_then(|v| v.as_str())
|
|
.or_else(|| item.get("name").and_then(|v| v.as_str()))
|
|
{
|
|
ids.insert(id.to_string());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
ids.into_iter().collect()
|
|
}
|
|
|
|
fn opencode_transport<'a>(
|
|
exec: &'a Exec,
|
|
config: &InstallConfig,
|
|
password: Option<SecretString>,
|
|
) -> Result<phoebus_executor::opencode_client::ExecOpenCodeTransport<'a>, String> {
|
|
let (server, provider, model, variant) = opencode_parts(config)?;
|
|
let mut transport = phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
|
exec, server, provider, model,
|
|
)
|
|
.with_auth(password);
|
|
if !variant.is_empty() && variant != "default" {
|
|
transport = transport.with_variant(variant);
|
|
}
|
|
Ok(transport)
|
|
}
|
|
|
|
#[allow(clippy::too_many_arguments)]
|
|
fn finish_review(
|
|
config: &mut InstallConfig,
|
|
redactor: &phoebus_core::Redactor,
|
|
facts: SystemFacts,
|
|
kind: ProviderKind,
|
|
endpoint: &str,
|
|
provider_label: &str,
|
|
model: &str,
|
|
transport: &dyn ModelTransport,
|
|
backend: &str,
|
|
) -> Result<Value, String> {
|
|
let outcome =
|
|
ai_guide::generate_and_review_at(config, &facts, kind, endpoint, model, transport)
|
|
.map_err(|e| {
|
|
// Error messages are redacted before they reach the GUI.
|
|
format!(
|
|
"connection or proposal failed: {}",
|
|
redactor.redact(&e.to_string())
|
|
)
|
|
})?;
|
|
let applied: Vec<Value> = outcome
|
|
.applied
|
|
.iter()
|
|
.filter(|c| !c.description.to_lowercase().starts_with("flatpak"))
|
|
.map(|c| {
|
|
json!({
|
|
"description": c.description,
|
|
"reason": c.reason,
|
|
"evidence": c.evidence,
|
|
})
|
|
})
|
|
.collect();
|
|
Ok(json!({
|
|
"connected": true,
|
|
"backend": backend,
|
|
"provider": provider_label,
|
|
"model": model,
|
|
"endpoint": endpoint,
|
|
"applied": applied,
|
|
"config": config,
|
|
"plan_digest": config_digest(config),
|
|
}))
|
|
}
|
|
|
|
/// OpenCode proposal review: the adapter talks the agent protocol and the
|
|
/// shared strict proposal parser/review applies the accepted changes.
|
|
fn review_opencode(
|
|
config: &mut InstallConfig,
|
|
redactor: &phoebus_core::Redactor,
|
|
facts: SystemFacts,
|
|
transport: &dyn ModelTransport,
|
|
) -> Result<Value, String> {
|
|
let (server, provider_id, model, _variant) = opencode_parts(config)?;
|
|
finish_review(
|
|
config,
|
|
redactor,
|
|
facts,
|
|
ProviderKind::Local,
|
|
&server,
|
|
&provider_id,
|
|
&model,
|
|
transport,
|
|
"opencode",
|
|
)
|
|
}
|
|
|
|
/// A deterministic digest of only the AI connection settings. The mandatory-AI
|
|
/// validation is bound to this, so choosing a disk or typing an account
|
|
/// password does not discard a successful model interaction, while changing the
|
|
/// provider, model, endpoint or server does.
|
|
fn ai_digest(config: &InstallConfig) -> String {
|
|
use sha2::{Digest, Sha256};
|
|
let ai = &config.ai;
|
|
let mut hasher = Sha256::new();
|
|
for field in [
|
|
ai.backend.as_str(),
|
|
ai.provider.as_str(),
|
|
ai.model.as_str(),
|
|
ai.endpoint.as_str(),
|
|
ai.opencode_server.as_str(),
|
|
ai.opencode_provider.as_str(),
|
|
ai.opencode_model.as_str(),
|
|
ai.opencode_variant.as_str(),
|
|
] {
|
|
hasher.update(field.as_bytes());
|
|
hasher.update([0u8]);
|
|
}
|
|
format!("{:x}", hasher.finalize())
|
|
}
|
|
|
|
/// Parse the direct provider from the configuration, validate the connection
|
|
/// and apply the reviewed proposal. This is the same `ai_guide` path the TUI
|
|
/// uses.
|
|
fn review_proposal(
|
|
config: &mut InstallConfig,
|
|
redactor: &phoebus_core::Redactor,
|
|
facts: SystemFacts,
|
|
api_key_present: bool,
|
|
transport: &dyn ModelTransport,
|
|
) -> Result<Value, String> {
|
|
let raw = config.ai.provider.clone();
|
|
let provider =
|
|
ProviderKind::parse(&raw).ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
|
|
if provider == ProviderKind::None {
|
|
return Err("no AI provider selected".into());
|
|
}
|
|
let endpoint = if config.ai.endpoint.is_empty() {
|
|
provider.endpoint().to_string()
|
|
} else {
|
|
config.ai.endpoint.clone()
|
|
};
|
|
let model = if config.ai.model.is_empty() {
|
|
provider.default_model().to_string()
|
|
} else {
|
|
config.ai.model.clone()
|
|
};
|
|
if provider.requires_key() && !api_key_present {
|
|
return Err(format!(
|
|
"provider `{}` requires an API key",
|
|
provider.as_str()
|
|
));
|
|
}
|
|
finish_review(
|
|
config,
|
|
redactor,
|
|
facts,
|
|
provider,
|
|
&endpoint,
|
|
provider.as_str(),
|
|
&model,
|
|
transport,
|
|
"direct",
|
|
)
|
|
}
|
|
|
|
/// The stdio entry point used by `--gui-bridge`.
|
|
pub fn run_stdio() -> io::Result<()> {
|
|
// The live medium may preseed the wizard's starting configuration. The
|
|
// deterministic CLI already honours `/etc/phoebus/install.conf`; the
|
|
// graphical wizard uses the same file so the two paths agree. A test or
|
|
// automation caller can point at another file with `PHOEBUS_GUI_CONFIG`.
|
|
// Only the defaults change: validation, the plan, the AI gate and the
|
|
// ERASE authorization are all unchanged.
|
|
let explicit = std::env::var("PHOEBUS_GUI_CONFIG")
|
|
.ok()
|
|
.filter(|p| !p.trim().is_empty());
|
|
let mut config = if let Some(path) = explicit {
|
|
InstallConfig::load_from_path(std::path::Path::new(path.trim())).map_err(|e| {
|
|
io::Error::new(
|
|
io::ErrorKind::InvalidInput,
|
|
format!("cannot load PHOEBUS_GUI_CONFIG: {e}"),
|
|
)
|
|
})?
|
|
} else {
|
|
let default = std::path::Path::new("/etc/phoebus/install.conf");
|
|
if default.is_file() {
|
|
InstallConfig::load_from_path(default).unwrap_or_else(|e| {
|
|
eprintln!("ignoring /etc/phoebus/install.conf: {e}");
|
|
InstallConfig::default()
|
|
})
|
|
} else {
|
|
InstallConfig::default()
|
|
}
|
|
};
|
|
// Test/automation hook: a dry run is non-destructive, so it is safe to
|
|
// expose through the environment for the harness. It never changes the
|
|
// authorization requirements.
|
|
if std::env::var("PHOEBUS_DRY_RUN")
|
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
|
.unwrap_or(false)
|
|
{
|
|
config.runtime.dry_run = true;
|
|
}
|
|
let mut state_dir = std::path::PathBuf::from(&config.runtime.state_dir);
|
|
if std::fs::create_dir_all(&state_dir).is_err() {
|
|
state_dir = std::path::PathBuf::from("/tmp/phoebus-installer");
|
|
std::fs::create_dir_all(&state_dir).ok();
|
|
}
|
|
let logger = phoebus_executor::Logger::open(
|
|
state_dir.join("install.log"),
|
|
phoebus_core::Redactor::new(),
|
|
false,
|
|
);
|
|
let logger_clone = logger.clone();
|
|
let runner = phoebus_executor::RealRunner::with_sink(std::sync::Arc::new(move |text: &str| {
|
|
logger_clone.stream_output(text);
|
|
}));
|
|
let exec = Exec::new(
|
|
Box::new(runner),
|
|
logger,
|
|
config.runtime.dry_run,
|
|
config.storage.install_root.clone(),
|
|
state_dir,
|
|
);
|
|
let mut bridge = Bridge::new(config, exec);
|
|
|
|
let stdin = io::stdin();
|
|
let mut out = io::stdout();
|
|
for line in stdin.lock().lines() {
|
|
let line = line?;
|
|
bridge.handle_line(&line, &mut out)?;
|
|
if bridge.should_quit() {
|
|
break;
|
|
}
|
|
}
|
|
Ok(())
|
|
}
|