aither-agent 0.18.0

AI agent framework with planning, memory, and tool execution for aither
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! Agent events for streaming execution.

use crate::context_window::ContextWindowPhase;
use crate::error::AgentError;
use crate::hook::CheckpointReason;
use aither_core::llm::ToolResult;
use jiff::Timestamp;

/// An [`AgentEvent`] together with the UTC time it was emitted.
///
/// The time is taken at the emission point inside the run, not when the
/// consumer reads the event.
#[derive(Debug, Clone)]
pub struct TimedEvent {
    /// When the agent emitted the event.
    pub at: Timestamp,
    /// The event itself.
    pub event: AgentEvent,
}

/// Reason why an agent run is paused or resumed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RunPauseReason {
    /// Waiting for a terminal permission approval.
    PermissionRequest,
    /// Waiting for an `ask_user` response.
    AskUser,
    /// Waiting for a `request_workspace` response.
    WorkspaceRequest,
    /// The context window is full and the run cannot continue.
    ///
    /// Emitted when usage reaches the
    /// [pause point](crate::ContextPolicy::pause_point) and no compaction can
    /// relieve it: there was nothing to compact, or the compaction landed and
    /// the window is still full. Sending the request anyway would have the
    /// provider reject it for length, so the run stops with the reason named
    /// instead. A compaction that fails twice is an error, not this pause.
    ContextExhausted,
}

/// Events emitted during agent execution.
#[derive(Debug, Clone)]
pub enum AgentEvent {
    /// Agent run started with a stable run identifier.
    RunStart {
        /// Unique identifier for this run invocation.
        run_id: String,
        /// Maximum number of iterations configured for this run.
        max_iterations: usize,
    },

    /// Text chunk from the LLM response.
    Text(String),

    /// The reply just streamed was not in the communication language: show
    /// this translation of it instead, marked as translated.
    ///
    /// The model's history keeps the original reply.
    ReplyTranslated {
        /// The reply translated into `language` by the fast model.
        text: String,
        /// The communication language's ISO 639-3 code.
        language: String,
    },

    /// Reasoning step (for models with extended thinking).
    Reasoning(String),

    /// Incremental tool call assembly progress from the model stream.
    ///
    /// Emitted as the model streams tool call name and arguments, before the
    /// full call is assembled. UI layers can use this to show early feedback.
    ToolCallDelta {
        /// Tool call identifier.
        id: String,
        /// Tool name (may be empty in very early deltas for some providers).
        name: String,
        /// Incremental JSON arguments fragment for this delta.
        arguments_fragment: String,
    },

    /// Tool is about to be called.
    ToolCallStart {
        /// Unique identifier for this tool call.
        id: String,
        /// Name of the tool being called.
        name: String,
        /// JSON-encoded arguments.
        arguments: String,
    },

    /// Tool execution completed.
    ToolCallEnd {
        /// Unique identifier matching the start event.
        id: String,
        /// Name of the tool that was called.
        name: String,
        /// Structured result of the tool execution.
        result: ToolResult,
    },

    /// A provider-hosted (server-side) tool call began.
    ///
    /// The provider executes these itself — nothing runs locally — but the
    /// call is part of the visible stream so UIs can show it live.
    BuiltInToolCall {
        /// Provider-assigned call identifier (may be empty).
        id: String,
        /// Hosted tool name (e.g. `web_search`).
        tool: String,
        /// Invocation detail — query, URL or code — as known at emit time.
        detail: String,
    },

    /// A provider-hosted (server-side) tool call produced a result.
    BuiltInToolResult {
        /// Call identifier matching the start event (may be empty).
        id: String,
        /// Hosted tool name.
        tool: String,
        /// Result summary.
        result: String,
    },

    /// Agent turn completed (may have more turns if tools were called).
    TurnComplete {
        /// The turn number (0-indexed).
        turn: usize,
        /// Whether this turn included tool calls.
        has_tool_calls: bool,
    },

    /// Runtime checkpoint emitted after mutating agent state.
    Checkpoint {
        /// Unique identifier for this run invocation.
        run_id: String,
        /// Why the checkpoint was emitted.
        reason: CheckpointReason,
        /// Current turn number (1-indexed within the agent loop).
        turn: usize,
        /// Current lifecycle phase of the assembled context window.
        phase: ContextWindowPhase,
        /// Number of recent conversation messages currently in memory.
        message_count: usize,
    },

    /// A terminal command was promoted to a background task.
    BackgroundTaskStarted {
        /// Background task identifier.
        task_id: String,
        /// Inline preview of current output.
        output_preview: String,
        /// File path or URL where full output can be recovered.
        output_file: String,
    },

    /// A background task completed and its result was reinjected into context.
    BackgroundTaskCompleted {
        /// Background task identifier.
        task_id: String,
        /// Structured XML/text payload injected back into context.
        result: String,
    },

    /// The run is now paused waiting for external input.
    RunPaused {
        /// Why the run paused.
        reason: RunPauseReason,
        /// Tool call identifier responsible for the pause.
        tool_call_id: String,
    },

    /// The run resumed after an external input arrived.
    RunResumed {
        /// Why the run had paused.
        reason: RunPauseReason,
        /// Tool call identifier responsible for the pause.
        tool_call_id: String,
    },

    /// A compaction failed with the window at the
    /// [pause point](crate::ContextPolicy::pause_point), so the context was
    /// cleaned and the compaction reruns on it now.
    ///
    /// The cleanup removes system alerts and reminders and moves long tool
    /// outputs to files. When the rerun fails too the run ends with its
    /// [`Error`](Self::Error); otherwise the run continues on the compacted
    /// window.
    CompactionRecovery {
        /// Why the compaction failed.
        error: AgentError,
        /// System alerts and reminders the cleanup removed.
        alerts_removed: usize,
        /// Long tool outputs the cleanup moved to files.
        outputs_spilled: usize,
    },

