feat(installer): wire OpenCode into the GUI, CLI and sys ask
Select the OpenCode adapter from canonical config in ai_check/ai_test; add --ai-backend/--opencode-* flags to the installer and sys. Require a validated interaction (not a provider name) for the mandatory-AI gate in both the bridge and the CLI, invalidated by config, model or credential changes. Tests cover the gate, invalidation and the OpenCode backend.
This commit is contained in:
parent
5c3674e3c2
commit
0d65d56eda
4 changed files with 784 additions and 143 deletions
|
|
@ -11,10 +11,11 @@ use std::process::ExitCode;
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
|
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
|
||||||
use phoebus_ai::provider::{ProviderKind, SystemFacts};
|
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
||||||
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
|
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
|
||||||
use phoebus_core::transaction::TransactionRecord;
|
use phoebus_core::transaction::TransactionRecord;
|
||||||
use phoebus_core::{InstallConfig, Redactor};
|
use phoebus_core::{AiBackend, InstallConfig, Redactor};
|
||||||
|
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
||||||
use phoebus_executor::{
|
use phoebus_executor::{
|
||||||
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization,
|
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization,
|
||||||
Exec, Logger, RealRunner, Result,
|
Exec, Logger, RealRunner, Result,
|
||||||
|
|
@ -61,6 +62,26 @@ struct Cli {
|
||||||
/// Run the assistant without the OS-level sandbox (development only).
|
/// Run the assistant without the OS-level sandbox (development only).
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
no_sandbox: bool,
|
no_sandbox: bool,
|
||||||
|
|
||||||
|
/// AI backend for `sys ask`: `direct` (default) or `opencode`.
|
||||||
|
#[arg(long, value_name = "BACKEND")]
|
||||||
|
ai_backend: Option<String>,
|
||||||
|
|
||||||
|
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
|
||||||
|
#[arg(long, value_name = "URL")]
|
||||||
|
opencode_server: Option<String>,
|
||||||
|
|
||||||
|
/// OpenCode provider id (e.g. `deepseek`).
|
||||||
|
#[arg(long, value_name = "PROVIDER")]
|
||||||
|
opencode_provider: Option<String>,
|
||||||
|
|
||||||
|
/// OpenCode model id (e.g. `deepseek-chat`).
|
||||||
|
#[arg(long, value_name = "MODEL")]
|
||||||
|
opencode_model: Option<String>,
|
||||||
|
|
||||||
|
/// Read the OpenCode server password from a mode-0600 file.
|
||||||
|
#[arg(long, value_name = "FILE")]
|
||||||
|
opencode_password_file: Option<PathBuf>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct SysConfirm {
|
struct SysConfirm {
|
||||||
|
|
@ -214,6 +235,16 @@ fn gather_facts(exec: &Exec) -> SystemFacts {
|
||||||
SystemFacts::from_system(&config, &hardware, &history, binhost, None)
|
SystemFacts::from_system(&config, &hardware, &history, binhost, None)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The AI backend selected on the command line or the environment.
|
||||||
|
fn resolve_backend(cli: &Cli) -> AiBackend {
|
||||||
|
let raw = cli
|
||||||
|
.ai_backend
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var("PHOEBUS_AI_BACKEND").ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
AiBackend::parse(&raw).unwrap_or(AiBackend::Direct)
|
||||||
|
}
|
||||||
|
|
||||||
/// The provider selected on the command line or the environment.
|
/// The provider selected on the command line or the environment.
|
||||||
fn resolve_provider(cli: &Cli) -> ProviderKind {
|
fn resolve_provider(cli: &Cli) -> ProviderKind {
|
||||||
let raw = cli
|
let raw = cli
|
||||||
|
|
@ -270,48 +301,112 @@ fn run_ask(
|
||||||
exec: &Exec,
|
exec: &Exec,
|
||||||
instruction: &str,
|
instruction: &str,
|
||||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
let provider = resolve_provider(cli);
|
|
||||||
if provider == ProviderKind::None {
|
|
||||||
deterministic_fallback(instruction);
|
|
||||||
return Err("no AI provider configured".into());
|
|
||||||
}
|
|
||||||
let endpoint = resolve_endpoint(cli, provider);
|
|
||||||
let model = resolve_model(cli);
|
|
||||||
let key = match api_key_file(cli) {
|
|
||||||
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
if provider.requires_key() && key.is_none() {
|
|
||||||
deterministic_fallback(instruction);
|
|
||||||
return Err(format!(
|
|
||||||
"provider `{}` requires --ai-api-key-file (mode 0600)",
|
|
||||||
provider.as_str()
|
|
||||||
)
|
|
||||||
.into());
|
|
||||||
}
|
|
||||||
|
|
||||||
let facts = gather_facts(exec);
|
let facts = gather_facts(exec);
|
||||||
eprintln!(
|
let backend = resolve_backend(cli);
|
||||||
"Sending these bounded system facts to {} (no passwords, files or home directories):",
|
let (provider, endpoint, model);
|
||||||
provider.as_str()
|
let transport: Box<dyn ModelTransport + '_>;
|
||||||
);
|
|
||||||
eprintln!("{}", facts.render());
|
|
||||||
|
|
||||||
let transport = phoebus_executor::ai::CurlTransport::new(exec, key);
|
match backend {
|
||||||
let transport = if cli.no_sandbox {
|
AiBackend::OpenCode => {
|
||||||
transport
|
let server = cli
|
||||||
} else {
|
.opencode_server
|
||||||
transport.sandboxed()
|
.clone()
|
||||||
};
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
|
||||||
let plan: AssistantPlan =
|
.unwrap_or_default();
|
||||||
match complete_plan(provider, &endpoint, &model, &facts, instruction, &transport) {
|
let opencode_provider = cli
|
||||||
Ok(plan) => plan,
|
.opencode_provider
|
||||||
Err(e) => {
|
.clone()
|
||||||
eprintln!("The model is unavailable or returned an unusable plan: {e}");
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
let opencode_model = cli
|
||||||
|
.opencode_model
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
|
||||||
|
.unwrap_or_default();
|
||||||
|
if server.trim().is_empty()
|
||||||
|
|| opencode_provider.trim().is_empty()
|
||||||
|
|| opencode_model.trim().is_empty()
|
||||||
|
{
|
||||||
deterministic_fallback(instruction);
|
deterministic_fallback(instruction);
|
||||||
return Err("model unavailable".into());
|
return Err(
|
||||||
|
"OpenCode requires --opencode-server, --opencode-provider and --opencode-model"
|
||||||
|
.into(),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
};
|
let password = match &cli.opencode_password_file {
|
||||||
|
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
eprintln!(
|
||||||
|
"Sending these bounded system facts through the OpenCode server at {} \
|
||||||
|
(provider {}, model {}); no passwords, files or home directories:",
|
||||||
|
server, opencode_provider, opencode_model
|
||||||
|
);
|
||||||
|
eprintln!("{}", facts.render());
|
||||||
|
provider = ProviderKind::Local;
|
||||||
|
endpoint = server;
|
||||||
|
model = opencode_model;
|
||||||
|
transport = Box::new(
|
||||||
|
ExecOpenCodeTransport::new(
|
||||||
|
exec,
|
||||||
|
endpoint.clone(),
|
||||||
|
opencode_provider,
|
||||||
|
model.clone(),
|
||||||
|
)
|
||||||
|
.with_auth(password),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
AiBackend::Direct => {
|
||||||
|
let resolved = resolve_provider(cli);
|
||||||
|
if resolved == ProviderKind::None {
|
||||||
|
deterministic_fallback(instruction);
|
||||||
|
return Err("no AI provider configured".into());
|
||||||
|
}
|
||||||
|
let key = match api_key_file(cli) {
|
||||||
|
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
if resolved.requires_key() && key.is_none() {
|
||||||
|
deterministic_fallback(instruction);
|
||||||
|
return Err(format!(
|
||||||
|
"provider `{}` requires --ai-api-key-file (mode 0600)",
|
||||||
|
resolved.as_str()
|
||||||
|
)
|
||||||
|
.into());
|
||||||
|
}
|
||||||
|
eprintln!(
|
||||||
|
"Sending these bounded system facts to {} \
|
||||||
|
(no passwords, files or home directories):",
|
||||||
|
resolved.as_str()
|
||||||
|
);
|
||||||
|
eprintln!("{}", facts.render());
|
||||||
|
provider = resolved;
|
||||||
|
endpoint = resolve_endpoint(cli, resolved);
|
||||||
|
model = resolve_model(cli);
|
||||||
|
let direct = phoebus_executor::ai::CurlTransport::new(exec, key);
|
||||||
|
transport = if cli.no_sandbox {
|
||||||
|
Box::new(direct)
|
||||||
|
} else {
|
||||||
|
Box::new(direct.sandboxed())
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let plan: AssistantPlan = match complete_plan(
|
||||||
|
provider,
|
||||||
|
&endpoint,
|
||||||
|
&model,
|
||||||
|
&facts,
|
||||||
|
instruction,
|
||||||
|
transport.as_ref(),
|
||||||
|
) {
|
||||||
|
Ok(plan) => plan,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("The model is unavailable or returned an unusable plan: {e}");
|
||||||
|
deterministic_fallback(instruction);
|
||||||
|
return Err("model unavailable".into());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
println!("{}", plan.render());
|
println!("{}", plan.render());
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -18,9 +18,10 @@ use std::io::{self, BufRead, Write};
|
||||||
|
|
||||||
use crate::{ai_guide, InstallObserver, Installer};
|
use crate::{ai_guide, InstallObserver, Installer};
|
||||||
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
||||||
use phoebus_core::{InstallConfig, InstallStep, SecretString};
|
use phoebus_core::{AiBackend, InstallConfig, InstallStep, SecretString};
|
||||||
use phoebus_executor::ai::CurlTransport;
|
use phoebus_executor::ai::CurlTransport;
|
||||||
use phoebus_executor::auth::{authorize, Confirmation};
|
use phoebus_executor::auth::{authorize, Confirmation};
|
||||||
|
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
||||||
use phoebus_executor::{Exec, Result as ExecResult};
|
use phoebus_executor::{Exec, Result as ExecResult};
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
@ -70,6 +71,10 @@ struct SecretsPatch {
|
||||||
root_password: Option<String>,
|
root_password: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
ai_api_key: Option<String>,
|
ai_api_key: Option<String>,
|
||||||
|
/// The OpenCode server password (basic auth). Distinct from a model
|
||||||
|
/// provider API key and never stored in the configuration.
|
||||||
|
#[serde(default)]
|
||||||
|
opencode_password: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE
|
/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE
|
||||||
|
|
@ -164,7 +169,12 @@ pub struct Bridge {
|
||||||
user_password: Option<SecretString>,
|
user_password: Option<SecretString>,
|
||||||
root_password: Option<SecretString>,
|
root_password: Option<SecretString>,
|
||||||
api_key: Option<SecretString>,
|
api_key: Option<SecretString>,
|
||||||
|
opencode_password: Option<SecretString>,
|
||||||
approved_digest: Option<String>,
|
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>>,
|
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
||||||
/// One destructive transaction at a time. An approval is single-use: it is
|
/// 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
|
/// consumed when the install starts so a replay, a second frontend or a
|
||||||
|
|
@ -183,7 +193,9 @@ impl Bridge {
|
||||||
user_password: None,
|
user_password: None,
|
||||||
root_password: None,
|
root_password: None,
|
||||||
api_key: None,
|
api_key: None,
|
||||||
|
opencode_password: None,
|
||||||
approved_digest: None,
|
approved_digest: None,
|
||||||
|
validated_ai: None,
|
||||||
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
||||||
installing: false,
|
installing: false,
|
||||||
installed: false,
|
installed: false,
|
||||||
|
|
@ -199,7 +211,9 @@ impl Bridge {
|
||||||
user_password: None,
|
user_password: None,
|
||||||
root_password: None,
|
root_password: None,
|
||||||
api_key: None,
|
api_key: None,
|
||||||
|
opencode_password: None,
|
||||||
approved_digest: None,
|
approved_digest: None,
|
||||||
|
validated_ai: None,
|
||||||
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
||||||
installing: false,
|
installing: false,
|
||||||
installed: false,
|
installed: false,
|
||||||
|
|
@ -251,6 +265,7 @@ impl Bridge {
|
||||||
"plan" => self.plan(),
|
"plan" => self.plan(),
|
||||||
"destructive_preview" => self.destructive_preview(),
|
"destructive_preview" => self.destructive_preview(),
|
||||||
"ai_check" => self.ai_check(),
|
"ai_check" => self.ai_check(),
|
||||||
|
"ai_test" => self.ai_test(),
|
||||||
"approve" => self.approve(&request),
|
"approve" => self.approve(&request),
|
||||||
"start_install" => return self.start_install(id, &request, out),
|
"start_install" => return self.start_install(id, &request, out),
|
||||||
"log_tail" => self.log_tail(&request),
|
"log_tail" => self.log_tail(&request),
|
||||||
|
|
@ -405,6 +420,9 @@ impl Bridge {
|
||||||
|
|
||||||
self.installer.reconfigure(config);
|
self.installer.reconfigure(config);
|
||||||
self.approved_digest = None;
|
self.approved_digest = None;
|
||||||
|
// A configuration change (provider, model, endpoint, server) invalidates
|
||||||
|
// any previous AI validation.
|
||||||
|
self.validated_ai = None;
|
||||||
let issues = self.installer.validate();
|
let issues = self.installer.validate();
|
||||||
Ok(json!({
|
Ok(json!({
|
||||||
"accepted": true,
|
"accepted": true,
|
||||||
|
|
@ -427,6 +445,7 @@ impl Bridge {
|
||||||
&patch.user_password,
|
&patch.user_password,
|
||||||
&patch.root_password,
|
&patch.root_password,
|
||||||
&patch.ai_api_key,
|
&patch.ai_api_key,
|
||||||
|
&patch.opencode_password,
|
||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
|
|
@ -455,12 +474,20 @@ impl Bridge {
|
||||||
self.installer.exec.register_secret(&s);
|
self.installer.exec.register_secret(&s);
|
||||||
self.api_key = Some(s);
|
self.api_key = Some(s);
|
||||||
}
|
}
|
||||||
|
if let Some(v) = &patch.opencode_password {
|
||||||
|
let s = SecretString::new(v.clone());
|
||||||
|
self.installer.exec.register_secret(&s);
|
||||||
|
self.opencode_password = Some(s);
|
||||||
|
}
|
||||||
|
// A credential change invalidates any previous AI validation.
|
||||||
|
self.validated_ai = None;
|
||||||
// Report only presence, never values.
|
// Report only presence, never values.
|
||||||
Ok(json!({
|
Ok(json!({
|
||||||
"luks_set": self.luks.is_some(),
|
"luks_set": self.luks.is_some(),
|
||||||
"user_password_set": self.user_password.is_some(),
|
"user_password_set": self.user_password.is_some(),
|
||||||
"root_password_set": self.root_password.is_some(),
|
"root_password_set": self.root_password.is_some(),
|
||||||
"ai_api_key_set": self.api_key.is_some(),
|
"ai_api_key_set": self.api_key.is_some(),
|
||||||
|
"opencode_password_set": self.opencode_password.is_some(),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -468,33 +495,107 @@ impl Bridge {
|
||||||
|
|
||||||
fn ai_check(&mut self) -> Result<Value, String> {
|
fn ai_check(&mut self) -> Result<Value, String> {
|
||||||
let facts = self.installer.system_facts();
|
let facts = self.installer.system_facts();
|
||||||
let api_key_present = self.api_key.is_some();
|
let backend = self.installer.config.ai.backend;
|
||||||
let Bridge {
|
let api_key = self.api_key.clone();
|
||||||
installer,
|
let opencode_password = self.opencode_password.clone();
|
||||||
api_key,
|
let value = {
|
||||||
approved_digest,
|
let Installer { exec, config, .. } = &mut self.installer;
|
||||||
..
|
let redactor = exec.redactor();
|
||||||
} = self;
|
match backend {
|
||||||
let Installer { exec, config, .. } = installer;
|
AiBackend::OpenCode => {
|
||||||
let transport = CurlTransport::new(exec, api_key.clone());
|
let transport = opencode_transport(exec, config, opencode_password)?;
|
||||||
let value = review_proposal(config, exec.redactor(), facts, api_key_present, &transport)?;
|
review_opencode(config, redactor, facts, &transport)?
|
||||||
*approved_digest = None;
|
}
|
||||||
|
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(self.plan_digest());
|
||||||
Ok(value)
|
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 (server, provider, model) = opencode_parts(&self.installer.config)?;
|
||||||
|
let transport =
|
||||||
|
ExecOpenCodeTransport::new(&self.installer.exec, server, provider, model)
|
||||||
|
.with_auth(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).
|
/// Validate the provider connection and review the proposal (fail-closed).
|
||||||
/// Exposed so tests can drive it with a canned transport.
|
/// Exposed so tests can drive it with a canned transport.
|
||||||
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
||||||
let facts = self.installer.system_facts();
|
let facts = self.installer.system_facts();
|
||||||
let api_key_present = self.api_key.is_some();
|
let api_key_present = self.api_key.is_some();
|
||||||
let Bridge {
|
let value = {
|
||||||
installer,
|
let Installer { exec, config, .. } = &mut self.installer;
|
||||||
approved_digest,
|
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
|
||||||
..
|
};
|
||||||
} = self;
|
self.approved_digest = None;
|
||||||
let Installer { exec, config, .. } = installer;
|
self.validated_ai = Some(self.plan_digest());
|
||||||
let value = review_proposal(config, exec.redactor(), facts, api_key_present, transport)?;
|
|
||||||
*approved_digest = None;
|
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -558,18 +659,20 @@ impl Bridge {
|
||||||
}
|
}
|
||||||
|
|
||||||
// AI is mandatory to install unless this is a dry run or an explicit
|
// AI is mandatory to install unless this is a dry run or an explicit
|
||||||
// break-glass (mirrors the CLI rule).
|
// 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;
|
let dry_run = self.installer.config.runtime.dry_run;
|
||||||
if !dry_run {
|
if !dry_run {
|
||||||
let provider = ProviderKind::parse(&self.installer.config.ai.provider)
|
|
||||||
.unwrap_or(ProviderKind::None);
|
|
||||||
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
||||||
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
if provider == ProviderKind::None && !break_glass {
|
let validated = self.validated_ai.as_deref() == Some(current.as_str());
|
||||||
|
if !validated && !break_glass {
|
||||||
return Err(
|
return Err(
|
||||||
"installing Phoebus requires a connected AI model; connect a provider \
|
"installing Phoebus requires a successful, validated AI interaction for \
|
||||||
or set PHOEBUS_NO_AI=1 for a deterministic install"
|
the current configuration; connect and validate a model, or set \
|
||||||
|
PHOEBUS_NO_AI=1 for a deterministic install"
|
||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -602,6 +705,7 @@ impl Bridge {
|
||||||
// Consume the approval and mark the session busy before any destructive
|
// Consume the approval and mark the session busy before any destructive
|
||||||
// work: a replay or a second frontend can never reach storage_prepare.
|
// work: a replay or a second frontend can never reach storage_prepare.
|
||||||
self.approved_digest = None;
|
self.approved_digest = None;
|
||||||
|
self.validated_ai = None;
|
||||||
self.installing = true;
|
self.installing = true;
|
||||||
let outcome = self.installer.install_observed(
|
let outcome = self.installer.install_observed(
|
||||||
&auth,
|
&auth,
|
||||||
|
|
@ -757,8 +861,109 @@ fn config_digest(config: &InstallConfig) -> String {
|
||||||
format!("{:x}", hasher.finalize())
|
format!("{:x}", hasher.finalize())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parse the provider from the configuration, validate the connection and apply
|
/// The OpenCode server URL, provider id and model id, validated for presence.
|
||||||
/// the reviewed proposal. This is the same `ai_guide` path the TUI uses.
|
fn opencode_parts(config: &InstallConfig) -> Result<(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();
|
||||||
|
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))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn opencode_transport<'a>(
|
||||||
|
exec: &'a Exec,
|
||||||
|
config: &InstallConfig,
|
||||||
|
password: Option<SecretString>,
|
||||||
|
) -> Result<phoebus_executor::opencode_client::ExecOpenCodeTransport<'a>, String> {
|
||||||
|
let (server, provider, model) = opencode_parts(config)?;
|
||||||
|
Ok(
|
||||||
|
phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
||||||
|
exec, server, provider, model,
|
||||||
|
)
|
||||||
|
.with_auth(password),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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()
|
||||||
|
.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) = opencode_parts(config)?;
|
||||||
|
finish_review(
|
||||||
|
config,
|
||||||
|
redactor,
|
||||||
|
facts,
|
||||||
|
ProviderKind::Local,
|
||||||
|
&server,
|
||||||
|
&provider_id,
|
||||||
|
&model,
|
||||||
|
transport,
|
||||||
|
"opencode",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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(
|
fn review_proposal(
|
||||||
config: &mut InstallConfig,
|
config: &mut InstallConfig,
|
||||||
redactor: &phoebus_core::Redactor,
|
redactor: &phoebus_core::Redactor,
|
||||||
|
|
@ -788,36 +993,17 @@ fn review_proposal(
|
||||||
provider.as_str()
|
provider.as_str()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
finish_review(
|
||||||
let outcome =
|
config,
|
||||||
ai_guide::generate_and_review_at(config, &facts, provider, &endpoint, &model, transport)
|
redactor,
|
||||||
.map_err(|e| {
|
facts,
|
||||||
// Error messages are redacted before they reach the GUI.
|
provider,
|
||||||
format!(
|
&endpoint,
|
||||||
"connection or proposal failed: {}",
|
provider.as_str(),
|
||||||
redactor.redact(&e.to_string())
|
&model,
|
||||||
)
|
transport,
|
||||||
})?;
|
"direct",
|
||||||
let applied: Vec<Value> = outcome
|
)
|
||||||
.applied
|
|
||||||
.iter()
|
|
||||||
.map(|c| {
|
|
||||||
json!({
|
|
||||||
"description": c.description,
|
|
||||||
"reason": c.reason,
|
|
||||||
"evidence": c.evidence,
|
|
||||||
})
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
Ok(json!({
|
|
||||||
"connected": true,
|
|
||||||
"provider": provider.as_str(),
|
|
||||||
"model": model,
|
|
||||||
"endpoint": endpoint,
|
|
||||||
"applied": applied,
|
|
||||||
"config": config,
|
|
||||||
"plan_digest": config_digest(config),
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The stdio entry point used by `--gui-bridge`.
|
/// The stdio entry point used by `--gui-bridge`.
|
||||||
|
|
@ -1275,4 +1461,173 @@ mod tests {
|
||||||
let lines = call(&mut bridge, &line);
|
let lines = call(&mut bridge, &line);
|
||||||
assert_eq!(response(&lines)["ok"], json!(false));
|
assert_eq!(response(&lines)["ok"], json!(false));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A non-dry bridge whose runner reports `/dev/vda`, so revalidation and
|
||||||
|
/// the install stages run against the fake runner (never a real disk).
|
||||||
|
fn test_bridge_non_dry() -> Bridge {
|
||||||
|
let runner = RecordingRunner::new();
|
||||||
|
runner.set_response(
|
||||||
|
"lsblk",
|
||||||
|
phoebus_executor::CommandOutput {
|
||||||
|
status: 0,
|
||||||
|
success: true,
|
||||||
|
stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(),
|
||||||
|
stderr: Vec::new(),
|
||||||
|
duration: std::time::Duration::from_millis(1),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
let dir = tempfile::tempdir().unwrap().keep();
|
||||||
|
let logger = Logger::open(dir.join("install.log"), Redactor::new(), false);
|
||||||
|
let mut config = InstallConfig::default();
|
||||||
|
config.runtime.dry_run = false;
|
||||||
|
config.system.hostname = "phoebus".into();
|
||||||
|
config.system.timezone = "UTC".into();
|
||||||
|
config.user.username = "tester".into();
|
||||||
|
config.storage.disk = "/dev/vda".into();
|
||||||
|
let exec = Exec::new(
|
||||||
|
Box::new(runner),
|
||||||
|
logger,
|
||||||
|
false,
|
||||||
|
dir.join("root"),
|
||||||
|
dir.clone(),
|
||||||
|
);
|
||||||
|
let mut installer = Installer::new(config, exec);
|
||||||
|
installer.disks.push(Disk {
|
||||||
|
path: "/dev/vda".into(),
|
||||||
|
model: Some("QEMU HARDDISK".into()),
|
||||||
|
size_bytes: 30 * 1024 * 1024 * 1024,
|
||||||
|
transport: Some("virtio".into()),
|
||||||
|
removable: false,
|
||||||
|
read_only: false,
|
||||||
|
mounted: false,
|
||||||
|
is_block_device: true,
|
||||||
|
kind: DiskKind::Physical,
|
||||||
|
live_media: false,
|
||||||
|
});
|
||||||
|
Bridge::with_installer(installer)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arm_ai(bridge: &mut Bridge) -> Value {
|
||||||
|
let mut c = config_json(bridge);
|
||||||
|
c["ai"]["provider"] = json!("deepseek");
|
||||||
|
c["ai"]["model"] = json!("deepseek-chat");
|
||||||
|
let _ = call(
|
||||||
|
bridge,
|
||||||
|
&json!({ "id": 30, "op": "set_config", "config": c }).to_string(),
|
||||||
|
);
|
||||||
|
bridge.api_key = Some(SecretString::new("test-key"));
|
||||||
|
let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["x"]}]}"#;
|
||||||
|
bridge
|
||||||
|
.ai_check_with(&TestTransport::proposal(proposal))
|
||||||
|
.expect("ai_check")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start(bridge: &mut Bridge, digest: &str) -> Value {
|
||||||
|
let lines = call(
|
||||||
|
bridge,
|
||||||
|
&json!({
|
||||||
|
"id": 31, "op": "start_install", "erase": "ERASE",
|
||||||
|
"final_confirm": true, "plan_digest": digest
|
||||||
|
})
|
||||||
|
.to_string(),
|
||||||
|
);
|
||||||
|
response(&lines)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_provider_name_alone_does_not_satisfy_the_ai_requirement() {
|
||||||
|
let mut bridge = test_bridge_non_dry();
|
||||||
|
set_valid_config(&mut bridge);
|
||||||
|
// Provider configured and key present, but no validated interaction.
|
||||||
|
let mut c = config_json(&bridge);
|
||||||
|
c["ai"]["provider"] = json!("deepseek");
|
||||||
|
let _ = call(
|
||||||
|
&mut bridge,
|
||||||
|
&json!({ "id": 40, "op": "set_config", "config": c }).to_string(),
|
||||||
|
);
|
||||||
|
bridge.api_key = Some(SecretString::new("test-key"));
|
||||||
|
let (digest, _) = approve(&mut bridge);
|
||||||
|
let resp = start(&mut bridge, &digest);
|
||||||
|
assert_eq!(resp["ok"], json!(false));
|
||||||
|
assert!(
|
||||||
|
resp["error"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.contains("validated AI interaction"),
|
||||||
|
"unexpected error: {}",
|
||||||
|
resp["error"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_validated_interaction_satisfies_the_ai_requirement() {
|
||||||
|
let mut bridge = test_bridge_non_dry();
|
||||||
|
set_valid_config(&mut bridge);
|
||||||
|
arm_ai(&mut bridge);
|
||||||
|
let (digest, _) = approve(&mut bridge);
|
||||||
|
let resp = start(&mut bridge, &digest);
|
||||||
|
// It may fail later in the fake storage stage, but never on the AI gate.
|
||||||
|
assert!(
|
||||||
|
!resp["error"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap_or("")
|
||||||
|
.contains("validated AI interaction"),
|
||||||
|
"the AI gate wrongly rejected a validated interaction: {}",
|
||||||
|
resp["error"]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_config_change_invalidates_the_validated_interaction() {
|
||||||
|
let mut bridge = test_bridge_non_dry();
|
||||||
|
set_valid_config(&mut bridge);
|
||||||
|
arm_ai(&mut bridge);
|
||||||
|
// Change the model after validation.
|
||||||
|
let mut c = config_json(&bridge);
|
||||||
|
c["ai"]["model"] = json!("deepseek-reasoner");
|
||||||
|
let _ = call(
|
||||||
|
&mut bridge,
|
||||||
|
&json!({ "id": 41, "op": "set_config", "config": c }).to_string(),
|
||||||
|
);
|
||||||
|
let (digest, _) = approve(&mut bridge);
|
||||||
|
let resp = start(&mut bridge, &digest);
|
||||||
|
assert_eq!(resp["ok"], json!(false));
|
||||||
|
assert!(resp["error"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.contains("validated AI interaction"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_secret_change_invalidates_the_validated_interaction() {
|
||||||
|
let mut bridge = test_bridge_non_dry();
|
||||||
|
set_valid_config(&mut bridge);
|
||||||
|
arm_ai(&mut bridge);
|
||||||
|
let _ = call(
|
||||||
|
&mut bridge,
|
||||||
|
r#"{"id":42,"op":"set_secrets","secrets":{"ai_api_key":"new-key"}}"#,
|
||||||
|
);
|
||||||
|
let (digest, _) = approve(&mut bridge);
|
||||||
|
let resp = start(&mut bridge, &digest);
|
||||||
|
assert_eq!(resp["ok"], json!(false));
|
||||||
|
assert!(resp["error"]
|
||||||
|
.as_str()
|
||||||
|
.unwrap()
|
||||||
|
.contains("validated AI interaction"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ai_test_is_a_known_operation_and_fails_without_a_provider() {
|
||||||
|
let mut bridge = test_bridge();
|
||||||
|
let lines = call(&mut bridge, r#"{"id":43,"op":"ai_test"}"#);
|
||||||
|
let resp = response(&lines);
|
||||||
|
// Not "unknown op": the operation exists and reports the configuration
|
||||||
|
// problem instead.
|
||||||
|
assert_eq!(resp["ok"], json!(false));
|
||||||
|
assert!(
|
||||||
|
!resp["error"].as_str().unwrap().contains("unknown op"),
|
||||||
|
"{}",
|
||||||
|
resp["error"]
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -122,10 +122,36 @@ struct Cli {
|
||||||
gui_bridge: bool,
|
gui_bridge: bool,
|
||||||
|
|
||||||
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
|
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
|
||||||
/// its capability as JSON. Read-only; exits nonzero unless a model is
|
/// its capability as JSON. Read-only; exits nonzero unless a model catalog
|
||||||
/// available. Never prints provider credentials.
|
/// is available. Never prints provider credentials.
|
||||||
#[arg(long, value_name = "URL")]
|
#[arg(long, value_name = "URL")]
|
||||||
opencode_probe: Option<String>,
|
opencode_probe: Option<String>,
|
||||||
|
|
||||||
|
/// Obtain a real model response through an OpenCode server and validate it,
|
||||||
|
/// then exit. This is the acceptance test for inference, not reachability.
|
||||||
|
#[arg(long, value_name = "URL")]
|
||||||
|
opencode_test: Option<String>,
|
||||||
|
|
||||||
|
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
|
||||||
|
#[arg(long, value_name = "URL")]
|
||||||
|
opencode_server: Option<String>,
|
||||||
|
|
||||||
|
/// OpenCode provider id (e.g. `deepseek`).
|
||||||
|
#[arg(long, value_name = "PROVIDER")]
|
||||||
|
opencode_provider: Option<String>,
|
||||||
|
|
||||||
|
/// OpenCode model id (e.g. `deepseek-chat`).
|
||||||
|
#[arg(long, value_name = "MODEL")]
|
||||||
|
opencode_model: Option<String>,
|
||||||
|
|
||||||
|
/// Read the OpenCode server password from a mode-0600 file (distinct from a
|
||||||
|
/// model provider API key).
|
||||||
|
#[arg(long, value_name = "FILE")]
|
||||||
|
opencode_password_file: Option<PathBuf>,
|
||||||
|
|
||||||
|
/// AI backend for install guidance: `direct` (default) or `opencode`.
|
||||||
|
#[arg(long, value_name = "BACKEND")]
|
||||||
|
ai_backend: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct TerminalConfirm;
|
struct TerminalConfirm;
|
||||||
|
|
@ -161,6 +187,94 @@ fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
|
||||||
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
|
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A lightweight `Exec` for the OpenCode probe/test commands, which do not
|
||||||
|
/// touch the target.
|
||||||
|
fn opencode_exec() -> Exec {
|
||||||
|
let dir = std::env::temp_dir().join("phoebus-opencode-cli");
|
||||||
|
let _ = std::fs::create_dir_all(&dir);
|
||||||
|
let logger = Logger::open(dir.join("opencode.log"), Redactor::new(), false);
|
||||||
|
Exec::new(Box::new(RealRunner), logger, false, dir.clone(), dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probe an OpenCode server (`validate_inference = false`) or obtain and
|
||||||
|
/// validate a real model response (`true`). Exits nonzero unless the requested
|
||||||
|
/// condition is met, so it can be used as an acceptance command.
|
||||||
|
fn run_opencode_probe(cli: &Cli, url: &str, validate_inference: bool) -> ExitCode {
|
||||||
|
use phoebus_executor::opencode_client::{CurlHttpClient, OpenCodeClient};
|
||||||
|
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint, ProbeRequest};
|
||||||
|
|
||||||
|
let endpoint = match Endpoint::parse(url) {
|
||||||
|
Ok(endpoint) => endpoint,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("invalid OpenCode endpoint `{url}`: {e}");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let auth = match &cli.opencode_password_file {
|
||||||
|
Some(path) => match read_secret(path) {
|
||||||
|
Ok(secret) => Some(secret),
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("cannot read OpenCode password file: {e}");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let provider = cli.opencode_provider.clone().unwrap_or_default();
|
||||||
|
let model = cli.opencode_model.clone().unwrap_or_default();
|
||||||
|
let exec = opencode_exec();
|
||||||
|
let http = CurlHttpClient::new(&exec);
|
||||||
|
|
||||||
|
if !validate_inference {
|
||||||
|
let mut request = ProbeRequest::new();
|
||||||
|
request.auth = auth.clone();
|
||||||
|
request.provider = (!provider.is_empty()).then(|| provider.clone());
|
||||||
|
request.model = (!model.is_empty()).then(|| model.clone());
|
||||||
|
let capability = probe(&http, &endpoint, &request);
|
||||||
|
match serde_json::to_string_pretty(&capability) {
|
||||||
|
Ok(json) => println!("{json}"),
|
||||||
|
Err(e) => eprintln!("could not render capability: {e}"),
|
||||||
|
}
|
||||||
|
return if matches!(
|
||||||
|
capability.state,
|
||||||
|
ConnectionState::ModelCatalog | ConnectionState::Ready
|
||||||
|
) {
|
||||||
|
ExitCode::SUCCESS
|
||||||
|
} else {
|
||||||
|
ExitCode::FAILURE
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if provider.is_empty() || model.is_empty() {
|
||||||
|
eprintln!("--opencode-test requires --opencode-provider and --opencode-model");
|
||||||
|
return ExitCode::FAILURE;
|
||||||
|
}
|
||||||
|
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model).with_auth(auth);
|
||||||
|
match client.one_shot(
|
||||||
|
"You are a connectivity test. Reply with JSON only.",
|
||||||
|
"Reply with exactly {\"phoebus\":\"ok\"} and nothing else.",
|
||||||
|
) {
|
||||||
|
Ok(reply) => match serde_json::from_str::<serde_json::Value>(&reply.content) {
|
||||||
|
Ok(value) if value.get("phoebus").and_then(|v| v.as_str()) == Some("ok") => {
|
||||||
|
println!("validated model response: {}", reply.content);
|
||||||
|
ExitCode::SUCCESS
|
||||||
|
}
|
||||||
|
Ok(value) => {
|
||||||
|
println!("model responded, but not as requested: {value}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
println!("model response was not JSON: {}", reply.content);
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("model validation failed: {e}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The provider selected on the command line, or the one the TUI/config chose.
|
/// The provider selected on the command line, or the one the TUI/config chose.
|
||||||
fn resolve_provider(
|
fn resolve_provider(
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
|
|
@ -183,48 +297,116 @@ fn no_ai_requested(cli: &Cli) -> bool {
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Installing Phoebus requires a connected model. `--no-ai`/`--legacy` is the
|
/// Installing Phoebus requires a **validated** AI interaction, not just a
|
||||||
/// explicit, documented break-glass for recovery or automation.
|
/// non-empty provider name. `--no-ai`/`--legacy` is the explicit, documented
|
||||||
|
/// break-glass for recovery or automation.
|
||||||
fn require_ai_for_install(
|
fn require_ai_for_install(
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
provider: ProviderKind,
|
validated: bool,
|
||||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
if no_ai_requested(cli) || provider != ProviderKind::None {
|
if no_ai_requested(cli) || validated {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
Err("installing Phoebus requires a connected AI model.\n\
|
Err(
|
||||||
Connect a provider (--ai-provider deepseek|openai|local, with \
|
"installing Phoebus requires a successful, validated AI interaction.\n\
|
||||||
--ai-api-key-file and/or --ai-endpoint), or pass --no-ai (alias \
|
Connect a provider (--ai-backend direct with --ai-provider \
|
||||||
--legacy) for a deterministic install."
|
deepseek|openai|local and --ai-api-key-file/--ai-endpoint, or \
|
||||||
.into())
|
--ai-backend opencode with --opencode-server/--opencode-provider/\
|
||||||
|
--opencode-model) and let it return a valid proposal, or pass --no-ai \
|
||||||
|
(alias --legacy) for a deterministic install."
|
||||||
|
.into(),
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply AI guidance to the configuration before the plan is shown or install
|
/// 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
|
/// runs. Returns `true` only when a model interaction produced a valid,
|
||||||
/// is reviewed with mandatory evidence and applied atomically.
|
/// reviewed proposal. The model never sees secrets and never executes anything.
|
||||||
fn run_ai_guidance(
|
fn run_ai_guidance(
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
installer: &mut Installer,
|
installer: &mut Installer,
|
||||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
) -> std::result::Result<bool, 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;
|
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
|
||||||
if !wants_ai {
|
if !wants_ai {
|
||||||
return Ok(());
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(path) = &cli.ai_proposal_file {
|
if let Some(path) = &cli.ai_proposal_file {
|
||||||
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
|
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
|
||||||
println!("{}", outcome.render());
|
println!("{}", outcome.render());
|
||||||
return Ok(());
|
return Ok(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let backend = cli
|
||||||
|
.ai_backend
|
||||||
|
.as_deref()
|
||||||
|
.and_then(phoebus_core::AiBackend::parse)
|
||||||
|
.unwrap_or(installer.config.ai.backend);
|
||||||
|
let facts = installer.system_facts();
|
||||||
|
|
||||||
|
if backend == phoebus_core::AiBackend::OpenCode {
|
||||||
|
let server = cli
|
||||||
|
.opencode_server
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
|
||||||
|
.unwrap_or_else(|| installer.config.ai.opencode_server.clone());
|
||||||
|
let provider_id = cli
|
||||||
|
.opencode_provider
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
|
||||||
|
.unwrap_or_else(|| installer.config.ai.opencode_provider.clone());
|
||||||
|
let model = cli
|
||||||
|
.opencode_model
|
||||||
|
.clone()
|
||||||
|
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
|
||||||
|
.unwrap_or_else(|| installer.config.ai.opencode_model.clone());
|
||||||
|
if server.trim().is_empty() || provider_id.trim().is_empty() || model.trim().is_empty() {
|
||||||
|
eprintln!(
|
||||||
|
"AI assistance is enabled but OpenCode is not fully configured \
|
||||||
|
(need server, provider and model); continuing without AI."
|
||||||
|
);
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
let password = match &cli.opencode_password_file {
|
||||||
|
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
eprintln!(
|
||||||
|
"Sending these system facts through the OpenCode server at {} \
|
||||||
|
(provider {}, no passwords, passphrases or files):",
|
||||||
|
server, provider_id
|
||||||
|
);
|
||||||
|
eprintln!("{}", facts.render());
|
||||||
|
let transport = phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
||||||
|
&installer.exec,
|
||||||
|
server.clone(),
|
||||||
|
provider_id.clone(),
|
||||||
|
model.clone(),
|
||||||
|
)
|
||||||
|
.with_auth(password);
|
||||||
|
return match phoebus_installer::ai_guide::generate_and_review_at(
|
||||||
|
&mut installer.config,
|
||||||
|
&facts,
|
||||||
|
ProviderKind::Local,
|
||||||
|
&server,
|
||||||
|
&model,
|
||||||
|
&transport,
|
||||||
|
) {
|
||||||
|
Ok(outcome) => {
|
||||||
|
println!("{}", outcome.render());
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("OpenCode proposal rejected; continuing with the proven defaults: {e}");
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let provider = resolve_provider(cli, &installer.config)?;
|
||||||
if provider == ProviderKind::None {
|
if provider == ProviderKind::None {
|
||||||
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
|
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
|
||||||
return Ok(());
|
return Ok(false);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Opt-in: show exactly what leaves the machine before sending it.
|
|
||||||
let facts = installer.system_facts();
|
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Sending these system facts to {} (no passwords, passphrases or files):",
|
"Sending these system facts to {} (no passwords, passphrases or files):",
|
||||||
provider.as_str()
|
provider.as_str()
|
||||||
|
|
@ -244,7 +426,6 @@ fn run_ai_guidance(
|
||||||
)
|
)
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
// A self-hosted local model usually needs no key.
|
|
||||||
(None, false) => None,
|
(None, false) => None,
|
||||||
};
|
};
|
||||||
let model = cli.ai_model.clone().unwrap_or_default();
|
let model = cli.ai_model.clone().unwrap_or_default();
|
||||||
|
|
@ -257,10 +438,15 @@ fn run_ai_guidance(
|
||||||
&model,
|
&model,
|
||||||
&transport,
|
&transport,
|
||||||
) {
|
) {
|
||||||
Ok(outcome) => println!("{}", outcome.render()),
|
Ok(outcome) => {
|
||||||
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
|
println!("{}", outcome.render());
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("AI proposal rejected; continuing with the proven defaults: {e}");
|
||||||
|
Ok(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> ExitCode {
|
fn main() -> ExitCode {
|
||||||
|
|
@ -282,16 +468,10 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(url) = &cli.opencode_probe {
|
if let Some(url) = &cli.opencode_probe {
|
||||||
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint};
|
return Ok(run_opencode_probe(&cli, url, false));
|
||||||
let endpoint =
|
}
|
||||||
Endpoint::parse(url).map_err(|e| format!("invalid OpenCode endpoint `{url}`: {e}"))?;
|
if let Some(url) = &cli.opencode_test {
|
||||||
let capability = probe(&endpoint, std::time::Duration::from_secs(5));
|
return Ok(run_opencode_probe(&cli, url, true));
|
||||||
println!("{}", serde_json::to_string_pretty(&capability)?);
|
|
||||||
return Ok(if capability.state == ConnectionState::Ready {
|
|
||||||
ExitCode::SUCCESS
|
|
||||||
} else {
|
|
||||||
ExitCode::FAILURE
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(name) = &cli.emit_asset {
|
if let Some(name) = &cli.emit_asset {
|
||||||
|
|
@ -411,12 +591,13 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
|
||||||
println!("{}", installer.system_facts().render());
|
println!("{}", installer.system_facts().render());
|
||||||
return Ok(ExitCode::SUCCESS);
|
return Ok(ExitCode::SUCCESS);
|
||||||
}
|
}
|
||||||
run_ai_guidance(&cli, &mut installer)?;
|
let ai_validated = run_ai_guidance(&cli, &mut installer)?;
|
||||||
|
|
||||||
// AI is mandatory to install; a deterministic no-AI run needs the explicit
|
// AI is mandatory to install, and a validated interaction (not merely a
|
||||||
|
// provider name) is required; a deterministic no-AI run needs the explicit
|
||||||
// break-glass. Dry-run and plan modes are exempt.
|
// break-glass. Dry-run and plan modes are exempt.
|
||||||
if do_install && !installer.config.runtime.dry_run {
|
if do_install && !installer.config.runtime.dry_run {
|
||||||
require_ai_for_install(&cli, resolve_provider(&cli, &installer.config)?)?;
|
require_ai_for_install(&cli, ai_validated)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(path) = &cli.save_config {
|
if let Some(path) = &cli.save_config {
|
||||||
|
|
|
||||||
|
|
@ -109,7 +109,7 @@ fn install_without_ai_is_refused() {
|
||||||
.expect("run phoebus-installer");
|
.expect("run phoebus-installer");
|
||||||
assert!(!out.status.success());
|
assert!(!out.status.success());
|
||||||
let err = String::from_utf8_lossy(&out.stderr);
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
assert!(err.contains("requires a connected AI"), "{err}");
|
assert!(err.contains("validated AI interaction"), "{err}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -122,21 +122,31 @@ fn no_ai_is_the_explicit_break_glass() {
|
||||||
.output()
|
.output()
|
||||||
.expect("run phoebus-installer");
|
.expect("run phoebus-installer");
|
||||||
let err = String::from_utf8_lossy(&out.stderr);
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
assert!(!err.contains("requires a connected AI"), "{flag}: {err}");
|
assert!(!err.contains("validated AI interaction"), "{flag}: {err}");
|
||||||
assert!(err.contains("configuration is incomplete"), "{flag}: {err}");
|
assert!(err.contains("configuration is incomplete"), "{flag}: {err}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn local_provider_needs_no_key_at_the_gate() {
|
fn an_unreachable_provider_does_not_satisfy_the_ai_gate() {
|
||||||
// A local provider satisfies the gate without --no-ai (it fails later at
|
// A provider *name* is not enough: without a real, validated model
|
||||||
// the incomplete config, not at the AI gate).
|
// interaction the install is refused (a deliberately closed port makes the
|
||||||
|
// result deterministic and offline).
|
||||||
let out = Command::new(bin())
|
let out = Command::new(bin())
|
||||||
.args(["--install", "--yes", "--ai", "--ai-provider", "local"])
|
.args([
|
||||||
|
"--install",
|
||||||
|
"--yes",
|
||||||
|
"--ai",
|
||||||
|
"--ai-provider",
|
||||||
|
"local",
|
||||||
|
"--ai-endpoint",
|
||||||
|
"http://127.0.0.1:1/v1/chat/completions",
|
||||||
|
])
|
||||||
.output()
|
.output()
|
||||||
.expect("run phoebus-installer");
|
.expect("run phoebus-installer");
|
||||||
|
assert!(!out.status.success());
|
||||||
let err = String::from_utf8_lossy(&out.stderr);
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
assert!(!err.contains("requires a connected AI"), "{err}");
|
assert!(err.contains("validated AI interaction"), "{err}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue