oxi_agent/events.rs
1/// Agent event system
2/// Defines all events emitted during an agent run, including lifecycle,
3/// streaming, tool execution, compaction, retry, and steering events.
4use crate::compaction::CompactionEvent;
5use serde::{Deserialize, Serialize};
6
7// ── Tool context types ────────────────────────────────────────────────────
8
9/// Semantic context for a tool execution event.
10///
11/// Carries structured information about *what* a tool call means,
12/// derived from the tool name and arguments by the agent loop.
13/// UI consumers that understand a context variant can render it
14/// richly; older consumers simply ignore the field.
15#[derive(Debug, Clone, Serialize, Deserialize)]
16#[serde(tag = "kind", rename_all = "snake_case")]
17#[non_exhaustive]
18pub enum ToolCallContext {
19 // ── Web exploration ──────────────────────────────────────
20 /// A search engine query.
21 WebSearch {
22 /// The search query string.
23 query: String,
24 /// Search engine used (e.g. "duckduckgo").
25 #[serde(skip_serializing_if = "Option::is_none")]
26 engine: Option<String>,
27 },
28
29 /// Visiting a web page.
30 PageVisit {
31 /// URL being visited.
32 url: String,
33 /// Why this page is being visited.
34 #[serde(skip_serializing_if = "Option::is_none")]
35 reason: Option<VisitReason>,
36 // ── Result fields (enriched by BrowseProgress::DocumentReady) ──
37 /// Page `<title>` after load.
38 #[serde(skip_serializing_if = "Option::is_none")]
39 page_title: Option<String>,
40 /// HTTP status code.
41 #[serde(skip_serializing_if = "Option::is_none")]
42 page_status: Option<u16>,
43 /// HTML body size in bytes.
44 #[serde(skip_serializing_if = "Option::is_none")]
45 page_bytes: Option<u64>,
46 /// Wall-clock page load duration in milliseconds.
47 #[serde(skip_serializing_if = "Option::is_none")]
48 page_duration_ms: Option<u64>,
49 // ── Error / enrichment fields ──
50 /// Navigation error message (from BrowseProgress::NavigationFailed).
51 #[serde(skip_serializing_if = "Option::is_none")]
52 navigation_error: Option<String>,
53 /// Screenshot metadata (from BrowseProgress::ScreenshotCaptured).
54 #[serde(skip_serializing_if = "Option::is_none")]
55 screenshot: Option<ScreenshotMeta>,
56 },
57
58 /// Extracting data from a web page.
59 DataExtraction {
60 /// Description of what is being extracted (e.g. CSS selector).
61 target: String,
62 /// URL of the page being extracted from.
63 #[serde(skip_serializing_if = "Option::is_none")]
64 url: Option<String>,
65 // ── Result fields (enriched by BrowseProgress::DocumentReady) ──
66 /// Number of items extracted.
67 #[serde(skip_serializing_if = "Option::is_none")]
68 result_count: Option<usize>,
69 /// HTTP status code of the page.
70 #[serde(skip_serializing_if = "Option::is_none")]
71 page_status: Option<u16>,
72 /// Page load duration in milliseconds.
73 #[serde(skip_serializing_if = "Option::is_none")]
74 page_duration_ms: Option<u64>,
75 },
76
77 /// An action within a persistent browser session.
78 SessionAction {
79 /// The session action being performed (e.g. "goto", "click").
80 action: String,
81 /// URL if the action involves navigation.
82 #[serde(skip_serializing_if = "Option::is_none")]
83 url: Option<String>,
84 },
85
86 /// A step within a browse script.
87 ScriptStep {
88 /// Current step index (1-based).
89 current: usize,
90 /// Total number of steps.
91 total: usize,
92 /// Human-readable step description.
93 step: String,
94 },
95}
96
97/// Screenshot metadata attached to PageVisit context.
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct ScreenshotMeta {
100 /// PNG payload size in bytes.
101 pub bytes: usize,
102 /// Viewport width.
103 pub width: u32,
104 /// Capture duration in milliseconds.
105 pub duration_ms: u64,
106}
107
108/// Reason for visiting a page.
109#[derive(Debug, Clone, Serialize, Deserialize)]
110#[serde(rename_all = "snake_case")]
111pub enum VisitReason {
112 /// The agent specified the URL directly.
113 DirectNavigation,
114 /// Clicked a search result at the given position.
115 SearchResult {
116 /// 1-based position in search results.
117 position: usize,
118 },
119 /// Followed a link from another page.
120 LinkFollowed {
121 /// The URL the link was on.
122 from_url: String,
123 },
124}
125
126/// Events emitted during agent execution.
127///
128/// Events are tagged with `type` and serialized as camelCase for JSON consumers.
129/// This enum is `#[non_exhaustive]` — new variants may be added in future releases.
130#[derive(Debug, Clone, Serialize, Deserialize)]
131#[serde(tag = "type", rename_all = "camelCase")]
132#[non_exhaustive]
133pub enum AgentEvent {
134 // ── Lifecycle events ──────────────────────────────────────────────
135 /// Emitted when the agent begins processing a batch of prompts.
136 AgentStart {
137 /// The initial prompt messages sent to the agent.
138 prompts: Vec<oxi_ai::Message>,
139 /// Optional session identifier for correlation.
140 session_id: Option<String>,
141 },
142
143 /// Emitted when the agent finishes all processing.
144 AgentEnd {
145 /// Final conversation messages.
146 messages: Vec<oxi_ai::Message>,
147 /// Why the agent stopped (e.g. `"end_turn"`, `"tool_use"`).
148 stop_reason: Option<String>,
149 /// Optional session identifier for correlation.
150 session_id: Option<String>,
151 },
152
153 /// Emitted at the start of each agent loop turn.
154 TurnStart {
155 /// Zero-based turn index.
156 turn_number: u32,
157 },
158
159 /// Emitted when a turn completes, including the assistant reply and tool results.
160 TurnEnd {
161 /// Turn index that just completed.
162 turn_number: u32,
163 /// The assistant message produced this turn.
164 assistant_message: oxi_ai::Message,
165 /// Tool results collected during this turn.
166 tool_results: Vec<oxi_ai::ToolResultMessage>,
167 },
168
169 // ── Message events ────────────────────────────────────────────────
170 /// A new message has been created in the conversation.
171 MessageStart {
172 /// The message that started.
173 message: oxi_ai::Message,
174 },
175
176 /// A message has been updated with new content.
177 MessageUpdate {
178 /// The message in its current state.
179 message: oxi_ai::Message,
180 /// Incremental text delta since the last update, if available.
181 delta: Option<String>,
182 },
183
184 /// A message has been finalized.
185 MessageEnd {
186 /// The completed message.
187 message: oxi_ai::Message,
188 },
189
190 // ── Tool execution events ────────────────────────────────────────
191 /// A tool is about to be executed.
192 ToolExecutionStart {
193 /// Unique identifier for this tool call.
194 tool_call_id: String,
195 /// Name of the tool being invoked.
196 tool_name: String,
197 /// JSON arguments passed to the tool.
198 args: serde_json::Value,
199 /// Semantic context inferred from tool name and arguments.
200 /// `None` for tools without a known context mapping.
201 #[serde(default, skip_serializing_if = "Option::is_none")]
202 context: Option<ToolCallContext>,
203 },
204
205 /// Partial progress from a running tool execution.
206 ToolExecutionUpdate {
207 /// Identifier of the tool call producing the update.
208 tool_call_id: String,
209 /// Name of the tool.
210 tool_name: String,
211 /// Partial result text so far.
212 partial_result: String,
213 /// Browser tab id that produced this progress (if the tool is
214 /// tab-aware). `None` for tools that don't have a tab concept,
215 /// or for older tool implementations that don't propagate tab ids.
216 #[serde(default, skip_serializing_if = "Option::is_none")]
217 tab_id: Option<uuid::Uuid>,
218 /// Semantic context inferred from tool name and arguments.
219 /// Carries structured information about what this update means.
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 context: Option<ToolCallContext>,
222 },
223
224 /// A tool execution has finished.
225 ToolExecutionEnd {
226 /// Identifier of the completed tool call.
227 tool_call_id: String,
228 /// Name of the tool.
229 tool_name: String,
230 /// The tool result payload.
231 result: oxi_ai::ToolResult,
232 /// Whether the tool execution resulted in an error.
233 is_error: bool,
234 },
235
236 // ── Streaming tool-call events ───────────────────────────────────
237 /// Partial tool-call arguments streamed by the LLM while it is still
238 /// constructing a tool call. Emitted between the provider's
239 /// `ToolCallStart` and `ToolCallEnd`, before [`AgentEvent::ToolExecutionStart`].
240 ///
241 /// Each `args_delta` is a raw JSON fragment (not valid JSON on its own) —
242 /// downstream consumers accumulate per `tool_call_id`.
243 ToolCallDelta {
244 /// Tool call identifier (matches the id later carried by
245 /// `ToolExecutionStart`).
246 tool_call_id: String,
247 /// Raw JSON argument fragment from the LLM stream.
248 args_delta: String,
249 },
250
251 // ── Legacy events (kept for backward compatibility) ──────────
252 /// Legacy: agent started processing a prompt.
253 #[serde(rename = "start")]
254 Start {
255 /// The user prompt that triggered the run.
256 prompt: String,
257 },
258
259 /// Agent is waiting for the first response token.
260 Thinking,
261
262 /// Incremental thinking / reasoning text from the model.
263 ThinkingDelta {
264 /// The reasoning text delta.
265 text: String,
266 },
267
268 /// The model finished a reasoning/thinking span and is about to produce
269 /// the answer (or begin another content block). Signal-only (no payload).
270 ///
271 /// Emitted when the provider reports `ThinkingEnd`. For models that
272 /// interleave reasoning and text (Claude 4, o-series) this may fire more
273 /// than once per turn — once per thinking span.
274 ThinkingEnd,
275
276 /// A chunk of generated text from the model.
277 TextChunk {
278 /// The text delta to append.
279 text: String,
280 },
281
282 /// The model requested a tool call.
283 ToolCall {
284 /// The tool call descriptor from the provider.
285 tool_call: oxi_ai::ToolCall,
286 },
287
288 /// A tool execution has started.
289 ToolStart {
290 /// Identifier of the tool call.
291 tool_call_id: String,
292 /// Name of the tool being invoked.
293 tool_name: String,
294 /// JSON arguments for the tool call.
295 #[serde(default)]
296 arguments: serde_json::Value,
297 },
298
299 /// Progress update from a running tool.
300 ToolProgress {
301 /// Identifier of the tool call.
302 tool_call_id: String,
303 /// Human-readable progress message.
304 message: String,
305 },
306
307 /// A tool execution has completed.
308 ToolComplete {
309 /// The tool result payload.
310 result: oxi_ai::ToolResult,
311 },
312
313 /// A tool execution failed.
314 ToolError {
315 /// Identifier of the failed tool call.
316 tool_call_id: String,
317 /// Error description.
318 error: String,
319 },
320
321 /// The agent produced a final response.
322 Complete {
323 /// Full response text.
324 content: String,
325 /// Stop reason string (e.g. `"EndTurn"`).
326 stop_reason: String,
327 },
328
329 /// An error occurred during agent execution.
330 Error {
331 /// Human-readable error message.
332 message: String,
333 /// Optional session identifier.
334 session_id: Option<String>,
335 },
336
337 /// Agent loop iteration counter update.
338 Iteration {
339 /// Current iteration number.
340 number: usize,
341 },
342
343 /// Token usage report for a completed turn.
344 Usage {
345 /// Number of prompt / input tokens consumed.
346 input_tokens: usize,
347 /// Number of completion / output tokens produced.
348 output_tokens: usize,
349 },
350
351 /// Context compaction lifecycle event.
352 Compaction {
353 /// The underlying compaction event detail.
354 event: CompactionEvent,
355 },
356
357 /// The agent is retrying after a transient error.
358 Retry {
359 /// Current retry attempt (1-based).
360 attempt: usize,
361 /// Maximum number of retries allowed.
362 max_retries: usize,
363 /// Seconds until the next attempt.
364 retry_after_secs: u64,
365 /// Why the previous attempt failed.
366 reason: String,
367 /// Optional session identifier.
368 session_id: Option<String>,
369 },
370
371 /// The agent switched to a fallback model.
372 Fallback {
373 /// Model that was being used before the failure.
374 from_model: String,
375 /// Fallback model that will be used instead.
376 to_model: String,
377 },
378
379 /// A TTSR rule violation was detected during streaming.
380 /// The stream was aborted and a system reminder will be injected.
381 TtsrInterrupt {
382 /// Name of the violated rule.
383 rule_name: String,
384 /// Session identifier for logging.
385 session_id: Option<String>,
386 },
387 /// The agent run was cancelled by the caller.
388 Cancelled,
389
390 /// A partial response delivered mid-stream (useful for UI rendering).
391 PartialResponse {
392 /// Accumulated response content so far.
393 content: String,
394 },
395
396 // ── Auto-retry events ─────────────────────────────────────────
397 /// An automatic retry attempt is starting.
398 AutoRetryStart {
399 /// Current retry attempt (1-based).
400 attempt: usize,
401 /// Total retry attempts that will be made.
402 max_attempts: usize,
403 /// Milliseconds before this attempt is sent.
404 delay_ms: u64,
405 /// The error that triggered the retry.
406 error_message: String,
407 },
408
409 /// An automatic retry attempt has concluded.
410 AutoRetryEnd {
411 /// Whether the retry succeeded.
412 success: bool,
413 /// Which attempt this was (1-based).
414 attempt: usize,
415 /// Final error if the retry failed, `None` on success.
416 final_error: Option<String>,
417 },
418
419 // ── Loop-specific steering events ─────────────────────────────
420 /// A system-level steering message injected into the conversation.
421 SteeringMessage {
422 /// The steering message to add to the context.
423 message: oxi_ai::Message,
424 },
425
426 /// A follow-up message appended to continue the conversation.
427 FollowUpMessage {
428 /// The follow-up message.
429 message: oxi_ai::Message,
430 },
431}
432
433impl AgentEvent {
434 /// Returns `true` if this event represents the end of the agent lifecycle.
435 pub fn is_terminal(&self) -> bool {
436 matches!(self, AgentEvent::AgentEnd { .. })
437 }
438
439 /// Returns the snake_case variant name of this event (useful for logging / serialization).
440 pub fn type_name(&self) -> &'static str {
441 match self {
442 AgentEvent::AgentStart { .. } => "agent_start",
443 AgentEvent::AgentEnd { .. } => "agent_end",
444 AgentEvent::TurnStart { .. } => "turn_start",
445 AgentEvent::TurnEnd { .. } => "turn_end",
446 AgentEvent::MessageStart { .. } => "message_start",
447 AgentEvent::MessageUpdate { .. } => "message_update",
448 AgentEvent::MessageEnd { .. } => "message_end",
449 AgentEvent::ToolExecutionStart { .. } => "tool_execution_start",
450 AgentEvent::ToolExecutionUpdate { .. } => "tool_execution_update",
451 AgentEvent::ToolExecutionEnd { .. } => "tool_execution_end",
452 AgentEvent::ToolCallDelta { .. } => "tool_call_delta",
453 AgentEvent::Start { .. } => "start",
454 AgentEvent::Thinking => "thinking",
455 AgentEvent::ThinkingDelta { .. } => "thinking_delta",
456 AgentEvent::ThinkingEnd => "thinking_end",
457 AgentEvent::TextChunk { .. } => "text_chunk",
458 AgentEvent::ToolCall { .. } => "tool_call",
459 AgentEvent::ToolStart { .. } => "tool_start",
460 AgentEvent::ToolProgress { .. } => "tool_progress",
461 AgentEvent::ToolComplete { .. } => "tool_complete",
462 AgentEvent::ToolError { .. } => "tool_error",
463 AgentEvent::Complete { .. } => "complete",
464 AgentEvent::Error { .. } => "error",
465 AgentEvent::Iteration { .. } => "iteration",
466 AgentEvent::Usage { .. } => "usage",
467 AgentEvent::Compaction { .. } => "compaction",
468 AgentEvent::Retry { .. } => "retry",
469 AgentEvent::Fallback { .. } => "fallback",
470 AgentEvent::TtsrInterrupt { .. } => "ttsr_interrupt",
471 AgentEvent::Cancelled => "cancelled",
472 AgentEvent::PartialResponse { .. } => "partial_response",
473 AgentEvent::AutoRetryStart { .. } => "auto_retry_start",
474 AgentEvent::AutoRetryEnd { .. } => "auto_retry_end",
475 AgentEvent::SteeringMessage { .. } => "steering_message",
476 AgentEvent::FollowUpMessage { .. } => "follow_up_message",
477 }
478 }
479}