active-call 0.3.75

A SIP/WebRTC voice agent
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
use crate::{
    app::AppState, call::RoutingState, config::PlaybookRule,
    useragent::invitation::InvitationHandler,
};
use anyhow::{Result, anyhow};
use async_trait::async_trait;
use regex::Regex;
use rsipstack::rsip::prelude::HeadersExt;
use rsipstack::dialog::server_dialog::ServerInviteDialog;
use std::sync::Arc;
use tokio_util::sync::CancellationToken;
use tracing::{info, warn};

pub struct PlaybookInvitationHandler {
    rules: Vec<CompiledPlaybookRule>,
    default: Option<String>,
    app_state: AppState,
}

struct CompiledPlaybookRule {
    caller: Option<Regex>,
    callee: Option<Regex>,
    playbook: String,
}

impl PlaybookInvitationHandler {
    pub fn new(
        rules: Vec<PlaybookRule>,
        default: Option<String>,
        app_state: AppState,
    ) -> Result<Self> {
        let mut compiled_rules = Vec::new();

        for rule in rules {
            let caller_regex = if let Some(pattern) = rule.caller {
                Some(
                    Regex::new(&pattern)
                        .map_err(|e| anyhow!("invalid caller regex '{}': {}", pattern, e))?,
                )
            } else {
                None
            };

            let callee_regex = if let Some(pattern) = rule.callee {
                Some(
                    Regex::new(&pattern)
                        .map_err(|e| anyhow!("invalid callee regex '{}': {}", pattern, e))?,
                )
            } else {
                None
            };

            compiled_rules.push(CompiledPlaybookRule {
                caller: caller_regex,
                callee: callee_regex,
                playbook: rule.playbook.clone(),
            });
        }

        Ok(Self {
            rules: compiled_rules,
            default,
            app_state,
        })
    }

    pub fn match_playbook(&self, caller: &str, callee: &str) -> Option<String> {
        for rule in &self.rules {
            let caller_matches = rule
                .caller
                .as_ref()
                .map(|r| r.is_match(caller))
                .unwrap_or(true);

            let callee_matches = rule
                .callee
                .as_ref()
                .map(|r| r.is_match(callee))
                .unwrap_or(true);

            if caller_matches && callee_matches {
                return Some(rule.playbook.clone());
            }
        }

        self.default.clone()
    }

    fn extract_custom_headers(
        headers: &rsipstack::rsip::Headers,
    ) -> std::collections::HashMap<String, serde_json::Value> {
        let mut extras = std::collections::HashMap::new();
        for header in headers.iter() {
            if let rsipstack::rsip::Header::Other(name, value) = header {
                // Capture all custom headers, Playbook logic can filter them later using `sip.extract_headers` if needed
                extras.insert(
                    name.to_string(),
                    serde_json::Value::String(value.to_string()),
                );
            }
        }
        extras
    }
}

