feat(ai): guided AI optimization with DeepSeek/OpenAI providers

Add an OpenAI-compatible provider layer (DeepSeek, OpenAI and a test
transport) that sends only bounded system facts and injects the API key via a
curl config on stdin, never in argv, config or logs. Extend the typed proposal
schema with scoped package.use, build jobs and binary-package preference; every
change now needs a non-empty reason and duplicates are rejected. Wire
--ai/--ai-proposal-file/--ai-facts into the CLI and add provider selection to
the TUI. Deterministic validation and review are unchanged: the model never
reaches the executor and the no-AI path keeps working.
This commit is contained in:
Phoebus 2026-09-20 04:47:11 -07:00
parent fcda004834
commit b45e61e361
11 changed files with 1415 additions and 24 deletions

View file

@ -7,9 +7,10 @@
//! step performed by the deterministic backend.
pub mod privacy;
pub mod provider;
use phoebus_core::config::{
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy,
DesktopProfile, Encryption, Filesystem, InstallConfig, KernelProfile, PackagePolicy, PackageUse,
};
use phoebus_core::validate;
use serde::{Deserialize, Serialize};
@ -22,31 +23,89 @@ pub enum AiError {
UnsupportedVersion(u32),
#[error("change rejected: {0}")]
Rejected(String),
#[error("AI provider unavailable: {0}")]
ProviderUnavailable(String),
#[error("AI provider error: {0}")]
Provider(String),
#[error("model context would carry personal data: {0}")]
PrivateData(String),
}
/// A versioned, closed set of configuration changes.
/// A versioned, closed set of configuration changes, each with a rationale.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AiProposal {
pub version: u32,
pub changes: Vec<ProposedChange>,
/// One entry per change, naming the action and giving the evidence/reason.
#[serde(default)]
pub rationale: Vec<Rationale>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
/// Why a change was proposed. Deterministic code requires a non-empty reason
/// for every accepted change.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct Rationale {
pub action: String,
pub reason: String,
#[serde(default)]
pub evidence: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(tag = "action", rename_all = "snake_case", deny_unknown_fields)]
pub enum ProposedChange {
SetHostname { value: String },
SetTimezone { value: String },
SetLocale { value: String },
SetKeymap { value: String },
SetUsername { value: String },
SetTargetDisk { value: String },
SetFilesystem { value: Filesystem },
SetEncryption { value: Encryption },
SetKernelProfile { value: KernelProfile },
SetPackagePolicy { value: PackagePolicy },
SetDesktopProfile { value: DesktopProfile },
SetFlatpak { value: bool },
SetHostname {
value: String,
},
SetTimezone {
value: String,
},
SetLocale {
value: String,
},
SetKeymap {
value: String,
},
SetUsername {
value: String,
},
SetTargetDisk {
value: String,
},
SetFilesystem {
value: Filesystem,
},
SetEncryption {
value: Encryption,
},
SetKernelProfile {
value: KernelProfile,
},
SetPackagePolicy {
value: PackagePolicy,
},
SetDesktopProfile {
value: DesktopProfile,
},
SetFlatpak {
value: bool,
},
/// Prefer signed binary packages (still signature-verified).
SetBinaryPackages {
value: bool,
},
/// Explicit Portage `MAKEOPTS -j` value (capped by available memory later).
SetBuildJobs {
value: u32,
},
/// One scoped `package.use` flag for one atom.
SetPackageUse {
atom: String,
flag: String,
enabled: bool,
},
}
impl ProposedChange {
@ -64,10 +123,67 @@ impl ProposedChange {
ProposedChange::SetPackagePolicy { value } => format!("package policy = {value}"),
ProposedChange::SetDesktopProfile { value } => format!("desktop profile = {value}"),
ProposedChange::SetFlatpak { value } => format!("flatpak = {value}"),
ProposedChange::SetBinaryPackages { value } => {
format!("prefer signed binary packages = {value}")
}
ProposedChange::SetBuildJobs { value } => format!("build jobs = {value}"),
ProposedChange::SetPackageUse {
atom,
flag,
enabled,
} => format!(
"package.use {atom} {}{flag}",
if *enabled { "" } else { "-" }
),
}
}
/// Semantic validation against the current configuration.
/// The stable action name (matches the serde tag).
pub fn action_name(&self) -> &'static str {
match self {
ProposedChange::SetHostname { .. } => "set_hostname",
ProposedChange::SetTimezone { .. } => "set_timezone",
ProposedChange::SetLocale { .. } => "set_locale",
ProposedChange::SetKeymap { .. } => "set_keymap",
ProposedChange::SetUsername { .. } => "set_username",
ProposedChange::SetTargetDisk { .. } => "set_target_disk",
ProposedChange::SetFilesystem { .. } => "set_filesystem",
ProposedChange::SetEncryption { .. } => "set_encryption",
ProposedChange::SetKernelProfile { .. } => "set_kernel_profile",
ProposedChange::SetPackagePolicy { .. } => "set_package_policy",
ProposedChange::SetDesktopProfile { .. } => "set_desktop_profile",
ProposedChange::SetFlatpak { .. } => "set_flatpak",
ProposedChange::SetBinaryPackages { .. } => "set_binary_packages",
ProposedChange::SetBuildJobs { .. } => "set_build_jobs",
ProposedChange::SetPackageUse { .. } => "set_package_use",
}
}
/// A key identifying what this change touches, for conflict detection.
pub fn target_key(&self) -> String {
match self {
ProposedChange::SetHostname { .. } => "system.hostname".into(),
ProposedChange::SetTimezone { .. } => "system.timezone".into(),
ProposedChange::SetLocale { .. } => "system.locale".into(),
ProposedChange::SetKeymap { .. } => "system.keymap".into(),
ProposedChange::SetUsername { .. } => "user.username".into(),
ProposedChange::SetTargetDisk { .. } => "storage.disk".into(),
ProposedChange::SetFilesystem { .. } => "storage.filesystem".into(),
ProposedChange::SetEncryption { .. } => "encryption.mode".into(),
ProposedChange::SetKernelProfile { .. } => "kernel.profile".into(),
ProposedChange::SetPackagePolicy { .. } => "packages.policy".into(),
ProposedChange::SetDesktopProfile { .. } => "desktop.profile".into(),
ProposedChange::SetFlatpak { .. } => "desktop.flatpak".into(),
ProposedChange::SetBinaryPackages { .. } => "packages.binary_packages".into(),
ProposedChange::SetBuildJobs { .. } => "packages.build_jobs".into(),
ProposedChange::SetPackageUse { atom, flag, .. } => {
format!("packages.package_use:{atom}:{flag}")
}
}
}
/// Semantic validation. `package.use` changes are validated with the same
/// rules the configuration uses.
pub fn validate(&self) -> Result<(), String> {
match self {
ProposedChange::SetHostname { value } => validate::validate_hostname(value),
@ -82,6 +198,17 @@ impl ProposedChange {
Err(format!("target disk must be a /dev path: {value}"))
}
}
ProposedChange::SetBuildJobs { value } => {
if (1..=256).contains(value) {
Ok(())
} else {
Err(format!("build jobs must be between 1 and 256: {value}"))
}
}
ProposedChange::SetPackageUse { atom, flag, .. } => {
validate::validate_package_atom(atom)?;
validate::validate_use_flag(flag)
}
_ => Ok(()),
}
}
@ -129,6 +256,29 @@ pub fn apply(
ProposedChange::SetPackagePolicy { value } => config.packages.policy = *value,
ProposedChange::SetDesktopProfile { value } => config.desktop.profile = *value,
ProposedChange::SetFlatpak { value } => config.desktop.flatpak = *value,
ProposedChange::SetBinaryPackages { value } => config.packages.binary_packages = *value,
ProposedChange::SetBuildJobs { value } => config.packages.build_jobs = Some(*value),
ProposedChange::SetPackageUse {
atom,
flag,
enabled,
} => {
let entry = PackageUse {
atom: atom.clone(),
flag: flag.clone(),
enabled: *enabled,
};
if let Some(existing) = config
.packages
.package_use
.iter_mut()
.find(|e| e.atom == *atom && e.flag == *flag)
{
existing.enabled = *enabled;
} else {
config.packages.package_use.push(entry);
}
}
}
applied.push(AppliedChange {
description: change.describe(),
@ -137,6 +287,101 @@ pub fn apply(
Ok(applied)
}
/// A change that passed review, with the model's stated reason.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewedChange {
pub description: String,
pub reason: String,
pub evidence: Vec<String>,
}
/// The result of reviewing a proposal: the changes that were applied and the
/// rationale behind each.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ReviewOutcome {
pub applied: Vec<ReviewedChange>,
}
impl ReviewOutcome {
/// A compact human-readable summary of accepted changes and reasons.
pub fn render(&self) -> String {
let mut out = String::new();
out.push_str("Accepted AI changes:\n");
if self.applied.is_empty() {
out.push_str(" (none)\n");
}
for change in &self.applied {
out.push_str(&format!(" + {}\n", change.description));
out.push_str(&format!(" reason: {}\n", change.reason));
for item in &change.evidence {
out.push_str(&format!(" evidence: {item}\n"));
}
}
out
}
}
/// Validate a proposal with mandatory evidence, reject conflicts, and apply it
/// atomically (fail closed). This is the path a guided install uses; the model
/// never reaches the executor without passing it.
pub fn review(config: &mut InstallConfig, proposal: &AiProposal) -> Result<ReviewOutcome, AiError> {
if proposal.version != 1 {
return Err(AiError::UnsupportedVersion(proposal.version));
}
// Every change needs an explicit, non-empty reason.
let reason_for = |change: &ProposedChange| -> Result<&Rationale, AiError> {
proposal
.rationale
.iter()
.find(|r| r.action == change.action_name() && !r.reason.trim().is_empty())
.ok_or_else(|| {
AiError::Rejected(format!(
"{}: missing a non-empty reason",
change.action_name()
))
})
};
// Reject conflicts before applying anything.
let mut seen: Vec<String> = Vec::new();
for change in &proposal.changes {
let key = change.target_key();
if seen.contains(&key) {
return Err(AiError::Rejected(format!("conflicting changes for {key}")));
}
seen.push(key);
}
// Validate everything; a single failure rejects the whole proposal.
for change in &proposal.changes {
change.validate().map_err(AiError::Rejected)?;
reason_for(change)?;
}
// Apply only after all checks pass. `apply` repeats validation, which is
// harmless and keeps a single merge implementation.
let applied = apply(config, proposal)?;
let reviewed = proposal
.changes
.iter()
.zip(applied)
.map(|(change, applied)| {
let rationale = proposal
.rationale
.iter()
.find(|r| r.action == change.action_name())
.expect("reason checked above");
ReviewedChange {
description: applied.description,
reason: rationale.reason.clone(),
evidence: rationale.evidence.clone(),
}
})
.collect();
Ok(ReviewOutcome { applied: reviewed })
}
#[cfg(test)]
mod tests {
use super::*;
@ -193,4 +438,105 @@ mod tests {
let text = r#"{"version":1,"changes":[{"action":"set_filesystem","value":"zfs"}]}"#;
assert!(parse_proposal(text).is_err());
}
#[test]
fn review_applies_scoped_package_use_and_build_jobs() {
let text = r#"{
"version": 1,
"changes": [
{"action":"set_build_jobs","value":6},
{"action":"set_binary_packages","value":true},
{"action":"set_package_use","atom":"www-client/firefox","flag":"wayland","enabled":true}
],
"rationale": [
{"action":"set_build_jobs","reason":"16 GiB of RAM","evidence":["memory_mib=16384"]},
{"action":"set_binary_packages","reason":"signed binhost is available","evidence":["binhost=openrc"]},
{"action":"set_package_use","reason":"wayland desktop","evidence":["desktop=dwl"]}
]
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
let outcome = review(&mut config, &proposal).unwrap();
assert_eq!(outcome.applied.len(), 3);
assert_eq!(config.packages.build_jobs, Some(6));
assert!(config.packages.binary_packages);
assert_eq!(config.packages.package_use.len(), 1);
assert_eq!(config.packages.package_use[0].atom, "www-client/firefox");
let rendered = outcome.render();
assert!(rendered.contains("reason:"));
assert!(rendered.contains("evidence:"));
}
#[test]
fn review_rejects_a_change_without_a_reason() {
let text = r#"{
"version": 1,
"changes": [{"action":"set_hostname","value":"box"}],
"rationale": []
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
assert!(matches!(
review(&mut config, &proposal),
Err(AiError::Rejected(_))
));
// Nothing applied.
assert_eq!(config.system.hostname, "phoebus");
}
#[test]
fn review_rejects_conflicting_changes() {
let text = r#"{
"version": 1,
"changes": [
{"action":"set_hostname","value":"one"},
{"action":"set_hostname","value":"two"}
],
"rationale": [
{"action":"set_hostname","reason":"a"},
{"action":"set_hostname","reason":"b"}
]
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
assert!(matches!(
review(&mut config, &proposal),
Err(AiError::Rejected(_))
));
assert_eq!(config.system.hostname, "phoebus");
}
#[test]
fn review_rejects_unsafe_package_use() {
let text = r#"{
"version": 1,
"changes": [
{"action":"set_package_use","atom":"*/*","flag":"*","enabled":true}
],
"rationale": [{"action":"set_package_use","reason":"all"}]
}"#;
let proposal = parse_proposal(text).unwrap();
let mut config = InstallConfig::default();
assert!(matches!(
review(&mut config, &proposal),
Err(AiError::Rejected(_))
));
assert!(config.packages.package_use.is_empty());
}
#[test]
fn review_requires_a_supported_version() {
let proposal = parse_proposal(r#"{"version":1,"changes":[]}"#).unwrap();
let mut config = InstallConfig::default();
assert!(review(&mut config, &proposal).is_ok());
let bad = AiProposal {
version: 2,
changes: vec![],
rationale: vec![],
};
assert!(matches!(
review(&mut config, &bad),
Err(AiError::UnsupportedVersion(2))
));
}
}

