rsclaw 2026.5.1

AI Agent Engine Compatible with OpenClaw
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
//! Custom user-defined channels (webhook and websocket).
//!
//! Allows users to connect any platform without writing code, using JSON path
//! extraction for inbound parsing and template-based outbound replies.

use std::{sync::Arc, time::Duration};

use anyhow::{Context, Result, bail};
use futures::{SinkExt as _, StreamExt as _, future::BoxFuture};
use reqwest::Client;
use serde_json::Value;
use tokio::sync::{Mutex, mpsc};
use tokio_tungstenite::{connect_async, tungstenite::Message as WsMessage};
use tracing::{debug, info, warn};

use super::{Channel, OutboundMessage};
use crate::config::schema::CustomChannelConfig;

// ---------------------------------------------------------------------------
// Simple JSON path extractor
// ---------------------------------------------------------------------------

/// Extract a value from a JSON tree using a simple path notation.
///
/// Supported syntax:
/// - `$.foo.bar`     -> value["foo"]["bar"]
/// - `$.foo[0].bar`  -> value["foo"][0]["bar"]
/// - `foo.bar`       -> value["foo"]["bar"] (leading "$." is optional)
pub fn json_path_extract<'a>(root: &'a Value, path: &str) -> Option<&'a Value> {
    let path = path.strip_prefix("$.").unwrap_or(path);
    if path.is_empty() {
        return Some(root);
    }

    let mut current = root;
    for segment in path.split('.') {
        if segment.is_empty() {
            continue;
        }
        // Check for array indexing: "foo[0]"
        if let Some(bracket_pos) = segment.find('[') {
            let key = &segment[..bracket_pos];
            if !key.is_empty() {
                current = current.get(key)?;
            }
            // Parse index(es) like [0] or [0][1]
            let rest = &segment[bracket_pos..];
            for part in rest.split('[') {
                let part = part.trim_end_matches(']');
                if part.is_empty() {
                    continue;
                }
                let idx: usize = part.parse().ok()?;
                current = current.get(idx)?;
            }
        } else {
            current = current.get(segment)?;
        }
    }
    Some(current)
}

/// Convert a JSON value to a plain string (unquoted for strings, raw for others).
fn value_as_string(val: &Value) -> String {
    match val {
        Value::String(s) => s.clone(),
        Value::Null => String::new(),
        other => other.to_string(),
    }
}

// ---------------------------------------------------------------------------
// Template engine
// ---------------------------------------------------------------------------

/// Replace `{{sender}}`, `{{chat_id}}`, `{{reply}}`, `{{is_group}}` in a template.
fn render_template(
    template: &str,
    sender: &str,
    chat_id: &str,
    reply: &str,
    is_group: bool,
) -> String {
    template
        .replace("{{sender}}", sender)
        .replace("{{chat_id}}", chat_id)
        .replace("{{reply}}", &escape_json_string(reply))
        .replace("{{is_group}}", if is_group { "true" } else { "false" })
}

/// Expand `${VAR}` references to environment variables.
fn expand_env_vars(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(ch) = chars.next() {
        if ch == '$' && chars.peek() == Some(&'{') {
            chars.next(); // consume '{'
            let mut var_name = String::new();
            for c in chars.by_ref() {
                if c == '}' {
                    break;
                }
                var_name.push(c);
            }
            if let Ok(val) = std::env::var(&var_name) {
                result.push_str(&val);
            }
        } else {
            result.push(ch);
        }
    }
    result
}

/// Escape a string for embedding in a JSON string value.
fn escape_json_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c => out.push(c),
        }
    }
    out
}

// ---------------------------------------------------------------------------
// Inbound message parsing (shared by webhook and websocket)
// ---------------------------------------------------------------------------

/// Parsed inbound message from a custom channel.
#[derive(Debug, Clone)]
pub struct ParsedMessage {
    pub text: String,
    pub sender: String,
    pub group_id: Option<String>,
}

