use std::path::PathBuf;
use std::process::{ExitStatus, Stdio};
use std::time::Duration;
use aither_sandbox::{PreparedTools, ToolRuntimeError};
use futures_lite::io::{AsyncReadExt, AsyncWriteExt};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HookCommand {
pub command: Vec<String>,
pub deadline_ms: u64,
}
impl HookCommand {
#[must_use]
pub const fn deadline(&self) -> Duration {
Duration::from_millis(self.deadline_ms)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum HookRole {
Main,
Subagent,
}
#[derive(Debug, thiserror::Error)]
pub enum HookRunError {
#[error("the hook command is empty")]
EmptyCommand,
#[error("the prepared tools cannot be put on the hook's PATH: {0}")]
ToolPath(#[source] ToolRuntimeError),
#[error("the hook input cannot be serialized: {0}")]
Input(#[source] serde_json::Error),
#[error("the hook `{program}` cannot be started: {source}")]
Spawn {
program: String,
#[source]
source: std::io::Error,
},
#[error("talking to the hook failed: {0}")]
Io(#[source] std::io::Error),
#[error("the hook ran past its {deadline:?} deadline and was killed")]
Timeout {
deadline: Duration,
},
#[error("the hook exited with {status}: {stderr}")]
Exit {
status: ExitStatus,
stderr: String,
},
#[error("the hook printed output that is not a valid answer: {0}")]
Output(#[source] serde_json::Error),
}
#[derive(Debug, Clone)]
pub struct HookRunner {
tools: Option<PreparedTools<PathBuf>>,
}
impl HookRunner {
#[must_use]
pub fn new(tools: &PreparedTools<PathBuf>) -> Self {
Self {
tools: Some(tools.clone()),
}
}
pub(super) const fn without_hooks() -> Self {
Self { tools: None }
}
pub(super) const fn has_tools(&self) -> bool {
self.tools.is_some()
}
pub async fn run<Input, Output>(
&self,
hook: &HookCommand,
input: &Input,
) -> Result<Option<Output>, HookRunError>
where
Input: Serialize + Sync,
Output: DeserializeOwned,
{
let input = serde_json::to_vec(input).map_err(HookRunError::Input)?;
let stdout = self.run_raw(hook, &input).await?;
if stdout.trim_ascii().is_empty() {
return Ok(None);
}
serde_json::from_slice(&stdout)
.map(Some)
.map_err(HookRunError::Output)
}
async fn run_raw(&self, hook: &HookCommand, input: &[u8]) -> Result<Vec<u8>, HookRunError> {
let (program, args) = hook
.command
.split_first()
.ok_or(HookRunError::EmptyCommand)?;
let mut command = std::process::Command::new(program);
command.args(args);
if let Some(tools) = &self.tools {
command.env(
"PATH",
tools
.prepend_path(std::env::var_os("PATH").as_deref())
.map_err(HookRunError::ToolPath)?,
);
}
#[cfg(unix)]
std::os::unix::process::CommandExt::process_group(&mut command, 0);
let mut child = async_process::Command::from(command)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true)
.spawn()
.map_err(|source| HookRunError::Spawn {
program: program.clone(),
source,
})?;
let pid = child.id();
let mut stdin = child.stdin.take().expect("the hook's stdin is piped");
let mut stdout = child.stdout.take().expect("the hook's stdout is piped");
let mut stderr = child.stderr.take().expect("the hook's stderr is piped");
let exchange = async {
let write = async {
let written = stdin.write_all(input).await;
drop(stdin);
match written {
Err(error) if error.kind() != std::io::ErrorKind::BrokenPipe => Err(error),
_ => Ok(()),
}
};
let read = async {
let mut output = Vec::new();
stdout.read_to_end(&mut output).await.map(|_| output)
};
let diagnostics = async {
let mut output = Vec::new();
stderr.read_to_end(&mut output).await.map(|_| output)
};
let (written, output, diagnostics, status) =
futures::join!(write, read, diagnostics, child.status());
written.map_err(HookRunError::Io)?;
let output = output.map_err(HookRunError::Io)?;
let diagnostics = diagnostics.map_err(HookRunError::Io)?;
let status = status.map_err(HookRunError::Io)?;
if status.success() {
Ok(output)
} else {
Err(HookRunError::Exit {
status,
stderr: String::from_utf8_lossy(&diagnostics).trim().to_string(),
})
}
};
let deadline = hook.deadline();
let expiry = async {
async_io::Timer::after(deadline).await;
Err(HookRunError::Timeout { deadline })
};
let result = futures_lite::future::or(exchange, expiry).await;
if matches!(result, Err(HookRunError::Timeout { .. }))
&& let Err(error) = aither_sandbox::kill_process_tree(pid).await
{
tracing::warn!(%error, "the hook's process tree could not be killed");
}
result
}
}