agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
//! Interactive PTY resources shared by desktop adapters and core callers.
mod agent_input;
pub mod clipboard;
pub(crate) mod interactive;
pub(crate) mod launch_command;
mod process;
mod script;
pub use script::prepare_script;
mod session;
mod shell;
use anyhow::{bail, Result};
use portable_pty::{CommandBuilder, PtySize};
use serde::{Deserialize, Serialize};
use session::Session;
pub use shell::{prepare_shell, LaunchState, ShellIntegration};
use std::{
    collections::{HashMap, HashSet},
    path::PathBuf,
    sync::{Arc, Mutex},
};

/// Maximum number of active or reserved terminal panes per workspace window.
pub const TERMINAL_PANE_LIMIT: usize = 99;

#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
pub struct TerminalSize {
    pub rows: u16,
    pub cols: u16,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct TerminalDisplay {
    pub fg: Option<String>,
    pub bg: Option<String>,
    pub cursor: Option<String>,
}
impl TerminalSize {
    pub fn validate(self) -> Result<()> {
        self.pty().map(|_| ())
    }

    fn pty(self) -> Result<PtySize> {
        if self.rows == 0 || self.cols == 0 || self.rows > 1000 || self.cols > 2000 {
            bail!("Terminal dimensions are outside the supported range");
        }
        Ok(PtySize {
            rows: self.rows,
            cols: self.cols,
            pixel_width: 0,
            pixel_height: 0,
        })
    }
}

pub struct TerminalSpec {
    pub project_id: String,
    pub cwd: PathBuf,
    pub command: CommandBuilder,
    pub integration: Option<ShellIntegration>,
    pub size: TerminalSize,
}

/// A terminal and any resource created exclusively for its lifetime.
pub struct PreparedTerminal {
    pub spec: TerminalSpec,
    pub resource: Option<Box<dyn Send>>,
    pub core_terminal: Option<CoreTerminalIdentity>,
}

impl From<TerminalSpec> for PreparedTerminal {
    fn from(spec: TerminalSpec) -> Self {
        Self {
            spec,
            resource: None,
            core_terminal: None,
        }
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct CoreTerminalIdentity {
    pub session: String,
    pub pane_id: String,
    pub terminal_id: String,
    #[serde(skip)]
    pub(crate) preserve_on_detach: Arc<std::sync::atomic::AtomicBool>,
}

#[derive(Clone, Debug, Serialize)]
pub struct TerminalSession {
    pub id: String,
    pub project_id: String,
    pub cwd: String,
    pub exited: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub core_terminal: Option<CoreTerminalIdentity>,
}

#[derive(Clone, Debug, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum TerminalEvent {
    Output { seq: u64, data: String },
    HerdrActivity { active: bool },
    Exit { code: u32 },
    Error { message: String },
}

type Sink = Arc<dyn Fn(TerminalEvent) -> bool + Send + Sync>;
#[derive(Default)]
struct Sessions {
    items: HashMap<String, Arc<Session>>,
    pending: HashMap<String, usize>,
    generations: HashMap<String, u64>,
    closed_owners: HashSet<String>,
    shutting_down: bool,
}
#[derive(Default)]
pub struct TerminalManager {
    sessions: Mutex<Sessions>,
}

impl TerminalManager {
    pub fn create(
        &self,
        owner: &str,
        spec: TerminalSpec,
        sink: impl Fn(TerminalEvent) -> bool + Send + Sync + 'static,
    ) -> Result<TerminalSession> {
        self.create_with(owner, || Ok(spec), sink)
    }

    /// Reserve capacity before preparing a slow external program.
    pub fn create_with(
        &self,
        owner: &str,
        prepare: impl FnOnce() -> Result<TerminalSpec>,
        sink: impl Fn(TerminalEvent) -> bool + Send + Sync + 'static,
    ) -> Result<TerminalSession> {
        self.create_prepared(owner, || prepare().map(PreparedTerminal::from), sink)
    }