/// Parse an inbound JSON payload using the custom channel config paths.
pub fn parse_inbound(cfg: &CustomChannelConfig, body: &str) -> Option<ParsedMessage> {
    let val: Value = serde_json::from_str(body).ok()?;

    // Apply filter: if filter_path is set, check value matches filter_value.
    if let Some(ref fp) = cfg.filter_path {
        let extracted = json_path_extract(&val, fp)?;
        if let Some(ref fv) = cfg.filter_value {
            if value_as_string(extracted) != *fv {
                return None;
            }
        }
    }

    // Extract text.
    let text = if let Some(ref tp) = cfg.text_path {
        let v = json_path_extract(&val, tp)?;
        value_as_string(v)
    } else {
        // Fallback: use entire body as text.
        body.to_owned()
    };

    if text.is_empty() {
        return None;
    }

    // Extract sender.
    let sender = if let Some(ref sp) = cfg.sender_path {
        json_path_extract(&val, sp)
            .map(value_as_string)
            .unwrap_or_else(|| "unknown".to_owned())
    } else {
        "unknown".to_owned()
    };

    // Extract group ID (optional).
    let group_id = cfg
        .group_path
        .as_ref()
        .and_then(|gp| json_path_extract(&val, gp).map(value_as_string));

    Some(ParsedMessage {
        text,
        sender,
        group_id,
    })
}

// ---------------------------------------------------------------------------
// CustomWebhookChannel
// ---------------------------------------------------------------------------

/// A custom webhook channel: receives messages via POST /hooks/{name},
/// sends replies via HTTP to reply_url.
pub struct CustomWebhookChannel {
    pub cfg: CustomChannelConfig,
    client: Client,
    #[allow(clippy::type_complexity)]
    on_message: Arc<dyn Fn(String, String, bool) + Send + Sync>,
}

impl CustomWebhookChannel {
    pub fn new(
        cfg: CustomChannelConfig,
        on_message: Arc<dyn Fn(String, String, bool) + Send + Sync>,
    ) -> Self {
        Self {
            cfg,
            client: crate::config::build_proxy_client()
                .timeout(Duration::from_secs(30))
                .build()
                .expect("reqwest client"),
            on_message,
        }
    }

    /// Handle an inbound webhook POST.
    pub fn handle_webhook(&self, body: &str) {
        if let Some(parsed) = parse_inbound(&self.cfg, body) {
            let is_group = parsed.group_id.is_some();
            (self.on_message)(parsed.sender, parsed.text, is_group);
        } else {
            debug!(channel = %self.cfg.name, "custom webhook: inbound message did not match filter/paths");
        }
    }

    /// Send an outbound reply via HTTP.
    async fn send_reply(&self, msg: &OutboundMessage) -> Result<()> {
        let reply_url = match &self.cfg.reply_url {
            Some(u) => expand_env_vars(u),
            None => {
                debug!(channel = %self.cfg.name, "no reply_url configured, skipping outbound");
                return Ok(());
            }
        };

        let template = self.cfg.reply_template.as_deref().unwrap_or(
            r#"{"sender":"{{sender}}","chat_id":"{{chat_id}}","text":"{{reply}}","is_group":{{is_group}}}"#,
        );

        let body = render_template(
            template,
            &msg.target_id,
            &msg.target_id,
            &msg.text,
            msg.is_group,
        );

        let method = self
            .cfg
            .reply_method
            .as_deref()
            .unwrap_or("POST")
            .to_uppercase();

        let mut req = match method.as_str() {
            "PUT" => self.client.put(&reply_url),
            "PATCH" => self.client.patch(&reply_url),
            _ => self.client.post(&reply_url),
        };

        req = req.header("Content-Type", "application/json").body(body);

        if let Some(ref headers) = self.cfg.reply_headers {
            for (k, v) in headers {
                req = req.header(k.as_str(), expand_env_vars(v));
            }
        }

        let resp = req.send().await.context("custom webhook reply HTTP send")?;
        if !resp.status().is_success() {
            warn!(
                channel = %self.cfg.name,
                status = %resp.status(),
                "custom webhook reply returned non-2xx"
            );
        }
        Ok(())
    }
}

impl Channel for CustomWebhookChannel {
    fn name(&self) -> &str {
        &self.cfg.name
    }

    fn send(&self, msg: OutboundMessage) -> BoxFuture<'_, Result<()>> {
        Box::pin(async move { self.send_reply(&msg).await })
    }

    fn run(self: Arc<Self>) -> BoxFuture<'static, Result<()>> {
        // Webhook channels are passive -- they wait for POST requests.
        // Nothing to poll. Just keep alive.
        Box::pin(async move {
            info!(channel = %self.cfg.name, "custom webhook channel ready");
            // Block forever (channel stays alive as long as the gateway runs).
            futures::future::pending::<()>().await;
            Ok(())
        })
    }
}

