ipckit 0.1.8

A cross-platform IPC (Inter-Process Communication) library for Rust and Python
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
//! Event Stream - Real-time Event Push System
//!
//! This module provides a publish-subscribe event system for real-time event pushing,
//! similar to Docker's `docker events` and `docker logs -f` functionality.
//!
//! # Features
//!
//! - Publish-subscribe pattern with multiple publishers and subscribers
//! - Event filtering by type and resource ID
//! - Event history with optional replay
//! - Backpressure handling for slow consumers
//! - MCP (Model Context Protocol) compatible progress events via [`McpProgressPayload`]
//!
//! # Example
//!
//! ```rust
//! use ipckit::{EventBus, Event, EventFilter};
//!
//! let bus = EventBus::new(Default::default());
//! let publisher = bus.publisher();
//!
//! // Subscribe to task events
//! let mut subscriber = bus.subscribe(
//!     EventFilter::new().event_type("task.*")
//! );
//!
//! // Publish an event
//! publisher.publish(Event::new("task.started", serde_json::json!({"task_id": "123"})));
//!
//! // Receive the event
//! if let Some(event) = subscriber.try_recv() {
//!     println!("Received: {:?}", event);
//! }
//! ```
//!
//! ## MCP progress events
//!
//! ```rust
//! use ipckit::{EventBus, EventFilter, event_types};
//!
//! let bus = EventBus::new(Default::default());
//! let publisher = bus.publisher();
//!
//! // Subscribe using the MCP-progress convenience filter
//! let subscriber = bus.subscribe(EventFilter::new().mcp_progress());
//!
//! // Publish an MCP-compatible progress notification
//! publisher.mcp_progress("render-token-abc", 42.0, Some(100.0), Some("Rendering frame 42/100"));
//!
//! if let Some(event) = subscriber.try_recv() {
//!     let payload: ipckit::McpProgressPayload =
//!         serde_json::from_value(event.data).unwrap();
//!     assert_eq!(payload.progress_token, "render-token-abc");
//! }
//! ```

use crate::error::{IpcError, Result};
use crossbeam_channel::{self, Receiver, Sender, TryRecvError};
use parking_lot::RwLock;
use serde::{Deserialize, Serialize};
use std::collections::VecDeque;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime};

/// A unique event identifier.
pub type EventId = u64;

/// An event that can be published and subscribed to.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Event {
    /// Unique event ID
    pub id: EventId,
    /// Event timestamp
    #[serde(with = "system_time_serde")]
    pub timestamp: SystemTime,
    /// Event type (e.g., "task.progress", "log.stdout", "task.completed")
    pub event_type: String,
    /// Associated resource ID (e.g., task_id)
    pub resource_id: Option<String>,
    /// Event data
    pub data: serde_json::Value,
}

mod system_time_serde {
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    pub fn serialize<S>(time: &SystemTime, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let duration = time.duration_since(UNIX_EPOCH).unwrap_or(Duration::ZERO);
        duration.as_secs_f64().serialize(serializer)
    }

    pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemTime, D::Error>
    where
        D: Deserializer<'de>,
    {
        let secs = f64::deserialize(deserializer)?;
        Ok(UNIX_EPOCH + Duration::from_secs_f64(secs))
    }
}

