codive-core 0.1.0

Core types, traits, and utilities for Codive
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
//! Event system for pub/sub communication
//!
//! This module provides an event bus that allows components to communicate
//! without direct coupling. The event bus uses broadcast channels to allow
//! multiple subscribers to receive the same events.
//!
//! # Architecture
//!
//! ```text
//! Publishers                    EventBus                  Subscribers
//! ┌─────────┐                  ┌────────┐                ┌─────────────┐
//! │  Agent  │──publish()──────▶│        │───recv()──────▶│ SSE Handler │
//! └─────────┘                  │        │                └─────────────┘
//!                              │        │                ┌─────────────┐
//! ┌─────────┐                  │        │───recv()──────▶│   Logger    │
//! │ Session │──publish()──────▶│        │                └─────────────┘
//! └─────────┘                  └────────┘                ┌─────────────┐
//!                                                        │   WebSocket │
//!                              subscribe() ─────────────▶└─────────────┘
//! ```
//!
//! # Usage
//!
//! ```rust
//! use codive_core::event::{Event, EventBus};
//!
//! #[tokio::main]
//! async fn main() {
//!     let bus = EventBus::new();
//!
//!     // Subscribe to events
//!     let mut rx = bus.subscribe();
//!
//!     // Publish an event
//!     bus.publish(Event::SessionCreated {
//!         session_id: "sess_123".into(),
//!     });
//!
//!     // Receive the event
//!     if let Ok(event) = rx.recv().await {
//!         println!("Received: {:?}", event);
//!     }
//! }
//! ```

use crate::tool::FileChangeMetadata;
use serde::{Deserialize, Serialize};
use tokio::sync::broadcast;

/// Default capacity for the event bus channel
const DEFAULT_CHANNEL_CAPACITY: usize = 1024;

// ============================================================================
// Event
// ============================================================================

/// Events that can occur in the agent system
///
/// These events are published on the event bus and can be subscribed to
/// by any component. They're designed to be serializable for sending
/// over SSE/WebSocket connections.
///
/// # Event Categories
///
/// - **Session events** - Session lifecycle (created, deleted)
/// - **Message events** - Message and streaming updates
/// - **Tool events** - Tool execution lifecycle
/// - **Agent events** - Agent state changes
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Event {
    // =========================================================================
    // Session Events
    // =========================================================================
    /// A new session was created
    SessionCreated {
        /// The new session's ID
        session_id: String,
    },

    /// A session was deleted
    SessionDeleted {
        /// The deleted session's ID
        session_id: String,
    },

    /// A session's title was updated
    SessionTitleChanged {
        /// The session ID
        session_id: String,
        /// The new title
        title: String,
    },

    // =========================================================================
    // Message Events
    // =========================================================================
    /// A new message was added to a session
    MessageCreated {
        /// The session ID
        session_id: String,
        /// The new message ID
        message_id: String,
        /// Role of the message sender
        role: String,
    },

    /// Streaming text delta for a message
    MessageDelta {
        /// The session ID
        session_id: String,
        /// The message being streamed
        message_id: String,
        /// The text fragment
        delta: String,
    },

    /// Message streaming completed
    MessageComplete {
        /// The session ID
        session_id: String,
        /// The completed message ID
        message_id: String,
    },

    // =========================================================================
    // Tool Events
    // =========================================================================
    /// A tool execution started
    ToolCallStarted {
        /// The session ID
        session_id: String,
        /// Unique ID for this tool call
        tool_call_id: String,
        /// Name of the tool
        tool_name: String,
        /// Tool arguments/parameters (JSON)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        arguments: Option<serde_json::Value>,
    },

    /// A tool execution completed
    ToolCallCompleted {
        /// The session ID
        session_id: String,
        /// The tool call ID
        tool_call_id: String,
        /// Whether the tool succeeded
        success: bool,
        /// Optional file change metadata (for diff display)
        #[serde(default, skip_serializing_if = "Option::is_none")]
        file_change: Option<FileChangeMetadata>,
    },

    // =========================================================================
    // Agent Events
    // =========================================================================
    /// Agent started thinking/processing
    AgentThinking {
        /// The session ID
        session_id: String,
    },

    /// Agent finished processing
    AgentIdle {
        /// The session ID
        session_id: String,
    },

    /// An error occurred
    Error {
        /// The session ID (if applicable)
        session_id: Option<String>,
        /// Error message
        message: String,
    },
}