// ---------------------------------------------------------------------------
// CustomWebSocketChannel
// ---------------------------------------------------------------------------

/// A custom WebSocket channel: connects to an external WS server, handles auth,
/// heartbeat, inbound parsing, and outbound reply frames.
pub struct CustomWebSocketChannel {
    pub cfg: CustomChannelConfig,
    #[allow(clippy::type_complexity)]
    on_message: Arc<dyn Fn(String, String, bool) + Send + Sync>,
    /// Sender half for outbound messages.
    ws_tx: Mutex<Option<mpsc::Sender<String>>>,
}

impl CustomWebSocketChannel {
    pub fn new(
        cfg: CustomChannelConfig,
        on_message: Arc<dyn Fn(String, String, bool) + Send + Sync>,
    ) -> Self {
        Self {
            cfg,
            on_message,
            ws_tx: Mutex::new(None),
        }
    }

    /// Build the WS connect request with optional custom headers.
    async fn connect_ws(
        &self,
    ) -> Result<(
        futures::stream::SplitSink<
            tokio_tungstenite::WebSocketStream<
                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
            >,
            WsMessage,
        >,
        futures::stream::SplitStream<
            tokio_tungstenite::WebSocketStream<
                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
            >,
        >,
    )> {
        let url = self.cfg.ws_url.as_deref().ok_or_else(|| {
            anyhow::anyhow!("custom WS channel '{}': ws_url is required", self.cfg.name)
        })?;
        let url = expand_env_vars(url);

        if let Some(ref headers_map) = self.cfg.ws_headers {
            use tokio_tungstenite::tungstenite::http::Request;
            let mut req = Request::builder().uri(&url);
            for (k, v) in headers_map {
                req = req.header(k.as_str(), expand_env_vars(v).as_str());
            }
            let req = req.body(()).context("custom WS: failed to build request")?;
            let (stream, _resp) = connect_async(req)
                .await
                .with_context(|| format!("custom WS connect to {url}"))?;
            Ok(stream.split())
        } else {
            let (stream, _resp) = connect_async(&url)
                .await
                .with_context(|| format!("custom WS connect to {url}"))?;
            Ok(stream.split())
        }
    }

    /// Send auth frame and validate response.
    async fn authenticate(
        &self,
        write: &mut futures::stream::SplitSink<
            tokio_tungstenite::WebSocketStream<
                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
            >,
            WsMessage,
        >,
        read: &mut futures::stream::SplitStream<
            tokio_tungstenite::WebSocketStream<
                tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>,
            >,
        >,
    ) -> Result<()> {
        let auth_frame = match &self.cfg.auth_frame {
            Some(f) => expand_env_vars(f),
            None => return Ok(()), // No auth required.
        };

        info!(channel = %self.cfg.name, "sending auth frame");
        write
            .send(WsMessage::Text(auth_frame.into()))
            .await
            .context("custom WS: failed to send auth frame")?;

        // If auth_success_path is configured, wait for a response and check it.
        if let Some(ref success_path) = self.cfg.auth_success_path {
            let resp = tokio::time::timeout(Duration::from_secs(10), read.next())
                .await
                .context("custom WS: auth response timeout")?
                .ok_or_else(|| anyhow::anyhow!("custom WS: connection closed during auth"))?
                .context("custom WS: error reading auth response")?;

            let text = match resp {
                WsMessage::Text(t) => t.to_string(),
                WsMessage::Binary(b) => String::from_utf8_lossy(&b).into_owned(),
                _ => bail!("custom WS: unexpected frame type in auth response"),
            };

            let val: Value = serde_json::from_str(&text)
                .context("custom WS: auth response is not valid JSON")?;

            if let Some(extracted) = json_path_extract(&val, success_path) {
                if let Some(ref expected) = self.cfg.auth_success_value {
                    if value_as_string(extracted) != *expected {
                        bail!(
                            "custom WS auth failed: expected '{}' at '{}', got '{}'",
                            expected,
                            success_path,
                            value_as_string(extracted)
                        );
                    }
                }
                info!(channel = %self.cfg.name, "WS auth successful");
            } else {
                bail!(
                    "custom WS auth failed: path '{}' not found in response",
                    success_path
                );
            }
        }

        Ok(())
    }