    /// A skill was activated for the current run.
    SkillActivated {
        /// Skill name.
        name: String,
        /// Explicitly allowed tools declared by the skill.
        allowed_tools: Option<Vec<String>>,
        /// Resource files made available by the skill.
        resource_paths: Option<Vec<String>>,
    },

    /// Agent finished processing successfully.
    Complete {
        /// The final response text.
        final_text: String,
        /// Total number of turns taken.
        turns: usize,
    },

    /// Token usage information from LLM.
    Usage(aither_core::llm::Usage),

    /// Error occurred during execution.
    Error(AgentError),
}

impl AgentEvent {
    /// Creates a new run-start event.
    #[must_use]
    pub fn run_start(run_id: impl Into<String>, max_iterations: usize) -> Self {
        Self::RunStart {
            run_id: run_id.into(),
            max_iterations,
        }
    }

    /// Creates a new text event.
    #[must_use]
    pub fn text(content: impl Into<String>) -> Self {
        Self::Text(content.into())
    }

    /// Creates a new reasoning event.
    #[must_use]
    pub fn reasoning(content: impl Into<String>) -> Self {
        Self::Reasoning(content.into())
    }

    /// Creates a new tool call delta event.
    #[must_use]
    pub fn tool_delta(
        id: impl Into<String>,
        name: impl Into<String>,
        arguments_fragment: impl Into<String>,
    ) -> Self {
        Self::ToolCallDelta {
            id: id.into(),
            name: name.into(),
            arguments_fragment: arguments_fragment.into(),
        }
    }

    /// Creates a new tool call start event.
    #[must_use]
    pub fn tool_start(
        id: impl Into<String>,
        name: impl Into<String>,
        arguments: impl Into<String>,
    ) -> Self {
        Self::ToolCallStart {
            id: id.into(),
            name: name.into(),
            arguments: arguments.into(),
        }
    }

    /// Creates a new tool call end event with success.
    #[must_use]
    pub fn tool_success(
        id: impl Into<String>,
        name: impl Into<String>,
        result: impl Into<String>,
    ) -> Self {
        Self::ToolCallEnd {
            id: id.into(),
            name: name.into(),
            result: ToolResult::text(result),
        }
    }

    /// Creates a new tool call end event with failure.
    #[must_use]
    pub fn tool_failure(
        id: impl Into<String>,
        name: impl Into<String>,
        error: impl Into<String>,
    ) -> Self {
        Self::ToolCallEnd {
            id: id.into(),
            name: name.into(),
            result: ToolResult::error(error),
        }
    }

    /// Creates a new turn complete event.
    #[must_use]
    pub const fn turn_complete(turn: usize, has_tool_calls: bool) -> Self {
        Self::TurnComplete {
            turn,
            has_tool_calls,
        }
    }

    /// Creates a new checkpoint event.
    #[must_use]
    pub fn checkpoint(
        run_id: impl Into<String>,
        reason: CheckpointReason,
        turn: usize,
        phase: ContextWindowPhase,
        message_count: usize,
    ) -> Self {
        Self::Checkpoint {
            run_id: run_id.into(),
            reason,
            turn,
            phase,
            message_count,
        }
    }

    /// Creates a background-task-started event.
    #[must_use]
    pub fn background_task_started(
        task_id: impl Into<String>,
        output_preview: impl Into<String>,
        output_file: impl Into<String>,
    ) -> Self {
        Self::BackgroundTaskStarted {
            task_id: task_id.into(),
            output_preview: output_preview.into(),
            output_file: output_file.into(),
        }
    }

    /// Creates a background-task-completed event.
    #[must_use]
    pub fn background_task_completed(
        task_id: impl Into<String>,
        result: impl Into<String>,
    ) -> Self {
        Self::BackgroundTaskCompleted {
            task_id: task_id.into(),
            result: result.into(),
        }
    }

    /// Creates a run-paused event.
    #[must_use]
    pub fn run_paused(reason: RunPauseReason, tool_call_id: impl Into<String>) -> Self {
        Self::RunPaused {
            reason,
            tool_call_id: tool_call_id.into(),
        }
    }

    /// Creates a run-resumed event.
    #[must_use]
    pub fn run_resumed(reason: RunPauseReason, tool_call_id: impl Into<String>) -> Self {
        Self::RunResumed {
            reason,
            tool_call_id: tool_call_id.into(),
        }
    }

    /// Creates a skill-activated event.
    #[must_use]
    pub fn skill_activated(
        name: impl Into<String>,
        allowed_tools: Option<Vec<String>>,
        resource_paths: Option<Vec<String>>,
    ) -> Self {
        Self::SkillActivated {
            name: name.into(),
            allowed_tools,
            resource_paths,
        }
    }

    /// Creates a new completion event.
    #[must_use]
    pub fn complete(final_text: impl Into<String>, turns: usize) -> Self {
        Self::Complete {
            final_text: final_text.into(),
            turns,
        }
    }

    /// Creates a new error event.
    #[must_use]
    pub const fn error(error: AgentError) -> Self {
        Self::Error(error)
    }

    /// Returns `true` if this is a completion event.
    #[must_use]
    pub const fn is_complete(&self) -> bool {
        matches!(self, Self::Complete { .. })
    }

    /// Returns `true` if this is an error event.
    #[must_use]
    pub const fn is_error(&self) -> bool {
        matches!(self, Self::Error(_))
    }

    /// Returns `true` if this is a terminal event (complete or error).
    #[must_use]
    pub const fn is_terminal(&self) -> bool {
        self.is_complete() || self.is_error()
    }
}