use adk_kernel::channels::{ChannelInbound, DecisionCard, InboundBody};
use chrono::FixedOffset;
use serde_json::{Value, json};
use super::WHATSAPP_CHANNEL;
use crate::channels::shared::{
Button, Heading, Piece, Words, buttons, card_words, chunks, clean_inbound, parse_callback,
truncate,
};
pub(crate) const MAX_BUTTONS: usize = 3;
pub(crate) const MAX_TITLE_CHARS: usize = 20;
const MAX_BODY_CHARS: usize = 1024;
const MAX_TEXT_CHARS: usize = 4096;
const MAX_REPLY_CHARS: usize = 3000;
const BREAK: char = '\u{200B}';
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Received {
pub(crate) id: String,
pub(crate) thread: String,
pub(crate) at: Option<i64>,
pub(crate) inbound: Option<ChannelInbound>,
pub(crate) card: Option<String>,
pub(crate) media: Option<(String, Option<String>)>,
}
fn text_of(value: &Value) -> &str {
value.as_str().unwrap_or_default()
}
pub(crate) fn parse(payload: &Value, phone_number_id: &str) -> Vec<Received> {
let mut received = Vec::new();
if payload["object"] != "whatsapp_business_account" {
return received;
}
let changes = payload["entry"]
.as_array()
.into_iter()
.flatten()
.flat_map(|entry| entry["changes"].as_array().into_iter().flatten());
for change in changes {
let value = &change["value"];
if change["field"] != "messages" || value["metadata"]["phone_number_id"] != phone_number_id
{
continue;
}
let contacts: Vec<&Value> = value["contacts"].as_array().into_iter().flatten().collect();
for message in value["messages"].as_array().into_iter().flatten() {
let (from, id) = (text_of(&message["from"]), text_of(&message["id"]));
if from.is_empty() || id.is_empty() {
continue;
}
let contact = match contacts.as_slice() {
[only] => Some(*only),
_ => contacts.iter().copied().find(|contact| contact["wa_id"] == from),
};
let thread = contact.map_or(from, |contact| text_of(&contact["wa_id"]));
let thread = if thread.is_empty() { from } else { thread };
let name = contact.and_then(|contact| contact["profile"]["name"].as_str());
let (inbound, card) = read(message, from, thread, id);
let media = (message["type"] == "image")
.then(|| message["image"]["id"].as_str().map(str::to_string))
.flatten()
.map(|media| (media, message["image"]["mime_type"].as_str().map(str::to_string)))
.filter(|_| inbound.is_some());
let inbound = match (inbound, name.filter(|name| !name.is_empty())) {
(Some(inbound), Some(name)) => Some(inbound.with_display_name(name)),
(inbound, _) => inbound,
};
received.push(Received {
id: id.to_string(),
thread: thread.to_string(),
at: text_of(&message["timestamp"]).parse().ok(),
inbound,
card,
media,
});
}
}
received
}
fn read(
message: &Value,
from: &str,
thread: &str,
id: &str,
) -> (Option<ChannelInbound>, Option<String>) {
match message["type"].as_str() {
Some("text") => {
let inbound = clean_inbound(text_of(&message["text"]["body"]))
.map(|text| ChannelInbound::text(WHATSAPP_CHANNEL, from, thread, id, text));
(inbound, None)
}
Some("image") if message["image"]["id"].is_string() => {
let text = clean_inbound(text_of(&message["image"]["caption"])).unwrap_or_default();
(Some(ChannelInbound::text(WHATSAPP_CHANNEL, from, thread, id, text)), None)
}
Some("interactive") if message["interactive"]["type"] == "button_reply" => {
let reply = &message["interactive"]["button_reply"];
let Some((answer, version, decision)) = reply["id"].as_str().and_then(parse_callback)
else {
return (None, None);
};
let card = message["context"]["id"].as_str().map(str::to_string);
let mut inbound = ChannelInbound::text(WHATSAPP_CHANNEL, from, thread, id, "");
inbound.body = InboundBody::Answer { decision, version, answer };
(Some(inbound), card)
}
_ => (None, None),
}
}
pub(crate) fn escape(text: &str) -> String {
let mut out = String::with_capacity(text.len() + 8);
let mut line_start = true;
for c in text.chars() {
match c {
'*' | '_' | '~' | '`' => {
out.push(BREAK);
out.push(c);
out.push(BREAK);
}
'>' | '-' if line_start => {
out.push(BREAK);
out.push(c);
}
c => out.push(c),
}
line_start = c == '\n' || (line_start && c == ' ');
}
out
}
fn render(words: &Words) -> String {
words.render(|piece| match piece {
Piece::Plain(text) => escape(text),
Piece::Bold(text) => format!("*{}*", escape(text)),
Piece::Code(text) => format!("```{}```", text.replace('`', "")),
Piece::Link { url, label } => format!("{label}: {url}"),
})
}
pub(crate) fn text(to: &str, body: &str, reply_to: Option<&str>) -> Value {
let mut message = json!({
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": to,
"type": "text",
"text": { "body": truncate(body, MAX_TEXT_CHARS), "preview_url": false },
});
if let Some(id) = reply_to {
message["context"] = json!({ "message_id": id });
}
message
}
pub(crate) fn message(to: &str, words: &Words, reply_to: Option<&str>) -> Value {
text(to, &render(words), reply_to)
}
fn reply_buttons(card: &DecisionCard) -> Option<Vec<Button>> {
let buttons = buttons(card);
(!buttons.is_empty() && buttons.len() <= MAX_BUTTONS).then_some(buttons)
}
pub(crate) fn card(
to: &str,
card: &DecisionCard,
heading: &Heading,
offset: Option<FixedOffset>,
) -> Value {
let words = card_words(card, heading, offset);
let Some(buttons) = reply_buttons(card) else {
let mut words = words;
if buttons(card).len() > MAX_BUTTONS {
let decide = adk_kernel::channels::ChannelNotice::DecideInHome { home: None }.text();
let at = words.lines.len() - usize::from(words.link().is_some());
words.lines.insert(at, vec![Piece::Plain(decide)]);
}
return text(to, &render(&words), None);
};
let buttons: Vec<Value> = buttons
.into_iter()
.map(|button| {
json!({ "type": "reply", "reply": { "id": button.data, "title": truncate(button.label, MAX_TITLE_CHARS) } })
})
.collect();
json!({
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": to,
"type": "interactive",
"interactive": {
"type": "button",
"body": { "text": truncate(&render(&words), MAX_BODY_CHARS) },
"action": { "buttons": buttons },
},
})
}
pub(crate) fn plain(to: &str, text_body: &str) -> Vec<Value> {
chunks(text_body, MAX_REPLY_CHARS)
.into_iter()
.map(|chunk| text(to, &escape(&chunk), None))
.collect()
}
pub(crate) fn template(to: &str, name: &str, language: &str) -> Value {
json!({
"messaging_product": "whatsapp",
"recipient_type": "individual",
"to": to,
"type": "template",
"template": { "name": name, "language": { "code": language } },
})
}
#[cfg(test)]
mod tests {
use adk_core::{
ActingContext, AgentPrincipal, ApprovalPolicy, ApprovalRequest, ApprovalRisk,
ApprovalScope, ApproverSelector, ToolConfirmationRequest,
};
use adk_kernel::channels::ChannelAnswer;
use proptest::prelude::*;
use super::*;
use crate::channels::shared::heading;
fn payload(message: Value) -> Value {
json!({ "object": "whatsapp_business_account", "entry": [{ "id": "w1", "changes": [{
"field": "messages",
"value": {
"messaging_product": "whatsapp",
"metadata": { "display_phone_number": "15550000000", "phone_number_id": "1001" },
"contacts": [{ "profile": { "name": "Ana" }, "wa_id": "254700000001" }],
"messages": [message],
},
}]}]})
}
#[test]
fn a_text_message_is_typed_and_a_reply_button_answers() {
let text_message = json!({ "from": "254700000001", "id": "wamid.1", "timestamp": "1761300000",
"type": "text", "text": { "body": " hi\u{200B} there " } });
let received = parse(&payload(text_message), "1001");
assert_eq!(received.len(), 1);
assert_eq!(
received[0].inbound,
Some(
ChannelInbound::text(
WHATSAPP_CHANNEL,
"254700000001",
"254700000001",
"wamid.1",
"hi there"
)
.with_display_name("Ana")
)
);
assert_eq!(received[0].at, Some(1_761_300_000));
let press = json!({ "from": "254700000001", "id": "wamid.2", "timestamp": "1761300001",
"type": "interactive", "context": { "from": "15550000000", "id": "wamid.card" },
"interactive": { "type": "button_reply", "button_reply": { "id": "y:4:apr_1", "title": "Allow once" } } });
let received = parse(&payload(press), "1001");
assert_eq!(
received[0].inbound.as_ref().unwrap().body,
InboundBody::Answer {
decision: "apr_1".into(),
version: 4,
answer: ChannelAnswer::AllowOnce
}
);
assert_eq!(received[0].card.as_deref(), Some("wamid.card"));
let typed = json!({ "from": "254700000001", "id": "wamid.3", "type": "text", "text": { "body": "y:4:apr_1" } });
assert!(matches!(
parse(&payload(typed.clone()), "1001")[0].inbound.as_ref().unwrap().body,
InboundBody::Text { .. }
));
assert!(parse(&payload(typed), "2002").is_empty());
let image = json!({ "from": "254700000001", "id": "wamid.4", "type": "image", "image": { "id": "m1" } });
let received = parse(&payload(image), "1001");
assert_eq!(
received[0].inbound.as_ref().unwrap().body,
InboundBody::Text { text: String::new() }
);
assert_eq!(received[0].media, Some(("m1".to_string(), None)));
let video = json!({ "from": "254700000001", "id": "wamid.5", "type": "video", "video": { "id": "v1" } });
assert!(
parse(&payload(video), "1001")[0].inbound.is_none(),
"media other than images reaches no agent"
);
assert!(parse(&json!({ "object": "page" }), "1001").is_empty());
}
fn request(risk: ApprovalRisk) -> ApprovalRequest {
let call = ToolConfirmationRequest::new("send_email", json!({ "to": "a@example.com" }));
ApprovalRequest::new(
"apr_1",
ApprovalScope::new("adk-rust", "ana", "s1"),
&call,
ApprovalPolicy::new([ApproverSelector::group("operator")]),
)
.with_summary("Send *the* _invoice_ to a@example.com")
.with_risk(risk)
.with_acting(ActingContext::new(AgentPrincipal::derived("adk-rust", "finance")))
}
#[test]
fn a_card_has_at_most_three_buttons_of_twenty_characters() {
let card_value = DecisionCard::from_request(
&request(ApprovalRisk::Low),
Some("https://home.example/ui/"),
);
let drawn = card(
"254700000001",
&card_value,
&heading(&card_value, None),
FixedOffset::east_opt(0),
);
let buttons = drawn["interactive"]["action"]["buttons"].as_array().unwrap();
assert!(buttons.len() <= MAX_BUTTONS);
for button in buttons {
assert!(button["reply"]["title"].as_str().unwrap().chars().count() <= MAX_TITLE_CHARS);
assert!(button["reply"]["id"].as_str().unwrap().len() <= 256);
}
let body = drawn["interactive"]["body"]["text"].as_str().unwrap();
assert!(body.contains("\u{200B}*\u{200B}the\u{200B}*\u{200B}"), "{body}");
assert!(body.ends_with("Open in home: https://home.example/ui/"), "{body}");
assert!(!drawn.to_string().contains("a@example.com"));
let high = DecisionCard::from_request(&request(ApprovalRisk::High), None);
let drawn = card("254700000001", &high, &heading(&high, None), None);
assert_eq!(drawn["type"], "text", "no buttons at high risk");
assert_eq!(
truncate("Allow once for all of this week", MAX_TITLE_CHARS).chars().count(),
MAX_TITLE_CHARS
);
}
proptest! {
#![proptest_config(ProptestConfig::with_cases(256))]
#[test]
fn escaping_reads_back_and_breaks_every_marker(text in "\\PC{0,200}") {
let escaped = escape(&text);
prop_assert_eq!(escaped.replace(BREAK, ""), text.replace(BREAK, ""));
let chars: Vec<char> = escaped.chars().collect();
for (index, c) in chars.iter().enumerate() {
if matches!(c, '*' | '_' | '~' | '`') {
prop_assert_eq!(chars.get(index + 1), Some(&BREAK));
prop_assert_eq!(index.checked_sub(1).and_then(|i| chars.get(i)), Some(&BREAK));
}
}
}
}
}