    /// Send a reply frame on the WS connection.
    fn format_reply(&self, msg: &OutboundMessage) -> Option<String> {
        let template = self.cfg.reply_frame.as_ref()?;
        Some(render_template(
            template,
            &msg.target_id,
            &msg.target_id,
            &msg.text,
            msg.is_group,
        ))
    }
}

impl Channel for CustomWebSocketChannel {
    fn name(&self) -> &str {
        &self.cfg.name
    }

    fn send(&self, msg: OutboundMessage) -> BoxFuture<'_, Result<()>> {
        Box::pin(async move {
            if let Some(frame) = self.format_reply(&msg) {
                let guard = self.ws_tx.lock().await;
                if let Some(ref tx) = *guard {
                    tx.send(frame)
                        .await
                        .context("custom WS: failed to enqueue reply frame")?;
                } else {
                    warn!(channel = %self.cfg.name, "WS not connected, dropping reply");
                }
            } else {
                debug!(channel = %self.cfg.name, "no reply_frame template configured");
            }
            Ok(())
        })
    }

    fn run(self: Arc<Self>) -> BoxFuture<'static, Result<()>> {
        Box::pin(async move {
            loop {
                info!(channel = %self.cfg.name, "custom WS channel connecting...");

                match self.run_once().await {
                    Ok(()) => {
                        info!(channel = %self.cfg.name, "custom WS channel disconnected cleanly");
                    }
                    Err(e) => {
                        warn!(channel = %self.cfg.name, error = %e, "custom WS channel error");
                    }
                }

                // Reconnect after a delay.
                info!(channel = %self.cfg.name, "reconnecting in 5s...");
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        })
    }
}