    pub fn create_prepared(
        &self,
        owner: &str,
        prepare: impl FnOnce() -> Result<PreparedTerminal>,
        sink: impl Fn(TerminalEvent) -> bool + Send + Sync + 'static,
    ) -> Result<TerminalSession> {
        let generation = {
            let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
            if sessions.shutting_down || sessions.closed_owners.contains(owner) {
                bail!("Terminal manager is shutting down");
            }
            if sessions.items.values().filter(|s| s.owner == owner).count()
                + sessions.pending.get(owner).copied().unwrap_or(0)
                >= TERMINAL_PANE_LIMIT
            {
                bail!("Close an existing terminal before opening another (limit: {TERMINAL_PANE_LIMIT})");
            }
            *sessions.pending.entry(owner.into()).or_default() += 1;
            *sessions.generations.entry(owner.into()).or_default()
        };
        let created = prepare().and_then(|spec| Session::spawn(owner, spec, Arc::new(sink)));
        let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(pending) = sessions.pending.get_mut(owner) {
            *pending -= 1;
        }
        let session = created?;
        if sessions.shutting_down || sessions.generations.get(owner) != Some(&generation) {
            drop(sessions);
            session.close();
            bail!("Terminal manager is shutting down");
        }
        let snapshot = session.snapshot();
        sessions.items.insert(snapshot.id.clone(), session);
        Ok(snapshot)
    }

    fn session(&self, owner: &str, id: &str) -> Result<Arc<Session>> {
        let sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
        let session = sessions
            .items
            .get(id)
            .ok_or_else(|| anyhow::anyhow!("Terminal is closed"))?;
        if session.owner != owner {
            bail!("Terminal belongs to another window");
        }
        Ok(session.clone())
    }
    pub fn write(&self, owner: &str, id: &str, bytes: Vec<u8>) -> Result<()> {
        self.session(owner, id)?.write(bytes)
    }
    pub fn mark_native_agent(&self, owner: &str, id: &str) -> Result<()> {
        self.session(owner, id)?.mark_native_agent();
        Ok(())
    }
    pub fn agent_prompt(&self, owner: &str, id: &str, prompt: &str) -> Result<()> {
        self.session(owner, id)?.agent_prompt(prompt)
    }
    pub fn resize(&self, owner: &str, id: &str, size: TerminalSize) -> Result<()> {
        self.session(owner, id)?.resize(size.pty()?)
    }
    pub fn ack(&self, owner: &str, id: &str, seq: u64) -> Result<()> {
        self.session(owner, id)?.ack(seq)
    }
    pub fn launch_state(&self, owner: &str, id: &str) -> Result<LaunchState> {
        Ok(self.session(owner, id)?.launch_state())
    }
    pub fn list(&self, owner: &str) -> Result<Vec<TerminalSession>> {
        Ok(self
            .sessions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .items
            .values()
            .filter(|s| s.owner == owner)
            .map(|s| s.snapshot())
            .collect())
    }
    pub fn close(&self, owner: &str, id: &str) -> Result<()> {
        self.remove(owner, id, false)
    }
    pub fn detach(&self, owner: &str, id: &str) -> Result<()> {
        self.remove(owner, id, true)
    }
    fn remove(&self, owner: &str, id: &str, preserve_core: bool) -> Result<()> {
        let session = self.session(owner, id)?;
        self.sessions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .items
            .remove(id);
        if preserve_core {
            session.detach();
        } else {
            session.close();
        }
        Ok(())
    }
    /// Reopen a trusted workspace identity before accepting new terminal requests.
    pub fn open_owner(&self, owner: &str) {
        self.sessions
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .closed_owners
            .remove(owner);
    }
    /// Atomically reject pending launches and detach PTYs; run cleanup off the UI thread.
    pub fn detach_owner(&self, owner: &str) -> impl FnOnce() + Send + 'static {
        let items = {
            let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
            sessions.closed_owners.insert(owner.into());
            *sessions.generations.entry(owner.into()).or_default() += 1;
            let ids: Vec<_> = sessions
                .items
                .iter()
                .filter(|(_, s)| s.owner == owner)
                .map(|(id, _)| id.clone())
                .collect();
            ids.into_iter()
                .filter_map(|id| sessions.items.remove(&id))
                .collect::<Vec<_>>()
        };
        move || {
            for session in items {
                session.detach();
            }
        }
    }
    /// Release only the PTYs owned by a closing workspace.
    pub fn close_owner(&self, owner: &str) {
        self.detach_owner(owner)();
    }
    pub fn close_all(&self) {
        let items = {
            let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
            sessions.shutting_down = true;
            std::mem::take(&mut sessions.items)
        };
        for session in items.into_values() {
            session.detach();
        }
    }
}
impl Drop for TerminalManager {
    fn drop(&mut self) {
        self.close_all();
    }
}