Some checks are pending
ci / test (push) Waiting to run
- Mango + DankMaterialShell desktop option (desktop.profile = "mango") through the GURU overlay with scoped ~amd64 keywords, a sealed session entry point and a dwl fallback session (ADR 0009). - Coherent rollback/recovery: coordinated @ + @var snapshots, fstab and BLS root-subvolume rewriting, matching-kernel selection, snapshot recovery entry, retention/space gates and sys undo (ADR 0007). - Installed assistant (sys ask) with an OS-level systemd sandbox boundary and fail-closed typed plans; resolved package effects bound to approval. - Nix build isolation enforced (sandbox, no fallback) plus lifecycle/cleanup. - Desktop helpers (menu/lock/idle), transaction log, release gates with atomic publish and signing helpers, and a Debian-Live appliance VM harness.
287 lines
9.8 KiB
Rust
287 lines
9.8 KiB
Rust
//! Installed conversational assistant: natural request -> validated typed plan.
|
|
//!
|
|
//! The model is given only bounded system facts and a closed action schema. It
|
|
//! returns an [`AssistantPlan`] whose actions deserialize into the same
|
|
//! `SystemAction` enum `sys` executes. Nothing here runs with privilege: the
|
|
//! caller shows the plan, obtains approval, and the deterministic broker in
|
|
//! `phoebus-executor` executes it.
|
|
|
|
use phoebus_core::action::SystemAction;
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
use crate::provider::{ChatMessage, ChatRequest, ModelTransport, ProviderKind, SystemFacts};
|
|
use crate::AiError;
|
|
|
|
/// One reason per proposed action.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AssistantRationale {
|
|
pub action: String,
|
|
pub reason: String,
|
|
}
|
|
|
|
/// A validated plan from the model.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
pub struct AssistantPlan {
|
|
pub version: u32,
|
|
/// A short, human-readable explanation of the plan.
|
|
pub summary: String,
|
|
#[serde(default)]
|
|
pub actions: Vec<SystemAction>,
|
|
#[serde(default)]
|
|
pub rationale: Vec<AssistantRationale>,
|
|
}
|
|
|
|
impl AssistantPlan {
|
|
pub fn render(&self) -> String {
|
|
let mut out = String::new();
|
|
out.push_str(&format!("{}\n", self.summary));
|
|
if self.actions.is_empty() {
|
|
out.push_str("(no system actions proposed)\n");
|
|
}
|
|
for action in &self.actions {
|
|
out.push_str(&format!(" - {}\n", action.describe()));
|
|
if let Some(r) = self
|
|
.rationale
|
|
.iter()
|
|
.find(|r| r.action == action_tag(action))
|
|
{
|
|
out.push_str(&format!(" reason: {}\n", r.reason));
|
|
}
|
|
}
|
|
out
|
|
}
|
|
}
|
|
|
|
/// The serde tag of an action (`install_package`, ...).
|
|
pub fn action_tag(action: &SystemAction) -> String {
|
|
serde_json::to_value(action)
|
|
.ok()
|
|
.and_then(|v| v.get("action").and_then(|a| a.as_str()).map(str::to_string))
|
|
.unwrap_or_default()
|
|
}
|
|
|
|
/// The system prompt for the installed assistant. The action set is closed and
|
|
/// there is no shell or file action.
|
|
pub const ASSISTANT_PROMPT: &str = "\
|
|
You are the Phoebus OS system assistant. You can ONLY propose actions from this \
|
|
closed set: inspect_service, enable_service, disable_service, inspect_package, \
|
|
install_package, remove_package, search_packages, flatpak_install, flatpak_remove, \
|
|
flatpak_list, nix_prepare, create_snapshot, undo, rollback_status, history, \
|
|
update_system, prepare_updates, inspect_updates.
|
|
|
|
Reply with ONLY a JSON object:
|
|
{\"version\":1,\"summary\":\"...\",\"actions\":[{\"action\":\"...\",...}],\
|
|
\"rationale\":[{\"action\":\"...\",\"reason\":\"...\"}]}
|
|
|
|
Rules: give every action a non-empty reason; prefer inspection before mutation; \
|
|
never propose disabling verification, enabling ~amd64 globally, weakening \
|
|
LUKS2/Btrfs/systemd/UEFI, or any shell, file or arbitrary command action. You do \
|
|
not have a shell, credentials, or access to private files. A human reviews and \
|
|
authenticates every mutation.";
|
|
|
|
/// Parse and validate an assistant plan, fail-closed.
|
|
pub fn parse_plan(text: &str) -> Result<AssistantPlan, AiError> {
|
|
let plan: AssistantPlan = serde_json::from_str(text)?;
|
|
if plan.version != 1 {
|
|
return Err(AiError::UnsupportedVersion(plan.version));
|
|
}
|
|
if plan.summary.trim().is_empty() {
|
|
return Err(AiError::Rejected("plan has no summary".into()));
|
|
}
|
|
for action in &plan.actions {
|
|
action
|
|
.validate()
|
|
.map_err(|e| AiError::Rejected(format!("{}: {e}", action.describe())))?;
|
|
let tag = action_tag(action);
|
|
let has_reason = plan
|
|
.rationale
|
|
.iter()
|
|
.any(|r| r.action == tag && !r.reason.trim().is_empty());
|
|
if !has_reason {
|
|
return Err(AiError::Rejected(format!(
|
|
"{}: missing a non-empty reason",
|
|
action.describe()
|
|
)));
|
|
}
|
|
}
|
|
Ok(plan)
|
|
}
|
|
|
|
/// Build the chat request for a user instruction plus system facts.
|
|
pub fn build_request(
|
|
provider: ProviderKind,
|
|
model: &str,
|
|
facts: &SystemFacts,
|
|
instruction: &str,
|
|
) -> ChatRequest {
|
|
let model = if model.trim().is_empty() {
|
|
provider.default_model().to_string()
|
|
} else {
|
|
model.trim().to_string()
|
|
};
|
|
let user = format!(
|
|
"Bounded system facts (JSON):\n{}\n\nUser request: {instruction}\n\n\
|
|
Respond with a version 1 assistant plan.",
|
|
facts.render()
|
|
);
|
|
ChatRequest {
|
|
model,
|
|
messages: vec![
|
|
ChatMessage {
|
|
role: "system".into(),
|
|
content: ASSISTANT_PROMPT.into(),
|
|
},
|
|
ChatMessage {
|
|
role: "user".into(),
|
|
content: user,
|
|
},
|
|
],
|
|
temperature: 0.0,
|
|
response_format: Some(crate::provider::ResponseFormat {
|
|
kind: "json_object".into(),
|
|
}),
|
|
}
|
|
}
|
|
|
|
/// Ask the provider for a plan and parse it, fail-closed at every step.
|
|
pub fn complete_plan(
|
|
provider: ProviderKind,
|
|
endpoint: &str,
|
|
model: &str,
|
|
facts: &SystemFacts,
|
|
instruction: &str,
|
|
transport: &dyn ModelTransport,
|
|
) -> Result<AssistantPlan, AiError> {
|
|
if provider == ProviderKind::None {
|
|
return Err(AiError::ProviderUnavailable(
|
|
"no AI provider selected".into(),
|
|
));
|
|
}
|
|
if endpoint.trim().is_empty() {
|
|
return Err(AiError::ProviderUnavailable(
|
|
"no provider endpoint configured".into(),
|
|
));
|
|
}
|
|
facts.validate_no_forbidden()?;
|
|
let request = build_request(provider, model, facts, instruction);
|
|
let body = serde_json::to_string(&request)?;
|
|
let response = transport.send(provider, endpoint, &body)?;
|
|
let content = crate::provider::extract_content(&response)?;
|
|
parse_plan(&content)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::provider::TestTransport;
|
|
use phoebus_core::hardware::HardwareReport;
|
|
use phoebus_core::InstallConfig;
|
|
|
|
fn facts() -> SystemFacts {
|
|
SystemFacts::from_system(
|
|
&InstallConfig::default(),
|
|
&HardwareReport::default(),
|
|
&std::collections::HashMap::new(),
|
|
true,
|
|
None,
|
|
)
|
|
}
|
|
|
|
fn wrap(plan_json: &str) -> String {
|
|
serde_json::json!({
|
|
"choices": [{ "message": { "content": plan_json } }]
|
|
})
|
|
.to_string()
|
|
}
|
|
|
|
#[test]
|
|
fn parses_a_valid_plan() {
|
|
let text = r#"{
|
|
"version": 1,
|
|
"summary": "Check ssh and install vim",
|
|
"actions": [
|
|
{"action":"inspect_service","name":"sshd"},
|
|
{"action":"install_package","atom":"app-editors/vim"}
|
|
],
|
|
"rationale": [
|
|
{"action":"inspect_service","reason":"confirm it is present"},
|
|
{"action":"install_package","reason":"the user asked for vim"}
|
|
]
|
|
}"#;
|
|
let plan = parse_plan(text).unwrap();
|
|
assert_eq!(plan.actions.len(), 2);
|
|
assert!(plan.render().contains("install package app-editors/vim"));
|
|
assert!(plan.render().contains("reason: the user asked for vim"));
|
|
}
|
|
|
|
#[test]
|
|
fn unknown_actions_and_shell_fail_closed() {
|
|
let text = r#"{"version":1,"summary":"x","actions":[{"action":"run_shell","command":"rm -rf /"}],"rationale":[{"action":"run_shell","reason":"no"}]}"#;
|
|
assert!(parse_plan(text).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn actions_require_a_reason() {
|
|
let text = r#"{"version":1,"summary":"x","actions":[{"action":"enable_service","name":"sshd"}],"rationale":[]}"#;
|
|
assert!(matches!(parse_plan(text), Err(AiError::Rejected(_))));
|
|
let empty_reason = r#"{"version":1,"summary":"x","actions":[{"action":"enable_service","name":"sshd"}],"rationale":[{"action":"enable_service","reason":" "}]}"#;
|
|
assert!(parse_plan(empty_reason).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn invalid_values_are_rejected() {
|
|
let text = r#"{"version":1,"summary":"x","actions":[{"action":"install_package","atom":"bad atom"}],"rationale":[{"action":"install_package","reason":"x"}]}"#;
|
|
assert!(parse_plan(text).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn transport_round_trip_and_unavailable_provider() {
|
|
let plan = r#"{"version":1,"summary":"look","actions":[{"action":"history"}],"rationale":[{"action":"history","reason":"user asked"}]}"#;
|
|
let transport = TestTransport::new(wrap(plan));
|
|
let parsed = complete_plan(
|
|
ProviderKind::DeepSeek,
|
|
"https://api.deepseek.com/chat/completions",
|
|
"",
|
|
&facts(),
|
|
"what changed?",
|
|
&transport,
|
|
)
|
|
.unwrap();
|
|
assert_eq!(parsed.actions.len(), 1);
|
|
assert!(complete_plan(ProviderKind::None, "", "", &facts(), "hi", &transport).is_err());
|
|
assert!(complete_plan(ProviderKind::Local, "", "", &facts(), "hi", &transport).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn malformed_responses_are_reported_not_ignored() {
|
|
let transport = TestTransport::new(wrap("not json at all"));
|
|
assert!(complete_plan(
|
|
ProviderKind::Local,
|
|
"http://127.0.0.1:11434/v1/chat/completions",
|
|
"m",
|
|
&facts(),
|
|
"hi",
|
|
&transport
|
|
)
|
|
.is_err());
|
|
// A response with no choices is a provider error.
|
|
let empty = TestTransport::new("{\"choices\":[]}");
|
|
assert!(complete_plan(
|
|
ProviderKind::Local,
|
|
"http://127.0.0.1:11434/v1/chat/completions",
|
|
"m",
|
|
&facts(),
|
|
"hi",
|
|
&empty
|
|
)
|
|
.is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn action_tag_matches_the_schema() {
|
|
assert_eq!(action_tag(&SystemAction::History), "history");
|
|
assert_eq!(action_tag(&SystemAction::FlatpakList), "flatpak_list");
|
|
}
|
|
}
|