use core::time::Duration;
use std::fmt;
use aither_core::llm::tool::{ApprovalKind, Progress};
use aither_core::llm::{ToolCallId, ToolResult, Usage};
use jiff::Timestamp;
use crate::context_window::ContextWindowPhase;
use crate::error::AgentError;
pub use aither_core::llm::AgentPath;
macro_rules! text_id {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct $name(String);
impl $name {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
};
}
macro_rules! counter_id {
($(#[$meta:meta])* $name:ident($inner:ty)) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct $name($inner);
impl $name {
#[must_use]
pub const fn new(id: $inner) -> Self {
Self(id)
}
#[must_use]
pub const fn get(self) -> $inner {
self.0
}
}
impl fmt::Display for $name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
};
}
text_id! {
RunId
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct SourceId(String);
impl SourceId {
#[must_use]
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for SourceId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
counter_id! {
RequestId(u64)
}
counter_id! {
BlockId(u32)
}
counter_id! {
PauseId(u64)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum OutputKind {
Text,
Reasoning,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ToolOrigin {
Local,
Hosted,
}
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum ToolVerdict {
Allowed,
Denied {
reason: String,
},
Rewritten,
AwaitingApproval,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum RunPause {
ContextExhausted,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum RunOutcome {
Completed {
final_text: String,
},
Paused {
pause: RunPause,
},
Cancelled,
Failed {
error: AgentError,
},
IterationLimit,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum RequestOutcome {
Completed,
Retrying {
error: AgentError,
retry: u32,
max_retries: u32,
delay: Duration,
},
Failed {
error: AgentError,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum CompactionTrigger {
Requested,
WindowFilling,
PausePoint,
Idle,
ColdCache,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum CompactionOutcome {
Applied(crate::CompactResult),
NothingToCompact,
Failed(AgentError),
Discarded,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum InjectionKind {
Stable,
Tail,
LiveChange,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum CheckpointReason {
TurnBoundary,
Stop,
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum AgentEvent {
#[non_exhaustive]
RunStarted {
run: RunId,
agent: AgentPath,
},
#[non_exhaustive]
RunEnded {
run: RunId,
outcome: RunOutcome,
},
#[non_exhaustive]
TurnStarted {
run: RunId,
turn: usize,
},
#[non_exhaustive]
TurnEnded {
run: RunId,
turn: usize,
tool_calls: usize,
},
#[non_exhaustive]
RequestStarted {
request: RequestId,
prefix: crate::context::PromptPrefix,
},
#[non_exhaustive]
RequestEnded {
request: RequestId,
usage: Option<Usage>,
outcome: RequestOutcome,
},
#[non_exhaustive]
BlockDelta {
request: RequestId,
block: BlockId,
kind: OutputKind,
text: String,
},
#[non_exhaustive]
BlockEnded {
request: RequestId,
block: BlockId,
kind: OutputKind,
},
#[non_exhaustive]
ToolCallDelta {
call: ToolCallId,
name: String,
arguments_fragment: String,
},
#[non_exhaustive]
ToolCallStarted {
call: ToolCallId,
name: String,
arguments: serde_json::Value,
origin: ToolOrigin,
},
#[non_exhaustive]
ToolCallDecided {
call: ToolCallId,
decision: ToolVerdict,
},
#[non_exhaustive]
ToolProgress {
call: ToolCallId,
progress: Progress,
},
#[non_exhaustive]
ToolCallEnded {
call: ToolCallId,
result: ToolResult,
},
#[non_exhaustive]
Paused {
pause: PauseId,
call: Option<ToolCallId>,
kind: ApprovalKind,
subject: String,
},
#[non_exhaustive]
Resumed {
pause: PauseId,
},
#[non_exhaustive]
CompactionStarted {
trigger: CompactionTrigger,
},
#[non_exhaustive]
CompactionEnded {
outcome: CompactionOutcome,
},
#[non_exhaustive]
CompactionRecovery {
error: AgentError,
alerts_removed: usize,
outputs_spilled: usize,
},
#[non_exhaustive]
ContextInjected {
source: SourceId,
kind: InjectionKind,
},
#[non_exhaustive]
SubagentStarted {
child: AgentPath,
name: String,
prompt: String,
},
#[non_exhaustive]
SubagentEnded {
child: AgentPath,
outcome: RunOutcome,
},
#[non_exhaustive]
Checkpoint {
run: RunId,
reason: CheckpointReason,
turn: usize,
phase: ContextWindowPhase,
message_count: usize,
},
}
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct TimedEvent {
pub at: Timestamp,
pub agent: AgentPath,
pub event: AgentEvent,
}
impl TimedEvent {
#[must_use]
pub fn now(agent: AgentPath, event: AgentEvent) -> Self {
Self {
at: Timestamp::now(),
agent,
event,
}
}
}
impl AgentEvent {
#[must_use]
pub const fn run_started(run: RunId, agent: AgentPath) -> Self {
Self::RunStarted { run, agent }
}
#[must_use]
pub const fn run_ended(run: RunId, outcome: RunOutcome) -> Self {
Self::RunEnded { run, outcome }
}
#[must_use]
pub const fn block_delta(
request: RequestId,
block: BlockId,
kind: OutputKind,
text: String,
) -> Self {
Self::BlockDelta {
request,
block,
kind,
text,
}
}
#[must_use]
pub const fn block_ended(request: RequestId, block: BlockId, kind: OutputKind) -> Self {
Self::BlockEnded {
request,
block,
kind,
}
}
#[must_use]
pub const fn tool_call_started(
call: ToolCallId,
name: String,
arguments: serde_json::Value,
origin: ToolOrigin,
) -> Self {
Self::ToolCallStarted {
call,
name,
arguments,
origin,
}
}
#[must_use]
pub const fn tool_call_decided(call: ToolCallId, decision: ToolVerdict) -> Self {
Self::ToolCallDecided { call, decision }
}
#[must_use]
pub const fn tool_progress(call: ToolCallId, progress: Progress) -> Self {
Self::ToolProgress { call, progress }
}
#[must_use]
pub const fn tool_call_ended(call: ToolCallId, result: ToolResult) -> Self {
Self::ToolCallEnded { call, result }
}
}
impl AgentEvent {
#[must_use]
pub const fn run(&self) -> Option<&RunId> {
match self {
Self::RunStarted { run, .. }
| Self::RunEnded { run, .. }
| Self::TurnStarted { run, .. }
| Self::TurnEnded { run, .. }
| Self::Checkpoint { run, .. } => Some(run),
_ => None,
}
}
}
#[cfg(all(test, feature = "serde"))]
mod serde_tests {
use aither_core::llm::tool::{ApprovalError, ApproverFailure};
use aither_core::llm::{Failure, Message};
use std::sync::Arc;
use super::*;
use crate::context::{PrefixChain, PrefixRewrites, PromptPrefix};
fn call() -> ToolCallId {
ToolCallId::new("call-1")
}
fn errors() -> Vec<AgentError> {
vec![
AgentError::Llm {
message: "overloaded".into(),
failure: Failure::transient().with_retry_after(Some(Duration::from_secs(5))),
},
AgentError::ToolExecution {
name: "terminal".into(),
error: "exit 1".into(),
},
AgentError::MaxIterations { limit: 8 },
AgentError::HookRejected {
hook: "before_tool".into(),
reason: "no".into(),
},
AgentError::ToolNotFound { name: "x".into() },
AgentError::Config("bad".into()),
AgentError::Approval(Arc::new(ApprovalError::NoApprover {
kind: ApprovalKind::new("run"),
})),
AgentError::Approval(Arc::new(ApprovalError::Failed {
kind: ApprovalKind::new("run"),
failure: ApproverFailure::new(std::io::Error::other("closed")),
})),
AgentError::Approval(Arc::new(ApprovalError::Cancelled)),
AgentError::Cancelled,
AgentError::Paused(RunPause::ContextExhausted),
]
}
fn outcomes() -> Vec<RunOutcome> {
let mut all = vec![
RunOutcome::Completed {
final_text: "done".into(),
},
RunOutcome::Paused {
pause: RunPause::ContextExhausted,
},
RunOutcome::Cancelled,
RunOutcome::IterationLimit,
];
all.extend(
errors()
.into_iter()
.map(|error| RunOutcome::Failed { error }),
);
all
}
#[allow(clippy::too_many_lines)]
fn events() -> Vec<AgentEvent> {
let run = || RunId::new("run-1");
let request = || RequestId::new(3);
let child = || AgentPath::main().child("reviewer");
let mut all = vec![
AgentEvent::RunStarted {
run: run(),
agent: child(),
},
AgentEvent::TurnStarted {
run: run(),
turn: 1,
},
AgentEvent::TurnEnded {
run: run(),
turn: 1,
tool_calls: 2,
},
AgentEvent::RequestStarted {
request: request(),
prefix: PromptPrefix {
chain: PrefixChain::of(&[], &[Message::user("hello")]),
rewrites: PrefixRewrites {
compacted: true,
reassembled: false,
},
first_request: true,
},
},
AgentEvent::RequestEnded {
request: request(),
usage: Some(Usage {
prompt_tokens: Some(10),
..Usage::default()
}),
outcome: RequestOutcome::Completed,
},
AgentEvent::BlockDelta {
request: request(),
block: BlockId::new(0),
kind: OutputKind::Reasoning,
text: "hm".into(),
},
AgentEvent::BlockEnded {
request: request(),
block: BlockId::new(0),
kind: OutputKind::Text,
},
AgentEvent::ToolCallDelta {
call: call(),
name: "terminal".into(),
arguments_fragment: "{\"cmd".into(),
},
AgentEvent::ToolCallStarted {
call: call(),
name: "terminal".into(),
arguments: serde_json::json!({"cmd": "ls"}),
origin: ToolOrigin::Hosted,
},
AgentEvent::ToolProgress {
call: call(),
progress: Progress::new(1.0),
},
AgentEvent::ToolCallEnded {
call: call(),
result: ToolResult::text("ok"),
},
AgentEvent::Paused {
pause: PauseId::new(1),
call: Some(call()),
kind: ApprovalKind::new("run"),
subject: "rm -rf".into(),
},
AgentEvent::Resumed {
pause: PauseId::new(1),
},
AgentEvent::CompactionStarted {
trigger: CompactionTrigger::ColdCache,
},
AgentEvent::CompactionRecovery {
error: AgentError::Cancelled,
alerts_removed: 1,
outputs_spilled: 2,
},
AgentEvent::ContextInjected {
source: SourceId::new("memory"),
kind: InjectionKind::LiveChange,
},
AgentEvent::SubagentStarted {
child: child(),
name: "reviewer".into(),
prompt: "look".into(),
},
AgentEvent::Checkpoint {
run: run(),
reason: CheckpointReason::Stop,
turn: 2,
phase: ContextWindowPhase::Stable,
message_count: 4,
},
];
for decision in [
ToolVerdict::Allowed,
ToolVerdict::Denied {
reason: "nope".into(),
},
ToolVerdict::Rewritten,
ToolVerdict::AwaitingApproval,
] {
all.push(AgentEvent::ToolCallDecided {
call: call(),
decision,
});
}
for outcome in outcomes() {
all.push(AgentEvent::RunEnded {
run: run(),
outcome: outcome.clone(),
});
all.push(AgentEvent::SubagentEnded {
child: child(),
outcome,
});
}
for error in errors() {
all.push(AgentEvent::RequestEnded {
request: request(),
usage: None,
outcome: RequestOutcome::Failed {
error: error.clone(),
},
});
all.push(AgentEvent::CompactionEnded {
outcome: CompactionOutcome::Failed(error),
});
}
all.push(AgentEvent::RequestEnded {
request: request(),
usage: None,
outcome: RequestOutcome::Retrying {
error: AgentError::llm_local("x"),
retry: 1,
max_retries: 3,
delay: Duration::from_millis(1500),
},
});
all.push(AgentEvent::CompactionEnded {
outcome: CompactionOutcome::Applied(crate::CompactResult {
messages_compacted: 5,
messages_remaining: 2,
summary: "s".into(),
}),
});
all.push(AgentEvent::CompactionEnded {
outcome: CompactionOutcome::NothingToCompact,
});
all.push(AgentEvent::CompactionEnded {
outcome: CompactionOutcome::Discarded,
});
all
}
#[test]
fn every_event_survives_a_round_trip() {
let at = Timestamp::from_second(1_700_000_000).expect("a valid timestamp");
for event in events() {
let timed = TimedEvent {
at,
agent: AgentPath::main().child("reviewer"),
event,
};
let text = serde_json::to_string(&timed).expect("serializes");
let back: TimedEvent = serde_json::from_str(&text).expect("deserializes");
assert_eq!(back.at, timed.at, "{text}");
assert_eq!(back.agent, timed.agent, "{text}");
assert_eq!(
serde_json::to_string(&back).expect("serializes again"),
text,
"a decoded event encodes to the same text"
);
assert_eq!(format!("{:?}", back.event), format!("{:?}", timed.event));
}
}
}