use aither_sandbox::{AnyCommandObserver, CommandCall, CommandObserver};
use askama::Template;
use executor_core::Executor;
use serde::{Deserialize, Serialize};
use super::live::{LiveHooks, UserPause};
use super::runner::{HookCommand, HookRole};
use crate::StopReason;
use crate::ask_user::{AskUserBroker, Question, QuestionAnswer};
use crate::hook::Hook;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum LifecycleKind {
SessionStart,
BeforeCompaction,
AfterCompaction,
Stop,
UserMessage,
SubagentStart,
SubagentStop,
AskUser,
CommandCall,
}
impl LifecycleKind {
pub(super) const fn occasion(self) -> &'static str {
match self {
Self::SessionStart => "the session started",
Self::BeforeCompaction => "a compaction was about to start",
Self::AfterCompaction => "a compaction finished",
Self::Stop => "a run stopped",
Self::UserMessage => "the user sent a message",
Self::SubagentStart => "a subagent was about to run",
Self::SubagentStop => "a subagent finished running",
Self::AskUser => "the user answered a question",
Self::CommandCall => "a command was called",
}
}
}
pub trait LifecyclePayload: Serialize + Send + Sync {
const KIND: LifecycleKind;
}
#[derive(Debug, Serialize)]
pub struct HookInput<'a, Payload> {
pub event: LifecycleKind,
pub role: HookRole,
#[serde(flatten)]
pub payload: &'a Payload,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LifecycleOutput {
#[serde(default)]
pub context: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct SessionStart {}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct BeforeCompaction {
pub messages: usize,
pub focus: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct AfterCompaction {
pub messages_remaining: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct Stop {
pub final_text: String,
pub turns: usize,
pub reason: StopReason,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct UserMessage {
pub message: String,
pub attachments: usize,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct SubagentStart {
pub subagent: String,
pub prompt: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum SubagentEnd {
Completed,
Failed,
Cancelled,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct SubagentStop {
pub subagent: String,
pub end: SubagentEnd,
pub result: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct AskUser {
pub questions: Vec<Question>,
pub answers: Vec<QuestionAnswer>,
}
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
pub struct CommandCalled {
pub name: String,
pub args: Vec<String>,
pub ok: bool,
pub output: Option<String>,
pub error: Option<String>,
}
macro_rules! payloads {
($($payload:ident => $kind:ident),* $(,)?) => {
$(impl LifecyclePayload for $payload {
const KIND: LifecycleKind = LifecycleKind::$kind;
})*
};
}
payloads! {
SessionStart => SessionStart,
BeforeCompaction => BeforeCompaction,
AfterCompaction => AfterCompaction,
Stop => Stop,
UserMessage => UserMessage,
SubagentStart => SubagentStart,
SubagentStop => SubagentStop,
AskUser => AskUser,
CommandCalled => CommandCall,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LifecycleHookConfig {
pub name: String,
#[serde(flatten)]
pub command: HookCommand,
pub events: Vec<LifecycleKind>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InjectedContext {
hook: String,
event: LifecycleKind,
context: String,
}
#[derive(Template)]
#[template(path = "lifecycle_context.txt", escape = "none")]
struct LifecycleContextTemplate<'a> {
hook: &'a str,
event: &'a str,
context: &'a str,
}
impl InjectedContext {
#[must_use]
pub fn alert_text(&self) -> String {
LifecycleContextTemplate {
hook: &self.hook,
event: self.event.occasion(),
context: &self.context,
}
.render()
.expect("lifecycle context template must render")
}
}
#[derive(Debug, Clone)]
pub struct ExternalHooks {
live: LiveHooks,
role: HookRole,
user: Option<UserPause>,
inbox: async_channel::Sender<InjectedContext>,
outbox: async_channel::Receiver<InjectedContext>,
}
impl ExternalHooks {
#[must_use]
pub fn new(live: &LiveHooks) -> Self {
Self::scope(live.clone(), HookRole::Main, None)
}
#[must_use]
pub fn none() -> Self {
Self::new(&LiveHooks::none())
}
#[must_use]
pub fn with_user_pause(mut self, broker: AskUserBroker, session_id: impl Into<String>) -> Self {
self.user = Some(UserPause::new(broker, session_id.into()));
self
}
pub(super) const fn live(&self) -> &LiveHooks {
&self.live
}
pub(super) const fn user(&self) -> Option<&UserPause> {
self.user.as_ref()
}
fn scope(live: LiveHooks, role: HookRole, user: Option<UserPause>) -> Self {
let (inbox, outbox) = async_channel::unbounded();
Self {
live,
role,
user,
inbox,
outbox,
}
}
#[must_use]
pub fn for_subagent(&self) -> Self {
Self::scope(self.live.clone(), HookRole::Subagent, self.user.clone())
}
#[must_use]
pub const fn role(&self) -> HookRole {
self.role
}
pub async fn fire<P: LifecyclePayload>(&self, payload: &P) {
let input = HookInput {
event: P::KIND,
role: self.role,
payload,
};
let set = self.live.set();
let runs = set
.lifecycle
.iter()
.filter(|hook| hook.config.events.contains(&P::KIND))
.filter_map(|hook| Some((hook, hook.current.as_ref()?)))
.map(|(hook, version)| {
let input = &input;
async move {
let answer = self
.live
.runner()
.run::<_, LifecycleOutput>(&version.command, input)
.await;
(&hook.config, answer)
}
});
for (hook, answer) in futures::future::join_all(runs).await {
match answer {
Ok(Some(LifecycleOutput {
context: Some(context),
})) if !context.trim().is_empty() => {
self.inbox
.try_send(InjectedContext {
hook: hook.name.clone(),
event: P::KIND,
context,
})
.expect("the scope holds its own inbox open");
}
Ok(_) => {}
Err(error) => tracing::warn!(
hook = %hook.name,
event = ?P::KIND,
%error,
"lifecycle hook failed; its result is ignored"
),
}
}
}
#[cfg(test)]
pub(super) fn queued(&self) -> usize {
self.outbox.len()
}
fn drain(&self) -> Vec<InjectedContext> {
std::iter::from_fn(|| self.outbox.try_recv().ok()).collect()
}
}
impl Hook for ExternalHooks {
fn on_lifecycle<P: LifecyclePayload>(
&self,
payload: &P,
) -> impl std::future::Future<Output = ()> + Send {
self.fire(payload)
}
fn take_injected_context(&self) -> Vec<InjectedContext> {
self.drain()
}
}
impl CommandObserver for ExternalHooks {
async fn command_called(&self, call: &CommandCall<'_>) {
if !self
.live
.set()
.lifecycle
.iter()
.any(|hook| hook.config.events.contains(&LifecycleKind::CommandCall))
{
return;
}
let payload = CommandCalled {
name: call.name.to_string(),
args: call.args.to_vec(),
ok: call.outcome.ok,
output: call
.outcome
.payload
.as_ref()
.map(aither_sandbox::CommandPayload::render_for_cli),
error: call.outcome.error.clone(),
};
let hooks = self.clone();
self.live
.executor()
.expect("a scope with hooks has an executor")
.spawn(async move { hooks.fire(&payload).await })
.detach();
}
}
impl ExternalHooks {
#[must_use]
pub fn command_observer(&self) -> AnyCommandObserver {
AnyCommandObserver::new(self.clone())
}
#[must_use]
pub fn of_observer(observer: Option<&AnyCommandObserver>) -> Option<Self> {
observer?.downcast_ref::<Self>().cloned()
}
}