consciousness/src/user/mod.rs

273 lines
8.2 KiB
Rust
Raw Normal View History

2026-04-04 02:46:32 -04:00
// user/ — User interface layer
//
2026-04-04 02:46:32 -04:00
// TUI, UI channel, parsing. The cognitive layer (session state
// machine, DMN, identity) lives in mind/.
pub mod ui_channel;
pub mod event_loop;
2026-04-04 02:46:32 -04:00
pub mod chat;
pub mod context;
pub mod subconscious;
pub mod unconscious;
pub mod thalamus;
// --- TUI infrastructure (moved from tui/mod.rs) ---
use ratatui::crossterm::{
event::{EnableMouseCapture, DisableMouseCapture, KeyCode, KeyEvent, KeyModifiers},
2026-04-04 02:46:32 -04:00
terminal::{self, EnterAlternateScreen, LeaveAlternateScreen},
ExecutableCommand,
};
use ratatui::{
backend::CrosstermBackend,
};
use std::io;
use crate::user::ui_channel::{ContextInfo, SharedContextState, StatusInfo};
2026-04-04 02:46:32 -04:00
/// Build the screen legend from screen labels.
pub(crate) fn screen_legend_from(interact: &dyn ScreenView, screens: &[Box<dyn ScreenView>]) -> String {
let mut parts = vec![format!("F1={}", interact.label())];
for (i, s) in screens.iter().enumerate() {
parts.push(format!("F{}={}", i + 2, s.label()));
}
format!(" {} ", parts.join(" "))
}
// Cached legend — set once at startup by event_loop
static SCREEN_LEGEND: std::sync::OnceLock<String> = std::sync::OnceLock::new();
pub(crate) fn set_screen_legend(legend: String) {
let _ = SCREEN_LEGEND.set(legend);
}
pub(crate) fn screen_legend() -> String {
SCREEN_LEGEND.get().cloned().unwrap_or_default()
}
2026-04-04 02:46:32 -04:00
/// Action returned from a screen's tick method.
pub enum ScreenAction {
/// Switch to screen at this index
Switch(usize),
/// Send a hotkey action to the Mind
Hotkey(HotkeyAction),
}
/// A screen that can draw itself and handle input.
pub(crate) trait ScreenView: Send {
fn tick(&mut self, frame: &mut ratatui::Frame, area: ratatui::layout::Rect,
key: Option<ratatui::crossterm::event::KeyEvent>, app: &mut App) -> Option<ScreenAction>;
fn label(&self) -> &'static str;
2026-04-04 02:46:32 -04:00
}
#[derive(Debug)]
pub enum HotkeyAction {
CycleReasoning, KillProcess, Interrupt, CycleAutonomy,
/// Adjust a sampling parameter: (param_index, delta)
/// 0=temperature, 1=top_p, 2=top_k
AdjustSampling(usize, f32),
2026-04-04 02:46:32 -04:00
}
#[derive(Clone)]
pub(crate) struct IdleInfo {
pub user_present: bool,
pub since_activity: f64,
pub activity_ewma: f64,
pub block_reason: String,
pub dreaming: bool,
pub sleeping: bool,
}
#[derive(Clone)]
pub(crate) struct ChannelStatus {
pub name: String,
pub connected: bool,
pub unread: u32,
}
pub struct App {
pub(crate) status: StatusInfo,
pub(crate) activity: String,
pub running_processes: u32,
pub reasoning_effort: String,
pub temperature: f32,
pub top_p: f32,
pub top_k: u32,
2026-04-04 02:46:32 -04:00
pub(crate) active_tools: crate::user::ui_channel::SharedActiveTools,
pub should_quit: bool,
pub submitted: Vec<String>,
pub hotkey_actions: Vec<HotkeyAction>,
pub(crate) context_info: Option<ContextInfo>,
pub(crate) shared_context: SharedContextState,
pub(crate) agent_state: Vec<crate::subconscious::subconscious::AgentSnapshot>,
pub(crate) channel_status: Vec<ChannelStatus>,
pub(crate) idle_info: Option<IdleInfo>,
}
impl App {
pub fn new(model: String, shared_context: SharedContextState, active_tools: crate::user::ui_channel::SharedActiveTools) -> Self {
Self {
status: StatusInfo {
dmn_state: "resting".into(), dmn_turns: 0, dmn_max_turns: 20,
prompt_tokens: 0, completion_tokens: 0, model,
turn_tools: 0, context_budget: String::new(),
},
activity: String::new(),
running_processes: 0,
2026-04-04 02:46:32 -04:00
reasoning_effort: "none".to_string(),
temperature: 0.6,
top_p: 0.95,
top_k: 20,
active_tools,
2026-04-04 02:46:32 -04:00
should_quit: false, submitted: Vec::new(), hotkey_actions: Vec::new(),
context_info: None, shared_context,
agent_state: Vec::new(),
channel_status: Vec::new(), idle_info: None,
2026-04-04 02:46:32 -04:00
}
}
pub fn handle_global_key_old(&mut self, _key: KeyEvent) -> bool { false } // placeholder
2026-04-04 02:46:32 -04:00
/// Handle global keys only (Ctrl combos).
pub fn handle_global_key(&mut self, key: KeyEvent) -> bool {
2026-04-04 02:46:32 -04:00
if key.modifiers.contains(KeyModifiers::CONTROL) {
match key.code {
KeyCode::Char('c') => { self.should_quit = true; return true; }
KeyCode::Char('r') => { self.hotkey_actions.push(HotkeyAction::CycleReasoning); return true; }
KeyCode::Char('k') => { self.hotkey_actions.push(HotkeyAction::KillProcess); return true; }
KeyCode::Char('p') => { self.hotkey_actions.push(HotkeyAction::CycleAutonomy); return true; }
2026-04-04 02:46:32 -04:00
_ => {}
}
}
false
2026-04-04 02:46:32 -04:00
}
pub fn set_channel_status(&mut self, channels: Vec<(String, bool, u32)>) {
self.channel_status = channels.into_iter()
.map(|(name, connected, unread)| ChannelStatus { name, connected, unread })
.collect();
}
pub fn update_idle(&mut self, state: &crate::thalamus::idle::State) {
self.idle_info = Some(IdleInfo {
user_present: state.user_present(), since_activity: state.since_activity(),
activity_ewma: state.activity_ewma, block_reason: state.block_reason().to_string(),
dreaming: state.dreaming, sleeping: state.sleep_until.is_some(),
});
}
}
pub fn init_terminal() -> io::Result<ratatui::Terminal<CrosstermBackend<io::Stdout>>> {
2026-04-04 02:46:32 -04:00
terminal::enable_raw_mode()?;
let mut stdout = io::stdout();
stdout.execute(EnterAlternateScreen)?;
stdout.execute(EnableMouseCapture)?;
let backend = CrosstermBackend::new(stdout);
ratatui::Terminal::new(backend)
2026-04-04 02:46:32 -04:00
}
pub fn restore_terminal(terminal: &mut ratatui::Terminal<CrosstermBackend<io::Stdout>>) -> io::Result<()> {
2026-04-04 02:46:32 -04:00
terminal::disable_raw_mode()?;
terminal.backend_mut().execute(DisableMouseCapture)?;
terminal.backend_mut().execute(LeaveAlternateScreen)?;
terminal.show_cursor()
}
// --- CLI ---
use clap::{Parser, Subcommand};
use std::path::PathBuf;
#[derive(Parser, Debug)]
#[command(name = "consciousness", about = "Substrate-independent AI agent")]
pub struct CliArgs {
/// Select active backend ("anthropic" or "openrouter")
#[arg(long)]
pub backend: Option<String>,
/// Model override
#[arg(short, long)]
pub model: Option<String>,
/// API key override
#[arg(long)]
pub api_key: Option<String>,
/// Base URL override
#[arg(long)]
pub api_base: Option<String>,
/// Enable debug logging
#[arg(long)]
pub debug: bool,
/// Print effective config with provenance and exit
#[arg(long)]
pub show_config: bool,
/// Override all prompt assembly with this file
#[arg(long)]
pub system_prompt_file: Option<PathBuf>,
/// Project memory directory
#[arg(long)]
pub memory_project: Option<PathBuf>,
/// Max consecutive DMN turns
#[arg(long)]
pub dmn_max_turns: Option<u32>,
/// Disable background agents (surface, observe, scoring)
#[arg(long)]
pub no_agents: bool,
2026-04-04 02:46:32 -04:00
#[command(subcommand)]
pub command: Option<SubCmd>,
}
#[derive(Subcommand, Debug)]
pub enum SubCmd {
/// Print new output since last read and exit
Read {
/// Stream output continuously instead of exiting
#[arg(short, long)]
follow: bool,
/// Block until a complete response is received, then exit
#[arg(long)]
block: bool,
},
/// Send a message to the running agent
Write {
/// The message to send
message: Vec<String>,
},
}
#[tokio::main]
pub async fn main() {
let cli = CliArgs::parse();
if cli.show_config {
match crate::config::load_app(&cli) {
Ok((app, figment)) => crate::config::show_config(&app, &figment),
Err(e) => {
eprintln!("Error loading config: {:#}", e);
std::process::exit(1);
}
}
return;
}
if let Err(e) = crate::user::event_loop::start(cli).await {
let _ = ratatui::crossterm::terminal::disable_raw_mode();
let _ = ratatui::crossterm::execute!(
2026-04-04 02:46:32 -04:00
std::io::stdout(),
ratatui::crossterm::terminal::LeaveAlternateScreen
2026-04-04 02:46:32 -04:00
);
eprintln!("Error: {:#}", e);
std::process::exit(1);
}
}