Skip to main content

oxicode_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// ── Stream delta types ────────────────────────────────────────────────────
98
99/// Typed incremental delta for [`AgentEvent::MessageUpdate`].
100///
101/// Replaces the former `Option<String>` which conflated text and thinking
102/// deltas. Consumers can now distinguish what kind of content changed.
103#[derive(Debug, Clone, Serialize, Deserialize)]
104pub enum StreamDelta {
105    /// Regular text output from the assistant.
106    Text(String),
107    /// Thinking/reasoning content from a reasoning model.
108    Thinking(String),
109    /// Non-text structural change (e.g. a tool call was finalized).
110    /// Consumers should re-render from `message` rather than appending.
111    Sync,
112}
113
114impl StreamDelta {
115    /// Returns the text content if this is a `Text` or `Thinking` delta.
116    pub fn as_text(&self) -> Option<&str> {
117        match self {
118            StreamDelta::Text(s) | StreamDelta::Thinking(s) => Some(s),
119            StreamDelta::Sync => None,
120        }
121    }
122
123    /// Returns `true` if this delta carries text content (Text or Thinking).
124    pub fn has_text(&self) -> bool {
125        !matches!(self, StreamDelta::Sync)
126    }
127}
128
129/// Screenshot metadata attached to PageVisit context.
130#[derive(Debug, Clone, Serialize, Deserialize)]
131pub struct ScreenshotMeta {
132    /// PNG payload size in bytes.
133    pub bytes: usize,
134    /// Viewport width.
135    pub width: u32,
136    /// Capture duration in milliseconds.
137    pub duration_ms: u64,
138}
139
140/// Reason for visiting a page.
141#[derive(Debug, Clone, Serialize, Deserialize)]
142#[serde(rename_all = "snake_case")]
143pub enum VisitReason {
144    /// The agent specified the URL directly.
145    DirectNavigation,
146    /// Clicked a search result at the given position.
147    SearchResult {
148        /// 1-based position in search results.
149        position: usize,
150    },
151    /// Followed a link from another page.
152    LinkFollowed {
153        /// The URL the link was on.
154        from_url: String,
155    },
156}
157
158/// Events emitted during agent execution.
159///
160/// Events are tagged with `type` and serialized as camelCase for JSON consumers.
161/// This enum is `#[non_exhaustive]` — new variants may be added in future releases.
162#[derive(Debug, Clone, Serialize, Deserialize)]
163#[serde(tag = "type", rename_all = "camelCase")]
164#[non_exhaustive]
165pub enum AgentEvent {
166    // ── Lifecycle events ──────────────────────────────────────────────
167    /// Emitted when the agent begins processing a batch of prompts.
168    AgentStart {
169        /// The initial prompt messages sent to the agent.
170        prompts: Vec<oxicode_ai::Message>,
171        /// Optional session identifier for correlation.
172        session_id: Option<String>,
173    },
174
175    /// Emitted when the agent finishes all processing.
176    AgentEnd {
177        /// Final conversation messages.
178        messages: Vec<oxicode_ai::Message>,
179        /// Why the agent stopped (e.g. `"end_turn"`, `"tool_use"`).
180        stop_reason: Option<String>,
181        /// Optional session identifier for correlation.
182        session_id: Option<String>,
183    },
184
185    /// Emitted at the start of each agent loop turn.
186    TurnStart {
187        /// Zero-based turn index.
188        turn_number: u32,
189    },
190
191    /// Emitted when a turn completes, including the assistant reply and tool results.
192    TurnEnd {
193        /// Turn index that just completed.
194        turn_number: u32,
195        /// The assistant message produced this turn.
196        assistant_message: oxicode_ai::Message,
197        /// Tool results collected during this turn.
198        tool_results: Vec<oxicode_ai::ToolResultMessage>,
199    },
200
201    // ── Message events ────────────────────────────────────────────────
202    /// A new message has been created in the conversation.
203    MessageStart {
204        /// The message that started.
205        message: oxicode_ai::Message,
206    },
207
208    /// A message has been updated with new content.
209    MessageUpdate {
210        /// The message in its current state.
211        message: oxicode_ai::Message,
212        /// Incremental delta describing what changed.
213        delta: StreamDelta,
214    },
215
216    /// A message has been finalized.
217    MessageEnd {
218        /// The completed message.
219        message: oxicode_ai::Message,
220    },
221
222    // ── Tool execution events ────────────────────────────────────────
223    /// A tool is about to be executed.
224    ToolExecutionStart {
225        /// Unique identifier for this tool call.
226        tool_call_id: String,
227        /// Name of the tool being invoked.
228        tool_name: String,
229        /// JSON arguments passed to the tool.
230        args: serde_json::Value,
231        /// Intent trace — a concise description of what this tool call does.
232        /// `None` for tools without intent tracing.
233        #[serde(default, skip_serializing_if = "Option::is_none")]
234        intent: Option<String>,
235        /// Semantic context inferred from tool name and arguments.
236        /// `None` for tools without a known context mapping.
237        #[serde(default, skip_serializing_if = "Option::is_none")]
238        context: Option<ToolCallContext>,
239    },
240
241    /// Partial progress from a running tool execution.
242    ToolExecutionUpdate {
243        /// Identifier of the tool call producing the update.
244        tool_call_id: String,
245        /// Name of the tool.
246        tool_name: String,
247        /// Partial result text so far.
248        partial_result: String,
249        /// Browser tab id that produced this progress (if the tool is
250        /// tab-aware). `None` for tools that don't have a tab concept,
251        /// or for older tool implementations that don't propagate tab ids.
252        #[serde(default, skip_serializing_if = "Option::is_none")]
253        tab_id: Option<uuid::Uuid>,
254        /// Semantic context inferred from tool name and arguments.
255        /// Carries structured information about what this update means.
256        #[serde(default, skip_serializing_if = "Option::is_none")]
257        context: Option<ToolCallContext>,
258    },
259
260    /// A tool execution has finished.
261    ToolExecutionEnd {
262        /// Identifier of the completed tool call.
263        tool_call_id: String,
264        /// Name of the tool.
265        tool_name: String,
266        /// Intent trace — a concise description of what this tool call did.
267        /// `None` for tools without intent tracing.
268        #[serde(default, skip_serializing_if = "Option::is_none")]
269        intent: Option<String>,
270        /// The tool result payload.
271        result: oxicode_ai::ToolResult,
272        /// Whether the tool execution resulted in an error.
273        is_error: bool,
274    },
275
276    // ── Streaming tool-call events ───────────────────────────────────
277    /// Partial tool-call arguments streamed by the LLM while it is still
278    /// constructing a tool call. Emitted between the provider's
279    /// `ToolCallStart` and `ToolCallEnd`, before [`AgentEvent::ToolExecutionStart`].
280    ///
281    /// Each `args_delta` is a raw JSON fragment (not valid JSON on its own) —
282    /// downstream consumers accumulate per `tool_call_id`.
283    ToolCallDelta {
284        /// Tool call identifier (matches the id later carried by
285        /// `ToolExecutionStart`).
286        tool_call_id: String,
287        /// Raw JSON argument fragment from the LLM stream.
288        args_delta: String,
289    },
290
291    // ── Legacy events (kept for backward compatibility) ──────────
292    /// Legacy: agent started processing a prompt.
293    #[serde(rename = "start")]
294    Start {
295        /// The user prompt that triggered the run.
296        prompt: String,
297    },
298
299    /// Agent is waiting for the first response token.
300    Thinking,
301
302    /// Incremental thinking / reasoning text from the model.
303    ThinkingDelta {
304        /// The reasoning text delta.
305        text: String,
306    },
307
308    /// The model finished a reasoning/thinking span and is about to produce
309    /// the answer (or begin another content block). Signal-only (no payload).
310    ///
311    /// Emitted when the provider reports `ThinkingEnd`. For models that
312    /// interleave reasoning and text (Claude 4, o-series) this may fire more
313    /// than once per turn — once per thinking span.
314    ThinkingEnd,
315
316    /// A chunk of generated text from the model.
317    TextChunk {
318        /// The text delta to append.
319        text: String,
320    },
321
322    /// The model requested a tool call.
323    ToolCall {
324        /// The tool call descriptor from the provider.
325        tool_call: oxicode_ai::ToolCall,
326    },
327
328    /// A tool execution has started.
329    ToolStart {
330        /// Identifier of the tool call.
331        tool_call_id: String,
332        /// Name of the tool being invoked.
333        tool_name: String,
334        /// JSON arguments for the tool call.
335        #[serde(default)]
336        arguments: serde_json::Value,
337    },
338
339    /// Progress update from a running tool.
340    ToolProgress {
341        /// Identifier of the tool call.
342        tool_call_id: String,
343        /// Human-readable progress message.
344        message: String,
345    },
346
347    /// A tool execution has completed.
348    ToolComplete {
349        /// The tool result payload.
350        result: oxicode_ai::ToolResult,
351    },
352
353    /// A tool execution failed.
354    ToolError {
355        /// Identifier of the failed tool call.
356        tool_call_id: String,
357        /// Error description.
358        error: String,
359    },
360
361    /// The agent produced a final response.
362    Complete {
363        /// Full response text.
364        content: String,
365        /// Stop reason string (e.g. `"EndTurn"`).
366        stop_reason: String,
367    },
368
369    /// An error occurred during agent execution.
370    Error {
371        /// Human-readable error message.
372        message: String,
373        /// Optional session identifier.
374        session_id: Option<String>,
375    },
376
377    /// Agent loop iteration counter update.
378    Iteration {
379        /// Current iteration number.
380        number: usize,
381    },
382
383    /// Token usage report for a completed turn.
384    Usage {
385        /// Number of prompt / input tokens consumed.
386        input_tokens: usize,
387        /// Number of completion / output tokens produced.
388        output_tokens: usize,
389    },
390
391    /// Context compaction lifecycle event.
392    Compaction {
393        /// The underlying compaction event detail.
394        event: CompactionEvent,
395    },
396
397    /// The agent is retrying after a transient error.
398    Retry {
399        /// Current retry attempt (1-based).
400        attempt: usize,
401        /// Maximum number of retries allowed.
402        max_retries: usize,
403        /// Seconds until the next attempt.
404        retry_after_secs: u64,
405        /// Why the previous attempt failed.
406        reason: String,
407        /// Optional session identifier.
408        session_id: Option<String>,
409    },
410
411    /// A TTSR rule violation was detected during streaming.
412    /// The stream was aborted and a system reminder will be injected.
413    TtsrInterrupt {
414        /// Name of the violated rule.
415        rule_name: String,
416        /// Session identifier for logging.
417        session_id: Option<String>,
418    },
419    /// The agent run was cancelled by the caller.
420    Cancelled,
421
422    /// A partial response delivered mid-stream (useful for UI rendering).
423    PartialResponse {
424        /// Accumulated response content so far.
425        content: String,
426    },
427
428    // ── Auto-retry events ─────────────────────────────────────────
429    /// An automatic retry attempt is starting.
430    AutoRetryStart {
431        /// Current retry attempt (1-based).
432        attempt: usize,
433        /// Total retry attempts that will be made.
434        max_attempts: usize,
435        /// Milliseconds before this attempt is sent.
436        delay_ms: u64,
437        /// The error that triggered the retry.
438        error_message: String,
439    },
440
441    /// An automatic retry attempt has concluded.
442    AutoRetryEnd {
443        /// Whether the retry succeeded.
444        success: bool,
445        /// Which attempt this was (1-based).
446        attempt: usize,
447        /// Final error if the retry failed, `None` on success.
448        final_error: Option<String>,
449    },
450
451    // ── Loop-specific steering events ─────────────────────────────
452    /// A system-level steering message injected into the conversation.
453    SteeringMessage {
454        /// The steering message to add to the context.
455        message: oxicode_ai::Message,
456    },
457
458    /// A follow-up message appended to continue the conversation.
459    FollowUpMessage {
460        /// The follow-up message.
461        message: oxicode_ai::Message,
462    },
463
464    // ── Approval events ────────────────────────────────────────────
465    /// A tool call requires human approval.
466    ApprovalRequired {
467        /// Tool call identifier.
468        tool_call_id: String,
469        /// Name of the tool requiring approval.
470        tool_name: String,
471        /// Arguments passed to the tool.
472        args: serde_json::Value,
473        /// Why approval is needed.
474        reason: String,
475        /// Session identifier for correlation.
476        #[serde(default, skip_serializing_if = "Option::is_none")]
477        session_id: Option<String>,
478    },
479    /// Result of an approval request.
480    ApprovalResult {
481        /// Tool call identifier this result corresponds to.
482        tool_call_id: String,
483        /// Whether the tool call was approved.
484        approved: bool,
485        /// Optional reason from the approver.
486        #[serde(default, skip_serializing_if = "Option::is_none")]
487        reason: Option<String>,
488    },
489
490    // ── Soft requirement events ─────────────────────────────────────
491    /// A soft-required tool was not called on the first turn.
492    /// The loop injects a reminder steering message.
493    SoftRequirementReminder {
494        /// Tool that should have been called.
495        tool_name: String,
496        /// Reason why the tool is needed.
497        reason: String,
498        /// Session identifier for correlation.
499        #[serde(default, skip_serializing_if = "Option::is_none")]
500        session_id: Option<String>,
501    },
502    /// A soft-required tool was not called after multiple turns.
503    /// Escalation — stronger action may be needed.
504    SoftRequirementEscalation {
505        /// Tool that should have been called.
506        tool_name: String,
507        /// Reason why the tool is needed.
508        reason: String,
509        /// Session identifier for correlation.
510        #[serde(default, skip_serializing_if = "Option::is_none")]
511        session_id: Option<String>,
512    },
513
514    // ── Harmony leak event ──────────────────────────────────────────
515    /// GPT-5 Harmony protocol leak detected in streaming output.
516    /// The stream was aborted to prevent the leaked content from
517    /// being persisted or acted upon.
518    HarmonyLeakDetected {
519        /// A preview of the leaked content (truncated, privacy-safe).
520        preview: String,
521        /// Session identifier for correlation.
522        #[serde(default, skip_serializing_if = "Option::is_none")]
523        session_id: Option<String>,
524    },
525}
526
527impl AgentEvent {
528    /// Returns `true` if this event represents the end of the agent lifecycle.
529    pub fn is_terminal(&self) -> bool {
530        matches!(self, AgentEvent::AgentEnd { .. })
531    }
532
533    /// Returns the snake_case variant name of this event (useful for logging / serialization).
534    pub fn type_name(&self) -> &'static str {
535        match self {
536            AgentEvent::AgentStart { .. } => "agent_start",
537            AgentEvent::AgentEnd { .. } => "agent_end",
538            AgentEvent::TurnStart { .. } => "turn_start",
539            AgentEvent::TurnEnd { .. } => "turn_end",
540            AgentEvent::MessageStart { .. } => "message_start",
541            AgentEvent::MessageUpdate { .. } => "message_update",
542            AgentEvent::MessageEnd { .. } => "message_end",
543            AgentEvent::ToolExecutionStart { .. } => "tool_execution_start",
544            AgentEvent::ToolExecutionUpdate { .. } => "tool_execution_update",
545            AgentEvent::ToolExecutionEnd { .. } => "tool_execution_end",
546            AgentEvent::ToolCallDelta { .. } => "tool_call_delta",
547            AgentEvent::Start { .. } => "start",
548            AgentEvent::Thinking => "thinking",
549            AgentEvent::ThinkingDelta { .. } => "thinking_delta",
550            AgentEvent::ThinkingEnd => "thinking_end",
551            AgentEvent::TextChunk { .. } => "text_chunk",
552            AgentEvent::ToolCall { .. } => "tool_call",
553            AgentEvent::ToolStart { .. } => "tool_start",
554            AgentEvent::ToolProgress { .. } => "tool_progress",
555            AgentEvent::ToolComplete { .. } => "tool_complete",
556            AgentEvent::ToolError { .. } => "tool_error",
557            AgentEvent::Complete { .. } => "complete",
558            AgentEvent::Error { .. } => "error",
559            AgentEvent::Iteration { .. } => "iteration",
560            AgentEvent::Usage { .. } => "usage",
561            AgentEvent::Compaction { .. } => "compaction",
562            AgentEvent::Retry { .. } => "retry",
563            AgentEvent::TtsrInterrupt { .. } => "ttsr_interrupt",
564            AgentEvent::Cancelled => "cancelled",
565            AgentEvent::PartialResponse { .. } => "partial_response",
566            AgentEvent::AutoRetryStart { .. } => "auto_retry_start",
567            AgentEvent::AutoRetryEnd { .. } => "auto_retry_end",
568            AgentEvent::SteeringMessage { .. } => "steering_message",
569            AgentEvent::FollowUpMessage { .. } => "follow_up_message",
570            AgentEvent::ApprovalRequired { .. } => "approval_required",
571            AgentEvent::ApprovalResult { .. } => "approval_result",
572            AgentEvent::SoftRequirementReminder { .. } => "soft_requirement_reminder",
573            AgentEvent::SoftRequirementEscalation { .. } => "soft_requirement_escalation",
574            AgentEvent::HarmonyLeakDetected { .. } => "harmony_leak_detected",
575        }
576    }
577}