#[async_trait]
impl InvitationHandler for PlaybookInvitationHandler {
    async fn on_invite(
        &self,
        dialog_id: String,
        cancel_token: CancellationToken,
        dialog: ServerInviteDialog,
        _routing_state: Arc<RoutingState>,
    ) -> Result<()> {
        let invite_request = dialog.initial_request();
        let caller = invite_request.from_header()?.uri()?.to_string();
        let callee = invite_request.to_header()?.uri()?.to_string();

        match self.match_playbook(&caller, &callee) {
            Some(playbook) => {
                info!(
                    dialog_id,
                    caller, callee, playbook, "matched playbook for invite"
                );

                // Extract custom headers
                let mut extras = Self::extract_custom_headers(&invite_request.headers);

                // Inject built-in caller/callee variables
                extras.insert(
                    crate::playbook::BUILTIN_CALLER.to_string(),
                    serde_json::Value::String(caller.clone()),
                );
                extras.insert(
                    crate::playbook::BUILTIN_CALLEE.to_string(),
                    serde_json::Value::String(callee.clone()),
                );

                let extras_opt = if extras.is_empty() {
                    None
                } else {
                    Some(extras)
                };

                // Start call handler in background task
                let app_state = self.app_state.clone();
                let session_id = dialog_id.clone();
                let cancel_token_clone = cancel_token.clone();

                crate::spawn(async move {
                    use crate::call::{ActiveCallType, Command};
                    use bytes::Bytes;
                    use std::path::PathBuf;

                    // Pre-validate playbook file exists (for SIP calls)
                    if !playbook.trim().starts_with("---") {
                        // It's a file path, check if it exists
                        let path = if playbook.starts_with("config/playbook/") {
                            PathBuf::from(&playbook)
                        } else {
                            PathBuf::from("config/playbook").join(&playbook)
                        };

                        if !path.exists() {
                            warn!(session_id, path=?path, "Playbook file not found, rejecting SIP call");
                            if let Err(e) = dialog.reject(
                                Some(rsipstack::rsip::StatusCode::ServiceUnavailable),
                                Some("Playbook Not Found".to_string()),
                            ) {
                                warn!(session_id, "Failed to reject SIP dialog: {}", e);
                            }
                            return;
                        }
                    }

                    let (_audio_sender, audio_receiver) =
                        tokio::sync::mpsc::unbounded_channel::<Bytes>();
                    let (command_sender, command_receiver) =
                        tokio::sync::mpsc::unbounded_channel::<Command>();
                    let (event_sender, _event_receiver) =
                        tokio::sync::mpsc::unbounded_channel::<crate::event::SessionEvent>();

                    // Send Accept command immediately to trigger SDP negotiation
                    let accept_option = crate::CallOption {
                        caller: Some(caller.clone()),
                        callee: Some(callee.clone()),
                        ..Default::default()
                    };
                    if let Err(e) = command_sender.send(Command::Accept {
                        option: accept_option,
                    }) {
                        warn!(session_id, "Failed to send accept command: {}", e);
                        return;
                    }

                    // Use a oneshot channel to receive final call extras
                    // (including _hangup_headers) from call_handler_core
                    let (extras_tx, extras_rx) = tokio::sync::oneshot::channel();
                    let extras_for_call = extras_opt;
                    let playbook_for_call = playbook;
                    crate::spawn({
                        let session_id = session_id.clone();
                        let app_state = app_state.clone();
                        let cancel_token = cancel_token_clone.clone();
                        async move {
                            let result = crate::handler::handler::call_handler_core(
                                ActiveCallType::Sip,
                                session_id,
                                app_state,
                                cancel_token,
                                audio_receiver,
                                None, // server_side_track
                                true, // dump_events
                                20,   // ping_interval
                                command_receiver,
                                event_sender,
                                extras_for_call,
                                Some(playbook_for_call),
                            )
                            .await;
                            let _ = extras_tx.send(result);
                        }
                    });

                    // Wait for call to complete or cancellation
                    let final_extras = tokio::select! {
                        result = extras_rx => {
                            info!(session_id, "SIP call handler completed");
                            result.ok().flatten()
                        }
                        _ = cancel_token_clone.cancelled() => {
                            info!(session_id, "SIP call cancelled");
                            None
                        }
                    };

                    // Extract hangup headers from final call extras
                    let headers = final_extras.and_then(|extras| {
                        extras.get("_hangup_headers").and_then(|h_val| {
                            serde_json::from_value::<std::collections::HashMap<String, String>>(
                                h_val.clone(),
                            )
                            .ok()
                            .or_else(|| {
                                if let serde_json::Value::String(s) = h_val {
                                    serde_json::from_str::<
                                        std::collections::HashMap<String, String>,
                                    >(s.as_str())
                                    .ok()
                                } else {
                                    None
                                }
                            })
                        })
                    });

                    let sip_headers = headers.map(|h_map| {
                        h_map
                            .into_iter()
                            .map(|(k, v)| rsipstack::rsip::Header::Other(k.into(), v.into()))
                            .collect::<Vec<_>>()
                    });

                    // Terminate the SIP dialog
                    if let Err(e) = dialog.bye_with_headers(sip_headers).await {
                        warn!(session_id, "Failed to send BYE: {}", e);
                    }
                });

                Ok(())
            }
            None => {
                warn!(
                    dialog_id,
                    caller, callee, "no playbook matched for invite, rejecting"
                );
                Err(anyhow!(
                    "no matching playbook found for caller {} and callee {}",
                    caller,
                    callee
                ))
            }
        }
    }
}

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

    // Simpler helper that creates just the matching function for testing
    struct TestMatcher {
        rules: Vec<(Option<Regex>, Option<Regex>, String)>,
        default: Option<String>,
    }

    impl TestMatcher {
        fn new(rules: Vec<PlaybookRule>, default: Option<String>) -> Result<Self> {
            let mut compiled_rules = Vec::new();

            for rule in rules {
                let caller_regex = if let Some(pattern) = rule.caller {
                    Some(
                        Regex::new(&pattern)
                            .map_err(|e| anyhow!("invalid caller regex '{}': {}", pattern, e))?,
                    )
                } else {
                    None
                };

                let callee_regex = if let Some(pattern) = rule.callee {
                    Some(
                        Regex::new(&pattern)
                            .map_err(|e| anyhow!("invalid callee regex '{}': {}", pattern, e))?,
                    )
                } else {
                    None
                };

                compiled_rules.push((caller_regex, callee_regex, rule.playbook.clone()));
            }

            Ok(Self {
                rules: compiled_rules,
                default,
            })
        }

        fn match_playbook(&self, caller: &str, callee: &str) -> Option<String> {
            for (caller_re, callee_re, playbook) in &self.rules {
                let caller_matches = caller_re
                    .as_ref()
                    .map(|r| r.is_match(caller))
                    .unwrap_or(true);

                let callee_matches = callee_re
                    .as_ref()
                    .map(|r| r.is_match(callee))
                    .unwrap_or(true);

                if caller_matches && callee_matches {
                    return Some(playbook.clone());
                }
            }

            self.default.clone()
        }
    }

    #[test]
    fn test_playbook_rule_matching() {
        let rules = vec![
            PlaybookRule {
                caller: Some(r"^\+1\d{10}$".to_string()),
                callee: Some(r"^sip:support@.*".to_string()),
                playbook: "support.md".to_string(),
            },
            PlaybookRule {
                caller: Some(r"^\+86\d+$".to_string()),
                callee: None,
                playbook: "chinese.md".to_string(),
            },
            PlaybookRule {
                caller: None,
                callee: Some(r"^sip:sales@.*".to_string()),
                playbook: "sales.md".to_string(),
            },
        ];

        let matcher = TestMatcher::new(rules, Some("default.md".to_string())).unwrap();

        // Test US number to support
        assert_eq!(
            matcher.match_playbook("+12125551234", "sip:support@example.com"),
            Some("support.md".to_string())
        );

        // Test Chinese number (matches second rule)
        assert_eq!(
            matcher.match_playbook("+8613800138000", "sip:any@example.com"),
            Some("chinese.md".to_string())
        );

        // Test sales callee (matches third rule)
        assert_eq!(
            matcher.match_playbook("+44123456789", "sip:sales@example.com"),
            Some("sales.md".to_string())
        );

        // Test no match - should use default
        assert_eq!(
            matcher.match_playbook("+44123456789", "sip:other@example.com"),
            Some("default.md".to_string())
        );
    }

    #[test]
    fn test_playbook_rule_no_default() {
        let rules = vec![PlaybookRule {
            caller: Some(r"^\+1.*".to_string()),
            callee: None,
            playbook: "us.md".to_string(),
        }];

        let matcher = TestMatcher::new(rules, None).unwrap();

        // Matches
        assert_eq!(
            matcher.match_playbook("+12125551234", "sip:any@example.com"),
            Some("us.md".to_string())
        );

        // No match and no default
        assert_eq!(
            matcher.match_playbook("+44123456789", "sip:any@example.com"),
            None
        );
    }

    #[test]
    fn test_invalid_regex() {
        let rules = vec![PlaybookRule {
            caller: Some(r"[invalid(".to_string()),
            callee: None,
            playbook: "test.md".to_string(),
        }];

        let result = TestMatcher::new(rules, None);
        assert!(result.is_err());
        let err_msg = result.err().unwrap().to_string();
        assert!(err_msg.contains("invalid caller regex"));
    }

    #[test]
    fn test_extract_custom_headers() {
        use rsipstack::rsip::Header;

        let mut headers = rsipstack::rsip::Headers::default();
        headers.push(Header::ContentLength(10.into())); // Standard header (ignored)
        headers.push(Header::Other("X-Tenant-ID".into(), "123".into()));
        headers.push(Header::Other("Custom-Header".into(), "xyz".into()));

        let extras = PlaybookInvitationHandler::extract_custom_headers(&headers);

        assert_eq!(extras.len(), 2);
        assert_eq!(
            extras.get("X-Tenant-ID").unwrap(),
            &serde_json::Value::String("123".to_string())
        );
        assert_eq!(
            extras.get("Custom-Header").unwrap(),
            &serde_json::Value::String("xyz".to_string())
        );
    }
}