Skip to main content

microclaw_engine/internal/channels/
channel.rs

1use std::sync::Arc;
2
3use crate::internal::channels::channel_adapter::ChannelRegistry;
4use crate::internal::storage::db::{call_blocking, Database, OutboxMessageRecord, StoredMessage};
5use microclaw_core::text::{sanitize_user_visible_text, split_text};
6
7#[derive(Clone, Debug)]
8struct ToolAuthContext {
9    caller_chat_id: i64,
10}
11
12fn auth_context_from_input(input: &serde_json::Value) -> Option<ToolAuthContext> {
13    let ctx = input.get("__microclaw_auth")?;
14    let caller_chat_id = ctx.get("caller_chat_id")?.as_i64()?;
15    Some(ToolAuthContext { caller_chat_id })
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub enum ConversationKind {
20    Private,
21    Group,
22}
23
24impl ConversationKind {
25    pub fn as_agent_chat_type(self) -> &'static str {
26        match self {
27            ConversationKind::Private => "private",
28            ConversationKind::Group => "group",
29        }
30    }
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ChatRouting {
35    pub channel_name: String,
36    pub conversation: ConversationKind,
37}
38
39pub fn parse_chat_routing(registry: &ChannelRegistry, db_chat_type: &str) -> Option<ChatRouting> {
40    let (channel_name, kind) = registry.resolve_routing(db_chat_type)?;
41    Some(ChatRouting {
42        channel_name: channel_name.to_string(),
43        conversation: kind,
44    })
45}
46
47fn infer_channel_from_chat_type(chat_type: &str) -> Option<&'static str> {
48    if chat_type.starts_with("telegram_") {
49        return Some("telegram");
50    }
51    if chat_type.starts_with("discord_") {
52        return Some("discord");
53    }
54    if chat_type.starts_with("slack_") {
55        return Some("slack");
56    }
57    if chat_type.starts_with("feishu_") {
58        return Some("feishu");
59    }
60    if chat_type.starts_with("whatsapp_") {
61        return Some("whatsapp");
62    }
63    if chat_type.starts_with("imessage_") {
64        return Some("imessage");
65    }
66    if chat_type.starts_with("email_") {
67        return Some("email");
68    }
69    if chat_type.starts_with("nostr_") {
70        return Some("nostr");
71    }
72    if chat_type.starts_with("signal_") {
73        return Some("signal");
74    }
75    if chat_type.starts_with("dingtalk_") {
76        return Some("dingtalk");
77    }
78    if chat_type.starts_with("qq_") {
79        return Some("qq");
80    }
81    if chat_type.starts_with("weixin_") {
82        return Some("weixin");
83    }
84    if chat_type.starts_with("irc_") {
85        return Some("irc");
86    }
87    None
88}
89
90pub async fn get_chat_type_raw(db: Arc<Database>, chat_id: i64) -> Result<Option<String>, String> {
91    call_blocking(db, move |d| d.get_chat_type(chat_id))
92        .await
93        .map_err(|e| format!("Failed to read chat type for chat {chat_id}: {e}"))
94}
95
96pub async fn get_chat_channel_raw(
97    db: Arc<Database>,
98    chat_id: i64,
99) -> Result<Option<String>, String> {
100    call_blocking(db, move |d| d.get_chat_channel(chat_id))
101        .await
102        .map_err(|e| format!("Failed to read chat channel for chat {chat_id}: {e}"))
103}
104
105pub async fn get_chat_routing(
106    registry: &ChannelRegistry,
107    db: Arc<Database>,
108    chat_id: i64,
109) -> Result<Option<ChatRouting>, String> {
110    let chat_type = get_chat_type_raw(db.clone(), chat_id).await?;
111    let Some(chat_type) = chat_type else {
112        return Ok(None);
113    };
114
115    let kind = registry
116        .resolve_routing(&chat_type)
117        .map(|(_, k)| k)
118        .unwrap_or(ConversationKind::Group);
119
120    if let Some(channel_name) = get_chat_channel_raw(db, chat_id).await? {
121        let normalized = channel_name.trim();
122        if !normalized.is_empty() && registry.get(normalized).is_some() {
123            return Ok(Some(ChatRouting {
124                channel_name: normalized.to_string(),
125                conversation: kind,
126            }));
127        }
128    }
129
130    Ok(parse_chat_routing(registry, &chat_type))
131}
132
133pub async fn get_required_chat_routing(
134    registry: &ChannelRegistry,
135    db: Arc<Database>,
136    chat_id: i64,
137) -> Result<ChatRouting, String> {
138    let chat_type = get_chat_type_raw(db.clone(), chat_id)
139        .await?
140        .ok_or_else(|| format!("target chat {chat_id} not found"))?;
141    if let Some(routing) = get_chat_routing(registry, db.clone(), chat_id).await? {
142        return Ok(routing);
143    }
144
145    let hinted_channel = get_chat_channel_raw(db, chat_id)
146        .await?
147        .map(|v| v.trim().to_string())
148        .filter(|v| !v.is_empty())
149        .or_else(|| infer_channel_from_chat_type(&chat_type).map(ToOwned::to_owned));
150
151    if let Some(channel_name) = hinted_channel {
152        if registry.get(&channel_name).is_none() {
153            return Err(format!(
154                "channel '{channel_name}' is not enabled for chat {chat_id} (chat_type='{chat_type}')"
155            ));
156        }
157    }
158
159    Err(format!(
160        "unsupported chat type '{chat_type}' for chat {chat_id}"
161    ))
162}
163
164pub fn session_source_for_chat(
165    registry: &ChannelRegistry,
166    chat_type: &str,
167    chat_title: Option<&str>,
168) -> String {
169    // Legacy discord detection: some old records have generic types like "private"
170    // but a title starting with "discord-"
171    if matches!(chat_type, "private" | "group" | "supergroup" | "channel")
172        && chat_title.is_some_and(|t| t.starts_with("discord-"))
173    {
174        return "discord".to_string();
175    }
176
177    if let Some((channel_name, _)) = registry.resolve_routing(chat_type) {
178        return channel_name.to_string();
179    }
180
181    chat_type.to_string()
182}
183
184pub async fn is_web_chat(registry: &ChannelRegistry, db: Arc<Database>, chat_id: i64) -> bool {
185    get_chat_routing(registry, db, chat_id)
186        .await
187        .ok()
188        .flatten()
189        .map(|r| r.channel_name == "web")
190        .unwrap_or(false)
191}
192
193pub async fn enforce_channel_policy(
194    registry: &ChannelRegistry,
195    db: Arc<Database>,
196    input: &serde_json::Value,
197    target_chat_id: i64,
198) -> Result<(), String> {
199    let Some(auth) = auth_context_from_input(input) else {
200        return Ok(());
201    };
202
203    // Check if the caller's channel disallows cross-chat operations
204    if let Ok(Some(routing)) = get_chat_routing(registry, db.clone(), auth.caller_chat_id).await {
205        if let Some(adapter) = registry.get(&routing.channel_name) {
206            if !adapter.allows_cross_chat() && auth.caller_chat_id != target_chat_id {
207                return Err(format!(
208                    "Permission denied: {} chats cannot operate on other chats",
209                    routing.channel_name
210                ));
211            }
212        }
213    }
214
215    Ok(())
216}
217
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub enum DeliveryOutcome {
220    Delivered,
221    Queued {
222        delivery_id: String,
223        failed_chunk: usize,
224        total_chunks: usize,
225    },
226}
227
228pub async fn deliver_and_store_bot_message(
229    registry: &ChannelRegistry,
230    db: Arc<Database>,
231    bot_username: &str,
232    chat_id: i64,
233    text: &str,
234) -> Result<(), String> {
235    deliver_and_store_bot_message_with_status(registry, db, bot_username, chat_id, text)
236        .await
237        .map(|_| ())
238}
239
240pub async fn deliver_and_store_bot_message_with_status(
241    registry: &ChannelRegistry,
242    db: Arc<Database>,
243    bot_username: &str,
244    chat_id: i64,
245    text: &str,
246) -> Result<DeliveryOutcome, String> {
247    let routing = get_required_chat_routing(registry, db.clone(), chat_id).await?;
248    let external_chat_id = call_blocking(db.clone(), move |d| d.get_chat_external_id(chat_id))
249        .await
250        .map_err(|e| format!("Failed to read external chat id for chat {chat_id}: {e}"))?
251        .unwrap_or_else(|| chat_id.to_string());
252
253    // This choke point is the final defense against model/runtime protocol
254    // details leaking into any user-facing channel.
255    let visible = sanitize_user_visible_text(text);
256    if visible.is_empty() && !text.trim().is_empty() {
257        return Err("outbound message contained no user-visible text".to_string());
258    }
259
260    // Outbound guardrail: scan for credential-like strings before delivery.
261    let guarded =
262        microclaw_core::redact::apply_output_guardrail(&visible, registry.output_guardrail());
263    if let Some(outcome) = &guarded {
264        tracing::warn!(
265            target: "output_guardrail",
266            chat_id,
267            blocked = outcome.blocked,
268            categories = ?outcome.categories,
269            "outbound message tripped the output guardrail"
270        );
271    }
272    let text: &str = guarded
273        .as_ref()
274        .map(|o| o.text.as_str())
275        .unwrap_or(&visible);
276
277    if let Some(adapter) = registry.get(&routing.channel_name) {
278        if adapter.is_local_only() {
279            store_bot_message(db, bot_username, chat_id, text).await?;
280            return Ok(DeliveryOutcome::Delivered);
281        }
282
283        let chunks = adapter
284            .text_chunk_limit_bytes()
285            .map(|limit| split_text(text, limit))
286            .unwrap_or_else(|| vec![text.to_string()]);
287        let delivery_id = format!("delivery-{}", uuid::Uuid::new_v4());
288        let delivery_id_for_create = delivery_id.clone();
289        let channel_for_create = routing.channel_name.clone();
290        let full_text = text.to_string();
291        let chunks_for_create = chunks.clone();
292        let chunk_ids = call_blocking(db.clone(), move |d| {
293            d.create_outbound_delivery(
294                &delivery_id_for_create,
295                chat_id,
296                &channel_for_create,
297                &full_text,
298                &chunks_for_create,
299            )
300        })
301        .await
302        .map_err(|e| format!("Failed to persist outbound delivery: {e}"))?;
303
304        for (index, (chunk_id, chunk)) in chunk_ids.iter().zip(chunks.iter()).enumerate() {
305            let chunk_id = *chunk_id;
306            let claimed = call_blocking(db.clone(), move |d| d.mark_outbox_sending(chunk_id))
307                .await
308                .map_err(|e| format!("Failed to claim outbound chunk: {e}"))?;
309            if !claimed {
310                continue;
311            }
312            let idempotency_key = format!("{delivery_id}:{}", index + 1);
313            if let Err(err) = adapter
314                .send_text_chunk(&external_chat_id, chunk, &idempotency_key)
315                .await
316            {
317                let retry_at = chrono::Utc::now().to_rfc3339();
318                let error_for_db = err.clone();
319                call_blocking(db.clone(), move |d| {
320                    d.mark_outbox_retry(chunk_id, 1, Some(&retry_at), &error_for_db, false)
321                })
322                .await
323                .map_err(|e| format!("{err}; failed to queue chunk retry: {e}"))?;
324                tracing::warn!(
325                    delivery_id,
326                    failed_chunk = index + 1,
327                    total_chunks = chunks.len(),
328                    error = %err,
329                    "outbound delivery accepted durably and queued for retry"
330                );
331                return Ok(DeliveryOutcome::Queued {
332                    delivery_id,
333                    failed_chunk: index + 1,
334                    total_chunks: chunks.len(),
335                });
336            }
337            call_blocking(db.clone(), move |d| d.mark_outbox_delivered(chunk_id))
338                .await
339                .map_err(|e| format!("Chunk sent but delivery ledger update failed: {e}"))?;
340            if index + 1 < chunks.len() {
341                if let Some(delay) = adapter.text_chunk_delay() {
342                    tokio::time::sleep(delay).await;
343                }
344            }
345        }
346
347        let delivery_for_finalize = delivery_id.clone();
348        let sender = bot_username.to_string();
349        call_blocking(db.clone(), move |d| {
350            d.finalize_outbound_delivery(&delivery_for_finalize, &sender)
351                .map(|_| ())
352        })
353        .await
354        .map_err(|e| format!("Delivery completed but message persistence failed: {e}"))?;
355        Ok(DeliveryOutcome::Delivered)
356    } else {
357        Err(format!(
358            "No adapter registered for channel '{}'",
359            routing.channel_name
360        ))
361    }
362}
363
364async fn store_bot_message(
365    db: Arc<Database>,
366    bot_username: &str,
367    chat_id: i64,
368    text: &str,
369) -> Result<(), String> {
370    let msg = StoredMessage {
371        id: uuid::Uuid::new_v4().to_string(),
372        chat_id,
373        sender_name: bot_username.to_string(),
374        content: text.to_string(),
375        is_from_bot: true,
376        timestamp: chrono::Utc::now().to_rfc3339(),
377    };
378    call_blocking(db.clone(), move |d| d.store_message(&msg))
379        .await
380        .map_err(|e| format!("Failed to store sent message: {e}"))
381}
382
383/// Send one persisted outbox chunk. The caller owns retry/backoff policy.
384pub async fn send_persisted_outbox_chunk(
385    registry: &ChannelRegistry,
386    db: Arc<Database>,
387    bot_username: &str,
388    row: &OutboxMessageRecord,
389) -> Result<bool, String> {
390    let row_id = row.id;
391    let claimed = call_blocking(db.clone(), move |d| d.mark_outbox_sending(row_id))
392        .await
393        .map_err(|e| format!("Failed to claim outbox chunk: {e}"))?;
394    if !claimed {
395        return Ok(false);
396    }
397    let routing = get_required_chat_routing(registry, db.clone(), row.chat_id).await?;
398    if routing.channel_name != row.channel {
399        return Err(format!(
400            "delivery channel changed from '{}' to '{}'",
401            row.channel, routing.channel_name
402        ));
403    }
404    let chat_id = row.chat_id;
405    let external_chat_id = call_blocking(db.clone(), move |d| d.get_chat_external_id(chat_id))
406        .await
407        .map_err(|e| format!("Failed to read external chat id for chat {chat_id}: {e}"))?
408        .unwrap_or_else(|| chat_id.to_string());
409    let adapter = registry.get(&routing.channel_name).ok_or_else(|| {
410        format!(
411            "No adapter registered for channel '{}'",
412            routing.channel_name
413        )
414    })?;
415    adapter
416        .send_text_chunk(&external_chat_id, &row.payload_text, &row.idempotency_key)
417        .await?;
418    let chunk_id = row.id;
419    call_blocking(db.clone(), move |d| d.mark_outbox_delivered(chunk_id))
420        .await
421        .map_err(|e| format!("Chunk sent but ledger update failed: {e}"))?;
422    let delivery_id = row.delivery_id.clone();
423    let sender = bot_username.to_string();
424    call_blocking(db, move |d| {
425        d.finalize_outbound_delivery(&delivery_id, &sender)
426    })
427    .await
428    .map_err(|e| format!("Failed to finalize outbound delivery: {e}"))
429}
430
431#[cfg(test)]
432mod tests {
433    use super::infer_channel_from_chat_type;
434
435    #[test]
436    fn test_infer_channel_from_prefixed_chat_type() {
437        assert_eq!(
438            infer_channel_from_chat_type("telegram_private"),
439            Some("telegram")
440        );
441        assert_eq!(infer_channel_from_chat_type("discord_dm"), Some("discord"));
442        assert_eq!(infer_channel_from_chat_type("weixin_dm"), Some("weixin"));
443    }
444
445    #[test]
446    fn test_infer_channel_from_unknown_chat_type() {
447        assert_eq!(infer_channel_from_chat_type("private"), None);
448        assert_eq!(infer_channel_from_chat_type("group"), None);
449    }
450}