mod agents;
mod app;
mod commands;
mod drawn;
mod full;
mod inline;
mod json;
mod markdown;
mod pump;
mod safe;
mod term;
#[cfg(test)]
mod tests;
mod theme;
mod view;
#[cfg(feature = "voice")]
mod voice;
use std::io::{IsTerminal, Write};
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use futures::future::BoxFuture;
use tokio::sync::mpsc::UnboundedReceiver;
pub use commands::{CommandContext, TerminalCommand};
pub use safe::terminal_safe;
pub use theme::{Appearance, Theme, ThemeChoice};
#[cfg(feature = "voice")]
pub use voice::TerminalVoice;
use crate::engine::SurfaceEngine;
use crate::origin::Caller;
pub const EXIT_DONE: i32 = 0;
pub const EXIT_ERROR: i32 = 1;
pub const EXIT_WAITING: i32 = 3;
pub const EXIT_BUDGET: i32 = 4;
const POLL: Duration = Duration::from_millis(400);
#[derive(Clone, Default)]
struct Shared(std::sync::Arc<std::sync::Mutex<Vec<u8>>>);
impl Write for Shared {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap_or_else(|e| e.into_inner()).extend_from_slice(buf);
Ok(buf.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum UiMode {
#[default]
FullScreen,
Inline,
}
impl FromStr for UiMode {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.trim().to_ascii_lowercase().as_str() {
"full" | "full-screen" | "fullscreen" => Ok(Self::FullScreen),
"inline" => Ok(Self::Inline),
other => Err(format!("unknown UI '{other}': use full or inline")),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum OutputFormat {
#[default]
Text,
Json,
}
impl FromStr for OutputFormat {
type Err = String;
fn from_str(value: &str) -> Result<Self, Self::Err> {
match value.trim().to_ascii_lowercase().as_str() {
"text" => Ok(Self::Text),
"json" => Ok(Self::Json),
other => Err(format!("unknown output '{other}': use text or json")),
}
}
}
type Opener =
Arc<dyn Fn(Option<String>) -> BoxFuture<'static, Result<String, String>> + Send + Sync>;
#[derive(Clone, Default)]
struct SessionGate(Option<Opener>);
impl std::fmt::Debug for SessionGate {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(if self.0.is_some() { "SessionGate(set)" } else { "SessionGate(none)" })
}
}
#[derive(Clone, Default)]
struct LateNotices(Arc<Mutex<Option<UnboundedReceiver<String>>>>);
impl LateNotices {
fn take(&self) -> Option<UnboundedReceiver<String>> {
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner).take()
}
}
impl std::fmt::Debug for LateNotices {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("LateNotices")
}
}
#[derive(Debug, Clone)]
pub struct TerminalSurface {
engine: SurfaceEngine,
caller: Caller,
session: Option<String>,
theme: ThemeChoice,
model: Option<String>,
place: Option<String>,
home: Option<String>,
poll: Duration,
notices: Vec<String>,
late: LateNotices,
signals: bool,
gate: SessionGate,
commands: commands::Commands,
#[cfg(feature = "voice")]
voice: voice::VoiceSlot,
}
impl TerminalSurface {
pub fn new(engine: SurfaceEngine, caller: Caller) -> Self {
Self {
engine,
caller,
session: None,
theme: ThemeChoice::Auto,
model: None,
place: None,
home: None,
poll: POLL,
notices: Vec::new(),
late: LateNotices::default(),
signals: true,
gate: SessionGate::default(),
commands: commands::Commands::default(),
#[cfg(feature = "voice")]
voice: voice::VoiceSlot::default(),
}
}
#[cfg(feature = "voice")]
#[must_use]
pub fn voice(self, voice: TerminalVoice) -> Self {
*self.voice.lock().unwrap_or_else(|e| e.into_inner()) = Some(voice);
self
}
#[must_use]
pub fn session(mut self, session: impl Into<String>) -> Self {
self.session = Some(session.into());
self
}
#[must_use]
pub fn theme(mut self, theme: ThemeChoice) -> Self {
self.theme = theme;
self
}
#[must_use]
pub fn model(mut self, model: impl Into<String>) -> Self {
self.model = Some(model.into());
self
}
#[must_use]
pub fn place(mut self, place: impl Into<String>) -> Self {
self.place = Some(place.into());
self
}
#[must_use]
pub fn home(mut self, url: impl Into<String>) -> Self {
self.home = Some(url.into().trim_end_matches('/').to_string());
self
}
#[must_use]
pub fn poll_interval(mut self, poll: Duration) -> Self {
self.poll = poll;
self
}
#[must_use]
pub fn notice(mut self, text: impl Into<String>) -> Self {
self.notices.push(text.into());
self
}
#[must_use]
pub fn notices_from(mut self, notices: UnboundedReceiver<String>) -> Self {
self.late = LateNotices(Arc::new(Mutex::new(Some(notices))));
self
}
#[must_use]
pub fn open_sessions_with<F>(mut self, open: F) -> Self
where
F: Fn(Option<String>) -> BoxFuture<'static, Result<String, String>> + Send + Sync + 'static,
{
self.gate = SessionGate(Some(Arc::new(open)));
self
}
#[must_use]
pub fn command(mut self, command: Arc<dyn TerminalCommand>) -> Self {
self.commands.add(command);
self
}
#[must_use]
pub fn restore_on_signals(mut self, enabled: bool) -> Self {
self.signals = enabled;
self
}
pub fn capable_terminal() -> bool {
std::io::stdin().is_terminal()
&& std::io::stdout().is_terminal()
&& std::env::var("TERM").map_or(cfg!(windows), |term| term != "dumb")
&& crossterm::terminal::size().is_ok_and(|(cols, rows)| cols >= 60 && rows >= 16)
}
pub async fn run(self, ui: UiMode) -> std::io::Result<i32> {
match ui {
UiMode::FullScreen => full::run(self).await,
UiMode::Inline => inline::run(self).await,
}
}
pub async fn run_json<W: Write + Send>(
self,
message: Option<String>,
out: W,
) -> std::io::Result<i32> {
json::run(self, message, out).await
}
pub async fn screen(&self, cols: u16, rows: u16) -> std::io::Result<Vec<u8>> {
use ratatui::backend::CrosstermBackend;
use ratatui::layout::Rect;
use ratatui::{Terminal, TerminalOptions, Viewport};
let session = self.initial_session().await;
let engine = &self.engine;
let caller = &self.caller;
let mut app = app::App::new(engine.source().app_name(), session.clone());
app.agents_pane.granted = engine.granted().to_vec();
app.model = self.model.clone();
app.place = self.place.clone();
app.commands = self.commands.clone();
let now = std::time::Instant::now();
let armed = now.checked_sub(app::ARM_DELAY * 2).unwrap_or(now);
let status = match engine.status(caller, Some(&session)).await {
Ok(status) => Some(status),
Err(_) => engine.status(caller, None).await.ok(),
};
if let Some(status) = status {
app.update(app::Update::Status(status), now);
}
if let Ok(agents) = engine.agents(caller).await {
app.update(app::Update::Agents(agents), now);
}
if let Ok(removed) = engine.removed_agents(caller).await {
app.update(app::Update::Removed(removed), now);
}
if let Ok(briefing) = engine.briefing(caller, pump::start_of_today()).await {
app.update(app::Update::Briefing(briefing), now);
}
let thread = match engine.thread(caller, &session).await {
Ok(thread) => thread,
Err(crate::SurfaceError::NotFound { .. }) => Vec::new(),
Err(error) => return Err(std::io::Error::other(error)),
};
for entry in thread {
let frame = crate::FeedFrame::Entry { entry };
app.update(app::Update::Frame { session: session.clone(), generation: 0, frame }, now);
}
let cards = engine
.decisions(caller)
.await
.map_err(std::io::Error::other)?
.into_iter()
.filter(|card| card.session_id == session)
.collect();
let frame = crate::FeedFrame::Decisions { cards };
app.update(app::Update::Frame { session: session.clone(), generation: 0, frame }, armed);
app.queued = engine.queued(caller, &session);
let appearance = match self.theme {
ThemeChoice::Light => Appearance::Light,
ThemeChoice::Dark | ThemeChoice::Auto => Appearance::Dark,
};
let mut renderer = view::Renderer::new(Theme::new(appearance, true));
let options = TerminalOptions { viewport: Viewport::Fixed(Rect::new(0, 0, cols, rows)) };
let bytes = Shared::default();
let mut terminal = Terminal::with_options(CrosstermBackend::new(bytes.clone()), options)?;
terminal.draw(|frame| {
renderer.draw(frame, &app, now);
})?;
drop(terminal);
Ok(std::mem::take(&mut *bytes.0.lock().unwrap_or_else(|e| e.into_inner())))
}
async fn open_session(&self, requested: Option<String>) -> Result<String, String> {
match &self.gate.0 {
Some(open) => open(requested).await,
None => Ok(requested.unwrap_or_else(|| uuid::Uuid::new_v4().to_string())),
}
}
async fn apply(
&self,
effect: app::Effect,
app: &mut app::App,
pump: &pump::Pump,
commands: &mut pump::Commands,
tx: &tokio::sync::mpsc::UnboundedSender<app::Update>,
shown: &mut Vec<String>,
) -> bool {
match effect {
app::Effect::Execute(command) => {
commands.execute(&self.engine, &self.caller, command, tx);
}
app::Effect::Session(session) => {
if !shown.contains(&session) {
shown.push(session.clone());
}
pump.switch(session);
}
app::Effect::OpenSession(requested) => match self.open_session(requested).await {
Ok(session) => {
for effect in app.switch_session(session) {
if let app::Effect::Session(session) = effect {
if !shown.contains(&session) {
shown.push(session.clone());
}
pump.switch(session);
}
}
}
Err(why) => app.notice(why, app::Tone::Problem),
},
app::Effect::Unqueue(session) => {
app.took_back(self.engine.unqueue_last(&self.caller, &session));
}
app::Effect::Briefing => pump.refresh_briefing(),
app::Effect::Open(url) => match open_in_browser(&url) {
Ok(()) => app.notice(format!("Opened {url}"), app::Tone::Info),
Err(why) => {
app.notice(format!("Open {url} in your browser: {why}"), app::Tone::Problem)
}
},
app::Effect::RunCommand { serial, name, args } => {
let found = self.commands.find(&name).or_else(|| self.commands.shadowed(&name));
match found {
Some(command) => {
let context = CommandContext::new(app.session.clone());
commands.run_added(command, args, context, serial, tx);
}
None => app.update(
app::Update::CommandDone {
serial,
result: Err(format!("No command /{name}. /help lists them.")),
},
std::time::Instant::now(),
),
}
}
app::Effect::Quit => return true,
}
false
}
async fn leave(&self, commands: pump::Commands, shown: &[String], out: &mut impl Write) {
if commands.running() {
let _ = writeln!(out, "Finishing what you sent…");
}
let left = commands.finish(pump::FINISH_WAIT).await;
if !left.is_empty() {
let _ = writeln!(out, "Left before this finished: {}.", left.join(", "));
}
let queued: Vec<String> = shown
.iter()
.flat_map(|session| self.engine.queued(&self.caller, session))
.map(|text| format!("\"{}\"", safe::safe_line(&text)))
.collect();
if !queued.is_empty() {
let _ = writeln!(
out,
"Not sent — queued in this terminal, which has closed: {}",
queued.join(", ")
);
}
let _ = out.flush();
}
async fn initial_session(&self) -> String {
if let Some(session) = &self.session {
return session.clone();
}
if let Ok(cards) = self.engine.decisions(&self.caller).await
&& let Some(card) = cards.first()
{
return card.session_id.clone();
}
uuid::Uuid::new_v4().to_string()
}
}
fn open_in_browser(url: &str) -> std::result::Result<(), String> {
if !(url.starts_with("http://") || url.starts_with("https://")) {
return Err("only a web address opens".into());
}
let mut command = if cfg!(target_os = "macos") {
std::process::Command::new("open")
} else if cfg!(windows) {
let mut start = std::process::Command::new("cmd");
start.args(["/C", "start", ""]);
start
} else {
std::process::Command::new("xdg-open")
};
command
.arg(url)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
.map(|_| ())
.map_err(|error| error.to_string())
}