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**, **Cancelled**, 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/// - `GoldEvaluationStarted` - Gold observe-only evaluation began
69/// - `GoldEvaluationCompleted` - Gold observe-only evaluation finished
70///
71/// ## Context Management
72/// - `TokenBudgetUpdated` - Context budget changed
73/// - `ContextCompressionStatus` - Context compression lifecycle progress
74/// - `ContextSummarized` - Old messages summarized
75///
76/// ## Sub-agents (Async Spawn)
77/// - `SubAgentStarted` - A child session is created and scheduled to run
78/// - `SubAgentEvent` - Forwarded raw child event (full fidelity)
79/// - `SubAgentHeartbeat` - Periodic heartbeat while the child is running
80/// - `SubAgentCompleted` - Child session finished (completed/cancelled/error)
81///
82/// ## Terminal Events
83/// - `Complete` - Execution finished successfully
84/// - `Cancelled` - Execution was cancelled by the user
85/// - `Error` - Execution failed
86///
87/// # Serialization
88///
89/// Events are serialized as JSON with a `type` field for discrimination:
90/// ```json
91/// {"type": "token", "content": "Hello"}
92/// {"type": "complete", "usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15}}
93/// {"type": "cancelled", "message": "Agent execution cancelled by user"}
94/// ```
95#[derive(Debug, Clone, Serialize, Deserialize)]
96#[serde(tag = "type", rename_all = "snake_case")]
97pub enum AgentEvent {
98    /// Text token generated by the LLM.
99    Token {
100        /// Generated text content
101        content: String,
102    },
103
104    /// Reasoning/thinking token generated by the LLM.
105    ///
106    /// This is streamed separately from assistant answer tokens so the UI can
107    /// choose whether and how to display model reasoning traces.
108    ReasoningToken {
109        /// Generated reasoning content
110        content: String,
111    },
112
113    /// Streaming output emitted while a specific tool call is running.
114    ///
115    /// This is used to render "live output" inside a tool-call card in the UI
116    /// without mixing tool output into the assistant's main token stream.
117    ToolToken {
118        /// Tool call identifier that this output belongs to.
119        tool_call_id: String,
120        /// Output chunk.
121        content: String,
122    },
123
124    /// Tool execution started.
125    ToolStart {
126        /// Unique tool call identifier
127        tool_call_id: String,
128        /// Name of the tool being executed
129        tool_name: String,
130        /// Tool arguments (JSON)
131        arguments: serde_json::Value,
132    },
133
134    /// Tool execution completed successfully.
135    ToolComplete {
136        /// Tool call identifier
137        tool_call_id: String,
138        /// Tool execution result
139        result: ToolResult,
140    },
141
142    /// Tool execution failed.
143    ToolError {
144        /// Tool call identifier
145        tool_call_id: String,
146        /// Error message
147        error: String,
148    },
149
150    /// Structured lifecycle event for tool execution tracking.
151    ///
152    /// These events complement `ToolStart`/`ToolComplete`/`ToolError` with
153    /// richer metadata (mutability, auto-approval, wall-clock timing) and
154    /// are emitted by `ToolEmitter` (in `bamboo-agent-tools`).
155    ToolLifecycle {
156        /// Tool call identifier
157        tool_call_id: String,
158        /// Canonical tool name
159        tool_name: String,
160        /// Lifecycle phase: "begin", "finished", "error", "cancelled"
161        phase: String,
162        /// Wall-clock milliseconds since the call began (None for begin)
163        #[serde(skip_serializing_if = "Option::is_none")]
164        elapsed_ms: Option<u64>,
165        /// Whether the tool mutates state (writes files, runs commands)
166        is_mutating: bool,
167        /// Whether execution was auto-approved (no user prompt needed)
168        auto_approved: bool,
169        /// Human-readable summary
170        #[serde(skip_serializing_if = "Option::is_none")]
171        summary: Option<String>,
172        /// Error message (if phase == "error")
173        #[serde(skip_serializing_if = "Option::is_none")]
174        error: Option<String>,
175    },
176
177    /// Agent needs clarification from the user.
178    NeedClarification {
179        /// Question to ask the user
180        question: String,
181        /// Optional predefined options
182        options: Option<Vec<String>>,
183        /// Tool call identifier that triggered this clarification
184        #[serde(default, skip_serializing_if = "Option::is_none")]
185        tool_call_id: Option<String>,
186        /// Tool name that triggered this clarification, when known.
187        #[serde(default, skip_serializing_if = "Option::is_none")]
188        tool_name: Option<String>,
189        /// Whether the user can provide a free-text response
190        #[serde(default = "default_allow_custom")]
191        allow_custom: bool,
192    },
193
194    /// Emitted when task list is created or updated.
195    TaskListUpdated {
196        /// Current task list state.
197        task_list: TaskList,
198    },
199
200    /// Emitted when a task item makes progress (delta update).
201    TaskListItemProgress {
202        /// Session identifier
203        session_id: String,
204        /// Item identifier
205        item_id: String,
206        /// New item status
207        status: TaskItemStatus,
208        /// Number of tool calls made
209        tool_calls_count: usize,
210        /// Item version (for optimistic concurrency)
211        version: u64,
212    },
213
214    /// Emitted when all task items are completed.
215    TaskListCompleted {
216        /// Session identifier
217        session_id: String,
218        /// Completion timestamp
219        completed_at: DateTime<Utc>,
220        /// Total agent rounds executed
221        total_rounds: u32,
222        /// Total tool calls made
223        total_tool_calls: usize,
224    },
225
226    /// Emitted when task evaluation starts.
227    TaskEvaluationStarted {
228        /// Session identifier
229        session_id: String,
230        /// Number of items to evaluate
231        items_count: usize,
232    },
233
234    /// Emitted when task evaluation completes.
235    TaskEvaluationCompleted {
236        /// Session identifier
237        session_id: String,
238        /// Number of items updated
239        updates_count: usize,
240        /// Evaluation reasoning
241        reasoning: String,
242    },
243
244    /// Emitted when gold observe-only evaluation starts.
245    GoldEvaluationStarted {
246        /// Session identifier
247        session_id: String,
248        /// Evaluation checkpoint
249        checkpoint: GoldCheckpoint,
250        /// Current iteration / round number associated with the evaluation
251        iteration: u32,
252    },
253
254    /// Emitted when gold observe-only evaluation completes.
255    GoldEvaluationCompleted {
256        /// Session identifier
257        session_id: String,
258        /// Evaluation checkpoint
259        checkpoint: GoldCheckpoint,
260        /// Current iteration / round number associated with the evaluation
261        iteration: u32,
262        /// Gold decision for the current checkpoint
263        decision: GoldDecision,
264        /// Confidence in the decision
265        confidence: GoldConfidence,
266        /// Short reasoning summary
267        reasoning: String,
268    },
269
270    /// Emitted whenever the runtime goal state changes — a new status
271    /// (active/complete/blocked/…), an incremented continuation count, or a
272    /// freshly recorded side-channel double-check verdict. Lets the UI reflect
273    /// live goal progress without re-fetching history. Ephemeral: it rides only
274    /// the per-session `/events/{id}` stream; reconnecting clients read the
275    /// authoritative `goal_state` from the history endpoint instead.
276    GoalStatusChanged {
277        /// Session identifier
278        session_id: String,
279        /// Full serialized goal state — identical shape to the history
280        /// response's `goal_state` field (see `bamboo_engine::runtime::goal_state`).
281        goal_state: serde_json::Value,
282    },
283
284    /// Emitted when token budget is prepared (after context truncation)
285    TokenBudgetUpdated {
286        /// Token budget details
287        usage: TokenBudgetUsage,
288    },
289
290    /// Emitted when host-side context compression lifecycle changes.
291    ContextCompressionStatus {
292        /// Compression phase label (for example: pre-turn, mid-turn).
293        phase: String,
294        /// Compression status: started | completed | failed | skipped
295        status: String,
296    },
297
298    /// Emitted when conversation context is summarized
299    ContextSummarized {
300        /// Generated summary text
301        summary: String,
302        /// Number of old messages summarized
303        messages_summarized: usize,
304        /// Tokens saved by summarization
305        tokens_saved: u32,
306        /// Context usage percentage before compression
307        #[serde(default)]
308        usage_before_percent: f64,
309        /// Context usage percentage after compression
310        #[serde(default)]
311        usage_after_percent: f64,
312        /// What triggered the compression: "auto" | "manual" | "critical"
313        #[serde(default)]
314        trigger_type: String,
315    },
316
317    /// Emitted when context pressure reaches warning or critical levels.
318    /// Frontend should display this to the user as a proactive notification.
319    ContextPressureNotification {
320        /// Context usage as a percentage of the context window.
321        percent: f64,
322        /// Severity level: "warning" (70%) or "critical" (90%).
323        level: String,
324        /// Human-readable message describing the pressure state.
325        message: String,
326    },
327
328    /// A child session was spawned from a parent session (async background job).
329    SubAgentStarted {
330        parent_session_id: String,
331        child_session_id: String,
332        /// Optional title (useful for UI lists).
333        #[serde(default, skip_serializing_if = "Option::is_none")]
334        title: Option<String>,
335    },
336
337    /// Forwarded raw child event to the parent session stream.
338    ///
339    /// Child sessions are not allowed to spawn further sessions, so this should not nest.
340    SubAgentEvent {
341        parent_session_id: String,
342        child_session_id: String,
343        event: Box<AgentEvent>,
344    },
345
346    /// Heartbeat emitted while a child session is running.
347    SubAgentHeartbeat {
348        parent_session_id: String,
349        child_session_id: String,
350        timestamp: DateTime<Utc>,
351    },
352
353    /// Child session finished (completed/cancelled/error).
354    SubAgentCompleted {
355        parent_session_id: String,
356        child_session_id: String,
357        /// One of: "completed" | "cancelled" | "error" | "skipped"
358        status: String,
359        #[serde(default, skip_serializing_if = "Option::is_none")]
360        error: Option<String>,
361    },
362
363    /// Plan mode was entered.
364    PlanModeEntered {
365        /// Session identifier
366        session_id: String,
367        /// Optional reason for entering plan mode
368        #[serde(default, skip_serializing_if = "Option::is_none")]
369        reason: Option<String>,
370        /// Previous permission mode before entering plan mode
371        pre_permission_mode: String,
372        /// RFC3339 timestamp when plan mode was entered.
373        entered_at: chrono::DateTime<chrono::Utc>,
374        /// Current plan mode phase/status.
375        status: bamboo_domain::PlanModeStatus,
376        /// Path to the persisted plan file, if already available.
377        #[serde(default, skip_serializing_if = "Option::is_none")]
378        plan_file_path: Option<String>,
379    },
380
381    /// Plan mode was exited.
382    PlanModeExited {
383        /// Session identifier
384        session_id: String,
385        /// Whether the exit was approved by the user
386        approved: bool,
387        /// The permission mode restored after exiting
388        restored_mode: String,
389        /// Plan content that was reviewed, if any
390        #[serde(default, skip_serializing_if = "Option::is_none")]
391        plan: Option<String>,
392    },
393
394    /// Plan file was updated.
395    PlanFileUpdated {
396        /// Session identifier
397        session_id: String,
398        /// Path to the plan file
399        file_path: String,
400        /// Summary of the plan content (truncated)
401        content_summary: String,
402    },
403
404    /// Runner progress update emitted at the start of each agent turn.
405    ///
406    /// Used to track live execution progress (round count, current activity)
407    /// for diagnostic visibility, especially for child sessions.
408    RunnerProgress {
409        /// Session identifier
410        session_id: String,
411        /// Current turn/round count
412        round_count: u32,
413    },
414
415    /// Session title was updated (auto-generated by backend or manually renamed via PATCH).
416    SessionTitleUpdated {
417        session_id: String,
418        title: String,
419        title_version: u64,
420        source: TitleSource,
421        updated_at: chrono::DateTime<chrono::Utc>,
422    },
423
424    /// Session pinned flag was toggled via PATCH.
425    ///
426    /// Replayable metadata event. `pinned` is an idempotent boolean so the
427    /// latest event wins; `updated_at` is used by the frontend to suppress
428    /// stale replays.
429    SessionPinnedUpdated {
430        session_id: String,
431        pinned: bool,
432        updated_at: chrono::DateTime<chrono::Utc>,
433    },
434
435    /// A new session was created.
436    ///
437    /// Change-feed event: durable, journaled, carried on the account `/stream`
438    /// feed so other clients can insert the session into their list without a
439    /// full `GET /sessions` poll.
440    SessionCreated {
441        session_id: String,
442        title: String,
443        kind: bamboo_domain::SessionKind,
444        created_at: chrono::DateTime<chrono::Utc>,
445    },
446
447    /// A session was deleted.
448    ///
449    /// Change-feed event: durable, journaled. Clients remove the session from
450    /// their local list on receipt.
451    SessionDeleted { session_id: String },
452
453    /// A session's message history was cleared (session kept).
454    ///
455    /// Change-feed event: durable, journaled. Clients drop cached messages for
456    /// the session and refetch lazily.
457    SessionCleared { session_id: String },
458
459    /// A message was appended to a session.
460    ///
461    /// Change-feed event: durable, journaled. The `seq` assigned to this event
462    /// on the account feed is the message's feed coordinate (used by
463    /// `GET /history/{id}?since={seq}` to compute deltas). `content` is the
464    /// plain-text body matching what `/history` returns to the UI.
465    MessageAppended {
466        session_id: String,
467        message_id: String,
468        role: bamboo_domain::Role,
469        content: String,
470        created_at: chrono::DateTime<chrono::Utc>,
471    },
472
473    /// Execution run has started and the runner is now active.
474    ///
475    /// Emitted as the first event after a runner reservation succeeds,
476    /// before any token or tool events. Carries the `run_id` so the
477    /// frontend can correlate subsequent SSE events across reconnects.
478    ExecutionStarted {
479        /// Unique identifier for this execution run.
480        run_id: String,
481        /// Session identifier.
482        session_id: String,
483        /// ISO 8601 timestamp when the run started.
484        started_at: String,
485    },
486
487    /// Tool execution requires user approval before proceeding.
488    ///
489    /// Emitted when a permission checker determines that a tool call needs
490    /// explicit user confirmation (e.g., mutating operations in restricted
491    /// permission mode). The frontend should present the approval request and
492    /// either grant or deny it.
493    ToolApprovalRequested {
494        /// Unique identifier for the tool call awaiting approval.
495        tool_call_id: String,
496        /// Name of the tool being executed.
497        tool_name: String,
498        /// Parameters that were passed to the tool.
499        parameters: serde_json::Value,
500    },
501
502    /// Agent execution completed successfully.
503    Complete {
504        /// Final token usage statistics
505        usage: TokenUsage,
506    },
507
508    /// Agent execution was cancelled.
509    Cancelled {
510        /// Optional human-readable message explaining the cancellation.
511        #[serde(default, skip_serializing_if = "Option::is_none")]
512        message: Option<String>,
513    },
514
515    /// Agent execution failed.
516    Error {
517        /// Error message
518        message: String,
519    },
520
521    /// A user-facing notification derived from agent activity by the backend
522    /// notification policy. Clients render this (e.g. an OS desktop notification)
523    /// after applying their own presence checks (window focus). The decision of
524    /// *whether* to notify — category, priority, preference gating, dedup — is
525    /// made server-side in `bamboo-notification`; the client just delivers it.
526    Notification {
527        /// Unique id (for client-side dedup / dismissal).
528        id: String,
529        /// Session this notification is about.
530        session_id: String,
531        /// Category, e.g. `needs_approval` | `needs_clarification` | `run_completed`
532        /// | `run_failed` | `subagent_completed` | `context_critical`.
533        category: String,
534        /// Priority: `high` | `normal` | `low`.
535        priority: String,
536        /// Short title line.
537        title: String,
538        /// Body text.
539        body: String,
540        /// Stable key for client-side coalescing within a short window.
541        #[serde(default, skip_serializing_if = "Option::is_none")]
542        dedup_key: Option<String>,
543        /// RFC3339 creation timestamp.
544        created_at: String,
545    },
546}
547
548impl AgentEvent {
549    /// Returns the session this event pertains to, when it carries one.
550    ///
551    /// Used by the account change-feed to route each event to the right
552    /// client-side session without a per-session connection. For sub-agent
553    /// events the *parent* session id is returned (that is the session a client
554    /// observes in its list). Pure streaming/diagnostic variants (`Token`,
555    /// `Complete`, …) return `None`; those are ephemeral and never ride the
556    /// account feed anyway.
557    pub fn session_id(&self) -> Option<&str> {
558        match self {
559            AgentEvent::TaskListUpdated { task_list } => Some(task_list.session_id.as_str()),
560            AgentEvent::TaskListItemProgress { session_id, .. }
561            | AgentEvent::TaskListCompleted { session_id, .. }
562            | AgentEvent::TaskEvaluationStarted { session_id, .. }
563            | AgentEvent::TaskEvaluationCompleted { session_id, .. }
564            | AgentEvent::GoldEvaluationStarted { session_id, .. }
565            | AgentEvent::GoldEvaluationCompleted { session_id, .. }
566            | AgentEvent::GoalStatusChanged { session_id, .. }
567            | AgentEvent::PlanModeEntered { session_id, .. }
568            | AgentEvent::PlanModeExited { session_id, .. }
569            | AgentEvent::PlanFileUpdated { session_id, .. }
570            | AgentEvent::RunnerProgress { session_id, .. }
571            | AgentEvent::SessionTitleUpdated { session_id, .. }
572            | AgentEvent::SessionPinnedUpdated { session_id, .. }
573            | AgentEvent::SessionCreated { session_id, .. }
574            | AgentEvent::SessionDeleted { session_id, .. }
575            | AgentEvent::SessionCleared { session_id, .. }
576            | AgentEvent::MessageAppended { session_id, .. }
577            | AgentEvent::ExecutionStarted { session_id, .. }
578            | AgentEvent::Notification { session_id, .. } => Some(session_id.as_str()),
579            AgentEvent::SubAgentStarted {
580                parent_session_id, ..
581            }
582            | AgentEvent::SubAgentEvent {
583                parent_session_id, ..
584            }
585            | AgentEvent::SubAgentHeartbeat {
586                parent_session_id, ..
587            }
588            | AgentEvent::SubAgentCompleted {
589                parent_session_id, ..
590            } => Some(parent_session_id.as_str()),
591            _ => None,
592        }
593    }
594
595    /// Whether this event belongs on the durable account change feed.
596    ///
597    /// Durable change events are low-volume, journaled to disk, and resumable
598    /// via the account `/stream` feed. Ephemeral events — token-by-token
599    /// streaming (`Token`/`ReasoningToken`/`ToolToken`), heartbeats, live
600    /// budget/pressure gauges, and raw forwarded sub-agent events — return
601    /// `false`: they stay exclusively on the per-session `/events/{id}` stream.
602    /// Keeping them off the journal and the multiplexed feed is the core
603    /// data-transfer win. This method lives in core so both the server and the
604    /// engine forwarder can filter before cloning onto the feed.
605    pub fn is_durable_change(&self) -> bool {
606        matches!(
607            self,
608            AgentEvent::MessageAppended { .. }
609                | AgentEvent::SessionCreated { .. }
610                | AgentEvent::SessionDeleted { .. }
611                | AgentEvent::SessionCleared { .. }
612                | AgentEvent::SessionTitleUpdated { .. }
613                | AgentEvent::SessionPinnedUpdated { .. }
614                | AgentEvent::TaskListUpdated { .. }
615                | AgentEvent::TaskListItemProgress { .. }
616                | AgentEvent::TaskListCompleted { .. }
617                | AgentEvent::TaskEvaluationCompleted { .. }
618                | AgentEvent::PlanModeEntered { .. }
619                | AgentEvent::PlanModeExited { .. }
620                | AgentEvent::PlanFileUpdated { .. }
621                | AgentEvent::SubAgentStarted { .. }
622                | AgentEvent::SubAgentCompleted { .. }
623                | AgentEvent::NeedClarification { .. }
624                | AgentEvent::ToolApprovalRequested { .. }
625                | AgentEvent::ExecutionStarted { .. }
626                | AgentEvent::Complete { .. }
627                | AgentEvent::Cancelled { .. }
628                | AgentEvent::Error { .. }
629        )
630    }
631}
632
633fn default_allow_custom() -> bool {
634    true
635}
636
637/// Gold evaluation checkpoint.
638#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
639#[serde(rename_all = "snake_case")]
640pub enum GoldCheckpoint {
641    PostRound,
642    Terminal,
643}
644
645impl GoldCheckpoint {
646    pub fn as_str(self) -> &'static str {
647        match self {
648            Self::PostRound => "post_round",
649            Self::Terminal => "terminal",
650        }
651    }
652}
653
654/// Gold evaluator decision.
655#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
656#[serde(rename_all = "snake_case")]
657pub enum GoldDecision {
658    Continue,
659    Achieved,
660    Blocked,
661    NeedInput,
662    Exhausted,
663}
664
665impl GoldDecision {
666    pub fn as_str(self) -> &'static str {
667        match self {
668            Self::Continue => "continue",
669            Self::Achieved => "achieved",
670            Self::Blocked => "blocked",
671            Self::NeedInput => "need_input",
672            Self::Exhausted => "exhausted",
673        }
674    }
675}
676
677/// Confidence level for a Gold evaluation result.
678#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
679#[serde(rename_all = "snake_case")]
680pub enum GoldConfidence {
681    Low,
682    Medium,
683    High,
684}
685
686impl GoldConfidence {
687    pub fn as_str(self) -> &'static str {
688        match self {
689            Self::Low => "low",
690            Self::Medium => "medium",
691            Self::High => "high",
692        }
693    }
694
695    /// Ordinal rank for threshold comparisons (`Low` < `Medium` < `High`).
696    pub fn rank(self) -> u8 {
697        match self {
698            Self::Low => 0,
699            Self::Medium => 1,
700            Self::High => 2,
701        }
702    }
703
704    /// Whether this confidence meets or exceeds the given floor.
705    pub fn meets(self, floor: GoldConfidence) -> bool {
706        self.rank() >= floor.rank()
707    }
708}
709
710/// Source that triggered a session title update.
711#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
712#[serde(rename_all = "snake_case")]
713pub enum TitleSource {
714    Auto,
715    Manual,
716    Fallback,
717}
718
719/// Re-exported shared token usage type.
720///
721/// See [`bamboo_domain::TokenUsage`] for the canonical definition.
722pub use bamboo_domain::TokenUsage;
723
724pub use bamboo_domain::budget_types::TokenBudgetUsage;
725
726#[cfg(test)]
727mod tests {
728    use super::*;
729    use bamboo_domain::{TaskItem, TaskItemStatus, TaskList};
730
731    fn sample_task_list() -> TaskList {
732        TaskList {
733            session_id: "session-1".to_string(),
734            title: "Task List".to_string(),
735            items: vec![TaskItem {
736                id: "task_1".to_string(),
737                description: "Implement event rename".to_string(),
738                status: TaskItemStatus::InProgress,
739                depends_on: Vec::new(),
740                notes: "Implementing".to_string(),
741                ..TaskItem::default()
742            }],
743            created_at: Utc::now(),
744            updated_at: Utc::now(),
745        }
746    }
747
748    #[test]
749    fn task_list_updated_serializes_with_task_names() {
750        let event = AgentEvent::TaskListUpdated {
751            task_list: sample_task_list(),
752        };
753
754        let value = serde_json::to_value(event).expect("event should serialize");
755        assert_eq!(value["type"], "task_list_updated");
756        assert!(value.get("task_list").is_some());
757        assert!(value.get("todo_list").is_none());
758    }
759
760    #[test]
761    fn cancelled_serializes_with_snake_case_type() {
762        let event = AgentEvent::Cancelled {
763            message: Some("Agent execution cancelled by user".to_string()),
764        };
765
766        let value = serde_json::to_value(event).expect("event should serialize");
767        assert_eq!(value["type"], "cancelled");
768        assert_eq!(
769            value["message"],
770            serde_json::Value::String("Agent execution cancelled by user".to_string())
771        );
772    }
773
774    #[test]
775    fn task_evaluation_completed_serializes_with_task_type() {
776        let event = AgentEvent::TaskEvaluationCompleted {
777            session_id: "session-1".to_string(),
778            updates_count: 2,
779            reasoning: "Updated statuses".to_string(),
780        };
781
782        let value = serde_json::to_value(event).expect("event should serialize");
783        assert_eq!(value["type"], "task_evaluation_completed");
784    }
785
786    #[test]
787    fn gold_evaluation_completed_serializes_with_gold_type_and_fields() {
788        let event = AgentEvent::GoldEvaluationCompleted {
789            session_id: "session-1".to_string(),
790            checkpoint: GoldCheckpoint::PostRound,
791            iteration: 3,
792            decision: GoldDecision::Continue,
793            confidence: GoldConfidence::Medium,
794            reasoning: "Need one more iteration".to_string(),
795        };
796
797        let value = serde_json::to_value(event).expect("event should serialize");
798        assert_eq!(value["type"], "gold_evaluation_completed");
799        assert_eq!(value["checkpoint"], "post_round");
800        assert_eq!(value["iteration"], 3);
801        assert_eq!(value["decision"], "continue");
802        assert_eq!(value["confidence"], "medium");
803        assert_eq!(value["reasoning"], "Need one more iteration");
804    }
805
806    #[test]
807    fn gold_evaluation_started_deserializes() {
808        let json = serde_json::json!({
809            "type": "gold_evaluation_started",
810            "session_id": "session-1",
811            "checkpoint": "terminal",
812            "iteration": 7
813        });
814
815        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
816        match event {
817            AgentEvent::GoldEvaluationStarted {
818                session_id,
819                checkpoint,
820                iteration,
821            } => {
822                assert_eq!(session_id, "session-1");
823                assert_eq!(checkpoint, GoldCheckpoint::Terminal);
824                assert_eq!(iteration, 7);
825            }
826            other => panic!("unexpected event: {other:?}"),
827        }
828    }
829
830    #[test]
831    fn context_compression_status_serializes_with_phase_and_status() {
832        let event = AgentEvent::ContextCompressionStatus {
833            phase: "mid-turn".to_string(),
834            status: "started".to_string(),
835        };
836
837        let value = serde_json::to_value(event).expect("event should serialize");
838        assert_eq!(value["type"], "context_compression_status");
839        assert_eq!(value["phase"], "mid-turn");
840        assert_eq!(value["status"], "started");
841    }
842
843    #[test]
844    fn need_clarification_serializes_with_new_fields() {
845        let event = AgentEvent::NeedClarification {
846            question: "Continue?".to_string(),
847            options: Some(vec!["Yes".to_string(), "No".to_string()]),
848            tool_call_id: Some("tool-1".to_string()),
849            tool_name: Some("conclusion_with_options".to_string()),
850            allow_custom: false,
851        };
852
853        let value = serde_json::to_value(event).expect("event should serialize");
854        assert_eq!(value["type"], "need_clarification");
855        assert_eq!(value["question"], "Continue?");
856        assert_eq!(value["options"], serde_json::json!(["Yes", "No"]));
857        assert_eq!(value["tool_call_id"], "tool-1");
858        assert_eq!(value["tool_name"], "conclusion_with_options");
859        assert_eq!(value["allow_custom"], false);
860    }
861
862    #[test]
863    fn need_clarification_deserializes_from_old_format_without_new_fields() {
864        let json = serde_json::json!({
865            "type": "need_clarification",
866            "question": "Continue?",
867            "options": ["Yes", "No"]
868        });
869
870        let event: AgentEvent =
871            serde_json::from_value(json).expect("should deserialize old format");
872        match event {
873            AgentEvent::NeedClarification {
874                question,
875                options,
876                tool_call_id,
877                tool_name,
878                allow_custom,
879            } => {
880                assert_eq!(question, "Continue?");
881                assert_eq!(options, Some(vec!["Yes".to_string(), "No".to_string()]));
882                assert_eq!(tool_call_id, None);
883                assert_eq!(tool_name, None);
884                assert!(allow_custom); // default_allow_custom returns true
885            }
886            other => panic!("unexpected event: {other:?}"),
887        }
888    }
889
890    #[test]
891    fn need_clarification_deserializes_with_allow_custom_false() {
892        let json = serde_json::json!({
893            "type": "need_clarification",
894            "question": "Pick one",
895            "allow_custom": false
896        });
897
898        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
899        match event {
900            AgentEvent::NeedClarification {
901                question,
902                options,
903                tool_call_id,
904                tool_name,
905                allow_custom,
906            } => {
907                assert_eq!(question, "Pick one");
908                assert_eq!(options, None);
909                assert_eq!(tool_call_id, None);
910                assert_eq!(tool_name, None);
911                assert!(!allow_custom);
912            }
913            other => panic!("unexpected event: {other:?}"),
914        }
915    }
916
917    #[test]
918    fn plan_mode_entered_serializes_correctly() {
919        let entered_at = Utc::now();
920        let event = AgentEvent::PlanModeEntered {
921            session_id: "sess-1".to_string(),
922            reason: Some("Complex refactor".to_string()),
923            pre_permission_mode: "default".to_string(),
924            entered_at,
925            status: bamboo_domain::PlanModeStatus::Exploring,
926            plan_file_path: None,
927        };
928
929        let value = serde_json::to_value(event).expect("event should serialize");
930        assert_eq!(value["type"], "plan_mode_entered");
931        assert_eq!(value["session_id"], "sess-1");
932        assert_eq!(value["reason"], "Complex refactor");
933        assert_eq!(value["pre_permission_mode"], "default");
934        assert_eq!(value["status"], "exploring");
935        // Compare against serde's own serialization (RFC3339 with `Z` for UTC),
936        // not `to_rfc3339()` which emits a `+00:00` offset instead.
937        assert_eq!(
938            value["entered_at"],
939            serde_json::to_value(entered_at).unwrap()
940        );
941    }
942
943    #[test]
944    fn plan_mode_exited_serializes_correctly() {
945        let event = AgentEvent::PlanModeExited {
946            session_id: "sess-1".to_string(),
947            approved: true,
948            restored_mode: "accept_edits".to_string(),
949            plan: Some("# Plan\n1. Step one".to_string()),
950        };
951
952        let value = serde_json::to_value(event).expect("event should serialize");
953        assert_eq!(value["type"], "plan_mode_exited");
954        assert_eq!(value["session_id"], "sess-1");
955        assert_eq!(value["approved"], true);
956        assert_eq!(value["restored_mode"], "accept_edits");
957        assert_eq!(value["plan"], "# Plan\n1. Step one");
958    }
959
960    #[test]
961    fn plan_file_updated_serializes_correctly() {
962        let event = AgentEvent::PlanFileUpdated {
963            session_id: "sess-1".to_string(),
964            file_path: "/tmp/plans/sess-1.md".to_string(),
965            content_summary: "Implementation plan for feature X".to_string(),
966        };
967
968        let value = serde_json::to_value(event).expect("event should serialize");
969        assert_eq!(value["type"], "plan_file_updated");
970        assert_eq!(value["session_id"], "sess-1");
971        assert_eq!(value["file_path"], "/tmp/plans/sess-1.md");
972        assert_eq!(
973            value["content_summary"],
974            "Implementation plan for feature X"
975        );
976    }
977
978    #[test]
979    fn tool_approval_requested_serializes_correctly() {
980        let event = AgentEvent::ToolApprovalRequested {
981            tool_call_id: "call-abc".to_string(),
982            tool_name: "Write".to_string(),
983            parameters: serde_json::json!({"file_path": "/tmp/test.txt"}),
984        };
985
986        let value = serde_json::to_value(event).expect("event should serialize");
987        assert_eq!(value["type"], "tool_approval_requested");
988        assert_eq!(value["tool_call_id"], "call-abc");
989        assert_eq!(value["tool_name"], "Write");
990        assert_eq!(
991            value["parameters"],
992            serde_json::json!({"file_path": "/tmp/test.txt"})
993        );
994    }
995
996    #[test]
997    fn tool_approval_requested_deserializes_correctly() {
998        let json = serde_json::json!({
999            "type": "tool_approval_requested",
1000            "tool_call_id": "call-xyz",
1001            "tool_name": "Bash",
1002            "parameters": {"command": "ls -la"}
1003        });
1004
1005        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
1006        match event {
1007            AgentEvent::ToolApprovalRequested {
1008                tool_call_id,
1009                tool_name,
1010                parameters,
1011            } => {
1012                assert_eq!(tool_call_id, "call-xyz");
1013                assert_eq!(tool_name, "Bash");
1014                assert_eq!(parameters, serde_json::json!({"command": "ls -la"}));
1015            }
1016            other => panic!("unexpected event: {other:?}"),
1017        }
1018    }
1019
1020    #[test]
1021    fn session_title_updated_round_trips_with_source_variants() {
1022        use chrono::Utc;
1023        let event = AgentEvent::SessionTitleUpdated {
1024            session_id: "sess-1".to_string(),
1025            title: "My title".to_string(),
1026            title_version: 3,
1027            source: TitleSource::Auto,
1028            updated_at: Utc::now(),
1029        };
1030        let json = serde_json::to_string(&event).unwrap();
1031        assert!(
1032            json.contains("\"type\":\"session_title_updated\""),
1033            "json: {json}"
1034        );
1035        assert!(json.contains("\"source\":\"auto\""), "json: {json}");
1036        let _decoded: AgentEvent = serde_json::from_str(&json).unwrap();
1037    }
1038
1039    #[test]
1040    fn plan_mode_events_deserialize_without_optional_fields() {
1041        let json = serde_json::json!({
1042            "type": "plan_mode_entered",
1043            "session_id": "sess-1",
1044            "pre_permission_mode": "default",
1045            "entered_at": "2025-01-01T00:00:00Z",
1046            "status": "exploring"
1047        });
1048
1049        let event: AgentEvent = serde_json::from_value(json).expect("should deserialize");
1050        match event {
1051            AgentEvent::PlanModeEntered {
1052                session_id,
1053                reason,
1054                pre_permission_mode,
1055                entered_at,
1056                status,
1057                plan_file_path,
1058            } => {
1059                assert_eq!(session_id, "sess-1");
1060                assert_eq!(reason, None);
1061                assert_eq!(pre_permission_mode, "default");
1062                assert_eq!(entered_at.to_rfc3339(), "2025-01-01T00:00:00+00:00");
1063                assert_eq!(status, bamboo_domain::PlanModeStatus::Exploring);
1064                assert_eq!(plan_file_path, None);
1065            }
1066            other => panic!("unexpected event: {other:?}"),
1067        }
1068    }
1069}