Skip to main content

bamboo_agent_core/agent/
events.rs

1//! Agent event system for real-time streaming.
2//!
3//! This module defines the event types emitted during agent execution,
4//! which are streamed to clients via Server-Sent Events (SSE).
5//!
6//! # Event Types
7//!
8//! - [`AgentEvent`] - All possible agent execution events
9//! - [`TokenUsage`] - Token consumption statistics
10//! - [`TokenBudgetUsage`] - Detailed token budget information
11//!
12//! # Event Flow
13//!
14//! 1. **Token** events stream generated text
15//! 2. **ToolStart/ToolComplete** track tool execution
16//! 3. **TaskListUpdated** tracks progress
17//! 4. **TokenBudgetUpdated** reports context management
18//! 5. **Complete** or **Error** ends the stream
19//!
20//! # Example
21//!
22//! ```javascript
23//! const eventSource = new EventSource('/api/v1/events/session-id');
24//! eventSource.onmessage = (event) => {
25//!   const data = JSON.parse(event.data);
26//!   switch (data.type) {
27//!     case 'token':
28//!       console.log('Token:', data.content);
29//!       break;
30//!     case 'complete':
31//!       console.log('Done!');
32//!       eventSource.close();
33//!       break;
34//!   }
35//! };
36//! ```
37
38use crate::tools::ToolResult;
39use bamboo_domain::{TaskItemStatus, TaskList};
40use chrono::{DateTime, Utc};
41use serde::{Deserialize, Serialize};
42
43/// Represents events emitted during agent execution.
44///
45/// These events are streamed to clients via SSE to provide real-time
46/// feedback on agent progress, tool execution, and completion.
47///
48/// # Variants
49///
50/// ## Text Generation
51/// - `Token` - Streaming text token
52/// - `ReasoningToken` - Streaming reasoning/thinking token (separate channel)
53///
54/// ## Tool Execution
55/// - `ToolStart` - Tool execution started
56/// - `ToolComplete` - Tool finished successfully
57/// - `ToolError` - Tool execution failed
58///
59/// ## User Interaction
60/// - `NeedClarification` - Agent needs user input
61///
62/// ## Progress Tracking
63/// - `TaskListUpdated` - Task list created or modified
64/// - `TaskListItemProgress` - Individual item progress
65/// - `TaskListCompleted` - All items completed
66/// - `TaskEvaluationStarted` - Task evaluation began
67/// - `TaskEvaluationCompleted` - Task evaluation finished
68///
69/// ## Context Management
70/// - `TokenBudgetUpdated` - Context budget changed
71/// - `ContextCompressionStatus` - Context compression lifecycle progress
72/// - `ContextSummarized` - Old messages summarized
73///
74/// ## Sub-sessions (Async Spawn)
75/// - `SubSessionStarted` - A child session is created and scheduled to run
76/// - `SubSessionEvent` - Forwarded raw child event (full fidelity)
77/// - `SubSessionHeartbeat` - Periodic heartbeat while the child is running
78/// - `SubSessionCompleted` - Child session finished (completed/cancelled/error)
79///
80/// ## Terminal Events
81/// - `Complete` - Execution finished successfully
82/// - `Error` - Execution failed
83///
84/// # Serialization
85///
86/// Events are serialized as JSON with a `type` field for discrimination:
87/// ```json
88/// {"type": "token", "content": "Hello"}
89/// {"type": "complete", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}
90/// ```
91#[derive(Debug, Clone, Serialize, Deserialize)]
92#[serde(tag = "type", rename_all = "snake_case")]
93pub enum AgentEvent {
94    /// Text token generated by the LLM.
95    Token {
96        /// Generated text content
97        content: String,
98    },
99
100    /// Reasoning/thinking token generated by the LLM.
101    ///
102    /// This is streamed separately from assistant answer tokens so the UI can
103    /// choose whether and how to display model reasoning traces.
104    ReasoningToken {
105        /// Generated reasoning content
106        content: String,
107    },
108
109    /// Streaming output emitted while a specific tool call is running.
110    ///
111    /// This is used to render "live output" inside a tool-call card in the UI
112    /// without mixing tool output into the assistant's main token stream.
113    ToolToken {
114        /// Tool call identifier that this output belongs to.
115        tool_call_id: String,
116        /// Output chunk.
117        content: String,
118    },
119
120    /// Tool execution started.
121    ToolStart {
122        /// Unique tool call identifier
123        tool_call_id: String,
124        /// Name of the tool being executed
125        tool_name: String,
126        /// Tool arguments (JSON)
127        arguments: serde_json::Value,
128    },
129
130    /// Tool execution completed successfully.
131    ToolComplete {
132        /// Tool call identifier
133        tool_call_id: String,
134        /// Tool execution result
135        result: ToolResult,
136    },
137
138    /// Tool execution failed.
139    ToolError {
140        /// Tool call identifier
141        tool_call_id: String,
142        /// Error message
143        error: String,
144    },
145
146    /// Structured lifecycle event for tool execution tracking.
147    ///
148    /// These events complement `ToolStart`/`ToolComplete`/`ToolError` with
149    /// richer metadata (mutability, auto-approval, wall-clock timing) and
150    /// are emitted by `ToolEmitter` (in `bamboo-agent-tools`).
151    ToolLifecycle {
152        /// Tool call identifier
153        tool_call_id: String,
154        /// Canonical tool name
155        tool_name: String,
156        /// Lifecycle phase: "begin", "finished", "error", "cancelled"
157        phase: String,
158        /// Wall-clock milliseconds since the call began (None for begin)
159        #[serde(skip_serializing_if = "Option::is_none")]
160        elapsed_ms: Option<u64>,
161        /// Whether the tool mutates state (writes files, runs commands)
162        is_mutating: bool,
163        /// Whether execution was auto-approved (no user prompt needed)
164        auto_approved: bool,
165        /// Human-readable summary
166        #[serde(skip_serializing_if = "Option::is_none")]
167        summary: Option<String>,
168        /// Error message (if phase == "error")
169        #[serde(skip_serializing_if = "Option::is_none")]
170        error: Option<String>,
171    },
172
173    /// Agent needs clarification from the user.
174    NeedClarification {
175        /// Question to ask the user
176        question: String,
177        /// Optional predefined options
178        options: Option<Vec<String>>,
179        /// Tool call identifier that triggered this clarification
180        #[serde(default, skip_serializing_if = "Option::is_none")]
181        tool_call_id: Option<String>,
182        /// Whether the user can provide a free-text response
183        #[serde(default = "default_allow_custom")]
184        allow_custom: bool,
185    },
186
187    /// Emitted when task list is created or updated.
188    TaskListUpdated {
189        /// Current task list state.
190        task_list: TaskList,
191    },
192
193    /// Emitted when a task item makes progress (delta update).
194    TaskListItemProgress {
195        /// Session identifier
196        session_id: String,
197        /// Item identifier
198        item_id: String,
199        /// New item status
200        status: TaskItemStatus,
201        /// Number of tool calls made
202        tool_calls_count: usize,
203        /// Item version (for optimistic concurrency)
204        version: u64,
205    },
206
207    /// Emitted when all task items are completed.
208    TaskListCompleted {
209        /// Session identifier
210        session_id: String,
211        /// Completion timestamp
212        completed_at: DateTime<Utc>,
213        /// Total agent rounds executed
214        total_rounds: u32,
215        /// Total tool calls made
216        total_tool_calls: usize,
217    },
218
219    /// Emitted when task evaluation starts.
220    TaskEvaluationStarted {
221        /// Session identifier
222        session_id: String,
223        /// Number of items to evaluate
224        items_count: usize,
225    },
226
227    /// Emitted when task evaluation completes.
228    TaskEvaluationCompleted {
229        /// Session identifier
230        session_id: String,
231        /// Number of items updated
232        updates_count: usize,
233        /// Evaluation reasoning
234        reasoning: String,
235    },
236
237    /// Emitted when token budget is prepared (after context truncation)
238    TokenBudgetUpdated {
239        /// Token budget details
240        usage: TokenBudgetUsage,
241    },
242
243    /// Emitted when host-side context compression lifecycle changes.
244    ContextCompressionStatus {
245        /// Compression phase label (for example: pre-turn, mid-turn).
246        phase: String,
247        /// Compression status: started | completed | failed | skipped
248        status: String,
249    },
250
251    /// Emitted when conversation context is summarized
252    ContextSummarized {
253        /// Generated summary text
254        summary: String,
255        /// Number of old messages summarized
256        messages_summarized: usize,
257        /// Tokens saved by summarization
258        tokens_saved: u32,
259        /// Context usage percentage before compression
260        #[serde(default)]
261        usage_before_percent: f64,
262        /// Context usage percentage after compression
263        #[serde(default)]
264        usage_after_percent: f64,
265        /// What triggered the compression: "auto" | "manual" | "critical"
266        #[serde(default)]
267        trigger_type: String,
268    },
269
270    /// Emitted when context pressure reaches warning or critical levels.
271    /// Frontend should display this to the user as a proactive notification.
272    ContextPressureNotification {
273        /// Context usage as a percentage of the context window.
274        percent: f64,
275        /// Severity level: "warning" (70%) or "critical" (90%).
276        level: String,
277        /// Human-readable message describing the pressure state.
278        message: String,
279    },
280
281    /// A child session was spawned from a parent session (async background job).
282    SubSessionStarted {
283        parent_session_id: String,
284        child_session_id: String,
285        /// Optional title (useful for UI lists).
286        #[serde(default, skip_serializing_if = "Option::is_none")]
287        title: Option<String>,
288    },
289
290    /// Forwarded raw child event to the parent session stream.
291    ///
292    /// Child sessions are not allowed to spawn further sessions, so this should not nest.
293    SubSessionEvent {
294        parent_session_id: String,
295        child_session_id: String,
296        event: Box<AgentEvent>,
297    },
298
299    /// Heartbeat emitted while a child session is running.
300    SubSessionHeartbeat {
301        parent_session_id: String,
302        child_session_id: String,
303        timestamp: DateTime<Utc>,
304    },
305
306    /// Child session finished (completed/cancelled/error).
307    SubSessionCompleted {
308        parent_session_id: String,
309        child_session_id: String,
310        /// One of: "completed" | "cancelled" | "error" | "skipped"
311        status: String,
312        #[serde(default, skip_serializing_if = "Option::is_none")]
313        error: Option<String>,
314    },
315
316    /// Plan mode was entered.
317    PlanModeEntered {
318        /// Session identifier
319        session_id: String,
320        /// Optional reason for entering plan mode
321        #[serde(default, skip_serializing_if = "Option::is_none")]
322        reason: Option<String>,
323        /// Previous permission mode before entering plan mode
324        pre_permission_mode: String,
325    },
326
327    /// Plan mode was exited.
328    PlanModeExited {
329        /// Session identifier
330        session_id: String,
331        /// Whether the exit was approved by the user
332        approved: bool,
333        /// The permission mode restored after exiting
334        restored_mode: String,
335        /// Plan content that was reviewed, if any
336        #[serde(default, skip_serializing_if = "Option::is_none")]
337        plan: Option<String>,
338    },
339
340    /// Plan file was updated.
341    PlanFileUpdated {
342        /// Session identifier
343        session_id: String,
344        /// Path to the plan file
345        file_path: String,
346        /// Summary of the plan content (truncated)
347        content_summary: String,
348    },
349
350    /// Runner progress update emitted at the start of each agent turn.
351    ///
352    /// Used to track live execution progress (round count, current activity)
353    /// for diagnostic visibility, especially for child sessions.
354    RunnerProgress {
355        /// Session identifier
356        session_id: String,
357        /// Current turn/round count
358        round_count: u32,
359    },
360
361    /// Execution run has started and the runner is now active.
362    ///
363    /// Emitted as the first event after a runner reservation succeeds,
364    /// before any token or tool events. Carries the `run_id` so the
365    /// frontend can correlate subsequent SSE events across reconnects.
366    ExecutionStarted {
367        /// Unique identifier for this execution run.
368        run_id: String,
369        /// Session identifier.
370        session_id: String,
371        /// ISO 8601 timestamp when the run started.
372        started_at: String,
373    },
374
375    /// Tool execution requires user approval before proceeding.
376    ///
377    /// Emitted when a permission checker determines that a tool call needs
378    /// explicit user confirmation (e.g., mutating operations in restricted
379    /// permission mode). The frontend should present the approval request and
380    /// either grant or deny it.
381    ToolApprovalRequested {
382        /// Unique identifier for the tool call awaiting approval.
383        tool_call_id: String,
384        /// Name of the tool being executed.
385        tool_name: String,
386        /// Parameters that were passed to the tool.
387        parameters: serde_json::Value,
388    },
389
390    /// Agent execution completed successfully.
391    Complete {
392        /// Final token usage statistics
393        usage: TokenUsage,
394    },
395
396    /// Agent execution failed.
397    Error {
398        /// Error message
399        message: String,
400    },
401}
402
403fn default_allow_custom() -> bool {
404    true
405}
406
407/// Re-exported shared token usage type.
408///
409/// See [`bamboo_domain::TokenUsage`] for the canonical definition.
410pub use bamboo_domain::TokenUsage;
411
412pub use bamboo_domain::budget_types::TokenBudgetUsage;
413
414#[cfg(test)]
415mod tests {
416    use super::*;
417    use bamboo_domain::{TaskItem, TaskItemStatus, TaskList};
418
419    fn sample_task_list() -> TaskList {
420        TaskList {
421            session_id: "session-1".to_string(),
422            title: "Task List".to_string(),
423            items: vec![TaskItem {
424                id: "task_1".to_string(),
425                description: "Implement event rename".to_string(),
426                status: TaskItemStatus::InProgress,
427                depends_on: Vec::new(),
428                notes: "Implementing".to_string(),
429                ..TaskItem::default()
430            }],
431            created_at: Utc::now(),
432            updated_at: Utc::now(),
433        }
434    }
435
436    #[test]
437    fn task_list_updated_serializes_with_task_names() {
438        let event = AgentEvent::TaskListUpdated {
439            task_list: sample_task_list(),
440        };
441
442        let value = serde_json::to_value(event).expect("event should serialize");
443        assert_eq!(value["type"], "task_list_updated");
444        assert!(value.get("task_list").is_some());
445        assert!(value.get("todo_list").is_none());
446    }
447
448    #[test]
449    fn task_evaluation_completed_serializes_with_task_type() {
450        let event = AgentEvent::TaskEvaluationCompleted {
451            session_id: "session-1".to_string(),
452            updates_count: 2,
453            reasoning: "Updated statuses".to_string(),
454        };
455
456        let value = serde_json::to_value(event).expect("event should serialize");
457        assert_eq!(value["type"], "task_evaluation_completed");
458    }
459
460    #[test]
461    fn context_compression_status_serializes_with_phase_and_status() {
462        let event = AgentEvent::ContextCompressionStatus {
463            phase: "mid-turn".to_string(),
464            status: "started".to_string(),
465        };
466
467        let value = serde_json::to_value(event).expect("event should serialize");
468        assert_eq!(value["type"], "context_compression_status");
469        assert_eq!(value["phase"], "mid-turn");
470        assert_eq!(value["status"], "started");
471    }
472
473    #[test]
474    fn need_clarification_serializes_with_new_fields() {
475        let event = AgentEvent::NeedClarification {
476            question: "Continue?".to_string(),
477            options: Some(vec!["Yes".to_string(), "No".to_string()]),
478            tool_call_id: Some("tool-1".to_string()),
479            allow_custom: false,
480        };
481
482        let value = serde_json::to_value(event).expect("event should serialize");
483        assert_eq!(value["type"], "need_clarification");
484        assert_eq!(value["question"], "Continue?");
485        assert_eq!(value["options"], serde_json::json!(["Yes", "No"]));
486        assert_eq!(value["tool_call_id"], "tool-1");
487        assert_eq!(value["allow_custom"], false);
488    }
489
490    #[test]
491    fn need_clarification_deserializes_from_old_format_without_new_fields() {
492        let json = serde_json::json!({
493            "type": "need_clarification",
494            "question": "Continue?",
495            "options": ["Yes", "No"]
496        });
497
498        let event: AgentEvent =
499            serde_json::from_value(json).expect("should deserialize old format");
500        match event {
501            AgentEvent::NeedClarification {
502                question,
503                options,
504                tool_call_id,
505                allow_custom,
506            } => {
507                assert_eq!(question, "Continue?");
508                assert_eq!(options, Some(vec!["Yes".to_string(), "No".to_string()]));
509                assert_eq!(tool_call_id, None);
510                assert!(allow_custom); // default_allow_custom returns true
511            }
512            other => panic!("unexpected event: {other:?}"),
513        }
514    }
515
516    #[test]
517    fn need_clarification_deserializes_with_allow_custom_false() {
518        let json = serde_json::json!({
519            "type": "need_clarification",
520            "question": "Pick one",
521            "allow_custom": false
522        });
523
524        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
525        match event {
526            AgentEvent::NeedClarification {
527                question,
528                options,
529                tool_call_id,
530                allow_custom,
531            } => {
532                assert_eq!(question, "Pick one");
533                assert_eq!(options, None);
534                assert_eq!(tool_call_id, None);
535                assert!(!allow_custom);
536            }
537            other => panic!("unexpected event: {other:?}"),
538        }
539    }
540
541    #[test]
542    fn plan_mode_entered_serializes_correctly() {
543        let event = AgentEvent::PlanModeEntered {
544            session_id: "sess-1".to_string(),
545            reason: Some("Complex refactor".to_string()),
546            pre_permission_mode: "default".to_string(),
547        };
548
549        let value = serde_json::to_value(event).expect("event should serialize");
550        assert_eq!(value["type"], "plan_mode_entered");
551        assert_eq!(value["session_id"], "sess-1");
552        assert_eq!(value["reason"], "Complex refactor");
553        assert_eq!(value["pre_permission_mode"], "default");
554    }
555
556    #[test]
557    fn plan_mode_exited_serializes_correctly() {
558        let event = AgentEvent::PlanModeExited {
559            session_id: "sess-1".to_string(),
560            approved: true,
561            restored_mode: "accept_edits".to_string(),
562            plan: Some("# Plan\n1. Step one".to_string()),
563        };
564
565        let value = serde_json::to_value(event).expect("event should serialize");
566        assert_eq!(value["type"], "plan_mode_exited");
567        assert_eq!(value["session_id"], "sess-1");
568        assert_eq!(value["approved"], true);
569        assert_eq!(value["restored_mode"], "accept_edits");
570        assert_eq!(value["plan"], "# Plan\n1. Step one");
571    }
572
573    #[test]
574    fn plan_file_updated_serializes_correctly() {
575        let event = AgentEvent::PlanFileUpdated {
576            session_id: "sess-1".to_string(),
577            file_path: "/tmp/plans/sess-1.md".to_string(),
578            content_summary: "Implementation plan for feature X".to_string(),
579        };
580
581        let value = serde_json::to_value(event).expect("event should serialize");
582        assert_eq!(value["type"], "plan_file_updated");
583        assert_eq!(value["session_id"], "sess-1");
584        assert_eq!(value["file_path"], "/tmp/plans/sess-1.md");
585        assert_eq!(
586            value["content_summary"],
587            "Implementation plan for feature X"
588        );
589    }
590
591    #[test]
592    fn tool_approval_requested_serializes_correctly() {
593        let event = AgentEvent::ToolApprovalRequested {
594            tool_call_id: "call-abc".to_string(),
595            tool_name: "Write".to_string(),
596            parameters: serde_json::json!({"file_path": "/tmp/test.txt"}),
597        };
598
599        let value = serde_json::to_value(event).expect("event should serialize");
600        assert_eq!(value["type"], "tool_approval_requested");
601        assert_eq!(value["tool_call_id"], "call-abc");
602        assert_eq!(value["tool_name"], "Write");
603        assert_eq!(
604            value["parameters"],
605            serde_json::json!({"file_path": "/tmp/test.txt"})
606        );
607    }
608
609    #[test]
610    fn tool_approval_requested_deserializes_correctly() {
611        let json = serde_json::json!({
612            "type": "tool_approval_requested",
613            "tool_call_id": "call-xyz",
614            "tool_name": "Bash",
615            "parameters": {"command": "ls -la"}
616        });
617
618        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
619        match event {
620            AgentEvent::ToolApprovalRequested {
621                tool_call_id,
622                tool_name,
623                parameters,
624            } => {
625                assert_eq!(tool_call_id, "call-xyz");
626                assert_eq!(tool_name, "Bash");
627                assert_eq!(parameters, serde_json::json!({"command": "ls -la"}));
628            }
629            other => panic!("unexpected event: {other:?}"),
630        }
631    }
632
633    #[test]
634    fn plan_mode_events_deserialize_without_optional_fields() {
635        let json = serde_json::json!({
636            "type": "plan_mode_entered",
637            "session_id": "sess-1",
638            "pre_permission_mode": "default"
639        });
640
641        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
642        match event {
643            AgentEvent::PlanModeEntered {
644                session_id,
645                reason,
646                pre_permission_mode,
647            } => {
648                assert_eq!(session_id, "sess-1");
649                assert_eq!(reason, None);
650                assert_eq!(pre_permission_mode, "default");
651            }
652            other => panic!("unexpected event: {other:?}"),
653        }
654    }
655}