Skip to main content

aither_agent/
event.rs

1//! Agent events for streaming execution.
2
3use crate::context_window::ContextWindowPhase;
4use crate::error::AgentError;
5use crate::hook::CheckpointReason;
6use aither_core::llm::ToolResult;
7
8pub use aither_sandbox::BackgroundReason;
9
10/// Reason why an agent run is paused or resumed.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum RunPauseReason {
13    /// Waiting for a terminal permission approval.
14    PermissionRequest,
15    /// Waiting for an `ask_user` response.
16    AskUser,
17    /// Waiting for a `request_workspace` response.
18    WorkspaceRequest,
19}
20
21/// Events emitted during agent execution.
22#[derive(Debug, Clone)]
23pub enum AgentEvent {
24    /// Agent run started with a stable run identifier.
25    RunStart {
26        /// Unique identifier for this run invocation.
27        run_id: String,
28        /// Maximum number of iterations configured for this run.
29        max_iterations: usize,
30    },
31
32    /// Text chunk from the LLM response.
33    Text(String),
34
35    /// Reasoning step (for models with extended thinking).
36    Reasoning(String),
37
38    /// Incremental tool call assembly progress from the model stream.
39    ///
40    /// Emitted as the model streams tool call name and arguments, before the
41    /// full call is assembled. UI layers can use this to show early feedback.
42    ToolCallDelta {
43        /// Tool call identifier.
44        id: String,
45        /// Tool name (may be empty in very early deltas for some providers).
46        name: String,
47        /// Partial JSON arguments accumulated so far.
48        arguments_fragment: String,
49    },
50
51    /// Tool is about to be called.
52    ToolCallStart {
53        /// Unique identifier for this tool call.
54        id: String,
55        /// Name of the tool being called.
56        name: String,
57        /// JSON-encoded arguments.
58        arguments: String,
59    },
60
61    /// Tool execution completed.
62    ToolCallEnd {
63        /// Unique identifier matching the start event.
64        id: String,
65        /// Name of the tool that was called.
66        name: String,
67        /// Structured result of the tool execution.
68        result: ToolResult,
69    },
70
71    /// Agent turn completed (may have more turns if tools were called).
72    TurnComplete {
73        /// The turn number (0-indexed).
74        turn: usize,
75        /// Whether this turn included tool calls.
76        has_tool_calls: bool,
77    },
78
79    /// Runtime checkpoint emitted after mutating agent state.
80    Checkpoint {
81        /// Unique identifier for this run invocation.
82        run_id: String,
83        /// Why the checkpoint was emitted.
84        reason: CheckpointReason,
85        /// Current turn number (1-indexed within the agent loop).
86        turn: usize,
87        /// Current lifecycle phase of the assembled context window.
88        phase: ContextWindowPhase,
89        /// Number of recent conversation messages currently in memory.
90        message_count: usize,
91    },
92
93    /// A terminal command was promoted to a background task.
94    BackgroundTaskStarted {
95        /// Background task identifier.
96        task_id: String,
97        /// Inline preview of current output.
98        output_preview: String,
99        /// File path or URL where full output can be recovered.
100        output_file: String,
101        /// Why the command was moved to the background.
102        reason: BackgroundReason,
103    },
104
105    /// A background task completed and its result was reinjected into context.
106    BackgroundTaskCompleted {
107        /// Background task identifier.
108        task_id: String,
109        /// Structured XML/text payload injected back into context.
110        result: String,
111    },
112
113    /// A terminal task is waiting for stdin from the user or host runtime.
114    TerminalInputNeeded {
115        /// Optional task identifier for the waiting terminal.
116        task_id: Option<String>,
117        /// Human-readable notice explaining why input is needed.
118        notice: String,
119    },
120
121    /// The run is now paused waiting for external input.
122    RunPaused {
123        /// Why the run paused.
124        reason: RunPauseReason,
125        /// Tool call identifier responsible for the pause.
126        tool_call_id: String,
127    },
128
129    /// The run resumed after an external input arrived.
130    RunResumed {
131        /// Why the run had paused.
132        reason: RunPauseReason,
133        /// Tool call identifier responsible for the pause.
134        tool_call_id: String,
135    },
136
137    /// A skill was activated for the current run.
138    SkillActivated {
139        /// Skill name.
140        name: String,
141        /// Explicitly allowed tools declared by the skill.
142        allowed_tools: Option<Vec<String>>,
143        /// Resource files made available by the skill.
144        resource_paths: Option<Vec<String>>,
145    },
146
147    /// Agent finished processing successfully.
148    Complete {
149        /// The final response text.
150        final_text: String,
151        /// Total number of turns taken.
152        turns: usize,
153    },
154
155    /// Token usage information from LLM.
156    Usage(aither_core::llm::Usage),
157
158    /// Error occurred during execution.
159    Error(AgentError),
160}
161
162impl AgentEvent {
163    /// Creates a new run-start event.
164    #[must_use]
165    pub fn run_start(run_id: impl Into<String>, max_iterations: usize) -> Self {
166        Self::RunStart {
167            run_id: run_id.into(),
168            max_iterations,
169        }
170    }
171
172    /// Creates a new text event.
173    #[must_use]
174    pub fn text(content: impl Into<String>) -> Self {
175        Self::Text(content.into())
176    }
177
178    /// Creates a new reasoning event.
179    #[must_use]
180    pub fn reasoning(content: impl Into<String>) -> Self {
181        Self::Reasoning(content.into())
182    }
183
184    /// Creates a new tool call delta event.
185    #[must_use]
186    pub fn tool_delta(
187        id: impl Into<String>,
188        name: impl Into<String>,
189        arguments_fragment: impl Into<String>,
190    ) -> Self {
191        Self::ToolCallDelta {
192            id: id.into(),
193            name: name.into(),
194            arguments_fragment: arguments_fragment.into(),
195        }
196    }
197
198    /// Creates a new tool call start event.
199    #[must_use]
200    pub fn tool_start(
201        id: impl Into<String>,
202        name: impl Into<String>,
203        arguments: impl Into<String>,
204    ) -> Self {
205        Self::ToolCallStart {
206            id: id.into(),
207            name: name.into(),
208            arguments: arguments.into(),
209        }
210    }
211
212    /// Creates a new tool call end event with success.
213    #[must_use]
214    pub fn tool_success(
215        id: impl Into<String>,
216        name: impl Into<String>,
217        result: impl Into<String>,
218    ) -> Self {
219        Self::ToolCallEnd {
220            id: id.into(),
221            name: name.into(),
222            result: ToolResult::text(result),
223        }
224    }
225
226    /// Creates a new tool call end event with failure.
227    #[must_use]
228    pub fn tool_failure(
229        id: impl Into<String>,
230        name: impl Into<String>,
231        error: impl Into<String>,
232    ) -> Self {
233        Self::ToolCallEnd {
234            id: id.into(),
235            name: name.into(),
236            result: ToolResult::error(error),
237        }
238    }
239
240    /// Creates a new turn complete event.
241    #[must_use]
242    pub const fn turn_complete(turn: usize, has_tool_calls: bool) -> Self {
243        Self::TurnComplete {
244            turn,
245            has_tool_calls,
246        }
247    }
248
249    /// Creates a new checkpoint event.
250    #[must_use]
251    pub fn checkpoint(
252        run_id: impl Into<String>,
253        reason: CheckpointReason,
254        turn: usize,
255        phase: ContextWindowPhase,
256        message_count: usize,
257    ) -> Self {
258        Self::Checkpoint {
259            run_id: run_id.into(),
260            reason,
261            turn,
262            phase,
263            message_count,
264        }
265    }
266
267    /// Creates a background-task-started event.
268    #[must_use]
269    pub fn background_task_started(
270        task_id: impl Into<String>,
271        output_preview: impl Into<String>,
272        output_file: impl Into<String>,
273        reason: BackgroundReason,
274    ) -> Self {
275        Self::BackgroundTaskStarted {
276            task_id: task_id.into(),
277            output_preview: output_preview.into(),
278            output_file: output_file.into(),
279            reason,
280        }
281    }
282
283    /// Creates a background-task-completed event.
284    #[must_use]
285    pub fn background_task_completed(
286        task_id: impl Into<String>,
287        result: impl Into<String>,
288    ) -> Self {
289        Self::BackgroundTaskCompleted {
290            task_id: task_id.into(),
291            result: result.into(),
292        }
293    }
294
295    /// Creates a terminal-input-needed event.
296    #[must_use]
297    pub fn terminal_input_needed(task_id: Option<String>, notice: impl Into<String>) -> Self {
298        Self::TerminalInputNeeded {
299            task_id,
300            notice: notice.into(),
301        }
302    }
303
304    /// Creates a run-paused event.
305    #[must_use]
306    pub fn run_paused(reason: RunPauseReason, tool_call_id: impl Into<String>) -> Self {
307        Self::RunPaused {
308            reason,
309            tool_call_id: tool_call_id.into(),
310        }
311    }
312
313    /// Creates a run-resumed event.
314    #[must_use]
315    pub fn run_resumed(reason: RunPauseReason, tool_call_id: impl Into<String>) -> Self {
316        Self::RunResumed {
317            reason,
318            tool_call_id: tool_call_id.into(),
319        }
320    }
321
322    /// Creates a skill-activated event.
323    #[must_use]
324    pub fn skill_activated(
325        name: impl Into<String>,
326        allowed_tools: Option<Vec<String>>,
327        resource_paths: Option<Vec<String>>,
328    ) -> Self {
329        Self::SkillActivated {
330            name: name.into(),
331            allowed_tools,
332            resource_paths,
333        }
334    }
335
336    /// Creates a new completion event.
337    #[must_use]
338    pub fn complete(final_text: impl Into<String>, turns: usize) -> Self {
339        Self::Complete {
340            final_text: final_text.into(),
341            turns,
342        }
343    }
344
345    /// Creates a new error event.
346    #[must_use]
347    pub const fn error(error: AgentError) -> Self {
348        Self::Error(error)
349    }
350
351    /// Returns `true` if this is a completion event.
352    #[must_use]
353    pub const fn is_complete(&self) -> bool {
354        matches!(self, Self::Complete { .. })
355    }
356
357    /// Returns `true` if this is an error event.
358    #[must_use]
359    pub const fn is_error(&self) -> bool {
360        matches!(self, Self::Error(_))
361    }
362
363    /// Returns `true` if this is a terminal event (complete or error).
364    #[must_use]
365    pub const fn is_terminal(&self) -> bool {
366        self.is_complete() || self.is_error()
367    }
368}