impl Event {
    /// Get the session ID associated with this event, if any
    pub fn session_id(&self) -> Option<&str> {
        match self {
            Event::SessionCreated { session_id }
            | Event::SessionDeleted { session_id }
            | Event::SessionTitleChanged { session_id, .. }
            | Event::MessageCreated { session_id, .. }
            | Event::MessageDelta { session_id, .. }
            | Event::MessageComplete { session_id, .. }
            | Event::ToolCallStarted { session_id, .. }
            | Event::ToolCallCompleted { session_id, .. }
            | Event::AgentThinking { session_id }
            | Event::AgentIdle { session_id } => Some(session_id),
            Event::Error { session_id, .. } => session_id.as_deref(),
        }
    }

    /// Check if this is an error event
    pub fn is_error(&self) -> bool {
        matches!(self, Event::Error { .. })
    }

    /// Create a session created event
    pub fn session_created(session_id: impl Into<String>) -> Self {
        Self::SessionCreated {
            session_id: session_id.into(),
        }
    }

    /// Create a message delta event
    pub fn message_delta(
        session_id: impl Into<String>,
        message_id: impl Into<String>,
        delta: impl Into<String>,
    ) -> Self {
        Self::MessageDelta {
            session_id: session_id.into(),
            message_id: message_id.into(),
            delta: delta.into(),
        }
    }

    /// Create an error event
    pub fn error(session_id: Option<String>, message: impl Into<String>) -> Self {
        Self::Error {
            session_id,
            message: message.into(),
        }
    }
}

// ============================================================================
// EventBus
// ============================================================================

/// A pub/sub event bus for broadcasting events to multiple subscribers
///
/// The event bus uses Tokio's broadcast channel internally. This means:
/// - Multiple subscribers can receive the same event
/// - Late subscribers only receive events published after they subscribed
/// - If a subscriber falls behind, older events are dropped (lagged)
///
/// # Thread Safety
///
/// The EventBus is `Clone` and can be shared across threads. All clones
/// share the same underlying channel, so events published on one clone
/// are received by subscribers on all clones.
#[derive(Clone)]
pub struct EventBus {
    sender: broadcast::Sender<Event>,
}

impl EventBus {
    /// Create a new event bus with default capacity
    pub fn new() -> Self {
        Self::with_capacity(DEFAULT_CHANNEL_CAPACITY)
    }

    /// Create a new event bus with custom capacity
    ///
    /// The capacity determines how many events can be buffered before
    /// slow subscribers start missing events (lagging).
    pub fn with_capacity(capacity: usize) -> Self {
        let (sender, _) = broadcast::channel(capacity);
        Self { sender }
    }

    /// Subscribe to events
    ///
    /// Returns a receiver that will receive all events published after
    /// this subscription was created. Events published before are not
    /// received (this is not a replay channel).
    pub fn subscribe(&self) -> broadcast::Receiver<Event> {
        self.sender.subscribe()
    }

    /// Publish an event to all subscribers
    ///
    /// Returns the number of subscribers that received the event.
    /// Note: A return value of 0 means no one is listening.
    pub fn publish(&self, event: Event) -> usize {
        // send() returns Err if there are no receivers, but that's ok
        self.sender.send(event).unwrap_or(0)
    }

    /// Get the number of active subscribers
    pub fn subscriber_count(&self) -> usize {
        self.sender.receiver_count()
    }
}

