From 74cdaae679f663fe0c01b34e3d09f62f16033639 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:49 +0100 Subject: [PATCH] capri: add command-line entry point --- crates/capri/src/main.rs | 222 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 222 insertions(+) create mode 100644 crates/capri/src/main.rs diff --git a/crates/capri/src/main.rs b/crates/capri/src/main.rs new file mode 100644 index 0000000..2e5eed5 --- /dev/null +++ b/crates/capri/src/main.rs @@ -0,0 +1,222 @@ +//! `capri`: desktop companion (default), terminal chat and maintenance commands. +mod desktop; +mod import; +mod wiring; + +use std::io::Write; +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::Result; +use capri_agent::{Engine, TurnEvent}; +use capri_core::avatar::Catalog; +use capri_core::{Paths, Settings}; +use capri_llm::server::{resolve_model, OllamaServer}; +use clap::{Parser, Subcommand}; + +#[derive(Parser)] +#[command(name = "capri", version, about = "Capri desktop AI companion for Linux (KDE Plasma and i3)")] +struct Cli { + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Open the desktop companion (default). + Desktop { + /// Send this text as the owner's first message once the companion is open (testing). + #[arg(long)] + submit: Option, + }, + /// Chat in the terminal. + Chat, + /// Show paths, settings and the state of the language model. + Status, + /// Download the configured language model into Capri's model store. + Pull { + /// Model to download; defaults to the configured upstream model. + model: Option, + }, + /// Import personality, memory, history and settings from a Capri 1.0.4 installation. + Import { + #[arg(default_value = "~/Capri")] + from: String, + }, + /// Start a new conversation (history is cleared, memory files are kept). + Reset, +} + +fn expand(path: &str) -> PathBuf { + match path.strip_prefix("~/") { + Some(rest) => std::env::var_os("HOME").map(PathBuf::from).unwrap_or_default().join(rest), + None => PathBuf::from(path), + } +} + +/// Avatar catalog from the configured Capri artwork, or the bundled fallback. +pub fn load_catalog(settings: &Settings) -> Arc { + let catalog = settings.avatar_dir.as_deref().map(Catalog::load); + match catalog { + Some(Ok(c)) => Arc::new(c), + Some(Err(e)) => { + eprintln!("Capri artwork unavailable ({e:#}); using the fallback avatar."); + Arc::new(Catalog::fallback()) + } + None => Arc::new(Catalog::fallback()), + } +} + +async fn chat(paths: Paths, settings: Settings) -> Result<()> { + let companion = wiring::start(&paths, capri_core::SettingsStore::new(paths.clone(), settings), None).await?; + let engine = companion.engine.clone(); + println!("Capri ({}). Type a message; Ctrl+D quits, /reset starts a new conversation, /web toggles internet mode.", engine.label()); + if let Some(w) = engine.history_warning() { + println!("{w}"); + } + let stdin = std::io::stdin(); + loop { + print!("> "); + std::io::stdout().flush()?; + let mut line = String::new(); + if stdin.read_line(&mut line)? == 0 { + break; + } + match line.trim() { + "" => continue, + "/web" => { + engine.set_internet(!engine.internet()); + println!("Internet mode {}.", if engine.internet() { "on" } else { "off" }); + continue; + } + "/reset" => { + engine.reset_conversation()?; + println!("New conversation."); + continue; + } + _ => {} + } + let turn = { + let engine = engine.clone(); + tokio::spawn(async move { + engine + .submit(&line, |event| match event { + TurnEvent::Delta { text, .. } => { + print!("{text}"); + let _ = std::io::stdout().flush(); + } + TurnEvent::Avatar { id, .. } => print!("[{id}] "), + TurnEvent::Completed { .. } => println!(), + TurnEvent::Failed { message, .. } => println!("\n{message}"), + TurnEvent::Cancelled { .. } => println!("\nReply stopped."), + TurnEvent::Tool { name, ok: None, .. } => eprint!("({name}) "), + TurnEvent::Started { .. } | TurnEvent::Tool { .. } => {} + }) + .await + }) + }; + let cancel = engine.clone(); + tokio::select! { + result = turn => if let Err(message) = result? { println!("{message}") }, + _ = tokio::signal::ctrl_c() => { cancel.cancel(); } + } + } + companion.stop().await; + Ok(()) +} + +async fn status(paths: Paths, settings: Settings) -> Result<()> { + println!("Config: {}", paths.config.display()); + println!("Data: {}", paths.data.display()); + println!("Models: {}", settings.models_dir(&paths).display()); + println!("Ollama: {}", settings.ollama_base_url()); + let catalog = load_catalog(&settings); + println!("Avatar: {} expressions ({})", catalog.model_sprites.len(), if settings.avatar_dir.is_some() { "Capri artwork" } else { "fallback" }); + let server = OllamaServer::start(&settings, &paths).await?; + println!("Ollama version {}{}", server.client.version().await?, if server.owned() { " (started by Capri)" } else { "" }); + match resolve_model(&server.client, &settings).await { + Ok((model, caps)) => println!("Model: {model} [{}]", caps.join(", ")), + Err(e) => println!("Model: {e}"), + } + server.stop().await; + Ok(()) +} + +async fn pull(paths: Paths, settings: Settings, model: Option) -> Result<()> { + let model = model.unwrap_or(settings.upstream_model.clone()); + let server = OllamaServer::start(&settings, &paths).await?; + let mut last = String::new(); + server + .client + .pull(&model, |status, done, total| { + let line = (done * 100).checked_div(total).map_or_else(|| status.to_string(), |pct| format!("{status} {pct}%")); + if line != last { + print!("\r{line:<60}"); + let _ = std::io::stdout().flush(); + last = line; + } + }) + .await?; + println!("\n{model} is ready."); + server.stop().await; + Ok(()) +} + +fn main() -> Result<()> { + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::try_from_env("CAPRI_LOG").unwrap_or_else(|_| "warn".into())) + .with_writer(std::io::stderr) + .init(); + let cli = Cli::parse(); + let paths = Paths::discover()?; + paths.ensure()?; + let mut settings = Settings::load(&paths)?; + let runtime = tokio::runtime::Runtime::new()?; + match cli.command.unwrap_or(Command::Desktop { submit: None }) { + Command::Desktop { submit } => { + let store = capri_core::SettingsStore::new(paths.clone(), settings); + let ui = capri_ui::UiHandle::new(); + let companion = runtime.block_on(wiring::start(&paths, store.clone(), Some(ui.clone())))?; + let pages = wiring::settings_pages(&companion, runtime.handle()); + // SIGINT/SIGTERM quit through the UI so `Companion::stop` releases KWin scripts and grabs. + let quit = ui.clone(); + runtime.spawn(async move { + let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).ok(); + let terminated = async { + match term.as_mut() { + Some(t) => t.recv().await, + None => std::future::pending().await, + } + }; + tokio::select! { _ = tokio::signal::ctrl_c() => {}, _ = terminated => {} } + quit.command(capri_ui::Command::Quit); + }); + if let Some(text) = submit { + let first = ui.clone(); + runtime.spawn(async move { + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + first.command(capri_ui::Command::Submit(text)); + }); + } + let result = capri_ui::run(runtime.handle().clone(), companion.engine.clone(), store, pages, ui); + runtime.block_on(companion.stop()); + result + } + Command::Chat => runtime.block_on(chat(paths, settings)), + Command::Status => runtime.block_on(status(paths, settings)), + Command::Pull { model } => runtime.block_on(pull(paths, settings, model)), + Command::Import { from } => { + for line in import::import(&expand(&from), &paths, &mut settings)? { + println!("{line}"); + } + Ok(()) + } + Command::Reset => { + // No model is needed: only the session and the visible history are reset. + let client = capri_llm::Ollama::new(settings.ollama_base_url()); + Engine::new(paths, settings.clone(), client, settings.model.clone(), &[], load_catalog(&settings))?.reset_conversation()?; + println!("New conversation started."); + Ok(()) + } + } +}