use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::{
path::Path,
process::{Command, Stdio},
sync::Mutex,
time::{Duration, Instant},
};
pub(crate) const SESSION: &str = "default";
pub(crate) static WORKSPACE_ROUTING: Mutex<()> = Mutex::new(());
static SERVER_START: Mutex<()> = Mutex::new(());
pub(crate) use crate::core::agent_runtime::INHERITED_CONTEXT;
pub(crate) struct Client<'a> {
pub executable: &'a Path,
pub cwd: &'a Path,
}
impl Client<'_> {
pub fn command(&self) -> Command {
self.transport().command()
}
pub fn call(&self, args: &[&str], timeout: u64) -> Result<Value> {
self.transport().call(args, timeout)
}
fn transport(&self) -> super::client::Client<'_> {
super::client::Client {
executable: self.executable,
session: Some(SESSION),
cwd: Some(self.cwd),
}
}
pub fn ensure_server(&self) -> Result<()> {
let _guard = SERVER_START
.lock()
.unwrap_or_else(|error| error.into_inner());
let sessions = self.call(&["session", "list", "--json"], 5)?;
if sessions["sessions"].as_array().is_some_and(|sessions| {
sessions
.iter()
.any(|session| session["name"] == SESSION && session["running"] == true)
}) {
return Ok(());
}
let mut server = self.command();
server
.arg("server")
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null());
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
server.process_group(0);
}
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
server.creation_flags(0x08000000);
}
spawn_server(server)?;
let deadline = Instant::now() + Duration::from_secs(8);
while Instant::now() < deadline {
if self.call(&["workspace", "list"], 1).is_ok() {
return Ok(());
}
std::thread::sleep(Duration::from_millis(100));
}
bail!("Herdr session default did not become ready; open it in Herdr and retry")
}
}
pub(crate) fn spawn_server(mut server: Command) -> Result<()> {
let mut child = server.spawn().context("Cannot start the Herdr session")?;
std::thread::spawn(move || {
let _ = child.wait();
});
Ok(())
}