impl Event {
    /// Create a new event with the given type and data.
    pub fn new(event_type: &str, data: serde_json::Value) -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);

        Self {
            id: NEXT_ID.fetch_add(1, Ordering::SeqCst),
            timestamp: SystemTime::now(),
            event_type: event_type.to_string(),
            resource_id: None,
            data,
        }
    }

    /// Create an event with a resource ID.
    pub fn with_resource(event_type: &str, resource_id: &str, data: serde_json::Value) -> Self {
        let mut event = Self::new(event_type, data);
        event.resource_id = Some(resource_id.to_string());
        event
    }

    /// Create a progress event.
    pub fn progress(resource_id: &str, current: u64, total: u64, message: &str) -> Self {
        Self::with_resource(
            event_types::TASK_PROGRESS,
            resource_id,
            serde_json::json!({
                "current": current,
                "total": total,
                "percentage": (current * 100).checked_div(total).unwrap_or(0),
                "message": message
            }),
        )
    }

    /// Create an MCP-compatible progress event (`mcp.notifications.progress`).
    ///
    /// The event `data` field is an [`McpProgressPayload`] serialised as JSON,
    /// matching the `notifications/progress` schema used by Claude MCP, OpenAI
    /// Agents SDK, Cursor, Cline, and other agent frameworks.
    ///
    /// # Arguments
    ///
    /// * `progress_token` – opaque token identifying the in-progress operation.
    /// * `progress` – units of work completed.
    /// * `total` – total units, or `None` for indeterminate progress.
    /// * `message` – optional status message.
    pub fn mcp_progress(
        progress_token: &str,
        progress: f64,
        total: Option<f64>,
        message: Option<&str>,
    ) -> Self {
        let payload = McpProgressPayload::new(progress_token, progress, total, message);
        Self::with_resource(
            event_types::MCP_PROGRESS,
            progress_token,
            serde_json::to_value(&payload).unwrap_or_default(),
        )
    }

    /// Create a log event.
    pub fn log(resource_id: &str, level: &str, message: &str) -> Self {
        let event_type = match level {
            "info" => event_types::LOG_INFO,
            "warn" | "warning" => event_types::LOG_WARN,
            "error" => event_types::LOG_ERROR,
            "stdout" => event_types::LOG_STDOUT,
            "stderr" => event_types::LOG_STDERR,
            _ => event_types::LOG_INFO,
        };

        Self::with_resource(
            event_type,
            resource_id,
            serde_json::json!({
                "level": level,
                "message": message
            }),
        )
    }

    /// Create a stdout log event.
    pub fn stdout(resource_id: &str, line: &str) -> Self {
        Self::log(resource_id, "stdout", line)
    }

    /// Create a stderr log event.
    pub fn stderr(resource_id: &str, line: &str) -> Self {
        Self::log(resource_id, "stderr", line)
    }
}

/// Standard event type constants.
pub mod event_types {
    // Task lifecycle
    pub const TASK_CREATED: &str = "task.created";
    pub const TASK_STARTED: &str = "task.started";
    pub const TASK_PROGRESS: &str = "task.progress";
    pub const TASK_COMPLETED: &str = "task.completed";
    pub const TASK_FAILED: &str = "task.failed";
    pub const TASK_CANCELLED: &str = "task.cancelled";
    pub const TASK_PAUSED: &str = "task.paused";
    pub const TASK_RESUMED: &str = "task.resumed";

    // Logs
    pub const LOG_STDOUT: &str = "log.stdout";
    pub const LOG_STDERR: &str = "log.stderr";
    pub const LOG_INFO: &str = "log.info";
    pub const LOG_WARN: &str = "log.warn";
    pub const LOG_ERROR: &str = "log.error";

    // File operations
    pub const FILE_UPLOAD_PROGRESS: &str = "file.upload.progress";
    pub const FILE_DOWNLOAD_PROGRESS: &str = "file.download.progress";

    // System
    pub const SYSTEM_SHUTDOWN: &str = "system.shutdown";
    pub const SYSTEM_ERROR: &str = "system.error";

    // MCP (Model Context Protocol) – mirrors `notifications/progress`
    /// MCP-aligned progress notification event.
    ///
    /// The event body is an [`McpProgressPayload`] serialised as JSON so it can
    /// be forwarded verbatim to any MCP gateway without a translation layer.
    pub const MCP_PROGRESS: &str = "mcp.notifications.progress";
}

// ────────────────────────────────────────────────────────────────────────────
// MCP progress payload
// ────────────────────────────────────────────────────────────────────────────