impl Default for EventBus {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for EventBus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventBus")
            .field("subscriber_count", &self.subscriber_count())
            .finish()
    }
}

// ============================================================================
// RUST CONCEPTS EXPLAINED (for learning)
// ============================================================================
//
// 1. `tokio::sync::broadcast`
//    - Multi-producer, multi-consumer channel
//    - All subscribers receive all messages (unlike mpsc)
//    - Has a fixed capacity - old messages dropped when full
//    - Perfect for pub/sub patterns like event buses
//
// 2. `#[derive(Clone)]` for EventBus
//    - Makes EventBus copyable (shallow copy)
//    - All clones share the same underlying channel
//    - This is how you share the bus across components
//
// 3. `broadcast::Sender<T>` and `broadcast::Receiver<T>`
//    - Sender is Clone - can have multiple publishers
//    - Receiver is NOT Clone - each subscriber gets their own
//    - `subscribe()` creates a new receiver from the sender
//
// 4. `#[serde(tag = "type")]` on Event
//    - Serializes as: `{"type": "session_created", "session_id": "..."}`
//    - Essential for SSE where clients need to know event type
//    - Also called "tagged" or "discriminated" union in JSON
//
// 5. Pattern matching with `|`
//    - `Event::A { x } | Event::B { x }` matches both variants
//    - All alternatives must bind the same variables
//    - Clean way to extract common fields from enums
//
// 6. `unwrap_or(0)` on send result
//    - `send()` returns `Err` if no receivers exist
//    - We don't care - publishing to no one is fine
//    - Returns count of receivers that got the message
//
// **📚 Read:**
// - [Tokio Channels](https://tokio.rs/tokio/tutorial/channels)
// - [Broadcast channel docs](https://docs.rs/tokio/latest/tokio/sync/broadcast/)

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_single_subscriber_receives_events() {
        let bus = EventBus::new();
        let mut rx = bus.subscribe();

        bus.publish(Event::SessionCreated {
            session_id: "test-123".into(),
        });

        let event = rx.recv().await.unwrap();
        match event {
            Event::SessionCreated { session_id } => {
                assert_eq!(session_id, "test-123");
            }
            _ => panic!("Wrong event type"),
        }
    }

    #[tokio::test]
    async fn test_multiple_subscribers_receive_same_event() {
        let bus = EventBus::new();
        let mut rx1 = bus.subscribe();
        let mut rx2 = bus.subscribe();

        bus.publish(Event::AgentThinking {
            session_id: "test".into(),
        });

        // Both subscribers should receive the event
        assert!(rx1.recv().await.is_ok());
        assert!(rx2.recv().await.is_ok());
    }

    #[tokio::test]
    async fn test_late_subscriber_misses_past_events() {
        let bus = EventBus::new();

        bus.publish(Event::SessionCreated {
            session_id: "old".into(),
        });

        let mut rx = bus.subscribe(); // Subscribe after publish

        bus.publish(Event::SessionCreated {
            session_id: "new".into(),
        });

        // Should only receive "new", not "old"
        let event = rx.recv().await.unwrap();
        match event {
            Event::SessionCreated { session_id } => {
                assert_eq!(session_id, "new");
            }
            _ => panic!("Wrong event"),
        }
    }

    #[test]
    fn test_events_are_serializable() {
        let event = Event::MessageDelta {
            session_id: "s1".into(),
            message_id: "m1".into(),
            delta: "Hello".into(),
        };
        let json = serde_json::to_string(&event).unwrap();
        assert!(json.contains("message_delta"));
        assert!(json.contains("Hello"));

        // Verify we can deserialize back
        let restored: Event = serde_json::from_str(&json).unwrap();
        match restored {
            Event::MessageDelta { delta, .. } => assert_eq!(delta, "Hello"),
            _ => panic!("Wrong event type after deserialization"),
        }
    }

    #[test]
    fn test_event_session_id() {
        let event = Event::session_created("sess_1");
        assert_eq!(event.session_id(), Some("sess_1"));

        let error = Event::error(None, "something failed");
        assert_eq!(error.session_id(), None);
    }

    #[test]
    fn test_event_is_error() {
        let event = Event::session_created("sess_1");
        assert!(!event.is_error());

        let error = Event::error(Some("sess_1".into()), "failed");
        assert!(error.is_error());
    }

    #[tokio::test]
    async fn test_publish_returns_subscriber_count() {
        let bus = EventBus::new();

        // No subscribers
        let count = bus.publish(Event::session_created("s1"));
        assert_eq!(count, 0);

        // One subscriber
        let _rx1 = bus.subscribe();
        let count = bus.publish(Event::session_created("s2"));
        assert_eq!(count, 1);

        // Two subscribers
        let _rx2 = bus.subscribe();
        let count = bus.publish(Event::session_created("s3"));
        assert_eq!(count, 2);
    }

    #[test]
    fn test_subscriber_count() {
        let bus = EventBus::new();
        assert_eq!(bus.subscriber_count(), 0);

        let _rx1 = bus.subscribe();
        assert_eq!(bus.subscriber_count(), 1);

        let _rx2 = bus.subscribe();
        assert_eq!(bus.subscriber_count(), 2);

        drop(_rx1);
        // Note: subscriber_count may not immediately reflect dropped receivers
        // This is a limitation of broadcast channels
    }

    #[test]
    fn test_eventbus_clone_shares_channel() {
        let bus1 = EventBus::new();
        let bus2 = bus1.clone();

        let mut rx = bus1.subscribe();

        // Publish on bus2, receive on bus1's subscriber
        bus2.publish(Event::session_created("from_bus2"));

        // Use try_recv since we're in a sync test
        // The event should be immediately available
        let result = rx.try_recv();
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_all_event_types_serializable() {
        let events = vec![
            Event::SessionCreated {
                session_id: "s".into(),
            },
            Event::SessionDeleted {
                session_id: "s".into(),
            },
            Event::SessionTitleChanged {
                session_id: "s".into(),
                title: "t".into(),
            },
            Event::MessageCreated {
                session_id: "s".into(),
                message_id: "m".into(),
                role: "user".into(),
            },
            Event::MessageDelta {
                session_id: "s".into(),
                message_id: "m".into(),
                delta: "d".into(),
            },
            Event::MessageComplete {
                session_id: "s".into(),
                message_id: "m".into(),
            },
            Event::ToolCallStarted {
                session_id: "s".into(),
                tool_call_id: "tc".into(),
                tool_name: "bash".into(),
                arguments: None,
            },
            Event::ToolCallCompleted {
                session_id: "s".into(),
                tool_call_id: "tc".into(),
                success: true,
                file_change: None,
            },
            Event::AgentThinking {
                session_id: "s".into(),
            },
            Event::AgentIdle {
                session_id: "s".into(),
            },
            Event::Error {
                session_id: Some("s".into()),
                message: "err".into(),
            },
        ];

        for event in events {
            let json = serde_json::to_string(&event).unwrap();
            let _restored: Event = serde_json::from_str(&json).unwrap();
        }
    }

    #[test]
    fn test_event_json_format() {
        let event = Event::ToolCallStarted {
            session_id: "sess_1".into(),
            tool_call_id: "call_1".into(),
            tool_name: "read_file".into(),
            arguments: Some(serde_json::json!({"path": "/tmp/test.txt"})),
        };

        let json = serde_json::to_string(&event).unwrap();

        // Verify the tagged format
        assert!(json.contains("\"type\":\"tool_call_started\""));
        assert!(json.contains("\"session_id\":\"sess_1\""));
        assert!(json.contains("\"tool_name\":\"read_file\""));
        assert!(json.contains("\"arguments\""));
    }
}