use std::collections::BTreeMap;
use std::fmt;
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use adk_core::AdkError;
use adk_server::auth_bridge::RequestContextExtractor;
use axum::Json;
use axum::Router;
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use serde::{Deserialize, Serialize};
use crate::error::{KernelError, Result};
use crate::kernel::Kernel;
mod agents;
pub mod api;
#[cfg(feature = "proc")]
mod away;
mod client;
mod commands;
mod decide;
mod memory;
mod pairing;
#[cfg(windows)]
mod pipe;
mod record;
mod routes;
mod server;
pub(crate) mod settings;
#[cfg(unix)]
mod socket;
mod store;
#[cfg(test)]
mod tests;
pub use crate::error::{DECIDE_NOT_HERE_CODE, RESUME_NOT_HERE_CODE};
pub use client::ControlClient;
pub use commands::{
AlwaysAllowResponse, CommandCall, CommandHost, CommandInfo, CommandReach, CommandsResponse,
RunCommandRequest, RunCommandResponse, SessionModeResponse, SurfaceRecord,
};
pub use memory::{FactOrigin, MemoryBook, RememberedFact, TidyUp, TidyUpUndo};
#[cfg(feature = "channels")]
pub(crate) use pairing::rated_high;
pub use record::{RecordBook, RecordCheck, RecordLine};
pub use server::ControlPlane;
pub(crate) use store::LastRead;
#[cfg(feature = "postgres")]
pub use store::PostgresControlStore;
#[cfg(feature = "redis")]
pub use store::RedisControlStore;
#[cfg(feature = "sqlite")]
pub use store::SqliteControlStore;
pub use store::{AreaSettings, AreaStart, AwayCursor, Change, ControlStore, InMemoryControlStore};
pub mod paths {
pub const API_PREFIX: &str = "/api";
pub const HEALTH: &str = "/kernel/health";
pub const INVENTORY: &str = "/kernel/inventory";
pub const PROCESSES: &str = "/kernel/processes";
pub const KILL: &str = "/kernel/processes/{pid}/kill";
pub const NICE: &str = "/kernel/processes/{pid}/nice";
pub const SUSPEND: &str = "/kernel/processes/{pid}/suspend";
pub const RESUME: &str = "/kernel/processes/{pid}/resume";
pub const RUN_NOW: &str = "/kernel/processes/{pid}/run-now";
pub const TRIGGER_RUN_NOW: &str = "/kernel/triggers/{name}/run-now";
pub const EVENTS: &str = "/kernel/events";
pub const ATTACH: &str = "/kernel/attach/{session}";
pub const FREEZE: &str = "/kernel/freeze";
pub const UNFREEZE: &str = "/kernel/unfreeze";
pub const AGENDA: &str = "/kernel/agenda";
pub const AGENDA_APPROVE: &str = "/kernel/agenda/{id}/approve";
pub const AGENDA_REJECT: &str = "/kernel/agenda/{id}/reject";
pub const AGENDA_SCHEDULE: &str = "/kernel/agenda/{id}/schedule";
pub const DRIVERS: &str = "/kernel/drivers";
pub const DRIVER_MOUNT: &str = "/kernel/drivers/{id}/mount";
pub const DRIVER_UNMOUNT: &str = "/kernel/drivers/{id}/unmount";
pub const DRIVER_RESTART: &str = "/kernel/drivers/{id}/restart";
pub const DRIVER_REAPPROVE: &str = "/kernel/drivers/{id}/reapprove";
pub const PROC_LEDGER: &str = "/kernel/proc/ledger";
pub const PROC_BASELINES: &str = "/kernel/proc/baselines";
pub const PROC_OBSERVATIONS: &str = "/kernel/proc/observations";
pub const PAIRING: &str = "/kernel/pairing";
pub const PAIRING_CLAIM: &str = "/kernel/pairing/claim";
pub const DEVICES: &str = "/kernel/devices";
pub const DEVICE_REVOKE: &str = "/kernel/devices/{id}/revoke";
pub const CHANNELS: &str = "/kernel/channels";
pub const CHANNEL_PAIR: &str = "/kernel/channels/pair";
pub const CHANNEL_REVOKE: &str = "/kernel/channels/{id}/revoke";
pub const CHANNEL_DISMISS: &str = "/kernel/channels/waiting/{id}/dismiss";
pub const AGENTS: &str = "/kernel/agents";
pub const AGENT: &str = "/kernel/agents/{id}";
pub const PARTITIONS: &str = "/kernel/partitions";
pub const PARTITION_MODE: &str = "/kernel/partitions/{id}/mode";
pub const SETTINGS: &str = "/kernel/settings";
pub const AREA_SETTINGS: &str = "/kernel/settings/{partition}";
pub const QUIET_TIME: &str = "/kernel/settings/{partition}/quiet-time";
pub const SPENDING_LIMIT: &str = "/kernel/settings/{partition}/spending-limit";
pub const AREA_MODE: &str = "/kernel/settings/{partition}/mode";
pub const AWAY: &str = "/kernel/away";
pub const AWAY_SEEN: &str = "/kernel/away/seen";
pub const AWAY_LINE: &str = "/kernel/away/lines/{seq}";
pub const MEMORY: &str = "/kernel/memory";
pub const FACT_CONFIRM: &str = "/kernel/memory/facts/{id}/confirm";
pub const FACT_FIX: &str = "/kernel/memory/facts/{id}/fix";
pub const FACT_FORGET: &str = "/kernel/memory/facts/{id}/forget";
pub const MEMORY_UNDO: &str = "/kernel/memory/undo";
pub const RECORD: &str = "/kernel/record";
pub const RECORD_CHECK: &str = "/kernel/record/check";
pub const COMMANDS: &str = "/kernel/commands";
pub const COMMAND_RUN: &str = "/kernel/commands/run";
pub const ALWAYS_ALLOW: &str = "/kernel/rules/always-allow/{id}";
pub const ALWAYS_ALLOW_PREPARE: &str = "/kernel/rules/always-allow/{id}/prepare";
pub const ALWAYS_ALLOW_GRANT: &str = "/kernel/rules/always-allow/{id}/grant";
pub const SESSION_MODE: &str = "/kernel/sessions/{session}/mode";
pub const SURFACE_RECORDS: &str = "/kernel/surface/records";
pub const SESSION_STEER: &str = "/kernel/sessions/{session}/steer";
}
#[derive(Clone)]
#[non_exhaustive]
pub struct ControlPlaneConfig {
pub socket: Option<PathBuf>,
pub http: Option<SocketAddr>,
pub extractor: Option<Arc<dyn RequestContextExtractor>>,
pub pairing: Option<crate::pairing::Pairing>,
pub control_store: Arc<dyn ControlStore>,
pub memory: Option<Arc<dyn MemoryBook>>,
pub record: Option<Arc<dyn RecordBook>>,
pub commands: Option<Arc<dyn CommandHost>>,
pub start_modes: BTreeMap<crate::partition::PartitionId, crate::partition::PartitionMode>,
pub refused_modes: Vec<(crate::partition::PartitionMode, String)>,
default_control_store: Arc<dyn ControlStore>,
}
impl ControlPlaneConfig {
pub const DEFAULT_SOCKET: &'static str = "kernel.sock";
#[must_use]
pub fn with_socket(mut self, path: impl Into<PathBuf>) -> Self {
self.socket = Some(path.into());
self
}
#[must_use]
pub fn without_socket(mut self) -> Self {
self.socket = None;
self
}
#[must_use]
pub fn with_http(mut self, addr: SocketAddr) -> Self {
self.http = Some(addr);
self
}
#[must_use]
pub fn with_extractor(mut self, extractor: Arc<dyn RequestContextExtractor>) -> Self {
self.extractor = Some(extractor);
self
}
#[must_use]
pub fn with_pairing(mut self, pairing: crate::pairing::Pairing) -> Self {
self.pairing = Some(pairing);
self
}
#[must_use]
pub fn with_control_store(mut self, store: Arc<dyn ControlStore>) -> Self {
self.control_store = store;
self
}
#[must_use]
pub fn with_memory(mut self, book: Arc<dyn MemoryBook>) -> Self {
self.memory = Some(book);
self
}
#[must_use]
pub fn with_record(mut self, book: Arc<dyn RecordBook>) -> Self {
self.record = Some(book);
self
}
#[must_use]
pub fn with_commands(mut self, host: Arc<dyn CommandHost>) -> Self {
self.commands = Some(host);
self
}
#[must_use]
pub fn with_start_mode(
mut self,
partition: impl Into<crate::partition::PartitionId>,
mode: crate::partition::PartitionMode,
) -> Self {
self.start_modes.insert(partition.into(), mode);
self
}
#[must_use]
pub fn with_refused_mode(
mut self,
mode: crate::partition::PartitionMode,
reason: impl Into<String>,
) -> Self {
self.refused_modes.push((mode, reason.into()));
self
}
pub fn has_default_control_store(&self) -> bool {
std::ptr::addr_eq(
Arc::as_ptr(&self.control_store),
Arc::as_ptr(&self.default_control_store),
)
}
pub fn refused_mode(&self, mode: crate::partition::PartitionMode) -> Option<&str> {
self.refused_modes
.iter()
.find(|(refused, _)| *refused == mode)
.map(|(_, reason)| reason.as_str())
}
pub fn socket_path(&self, home: &Path) -> Option<PathBuf> {
let path = home.join(self.socket.as_ref()?);
#[cfg(unix)]
let path = socket::place(path);
Some(path)
}
pub fn pipe_name(&self, home: &Path) -> Option<String> {
let socket = home.join(self.socket.as_ref()?);
Some(format!(r"\\.\pipe\adk-rust-kernel-{}", crate::path_tag(&socket)))
}
pub fn validate(&self) -> Result<()> {
match self.http {
Some(addr) if !addr.ip().is_loopback() && self.extractor.is_none() => {
Err(KernelError::Config {
reason: format!(
"serving the control plane on {addr} needs authentication: pass a \
bearer token or SSO extractor, or bind 127.0.0.1"
),
})
}
_ => Ok(()),
}
}
}
impl Default for ControlPlaneConfig {
fn default() -> Self {
let control_store: Arc<dyn ControlStore> = Arc::new(InMemoryControlStore::new());
Self {
socket: Some(PathBuf::from(Self::DEFAULT_SOCKET)),
http: None,
extractor: None,
pairing: None,
default_control_store: Arc::clone(&control_store),
control_store,
memory: None,
record: None,
commands: None,
start_modes: BTreeMap::new(),
refused_modes: Vec::new(),
}
}
}
impl fmt::Debug for ControlPlaneConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ControlPlaneConfig")
.field("socket", &self.socket)
.field("http", &self.http)
.field("extractor", &self.extractor.is_some())
.field("pairing", &self.pairing)
.field("memory", &self.memory.is_some())
.field("record", &self.record.is_some())
.field("commands", &self.commands.is_some())
.field("start_modes", &self.start_modes)
.field("refused_modes", &self.refused_modes)
.finish()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[non_exhaustive]
pub enum ControlTransport {
Socket,
Http,
Pipe,
}
pub fn router(kernel: Kernel) -> Router {
kernel.mark_routes_served();
routes::routes(Arc::new(kernel))
}
pub fn claim_router(kernel: Kernel) -> Router {
let backend: Arc<dyn routes::ControlBackend> = Arc::new(kernel);
match backend.pairing() {
Some(_) => pairing::claim_routes(backend),
None => Router::new(),
}
}
pub fn guard_devices(kernel: &Kernel, app: Router) -> Router {
pairing::guard(Arc::new(kernel.clone()), app)
}
pub fn decide_guard(kernel: &Kernel) -> Arc<dyn adk_server::approvals::DecideGuard> {
Arc::new(decide::KernelDecideGuard::new(Arc::new(kernel.clone())))
}
impl IntoResponse for KernelError {
fn into_response(self) -> Response {
let error = AdkError::from(self);
let status = StatusCode::from_u16(error.http_status_code())
.unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
(status, Json(error.to_problem_json())).into_response()
}
}