View file

@ -0,0 +1,475 @@
//! Model provider connections.
//!
//! DeepSeek and OpenAI both expose an OpenAI-compatible chat-completions API,
//! so one request/response shape covers both. The provider layer builds the
//! request from a closed set of approved [`SystemFacts`]; the API key is never
//! part of the request and is injected by the transport (see
//! `phoebus-executor::ai`). [`TestTransport`] makes the whole path exercisable
//! without a network.
use std::collections::{BTreeMap, HashMap};
use phoebus_core::config::InstallConfig;
use phoebus_core::hardware::HardwareReport;
use serde::{Deserialize, Serialize};
use crate::privacy::is_forbidden_path;
use crate::{parse_proposal, AiError, AiProposal};
/// The selectable providers. `None` means "continue without AI".
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProviderKind {
None,
DeepSeek,
OpenAi,
}
impl ProviderKind {
pub fn as_str(self) -> &'static str {
match self {
ProviderKind::None => "none",
ProviderKind::DeepSeek => "deepseek",
ProviderKind::OpenAi => "openai",
}
}
/// Parse a user-facing provider name (aliases included).
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"" | "none" | "no" | "off" | "without" => Some(ProviderKind::None),
"deepseek" => Some(ProviderKind::DeepSeek),
"openai" | "chatgpt" | "gpt" => Some(ProviderKind::OpenAi),
_ => None,
}
}
/// The chat-completions endpoint.
pub fn endpoint(self) -> &'static str {
match self {
ProviderKind::None => "",
ProviderKind::DeepSeek => "https://api.deepseek.com/chat/completions",
ProviderKind::OpenAi => "https://api.openai.com/v1/chat/completions",
}
}
pub fn default_model(self) -> &'static str {
match self {
ProviderKind::None => "",
ProviderKind::DeepSeek => "deepseek-chat",
ProviderKind::OpenAi => "gpt-4o-mini",
}
}
pub fn requires_key(self) -> bool {
!matches!(self, ProviderKind::None)
}
}
/// A bounded summary of the machine, and nothing else. No home directories, no
/// logs, no credentials, no file contents.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SystemFacts {
pub arch: String,
pub cpu_model: String,
pub cpu_cores: u32,
pub memory_mib: u64,
pub cpu_features: Vec<String>,
pub gpu_vendors: Vec<String>,
pub firmware: String,
pub target_disk: String,
pub disk_size_gib: u64,
pub disk_ssd: bool,
pub gentoo_profile: String,
pub binhost_available: bool,
pub desktop_profile: String,
pub filesystem: String,
pub encryption: String,
pub recommended_kernel_profile: String,
/// Measured compile times (seconds) for the slowest packages, capped.
pub measured_compile_times: BTreeMap<String, u64>,
}
/// Storage facts supplied by the caller (disk probing lives in the executor).
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DiskSummary {
pub path: String,
pub size_gib: u64,
pub ssd: bool,
}
const MAX_HISTORY: usize = 40;
impl SystemFacts {
pub fn from_system(
config: &InstallConfig,
hardware: &HardwareReport,
history: &HashMap<String, u64>,
binhost_available: bool,
disk: Option<DiskSummary>,
) -> Self {
let mut measured: Vec<(String, u64)> = history
.iter()
.map(|(atom, secs)| (atom.clone(), *secs))
.collect();
measured.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
measured.truncate(MAX_HISTORY);
let disk = disk.unwrap_or_default();
SystemFacts {
arch: config.system.arch.clone(),
cpu_model: hardware.cpu.model.clone(),
cpu_cores: hardware.cpu.cores,
memory_mib: hardware.memory_mib,
cpu_features: hardware.cpu.features.clone(),
gpu_vendors: hardware
.gpu_vendors()
.into_iter()
.map(|v| v.as_str().to_string())
.collect(),
firmware: hardware.firmware_str().to_string(),
target_disk: disk.path,
disk_size_gib: disk.size_gib,
disk_ssd: disk.ssd,
gentoo_profile: phoebus_core::system::selected_profile(config),
binhost_available,
desktop_profile: config.desktop.profile.to_string(),
filesystem: config.storage.filesystem.to_string(),
encryption: config.encryption.mode.to_string(),
recommended_kernel_profile: hardware.recommended_kernel_profile().to_string(),
measured_compile_times: measured.into_iter().collect(),
}
}
pub fn render(&self) -> String {
serde_json::to_string_pretty(self).unwrap_or_else(|_| "{}".to_string())
}
/// Refuse to send facts if any string field looks like a personal path.
pub fn validate_no_forbidden(&self) -> Result<(), AiError> {
let strings = [
&self.arch,
&self.cpu_model,
&self.firmware,
&self.target_disk,
&self.gentoo_profile,
&self.desktop_profile,
&self.filesystem,
&self.encryption,
&self.recommended_kernel_profile,
];
for value in strings.into_iter().chain(self.gpu_vendors.iter()) {
if is_forbidden_path(value) {
return Err(AiError::PrivateData(value.clone()));
}
}
for atom in self.measured_compile_times.keys() {
if is_forbidden_path(atom) {
return Err(AiError::PrivateData(atom.clone()));
}
}
Ok(())
}
}
/// The instructions given to the model. They are deliberately explicit about
/// the closed action set and the evidence requirement.
pub const SYSTEM_PROMPT: &str = "\
You are the Phoebus OS installation advisor. You may ONLY propose changes using \
this closed set of actions, each with a non-empty reason and optional evidence:
set_hostname, set_timezone, set_locale, set_keymap, set_username, set_target_disk,
set_filesystem (btrfs|ext4), set_encryption (none|luks2), set_kernel_profile
(safe|optimized|aggressive), set_package_policy (balanced|source_first|binary_first),
set_desktop_profile (none|minimal|dwl|full), set_flatpak (bool),
set_binary_packages (bool), set_build_jobs (1-256), set_package_use (atom, flag,
enabled).
Reply with ONLY a JSON object of the form:
{\"version\":1,\"changes\":[{\"action\":\"...\",...}],\"rationale\":[{\"action\":\"...\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
Rules: prefer stability and a proven boot over speculative performance; never
propose disabling signature verification, enabling ~amd64 globally, weakening
LUKS2/Btrfs/systemd/UEFI, or any shell/command action; do not invent package
atoms; keep required boot/encryption/filesystem settings fixed. You do not have
a shell and cannot execute anything.";
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ChatMessage {
pub role: String,
pub content: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct ResponseFormat {
#[serde(rename = "type")]
pub kind: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ChatRequest {
pub model: String,
pub messages: Vec<ChatMessage>,
pub temperature: f32,
#[serde(skip_serializing_if = "Option::is_none")]
pub response_format: Option<ResponseFormat>,
}
/// Build the chat request for a provider. The API key is not part of it.
pub fn build_request(provider: ProviderKind, model: &str, facts: &SystemFacts) -> ChatRequest {
let model = if model.trim().is_empty() {
provider.default_model().to_string()
} else {
model.trim().to_string()
};
let user = format!(
"Detected system facts (JSON):\n{}\n\nPropose a version 1 AiProposal.",
facts.render()
);
ChatRequest {
model,
messages: vec![
ChatMessage {
role: "system".into(),
content: SYSTEM_PROMPT.into(),
},
ChatMessage {
role: "user".into(),
content: user,
},
],
temperature: 0.0,
response_format: Some(ResponseFormat {
kind: "json_object".into(),
}),
}
}
#[derive(Debug, Deserialize)]
struct ChatResponse {
choices: Vec<Choice>,
}
#[derive(Debug, Deserialize)]
struct Choice {
message: ChoiceMessage,
}
#[derive(Debug, Deserialize)]
struct ChoiceMessage {
content: String,
}
/// Extract the assistant's text content from a chat-completions response and
/// strip a Markdown code fence if the model added one.
pub fn extract_content(body: &str) -> Result<String, AiError> {
let parsed: ChatResponse = serde_json::from_str(body)
.map_err(|e| AiError::Provider(format!("invalid chat response: {e}")))?;
let content = parsed
.choices
.first()
.map(|c| c.message.content.trim().to_string())
.filter(|c| !c.is_empty())
.ok_or_else(|| AiError::Provider("model returned no content".into()))?;
let inner = if let Some(rest) = content.strip_prefix("```") {
let rest = rest.strip_prefix("json").unwrap_or(rest);
rest.trim_start_matches(['\n', '\r'])
.trim_end()
.strip_suffix("```")
.unwrap_or(rest)
.trim()
.to_string()
} else {
content
};
if inner.is_empty() {
return Err(AiError::Provider("model returned empty content".into()));
}
Ok(inner)
}
/// Transport used to reach a provider. The executor implements this with curl;
/// tests implement it with canned responses.
pub trait ModelTransport {
fn send(&self, provider: ProviderKind, url: &str, body: &str) -> Result<String, AiError>;
}
/// A transport that always returns a fixed response (tests, offline dry runs).
pub struct TestTransport {
pub response: String,
}
impl TestTransport {
pub fn new(response: impl Into<String>) -> Self {
Self {
response: response.into(),
}
}
/// Wrap a bare proposal JSON in an OpenAI-style chat response.
pub fn proposal(proposal_json: &str) -> Self {
Self::new(
serde_json::json!({
"choices": [{ "message": { "content": proposal_json } }]
})
.to_string(),
)
}
}
impl ModelTransport for TestTransport {
fn send(&self, _provider: ProviderKind, _url: &str, _body: &str) -> Result<String, AiError> {
Ok(self.response.clone())
}
}
/// Ask a provider for a proposal and parse it, fail-closed at every step.
pub fn complete_proposal(
provider: ProviderKind,
model: &str,
facts: &SystemFacts,
transport: &dyn ModelTransport,
) -> Result<AiProposal, AiError> {
if provider == ProviderKind::None {
return Err(AiError::ProviderUnavailable(
"no AI provider selected".into(),
));
}
facts.validate_no_forbidden()?;
let request = build_request(provider, model, facts);
let body = serde_json::to_string(&request)?;
let response = transport.send(provider, provider.endpoint(), &body)?;
let content = extract_content(&response)?;
parse_proposal(&content)
}
#[cfg(test)]
mod tests {
use super::*;
use phoebus_core::config::InstallConfig;
use phoebus_core::hardware::{CpuInfo, GpuInfo, GpuVendor, HardwareReport};
fn facts() -> SystemFacts {
let mut config = InstallConfig::default();
config.desktop.profile = phoebus_core::DesktopProfile::Dwl;
let hardware = HardwareReport {
cpu: CpuInfo {
model: "Test CPU".into(),
cores: 8,
features: vec!["vmx".into(), "avx2".into()],
..Default::default()
},
memory_mib: 16384,
gpus: vec![GpuInfo {
vendor: GpuVendor::Intel,
description: "iGPU".into(),
}],
..Default::default()
};
let history = HashMap::from([("sys-apps/systemd".to_string(), 420u64)]);
SystemFacts::from_system(
&config,
&hardware,
&history,
true,
Some(DiskSummary {
path: "/dev/vda".into(),
size_gib: 32,
ssd: true,
}),
)
}
#[test]
fn facts_contain_only_system_data() {
let facts = facts();
let rendered = facts.render();
assert!(rendered.contains("Test CPU"));
assert!(rendered.contains("/dev/vda"));
assert!(!rendered.contains("/home/"));
assert!(!is_forbidden_path(&facts.target_disk));
facts.validate_no_forbidden().unwrap();
}
#[test]
fn forbidden_paths_in_facts_are_refused() {
let mut facts = facts();
facts.cpu_model = "/home/alice/secret".into();
assert!(matches!(
facts.validate_no_forbidden(),
Err(AiError::PrivateData(_))
));
}
#[test]
fn history_is_capped_and_sorted() {
let mut history = HashMap::new();
for i in 0..100u64 {
history.insert(format!("cat/pkg{i}"), i);
}
let facts = SystemFacts::from_system(
&InstallConfig::default(),
&HardwareReport::default(),
&history,
true,
None,
);
assert_eq!(facts.measured_compile_times.len(), MAX_HISTORY);
// The 40 slowest packages (60..=99) are kept.
assert!(facts
.measured_compile_times
.values()
.all(|v| *v >= 100 - MAX_HISTORY as u64));
}
#[test]
fn provider_endpoints_and_parsing() {
assert_eq!(ProviderKind::parse("ChatGPT"), Some(ProviderKind::OpenAi));
assert_eq!(
ProviderKind::parse("deepseek"),
Some(ProviderKind::DeepSeek)
);
assert_eq!(ProviderKind::parse("continue without AI"), None);
assert_eq!(ProviderKind::parse("none"), Some(ProviderKind::None));
assert!(ProviderKind::OpenAi.endpoint().starts_with("https://"));
assert!(ProviderKind::None.endpoint().is_empty());
assert!(ProviderKind::DeepSeek.requires_key());
assert!(!ProviderKind::None.requires_key());
}
#[test]
fn request_has_no_secret_and_pins_the_schema() {
let request = build_request(ProviderKind::DeepSeek, "", &facts());
let body = serde_json::to_string(&request).unwrap();
assert_eq!(request.model, "deepseek-chat");
assert!(body.contains(SYSTEM_PROMPT.split('.').next().unwrap()));
assert!(!body.to_lowercase().contains("api_key"));
assert!(!body.contains("Bearer"));
assert_eq!(
request.response_format.as_ref().map(|r| r.kind.as_str()),
Some("json_object")
);
}
#[test]
fn extract_content_strips_code_fences() {
let body = r#"{"choices":[{"message":{"content":"```json\n{\"version\":1,\"changes\":[]}\n```"}}]}"#;
let content = extract_content(body).unwrap();
assert_eq!(content, r#"{"version":1,"changes":[]}"#);
assert!(extract_content("not json").is_err());
assert!(extract_content(r#"{"choices":[]}"#).is_err());
}
#[test]
fn test_transport_round_trips_a_proposal() {
let proposal = r#"{"version":1,"changes":[{"action":"set_flatpak","value":true}]}"#;
let transport = TestTransport::proposal(proposal);
let parsed = complete_proposal(ProviderKind::OpenAi, "", &facts(), &transport).unwrap();
assert_eq!(parsed.changes.len(), 1);
}
#[test]
fn unavailable_provider_is_explicit() {
let transport = TestTransport::new("{}");
let err = complete_proposal(ProviderKind::None, "", &facts(), &transport).unwrap_err();
assert!(matches!(err, AiError::ProviderUnavailable(_)));
}
}

View file

@ -0,0 +1,158 @@
//! Model provider transport.
//!
//! The API key never appears on a command line or in a log. It is injected into
//! a curl configuration file passed on stdin, while curl reads the JSON request
//! body from a 0600 temporary file. The body contains only the approved facts
//! built by `phoebus_ai::provider`.
use std::path::Path;
use phoebus_ai::provider::{ModelTransport, ProviderKind};
use phoebus_ai::AiError;
use phoebus_core::SecretString;
use crate::command::CommandSpec;
use crate::error::{ExecError, Result};
use crate::exec::Exec;
/// Read an API key from a file that must be mode 0600. The value is returned
/// as a `SecretString`; callers must register it with the redactor (the
/// transport does this automatically).
pub fn load_api_key(path: &Path) -> Result<SecretString> {
use std::os::unix::fs::PermissionsExt;
let meta = std::fs::metadata(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
if meta.permissions().mode() & 0o077 != 0 {
return Err(ExecError::operation(
"ai",
"read API key",
format!("{} must be mode 0600", path.display()),
));
}
let key = std::fs::read_to_string(path).map_err(|e| ExecError::io(path.to_path_buf(), e))?;
let key = key.trim().to_string();
if key.is_empty() {
return Err(ExecError::operation(
"ai",
"read API key",
"API key file is empty",
));
}
Ok(SecretString::new(key))
}
/// A transport that talks to an OpenAI-compatible endpoint with curl.
pub struct CurlTransport<'a> {
exec: &'a Exec,
api_key: SecretString,
}
impl<'a> CurlTransport<'a> {
pub fn new(exec: &'a Exec, api_key: SecretString) -> Self {
exec.register_secret(&api_key);
Self { exec, api_key }
}
}
impl ModelTransport for CurlTransport<'_> {
fn send(
&self,
_provider: ProviderKind,
url: &str,
body: &str,
) -> std::result::Result<String, AiError> {
let mut request = tempfile::Builder::new()
.prefix("phoebus-ai-request.")
.tempfile()
.map_err(|e| AiError::Provider(e.to_string()))?;
use std::io::Write;
request
.write_all(body.as_bytes())
.and_then(|_| request.flush())
.map_err(|e| AiError::Provider(e.to_string()))?;
// curl reads this config from stdin, so Exec marks the stdin as hidden
// and never logs it. The key is therefore absent from argv and logs.
let config = format!(
"url = \"{url}\"\n\
header = \"Content-Type: application/json\"\n\
header = \"Authorization: Bearer {key}\"\n\
data = \"@{path}\"\n\
silent\nshow-error\nfail-with-body\nmax-time = 120\n",
key = self.api_key.expose(),
path = request.path().display()
);
let spec = CommandSpec::new("ai", "query model", "curl")
.args(["-sS", "-K", "-"])
.stdin(config.into_bytes());
let out = self
.exec
.run(spec)
.map_err(|e| AiError::Provider(e.to_string()))?;
Ok(out.stdout_lossy())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::command::{CommandOutput, RecordingRunner};
use crate::log::Logger;
use phoebus_core::Redactor;
use std::os::unix::fs::PermissionsExt;
use std::time::Duration;
fn make_exec(runner: RecordingRunner) -> Exec {
let path = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(path.join("l.log"), Redactor::new(), false);
Exec::new(Box::new(runner), logger, false, path.join("root"), path)
}
#[test]
fn api_key_must_be_mode_0600() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("key");
std::fs::write(&path, "sk-test\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
assert!(load_api_key(&path).is_err());
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
assert_eq!(load_api_key(&path).unwrap().expose(), "sk-test");
}
#[test]
fn curl_transport_keeps_the_key_out_of_arguments_and_logs() {
let runner = RecordingRunner::new();
runner.set_response(
"curl",
CommandOutput {
status: 0,
success: true,
stdout: br#"{"choices":[{"message":{"content":"{}"}}]}"#.to_vec(),
stderr: Vec::new(),
duration: Duration::from_millis(1),
},
);
let exec = make_exec(runner.clone());
let transport = CurlTransport::new(&exec, SecretString::new("sk-secret-value"));
let out = transport
.send(
ProviderKind::OpenAi,
"https://example.invalid/v1/chat/completions",
r#"{"model":"m"}"#,
)
.unwrap();
assert!(out.contains("choices"));
let specs = runner.recorded();
let spec = &specs[0];
assert_eq!(spec.program, "curl");
assert!(
!spec.args.iter().any(|a| a.contains("sk-secret-value")),
"the key must not be in argv: {:?}",
spec.args
);
let stdin = String::from_utf8(spec.stdin.clone().unwrap()).unwrap();
assert!(stdin.contains("Authorization: Bearer sk-secret-value"));
// And the key is registered for redaction.
assert_eq!(exec.redactor().redact("sk-secret-value"), "<redacted>");
}
}

View file

@ -6,6 +6,7 @@
pub mod actions;
pub mod admin;
pub mod ai;
pub mod auth;
pub mod boot;
pub mod command;

View file

@ -12,6 +12,7 @@ path = "src/main.rs"
[dependencies]
phoebus-core.workspace = true
phoebus-executor.workspace = true
phoebus-ai.workspace = true
phoebus-tui = { path = "../phoebus-tui" }
clap.workspace = true
serde.workspace = true

View file

@ -0,0 +1,119 @@
//! Guided (AI-assisted) installation.
//!
//! This is the only place a model response becomes configuration. The response
//! is parsed into the closed `AiProposal` schema, reviewed with mandatory
//! evidence and conflict detection, and applied atomically. The model never
//! receives secrets and never reaches the executor.
use std::path::Path;
use phoebus_ai::provider::{complete_proposal, ModelTransport, ProviderKind, SystemFacts};
use phoebus_ai::{parse_proposal, review, AiError, ReviewOutcome};
use phoebus_core::InstallConfig;
/// Review a full chat-completions response body and apply the accepted changes.
pub fn review_response(
config: &mut InstallConfig,
response_body: &str,
) -> Result<ReviewOutcome, AiError> {
let content = phoebus_ai::provider::extract_content(response_body)?;
let proposal = parse_proposal(&content)?;
review(config, &proposal)
}
/// Review a bare proposal (already-extracted JSON) and apply it.
pub fn review_proposal_text(
config: &mut InstallConfig,
text: &str,
) -> Result<ReviewOutcome, AiError> {
let proposal = parse_proposal(text)?;
review(config, &proposal)
}
/// Read a proposal from a file. The file may be a full chat response (as a
/// provider returns) or a bare proposal JSON object. Review is atomic, so a
/// failed first interpretation leaves the configuration untouched.
pub fn review_file(config: &mut InstallConfig, path: &Path) -> Result<ReviewOutcome, AiError> {
let text = std::fs::read_to_string(path)
.map_err(|e| AiError::Provider(format!("cannot read {}: {e}", path.display())))?;
if let Ok(outcome) = review_response(config, &text) {
return Ok(outcome);
}
review_proposal_text(config, &text)
}
/// Ask a provider for a proposal and review it (fail-closed).
pub fn generate_and_review(
config: &mut InstallConfig,
facts: &SystemFacts,
provider: ProviderKind,
model: &str,
transport: &dyn ModelTransport,
) -> Result<ReviewOutcome, AiError> {
let proposal = complete_proposal(provider, model, facts, transport)?;
review(config, &proposal)
}
#[cfg(test)]
mod tests {
use super::*;
use phoebus_ai::provider::TestTransport;
const PROPOSAL: &str = r#"{
"version": 1,
"changes": [
{"action":"set_kernel_profile","value":"safe"},
{"action":"set_build_jobs","value":4}
],
"rationale": [
{"action":"set_kernel_profile","reason":"stability over novelty","evidence":["proven boot uses gentoo-kernel-bin"]},
{"action":"set_build_jobs","reason":"16 GiB RAM","evidence":["memory_mib=16384"]}
]
}"#;
#[test]
fn proposal_file_is_reviewed_and_applied() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proposal.json");
std::fs::write(&path, PROPOSAL).unwrap();
let mut config = InstallConfig::default();
let outcome = review_file(&mut config, &path).unwrap();
assert_eq!(outcome.applied.len(), 2);
assert_eq!(config.kernel.profile, phoebus_core::KernelProfile::Safe);
assert_eq!(config.packages.build_jobs, Some(4));
}
#[test]
fn chat_response_is_unwrapped() {
let transport = TestTransport::proposal(PROPOSAL);
let mut config = InstallConfig::default();
let outcome = review_response(&mut config, &transport.response).unwrap();
assert_eq!(outcome.applied.len(), 2);
}
#[test]
fn invalid_proposal_leaves_config_unchanged() {
let bad = r#"{"version":1,"changes":[{"action":"set_hostname","value":"bad host"}],"rationale":[{"action":"set_hostname","reason":"x"}]}"#;
let mut config = InstallConfig::default();
assert!(review_proposal_text(&mut config, bad).is_err());
assert_eq!(config.system.hostname, "phoebus");
}
#[test]
fn generate_uses_the_same_review_path() {
use phoebus_core::hardware::HardwareReport;
let facts = SystemFacts::from_system(
&InstallConfig::default(),
&HardwareReport::default(),
&std::collections::HashMap::new(),
true,
None,
);
let transport = TestTransport::proposal(PROPOSAL);
let mut config = InstallConfig::default();
let outcome =
generate_and_review(&mut config, &facts, ProviderKind::DeepSeek, "", &transport)
.unwrap();
assert_eq!(outcome.applied.len(), 2);
}
}

View file

@ -1,5 +1,6 @@
//! Phoebus installer orchestration and CLI support.
pub mod ai_guide;
pub mod orchestrate;
pub mod release;

View file

@ -9,6 +9,7 @@ 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,
@ -76,6 +77,30 @@ struct Cli {
/// 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,
}
struct TerminalConfirm;
@ -111,6 +136,69 @@ fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
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 or none)").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 key_path = cli
.ai_api_key_file
.as_ref()
.ok_or("--ai-api-key-file is required for a live AI provider")?;
let api_key = phoebus_executor::ai::load_api_key(key_path)?;
let model = cli.ai_model.clone().unwrap_or_default();
let transport = phoebus_executor::ai::CurlTransport::new(&installer.exec, api_key);
let outcome = phoebus_installer::ai_guide::generate_and_review(
&mut installer.config,
&facts,
provider,
&model,
&transport,
)?;
println!("{}", outcome.render());
Ok(())
}
fn main() -> ExitCode {
match run() {
Ok(code) => code,
@ -183,11 +271,6 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
}
}
if let Some(path) = &cli.save_config {
std::fs::write(path, config.to_toml_string()?)?;
println!("wrote {}", path.display());
}
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");
@ -229,6 +312,17 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
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)?;
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());