impl CustomWebSocketChannel {
    async fn run_once(self: &Arc<Self>) -> Result<()> {
        let (mut write, mut read) = self.connect_ws().await?;

        // Auth.
        self.authenticate(&mut write, &mut read).await?;

        info!(channel = %self.cfg.name, "custom WS channel connected");

        // Set up outbound sender.
        let (out_tx, mut out_rx) = mpsc::channel::<String>(64);
        {
            let mut guard = self.ws_tx.lock().await;
            *guard = Some(out_tx);
        }

        // Heartbeat setup.
        let hb_interval = self.cfg.heartbeat_interval.unwrap_or(0);
        let hb_frame = self.cfg.heartbeat_frame.clone();
        let mut hb_timer = if hb_interval > 0 && hb_frame.is_some() {
            Some(tokio::time::interval(Duration::from_secs(hb_interval)))
        } else {
            None
        };

        loop {
            tokio::select! {
                // Inbound WS message.
                frame = read.next() => {
                    match frame {
                        Some(Ok(WsMessage::Text(text))) => {
                            let text_str: &str = &text;
                            if let Some(parsed) = parse_inbound(&self.cfg, text_str) {
                                let is_group = parsed.group_id.is_some();
                                (self.on_message)(parsed.sender, parsed.text, is_group);
                            }
                        }
                        Some(Ok(WsMessage::Binary(data))) => {
                            let text = String::from_utf8_lossy(&data);
                            if let Some(parsed) = parse_inbound(&self.cfg, &text) {
                                let is_group = parsed.group_id.is_some();
                                (self.on_message)(parsed.sender, parsed.text, is_group);
                            }
                        }
                        Some(Ok(WsMessage::Close(_))) => {
                            info!(channel = %self.cfg.name, "WS close frame received");
                            break;
                        }
                        Some(Ok(WsMessage::Ping(data))) => {
                            let _ = write.send(WsMessage::Pong(data)).await;
                        }
                        Some(Ok(_)) => {} // Pong, Frame — ignore
                        Some(Err(e)) => {
                            warn!(channel = %self.cfg.name, error = %e, "WS read error");
                            break;
                        }
                        None => {
                            info!(channel = %self.cfg.name, "WS stream ended");
                            break;
                        }
                    }
                }

                // Outbound reply frame.
                Some(frame) = out_rx.recv() => {
                    if let Err(e) = write.send(WsMessage::Text(frame.into())).await {
                        warn!(channel = %self.cfg.name, error = %e, "WS write error");
                        break;
                    }
                }

                // Heartbeat.
                _ = async {
                    match hb_timer.as_mut() {
                        Some(t) => t.tick().await,
                        None => futures::future::pending().await,
                    }
                } => {
                    if let Some(ref frame) = hb_frame {
                        let expanded = expand_env_vars(frame);
                        if let Err(e) = write.send(WsMessage::Text(expanded.into())).await {
                            warn!(channel = %self.cfg.name, error = %e, "WS heartbeat send error");
                            break;
                        }
                    }
                }
            }
        }

        // Clear the sender so we don't try to send on a dead connection.
        {
            let mut guard = self.ws_tx.lock().await;
            *guard = None;
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn json_path_simple() {
        let val: Value = serde_json::json!({
            "type": "message",
            "data": {
                "text": "hello",
                "from": { "id": "user123" }
            }
        });

        assert_eq!(
            json_path_extract(&val, "$.type").unwrap(),
            &Value::String("message".to_owned())
        );
        assert_eq!(
            json_path_extract(&val, "$.data.text").unwrap(),
            &Value::String("hello".to_owned())
        );
        assert_eq!(
            json_path_extract(&val, "$.data.from.id").unwrap(),
            &Value::String("user123".to_owned())
        );
        assert!(json_path_extract(&val, "$.nonexistent").is_none());
    }

    #[test]
    fn json_path_array_index() {
        let val: Value = serde_json::json!({
            "items": [
                { "name": "first" },
                { "name": "second" }
            ]
        });

        assert_eq!(
            json_path_extract(&val, "$.items[0].name").unwrap(),
            &Value::String("first".to_owned())
        );
        assert_eq!(
            json_path_extract(&val, "$.items[1].name").unwrap(),
            &Value::String("second".to_owned())
        );
        assert!(json_path_extract(&val, "$.items[5].name").is_none());
    }

    #[test]
    fn json_path_no_dollar_prefix() {
        let val: Value = serde_json::json!({"foo": {"bar": 42}});
        assert_eq!(
            json_path_extract(&val, "foo.bar").unwrap(),
            &Value::Number(42.into())
        );
    }

    #[test]
    fn template_rendering() {
        let result = render_template(
            r#"{"to":"{{sender}}","msg":"{{reply}}","group":{{is_group}}}"#,
            "user1",
            "chat1",
            "hello world",
            true,
        );
        assert_eq!(result, r#"{"to":"user1","msg":"hello world","group":true}"#);
    }

    #[test]
    fn template_escapes_json() {
        let result = render_template(
            r#"{"text":"{{reply}}"}"#,
            "",
            "",
            "line1\nline2\"quoted\"",
            false,
        );
        assert_eq!(result, r#"{"text":"line1\nline2\"quoted\""}"#);
    }

    #[test]
    fn env_var_expansion() {
        unsafe {
            std::env::set_var("_RSCLAW_TEST_VAR", "test_value");
        }
        let result = expand_env_vars("prefix-${_RSCLAW_TEST_VAR}-suffix");
        assert_eq!(result, "prefix-test_value-suffix");
        unsafe {
            std::env::remove_var("_RSCLAW_TEST_VAR");
        }
    }

    #[test]
    fn parse_inbound_with_filter() {
        let cfg = CustomChannelConfig {
            name: "test".to_owned(),
            channel_type: "webhook".to_owned(),
            base: Default::default(),
            ws_url: None,
            ws_headers: None,
            auth_frame: None,
            auth_success_path: None,
            auth_success_value: None,
            heartbeat_interval: None,
            heartbeat_frame: None,
            filter_path: Some("$.type".to_owned()),
            filter_value: Some("message".to_owned()),
            text_path: Some("$.data.text".to_owned()),
            sender_path: Some("$.data.from".to_owned()),
            group_path: None,
            reply_url: None,
            reply_method: None,
            reply_template: None,
            reply_headers: None,
            reply_frame: None,
        };

        // Matching message.
        let body = r#"{"type":"message","data":{"text":"hello","from":"user1"}}"#;
        let parsed = parse_inbound(&cfg, body).unwrap();
        assert_eq!(parsed.text, "hello");
        assert_eq!(parsed.sender, "user1");
        assert!(parsed.group_id.is_none());

        // Non-matching type.
        let body2 = r#"{"type":"heartbeat","data":{}}"#;
        assert!(parse_inbound(&cfg, body2).is_none());
    }
}