/// Progress notification payload compatible with the MCP specification's
/// `notifications/progress` message shape.
///
/// Every field maps 1-to-1 to the MCP JSON payload so that ipckit progress
/// events can be forwarded verbatim to any MCP gateway (Claude, OpenAI Agents
/// SDK, Cursor, Cline, …) without a translation layer.
///
/// # Schema
///
/// ```json
/// {
///   "progressToken": "task-uuid",
///   "progress": 42.0,
///   "total": 100.0,
///   "message": "Rendering frame 42/100"
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct McpProgressPayload {
    /// Opaque token that identifies the in-progress operation.
    ///
    /// Consumers MUST treat this as an opaque string; its internal structure is
    /// defined by the producer.
    pub progress_token: String,

    /// How much of the work has been completed so far.
    ///
    /// The unit is left to the producer; it is only meaningful relative to
    /// [`total`](Self::total) when that field is present.
    pub progress: f64,

    /// Total amount of work, if known.
    ///
    /// `None` signals an indeterminate operation (spinner, not progress bar).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total: Option<f64>,

    /// Human-readable status message.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

impl McpProgressPayload {
    /// Create a new MCP progress payload.
    ///
    /// # Arguments
    ///
    /// * `progress_token` – opaque identifier for the in-progress operation.
    /// * `progress` – units of work completed so far.
    /// * `total` – total units of work, or `None` for indeterminate progress.
    /// * `message` – optional human-readable status string.
    pub fn new(
        progress_token: impl Into<String>,
        progress: f64,
        total: Option<f64>,
        message: Option<impl Into<String>>,
    ) -> Self {
        Self {
            progress_token: progress_token.into(),
            progress,
            total,
            message: message.map(Into::into),
        }
    }
}

/// Event filter for subscribing to specific events.
#[derive(Debug, Clone, Default)]
pub struct EventFilter {
    /// Event type patterns (supports wildcards like "task.*")
    pub event_types: Option<Vec<String>>,
    /// Resource ID filter
    pub resource_ids: Option<Vec<String>>,
    /// Start time filter
    pub since: Option<SystemTime>,
    /// End time filter
    pub until: Option<SystemTime>,
}

impl EventFilter {
    /// Create a new empty filter that matches all events.
    pub fn new() -> Self {
        Self::default()
    }

    /// Add an event type pattern to the filter.
    ///
    /// Supports wildcards like "task.*" to match all task events.
    pub fn event_type(mut self, pattern: &str) -> Self {
        let types = self.event_types.get_or_insert_with(Vec::new);
        types.push(pattern.to_string());
        self
    }

    /// Add a resource ID to the filter.
    pub fn resource(mut self, id: &str) -> Self {
        let ids = self.resource_ids.get_or_insert_with(Vec::new);
        ids.push(id.to_string());
        self
    }

    /// Set the start time filter.
    pub fn since(mut self, time: SystemTime) -> Self {
        self.since = Some(time);
        self
    }

    /// Set the end time filter.
    pub fn until(mut self, time: SystemTime) -> Self {
        self.until = Some(time);
        self
    }

    /// Filter to MCP progress events only.
    ///
    /// Convenience shorthand for `.event_type(event_types::MCP_PROGRESS)`.
    /// An MCP server crate can subscribe with this filter and forward events
    /// verbatim — no translation needed.
    pub fn mcp_progress(self) -> Self {
        self.event_type(event_types::MCP_PROGRESS)
    }

    /// Check if an event matches this filter.
    pub fn matches(&self, event: &Event) -> bool {
        // Check event type
        if let Some(ref patterns) = self.event_types {
            let matches_type = patterns.iter().any(|pattern| {
                if pattern.ends_with(".*") {
                    let prefix = &pattern[..pattern.len() - 2];
                    event.event_type.starts_with(prefix)
                } else if pattern.contains('*') {
                    // Simple glob matching
                    let parts: Vec<&str> = pattern.split('*').collect();
                    let mut pos = 0;
                    for (i, part) in parts.iter().enumerate() {
                        if part.is_empty() {
                            continue;
                        }
                        if let Some(found) = event.event_type[pos..].find(part) {
                            if i == 0 && found != 0 {
                                return false;
                            }
                            pos += found + part.len();
                        } else {
                            return false;
                        }
                    }
                    true
                } else {
                    event.event_type == *pattern
                }
            });

            if !matches_type {
                return false;
            }
        }

        // Check resource ID
        if let Some(ref ids) = self.resource_ids {
            if let Some(ref event_resource) = event.resource_id {
                if !ids.iter().any(|id| id == event_resource) {
                    return false;
                }
            } else {
                return false;
            }
        }

        // Check time range
        if let Some(since) = self.since {
            if event.timestamp < since {
                return false;
            }
        }

        if let Some(until) = self.until {
            if event.timestamp > until {
                return false;
            }
        }

        true
    }
}

/// Policy for handling slow consumers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SlowConsumerPolicy {
    /// Drop oldest events when buffer is full
    #[default]
    DropOldest,
    /// Drop newest events when buffer is full
    DropNewest,
    /// Block until space is available
    Block,
}

/// Configuration for the event bus.
#[derive(Debug, Clone)]
pub struct EventBusConfig {
    /// Number of events to keep in history
    pub history_size: usize,
    /// Buffer size per subscriber
    pub subscriber_buffer: usize,
    /// Policy for slow consumers
    pub slow_consumer: SlowConsumerPolicy,
}

impl Default for EventBusConfig {
    fn default() -> Self {
        Self {
            history_size: 1000,
            subscriber_buffer: 256,
            slow_consumer: SlowConsumerPolicy::DropOldest,
        }
    }
}

/// Event publisher for sending events to the bus.
#[derive(Clone)]
pub struct EventPublisher {
    inner: Arc<EventBusInner>,
}

impl EventPublisher {
    /// Publish an event to the bus.
    pub fn publish(&self, event: Event) {
        self.inner.publish(event);
    }

    /// Publish a progress event.
    pub fn progress(&self, resource_id: &str, current: u64, total: u64, message: &str) {
        self.publish(Event::progress(resource_id, current, total, message));
    }

    /// Publish an MCP-compatible progress notification.
    ///
    /// The event body follows the `notifications/progress` schema used by
    /// Claude MCP, OpenAI Agents SDK, Cursor, Cline, and other agent
    /// frameworks, so it can be forwarded verbatim without translation.
    ///
    /// # Arguments
    ///
    /// * `progress_token` – opaque token identifying the in-progress operation.
    /// * `progress` – units of work completed.
    /// * `total` – total units, or `None` for indeterminate progress.
    /// * `message` – optional human-readable status string.
    pub fn mcp_progress(
        &self,
        progress_token: &str,
        progress: f64,
        total: Option<f64>,
        message: Option<&str>,
    ) {
        self.publish(Event::mcp_progress(
            progress_token,
            progress,
            total,
            message,
        ));
    }

    /// Publish a log event.
    pub fn log(&self, resource_id: &str, level: &str, message: &str) {
        self.publish(Event::log(resource_id, level, message));
    }

    /// Publish a stdout log event.
    pub fn stdout(&self, resource_id: &str, line: &str) {
        self.publish(Event::stdout(resource_id, line));
    }

    /// Publish a stderr log event.
    pub fn stderr(&self, resource_id: &str, line: &str) {
        self.publish(Event::stderr(resource_id, line));
    }

    /// Publish a task started event.
    pub fn task_started(&self, task_id: &str, data: serde_json::Value) {
        self.publish(Event::with_resource(
            event_types::TASK_STARTED,
            task_id,
            data,
        ));
    }

    /// Publish a task completed event.
    pub fn task_completed(&self, task_id: &str, result: serde_json::Value) {
        self.publish(Event::with_resource(
            event_types::TASK_COMPLETED,
            task_id,
            serde_json::json!({ "result": result }),
        ));
    }

    /// Publish a task failed event.
    pub fn task_failed(&self, task_id: &str, error: &str) {
        self.publish(Event::with_resource(
            event_types::TASK_FAILED,
            task_id,
            serde_json::json!({ "error": error }),
        ));
    }

    /// Publish a task cancelled event.
    pub fn task_cancelled(&self, task_id: &str) {
        self.publish(Event::with_resource(
            event_types::TASK_CANCELLED,
            task_id,
            serde_json::json!({}),
        ));
    }
}

/// Event subscriber for receiving events from the bus.
pub struct EventSubscriber {
    receiver: Receiver<Event>,
    filter: EventFilter,
}

impl EventSubscriber {
    /// Receive the next event (blocking).
    pub fn recv(&self) -> Option<Event> {
        loop {
            match self.receiver.recv() {
                Ok(event) => {
                    if self.filter.matches(&event) {
                        return Some(event);
                    }
                }
                Err(_) => return None,
            }
        }
    }

    /// Try to receive an event without blocking.
    pub fn try_recv(&self) -> Option<Event> {
        loop {
            match self.receiver.try_recv() {
                Ok(event) => {
                    if self.filter.matches(&event) {
                        return Some(event);
                    }
                }
                Err(TryRecvError::Empty) => return None,
                Err(TryRecvError::Disconnected) => return None,
            }
        }
    }

    /// Receive an event with a timeout.
    pub fn recv_timeout(&self, timeout: Duration) -> Result<Event> {
        let deadline = std::time::Instant::now() + timeout;

        loop {
            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() {
                return Err(IpcError::Timeout);
            }

            match self.receiver.recv_timeout(remaining) {
                Ok(event) => {
                    if self.filter.matches(&event) {
                        return Ok(event);
                    }
                }
                Err(crossbeam_channel::RecvTimeoutError::Timeout) => {
                    return Err(IpcError::Timeout);
                }
                Err(crossbeam_channel::RecvTimeoutError::Disconnected) => {
                    return Err(IpcError::Closed);
                }
            }
        }
    }

    /// Create an iterator over events.
    pub fn iter(&self) -> impl Iterator<Item = Event> + '_ {
        std::iter::from_fn(move || self.recv())
    }

    /// Create a non-blocking iterator over available events.
    pub fn try_iter(&self) -> impl Iterator<Item = Event> + '_ {
        std::iter::from_fn(move || self.try_recv())
    }

    /// Get the filter for this subscriber.
    pub fn filter(&self) -> &EventFilter {
        &self.filter
    }
}

struct Subscriber {
    sender: Sender<Event>,
    filter: EventFilter,
}

struct EventBusInner {
    config: EventBusConfig,
    subscribers: RwLock<Vec<Subscriber>>,
    history: RwLock<VecDeque<Event>>,
}

impl EventBusInner {
    fn new(config: EventBusConfig) -> Self {
        Self {
            config,
            subscribers: RwLock::new(Vec::new()),
            history: RwLock::new(VecDeque::new()),
        }
    }

    fn publish(&self, event: Event) {
        // Add to history
        {
            let mut history = self.history.write();
            history.push_back(event.clone());

            // Trim history if needed
            while history.len() > self.config.history_size {
                history.pop_front();
            }
        }

        // Send to subscribers
        let subscribers = self.subscribers.read();
        for sub in subscribers.iter() {
            if sub.filter.matches(&event) {
                match self.config.slow_consumer {
                    SlowConsumerPolicy::Block => {
                        let _ = sub.sender.send(event.clone());
                    }
                    SlowConsumerPolicy::DropNewest => {
                        let _ = sub.sender.try_send(event.clone());
                    }
                    SlowConsumerPolicy::DropOldest => {
                        // Try to send, if full, receive one and try again
                        if sub.sender.try_send(event.clone()).is_err() {
                            // Channel is full, we just drop the event for this subscriber
                            // In a more sophisticated implementation, we could drain old events
                        }
                    }
                }
            }
        }
    }

    fn subscribe(&self, filter: EventFilter) -> EventSubscriber {
        let (tx, rx) = crossbeam_channel::bounded(self.config.subscriber_buffer);

        let subscriber = Subscriber {
            sender: tx,
            filter: filter.clone(),
        };

        self.subscribers.write().push(subscriber);

        EventSubscriber {
            receiver: rx,
            filter,
        }
    }

    fn history(&self, filter: &EventFilter) -> Vec<Event> {
        let history = self.history.read();
        history
            .iter()
            .filter(|e| filter.matches(e))
            .cloned()
            .collect()
    }

    fn clear_history(&self) {
        self.history.write().clear();
    }
}

/// The main event bus for publish-subscribe communication.
#[derive(Clone)]
pub struct EventBus {
    inner: Arc<EventBusInner>,
}

impl EventBus {
    /// Create a new event bus with the given configuration.
    pub fn new(config: EventBusConfig) -> Self {
        Self {
            inner: Arc::new(EventBusInner::new(config)),
        }
    }

    /// Create a new publisher for this bus.
    pub fn publisher(&self) -> EventPublisher {
        EventPublisher {
            inner: Arc::clone(&self.inner),
        }
    }

    /// Subscribe to events matching the given filter.
    pub fn subscribe(&self, filter: EventFilter) -> EventSubscriber {
        self.inner.subscribe(filter)
    }

    /// Get historical events matching the given filter.
    pub fn history(&self, filter: &EventFilter) -> Vec<Event> {
        self.inner.history(filter)
    }

    /// Clear all event history.
    pub fn clear_history(&self) {
        self.inner.clear_history();
    }