View file

@ -76,6 +76,41 @@ impl Installer {
probe::probe_disk_layout(self.exec.runner.as_ref(), &self.config.storage.disk)
}
/// Bounded system facts for AI assistance: hardware, selected profile,
/// signed-binhost availability and measured compile times. No personal
/// data, credentials or file contents.
pub fn system_facts(&self) -> phoebus_ai::provider::SystemFacts {
let persistent = self.exec.root.join("var/lib/phoebus/compile-times.tsv");
let volatile = self.exec.state_dir.join("compile-times.tsv");
let history = if persistent.exists() {
load_history(&persistent)
} else {
load_history(&volatile)
};
let binhost_available = self.config.packages.binary_packages
&& !phoebus_core::system::resolved_binhost_uri(&self.config).is_empty();
let disk = self
.disks
.iter()
.find(|d| d.path == self.config.storage.disk)
.map(|d| phoebus_ai::provider::DiskSummary {
path: d.path.clone(),
size_gib: d.size_bytes / (1024 * 1024 * 1024),
ssd: d
.transport
.as_deref()
.map(|t| t.contains("nvme"))
.unwrap_or(false),
});
phoebus_ai::provider::SystemFacts::from_system(
&self.config,
&self.hardware,
&history,
binhost_available,
disk,
)
}
/// Configuration plus target-disk validation.
pub fn validate(&self) -> Vec<ValidationIssue> {
let mut issues = validate::validate_config(&self.config);

View file

@ -0,0 +1,127 @@
//! End-to-end tests for the AI-assisted path.
//!
//! These run the real binary with `--ai-proposal-file`, which sends a proposal
//! through exactly the same parse -> review (evidence + conflicts) -> apply ->
//! plan path the live provider path uses. Provider fixtures are labelled as
//! such; no test here claims a live provider call.
use std::process::Command;
fn bin() -> &'static str {
env!("CARGO_BIN_EXE_phoebus-installer")
}
fn run_with_proposal(body: &str, extra: &[&str]) -> std::process::Output {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("proposal.json");
std::fs::write(&path, body).unwrap();
let mut cmd = Command::new(bin());
cmd.arg("--ai-proposal-file")
.arg(&path)
.arg("--plan")
.args(extra);
cmd.output().expect("run phoebus-installer")
}
const VALID: &str = r#"{
"version": 1,
"changes": [
{"action":"set_kernel_profile","value":"safe"},
{"action":"set_build_jobs","value":4}
],
"rationale": [
{"action":"set_kernel_profile","reason":"stability over novelty","evidence":["the proven boot uses gentoo-kernel-bin"]},
{"action":"set_build_jobs","reason":"16 GiB RAM","evidence":["memory_mib=16384"]}
]
}"#;
#[test]
fn valid_proposal_is_accepted_and_reaches_the_plan() {
let out = run_with_proposal(VALID, &[]);
assert!(out.status.success(), "{:?}", out);
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Accepted AI changes"), "{stdout}");
assert!(stdout.contains("kernel profile = safe"), "{stdout}");
assert!(
stdout.contains("reason: stability over novelty"),
"{stdout}"
);
// The canonical plan reflects the change.
assert!(stdout.contains("gentoo-kernel-bin"), "{stdout}");
}
#[test]
fn missing_evidence_is_rejected() {
let body = r#"{
"version": 1,
"changes": [{"action":"set_hostname","value":"box"}],
"rationale": []
}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("reason"));
}
#[test]
fn conflicting_changes_are_rejected() {
let body = r#"{
"version": 1,
"changes": [
{"action":"set_hostname","value":"one"},
{"action":"set_hostname","value":"two"}
],
"rationale": [
{"action":"set_hostname","reason":"a"},
{"action":"set_hostname","reason":"b"}
]
}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).contains("conflicting"));
}
#[test]
fn malicious_proposal_is_refused() {
let body = r#"{"version":1,"changes":[{"action":"run_shell","command":"rm -rf /"}]}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("invalid") || err.contains("unknown"), "{err}");
}
#[test]
fn invalid_value_is_refused() {
let body = r#"{
"version": 1,
"changes": [{"action":"set_hostname","value":"bad host"}],
"rationale": [{"action":"set_hostname","reason":"x"}]
}"#;
let out = run_with_proposal(body, &[]);
assert!(!out.status.success());
}
#[test]
fn no_ai_fallback_still_prints_a_plan() {
let out = Command::new(bin())
.arg("--plan")
.output()
.expect("run phoebus-installer --plan");
assert!(out.status.success());
let stdout = String::from_utf8_lossy(&out.stdout);
assert!(stdout.contains("Installation plan"));
assert!(!stdout.contains("Accepted AI changes"));
}
#[test]
fn ai_facts_are_printed_without_a_provider() {
let out = Command::new(bin())
.arg("--ai-facts")
.output()
.expect("run phoebus-installer --ai-facts");
assert!(out.status.success(), "{:?}", out);
let stdout = String::from_utf8_lossy(&out.stdout);
// The approved fact set is JSON and contains no personal path.
assert!(stdout.trim_start().starts_with('{'), "{stdout}");
assert!(stdout.contains("gentoo_profile"));
assert!(!stdout.contains("/home/"), "{stdout}");
}

