Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(whatsapp): WhatsApp plugin, phase 1 text channel (#202)

Salman Qureshi738f25a9d641
diff --git a/.github/workflows/plugin-whatsapp.yml b/.github/workflows/plugin-whatsapp.yml
new file mode 100644
index 00000000..4c64d31a
--- /dev/null
+++ b/.github/workflows/plugin-whatsapp.yml
@@ -0,0 +1,80 @@
+name: plugin-whatsapp
+
+# Builds the WhatsApp plugin's companion for each platform and uploads the
+# packaged plugins as workflow artifacts. Nothing is released or published.
+on:
+ push:
+ paths:
+ - 'plugins/whatsapp/**'
+ - '.github/workflows/plugin-whatsapp.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ build:
+ strategy:
+ fail-fast: false
+ matrix:
+ include:
+ - { os: ubuntu-24.04, target: x86_64-unknown-linux-gnu, platform: linux-x64 }
+ - { os: ubuntu-24.04-arm, target: aarch64-unknown-linux-gnu, platform: linux-arm64 }
+ - { os: macos-14, target: aarch64-apple-darwin, platform: darwin-arm64 }
+ - { os: macos-14, target: x86_64-apple-darwin, platform: darwin-x64 }
+ - { os: windows-latest, target: x86_64-pc-windows-msvc, platform: win32-x64 }
+ runs-on: ${{ matrix.os }}
+ defaults:
+ run:
+ shell: bash
+ steps:
+ - uses: actions/checkout@v4
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ targets: ${{ matrix.target }}
+ - uses: actions/cache@v4
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ plugins/whatsapp/companion/target
+ key: wa-${{ matrix.target }}-${{ hashFiles('plugins/whatsapp/companion/Cargo.toml', 'plugins/whatsapp/companion/Cargo.lock') }}
+ - name: Build
+ working-directory: plugins/whatsapp/companion
+ run: cargo build --release --locked --target ${{ matrix.target }} || cargo build --release --target ${{ matrix.target }}
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ - name: Package
+ run: |
+ ext=""; [ "${{ matrix.platform }}" = "win32-x64" ] && ext=".exe"
+ node plugins/whatsapp/package.mjs "plugins/whatsapp/companion/target/${{ matrix.target }}/release/mercury-wa$ext" ${{ matrix.platform }} dist
+ ls -la dist
+ - uses: actions/upload-artifact@v4
+ with:
+ name: mercury-plugin-whatsapp-${{ matrix.platform }}
+ path: dist/*
+ if-no-files-found: error
+ retention-days: 30
+
+ conformance:
+ # Install the Linux package into Mercury from this commit and run the
+ # plugin conformance kit (handshake, start, stop, restart).
+ needs: build
+ runs-on: ubuntu-24.04
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
+ cache: npm
+ - run: npm ci
+ - run: npm run build
+ - uses: actions/download-artifact@v4
+ with:
+ name: mercury-plugin-whatsapp-linux-x64
+ path: dist-plugin
+ - name: Validate
+ run: |
+ mkdir pkg && tar -xzf dist-plugin/mercury-plugin-linux-x64.tgz -C pkg
+ MERCURY_HOME="$RUNNER_TEMP/mh" MERCURY_PLUGIN_CATALOG_URL=off node dist/index.js plugins validate pkg
diff --git a/plugins/whatsapp/.gitignore b/plugins/whatsapp/.gitignore
new file mode 100644
index 00000000..849ddff3
--- /dev/null
+++ b/plugins/whatsapp/.gitignore
@@ -0,0 +1 @@
+dist/
diff --git a/plugins/whatsapp/README.md b/plugins/whatsapp/README.md
new file mode 100644
index 00000000..d72c324d
--- /dev/null
+++ b/plugins/whatsapp/README.md
@@ -0,0 +1,69 @@
+# WhatsApp for Mercury
+
+Chat with Mercury on WhatsApp. Mercury runs on a **spare number** as a
+linked device, the same way WhatsApp Web connects, so no WhatsApp Business
+account is needed.
+
+> ⚠️ This uses an **unofficial, reverse-engineered protocol**
+> ([whatsapp-rust](https://github.com/oxidezap/whatsapp-rust)). A WhatsApp
+> update can break it, and automated use can get the number restricted or
+> banned. Use a spare number you can afford to lose, **not your main one**.
+
+## Set up
+
+1. Install it and set your own number as the owner:
+
+ ```sh
+ mercury plugins install whatsapp
+ mercury plugins set whatsapp owner +15551234567
+ ```
+
+ The owner is the number you'll chat *from*. Only the owner, and any
+ numbers you add to `members`, can talk to Mercury.
+
+2. Link the spare number. Either scan a QR code in the terminal:
+
+ ```sh
+ mercury plugins pair whatsapp
+ ```
+
+ Then, on the phone with the spare number, go to WhatsApp → Settings →
+ Linked devices → Link a device.
+
+ Or get a pairing code, which also works from chat:
+
+ ```sh
+ mercury plugins pair whatsapp --code +15550001111
+ ```
+
+3. Message the spare number from your own number. Mercury answers there.
+
+## What works
+
+- Text both ways, with long replies split and Markdown converted to
+ WhatsApp formatting.
+- Files from Mercury arrive as attachments (images as photos, everything
+ else as documents).
+- Images, documents and voice notes you send are passed to Mercury as files.
+- Approvals by reply: *1* yes, *2* no, *3* always for this chat.
+- Groups are ignored unless you turn on `allowGroups`.
+- If WhatsApp logs the device out, Mercury tells you on another channel.
+
+Voice calls are coming next (#202, phase 2).
+
+## Unlink
+
+```sh
+mercury plugins unlink whatsapp
+```
+
+Also remove "Mercury" from Linked devices on the phone if it's still listed.
+
+## Build from source
+
+```sh
+cd plugins/whatsapp/companion
+cargo build --release # Rust 1.94+, a C compiler
+node ../package.mjs target/release/mercury-wa darwin-arm64 ../dist
+mercury plugins install ../dist/mercury-plugin-darwin-arm64.tgz
+```
diff --git a/plugins/whatsapp/companion/.gitignore b/plugins/whatsapp/companion/.gitignore
new file mode 100644
index 00000000..2f7896d1
--- /dev/null
+++ b/plugins/whatsapp/companion/.gitignore
@@ -0,0 +1 @@
+target/
diff --git a/plugins/whatsapp/companion/Cargo.toml b/plugins/whatsapp/companion/Cargo.toml
new file mode 100644
index 00000000..69057f9d
--- /dev/null
+++ b/plugins/whatsapp/companion/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+name = "mercury-wa"
+version = "0.1.0"
+edition = "2024"
+rust-version = "1.94"
+description = "WhatsApp companion for the Mercury WhatsApp plugin (linked device, via whatsapp-rust)"
+license = "MIT"
+publish = false
+
+[dependencies]
+# Pinned: main @ 2026-10-20. Bump deliberately; the protocol is unofficial.
+whatsapp-rust = { git = "https://github.com/oxidezap/whatsapp-rust", rev = "c373266fd2c66ae39752171cff5e0dd798a90205" }
+tokio = { version = "1.47", features = ["full"] }
+serde_json = "1"
+anyhow = "1"
+
+[profile.release]
+opt-level = "z"
+lto = "fat"
+codegen-units = 1
+panic = "abort"
+strip = true
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rs
new file mode 100644
index 00000000..34a3fbb1
--- /dev/null
+++ b/plugins/whatsapp/companion/src/main.rs
@@ -0,0 +1,396 @@
+//! mercury-wa: the WhatsApp side of the Mercury WhatsApp plugin.
+//!
+//! Mercury starts this program and talks to it over stdio, one JSON-RPC 2.0
+//! message per line: MCP (`initialize`, `tools/list`, `ping`) plus the
+//! Mercury channel extension (plugin API 1.1). See
+//! website/docs/reference/plugins.mdx → "Chat channels".
+//!
+//! This process only moves messages. Mercury decides who may talk to the
+//! agent (owner and members), so nothing here filters senders.
+//!
+//! stdout is the protocol channel: logs go to stderr only.
+
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::Duration;
+
+use serde_json::{Value, json};
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+use tokio::sync::{Mutex, mpsc};
+use whatsapp_rust::download::{DownloadLimits, MediaType};
+use whatsapp_rust::media::{self, DocumentOptions, ImageOptions};
+use whatsapp_rust::pair_code::PairCodeOptions;
+use whatsapp_rust::prelude::*;
+use whatsapp_rust::upload::UploadOptions;
+
+const MAX_DOWNLOAD_BYTES: usize = 50 * 1024 * 1024;
+
+/// Writes protocol lines to stdout, in order, from any task.
+#[derive(Clone)]
+struct Out(mpsc::UnboundedSender<Value>);
+
+impl Out {
+ fn notify(&self, method: &str, params: Value) {
+ let _ = self.0.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
+ }
+ fn reply(&self, id: &Value, result: Value) {
+ let _ = self.0.send(json!({ "jsonrpc": "2.0", "id": id, "result": result }));
+ }
+ fn error(&self, id: &Value, code: i64, message: impl Into<String>) {
+ let _ = self.0.send(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message.into() } }));
+ }
+ fn status(&self, state: &str, extra: Value) {
+ let mut params = json!({ "state": state });
+ if let (Some(p), Some(e)) = (params.as_object_mut(), extra.as_object()) {
+ for (k, v) in e {
+ p.insert(k.clone(), v.clone());
+ }
+ }
+ self.notify("mercury/channel/status", params);
+ }
+}
+
+struct State {
+ data_dir: PathBuf,
+ out: Out,
+ bot: Mutex<Option<BotHandle>>,
+ client: Mutex<Option<Arc<Client>>>,
+}
+
+fn log(msg: impl AsRef<str>) {
+ eprintln!("[mercury-wa] {}", msg.as_ref());
+}
+
+fn db_path(dir: &Path) -> PathBuf {
+ dir.join("whatsapp.db")
+}
+
+/// The user part of a phone-number JID ("[email protected]" → "15551234567").
+fn phone_of(jid: &Jid) -> Option<String> {
+ let s = jid.to_string();
+ let (user, server) = s.split_once('@')?;
+ if server != "s.whatsapp.net" {
+ return None;
+ }
+ Some(user.split(':').next().unwrap_or(user).to_string())
+}
+
+#[tokio::main]
+async fn main() -> anyhow::Result<()> {
+ let data_dir = PathBuf::from(std::env::var("MERCURY_PLUGIN_DATA_DIR").unwrap_or_else(|_| ".".into()));
+ std::fs::create_dir_all(data_dir.join("media"))?;
+
+ let (tx, mut rx) = mpsc::unbounded_channel::<Value>();
+ tokio::spawn(async move {
+ let mut stdout = tokio::io::stdout();
+ while let Some(v) = rx.recv().await {
+ let mut line = v.to_string();
+ line.push('\n');
+ if stdout.write_all(line.as_bytes()).await.is_err() {
+ break;
+ }
+ let _ = stdout.flush().await;
+ }
+ });
+ let out = Out(tx);
+ let state = Arc::new(State { data_dir, out: out.clone(), bot: Mutex::new(None), client: Mutex::new(None) });
+
+ let mut lines = BufReader::new(tokio::io::stdin()).lines();
+ while let Some(line) = lines.next_line().await? {
+ let Ok(msg) = serde_json::from_str::<Value>(&line) else { continue };
+ let st = state.clone();
+ tokio::spawn(async move { handle(st, msg).await });
+ }
+ // Mercury closed stdin: we are being stopped.
+ if let Some(bot) = state.bot.lock().await.take() {
+ let _ = tokio::time::timeout(Duration::from_secs(3), bot.shutdown()).await;
+ }
+ Ok(())
+}
+
+async fn handle(st: Arc<State>, msg: Value) {
+ let method = msg.get("method").and_then(Value::as_str).unwrap_or("");
+ let params = msg.get("params").cloned().unwrap_or(Value::Null);
+ let Some(id) = msg.get("id").cloned() else {
+ // Notifications from Mercury.
+ if method == "notifications/initialized" {
+ if db_path(&st.data_dir).exists() {
+ // Linked before: reconnect with the saved session.
+ if let Err(e) = start_bot(st.clone(), None).await {
+ st.out.status("error", json!({ "detail": format!("couldn't start: {e}") }));
+ }
+ } else {
+ st.out.status("needs-pairing", json!({}));
+ }
+ }
+ return;
+ };
+ let out = st.out.clone();
+ let result: Result<Value, String> = match method {
+ "initialize" => Ok(json!({
+ "protocolVersion": "2025-06-18",
+ "capabilities": { "tools": {} },
+ "serverInfo": { "name": "mercury-wa", "version": env!("CARGO_PKG_VERSION") },
+ })),
+ "ping" => Ok(json!({})),
+ "tools/list" => Ok(json!({ "tools": [] })),
+ "mercury/channel/pair" => pair(st.clone(), &params).await,
+ "mercury/channel/unlink" => unlink(st.clone()).await,
+ "mercury/channel/send" => send_text(st.clone(), &params).await,
+ "mercury/channel/sendFile" => send_file(st.clone(), &params).await,
+ "mercury/channel/typing" => typing(st.clone(), &params).await,
+ _ => {
+ out.error(&id, -32601, format!("Method not found: {method}"));
+ return;
+ }
+ };
+ match result {
+ Ok(v) => out.reply(&id, v),
+ Err(e) => out.error(&id, -32000, e),
+ }
+}
+
+async fn client(st: &State) -> Result<Arc<Client>, String> {
+ st.client.lock().await.clone().ok_or_else(|| "WhatsApp is not linked yet. Pair first.".to_string())
+}
+
+fn jid_param(params: &Value) -> Result<Jid, String> {
+ let s = params.get("chatId").and_then(Value::as_str).ok_or("chatId is required")?;
+ s.parse::<Jid>().map_err(|e| format!("bad chatId {s}: {e}"))
+}
+
+async fn pair(st: Arc<State>, params: &Value) -> Result<Value, String> {
+ let phone = params.get("phone").and_then(Value::as_str).map(|p| p.chars().filter(char::is_ascii_digit).collect::<String>());
+ let method = params.get("method").and_then(Value::as_str).unwrap_or("qr");
+ if method == "code" && phone.as_deref().unwrap_or("").len() < 6 {
+ return Err("a pairing code needs the phone number being linked".into());
+ }
+ // Already connected?
+ if let Some(c) = st.client.lock().await.clone() {
+ if c.is_logged_in() {
+ st.out.status("connected", json!({ "account": c.pn().and_then(|j| phone_of(&j)) }));
+ return Ok(json!({}));
+ }
+ }
+ // Restart linking from scratch so the requested method takes effect.
+ if let Some(bot) = st.bot.lock().await.take() {
+ let _ = tokio::time::timeout(Duration::from_secs(3), bot.shutdown()).await;
+ }
+ *st.client.lock().await = None;
+ remove_session(&st.data_dir);
+ start_bot(st.clone(), if method == "code" { phone } else { None }).await.map_err(|e| e.to_string())?;
+ Ok(json!({}))
+}
+
+fn remove_session(dir: &Path) {
+ for suffix in ["", "-wal", "-shm", "-journal"] {
+ let _ = std::fs::remove_file(dir.join(format!("whatsapp.db{suffix}")));
+ }
+}
+
+async fn unlink(st: Arc<State>) -> Result<Value, String> {
+ let c = st.client.lock().await.take();
+ if let Some(c) = c {
+ let _ = tokio::time::timeout(Duration::from_secs(10), c.logout()).await;
+ }
+ if let Some(bot) = st.bot.lock().await.take() {
+ let _ = tokio::time::timeout(Duration::from_secs(3), bot.shutdown()).await;
+ }
+ remove_session(&st.data_dir);
+ st.out.status("logged-out", json!({ "detail": "unlinked by the owner" }));
+ Ok(json!({}))
+}
+
+async fn send_text(st: Arc<State>, params: &Value) -> Result<Value, String> {
+ let c = client(&st).await?;
+ let to = jid_param(params)?;
+ let text = params.get("text").and_then(Value::as_str).ok_or("text is required")?;
+ let sent = c.send_text(to, text).await.map_err(|e| e.to_string())?;
+ Ok(json!({ "id": sent.message_id.to_string() }))
+}
+
+async fn send_file(st: Arc<State>, params: &Value) -> Result<Value, String> {
+ let c = client(&st).await?;
+ let to = jid_param(params)?;
+ let path = PathBuf::from(params.get("path").and_then(Value::as_str).ok_or("path is required")?);
+ let caption = params.get("caption").and_then(Value::as_str).map(str::to_string);
+ let bytes = tokio::fs::read(&path).await.map_err(|e| format!("can't read {}: {e}", path.display()))?;
+ let name = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| "file".into());
+ let mime = mime_of(&name);
+ let is_image = mime.starts_with("image/") && mime != "image/svg+xml";
+ let msg = if is_image {
+ let up = c.upload(bytes, MediaType::Image, UploadOptions::default()).await.map_err(|e| e.to_string())?;
+ let mut opts = ImageOptions::default().with_mimetype(mime);
+ if let Some(cap) = caption {
+ opts = opts.with_caption(cap);
+ }
+ media::image_message(up, opts)
+ } else {
+ let up = c.upload(bytes, MediaType::Document, UploadOptions::default()).await.map_err(|e| e.to_string())?;
+ let mut opts = DocumentOptions::default().with_file_name(name).with_mimetype(mime);
+ if let Some(cap) = caption {
+ opts = opts.with_caption(cap);
+ }
+ media::document_message(up, opts)
+ };
+ let sent = c.send_message(to, msg).await.map_err(|e| e.to_string())?;
+ Ok(json!({ "id": sent.message_id.to_string() }))
+}
+
+async fn typing(st: Arc<State>, params: &Value) -> Result<Value, String> {
+ let c = client(&st).await?;
+ let to = jid_param(params)?;
+ let on = params.get("on").and_then(Value::as_bool).unwrap_or(true);
+ let r = if on { c.chatstate().send_composing(&to).await } else { c.chatstate().send_paused(&to).await };
+ r.map_err(|e| e.to_string())?;
+ Ok(json!({}))
+}
+
+fn mime_of(name: &str) -> String {
+ let ext = name.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
+ match ext.as_str() {
+ "png" => "image/png",
+ "jpg" | "jpeg" => "image/jpeg",
+ "gif" => "image/gif",
+ "webp" => "image/webp",
+ "pdf" => "application/pdf",
+ "txt" | "md" | "log" => "text/plain",
+ "csv" => "text/csv",
+ "json" => "application/json",
+ "html" => "text/html",
+ "zip" => "application/zip",
+ "doc" => "application/msword",
+ "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
+ "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
+ "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
+ "mp3" => "audio/mpeg",
+ "ogg" | "opus" => "audio/ogg",
+ "mp4" => "video/mp4",
+ _ => "application/octet-stream",
+ }
+ .to_string()
+}
+
+async fn start_bot(st: Arc<State>, phone: Option<String>) -> anyhow::Result<()> {
+ let db = db_path(&st.data_dir);
+ let store = SqliteStore::open(&db.to_string_lossy()).await?;
+ st.out.status("starting", json!({}));
+
+ let (o1, o2, o3, o4, o5) = (st.out.clone(), st.out.clone(), st.out.clone(), st.out.clone(), st.out.clone());
+ let st_conn = st.clone();
+ let st_msg = st.clone();
+ let mut builder = Bot::builder()
+ .with_backend(store)
+ .on_qr_code(move |code, _ttl| {
+ let o = o1.clone();
+ async move { o.status("pairing", json!({ "qr": code })) }
+ })
+ .on_pair_code(move |code, _ttl| {
+ let o = o2.clone();
+ async move { o.status("pairing", json!({ "pairCode": code })) }
+ })
+ .on_connected(move |client| {
+ let st = st_conn.clone();
+ async move {
+ let account = client.pn().and_then(|j| phone_of(&j));
+ *st.client.lock().await = Some(client);
+ st.out.status("connected", json!({ "account": account }));
+ }
+ })
+ .on_logged_out(move |lo| {
+ let o = o3.clone();
+ async move { o.status("logged-out", json!({ "detail": format!("{:?}", lo.reason) })) }
+ })
+ .on_event_for(&[EventKind::Disconnected, EventKind::TemporaryBan, EventKind::StreamReplaced, EventKind::ClientOutdated], move |ev, _client| {
+ let o = o4.clone();
+ async move {
+ match &*ev {
+ Event::TemporaryBan(b) => o.status("error", json!({ "detail": format!("WhatsApp temporarily banned this number: {b:?}") })),
+ Event::StreamReplaced(_) => o.status("disconnected", json!({ "detail": "another WhatsApp Web session took over this link" })),
+ Event::ClientOutdated(_) => o.status("error", json!({ "detail": "WhatsApp says this client is outdated: update the plugin" })),
+ _ => o.status("disconnected", json!({ "detail": "connection lost, reconnecting" })),
+ }
+ }
+ })
+ .on_message(move |ctx| {
+ let st = st_msg.clone();
+ let o = o5.clone();
+ async move { on_message(st, o, ctx).await }
+ });
+ if let Some(phone) = phone {
+ builder = builder.with_pair_code(PairCodeOptions { phone_number: phone, ..Default::default() });
+ }
+ let bot = builder.build().await?;
+ let handle = bot.spawn();
+ *st.client.lock().await = None;
+ *st.bot.lock().await = Some(handle);
+ Ok(())
+}
+
+async fn on_message(st: Arc<State>, out: Out, ctx: MessageContext) {
+ let src = &ctx.info.source;
+ if src.is_from_me {
+ return;
+ }
+ let chat = src.chat.to_string();
+ let sender_phone = phone_of(&src.sender).or_else(|| src.sender_alt.as_ref().and_then(phone_of));
+ let mut text = ctx.message.text_content().map(str::to_string).unwrap_or_default();
+ let mut attachments = Vec::new();
+
+ let base = ctx.message.get_base_message();
+ let dir = st.data_dir.join("media");
+ let id = ctx.info.id.to_string();
+ let safe_id: String = id.chars().filter(|c| c.is_ascii_alphanumeric()).take(40).collect();
+
+ if let Some(m) = base.image_message.as_option() {
+ if text.is_empty() {
+ text = m.caption.clone().unwrap_or_default();
+ }
+ let r = ctx.client.download(m, DownloadLimits::default()).await.map_err(|e| e.to_string());
+ save(&dir, "image", &safe_id, "jpg", r, &mut attachments).await;
+ }
+ if let Some(m) = base.document_message.as_option() {
+ if text.is_empty() {
+ text = m.caption.clone().unwrap_or_default();
+ }
+ let ext = m.file_name.as_deref().and_then(|n| n.rsplit('.').next()).filter(|e| e.len() <= 8 && e.chars().all(|c| c.is_ascii_alphanumeric())).unwrap_or("bin").to_string();
+ let r = ctx.client.download(m, DownloadLimits::default()).await.map_err(|e| e.to_string());
+ save(&dir, "document", &safe_id, &ext, r, &mut attachments).await;
+ }
+ if let Some(m) = base.audio_message.as_option() {
+ let kind = if m.ptt == Some(true) { "voice" } else { "audio" };
+ let r = ctx.client.download(m, DownloadLimits::default()).await.map_err(|e| e.to_string());
+ save(&dir, kind, &safe_id, "ogg", r, &mut attachments).await;
+ }
+
+ if text.is_empty() && attachments.is_empty() {
+ return;
+ }
+ let _ = ctx.client.mark_as_read(&src.chat, if src.is_group { Some(&src.sender) } else { None }, &[id.as_str()]).await;
+ out.notify("mercury/channel/message", json!({
+ "id": id,
+ "chatId": chat,
+ "senderId": src.sender.to_string(),
+ "senderPhone": sender_phone,
+ "senderName": ctx.info.push_name.to_string(),
+ "isGroup": src.is_group,
+ "fromMe": false,
+ "text": text,
+ "attachments": attachments,
+ "timestamp": ctx.info.timestamp.timestamp_millis(),
+ }));
+}
+
+async fn save(dir: &Path, kind: &str, id: &str, ext: &str, bytes: Result<Vec<u8>, String>, attachments: &mut Vec<Value>) {
+ match bytes {
+ Ok(b) if b.len() <= MAX_DOWNLOAD_BYTES => {
+ let path = dir.join(format!("{kind}-{id}.{ext}"));
+ match tokio::fs::write(&path, &b).await {
+ Ok(()) => attachments.push(json!({ "kind": kind, "path": path.to_string_lossy() })),
+ Err(e) => log(format!("couldn't save attachment: {e}")),
+ }
+ }
+ Ok(_) => log("skipped an attachment over 50 MB"),
+ Err(e) => log(format!("attachment download failed: {e}")),
+ }
+}
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.json
new file mode 100644
index 00000000..9652f0e1
--- /dev/null
+++ b/plugins/whatsapp/mercury-plugin.template.json
@@ -0,0 +1,33 @@
+{
+ "manifestVersion": 1,
+ "id": "whatsapp",
+ "name": "WhatsApp",
+ "version": "0.1.0",
+ "description": "Chat with Mercury on WhatsApp from your phone. Mercury runs on a spare number as a linked device (unofficial protocol).",
+ "kind": "out-of-process",
+ "author": "Cosmic Stack",
+ "homepage": "https://github.com/cosmicstack-labs/mercury-agent/tree/main/plugins/whatsapp",
+ "license": "MIT",
+ "engines": { "mercury": ">=1.3.9 <2.0.0", "pluginApi": "^1.1.0" },
+ "server": {
+ "command": "bin/mercury-wa",
+ "args": [],
+ "platforms": { "win32-x64": { "command": "bin/mercury-wa.exe", "args": [] } }
+ },
+ "contributes": {
+ "tools": [],
+ "channel": { "type": "whatsapp" }
+ },
+ "permissions": {
+ "network": ["web.whatsapp.com", "*.whatsapp.net", "*.whatsapp.com"],
+ "secrets": []
+ },
+ "settings": {
+ "version": 1,
+ "fields": {
+ "owner": { "type": "string", "description": "Your own WhatsApp number (with country code). Only this number can talk to Mercury.", "default": "" },
+ "members": { "type": "string", "description": "Other numbers allowed to chat with Mercury, comma separated (they can't run admin commands).", "default": "" },
+ "allowGroups": { "type": "boolean", "description": "Answer in WhatsApp groups (owner and members only).", "default": false }
+ }
+ }
+}
diff --git a/plugins/whatsapp/package.mjs b/plugins/whatsapp/package.mjs
new file mode 100644
index 00000000..46b09b70
--- /dev/null
+++ b/plugins/whatsapp/package.mjs
@@ -0,0 +1,39 @@
+// Build a per-platform plugin package from a compiled companion binary:
+// node plugins/whatsapp/package.mjs <binary> <platform-key> <out-dir>
+// Writes <out-dir>/mercury-plugin-<platform-key>.tgz containing the
+// manifest (with this platform and the binary's SHA-256 pinned), the
+// binary under bin/, and the README.
+import { createHash } from 'node:crypto';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const [binary, platform, outDir] = process.argv.slice(2);
+if (!binary || !platform || !outDir) {
+ console.error('usage: node package.mjs <binary> <platform-key> <out-dir>');
+ process.exit(2);
+}
+const here = dirname(fileURLToPath(import.meta.url));
+const manifest = JSON.parse(readFileSync(join(here, 'mercury-plugin.template.json'), 'utf8'));
+const exe = platform.startsWith('win32') ? 'mercury-wa.exe' : 'mercury-wa';
+const rel = `bin/${exe}`;
+
+const stage = mkdtempSync(join(tmpdir(), 'mercury-wa-pkg-'));
+mkdirSync(join(stage, 'bin'));
+copyFileSync(binary, join(stage, rel));
+chmodSync(join(stage, rel), 0o755);
+copyFileSync(join(here, 'README.md'), join(stage, 'README.md'));
+
+manifest.platforms = [platform];
+manifest.checksums = { [rel]: createHash('sha256').update(readFileSync(join(stage, rel))).digest('hex') };
+writeFileSync(join(stage, 'mercury-plugin.json'), `${JSON.stringify(manifest, null, 2)}\n`);
+
+mkdirSync(outDir, { recursive: true });
+const out = resolve(outDir, `mercury-plugin-${platform}.tgz`);
+execFileSync('tar', ['-czf', out, '-C', stage, 'mercury-plugin.json', 'bin', 'README.md']);
+const sha = createHash('sha256').update(readFileSync(out)).digest('hex');
+writeFileSync(`${out}.sha256`, `${sha} mercury-plugin-${platform}.tgz\n`);
+rmSync(stage, { recursive: true, force: true });
+console.log(`${out}\n${sha}`);