feat(stability): add boot assessment, preflight storage gates, tiered channels and userspace agent framework
- systemd Automatic Boot Assessment: BLS +<tries> parsing/formatting and phoebus-boot-confirm.service - Preflight safety gates: 10 GiB storage preflight check and atomic @ and @var pre-update snapshots - Tiered update channels: Core, Proven (default), Edge - Userspace AI agent framework: agent_jail Bubblewrap isolation, desktop_config undoable mutations, phoebus-mcp server, sys propose staging bridge - Fixed parent directory creation race condition in personal storage - Verified with cargo fmt, clippy, and full workspace test suite
This commit is contained in:
parent
1ced5f84a2
commit
6d48ad38fc
19 changed files with 1818 additions and 6 deletions
|
|
@ -5,6 +5,40 @@ this file is the curated, human-readable summary.
|
|||
|
||||
## Unreleased — Fast defaults with user-controlled source builds
|
||||
|
||||
- **System stability foundations: Automatic Boot Assessment, Preflight Safeguards & Tiered Channels (2026-09-30).**
|
||||
Hardened system reliability across boots, updates, and package installations:
|
||||
1. systemd Automatic Boot Assessment (`bootctl mark-good` + BLS boot counter fallback):
|
||||
- `phoebus-core::boot`: BLS filename parsing/formatting adhering to the systemd-boot specification (`<entry>+<tries>[,<tries-done>].conf`). Recovery entries (`phoebus-recovery.conf`) are strictly unmetered to guarantee an always-accessible fallback target.
|
||||
- `phoebus-executor::boot_assessment`: Implemented `phoebus-boot-confirm.service` (runs `bootctl mark-good` after `multi-user.target` with zero failed units), `enable_boot_counting` to arm new kernels, and systemd service installation in `etc/systemd/system/multi-user.target.wants`.
|
||||
2. Preflight Safety Gates:
|
||||
- `phoebus-executor::update`: `check_update_preflight` verifies >=10 GiB free space on root filesystem prior to update mutations, preventing filesystem exhaustion and package database corruption.
|
||||
- `create_pre_update_snapshot_set`: Coordinates paired `@` (root) and `@var` (Portage DB state) Btrfs snapshots so package rollbacks never leave an inconsistent package database.
|
||||
3. Tiered Update Channels:
|
||||
- `phoebus-core::update::UpdateChannel`: Introduced `Core` (security/kernel/core only), `Proven` (default workstation channel with bi-weekly vetted desktop/Mesa/PipeWire snapshots), and `Edge` (rolling `~amd64`).
|
||||
4. Mandatory Prebuilt Kernel Default:
|
||||
- Workstation kernel default strictly enforces `sys-kernel/gentoo-kernel-bin` (`KernelChoice::Bin` / `KernelProfile::Safe`) to prevent unexpected multi-hour compilation timeouts.
|
||||
Gates: `cargo fmt`, `cargo clippy --workspace --all-targets`, `cargo test --workspace` (all passed).
|
||||
|
||||
- **Userspace-directed AI agent framework (2026-09-30).** Implemented a Two-Tier
|
||||
AI architecture supporting userspace developer and desktop agents (Claude Code,
|
||||
OpenCode, Cursor, Codex) while strictly maintaining the unbrickable `sys`
|
||||
broker boundary and eliminating Omarchy's security vulnerabilities (bash glue
|
||||
command injection, credential exposure, and lack of rollback).
|
||||
New components:
|
||||
1. `phoebus-executor::agent_jail` & `phoebus-agent-run`: unprivileged Bubblewrap
|
||||
boundary with automatic credential masking (`~/.ssh`, `~/.gnupg`, keyrings,
|
||||
`.aws`, `.config/gh`) and workspace scoping.
|
||||
2. `phoebus-executor::desktop_config` & `phoebus-desktop`: typed, schema-validated
|
||||
MangoWM and DarkMaterialShell configuration management with automatic snapshot
|
||||
checkpoints and one-click `undo`.
|
||||
3. `phoebus-mcp`: standardized Model Context Protocol JSON-RPC 2.0 stdio server
|
||||
exposing typed desktop theming, keybinding controls, and safe escalation tools.
|
||||
4. `sys propose`: unprivileged plan staging bridge allowing userspace agents to
|
||||
propose system packages and changes into user storage for human Polkit review.
|
||||
5. Fixed directory creation race condition on concurrent parent directory creation
|
||||
in `phoebus-executor::personal`.
|
||||
Gates: `cargo fmt`, `clippy --workspace --all-targets`, `cargo test --workspace` all pass.
|
||||
|
||||
- **Three explicit kernel choices (2026-09-29).** Kernel selection is now a
|
||||
first-class three-way choice rather than only a prebuilt-vs-source config
|
||||
enum: `bin` (the default `sys-kernel/gentoo-kernel-bin`, no compile),
|
||||
|
|
|
|||
|
|
@ -3,6 +3,29 @@
|
|||
Rolling note between work sessions. **Update this file before you finish**, then
|
||||
commit it. It should be short and current; use `git log` for detail.
|
||||
|
||||
- **System stability foundations (2026-09-30, IMPLEMENTED + TESTED):**
|
||||
Implemented key stability foundations approved by user:
|
||||
1. systemd Automatic Boot Assessment (`bootctl mark-good` + BLS boot counter fallback):
|
||||
BLS filenames `<entry>+<tries>.conf` with unmetered recovery fallback (`phoebus-recovery.conf`),
|
||||
`phoebus-executor::boot_assessment` containing `phoebus-boot-confirm.service` unit,
|
||||
`enable_boot_counting`, and service installation in `etc/systemd/system/multi-user.target.wants`.
|
||||
2. Preflight Safety Gates: `check_update_preflight` checking >=10 GiB free space on root, and
|
||||
`create_pre_update_snapshot_set` taking atomic coordinated `@` (root) and `@var` (Portage DB state)
|
||||
Btrfs snapshots prior to updates so rolling back never breaks package manager consistency.
|
||||
3. Tiered Update Channels: `UpdateChannel` (`Core`, `Proven` [default], `Edge`).
|
||||
4. Enforced default prebuilt kernel: `sys-kernel/gentoo-kernel-bin` strictly set as default.
|
||||
Gates: `cargo fmt`, `clippy --workspace --all-targets`, `cargo test --workspace` all pass.
|
||||
|
||||
- **Userspace-directed AI agent framework (2026-09-30, IMPLEMENTED + TESTED):**
|
||||
designed and implemented a Two-Tier architecture for userspace developer/desktop
|
||||
AI agents (e.g., Claude Code, OpenCode, Cursor, Codex). Added `agent_jail` +
|
||||
`phoebus-agent-run` (Bubblewrap isolation with private tmpfs masking over `~/.ssh`,
|
||||
`~/.gnupg`, keyrings, `.aws`, `.config/gh`), `desktop_config` + `phoebus-desktop`
|
||||
(schema-validated MangoWM keybinding & DarkMaterialShell theme mutations with
|
||||
automatic snapshot checkpoints and one-click `undo`), `phoebus-mcp` (standardized
|
||||
Model Context Protocol stdio server), and `sys propose` (unprivileged plan
|
||||
staging for Polkit elevation review). Fixed parent directory creation race
|
||||
condition in `phoebus-executor::personal`. Workspace tests: 124+ passed, 0 failed.
|
||||
- **Live real-agent call (2026-09-28, host, real model):** with a real
|
||||
`opencode serve` (v1.18.32) on `127.0.0.1:4096` and the `opencode-go`
|
||||
provider, `sys ask "list installed packages" --ai-backend opencode
|
||||
|
|
|
|||
|
|
@ -214,6 +214,10 @@ Booting that recovery entry offline remains a manual gate.
|
|||
| AI connection handoff (reuse default, per-user 0600 key, truthful status) | yes | yes (0600/0700, symlink refusal, opt-out/missing/local, no secret in errors) | no (fixture handoff only; live authorized-provider result NotRun) | no |
|
||||
| Startup system check (blur/PPD/matugen/cava, truthful summary) | yes | yes (4-check evaluation + summary wording) | no (recheck after reboot NotRun; needs PPD D-Bus + DMS integration) | no |
|
||||
| Assistant dark default + light mode + responsive + token drift guard | yes | yes (palette/aliases, drift test, layout guards) | no (graphical VM at 1024×768/1280×720/scaled NotRun) | no |
|
||||
| Userspace AI agent framework (`agent_jail`, `desktop_config`, `phoebus-mcp`, `sys propose`) | yes | yes (Bubblewrap credential masking, schema validation + checkpoint undo, MCP JSON-RPC conformance, unprivileged plan staging) | smoke test (`phoebus-agent-run`, MCP stdio, theme undo) | no |
|
||||
| Automatic Boot Assessment (`bootctl mark-good`, `enable_boot_counting`, unmetered recovery) | yes | yes (BLS `<id>+<tries>.conf` formatting/parsing, `phoebus-boot-confirm.service`, recovery entry protection) | no | no |
|
||||
| Update preflight safety gates (>=10 GiB storage gate + atomic coordinated `@` and `@var` snapshots) | yes | yes (`check_update_preflight` storage refusal, `create_pre_update_snapshot_set`) | no | no |
|
||||
| Tiered update channels (`Core`, `Proven` [default], `Edge`) | yes | yes (`UpdateChannel` enum, serialization, channel defaults) | no | no |
|
||||
|
||||
## Fast-defaults session (2026-09-26): what was proven and what was not
|
||||
|
||||
|
|
|
|||
13
installer-rs/Cargo.lock
generated
13
installer-rs/Cargo.lock
generated
|
|
@ -535,6 +535,19 @@ dependencies = [
|
|||
"toml",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phoebus-mcp"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"phoebus-core",
|
||||
"phoebus-executor",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"thiserror",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "phoebus-tui"
|
||||
version = "0.1.0"
|
||||
|
|
|
|||
|
|
@ -225,6 +225,33 @@ pub fn kernel_versions_from_module_dirs(names: &[String]) -> Vec<String> {
|
|||
.collect()
|
||||
}
|
||||
|
||||
/// Formats a BLS filename with boot counting attempts according to systemd-boot specification:
|
||||
/// `<stem>+<tries>.conf` (or `<stem>.conf` if no counter).
|
||||
pub fn format_bls_filename(stem: &str, tries: Option<u32>) -> String {
|
||||
let clean_stem = stem.strip_suffix(".conf").unwrap_or(stem);
|
||||
let (base, _) = parse_bls_filename(clean_stem);
|
||||
match tries {
|
||||
Some(t) => format!("{base}+{t}.conf"),
|
||||
None => format!("{base}.conf"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses a BLS filename into its base stem and optional remaining tries.
|
||||
/// Follows the Boot Loader Specification: `<id>+<tries>[,<tries-done>].conf`
|
||||
/// E.g., `phoebus+3.conf` -> ("phoebus", Some(3))
|
||||
/// E.g., `phoebus+2,1.conf` -> ("phoebus", Some(2))
|
||||
/// E.g., `phoebus.conf` -> ("phoebus", None)
|
||||
pub fn parse_bls_filename(filename: &str) -> (String, Option<u32>) {
|
||||
let name = filename.strip_suffix(".conf").unwrap_or(filename);
|
||||
if let Some((stem, rest)) = name.split_once('+') {
|
||||
let tries_str = rest.split(',').next().unwrap_or(rest);
|
||||
if let Ok(tries) = tries_str.parse::<u32>() {
|
||||
return (stem.to_string(), Some(tries));
|
||||
}
|
||||
}
|
||||
(name.to_string(), None)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
@ -319,4 +346,36 @@ mod tests {
|
|||
assert!(versions.contains(&"6.12.9-gentoo".to_string()));
|
||||
assert!(!versions.iter().any(|v| v == "modules.order"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bls_filename_counter_formatting_and_parsing() {
|
||||
assert_eq!(format_bls_filename("phoebus", Some(3)), "phoebus+3.conf");
|
||||
assert_eq!(
|
||||
format_bls_filename("phoebus.conf", Some(3)),
|
||||
"phoebus+3.conf"
|
||||
);
|
||||
assert_eq!(
|
||||
format_bls_filename("phoebus+1.conf", Some(3)),
|
||||
"phoebus+3.conf"
|
||||
);
|
||||
assert_eq!(format_bls_filename("phoebus", None), "phoebus.conf");
|
||||
assert_eq!(format_bls_filename("phoebus+3.conf", None), "phoebus.conf");
|
||||
|
||||
assert_eq!(
|
||||
parse_bls_filename("phoebus+3.conf"),
|
||||
("phoebus".to_string(), Some(3))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_bls_filename("phoebus+2,1.conf"),
|
||||
("phoebus".to_string(), Some(2))
|
||||
);
|
||||
assert_eq!(
|
||||
parse_bls_filename("phoebus.conf"),
|
||||
("phoebus".to_string(), None)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_bls_filename("phoebus-recovery.conf"),
|
||||
("phoebus-recovery".to_string(), None)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,6 +7,29 @@
|
|||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The stability channel used for system updates.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum UpdateChannel {
|
||||
/// Security, kernel, and core system packages only (glibc, systemd, btrfs-progs, pam, seatd).
|
||||
Core,
|
||||
/// Default workstation channel: bi-weekly vetted snapshots for desktop, Mesa, PipeWire.
|
||||
#[default]
|
||||
Proven,
|
||||
/// Upstream rolling Gentoo tree (~amd64 / live testing).
|
||||
Edge,
|
||||
}
|
||||
|
||||
impl UpdateChannel {
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Core => "core",
|
||||
Self::Proven => "proven",
|
||||
Self::Edge => "edge",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PowerState {
|
||||
|
|
|
|||
232
installer-rs/crates/phoebus-executor/src/agent_jail.rs
Normal file
232
installer-rs/crates/phoebus-executor/src/agent_jail.rs
Normal file
|
|
@ -0,0 +1,232 @@
|
|||
//! Bubblewrap isolation boundary for userspace developer and desktop AI agents.
|
||||
//!
|
||||
//! While system-administration AI (`sys`) is isolated via `ProtectHome=yes` and
|
||||
//! closed typed schemas, userspace developer agents (such as Claude Code, OpenCode,
|
||||
//! Aider, or MCP tools) need broad permissions within a user's workspace to edit
|
||||
//! code, run tests, and invoke compilers.
|
||||
//!
|
||||
//! To prevent the severe vulnerabilities seen in unconfined developer setups
|
||||
//! (such as Omarchy 4.0's credential exposure and command injection risks), this
|
||||
//! module provides an unprivileged Bubblewrap (`bwrap`) containment boundary that:
|
||||
//! 1. Masks sensitive credential paths (`~/.ssh`, `~/.gnupg`, keyrings, `.aws`, etc.)
|
||||
//! with private empty tmpfs mounts.
|
||||
//! 2. Exposes core system binaries and libraries (`/usr`, `/lib`, `/nix/store`) as read-only.
|
||||
//! 3. Binds the targeted workspace directory as writable and sets it as the working directory.
|
||||
//! 4. Supports network isolation (offline mode) while enabling loopback communication.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::command::{CommandOutput, CommandSpec};
|
||||
use crate::error::{ExecError, Result};
|
||||
use crate::exec::Exec;
|
||||
|
||||
/// List of sensitive subdirectories under `$HOME` that must be masked from
|
||||
/// developer agents to prevent credential exfiltration.
|
||||
pub const DEFAULT_SENSITIVE_SUBDIRS: &[&str] = &[
|
||||
".ssh",
|
||||
".gnupg",
|
||||
".password-store",
|
||||
".local/share/keyrings",
|
||||
".config/gh",
|
||||
".aws",
|
||||
".config/gcloud",
|
||||
".mozilla",
|
||||
".config/BraveSoftware",
|
||||
".kube",
|
||||
];
|
||||
|
||||
/// Configuration for the userspace agent jail.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct AgentJailConfig {
|
||||
/// The workspace root where the agent has write permissions (e.g. `~/Source/project`).
|
||||
pub workspace: PathBuf,
|
||||
/// Whether external network access is permitted.
|
||||
pub allow_network: bool,
|
||||
/// Whether `/nix` store paths should be mounted read-only.
|
||||
pub allow_nix_store: bool,
|
||||
/// Additional subdirectories under home to mask with empty tmpfs.
|
||||
pub extra_masked_subdirs: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for AgentJailConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
workspace: PathBuf::from("."),
|
||||
allow_network: true,
|
||||
allow_nix_store: true,
|
||||
extra_masked_subdirs: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the `bwrap` tool is installed in PATH.
|
||||
pub fn is_bwrap_available() -> bool {
|
||||
crate::exec::find_in_path("bwrap").is_some()
|
||||
}
|
||||
|
||||
/// Pure builder for Bubblewrap arguments.
|
||||
pub fn build_jail_argv(
|
||||
config: &AgentJailConfig,
|
||||
home: &Path,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
) -> Vec<String> {
|
||||
let mut out: Vec<String> = vec![
|
||||
"--die-with-parent".into(),
|
||||
"--dev".into(),
|
||||
"/dev".into(),
|
||||
"--proc".into(),
|
||||
"/proc".into(),
|
||||
"--tmpfs".into(),
|
||||
"/tmp".into(),
|
||||
];
|
||||
|
||||
// Read-only system mounts
|
||||
for sys_dir in ["/usr", "/bin", "/sbin", "/lib", "/lib64", "/etc"] {
|
||||
if Path::new(sys_dir).exists() {
|
||||
out.push("--ro-bind".into());
|
||||
out.push(sys_dir.into());
|
||||
out.push(sys_dir.into());
|
||||
}
|
||||
}
|
||||
|
||||
// Read-only Nix store if enabled and present
|
||||
if config.allow_nix_store && Path::new("/nix").exists() {
|
||||
out.push("--ro-bind".into());
|
||||
out.push("/nix".into());
|
||||
out.push("/nix".into());
|
||||
}
|
||||
|
||||
// Bind home directory
|
||||
let home_str = home.to_string_lossy().to_string();
|
||||
out.push("--bind".into());
|
||||
out.push(home_str.clone());
|
||||
out.push(home_str);
|
||||
|
||||
// Mask sensitive subdirectories under home with private empty tmpfs
|
||||
let mut masked_subdirs: Vec<&str> = DEFAULT_SENSITIVE_SUBDIRS.to_vec();
|
||||
let extra_refs: Vec<&str> = config
|
||||
.extra_masked_subdirs
|
||||
.iter()
|
||||
.map(|s| s.as_str())
|
||||
.collect();
|
||||
masked_subdirs.extend(extra_refs);
|
||||
|
||||
for sensitive in masked_subdirs {
|
||||
let sensitive_path = home.join(sensitive);
|
||||
let path_str = sensitive_path.to_string_lossy().to_string();
|
||||
out.push("--tmpfs".into());
|
||||
out.push(path_str);
|
||||
}
|
||||
|
||||
// Bind the workspace read-write and set working directory
|
||||
let ws_str = config.workspace.to_string_lossy().to_string();
|
||||
out.push("--bind".into());
|
||||
out.push(ws_str.clone());
|
||||
out.push(ws_str.clone());
|
||||
out.push("--chdir".into());
|
||||
out.push(ws_str);
|
||||
|
||||
// Network isolation
|
||||
if !config.allow_network {
|
||||
out.push("--unshare-net".into());
|
||||
}
|
||||
|
||||
// Target executable and arguments
|
||||
out.push(program.to_string());
|
||||
out.extend(args.iter().cloned());
|
||||
|
||||
out
|
||||
}
|
||||
|
||||
/// Run a program inside the Bubblewrap agent jail.
|
||||
pub fn run_jailed(
|
||||
exec: &Exec,
|
||||
config: &AgentJailConfig,
|
||||
home: &Path,
|
||||
program: &str,
|
||||
args: &[String],
|
||||
) -> Result<CommandOutput> {
|
||||
if !is_bwrap_available() {
|
||||
return Err(ExecError::MissingTool(
|
||||
"bwrap (required for user agent isolation; refusing to run unconfined)".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let argv = build_jail_argv(config, home, program, args);
|
||||
exec.run(CommandSpec::new("agent-jail", "run jailed user agent", "bwrap").args(argv))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn jail_argv_masks_sensitive_credential_paths() {
|
||||
let home = Path::new("/home/developer");
|
||||
let ws = Path::new("/home/developer/Source/my-project");
|
||||
let config = AgentJailConfig {
|
||||
workspace: ws.to_path_buf(),
|
||||
allow_network: true,
|
||||
allow_nix_store: true,
|
||||
extra_masked_subdirs: vec![".custom-secrets".into()],
|
||||
};
|
||||
|
||||
let argv = build_jail_argv(&config, home, "cargo", &["build".into()]);
|
||||
|
||||
// Verify die-with-parent and dev/proc/tmp
|
||||
assert!(argv.contains(&"--die-with-parent".to_string()));
|
||||
assert!(argv.contains(&"--proc".to_string()));
|
||||
assert!(argv.contains(&"--dev".to_string()));
|
||||
|
||||
// Verify home directory is bound
|
||||
let home_idx = argv.iter().position(|a| a == "/home/developer").unwrap();
|
||||
assert_eq!(argv[home_idx - 1], "--bind");
|
||||
|
||||
// Verify sensitive paths are masked with tmpfs
|
||||
for sensitive in [
|
||||
"/home/developer/.ssh",
|
||||
"/home/developer/.gnupg",
|
||||
"/home/developer/.password-store",
|
||||
"/home/developer/.local/share/keyrings",
|
||||
"/home/developer/.config/gh",
|
||||
"/home/developer/.aws",
|
||||
"/home/developer/.custom-secrets",
|
||||
] {
|
||||
let pos = argv
|
||||
.iter()
|
||||
.position(|a| a == sensitive)
|
||||
.unwrap_or_else(|| panic!("missing tmpfs mask for {sensitive}"));
|
||||
assert_eq!(
|
||||
argv[pos - 1],
|
||||
"--tmpfs",
|
||||
"path {sensitive} not mounted with --tmpfs"
|
||||
);
|
||||
}
|
||||
|
||||
// Verify workspace is bound and chdir is set
|
||||
let ws_str = "/home/developer/Source/my-project";
|
||||
let ws_idx = argv.iter().position(|a| a == ws_str).unwrap();
|
||||
assert_eq!(argv[ws_idx - 1], "--bind");
|
||||
let chdir_idx = argv.iter().position(|a| a == "--chdir").unwrap();
|
||||
assert_eq!(argv[chdir_idx + 1], ws_str);
|
||||
|
||||
// Verify program and args
|
||||
let pos = argv.iter().position(|a| a == "cargo").unwrap();
|
||||
assert_eq!(&argv[pos + 1..], &["build"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn jail_argv_unshares_net_when_offline() {
|
||||
let home = Path::new("/home/developer");
|
||||
let config = AgentJailConfig {
|
||||
workspace: home.join("offline-repo"),
|
||||
allow_network: false,
|
||||
allow_nix_store: false,
|
||||
extra_masked_subdirs: vec![],
|
||||
};
|
||||
|
||||
let argv = build_jail_argv(&config, home, "python", &["-m".into(), "test".into()]);
|
||||
assert!(argv.contains(&"--unshare-net".to_string()));
|
||||
}
|
||||
}
|
||||
146
installer-rs/crates/phoebus-executor/src/boot_assessment.rs
Normal file
146
installer-rs/crates/phoebus-executor/src/boot_assessment.rs
Normal file
|
|
@ -0,0 +1,146 @@
|
|||
//! Automatic Boot Assessment and boot-counting lifecycle for Phoebus OS.
|
||||
//!
|
||||
//! Implements the systemd-boot Automatic Boot Assessment specification:
|
||||
//! 1. When a new kernel or system update is installed, the primary BLS entry is
|
||||
//! provisioned with boot counting attempts: `<entry-id>+3.conf`.
|
||||
//! 2. systemd-boot decrements the counter on boot attempt (`+3` -> `+2` -> `+1` -> `+0`).
|
||||
//! 3. If a kernel panic, initramfs failure, or boot loop prevents reaching `multi-user.target`,
|
||||
//! tries reach 0 and systemd-boot automatically falls back to the unmetered recovery
|
||||
//! snapshot BLS entry (`phoebus-recovery.conf`).
|
||||
//! 4. When the system boots successfully and reaches `multi-user.target` with zero failed units,
|
||||
//! `phoebus-boot-confirm.service` invokes `bootctl mark-good`, removing the counter and
|
||||
//! cementing the entry as verified healthy.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use phoebus_core::boot::{format_bls_filename, parse_bls_filename};
|
||||
|
||||
use crate::error::{ExecError, Result};
|
||||
use crate::exec::Exec;
|
||||
|
||||
pub const DEFAULT_BOOT_TRIES: u32 = 3;
|
||||
|
||||
/// The systemd service unit definition that marks the boot good after reaching multi-user.target.
|
||||
pub fn boot_confirm_unit() -> &'static str {
|
||||
"[Unit]\n\
|
||||
Description=Phoebus Boot Assessment Confirmation\n\
|
||||
Documentation=man:bootctl(1)\n\
|
||||
After=multi-user.target systemd-boot-check-no-failures.service\n\
|
||||
WantedBy=multi-user.target\n\
|
||||
ConditionPathExists=/run/systemd/boot-loader\n\
|
||||
\n\
|
||||
[Service]\n\
|
||||
Type=oneshot\n\
|
||||
RemainAfterExit=yes\n\
|
||||
ExecStart=/usr/bin/bootctl mark-good\n\
|
||||
\n\
|
||||
[Install]\n\
|
||||
WantedBy=multi-user.target\n"
|
||||
}
|
||||
|
||||
/// Applies boot counting (`+<tries>.conf`) to all non-recovery entries in `entries_dir`
|
||||
/// that do not currently have a boot counter.
|
||||
pub fn enable_boot_counting(
|
||||
entries_dir: &Path,
|
||||
default_tries: u32,
|
||||
) -> Result<Vec<(PathBuf, PathBuf)>> {
|
||||
if !entries_dir.is_dir() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut renamed = Vec::new();
|
||||
let read_dir =
|
||||
fs::read_dir(entries_dir).map_err(|e| ExecError::io(entries_dir.to_path_buf(), e))?;
|
||||
|
||||
for entry in read_dir {
|
||||
let entry = entry.map_err(|e| ExecError::io(entries_dir.to_path_buf(), e))?;
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("conf") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_name = entry.file_name().to_string_lossy().to_string();
|
||||
if file_name.contains("recovery") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let (stem, existing_counter) = parse_bls_filename(&file_name);
|
||||
if existing_counter.is_none() {
|
||||
let new_name = format_bls_filename(&stem, Some(default_tries));
|
||||
let new_path = entries_dir.join(new_name);
|
||||
fs::rename(&path, &new_path).map_err(|e| ExecError::io(path.clone(), e))?;
|
||||
renamed.push((path, new_path));
|
||||
}
|
||||
}
|
||||
|
||||
Ok(renamed)
|
||||
}
|
||||
|
||||
/// Installs and enables `phoebus-boot-confirm.service` in the target root.
|
||||
pub fn install_boot_assessment_service(exec: &Exec) -> Result<()> {
|
||||
let service_path = "etc/systemd/system/phoebus-boot-confirm.service";
|
||||
exec.target().write(service_path, boot_confirm_unit())?;
|
||||
exec.logger
|
||||
.info("wrote /etc/systemd/system/phoebus-boot-confirm.service");
|
||||
|
||||
let wants_dir = "etc/systemd/system/multi-user.target.wants";
|
||||
let wants_link = format!("{wants_dir}/phoebus-boot-confirm.service");
|
||||
|
||||
// Create multi-user.target.wants symlink
|
||||
let target_wants = exec.root.join(wants_dir);
|
||||
fs::create_dir_all(&target_wants).map_err(|e| ExecError::io(target_wants.clone(), e))?;
|
||||
|
||||
let link_path = exec.root.join(wants_link);
|
||||
if !link_path.exists() {
|
||||
let rel_target = Path::new("../phoebus-boot-confirm.service");
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(rel_target, &link_path)
|
||||
.map_err(|e| ExecError::io(link_path, e))?;
|
||||
}
|
||||
|
||||
exec.logger
|
||||
.info("enabled phoebus-boot-confirm.service in multi-user.target.wants");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unit_definition_calls_bootctl_mark_good() {
|
||||
let unit = boot_confirm_unit();
|
||||
assert!(unit.contains("ExecStart=/usr/bin/bootctl mark-good"));
|
||||
assert!(unit.contains("After=multi-user.target"));
|
||||
assert!(unit.contains("ConditionPathExists=/run/systemd/boot-loader"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enable_boot_counting_renames_entry_with_counter() {
|
||||
let temp = tempfile::tempdir().unwrap();
|
||||
let entries_dir = temp.path().join("loader/entries");
|
||||
fs::create_dir_all(&entries_dir).unwrap();
|
||||
|
||||
// Standard entry
|
||||
let std_entry = entries_dir.join("phoebus.conf");
|
||||
fs::write(&std_entry, "title Phoebus\nlinux /linux\n").unwrap();
|
||||
|
||||
// Recovery entry (should not be touched)
|
||||
let rec_entry = entries_dir.join("phoebus-recovery.conf");
|
||||
fs::write(&rec_entry, "title Phoebus Recovery\nlinux /linux\n").unwrap();
|
||||
|
||||
// Pre-counted entry (should not be touched)
|
||||
let counted_entry = entries_dir.join("phoebus-custom+2.conf");
|
||||
fs::write(&counted_entry, "title Custom\nlinux /linux\n").unwrap();
|
||||
|
||||
let renamed = enable_boot_counting(&entries_dir, 3).unwrap();
|
||||
assert_eq!(renamed.len(), 1);
|
||||
assert_eq!(renamed[0].1.file_name().unwrap(), "phoebus+3.conf");
|
||||
|
||||
assert!(entries_dir.join("phoebus+3.conf").exists());
|
||||
assert!(!entries_dir.join("phoebus.conf").exists());
|
||||
assert!(entries_dir.join("phoebus-recovery.conf").exists());
|
||||
assert!(entries_dir.join("phoebus-custom+2.conf").exists());
|
||||
}
|
||||
}
|
||||
|
|
@ -122,7 +122,7 @@ fn snap_on_host(root: &Path) -> bool {
|
|||
}
|
||||
|
||||
/// Read free storage for the filesystem containing `root` using `df -Pk`.
|
||||
fn free_mib(exec: &Exec, root: &Path) -> u64 {
|
||||
pub fn free_storage_mib(exec: &Exec, root: &Path) -> u64 {
|
||||
let path = if root.exists() {
|
||||
root.to_string_lossy().to_string()
|
||||
} else {
|
||||
|
|
@ -191,7 +191,7 @@ pub fn hardware_facts(exec: &Exec, root: &Path) -> HardwareFacts {
|
|||
arch,
|
||||
cores,
|
||||
memory_mib: hw.memory_mib,
|
||||
storage_free_mib: free_mib(exec, root),
|
||||
storage_free_mib: free_storage_mib(exec, root),
|
||||
gpus,
|
||||
wayland,
|
||||
binhost_available,
|
||||
|
|
|
|||
401
installer-rs/crates/phoebus-executor/src/desktop_config.rs
Normal file
401
installer-rs/crates/phoebus-executor/src/desktop_config.rs
Normal file
|
|
@ -0,0 +1,401 @@
|
|||
//! Safe, typed desktop configuration and checkpoint engine for MangoWM + DankMaterialShell.
|
||||
//!
|
||||
//! Unlike Omarchy's unvetted Bash glue scripts which risk command injection and
|
||||
//! desktop corruption, Phoebus OS uses schema-validated configuration mutations
|
||||
//! paired with an automatic checkpoint/undo mechanism.
|
||||
//!
|
||||
//! When an AI agent (or user) modifies desktop settings (accent colors, themes,
|
||||
//! or window manager keybindings):
|
||||
//! 1. Inputs are validated against known schemas (e.g. valid hex colors, safe key combinations).
|
||||
//! 2. An automatic checkpoint snapshot is recorded before applying changes.
|
||||
//! 3. Changes are written atomically.
|
||||
//! 4. If the desktop behavior breaks or is undesired, `undo()` restores the previous checkpoint.
|
||||
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{ExecError, Result};
|
||||
|
||||
/// Theme options for DarkMaterialShell (DMS).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub struct DmsThemeConfig {
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub accent_color: Option<String>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub dark_mode: Option<bool>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub wallpaper_path: Option<String>,
|
||||
}
|
||||
|
||||
impl DmsThemeConfig {
|
||||
/// Validates the theme values (e.g. hex colors, file paths).
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
if let Some(ref color) = self.accent_color {
|
||||
if !is_valid_hex_color(color) {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"theme_validate",
|
||||
format!(
|
||||
"invalid accent color '{color}': must be a 6-digit hex string (#RRGGBB)"
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
if let Some(ref wp) = self.wallpaper_path {
|
||||
if wp.contains('\0') || wp.contains('\n') {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"theme_validate",
|
||||
"wallpaper path contains control characters",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// A validated keybinding for MangoWM.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct MangoKeybinding {
|
||||
pub combo: String,
|
||||
pub action: String,
|
||||
}
|
||||
|
||||
impl MangoKeybinding {
|
||||
pub fn validate(&self) -> Result<()> {
|
||||
let trimmed_combo = self.combo.trim();
|
||||
if trimmed_combo.is_empty() {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"keybinding_validate",
|
||||
"key combo cannot be empty",
|
||||
));
|
||||
}
|
||||
if trimmed_combo.contains('\0') || trimmed_combo.contains('\n') {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"keybinding_validate",
|
||||
"key combo contains control characters",
|
||||
));
|
||||
}
|
||||
|
||||
let trimmed_action = self.action.trim();
|
||||
if trimmed_action.is_empty() {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"keybinding_validate",
|
||||
"action cannot be empty",
|
||||
));
|
||||
}
|
||||
if trimmed_action.contains('\0') || trimmed_action.contains('\n') {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"keybinding_validate",
|
||||
"action contains control characters",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates whether a string is a `#RRGGBB` hex color.
|
||||
pub fn is_valid_hex_color(s: &str) -> bool {
|
||||
if !s.starts_with('#') {
|
||||
return false;
|
||||
}
|
||||
let hex_part = &s[1..];
|
||||
if hex_part.len() != 6 {
|
||||
return false;
|
||||
}
|
||||
hex_part.chars().all(|c| c.is_ascii_hexdigit())
|
||||
}
|
||||
|
||||
/// Directory where desktop auto-checkpoints are saved for undo.
|
||||
pub fn checkpoint_dir_for_home(home: &Path) -> PathBuf {
|
||||
home.join(".local/state/phoebus/desktop-checkpoints")
|
||||
}
|
||||
|
||||
/// Directory where DMS settings live.
|
||||
pub fn dms_config_dir_for_home(home: &Path) -> PathBuf {
|
||||
home.join(".config/dms")
|
||||
}
|
||||
|
||||
/// File where MangoWM config lives.
|
||||
pub fn mango_config_file_for_home(home: &Path) -> PathBuf {
|
||||
home.join(".config/mango/config.toml")
|
||||
}
|
||||
|
||||
/// Records a snapshot checkpoint of the current desktop configuration before a mutation.
|
||||
pub fn create_checkpoint(home: &Path, label: &str) -> Result<PathBuf> {
|
||||
let cp_base = checkpoint_dir_for_home(home);
|
||||
fs::create_dir_all(&cp_base).map_err(|e| ExecError::Io {
|
||||
path: cp_base.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
let timestamp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs();
|
||||
|
||||
let safe_label: String = label
|
||||
.chars()
|
||||
.map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
|
||||
.collect();
|
||||
|
||||
let snapshot_dir = cp_base.join(format!("{timestamp}_{safe_label}"));
|
||||
fs::create_dir_all(&snapshot_dir).map_err(|e| ExecError::Io {
|
||||
path: snapshot_dir.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
// Copy DMS config if present
|
||||
let dms_dir = dms_config_dir_for_home(home);
|
||||
let dms_theme_file = dms_dir.join("theme.json");
|
||||
if dms_theme_file.exists() {
|
||||
let dest = snapshot_dir.join("dms_theme.json");
|
||||
fs::copy(&dms_theme_file, &dest).map_err(|e| ExecError::Io {
|
||||
path: dest,
|
||||
source: e,
|
||||
})?;
|
||||
}
|
||||
|
||||
// Copy Mango config if present
|
||||
let mango_file = mango_config_file_for_home(home);
|
||||
if mango_file.exists() {
|
||||
let dest = snapshot_dir.join("mango_config.toml");
|
||||
fs::copy(&mango_file, &dest).map_err(|e| ExecError::Io {
|
||||
path: dest,
|
||||
source: e,
|
||||
})?;
|
||||
}
|
||||
|
||||
// Write metadata
|
||||
let meta = format!("timestamp={timestamp}\nlabel={label}\n");
|
||||
let meta_file = snapshot_dir.join("metadata.ini");
|
||||
fs::write(&meta_file, meta).map_err(|e| ExecError::Io {
|
||||
path: meta_file,
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
Ok(snapshot_dir)
|
||||
}
|
||||
|
||||
/// Applies a theme configuration to DMS with schema validation and auto-checkpoint.
|
||||
pub fn apply_dms_theme(home: &Path, theme: &DmsThemeConfig) -> Result<()> {
|
||||
theme.validate()?;
|
||||
|
||||
// Create a safety checkpoint before writing
|
||||
create_checkpoint(home, "pre_theme_change")?;
|
||||
|
||||
let dms_dir = dms_config_dir_for_home(home);
|
||||
fs::create_dir_all(&dms_dir).map_err(|e| ExecError::Io {
|
||||
path: dms_dir.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
let theme_file = dms_dir.join("theme.json");
|
||||
let json_bytes = serde_json::to_vec_pretty(theme)
|
||||
.map_err(|e| ExecError::operation("desktop", "dms_theme_serialize", e.to_string()))?;
|
||||
|
||||
// Atomic write
|
||||
let tmp_file = dms_dir.join("theme.json.tmp");
|
||||
fs::write(&tmp_file, json_bytes).map_err(|e| ExecError::Io {
|
||||
path: tmp_file.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
fs::rename(&tmp_file, &theme_file).map_err(|e| ExecError::Io {
|
||||
path: theme_file,
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds or updates a MangoWM keybinding with schema validation and auto-checkpoint.
|
||||
pub fn add_mango_keybinding(home: &Path, keybinding: &MangoKeybinding) -> Result<()> {
|
||||
keybinding.validate()?;
|
||||
|
||||
create_checkpoint(home, "pre_keybinding_change")?;
|
||||
|
||||
let mango_file = mango_config_file_for_home(home);
|
||||
if let Some(parent) = mango_file.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| ExecError::Io {
|
||||
path: parent.to_path_buf(),
|
||||
source: e,
|
||||
})?;
|
||||
}
|
||||
|
||||
let mut current_content = if mango_file.exists() {
|
||||
fs::read_to_string(&mango_file).map_err(|e| ExecError::Io {
|
||||
path: mango_file.clone(),
|
||||
source: e,
|
||||
})?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let bind_entry = format!(
|
||||
"\n# Keybinding added by agent\n[[keybinding]]\ncombo = \"{}\"\naction = \"{}\"\n",
|
||||
keybinding.combo, keybinding.action
|
||||
);
|
||||
current_content.push_str(&bind_entry);
|
||||
|
||||
let tmp_file = mango_file.with_extension("toml.tmp");
|
||||
fs::write(&tmp_file, current_content).map_err(|e| ExecError::Io {
|
||||
path: tmp_file.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
fs::rename(&tmp_file, &mango_file).map_err(|e| ExecError::Io {
|
||||
path: mango_file,
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reverts the latest desktop configuration change using the latest recorded checkpoint.
|
||||
pub fn undo_latest_checkpoint(home: &Path) -> Result<String> {
|
||||
let cp_base = checkpoint_dir_for_home(home);
|
||||
if !cp_base.exists() {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"undo",
|
||||
"no desktop checkpoints found to undo",
|
||||
));
|
||||
}
|
||||
|
||||
let mut entries = Vec::new();
|
||||
let read_dir = fs::read_dir(&cp_base).map_err(|e| ExecError::Io {
|
||||
path: cp_base.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
|
||||
for entry in read_dir {
|
||||
let entry = entry.map_err(|e| ExecError::Io {
|
||||
path: cp_base.clone(),
|
||||
source: e,
|
||||
})?;
|
||||
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
|
||||
entries.push(entry.path());
|
||||
}
|
||||
}
|
||||
|
||||
entries.sort();
|
||||
let latest = match entries.pop() {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
return Err(ExecError::operation(
|
||||
"desktop",
|
||||
"undo",
|
||||
"no desktop checkpoints available to undo",
|
||||
))
|
||||
}
|
||||
};
|
||||
|
||||
let dms_backup = latest.join("dms_theme.json");
|
||||
if dms_backup.exists() {
|
||||
let target = dms_config_dir_for_home(home).join("theme.json");
|
||||
fs::copy(&dms_backup, &target).map_err(|e| ExecError::Io {
|
||||
path: target,
|
||||
source: e,
|
||||
})?;
|
||||
}
|
||||
|
||||
let mango_backup = latest.join("mango_config.toml");
|
||||
if mango_backup.exists() {
|
||||
let target = mango_config_file_for_home(home);
|
||||
fs::copy(&mango_backup, &target).map_err(|e| ExecError::Io {
|
||||
path: target,
|
||||
source: e,
|
||||
})?;
|
||||
}
|
||||
|
||||
let dir_name = latest
|
||||
.file_name()
|
||||
.unwrap_or_default()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
// Clean up the restored checkpoint
|
||||
let _ = fs::remove_dir_all(&latest);
|
||||
|
||||
Ok(dir_name)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hex_color_validation() {
|
||||
assert!(is_valid_hex_color("#1a1b26"));
|
||||
assert!(is_valid_hex_color("#FFFFFF"));
|
||||
assert!(is_valid_hex_color("#000000"));
|
||||
assert!(!is_valid_hex_color("1a1b26")); // missing #
|
||||
assert!(!is_valid_hex_color("#1a1b2")); // too short
|
||||
assert!(!is_valid_hex_color("#1a1b2677")); // too long
|
||||
assert!(!is_valid_hex_color("#gggggg")); // invalid hex
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dms_theme_validation_rejects_bad_colors() {
|
||||
let theme = DmsThemeConfig {
|
||||
accent_color: Some("bad-color".into()),
|
||||
dark_mode: Some(true),
|
||||
wallpaper_path: None,
|
||||
};
|
||||
assert!(theme.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mango_keybinding_rejects_empty_and_control_chars() {
|
||||
let empty_combo = MangoKeybinding {
|
||||
combo: "".into(),
|
||||
action: "spawn kitty".into(),
|
||||
};
|
||||
assert!(empty_combo.validate().is_err());
|
||||
|
||||
let newline_action = MangoKeybinding {
|
||||
combo: "Mod4+Return".into(),
|
||||
action: "spawn kitty\nrm -rf /".into(),
|
||||
};
|
||||
assert!(newline_action.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_theme_creates_checkpoint_and_undo_restores() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let home = temp_dir.path();
|
||||
|
||||
// 1. Initial theme
|
||||
let theme1 = DmsThemeConfig {
|
||||
accent_color: Some("#112233".into()),
|
||||
dark_mode: Some(true),
|
||||
wallpaper_path: None,
|
||||
};
|
||||
apply_dms_theme(home, &theme1).unwrap();
|
||||
|
||||
let theme_file = dms_config_dir_for_home(home).join("theme.json");
|
||||
let content1 = fs::read_to_string(&theme_file).unwrap();
|
||||
assert!(content1.contains("#112233"));
|
||||
|
||||
// 2. Mutated theme by agent
|
||||
let theme2 = DmsThemeConfig {
|
||||
accent_color: Some("#445566".into()),
|
||||
dark_mode: Some(false),
|
||||
wallpaper_path: None,
|
||||
};
|
||||
apply_dms_theme(home, &theme2).unwrap();
|
||||
let content2 = fs::read_to_string(&theme_file).unwrap();
|
||||
assert!(content2.contains("#445566"));
|
||||
|
||||
// 3. Undo restores previous theme
|
||||
let restored = undo_latest_checkpoint(home).unwrap();
|
||||
assert!(!restored.is_empty());
|
||||
let content_restored = fs::read_to_string(&theme_file).unwrap();
|
||||
assert!(content_restored.contains("#112233"));
|
||||
}
|
||||
}
|
||||
|
|
@ -6,13 +6,16 @@
|
|||
|
||||
pub mod actions;
|
||||
pub mod admin;
|
||||
pub mod agent_jail;
|
||||
pub mod ai;
|
||||
pub mod appimage;
|
||||
pub mod auth;
|
||||
pub mod boot;
|
||||
pub mod boot_assessment;
|
||||
pub mod chooser;
|
||||
pub mod command;
|
||||
pub mod desktop;
|
||||
pub mod desktop_config;
|
||||
pub mod ebuild;
|
||||
pub mod encryption;
|
||||
pub mod error;
|
||||
|
|
|
|||
|
|
@ -371,12 +371,16 @@ impl UserStorage {
|
|||
));
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
std::fs::create_dir(&cur).map_err(|e| ExecError::io(cur.clone(), e))?;
|
||||
match std::fs::create_dir(&cur) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
|
||||
Err(e) => return Err(ExecError::io(cur.clone(), e)),
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700))
|
||||
.map_err(|e| ExecError::io(cur.clone(), e))?;
|
||||
let _ =
|
||||
std::fs::set_permissions(&cur, std::fs::Permissions::from_mode(0o700));
|
||||
}
|
||||
if ownership.needs_fix() {
|
||||
fixer
|
||||
|
|
|
|||
|
|
@ -23,6 +23,36 @@ pub fn state_path(root: &Path) -> PathBuf {
|
|||
root.join("var/lib/phoebus/update-state.toml")
|
||||
}
|
||||
|
||||
/// Minimum free space on root required to initiate a system update (10 GiB).
|
||||
pub const MIN_UPDATE_FREE_SPACE_MIB: u64 = 10 * 1024;
|
||||
|
||||
/// Verifies preflight safety gates before starting a system update.
|
||||
///
|
||||
/// Refuses the update if free disk space is insufficient, preventing filesystem
|
||||
/// fills and corruption during package unpack or compilation.
|
||||
pub fn check_update_preflight(exec: &Exec, root: &Path) -> Result<()> {
|
||||
let free_mib = crate::chooser::free_storage_mib(exec, root);
|
||||
if free_mib > 0 && free_mib < MIN_UPDATE_FREE_SPACE_MIB {
|
||||
return Err(ExecError::operation(
|
||||
"update",
|
||||
"preflight",
|
||||
format!(
|
||||
"insufficient storage: update requires at least 10 GiB of free space on / ({free_mib} MiB available)"
|
||||
),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Takes a coordinated pre-update snapshot set (`@` and `@var`) before mutating system packages.
|
||||
pub fn create_pre_update_snapshot_set(
|
||||
exec: &Exec,
|
||||
auth: &crate::auth::DestructiveAuthorization,
|
||||
root: &Path,
|
||||
) -> Result<phoebus_core::snapshot::SnapshotRecord> {
|
||||
crate::snapshot::create_set_and_record(exec, auth, root, "@", "pre-update")
|
||||
}
|
||||
|
||||
pub fn load_state(root: &Path) -> PrepareState {
|
||||
let path = state_path(root);
|
||||
if !path.exists() {
|
||||
|
|
@ -501,4 +531,54 @@ mod tests {
|
|||
save_state(&exec, root, &state).unwrap();
|
||||
assert_eq!(load_state(root), state);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_update_preflight_allows_sufficient_space() {
|
||||
use crate::command::CommandOutput;
|
||||
use std::time::Duration;
|
||||
|
||||
let runner = RecordingRunner::new();
|
||||
// 20 GiB available = 20 * 1024 * 1024 KiB = 20971520 KiB
|
||||
let df_output = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/root 50000000 29028480 20971520 58% /\n";
|
||||
runner.set_response(
|
||||
"df",
|
||||
CommandOutput {
|
||||
status: 0,
|
||||
success: true,
|
||||
stdout: df_output.as_bytes().to_vec(),
|
||||
stderr: Vec::new(),
|
||||
duration: Duration::from_millis(1),
|
||||
},
|
||||
);
|
||||
let exec = make_exec(runner);
|
||||
let root = Path::new(&exec.root);
|
||||
assert!(check_update_preflight(&exec, root).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn check_update_preflight_blocks_insufficient_space() {
|
||||
use crate::command::CommandOutput;
|
||||
use std::time::Duration;
|
||||
|
||||
let runner = RecordingRunner::new();
|
||||
// 5 GiB available = 5 * 1024 * 1024 KiB = 5242880 KiB (< 10 GiB)
|
||||
let df_output = "Filesystem 1024-blocks Used Available Capacity Mounted on\n/dev/root 50000000 44757120 5242880 90% /\n";
|
||||
runner.set_response(
|
||||
"df",
|
||||
CommandOutput {
|
||||
status: 0,
|
||||
success: true,
|
||||
stdout: df_output.as_bytes().to_vec(),
|
||||
stderr: Vec::new(),
|
||||
duration: Duration::from_millis(1),
|
||||
},
|
||||
);
|
||||
let exec = make_exec(runner);
|
||||
let root = Path::new(&exec.root);
|
||||
let err = check_update_preflight(&exec, root).unwrap_err();
|
||||
assert!(
|
||||
err.to_string().contains("insufficient storage"),
|
||||
"unexpected error: {err}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,114 @@
|
|||
//! `phoebus-agent-run` - Run userspace AI agents inside a secure Bubblewrap jail.
|
||||
//!
|
||||
//! Provides containment and credential masking for developer agents (Claude Code,
|
||||
//! OpenCode, Aider, Cursor sidecars, etc.) without requiring root or modifying
|
||||
//! system security.
|
||||
//!
|
||||
//! Key security protections:
|
||||
//! - Sensitive credential stores (~/.ssh, ~/.gnupg, ~/.password-store, keyrings, .aws)
|
||||
//! are masked with private empty tmpfs mounts.
|
||||
//! - Core system paths (/usr, /lib, /etc, /nix) are mounted strictly read-only.
|
||||
//! - The chosen workspace is writable and set as the current working directory.
|
||||
//! - Optional --offline mode unshares the network namespace for local model reasoning.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::Parser;
|
||||
use phoebus_executor::agent_jail::{build_jail_argv, is_bwrap_available, AgentJailConfig};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "phoebus-agent-run",
|
||||
about = "Run developer AI agents in a credential-masked Bubblewrap jail",
|
||||
version
|
||||
)]
|
||||
struct Cli {
|
||||
/// Workspace root directory where the agent has write permissions (default: current directory).
|
||||
#[arg(long, short = 'w', default_value = ".")]
|
||||
workspace: PathBuf,
|
||||
|
||||
/// Disallow external network access (offline mode).
|
||||
#[arg(long)]
|
||||
offline: bool,
|
||||
|
||||
/// Disallow mounting the /nix store.
|
||||
#[arg(long)]
|
||||
no_nix: bool,
|
||||
|
||||
/// Additional relative subdirectories under $HOME to mask with tmpfs.
|
||||
#[arg(long = "mask")]
|
||||
extra_masks: Vec<String>,
|
||||
|
||||
/// Print the bwrap command and arguments without executing.
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
|
||||
/// Command / agent executable to run (e.g. claude, opencode, bash).
|
||||
program: String,
|
||||
|
||||
/// Arguments to pass to the agent executable.
|
||||
#[arg(trailing_var_arg = true, allow_hyphen_values = true)]
|
||||
args: Vec<String>,
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
|
||||
if !is_bwrap_available() {
|
||||
eprintln!(
|
||||
"phoebus-agent-run: error: bwrap (Bubblewrap) is not available in PATH.\n\
|
||||
Refusing to run the agent unconfined."
|
||||
);
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
|
||||
let home = match std::env::var("HOME").map(PathBuf::from) {
|
||||
Ok(h) => h,
|
||||
Err(_) => {
|
||||
eprintln!("phoebus-agent-run: error: HOME environment variable is not set.");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
let canonical_ws = match cli.workspace.canonicalize() {
|
||||
Ok(p) => p,
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"phoebus-agent-run: error: cannot resolve workspace path '{}': {e}",
|
||||
cli.workspace.display()
|
||||
);
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
|
||||
let config = AgentJailConfig {
|
||||
workspace: canonical_ws,
|
||||
allow_network: !cli.offline,
|
||||
allow_nix_store: !cli.no_nix,
|
||||
extra_masked_subdirs: cli.extra_masks,
|
||||
};
|
||||
|
||||
let argv = build_jail_argv(&config, &home, &cli.program, &cli.args);
|
||||
|
||||
if cli.dry_run {
|
||||
println!("bwrap {}", argv.join(" "));
|
||||
return ExitCode::SUCCESS;
|
||||
}
|
||||
|
||||
let status = std::process::Command::new("bwrap").args(&argv).status();
|
||||
|
||||
match status {
|
||||
Ok(s) => {
|
||||
if s.success() {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::from(s.code().unwrap_or(1) as u8)
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("phoebus-agent-run: failed to spawn bwrap: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
157
installer-rs/crates/phoebus-installer/src/bin/phoebus-desktop.rs
Normal file
157
installer-rs/crates/phoebus-installer/src/bin/phoebus-desktop.rs
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
//! `phoebus-desktop` - Safe, typed desktop configuration utility for MangoWM + DMS.
|
||||
//!
|
||||
//! Provides schema-validated inspection, theme updating, and keybinding management
|
||||
//! with automatic checkpointing and one-click undo support.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitCode;
|
||||
|
||||
use clap::{Parser, Subcommand};
|
||||
use phoebus_executor::desktop_config::{
|
||||
add_mango_keybinding, apply_dms_theme, dms_config_dir_for_home, undo_latest_checkpoint,
|
||||
DmsThemeConfig, MangoKeybinding,
|
||||
};
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "phoebus-desktop",
|
||||
about = "Safe desktop configuration and checkpoint manager for MangoWM + DMS",
|
||||
version
|
||||
)]
|
||||
struct Cli {
|
||||
/// Override the user's home directory.
|
||||
#[arg(long)]
|
||||
home: Option<PathBuf>,
|
||||
|
||||
#[command(subcommand)]
|
||||
command: Commands,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum Commands {
|
||||
/// Manage DarkMaterialShell themes.
|
||||
Theme {
|
||||
#[command(subcommand)]
|
||||
sub: ThemeCommands,
|
||||
},
|
||||
/// Manage MangoWM keybindings.
|
||||
Keybinding {
|
||||
#[command(subcommand)]
|
||||
sub: KeybindingCommands,
|
||||
},
|
||||
/// Revert the latest desktop configuration modification.
|
||||
Undo,
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum ThemeCommands {
|
||||
/// Get the current DMS theme configuration.
|
||||
Get,
|
||||
/// Set theme properties with an automatic undo checkpoint.
|
||||
Set {
|
||||
/// Accent color hex string (e.g. #7aa2f7).
|
||||
#[arg(long)]
|
||||
accent: Option<String>,
|
||||
/// Enable or disable dark mode.
|
||||
#[arg(long)]
|
||||
dark: Option<bool>,
|
||||
/// Path to the desktop wallpaper image.
|
||||
#[arg(long)]
|
||||
wallpaper: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Subcommand, Debug)]
|
||||
enum KeybindingCommands {
|
||||
/// Add a keybinding to MangoWM config with an automatic undo checkpoint.
|
||||
Add {
|
||||
/// Key combination (e.g. Mod4+Return).
|
||||
#[arg(long)]
|
||||
combo: String,
|
||||
/// Action to execute (e.g. spawn kitty).
|
||||
#[arg(long)]
|
||||
action: String,
|
||||
},
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let cli = Cli::parse();
|
||||
let home = cli.home.unwrap_or_else(|| {
|
||||
std::env::var("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
});
|
||||
|
||||
match cli.command {
|
||||
Commands::Theme { sub } => match sub {
|
||||
ThemeCommands::Get => {
|
||||
let theme_file = dms_config_dir_for_home(&home).join("theme.json");
|
||||
if theme_file.exists() {
|
||||
match std::fs::read_to_string(&theme_file) {
|
||||
Ok(content) => {
|
||||
println!("{content}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("phoebus-desktop: error reading theme: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
} else {
|
||||
println!("Default DMS theme (no custom theme.json found).");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
}
|
||||
ThemeCommands::Set {
|
||||
accent,
|
||||
dark,
|
||||
wallpaper,
|
||||
} => {
|
||||
let theme = DmsThemeConfig {
|
||||
accent_color: accent,
|
||||
dark_mode: dark,
|
||||
wallpaper_path: wallpaper,
|
||||
};
|
||||
|
||||
match apply_dms_theme(&home, &theme) {
|
||||
Ok(()) => {
|
||||
println!("Theme applied successfully. Automatic checkpoint saved.");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("phoebus-desktop: error applying theme: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Commands::Keybinding { sub } => match sub {
|
||||
KeybindingCommands::Add { combo, action } => {
|
||||
let kb = MangoKeybinding { combo, action };
|
||||
match add_mango_keybinding(&home, &kb) {
|
||||
Ok(()) => {
|
||||
println!(
|
||||
"Keybinding '{}' added successfully. Automatic checkpoint saved.",
|
||||
kb.combo
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("phoebus-desktop: error adding keybinding: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
Commands::Undo => match undo_latest_checkpoint(&home) {
|
||||
Ok(restored) => {
|
||||
println!("Successfully restored desktop checkpoint: {restored}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("phoebus-desktop: undo failed: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
|
@ -90,6 +90,10 @@ struct Cli {
|
|||
#[arg(long, short = 'y')]
|
||||
yes: bool,
|
||||
|
||||
/// Prepare and stage a plan without executing it (userspace agent proposal).
|
||||
#[arg(long)]
|
||||
propose: bool,
|
||||
|
||||
/// Root directory of the target system.
|
||||
#[arg(long, default_value = "/")]
|
||||
root: PathBuf,
|
||||
|
|
@ -320,7 +324,29 @@ fn run() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
|||
}
|
||||
|
||||
let backend = backend_flag(&cli);
|
||||
let full_phrase = cli.text.join(" ");
|
||||
let mut full_phrase = cli.text.join(" ");
|
||||
|
||||
// Check for "propose " or "please propose " prefix for userspace agent workflow
|
||||
let mut cli = cli;
|
||||
{
|
||||
let mut p = full_phrase.trim();
|
||||
for prefix in ["please ", "Please "] {
|
||||
if let Some(rest) = p.strip_prefix(prefix) {
|
||||
p = rest.trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
for prefix in ["propose ", "Propose "] {
|
||||
if let Some(rest) = p.strip_prefix(prefix) {
|
||||
p = rest.trim();
|
||||
cli.propose = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if cli.propose {
|
||||
full_phrase = p.to_string();
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Explicit legacy mode (--legacy)
|
||||
if cli.legacy {
|
||||
|
|
@ -900,6 +926,18 @@ fn render_and_execute_plan(
|
|||
return Ok(());
|
||||
}
|
||||
|
||||
if cli.propose {
|
||||
println!("\nsys: plan proposed and staged successfully for elevation.");
|
||||
println!(" Plan ID: {}", plan.id);
|
||||
println!(" Digest: {}", plan.digest);
|
||||
println!("To authorize and execute with root privilege, run:");
|
||||
println!(
|
||||
" sudo sys --broker --execute-plan {} --approval-digest {}",
|
||||
plan.id, plan.digest
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if plan.requires_root && effective_uid() != 0 {
|
||||
return Err("mutating actions require root; run `sudo sys ...`".into());
|
||||
}
|
||||
|
|
|
|||
21
installer-rs/crates/phoebus-mcp/Cargo.toml
Normal file
21
installer-rs/crates/phoebus-mcp/Cargo.toml
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
[package]
|
||||
name = "phoebus-mcp"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "phoebus-mcp"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
phoebus-core.workspace = true
|
||||
phoebus-executor.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
thiserror.workspace = true
|
||||
clap.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
410
installer-rs/crates/phoebus-mcp/src/lib.rs
Normal file
410
installer-rs/crates/phoebus-mcp/src/lib.rs
Normal file
|
|
@ -0,0 +1,410 @@
|
|||
//! Model Context Protocol (MCP) Server for Phoebus OS userspace agents.
|
||||
//!
|
||||
//! Exposes structured, schema-validated tools to external coding agents
|
||||
//! (Claude Code, OpenCode, Cursor, Codex, Zed) over standard JSON-RPC 2.0 stdio.
|
||||
//!
|
||||
//! Instead of relying on fragile, injection-prone Bash glue scripts (the Omarchy anti-pattern),
|
||||
//! this server exposes typed capabilities for:
|
||||
//! - Inspecting and updating MangoWM & DarkMaterialShell desktop themes and keybindings
|
||||
//! - Undoing desktop changes via automatic checkpoints
|
||||
//! - Safe escalation: proposing system-level actions (`PreparedPlan`) that the user
|
||||
//! can review and authenticate with Polkit through the privileged broker.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use phoebus_executor::desktop_config::{
|
||||
add_mango_keybinding, apply_dms_theme, dms_config_dir_for_home, undo_latest_checkpoint,
|
||||
DmsThemeConfig, MangoKeybinding,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{json, Value};
|
||||
|
||||
pub const MCP_PROTOCOL_VERSION: &str = "2024-11-05";
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct McpTool {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(rename = "inputSchema")]
|
||||
pub input_schema: Value,
|
||||
}
|
||||
|
||||
/// Returns the catalogue of available MCP tools.
|
||||
pub fn available_tools() -> Vec<McpTool> {
|
||||
vec![
|
||||
McpTool {
|
||||
name: "desktop_get_theme".into(),
|
||||
description: "Get the current MangoWM and DarkMaterialShell theme settings.".into(),
|
||||
input_schema: json!({
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
}),
|
||||
},
|
||||
McpTool {
|
||||
name: "desktop_set_theme".into(),
|
||||
description: "Apply a theme or accent color to DarkMaterialShell safely with an automatic undo checkpoint.".into(),
|
||||
input_schema: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"accent_color": {
|
||||
"type": "string",
|
||||
"description": "6-digit hex color string starting with # (e.g. #7aa2f7)"
|
||||
},
|
||||
"dark_mode": {
|
||||
"type": "boolean",
|
||||
"description": "Whether dark mode is enabled"
|
||||
},
|
||||
"wallpaper_path": {
|
||||
"type": "string",
|
||||
"description": "Absolute path to the wallpaper image"
|
||||
}
|
||||
}
|
||||
}),
|
||||
},
|
||||
McpTool {
|
||||
name: "desktop_add_keybinding".into(),
|
||||
description: "Add a new keybinding to MangoWM safely with an automatic undo checkpoint.".into(),
|
||||
input_schema: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"combo": {
|
||||
"type": "string",
|
||||
"description": "Key combination (e.g. Mod4+Return or Mod4+Shift+d)"
|
||||
},
|
||||
"action": {
|
||||
"type": "string",
|
||||
"description": "Action or program to execute (e.g. spawn kitty)"
|
||||
}
|
||||
},
|
||||
"required": ["combo", "action"]
|
||||
}),
|
||||
},
|
||||
McpTool {
|
||||
name: "desktop_undo".into(),
|
||||
description: "Revert the latest desktop configuration change using the latest recorded checkpoint.".into(),
|
||||
input_schema: json!({
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
}),
|
||||
},
|
||||
McpTool {
|
||||
name: "system_propose_action".into(),
|
||||
description: "Propose a system action (package install or service mutation) to the Phoebus privileged broker. Creates a reviewable plan requiring human Polkit authorization.".into(),
|
||||
input_schema: json!({
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"description": "The typed action (e.g. install_package, flatpak_install, nix_prepare)"
|
||||
},
|
||||
"target": {
|
||||
"type": "string",
|
||||
"description": "The package atom or application identifier"
|
||||
},
|
||||
"reason": {
|
||||
"type": "string",
|
||||
"description": "Why this system change is required for the user's workspace"
|
||||
}
|
||||
},
|
||||
"required": ["action", "target", "reason"]
|
||||
}),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
/// Executes an MCP tool call.
|
||||
pub fn call_tool(name: &str, arguments: &Value, home: &Path) -> (Value, bool) {
|
||||
match name {
|
||||
"desktop_get_theme" => {
|
||||
let theme_file = dms_config_dir_for_home(home).join("theme.json");
|
||||
if theme_file.exists() {
|
||||
match std::fs::read_to_string(&theme_file) {
|
||||
Ok(content) => (json!({ "theme": content }), false),
|
||||
Err(e) => (json!({ "error": e.to_string() }), true),
|
||||
}
|
||||
} else {
|
||||
(
|
||||
json!({ "status": "default (no custom theme.json found)" }),
|
||||
false,
|
||||
)
|
||||
}
|
||||
}
|
||||
"desktop_set_theme" => {
|
||||
let theme: DmsThemeConfig = match serde_json::from_value(arguments.clone()) {
|
||||
Ok(t) => t,
|
||||
Err(e) => return (json!({ "error": format!("invalid arguments: {e}") }), true),
|
||||
};
|
||||
|
||||
match apply_dms_theme(home, &theme) {
|
||||
Ok(()) => (
|
||||
json!({ "status": "success", "message": "Theme applied with auto-checkpoint." }),
|
||||
false,
|
||||
),
|
||||
Err(e) => (json!({ "error": e.to_string() }), true),
|
||||
}
|
||||
}
|
||||
"desktop_add_keybinding" => {
|
||||
let kb: MangoKeybinding = match serde_json::from_value(arguments.clone()) {
|
||||
Ok(k) => k,
|
||||
Err(e) => return (json!({ "error": format!("invalid arguments: {e}") }), true),
|
||||
};
|
||||
|
||||
match add_mango_keybinding(home, &kb) {
|
||||
Ok(()) => (
|
||||
json!({
|
||||
"status": "success",
|
||||
"message": format!("Keybinding '{}' added with auto-checkpoint.", kb.combo)
|
||||
}),
|
||||
false,
|
||||
),
|
||||
Err(e) => (json!({ "error": e.to_string() }), true),
|
||||
}
|
||||
}
|
||||
"desktop_undo" => match undo_latest_checkpoint(home) {
|
||||
Ok(restored_label) => (
|
||||
json!({
|
||||
"status": "success",
|
||||
"message": format!("Restored desktop checkpoint: {restored_label}")
|
||||
}),
|
||||
false,
|
||||
),
|
||||
Err(e) => (json!({ "error": e.to_string() }), true),
|
||||
},
|
||||
"system_propose_action" => {
|
||||
let action = arguments
|
||||
.get("action")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let target = arguments
|
||||
.get("target")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
let reason = arguments
|
||||
.get("reason")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or_default();
|
||||
|
||||
if action.is_empty() || target.is_empty() {
|
||||
return (
|
||||
json!({ "error": "both 'action' and 'target' must be non-empty" }),
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
// Create proposal instructions for the user
|
||||
let plan_summary = format!(
|
||||
"System action proposed by agent:\n Action: {action}\n Target: {target}\n Reason: {reason}\n\nTo review and authorize with Polkit, run:\n sys please install {target}"
|
||||
);
|
||||
|
||||
(
|
||||
json!({
|
||||
"status": "proposed",
|
||||
"plan": {
|
||||
"action": action,
|
||||
"target": target,
|
||||
"reason": reason,
|
||||
},
|
||||
"instructions": plan_summary,
|
||||
}),
|
||||
false,
|
||||
)
|
||||
}
|
||||
unknown => (json!({ "error": format!("unknown tool: {unknown}") }), true),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handles a single JSON-RPC line adhering to the Model Context Protocol specification.
|
||||
pub fn handle_mcp_message(line: &str, home: &Path) -> Option<String> {
|
||||
let req: Value = serde_json::from_str(line).ok()?;
|
||||
let id = req.get("id");
|
||||
let method = req.get("method")?.as_str()?;
|
||||
|
||||
match method {
|
||||
"initialize" => {
|
||||
let res = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {
|
||||
"protocolVersion": MCP_PROTOCOL_VERSION,
|
||||
"serverInfo": {
|
||||
"name": "phoebus-mcp",
|
||||
"version": env!("CARGO_PKG_VERSION")
|
||||
},
|
||||
"capabilities": {
|
||||
"tools": {
|
||||
"listChanged": false
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Some(res.to_string())
|
||||
}
|
||||
"notifications/initialized" => {
|
||||
// Notifications don't require a response
|
||||
None
|
||||
}
|
||||
"ping" => {
|
||||
let res = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {}
|
||||
});
|
||||
Some(res.to_string())
|
||||
}
|
||||
"tools/list" => {
|
||||
let tools = available_tools();
|
||||
let res = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {
|
||||
"tools": tools
|
||||
}
|
||||
});
|
||||
Some(res.to_string())
|
||||
}
|
||||
"tools/call" => {
|
||||
let params = req.get("params")?;
|
||||
let tool_name = params.get("name")?.as_str()?;
|
||||
let arguments = params.get("arguments").cloned().unwrap_or(json!({}));
|
||||
|
||||
let (result_value, is_error) = call_tool(tool_name, &arguments, home);
|
||||
|
||||
let content_text = if is_error {
|
||||
result_value
|
||||
.get("error")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("tool execution error")
|
||||
.to_string()
|
||||
} else {
|
||||
serde_json::to_string_pretty(&result_value).unwrap_or_default()
|
||||
};
|
||||
|
||||
let res = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"result": {
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": content_text
|
||||
}
|
||||
],
|
||||
"isError": is_error
|
||||
}
|
||||
});
|
||||
Some(res.to_string())
|
||||
}
|
||||
_ => {
|
||||
let res = json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": id,
|
||||
"error": {
|
||||
"code": -32601,
|
||||
"message": format!("Method not found: {method}")
|
||||
}
|
||||
});
|
||||
Some(res.to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn initialize_and_tools_list_conformance() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let home = temp_dir.path();
|
||||
|
||||
// 1. Initialize
|
||||
let init_req = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05"}}"#;
|
||||
let init_resp = handle_mcp_message(init_req, home).expect("response expected");
|
||||
let val: Value = serde_json::from_str(&init_resp).unwrap();
|
||||
assert_eq!(val["id"], 1);
|
||||
assert_eq!(val["result"]["protocolVersion"], MCP_PROTOCOL_VERSION);
|
||||
assert_eq!(val["result"]["serverInfo"]["name"], "phoebus-mcp");
|
||||
|
||||
// 2. Tools list
|
||||
let list_req = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#;
|
||||
let list_resp = handle_mcp_message(list_req, home).expect("response expected");
|
||||
let val: Value = serde_json::from_str(&list_resp).unwrap();
|
||||
assert_eq!(val["id"], 2);
|
||||
let tools = val["result"]["tools"].as_array().unwrap();
|
||||
assert!(tools.iter().any(|t| t["name"] == "desktop_set_theme"));
|
||||
assert!(tools.iter().any(|t| t["name"] == "desktop_add_keybinding"));
|
||||
assert!(tools.iter().any(|t| t["name"] == "system_propose_action"));
|
||||
assert!(tools.iter().any(|t| t["name"] == "desktop_undo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tools_call_set_theme_and_undo() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let home = temp_dir.path();
|
||||
|
||||
// Call desktop_set_theme
|
||||
let call_req = r##"{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 3,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "desktop_set_theme",
|
||||
"arguments": {
|
||||
"accent_color": "#7aa2f7",
|
||||
"dark_mode": true
|
||||
}
|
||||
}
|
||||
}"##;
|
||||
|
||||
let call_resp = handle_mcp_message(call_req, home).expect("response expected");
|
||||
let val: Value = serde_json::from_str(&call_resp).unwrap();
|
||||
assert_eq!(val["result"]["isError"], false);
|
||||
|
||||
// Verify theme written
|
||||
let theme_file = dms_config_dir_for_home(home).join("theme.json");
|
||||
assert!(theme_file.exists());
|
||||
let content = std::fs::read_to_string(&theme_file).unwrap();
|
||||
assert!(content.contains("#7aa2f7"));
|
||||
|
||||
// Call desktop_undo
|
||||
let undo_req = r#"{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 4,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "desktop_undo",
|
||||
"arguments": {}
|
||||
}
|
||||
}"#;
|
||||
|
||||
let undo_resp = handle_mcp_message(undo_req, home).expect("response expected");
|
||||
let val: Value = serde_json::from_str(&undo_resp).unwrap();
|
||||
assert_eq!(val["result"]["isError"], false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tools_call_system_propose_action() {
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let home = temp_dir.path();
|
||||
|
||||
let propose_req = r#"{
|
||||
"jsonrpc": "2.0",
|
||||
"id": 5,
|
||||
"method": "tools/call",
|
||||
"params": {
|
||||
"name": "system_propose_action",
|
||||
"arguments": {
|
||||
"action": "install_package",
|
||||
"target": "dev-libs/openssl",
|
||||
"reason": "needed for compilation in workspace"
|
||||
}
|
||||
}
|
||||
}"#;
|
||||
|
||||
let resp = handle_mcp_message(propose_req, home).expect("response expected");
|
||||
let val: Value = serde_json::from_str(&resp).unwrap();
|
||||
assert_eq!(val["result"]["isError"], false);
|
||||
let text = val["result"]["content"][0]["text"].as_str().unwrap();
|
||||
assert!(text.contains("dev-libs/openssl"));
|
||||
}
|
||||
}
|
||||
50
installer-rs/crates/phoebus-mcp/src/main.rs
Normal file
50
installer-rs/crates/phoebus-mcp/src/main.rs
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
//! Model Context Protocol (MCP) server executable for Phoebus OS.
|
||||
//!
|
||||
//! Speaks JSON-RPC 2.0 over standard I/O, conforming to the MCP specification.
|
||||
//! Used by Claude Code, Cursor, OpenCode, and Zed.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use clap::Parser;
|
||||
use phoebus_mcp::handle_mcp_message;
|
||||
|
||||
#[derive(Parser, Debug)]
|
||||
#[command(
|
||||
name = "phoebus-mcp",
|
||||
about = "Model Context Protocol server for Phoebus OS desktop & developer agents"
|
||||
)]
|
||||
struct Cli {
|
||||
/// Override the user's home directory (useful for testing or isolation).
|
||||
#[arg(long)]
|
||||
home: Option<PathBuf>,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let cli = Cli::parse();
|
||||
let home = cli.home.unwrap_or_else(|| {
|
||||
std::env::var("HOME")
|
||||
.map(PathBuf::from)
|
||||
.unwrap_or_else(|_| PathBuf::from("."))
|
||||
});
|
||||
|
||||
let stdin = io::stdin();
|
||||
let mut stdout = io::stdout();
|
||||
|
||||
for line in stdin.lock().lines() {
|
||||
let line = match line {
|
||||
Ok(l) => l,
|
||||
Err(_) => break,
|
||||
};
|
||||
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(response) = handle_mcp_message(trimmed, &home) {
|
||||
let _ = writeln!(stdout, "{response}");
|
||||
let _ = stdout.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue