rvoip-sip 0.2.4

SIP umbrella for RVoIP: api/* (UnifiedCoordinator, StreamPeer, CallbackPeer, Endpoint), server/* (B2BUA helpers), adapter/* (rvoip-core::ConnectionAdapter impl)
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
use crate::types::CallState;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};

/// Session ID type. The public [`CallId`](crate::CallId) is an alias for this.
///
/// Round-trip a call id through a `String` (e.g. when it crosses a UI event
/// channel) with [`as_str`](Self::as_str) / [`from_string`](Self::from_string):
///
/// ```
/// use rvoip_sip::CallId;
/// let id = CallId::from_string("call-42");
/// assert_eq!(id.as_str(), "call-42");
/// let id2: CallId = id.as_str().to_string().into();
/// assert_eq!(id, id2);
/// ```
#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct SessionId(pub String);

impl SessionId {
    /// Generate a fresh, random session id.
    pub fn new() -> Self {
        Self(format!("session-{}", uuid::Uuid::new_v4()))
    }

    /// Wrap an existing id string (the inverse of [`as_str`](Self::as_str)).
    pub fn from_string(s: impl Into<String>) -> Self {
        Self(s.into())
    }

    /// Borrow the id as a string slice.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<String> for SessionId {
    fn from(s: String) -> Self {
        Self(s)
    }
}

impl From<&str> for SessionId {
    fn from(s: &str) -> Self {
        Self(s.to_string())
    }
}

impl std::fmt::Display for SessionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Direction of media flow
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum MediaFlowDirection {
    Send,
    Receive,
    Both,
    None,
}

/// Media direction for hold/resume
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum MediaDirection {
    SendRecv,
    SendOnly,
    RecvOnly,
    Inactive,
}

/// Dialog ID type - wraps UUID for compatibility with rvoip_sip_dialog
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct DialogId(pub uuid::Uuid);

impl DialogId {
    pub fn new() -> Self {
        Self(uuid::Uuid::new_v4())
    }

    /// Create from a UUID
    pub fn from_uuid(uuid: uuid::Uuid) -> Self {
        Self(uuid)
    }

    /// Get the inner UUID
    pub fn as_uuid(&self) -> &uuid::Uuid {
        &self.0
    }
}

impl std::fmt::Display for DialogId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// Conversion from rvoip_sip_dialog::DialogId to our DialogId
impl From<rvoip_sip_dialog::DialogId> for DialogId {
    fn from(dialog_id: rvoip_sip_dialog::DialogId) -> Self {
        Self(dialog_id.0)
    }
}

// Conversion from our DialogId to rvoip_sip_dialog::DialogId
impl From<DialogId> for rvoip_sip_dialog::DialogId {
    fn from(dialog_id: DialogId) -> Self {
        rvoip_sip_dialog::DialogId(dialog_id.0)
    }
}

// Allow conversion from &DialogId to rvoip_sip_dialog::DialogId
impl From<&DialogId> for rvoip_sip_dialog::DialogId {
    fn from(dialog_id: &DialogId) -> Self {
        rvoip_sip_dialog::DialogId(dialog_id.0)
    }
}

/// rvoip-sip's identifier for a media session is exactly media-core's
/// `DialogId`. Aliased so call sites can keep saying `MediaSessionId`
/// where it reads better, while the underlying type is unified across
/// the media boundary (eliminates `MediaSessionId::from_dialog(&...)`
/// reconstruction and the "fresh UUID" bug class — see
/// `crates/sip/rvoip-sip/docs/MEDIA_PLANE_LAYERING_FOLLOWUPS.md` P5).
///
/// Note: this is **not** the same type as `state_table::DialogId`
/// above — that one is a `Copy` Uuid newtype with bidirectional
/// conversions to `rvoip_sip_dialog::DialogId`, and is intentionally
/// preserved (Sprint 2.5 Decision A).
pub type MediaSessionId = rvoip_media_core::DialogId;

/// Call ID type
pub type CallId = String;

/// Key for looking up transitions in the state table
#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub struct StateKey {
    pub role: Role,
    pub state: CallState,
    pub event: EventType,
}

/// Role in the call (caller or receiver)
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum Role {
    UAC,  // User Agent Client (caller)
    UAS,  // User Agent Server (receiver)
    Both, // Applies to both roles
}

/// Event types that trigger transitions
#[derive(Debug, Clone, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum EventType {
    // User-initiated events
    MakeCall {
        target: String,
    },
    IncomingCall {
        from: String,
        sdp: Option<String>,
    },
    IncomingCallAutoAccept {
        from: String,
        sdp: Option<String>,
    },
    AcceptCall,
    RejectCall {
        status: u16,
        reason: String,
    },
    /// RFC 3261 §8.1.3.4 — UAS-side redirect. Send a 3xx response with one
    /// or more `Contact:` URIs so the UAC can retarget. Valid from Ringing
    /// and EarlyMedia on the UAS role.
    RedirectCall {
        status: u16,
        contacts: Vec<String>,
    },
    /// RFC 3262 — emit a reliable 183 Session Progress with early-media SDP.
    /// `sdp: Some(_)` uses caller-supplied SDP verbatim; `None` triggers
    /// `negotiate_sdp_as_uas` against the stored remote offer.
    SendEarlyMedia {
        sdp: Option<String>,
    },
    /// RFC 3261 §22.2 — server or proxy challenged the UAC request with
    /// 401/407. `challenge` is the raw header value (e.g.
    /// `Digest realm="...", nonce="..."`) ready for
    /// `auth-core::DigestAuthenticator::parse_challenge`. Same variant drives
    /// INVITE (`Initiating`) and REGISTER (`Registering`) retries — the
    /// current state disambiguates which request to re-send.
    AuthRequired {
        status_code: u16,
        challenge: String,
        /// SIP method of the challenged request — `"INVITE"`,
        /// `"REGISTER"`, `"BYE"`, `"SUBSCRIBE"`, … — extracted from the
        /// response `CSeq:`. Used by `Action::SendRequestWithAuth` to
        /// route the retry to the right per-method dispatcher. Empty
        /// string preserves the legacy method-agnostic shape used by
        /// the existing `Initiating + AuthRequired` (INVITE) and
        /// `Registering + AuthRequired` (REGISTER) rows; new
        /// per-method rows match on this field via YAML conditions.
        method: String,
    },
    /// RFC 4028 §6 — UAS replied 422 Session Interval Too Small. `min_se_secs`
    /// is the peer's required floor, parsed from the `Min-SE` response header.
    /// The state machine caches it onto the session and fires
    /// `SendINVITEWithBumpedSessionExpires` to retry with the bumped values;
    /// the 2-retry cap lives in the action, and on exhaustion the session
    /// falls through to the generic `Dialog4xxFailure` failure path.
    SessionIntervalTooSmall {
        min_se_secs: u32,
    },
    HangupCall,
    CancelCall,
    HoldCall,
    ResumeCall,
    MuteCall,
    UnmuteCall,

    // Media control events
    PlayAudio {
        file: String,
    },
    StartRecording,
    StopRecording,

    // Dialog events (from dialog-core)
    DialogCreated {
        dialog_id: String,
        call_id: String,
    },
    CallEstablished {
        session_id: String,
        sdp_answer: Option<String>,
    },
    DialogInvite,
    Dialog180Ringing,
    Dialog183SessionProgress,
    Dialog200OK,
    DialogACK,
    DialogBYE,
    DialogCANCEL,
    DialogREFER,
    DialogReINVITE,
    Dialog3xxRedirect {
        status: u16,
        targets: Vec<String>,
    },
    /// RFC 3261 §14.1 — 491 Request Pending on a re-INVITE. UAC should wait
    /// a random interval and retry whatever re-INVITE was in flight
    /// (session.pending_reinvite captures that).
    ReinviteGlare,
    Dialog4xxFailure(u16),
    Dialog5xxFailure(u16),
    Dialog6xxFailure(u16),
    Dialog487RequestTerminated,
    DialogTimeout,
    DialogTerminated,
    DialogError(String),
    DialogStateChanged {
        old_state: String,
        new_state: String,
    },
    ReinviteReceived {
        sdp: Option<String>,
    },
    /// UPDATE received (RFC 3311 / RFC 4028). Distinct from re-INVITE so
    /// the state table can route them to different transitions —
    /// session-timer refresh over UPDATE carries no SDP, media renegotiation
    /// over re-INVITE does.
    UpdateReceived {
        sdp: Option<String>,
    },
    TransferRequested {
        refer_to: String,
        transfer_type: String,
        transaction_id: String,
    }, // Kept for callback system

    // Media events (from media-core)
    MediaSessionCreated,
    MediaSessionReady,
    MediaNegotiated,
    MediaFlowEstablished,
    MediaError(String),
    MediaEvent(String), // Generic media events like "rfc_compliant_media_creation_uac"
    MediaQualityDegraded {
        packet_loss_percent: u32,
        jitter_ms: u32,
        severity: String,
    },
    DtmfDetected {
        digit: char,
        duration_ms: u32,
    },
    RtpTimeout {
        last_packet_time: String,
    },
    PacketLossThresholdExceeded {
        loss_percentage: u32,
    },

    // Internal coordination events
    InternalCheckReady,
    InternalACKSent,
    InternalUASMedia,
    InternalCleanupComplete,
    CheckConditions,
    PublishCallEstablished,

    // Conference events
    CreateConference {
        name: String,
    },
    AddParticipant {
        session_id: String,
    },
    JoinConference {
        conference_id: String,
    },
    LeaveConference,
    MuteInConference,
    UnmuteInConference,

    // Bridge events (kept for single session bridging)
    BridgeSessions {
        other_session: SessionId,
    },
    UnbridgeSessions,

    // Session modification
    ModifySession,

    // Registration events
    StartRegistration,
    Registration200OK,
    Registration401,
    RegistrationFailed(u16),
    RetryRegistration,
    RefreshRegistration,
    StartUnregistration,
    Unregistration200OK,
    UnregistrationFailed,
    UnregisterRequest,
    RegistrationExpired,

    // Subscription/Notify events
    StartSubscription,
    ReceiveNOTIFY,
    SendNOTIFY,
    SubscriptionAccepted,
    SubscriptionFailed(u16),
    SubscriptionExpired,
    UnsubscribeRequest,

    // Message events
    SendMessage,
    ReceiveMESSAGE,
    MessageDelivered,
    MessageFailed(u16),

    // Cleanup events
    CleanupComplete,
    Reset,

    // Internal transfer coordination events
    InternalProceedWithTransfer,
    InternalMakeTransferCall,
    InternalTransferCallEstablished,

    // ──────────────────────────────────────────────────────────────────
    // SIP_API_DESIGN_2 §7.1 — Builder-driven outbound dispatch.
    //
    // Each rvoip-sip outbound builder stages its options struct into
    // the matching `pending_<method>_options` slot via
    // `StateMachine::stage_outbound_options` (which performs the §7.3
    // invariant #5 conflict guard) and then queues one of these
    // events. The YAML state-table routes `SendOutbound<METHOD>` to
    // `Action::Send<METHOD>WithOptions`, which reads the stash. The
    // payload-free shape keeps the data lifecycle observable in the
    // stash rather than threading it through event payloads.
    // ──────────────────────────────────────────────────────────────────
    SendOutboundInvite,
    SendOutboundReInvite,
    SendOutboundBye,
    SendOutboundCancel,
    SendOutboundRefer,
    SendOutboundNotify,
    SendOutboundInfo,
    SendOutboundUpdate,
    SendOutboundMessage,
    SendOutboundOptions,
    SendOutboundSubscribe,
    SendOutboundRegister,
}

impl EventType {
    /// Normalize the event for state table lookups by removing runtime-specific field values.
    /// This allows the state table to match on event type rather than exact field values.
    pub fn normalize(&self) -> Self {
        match self {
            // User events - normalize to empty/default values
            EventType::MakeCall { .. } => EventType::MakeCall {
                target: String::new(),
            },
            EventType::IncomingCall { .. } => EventType::IncomingCall {
                from: String::new(),
                sdp: None,
            },
            EventType::IncomingCallAutoAccept { .. } => EventType::IncomingCallAutoAccept {
                from: String::new(),
                sdp: None,
            },
            EventType::RejectCall { .. } => EventType::RejectCall {
                status: 0,
                reason: String::new(),
            },
            EventType::RedirectCall { .. } => EventType::RedirectCall {
                status: 0,
                contacts: Vec::new(),
            },
            EventType::SendEarlyMedia { .. } => EventType::SendEarlyMedia { sdp: None },
            EventType::AuthRequired { .. } => EventType::AuthRequired {
                status_code: 0,
                challenge: String::new(),
                method: String::new(),
            },
            EventType::SessionIntervalTooSmall { .. } => {
                EventType::SessionIntervalTooSmall { min_se_secs: 0 }
            }
            // BlindTransfer and AttendedTransfer events removed

            // Media events - normalize
            EventType::PlayAudio { .. } => EventType::PlayAudio {
                file: String::new(),
            },

            // Conference events - normalize
            EventType::CreateConference { .. } => EventType::CreateConference {
                name: String::new(),
            },
            EventType::AddParticipant { .. } => EventType::AddParticipant {
                session_id: String::new(),
            },
            EventType::JoinConference { .. } => EventType::JoinConference {
                conference_id: String::new(),
            },

            // Bridge events - normalize session ID
            EventType::BridgeSessions { .. } => EventType::BridgeSessions {
                other_session: SessionId::new(),
            },

            // Transfer events - normalize
            EventType::TransferRequested { .. } => EventType::TransferRequested {
                refer_to: String::new(),
                transfer_type: String::new(),
                transaction_id: String::new(),
            },

            // Dialog failure events — normalize payloads so the state table
            // can match on the variant alone, not the carried details.
            EventType::Dialog3xxRedirect { .. } => EventType::Dialog3xxRedirect {
                status: 0,
                targets: Vec::new(),
            },
            EventType::Dialog4xxFailure(_) => EventType::Dialog4xxFailure(400),
            EventType::Dialog5xxFailure(_) => EventType::Dialog5xxFailure(500),
            EventType::Dialog6xxFailure(_) => EventType::Dialog6xxFailure(600),

            // Mid-dialog re-INVITE / UPDATE — strip the SDP body so the
            // state table can match on variant regardless of SDP contents.
            EventType::ReinviteReceived { .. } => EventType::ReinviteReceived { sdp: None },
            EventType::UpdateReceived { .. } => EventType::UpdateReceived { sdp: None },

            // Registration events - normalize status codes
            EventType::RegistrationFailed(_) => EventType::RegistrationFailed(0),
            EventType::UnregistrationFailed => EventType::UnregistrationFailed,
            EventType::Registration401 => EventType::Registration401,
            EventType::RetryRegistration => EventType::RetryRegistration,
            EventType::RefreshRegistration => EventType::RefreshRegistration,
            EventType::StartUnregistration => EventType::StartUnregistration,
            EventType::Unregistration200OK => EventType::Unregistration200OK,

            // Subscription events - normalize status codes
            EventType::SubscriptionFailed(_) => EventType::SubscriptionFailed(0),

            // Message events - normalize status codes
            EventType::MessageFailed(_) => EventType::MessageFailed(0),

            // Events without fields pass through unchanged
            _ => self.clone(),
        }
    }
}

/// Transition definition - what happens when an event occurs in a state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Transition {
    /// Conditions that must be true for this transition
    pub guards: Vec<Guard>,

    /// Actions to execute
    pub actions: Vec<Action>,

    /// Next state (if changing)
    pub next_state: Option<CallState>,

    /// Condition flags to update
    pub condition_updates: ConditionUpdates,

    /// Events to publish after transition
    pub publish_events: Vec<EventTemplate>,
}

/// Guards that must be satisfied for a transition
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum Guard {
    HasLocalSDP,
    HasRemoteSDP,
    HasNegotiatedConfig,
    AllConditionsMet,
    DialogEstablished,
    MediaReady,
    SDPNegotiated,
    IsIdle,
    InActiveCall,
    IsRegistered,
    IsSubscribed,
    HasActiveSubscription,
    /// True when the session has an outgoing re-INVITE in flight.
    /// Used by the RFC 3261 §14.1 glare path to send 491 Request Pending
    /// in response to a UAS-side re-INVITE while our own is pending.
    HasPendingReinvite,
    Custom(String),
}

/// Actions to execute during a transition.
///
/// `strum::VariantNames` reflects the variant names so the YAML loader's
/// validation pass (see `yaml_loader.rs::parse_action_by_name` +
/// `tests::action_variants_have_parse_mapping`) can prove every variant is
/// reachable from at least one YAML action name. This catches drift when a
/// new variant is added without a matching `parse_action_by_name` case.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, strum::VariantNames)]
pub enum Action {
    // Dialog actions
    CreateDialog,
    CreateMediaSession,
    GenerateLocalSDP,
    SendSIPResponse(u16, String),
    /// Send a SIP response using the status/reason captured from the current
    /// RejectCall event. Use this in `RejectCall` transitions so the handler's
    /// chosen status code (e.g. 403 Forbidden, 404 Not Found) is preserved
    /// instead of being replaced by a hardcoded value.
    SendRejectResponse,
    /// RFC 3261 §8.1.3.4 — send a 3xx redirect response with one or more
    /// `Contact:` URIs. Status + contacts come from
    /// `session.redirect_response_{status,contacts}`, set by the executor on
    /// `EventType::RedirectCall`.
    SendRedirectResponse,
    SendINVITE,
    SendACK,
    SendBYE,
    SendReINVITE,
    /// Follow a 3xx redirect (RFC 3261 §8.1.3.4): pop the next URI from
    /// `session.redirect_targets` and re-send INVITE to it. Gives up after
    /// 5 redirects per RFC-recommended loop breaker.
    RetryWithContact,
    /// RFC 3261 §14.1 — after receiving 491 Request Pending on a re-INVITE,
    /// sleep a random interval (owner: 2.1-4.0 s, non-owner: 0-2.0 s) and
    /// re-issue whatever re-INVITE kind was pending. Caps at 3 retries.
    ScheduleReinviteRetry,
    /// RFC 3261 §14.1 glare resolution: when the peer's re-INVITE arrives
    /// while our own is pending and we accept theirs, cancel our scheduled
    /// retry by clearing `pending_reinvite` + `reinvite_retry_attempts`.
    /// Any sleeping retry noops at wake-up because `ScheduleReinviteRetry`
    /// reads `pending_reinvite` and returns early when it's `None`.
    ClearPendingReinvite,

    // Call control actions
    HoldCall,
    ResumeCall,
    TransferCall(String),
    StartRecording,
    StopRecording,

    // Media actions
    StartMediaSession,
    /// Switch the RTP audio transmitter back to `PassThrough` on the
    /// `EarlyMedia → Active` transition so bidirectional audio replaces any
    /// early-media ringback / announcement source the app installed during
    /// `EarlyMedia`. Idempotent: for calls that never set an early-media
    /// source the transmitter is already in `PassThrough` (set by
    /// `establish_media_flow`), so the action is a no-op swap. Swallows
    /// "transmitter not active" errors because pre-negotiated-SDP flows
    /// (e.g. `accept_call_with_sdp`) don't start a transmitter until later.
    SwitchToPassThroughOnActive,
    NegotiateSDPAsUAC,
    NegotiateSDPAsUAS,
    /// RFC 3262 — prepare SDP for a reliable 183. Uses caller-supplied SDP
    /// from `session.early_media_sdp` if present, otherwise negotiates
    /// against the stored remote offer. Writes the result into
    /// `session.local_sdp` so the following `SendSIPResponse(183, …)` picks
    /// it up. A separate action (rather than overloading `NegotiateSDPAsUAS`)
    /// because the explicit-SDP path must bypass negotiation entirely.
    PrepareEarlyMediaSDP,
    /// RFC 3261 §22.2 — compute an Authorization (or Proxy-Authorization)
    /// header from the cached challenge plus configured UAC auth and resend
    /// the INVITE via `DialogAdapter::resend_invite_with_auth`. Bumps
    /// `session.invite_auth_retry_count`; errors if the cap is exceeded.
    SendINVITEWithAuth,
    /// SIP_API_DESIGN_2 R2 — auth-retry for non-INVITE/non-REGISTER
    /// methods. Reads `session.pending_auth_method` to discriminate
    /// which `pending_<method>_options` to re-issue (falls back to
    /// inspecting which stash is set when method is missing), computes
    /// the selected auth header, and dispatches via the matching
    /// `DialogAdapter::send_<method>_with_auth` mirror. Covers BYE,
    /// REFER, NOTIFY, INFO, UPDATE, MESSAGE, OPTIONS, SUBSCRIBE.
    SendRequestWithAuth,
    /// RFC 4028 §6 — resend the INVITE with a bumped `Session-Expires` /
    /// `Min-SE` header derived from `session.session_timer_min_se` after a
    /// 422 Session Interval Too Small. Bumps `session.session_timer_retry_count`;
    /// errors if the 2-retry cap is exceeded so the upstream failure path
    /// surfaces a clean `CallFailed(422)`.
    SendINVITEWithBumpedSessionExpires,
    PlayAudioFile(String),
    StartRecordingMedia,
    StopRecordingMedia,

    // Conference actions
    CreateAudioMixer,
    RedirectToMixer,
    ConnectToMixer,
    DisconnectFromMixer,
    MuteToMixer,
    UnmuteToMixer,
    DestroyMixer,
    BridgeToMixer,
    RestoreDirectMedia,
    StartRecordingMixer,
    StopRecordingMixer,

    // Media direction actions
    UpdateMediaDirection {
        direction: MediaDirection,
    },

    // Hold/Resume actions (kept for single session)
    HoldCurrentCall,

    // State updates
    SetCondition(Condition, bool),
    StoreLocalSDP,
    StoreRemoteSDP,
    StoreNegotiatedConfig,

    // Bridge/Transfer actions
    CreateBridge(SessionId),
    DestroyBridge,

    // Resource management
    RestoreMediaFlow,
    ReleaseAllResources,
    StartEmergencyCleanup,
    AttemptMediaRecovery,
    CleanupResources,

    // Callbacks
    TriggerCallEstablished,
    TriggerCallTerminated,

    // Cleanup
    StartDialogCleanup,
    StartMediaCleanup,

    // Registration actions
    SendREGISTER,
    SendREGISTERWithAuth,
    SendUnREGISTER,
    StoreAuthChallenge,
    ProcessRegistrationResponse,

    // Subscription actions
    SendSUBSCRIBE,
    ProcessNOTIFY,

    // Message actions
    SendMESSAGE,
    ProcessMESSAGE,

    // ──────────────────────────────────────────────────────────────────
    // SIP_API_DESIGN_2 §7.1 — Unified outbound dispatch.
    //
    // Twelve trigger actions that route every outbound SIP method
    // through `Action::Send*WithOptions`. Per §7.3 invariant #1, the
    // builder's `.send()` writes the matching `Arc<XxxRequestOptions>`
    // to `session.pending_<method>_options` *before* queuing the
    // event; the action handler reads from that stash, dispatches via
    // `DialogAdapter::send_*_with_options`, and clears the slot when
    // the transaction reaches a final response.
    //
    // The unit-variant shape keeps `Action` `PartialEq + Serialize`
    // (state-table YAML compatibility); the payload travels in the
    // stash where lifecycle is observable.
    // ──────────────────────────────────────────────────────────────────
    SendINVITEWithOptions,
    SendReINVITEWithOptions,
    SendREGISTERWithOptions,
    SendSUBSCRIBEWithOptions,
    SendMESSAGEWithOptions,
    SendNOTIFYWithOptions,
    SendBYEWithOptions,
    SendCANCELWithOptions,
    SendREFERWithOptions,
    SendINFOWithOptions,
    SendUPDATEWithOptions,
    SendOPTIONSWithOptions,

    // ──────────────────────────────────────────────────────────────────
    // SIP_API_DESIGN_2 §7.3 invariant #2 — stash clear actions.
    //
    // The matching `Send*WithOptions` handler now reads the stash via
    // `.clone()` rather than `.take()`, so the `Arc<XxxRequestOptions>`
    // persists across auth-retry / refresh dispatches. The state-table
    // emits `ClearPending<METHOD>Options` on the transition that
    // reaches a final response (`Dialog200OK`, `Dialog{4,5,6}xxFailure`,
    // `DialogTimeout`) for that method. The `Terminated` backstop in
    // the executor wipes every slot unconditionally so a YAML gap can
    // never leave a stash permanently occupied.
    // ──────────────────────────────────────────────────────────────────
    ClearPendingINVITEOptions,
    ClearPendingReINVITEOptions,
    ClearPendingREGISTEROptions,
    ClearPendingSUBSCRIBEOptions,
    ClearPendingMESSAGEOptions,
    ClearPendingNOTIFYOptions,
    ClearPendingBYEOptions,
    ClearPendingCANCELOptions,
    ClearPendingREFEROptions,
    ClearPendingINFOOptions,
    ClearPendingUPDATEOptions,
    ClearPendingOPTIONSOptions,

    // Generic cleanup actions
    CleanupDialog,
    CleanupMedia,

    // REFER response action (keep for proper REFER handling)
    SendReferAccepted,

    // RFC 3515 §2.4.5 transfer-progress NOTIFYs.
    //
    // `SendRefer100Trying` fires on the REFER-receiver's own dialog when
    // the REFER is accepted (alongside `SendReferAccepted`). The other
    // three fire from the transfer-leg's UAC transitions and are no-ops
    // when `session.transferor_session_id == None`, so appending them to
    // shared `Dialog180Ringing` / `Dialog200OK` / `Dialog{4,5,6}xxFailure`
    // rows is safe for non-transfer calls.
    SendRefer100Trying,
    SendTransferNotifyRinging,
    SendTransferNotifySuccess,
    SendTransferNotifyFailure,

    // Custom action for extension
    Custom(String),
}

/// Conditions that track readiness
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq, Serialize, Deserialize)]
pub enum Condition {
    DialogEstablished,
    MediaSessionReady,
    SDPNegotiated,
}

/// Updates to condition flags
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ConditionUpdates {
    pub dialog_established: Option<bool>,
    pub media_session_ready: Option<bool>,
    pub sdp_negotiated: Option<bool>,
}

impl ConditionUpdates {
    pub fn none() -> Self {
        Self::default()
    }

    pub fn set_dialog_established(established: bool) -> Self {
        Self {
            dialog_established: Some(established),
            ..Default::default()
        }
    }

    pub fn set_media_ready(ready: bool) -> Self {
        Self {
            media_session_ready: Some(ready),
            ..Default::default()
        }
    }

    pub fn set_sdp_negotiated(negotiated: bool) -> Self {
        Self {
            sdp_negotiated: Some(negotiated),
            ..Default::default()
        }
    }
}

/// Event templates for publishing
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum EventTemplate {
    StateChanged,
    SessionCreated,
    IncomingCall,
    CallEstablished,
    CallTerminated,
    CallFailed,
    CallCancelled,
    CallOnHold,
    CallResumed,
    MediaFlowEstablished,
    MediaNegotiated,
    MediaSessionReady,
    Custom(String),
}

/// States that must always have exit transitions if used
const CORE_STATES_REQUIRING_EXITS: &[CallState] = &[
    CallState::Idle,
    CallState::Initiating,
    CallState::CancelPending,
    CallState::Cancelling,
    CallState::Ringing,
    CallState::Answering,
    CallState::AnsweringHangupPending,
    CallState::Active,
];

/// Master state table containing all transitions
pub struct MasterStateTable {
    transitions: HashMap<StateKey, Transition>,
    /// Wildcard transitions that apply to any state
    wildcard_transitions: HashMap<(Role, EventType), Transition>,
}

/// Type alias for external use
pub type StateTable = MasterStateTable;

impl MasterStateTable {
    pub fn new() -> Self {
        Self {
            transitions: HashMap::new(),
            wildcard_transitions: HashMap::new(),
        }
    }

    pub fn insert(&mut self, key: StateKey, transition: Transition) {
        // Always normalize the event when inserting
        let normalized_key = StateKey {
            role: key.role,
            state: key.state,
            event: key.event.normalize(),
        };
        self.transitions.insert(normalized_key, transition);
    }

    /// Insert a wildcard transition that applies to any state
    pub fn insert_wildcard(&mut self, role: Role, event: EventType, transition: Transition) {
        let normalized_event = event.normalize();
        self.wildcard_transitions
            .insert((role, normalized_event), transition);
    }

    pub fn get(&self, key: &StateKey) -> Option<&Transition> {
        // Normalize the event for lookup
        let normalized_key = StateKey {
            role: key.role,
            state: key.state,
            event: key.event.normalize(),
        };

        // First check for exact role match
        if let Some(transition) = self.transitions.get(&normalized_key) {
            return Some(transition);
        }

        // If UAC or UAS, also check for Role::Both transitions
        if key.role == Role::UAC || key.role == Role::UAS {
            let both_key = StateKey {
                role: Role::Both,
                state: key.state,
                event: key.event.normalize(),
            };
            if let Some(transition) = self.transitions.get(&both_key) {
                return Some(transition);
            }
        }

        // If no exact match, check for wildcard transition
        let normalized_event = key.event.normalize();
        self.wildcard_transitions.get(&(key.role, normalized_event))
    }

    pub fn get_transition(&self, key: &StateKey) -> Option<&Transition> {
        self.get(key)
    }

    pub fn has_transition(&self, key: &StateKey) -> bool {
        // Normalize the event for lookup
        let normalized_key = StateKey {
            role: key.role,
            state: key.state,
            event: key.event.normalize(),
        };

        // Check exact role match first
        if self.transitions.contains_key(&normalized_key) {
            return true;
        }

        // If UAC or UAS, also check for Role::Both transitions
        if key.role == Role::UAC || key.role == Role::UAS {
            let both_key = StateKey {
                role: Role::Both,
                state: key.state,
                event: key.event.normalize(),
            };
            if self.transitions.contains_key(&both_key) {
                return true;
            }
        }

        // Check wildcard match
        let normalized_event = key.event.normalize();
        self.wildcard_transitions
            .contains_key(&(key.role, normalized_event))
    }

    pub fn transition_count(&self) -> usize {
        self.transitions.len() + self.wildcard_transitions.len()
    }

    /// Collect all states referenced in this state table
    pub fn collect_used_states(&self) -> HashSet<CallState> {
        let mut states = HashSet::new();

        // Collect from regular transitions
        for (key, transition) in &self.transitions {
            states.insert(key.state);
            if let Some(next_state) = &transition.next_state {
                states.insert(*next_state);
            }
        }

        // Collect from wildcard transitions
        for (_, transition) in &self.wildcard_transitions {
            if let Some(next_state) = &transition.next_state {
                states.insert(*next_state);
            }
        }

        states
    }

    pub fn validate(&self) -> Result<(), Vec<String>> {
        let mut errors = Vec::new();

        // Collect states actually used in this table
        let used_states = self.collect_used_states();

        // Check for orphan states only among used states
        for state in used_states.iter() {
            // Skip terminal states
            if matches!(
                state,
                CallState::Terminated | CallState::Cancelled | CallState::Failed(_)
            ) {
                continue;
            }

            // Check if state has exit transitions
            let has_exact_exit = self.transitions.iter().any(|(k, _)| k.state == *state);
            let has_wildcard_exit = !self.wildcard_transitions.is_empty();

            if !has_exact_exit && !has_wildcard_exit {
                // Only error for core states, warn for others
                if CORE_STATES_REQUIRING_EXITS.contains(state) {
                    errors.push(format!("Core state {:?} has no exit transitions", state));
                }
                // Note: We could collect warnings here for non-core states if desired
                // For now, we just skip them to avoid false positives
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}