// user/ — User interface layer // // TUI, UI channel, parsing. The cognitive layer (session state // machine, DMN, identity) lives in mind/. pub mod chat; pub mod context; pub mod subconscious; pub mod unconscious; pub mod thalamus; use anyhow::Result; use ratatui::crossterm::event::{Event, EventStream, KeyEventKind}; use futures::StreamExt; use std::time::Duration; use crate::mind::MindCommand; use crate::user::{self as tui}; // --- TUI infrastructure (moved from tui/mod.rs) --- use ratatui::crossterm::{ event::{EnableMouseCapture, DisableMouseCapture, KeyCode, KeyEvent, KeyModifiers}, terminal::{self, EnterAlternateScreen, LeaveAlternateScreen}, ExecutableCommand, }; use ratatui::{ backend::CrosstermBackend, }; use std::io; use crate::agent::context::SharedContextState; /// Status info for the bottom status bar. #[derive(Debug, Clone)] pub struct StatusInfo { pub dmn_state: String, pub dmn_turns: u32, pub dmn_max_turns: u32, pub prompt_tokens: u32, pub completion_tokens: u32, pub model: String, pub turn_tools: u32, pub context_budget: String, } /// Context loading details for the debug screen. #[derive(Debug, Clone)] pub struct ContextInfo { pub model: String, pub available_models: Vec, pub prompt_file: String, pub backend: String, pub instruction_files: Vec<(String, usize)>, pub memory_files: Vec<(String, usize)>, pub system_prompt_chars: usize, pub context_message_chars: usize, } /// Build the screen legend from screen labels. pub(crate) fn screen_legend_from(interact: &dyn ScreenView, screens: &[Box]) -> 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 = 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() } /// 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, app: &mut App) -> Option; fn label(&self) -> &'static str; } #[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), } #[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, pub(crate) active_tools: crate::agent::tools::SharedActiveTools, pub should_quit: bool, pub submitted: Vec, pub hotkey_actions: Vec, pub(crate) context_info: Option, pub(crate) shared_context: SharedContextState, pub(crate) agent_state: Vec, pub(crate) channel_status: Vec, pub(crate) idle_info: Option, } impl App { pub fn new(model: String, shared_context: SharedContextState, active_tools: crate::agent::tools::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, reasoning_effort: "none".to_string(), temperature: 0.6, top_p: 0.95, top_k: 20, active_tools, 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, } } pub fn handle_global_key_old(&mut self, _key: KeyEvent) -> bool { false } // placeholder /// Handle global keys only (Ctrl combos). pub fn handle_global_key(&mut self, key: KeyEvent) -> bool { 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; } _ => {} } } false } 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>> { terminal::enable_raw_mode()?; let mut stdout = io::stdout(); stdout.execute(EnterAlternateScreen)?; stdout.execute(EnableMouseCapture)?; let backend = CrosstermBackend::new(stdout); ratatui::Terminal::new(backend) } pub fn restore_terminal(terminal: &mut ratatui::Terminal>) -> io::Result<()> { terminal::disable_raw_mode()?; terminal.backend_mut().execute(DisableMouseCapture)?; terminal.backend_mut().execute(LeaveAlternateScreen)?; terminal.show_cursor() } /// Top-level entry point — creates Mind and UI, wires them together. pub async fn start(cli: crate::user::CliArgs) -> Result<()> { let (config, _figment) = crate::config::load_session(&cli)?; if config.app.debug { unsafe { std::env::set_var("POC_DEBUG", "1") }; } let (turn_tx, turn_rx) = tokio::sync::mpsc::channel(1); let (mind_tx, mind_rx) = tokio::sync::mpsc::unbounded_channel(); let mind = crate::mind::Mind::new(config, turn_tx); let shared_context = mind.agent.lock().await.shared_context.clone(); let shared_active_tools = mind.agent.lock().await.active_tools.clone(); let mut result = Ok(()); tokio_scoped::scope(|s| { // Mind event loop — init + run s.spawn(async { mind.init().await; mind.run(mind_rx, turn_rx).await; }); // UI event loop s.spawn(async { result = run( tui::App::new(String::new(), shared_context, shared_active_tools), &mind, mind_tx, ).await; }); }); result } fn hotkey_cycle_reasoning(mind: &crate::mind::Mind) { if let Ok(mut ag) = mind.agent.try_lock() { let next = match ag.reasoning_effort.as_str() { "none" => "low", "low" => "high", _ => "none", }; ag.reasoning_effort = next.to_string(); let label = match next { "none" => "off (monologue hidden)", "low" => "low (brief monologue)", "high" => "high (full monologue)", _ => next, }; ag.notify(format!("reasoning: {}", label)); } } async fn hotkey_kill_processes(mind: &crate::mind::Mind) { let mut ag = mind.agent.lock().await; let active_tools = ag.active_tools.clone(); let mut tools = active_tools.lock().unwrap(); if tools.is_empty() { ag.notify("no running tools"); } else { let count = tools.len(); for entry in tools.drain(..) { entry.handle.abort(); } ag.notify(format!("killed {} tools", count)); } } fn hotkey_cycle_autonomy(mind: &crate::mind::Mind) { let mut s = mind.shared.lock().unwrap(); let label = match &s.dmn { crate::mind::dmn::State::Engaged | crate::mind::dmn::State::Working | crate::mind::dmn::State::Foraging => { s.dmn = crate::mind::dmn::State::Resting { since: std::time::Instant::now() }; "resting" } crate::mind::dmn::State::Resting { .. } => { s.dmn = crate::mind::dmn::State::Paused; "PAUSED" } crate::mind::dmn::State::Paused => { crate::mind::dmn::set_off(true); s.dmn = crate::mind::dmn::State::Off; "OFF (persists across restarts)" } crate::mind::dmn::State::Off => { crate::mind::dmn::set_off(false); s.dmn = crate::mind::dmn::State::Foraging; "foraging" } }; s.dmn_turns = 0; drop(s); if let Ok(mut ag) = mind.agent.try_lock() { ag.notify(format!("DMN → {}", label)); } } fn hotkey_adjust_sampling(mind: &crate::mind::Mind, param: usize, delta: f32) { if let Ok(mut ag) = mind.agent.try_lock() { match param { 0 => ag.temperature = (ag.temperature + delta).clamp(0.0, 2.0), 1 => ag.top_p = (ag.top_p + delta).clamp(0.0, 1.0), 2 => ag.top_k = (ag.top_k as f32 + delta).max(0.0) as u32, _ => {} } } } fn diff_mind_state( cur: &crate::mind::MindState, prev: &crate::mind::MindState, dirty: &mut bool, ) { if cur.dmn.label() != prev.dmn.label() || cur.dmn_turns != prev.dmn_turns { *dirty = true; } // Input consumed — Mind started a turn with it if !prev.input.is_empty() && cur.input.is_empty() { *dirty = true; } if cur.turn_active != prev.turn_active { *dirty = true; } if cur.scoring_in_flight != prev.scoring_in_flight { *dirty = true; } if cur.compaction_in_flight != prev.compaction_in_flight { *dirty = true; } } pub async fn run( mut app: tui::App, mind: &crate::mind::Mind, mind_tx: tokio::sync::mpsc::UnboundedSender, ) -> Result<()> { let agent = &mind.agent; let shared_mind = &mind.shared; // UI-owned state let mut idle_state = crate::thalamus::idle::State::new(); idle_state.load(); let (channel_tx, mut channel_rx) = tokio::sync::mpsc::channel::>(4); { let tx = channel_tx.clone(); tokio::spawn(async move { let result = crate::thalamus::channels::fetch_all_channels().await; let _ = tx.send(result).await; }); } let notify_rx = crate::thalamus::channels::subscribe_all(); let mut interact = crate::user::chat::InteractScreen::new( mind.agent.clone(), mind.shared.clone(), mind_tx.clone(), ); // Overlay screens: F2=conscious, F3=subconscious, F4=unconscious, F5=thalamus let mut screens: Vec> = vec![ Box::new(crate::user::context::ConsciousScreen::new()), Box::new(crate::user::subconscious::SubconsciousScreen::new()), Box::new(crate::user::unconscious::UnconsciousScreen::new()), Box::new(crate::user::thalamus::ThalamusScreen::new()), ]; let mut active_screen: usize = 0; // 0 = interact, 1-4 = overlay tui::set_screen_legend(tui::screen_legend_from(&interact, &screens)); let mut terminal = tui::init_terminal()?; let mut reader = EventStream::new(); let mut render_interval = tokio::time::interval(Duration::from_millis(50)); render_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); let mut dirty = true; let mut prev_mind = shared_mind.lock().unwrap().clone(); let mut pending_key: Option = None; terminal.hide_cursor()?; if let Ok(mut ag) = agent.try_lock() { ag.notify("consciousness v0.3"); } // Initial render terminal.draw(|f| { let area = f.area(); interact.tick(f, area, None, &mut app); })?; // Replay conversation after Mind init completes (non-blocking check) let mut startup_done = false; loop { tokio::select! { biased; maybe_event = reader.next() => { match maybe_event { Some(Ok(Event::Key(key))) => { if key.kind != KeyEventKind::Press { continue; } idle_state.user_activity(); // F-keys switch screens if let ratatui::crossterm::event::KeyCode::F(n) = key.code { active_screen = match n { 1 => 0, // interact n @ 2..=5 if (n as usize - 2) < screens.len() => n as usize - 1, _ => active_screen, }; if active_screen == 4 { // thalamus — refresh channels let tx = channel_tx.clone(); tokio::spawn(async move { let result = crate::thalamus::channels::fetch_all_channels().await; let _ = tx.send(result).await; }); } dirty = true; continue; } // Global keys (Ctrl combos) — only pass to screen if not consumed if !app.handle_global_key(key) { pending_key = Some(key); } dirty = true; } Some(Ok(Event::Mouse(_mouse))) => { // TODO: route to active screen dirty = true; } Some(Ok(Event::Resize(_w, _h))) => { terminal.clear()?; dirty = true; } Some(Err(_)) => break, None => break, _ => continue, } } _ = render_interval.tick() => { idle_state.decay_ewma(); app.update_idle(&idle_state); // One-time: mark startup done after Mind init if !startup_done { if let Ok(mut ag) = agent.try_lock() { let model = ag.model().to_string(); ag.notify(format!("model: {}", model)); startup_done = true; dirty = true; } } // Diff MindState — generate UI messages from changes { let cur = shared_mind.lock().unwrap(); diff_mind_state(&cur, &prev_mind, &mut dirty); prev_mind = cur.clone(); } while let Ok(notif) = notify_rx.try_recv() { let tx = channel_tx.clone(); tokio::spawn(async move { let result = crate::thalamus::channels::fetch_all_channels().await; let _ = tx.send(result).await; }); } } Some(channels) = channel_rx.recv() => { app.set_channel_status(channels); dirty = true; } } // Handle hotkey actions let actions: Vec = app.hotkey_actions.drain(..).collect(); for action in actions { match action { HotkeyAction::CycleReasoning => hotkey_cycle_reasoning(mind), HotkeyAction::KillProcess => hotkey_kill_processes(mind).await, HotkeyAction::Interrupt => { let _ = mind_tx.send(MindCommand::Interrupt); } HotkeyAction::CycleAutonomy => hotkey_cycle_autonomy(mind), HotkeyAction::AdjustSampling(param, delta) => hotkey_adjust_sampling(mind, param, delta), } dirty = true; } if dirty { let key = pending_key.take(); let mut screen_action = None; if active_screen == 0 { terminal.draw(|f| { let area = f.area(); screen_action = interact.tick(f, area, key, &mut app); })?; } else { let screen = &mut screens[active_screen - 1]; terminal.draw(|f| { let area = f.area(); screen_action = screen.tick(f, area, key, &mut app); })?; } if let Some(action) = screen_action { match action { tui::ScreenAction::Switch(i) => { active_screen = i; dirty = true; continue; } tui::ScreenAction::Hotkey(h) => app.hotkey_actions.push(h), } } dirty = false; } if app.should_quit { break; } } tui::restore_terminal(&mut terminal)?; Ok(()) } // --- 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, /// Model override #[arg(short, long)] pub model: Option, /// API key override #[arg(long)] pub api_key: Option, /// Base URL override #[arg(long)] pub api_base: Option, /// 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, /// Project memory directory #[arg(long)] pub memory_project: Option, /// Max consecutive DMN turns #[arg(long)] pub dmn_max_turns: Option, /// Disable background agents (surface, observe, scoring) #[arg(long)] pub no_agents: bool, #[command(subcommand)] pub command: Option, } #[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, }, } #[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) = start(cli).await { let _ = ratatui::crossterm::terminal::disable_raw_mode(); let _ = ratatui::crossterm::execute!( std::io::stdout(), ratatui::crossterm::terminal::LeaveAlternateScreen ); eprintln!("Error: {:#}", e); std::process::exit(1); } }