    /// Publish an event directly.
    pub fn publish(&self, event: Event) {
        self.inner.publish(event);
    }
}

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

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

    #[test]
    fn test_event_creation() {
        let event = Event::new("test.event", serde_json::json!({"key": "value"}));

        assert!(event.id > 0);
        assert_eq!(event.event_type, "test.event");
        assert!(event.resource_id.is_none());
    }

    #[test]
    fn test_event_with_resource() {
        let event = Event::with_resource("task.started", "task-123", serde_json::json!({}));

        assert_eq!(event.event_type, "task.started");
        assert_eq!(event.resource_id, Some("task-123".to_string()));
    }

    #[test]
    fn test_progress_event() {
        let event = Event::progress("task-123", 50, 100, "Half done");

        assert_eq!(event.event_type, event_types::TASK_PROGRESS);
        assert_eq!(event.resource_id, Some("task-123".to_string()));
        assert_eq!(event.data["percentage"], 50);
    }

    #[test]
    fn test_filter_event_type() {
        let filter = EventFilter::new().event_type("task.*");

        let event1 = Event::new("task.started", serde_json::json!({}));
        let event2 = Event::new("log.info", serde_json::json!({}));

        assert!(filter.matches(&event1));
        assert!(!filter.matches(&event2));
    }

    #[test]
    fn test_filter_resource() {
        let filter = EventFilter::new().resource("task-123");

        let event1 = Event::with_resource("task.started", "task-123", serde_json::json!({}));
        let event2 = Event::with_resource("task.started", "task-456", serde_json::json!({}));
        let event3 = Event::new("task.started", serde_json::json!({}));

        assert!(filter.matches(&event1));
        assert!(!filter.matches(&event2));
        assert!(!filter.matches(&event3));
    }

    #[test]
    fn test_filter_combined() {
        let filter = EventFilter::new().event_type("task.*").resource("task-123");

        let event1 = Event::with_resource("task.started", "task-123", serde_json::json!({}));
        let event2 = Event::with_resource("log.info", "task-123", serde_json::json!({}));
        let event3 = Event::with_resource("task.started", "task-456", serde_json::json!({}));

        assert!(filter.matches(&event1));
        assert!(!filter.matches(&event2));
        assert!(!filter.matches(&event3));
    }

    #[test]
    fn test_event_bus_publish_subscribe() {
        let bus = EventBus::new(Default::default());
        let publisher = bus.publisher();
        let subscriber = bus.subscribe(EventFilter::new());

        publisher.publish(Event::new("test.event", serde_json::json!({"value": 42})));

        let event = subscriber.try_recv().unwrap();
        assert_eq!(event.event_type, "test.event");
        assert_eq!(event.data["value"], 42);
    }

    #[test]
    fn test_event_bus_filtered_subscription() {
        let bus = EventBus::new(Default::default());
        let publisher = bus.publisher();
        let subscriber = bus.subscribe(EventFilter::new().event_type("task.*"));

        publisher.publish(Event::new("task.started", serde_json::json!({})));
        publisher.publish(Event::new("log.info", serde_json::json!({})));
        publisher.publish(Event::new("task.completed", serde_json::json!({})));

        let events: Vec<Event> = subscriber.try_iter().collect();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].event_type, "task.started");
        assert_eq!(events[1].event_type, "task.completed");
    }

    #[test]
    fn test_event_bus_history() {
        let bus = EventBus::new(EventBusConfig {
            history_size: 10,
            ..Default::default()
        });

        bus.publish(Event::new("event.1", serde_json::json!({})));
        bus.publish(Event::new("event.2", serde_json::json!({})));
        bus.publish(Event::new("event.3", serde_json::json!({})));

        let history = bus.history(&EventFilter::new());
        assert_eq!(history.len(), 3);
    }

    #[test]
    fn test_event_bus_history_limit() {
        let bus = EventBus::new(EventBusConfig {
            history_size: 2,
            ..Default::default()
        });

        bus.publish(Event::new("event.1", serde_json::json!({})));
        bus.publish(Event::new("event.2", serde_json::json!({})));
        bus.publish(Event::new("event.3", serde_json::json!({})));

        let history = bus.history(&EventFilter::new());
        assert_eq!(history.len(), 2);
        assert_eq!(history[0].event_type, "event.2");
        assert_eq!(history[1].event_type, "event.3");
    }

    #[test]
    fn test_event_bus_clear_history() {
        let bus = EventBus::new(Default::default());

        bus.publish(Event::new("event.1", serde_json::json!({})));
        bus.publish(Event::new("event.2", serde_json::json!({})));

        assert_eq!(bus.history(&EventFilter::new()).len(), 2);

        bus.clear_history();

        assert_eq!(bus.history(&EventFilter::new()).len(), 0);
    }

    #[test]
    fn test_multiple_subscribers() {
        let bus = EventBus::new(Default::default());
        let publisher = bus.publisher();

        let sub1 = bus.subscribe(EventFilter::new().event_type("task.*"));
        let sub2 = bus.subscribe(EventFilter::new().event_type("log.*"));
        let sub3 = bus.subscribe(EventFilter::new());

        publisher.publish(Event::new("task.started", serde_json::json!({})));
        publisher.publish(Event::new("log.info", serde_json::json!({})));

        assert_eq!(sub1.try_iter().count(), 1);
        assert_eq!(sub2.try_iter().count(), 1);
        assert_eq!(sub3.try_iter().count(), 2);
    }

    #[test]
    fn test_publisher_helper_methods() {
        let bus = EventBus::new(Default::default());
        let publisher = bus.publisher();
        let subscriber = bus.subscribe(EventFilter::new());

        publisher.progress("task-1", 50, 100, "Half done");
        publisher.log("task-1", "info", "Processing...");
        publisher.stdout("task-1", "Output line");
        publisher.task_completed("task-1", serde_json::json!({"success": true}));

        let events: Vec<Event> = subscriber.try_iter().collect();
        assert_eq!(events.len(), 4);
    }

    #[test]
    fn test_event_serialization() {
        let event = Event::with_resource(
            "task.started",
            "task-123",
            serde_json::json!({"key": "value"}),
        );

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

        assert_eq!(deserialized.id, event.id);
        assert_eq!(deserialized.event_type, event.event_type);
        assert_eq!(deserialized.resource_id, event.resource_id);
    }

    // ────────────────────────────────────────────────────────────────────────
    // MCP progress tests
    // ────────────────────────────────────────────────────────────────────────

    #[test]
    fn test_mcp_progress_payload_serialization() {
        let payload = McpProgressPayload::new("token-abc", 42.0, Some(100.0), Some("step 42/100"));

        let json = serde_json::to_value(&payload).unwrap();

        // camelCase field names as required by the MCP spec
        assert_eq!(json["progressToken"], "token-abc");
        assert!((json["progress"].as_f64().unwrap() - 42.0).abs() < f64::EPSILON);
        assert!((json["total"].as_f64().unwrap() - 100.0).abs() < f64::EPSILON);
        assert_eq!(json["message"], "step 42/100");
    }

    #[test]
    fn test_mcp_progress_payload_no_total() {
        let payload = McpProgressPayload::new("token-xyz", 3.0, None, None::<&str>);
        let json = serde_json::to_value(&payload).unwrap();

        // `total` and `message` must be absent when None (skip_serializing_if)
        assert!(json.get("total").is_none());
        assert!(json.get("message").is_none());
    }

    #[test]
    fn test_mcp_progress_payload_round_trip() {
        let original = McpProgressPayload::new("tok", 7.5, Some(10.0), Some("msg"));
        let json = serde_json::to_string(&original).unwrap();
        let restored: McpProgressPayload = serde_json::from_str(&json).unwrap();
        assert_eq!(original, restored);
    }

    #[test]
    fn test_event_mcp_progress_constructor() {
        let event = Event::mcp_progress("render-token", 42.0, Some(100.0), Some("frame 42"));

        assert_eq!(event.event_type, event_types::MCP_PROGRESS);
        assert_eq!(event.resource_id.as_deref(), Some("render-token"));

        let payload: McpProgressPayload = serde_json::from_value(event.data).unwrap();
        assert_eq!(payload.progress_token, "render-token");
        assert!((payload.progress - 42.0).abs() < f64::EPSILON);
        assert_eq!(payload.total, Some(100.0));
        assert_eq!(payload.message.as_deref(), Some("frame 42"));
    }

    #[test]
    fn test_publisher_mcp_progress() {
        let bus = EventBus::new(Default::default());
        let publisher = bus.publisher();
        // Use the MCP-progress convenience filter
        let sub = bus.subscribe(EventFilter::new().mcp_progress());

        publisher.mcp_progress("tok", 1.0, Some(10.0), Some("start"));
        // A plain task.progress event must NOT match the mcp-filter
        publisher.progress("task-1", 50, 100, "half");

        let events: Vec<Event> = sub.try_iter().collect();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, event_types::MCP_PROGRESS);
    }

    #[test]
    fn test_filter_mcp_progress_excludes_others() {
        let bus = EventBus::new(Default::default());
        let publisher = bus.publisher();
        let sub_all = bus.subscribe(EventFilter::new());
        let sub_mcp = bus.subscribe(EventFilter::new().mcp_progress());

        publisher.mcp_progress("t", 0.0, None, None);
        publisher.publish(Event::new("task.started", serde_json::json!({})));

        assert_eq!(sub_all.try_iter().count(), 2);
        assert_eq!(sub_mcp.try_iter().count(), 1);
    }
}