agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
//! Herdr Core terminal control. Terminal rendering remains with the caller.
mod discovery;
pub(crate) mod install;
pub(crate) mod interactive;
pub(crate) mod managed;
mod rpc;
pub(crate) mod sessions;

use anyhow::{bail, ensure, Context, Result};
use portable_pty::CommandBuilder;
use serde_json::{json, Value};
use std::path::{Path, PathBuf};
use std::process::Command;

pub(crate) const VIEWER_ENV: &str = "AGENT_HUB_HC_VIEWER";
const CONTEXT: &[&str] = &[
    "HC_SOCKET",
    "HC_TERMINAL_SOCKET",
    "HC_TERMINAL_ID",
    "HC_SCOPE",
    "HC_SESSION",
];

#[derive(Clone)]
pub(crate) struct Core {
    executable: PathBuf,
    version: semver::Version,
    managed: bool,
    session: Option<String>,
}

impl Core {
    pub(crate) fn discover() -> Option<Self> {
        discovery::discover()
    }

    pub(crate) fn call(&self, method: &str, params: Value) -> Result<Value> {
        let _guard = self.session.as_ref().map(|_| {
            sessions::ACCESS
                .read()
                .unwrap_or_else(|error| error.into_inner())
        });
        if let Some(session) = &self.session {
            ensure!(
                sessions::exists(session),
                "Herdr Core session no longer exists"
            );
        }
        rpc::call(&self.executable, self.session.as_deref(), method, params)
    }

    fn terminal_stopped(&self, address: &str) -> bool {
        self.call("terminal.list", json!({})).is_ok_and(|snapshot| {
            snapshot["terminals"].as_array().is_some_and(|rows| {
                !rows
                    .iter()
                    .any(|row| row["address"] == address && row["state"] == "live")
            })
        })
    }

    pub(crate) fn live_terminal(&self, address: &str) -> Result<Option<Value>> {
        match self.call("terminal.get", json!({"terminal": address})) {
            Ok(row) if row["state"] == "live" => Ok(Some(row)),
            Ok(row) if row["state"] == "finished" => Ok(None),
            Ok(_) => bail!("Herdr Core did not return a terminal state"),
            Err(_) if self.terminal_stopped(address) => Ok(None),
            Err(error) => Err(error),
        }
    }

    pub(crate) fn stop_terminal(&self, address: &str) -> Result<()> {
        match self.call("terminal.kill", json!({"terminal": address})) {
            Ok(_) => Ok(()),
            // Core occasionally removes an ephemeral terminal before replying.
            Err(_) if self.terminal_stopped(address) => Ok(()),
            Err(error) => Err(error),
        }
    }

    pub(crate) fn installation(&self) -> Result<super::tools::HerdrInstallation> {
        Ok(super::tools::HerdrInstallation {
            path: self.executable.to_string_lossy().into_owned(),
            version: self.version.to_string(),
            managed: self.managed,
        })
    }

    pub(crate) fn agent_argv(
        cwd: &Path,
        mut launch: crate::core::agent_launch_config::Launch,
        prompt: Option<&str>,
    ) -> Result<Vec<String>> {
        let program = crate::core::tool_detection::resolve_program(&launch.program, cwd)
            .context("Configured Agent executable is unavailable")?;
        configure_agent(launch.kind.as_deref(), &mut launch.arguments, 0);
        let mut argv = vec![program
            .to_str()
            .context("Agent executable path must be Unicode")?
            .to_owned()];
        argv.extend(crate::core::agent_launcher::initial_task_arguments(
            &launch, prompt,
        )?);
        Ok(argv)
    }

    pub(crate) fn status(&self) -> Result<Value> {
        let mut command = control_command(&self.executable, self.session.as_deref());
        command.args(["server", "status", "--json"]);
        let (output, _) =
            crate::core::cli_process::capture_prepared(command, "Herdr Core", 5, None)
                .map_err(anyhow::Error::msg)?;
        Ok(serde_json::from_str(&output)?)
    }

    pub(crate) fn run(
        &self,
        cwd: &Path,
        argv: &[String],
        name: Option<&str>,
        labels: Value,
        env: Value,
    ) -> Result<String> {
        let cwd = cwd.to_str().context("Project directory must be Unicode")?;
        self.run_terminal(json!({
            "cwd": cwd,
            "argv": argv,
            "name": name,
            "labels": labels,
            "env": env,
            "no_parent": true,
            "no_notify": true,
        }))
    }

    fn run_terminal(&self, args: Value) -> Result<String> {
        let value = self.call("terminal.run", args)?;
        let address = value["address"]
            .as_str()
            .context("Herdr Core did not return a terminal address")?;
        if !local_address(address) {
            bail!("Herdr Core did not return a local terminal address");
        }
        Ok(address.to_owned())
    }

    pub(crate) fn attach(&self, address: &str) -> Result<CommandBuilder> {
        if !local_address(address) {
            bail!("Invalid local Herdr Core terminal address");
        }
        let mut command = CommandBuilder::new(&self.executable);
        command.args(["attach", "--history", "2000", address]);
        command.env("TERM", "xterm-256color");
        command.env("COLORTERM", "truecolor");
        command.env(VIEWER_ENV, "1");
        clear_context(|key| {
            command.env_remove(key);
        });
        if let Some(session) = &self.session {
            command.env("HC_SESSION", session);
        }
        Ok(command)
    }
}

fn configure_agent(kind: Option<&str>, args: &mut Vec<String>, initial_argument: usize) {
    if kind == Some("codex") && !args.iter().any(|arg| arg == "--no-daemon") {
        args.insert(initial_argument, "--no-daemon".into());
    }
}

pub(super) fn probe_version(executable: &Path) -> Result<semver::Version> {
    let mut command = control_command(executable, None);
    command.arg("--version");
    let (stdout, _) = crate::core::cli_process::capture_prepared(command, "Herdr Core", 2, None)
        .map_err(anyhow::Error::msg)?;
    let version = stdout
        .trim()
        .strip_prefix("hc ")
        .context("The executable is not Herdr Core")?;
    Ok(semver::Version::parse(version)?)
}

fn control_command(executable: &Path, session: Option<&str>) -> Command {
    let mut command = Command::new(executable);
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
    }
    clear_context(|key| {
        command.env_remove(key);
    });
    if let Some(session) = session {
        command.env("HC_SESSION", session);
    }
    command
}

pub(crate) fn local_address(value: &str) -> bool {
    value.strip_prefix('t').is_some_and(|id| {
        !id.is_empty()
            && id.len() <= 32
            && id
                .bytes()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit())
    })
}

pub(super) fn clear_context(mut remove: impl FnMut(&str)) {
    for key in CONTEXT
        .iter()
        .chain(crate::core::agent_runtime::INHERITED_CONTEXT)
    {
        remove(key);
    }
}