View file

@ -55,6 +55,7 @@ enum Choice {
KernelProfile,
PackagePolicy,
DesktopProfile,
AiProvider,
}
enum Mode {
@ -123,6 +124,14 @@ impl App {
}
.into(),
),
(
"AI assistant".into(),
if c.ai.enabled && !c.ai.provider.is_empty() {
c.ai.provider.clone()
} else {
"none".into()
},
),
("Review plan".into(), String::new()),
("Install".into(), String::new()),
("Exit".into(), String::new()),
@ -194,9 +203,10 @@ impl App {
self.mode =
Mode::Edit(self.edit("User password", "", EditTarget::UserPassword, true))
}
14 => self.mode = Mode::Plan(self.render_plan(), 0),
15 => self.mode = Mode::ConfirmErase,
16 => self.mode = Mode::Message("__exit__".into()),
14 => self.mode = Mode::Choice(Choice::AiProvider, 0),
15 => self.mode = Mode::Plan(self.render_plan(), 0),
16 => self.mode = Mode::ConfirmErase,
17 => self.mode = Mode::Message("__exit__".into()),
_ => {}
}
}
@ -390,6 +400,7 @@ fn choice_options(choice: Choice, _config: &InstallConfig) -> Vec<String> {
DesktopProfile::Minimal.to_string(),
DesktopProfile::Full.to_string(),
],
Choice::AiProvider => vec!["none".into(), "deepseek".into(), "openai".into()],
}
}
@ -442,6 +453,17 @@ fn apply_choice(choice: Choice, index: usize, config: &mut InstallConfig) {
DesktopProfile::Full,
][index.min(3)];
}
Choice::AiProvider => {
let provider = ["none", "deepseek", "openai"][index.min(2)];
config.ai.provider = provider.to_string();
config.ai.enabled = provider != "none";
if config.ai.enabled && config.ai.model.is_empty() {
config.ai.model = match provider {
"deepseek" => "deepseek-chat".to_string(),
_ => "gpt-4o-mini".to_string(),
};
}
}
}
}
@ -600,4 +622,16 @@ mod tests {
apply_choice(Choice::Encryption, 1, &mut config);
assert_eq!(config.encryption.mode, Encryption::None);
}
#[test]
fn ai_provider_choice_enables_and_defaults_the_model() {
let mut config = InstallConfig::default();
apply_choice(Choice::AiProvider, 1, &mut config);
assert_eq!(config.ai.provider, "deepseek");
assert!(config.ai.enabled);
assert_eq!(config.ai.model, "deepseek-chat");
apply_choice(Choice::AiProvider, 0, &mut config);
assert_eq!(config.ai.provider, "none");
assert!(!config.ai.enabled);
}
}