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): phase 2, voice calls with OpenAI Realtime (#202)

Salman Qureshi2b043a7614fe
diff --git a/plugins/whatsapp/README.md b/plugins/whatsapp/README.md
index d72c324d..ac448abb 100644
--- a/plugins/whatsapp/README.md
+++ b/plugins/whatsapp/README.md
@@ -49,7 +49,27 @@ account is needed.
- 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).
+## Voice calls
+
+Call the spare number from your own number and talk to Mercury. Mercury can
+also call you when something matters (the `call_owner` tool).
+
+- **Key:** calls use the OpenAI provider you already set up in Mercury
+ (dashboard → Providers, or `mercury doctor`). Nothing extra to configure.
+ Without one, text still works, and Mercury tells you once that calls need
+ an OpenAI provider.
+- **Who can call:** only the owner. Other callers are declined.
+- **Mid-call actions:** Mercury can look things up and act during a call,
+ using its memory, tools and files.
+- **Approvals:** nothing that needs your approval runs during a call
+ (nobody can tap Allow), and Mercury offers to do it by message instead.
+- **After the call:** you get a summary with the transcript on WhatsApp.
+- **Limits:** Mercury calls you at most `maxCallsPerHour` times an hour
+ (default 4), and calls are capped at `maxCallMinutes` (default 15).
+- **Settings:** `voice` (default `marin`), `voiceModel` (default
+ `gpt-realtime`), and `answerCalls` (on by default).
+- **Privacy:** call audio goes only to OpenAI, under OpenAI's API data
+ policy.
## Unlink
diff --git a/plugins/whatsapp/companion/Cargo.toml b/plugins/whatsapp/companion/Cargo.toml
index 69057f9d..0ecc3273 100644
--- a/plugins/whatsapp/companion/Cargo.toml
+++ b/plugins/whatsapp/companion/Cargo.toml
@@ -9,7 +9,12 @@ 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" }
+# "voip": 1:1 calls (MLOW + Opus via libopus, which needs cmake to build).
+whatsapp-rust = { git = "https://github.com/oxidezap/whatsapp-rust", rev = "c373266fd2c66ae39752171cff5e0dd798a90205", features = ["voip"] }
+# Voice: OpenAI Realtime over the same WebSocket/TLS stack whatsapp-rust uses (rustls + ring).
+tokio-websockets = { version = "0.13.3", features = ["client", "rustls-webpki-roots", "rand", "ring"] }
+http = "1"
+base64 = "0.22"
tokio = { version = "1.47", features = ["full"] }
serde_json = "1"
anyhow = "1"
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rs
index 34a3fbb1..a6eafd6c 100644
--- a/plugins/whatsapp/companion/src/main.rs
+++ b/plugins/whatsapp/companion/src/main.rs
@@ -10,13 +10,17 @@
//!
//! stdout is the protocol channel: logs go to stderr only.
+mod voice;
+
+use std::collections::HashMap;
use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicU64, Ordering};
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 tokio::sync::{Mutex, mpsc, oneshot};
use whatsapp_rust::download::{DownloadLimits, MediaType};
use whatsapp_rust::media::{self, DocumentOptions, ImageOptions};
use whatsapp_rust::pair_code::PairCodeOptions;
@@ -25,19 +29,46 @@ use whatsapp_rust::upload::UploadOptions;
const MAX_DOWNLOAD_BYTES: usize = 50 * 1024 * 1024;
-/// Writes protocol lines to stdout, in order, from any task.
+type Pending = Arc<std::sync::Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>>;
+
+/// Writes protocol lines to stdout, in order, from any task, and keeps
+/// track of our own requests to Mercury (call decisions, ask_mercury).
#[derive(Clone)]
-struct Out(mpsc::UnboundedSender<Value>);
+pub struct Out {
+ tx: mpsc::UnboundedSender<Value>,
+ pending: Pending,
+ next_id: Arc<AtomicU64>,
+}
impl Out {
- fn notify(&self, method: &str, params: Value) {
- let _ = self.0.send(json!({ "jsonrpc": "2.0", "method": method, "params": params }));
+ pub fn notify(&self, method: &str, params: Value) {
+ let _ = self.tx.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 }));
+ let _ = self.tx.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() } }));
+ let _ = self.tx.send(json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message.into() } }));
+ }
+ /// A request to Mercury. Ids are strings ("wa-N") so they never collide with Mercury's numeric ids.
+ pub async fn request(&self, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {
+ let n = self.next_id.fetch_add(1, Ordering::Relaxed);
+ let (tx, rx) = oneshot::channel();
+ self.pending.lock().unwrap().insert(n, tx);
+ let _ = self.tx.send(json!({ "jsonrpc": "2.0", "id": format!("wa-{n}"), "method": method, "params": params }));
+ let r = tokio::time::timeout(timeout, rx).await;
+ self.pending.lock().unwrap().remove(&n);
+ match r {
+ Ok(Ok(v)) => v,
+ Ok(Err(_)) => Err("Mercury went away".into()),
+ Err(_) => Err(format!("{method} timed out")),
+ }
+ }
+ fn resolve(&self, id: &str, result: Result<Value, String>) {
+ let Some(n) = id.strip_prefix("wa-").and_then(|n| n.parse::<u64>().ok()) else { return };
+ if let Some(tx) = self.pending.lock().unwrap().remove(&n) {
+ let _ = tx.send(result);
+ }
}
fn status(&self, state: &str, extra: Value) {
let mut params = json!({ "state": state });
@@ -50,14 +81,18 @@ impl Out {
}
}
-struct State {
+pub struct State {
data_dir: PathBuf,
- out: Out,
+ pub out: Out,
bot: Mutex<Option<BotHandle>>,
- client: Mutex<Option<Arc<Client>>>,
+ pub client: Mutex<Option<Arc<Client>>>,
+ /// When call_owner last rang the owner (rate limit).
+ pub recent_calls: Mutex<Vec<std::time::Instant>>,
+ /// Outcomes of outgoing calls being placed.
+ pub call_watchers: voice::CallWatchers,
}
-fn log(msg: impl AsRef<str>) {
+pub fn log(msg: impl AsRef<str>) {
eprintln!("[mercury-wa] {}", msg.as_ref());
}
@@ -66,7 +101,7 @@ fn db_path(dir: &Path) -> PathBuf {
}
/// The user part of a phone-number JID ("[email protected]" → "15551234567").
-fn phone_of(jid: &Jid) -> Option<String> {
+pub fn phone_of(jid: &Jid) -> Option<String> {
let s = jid.to_string();
let (user, server) = s.split_once('@')?;
if server != "s.whatsapp.net" {
@@ -92,8 +127,15 @@ async fn main() -> anyhow::Result<()> {
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 out = Out { tx, pending: Arc::new(std::sync::Mutex::new(HashMap::new())), next_id: Arc::new(AtomicU64::new(1)) };
+ let state = Arc::new(State {
+ data_dir,
+ out: out.clone(),
+ bot: Mutex::new(None),
+ client: Mutex::new(None),
+ recent_calls: Mutex::new(Vec::new()),
+ call_watchers: Arc::new(Mutex::new(HashMap::new())),
+ });
let mut lines = BufReader::new(tokio::io::stdin()).lines();
while let Some(line) = lines.next_line().await? {
@@ -109,6 +151,17 @@ async fn main() -> anyhow::Result<()> {
}
async fn handle(st: Arc<State>, msg: Value) {
+ // A reply to one of our own requests.
+ if msg.get("method").is_none() {
+ if let Some(id) = msg.get("id").and_then(Value::as_str) {
+ let result = match msg.get("error") {
+ Some(e) => Err(e.get("message").and_then(Value::as_str).unwrap_or("error").to_string()),
+ None => Ok(msg.get("result").cloned().unwrap_or(Value::Null)),
+ };
+ st.out.resolve(id, result);
+ }
+ return;
+ }
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 {
@@ -133,7 +186,23 @@ async fn handle(st: Arc<State>, msg: Value) {
"serverInfo": { "name": "mercury-wa", "version": env!("CARGO_PKG_VERSION") },
})),
"ping" => Ok(json!({})),
- "tools/list" => Ok(json!({ "tools": [] })),
+ "tools/list" => Ok(json!({ "tools": [{
+ "name": "call_owner",
+ "description": "Ring the owner on WhatsApp and talk to them by voice. Only the owner can be called.",
+ "inputSchema": { "type": "object", "properties": { "reason": { "type": "string", "description": "Why you're calling, in one sentence" } }, "required": ["reason"] },
+ }] })),
+ "tools/call" => {
+ let name = params.get("name").and_then(Value::as_str).unwrap_or("");
+ let args = params.get("arguments").cloned().unwrap_or(json!({}));
+ if name != "call_owner" {
+ Err(format!("unknown tool {name}"))
+ } else {
+ Ok(match voice::call_owner(st.clone(), &args).await {
+ Ok(text) => json!({ "content": [{ "type": "text", "text": text }] }),
+ Err(e) => json!({ "content": [{ "type": "text", "text": e }], "isError": true }),
+ })
+ }
+ }
"mercury/channel/pair" => pair(st.clone(), &params).await,
"mercury/channel/unlink" => unlink(st.clone()).await,
"mercury/channel/send" => send_text(st.clone(), &params).await,
@@ -279,6 +348,7 @@ async fn start_bot(st: Arc<State>, phone: Option<String>) -> anyhow::Result<()>
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 st_call = st.clone();
let mut builder = Bot::builder()
.with_backend(store)
.on_qr_code(move |code, _ttl| {
@@ -312,6 +382,18 @@ async fn start_bot(st: Arc<State>, phone: Option<String>) -> anyhow::Result<()>
}
}
})
+ .on_event_for(&[EventKind::IncomingCall], move |ev, client| {
+ let st = st_call.clone();
+ async move {
+ if let Event::IncomingCall(call) = &*ev {
+ voice::route_call_event(&st.call_watchers, call).await;
+ if matches!(call.action, whatsapp_rust::types::call::CallAction::Offer { .. }) {
+ let call = call.clone();
+ tokio::spawn(async move { voice::on_offer(st, client, call).await });
+ }
+ }
+ }
+ })
.on_message(move |ctx| {
let st = st_msg.clone();
let o = o5.clone();
diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rs
new file mode 100644
index 00000000..3bb6ff82
--- /dev/null
+++ b/plugins/whatsapp/companion/src/voice.rs
@@ -0,0 +1,431 @@
+//! Voice calls: WhatsApp call audio ⇄ OpenAI Realtime.
+//!
+//! Audio never leaves this process except to the voice provider. Mercury is
+//! asked two things over the plugin connection: whether to answer a call
+//! (only the owner, decided by Mercury) and, mid-call, `ask_mercury`
+//! questions, which run as a normal Mercury turn whose answer is spoken back.
+//!
+//! WhatsApp call audio (PCM path): 16 kHz mono i16, 960-sample (60 ms) frames.
+//! OpenAI Realtime: 24 kHz mono i16, base64, any chunk size.
+
+use std::collections::{HashMap, VecDeque};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use base64::Engine as _;
+use base64::engine::general_purpose::STANDARD as B64;
+use serde_json::{Value, json};
+use tokio::sync::{Mutex, mpsc};
+use tokio_websockets::{ClientBuilder, Message};
+use whatsapp_rust::async_channel;
+use whatsapp_rust::futures::{SinkExt, StreamExt};
+use whatsapp_rust::prelude::*;
+use whatsapp_rust::types::call::{CallAction, IncomingCall};
+use whatsapp_rust::voip::CallHandle;
+
+use crate::{Out, State, log, phone_of};
+
+const WA_RATE: u32 = 16_000;
+const AI_RATE: u32 = 24_000;
+const FRAME: usize = 960;
+const RING_TIMEOUT: Duration = Duration::from_secs(45);
+const ASK_TIMEOUT: Duration = Duration::from_secs(100);
+
+/// Outcomes of outgoing calls, keyed by call id, fed from the client event bus.
+pub type CallWatchers = Arc<Mutex<HashMap<String, mpsc::UnboundedSender<&'static str>>>>;
+
+pub fn settings() -> Value {
+ std::env::var("MERCURY_PLUGIN_SETTINGS").ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or(json!({}))
+}
+
+fn setting_str(key: &str, default: &str) -> String {
+ settings().get(key).and_then(Value::as_str).filter(|s| !s.is_empty()).unwrap_or(default).to_string()
+}
+
+pub fn voice_ready() -> bool {
+ std::env::var("MERCURY_PROVIDER_OPENAI_API_KEY").map(|k| !k.is_empty()).unwrap_or(false)
+}
+
+fn realtime_url() -> String {
+ let base = std::env::var("MERCURY_PROVIDER_OPENAI_BASE_URL").ok().filter(|s| !s.is_empty()).unwrap_or_else(|| "https://api.openai.com/v1".into());
+ let base = base.trim_end_matches('/');
+ let ws = if let Some(rest) = base.strip_prefix("https://") { format!("wss://{rest}") } else if let Some(rest) = base.strip_prefix("http://") { format!("ws://{rest}") } else { base.to_string() };
+ format!("{ws}/realtime?model={}", setting_str("voiceModel", "gpt-realtime"))
+}
+
+/// Linear resampling of mono i16 PCM.
+pub fn resample(input: &[i16], from: u32, to: u32) -> Vec<i16> {
+ if input.is_empty() || from == to {
+ return input.to_vec();
+ }
+ let out_len = ((input.len() as u64 * to as u64) / from as u64).max(1) as usize;
+ let step = from as f64 / to as f64;
+ (0..out_len)
+ .map(|i| {
+ let pos = i as f64 * step;
+ let idx = pos as usize;
+ let frac = pos - idx as f64;
+ let a = input[idx.min(input.len() - 1)] as f64;
+ let b = input[(idx + 1).min(input.len() - 1)] as f64;
+ (a + (b - a) * frac).round().clamp(i16::MIN as f64, i16::MAX as f64) as i16
+ })
+ .collect()
+}
+
+fn pcm_to_b64(samples: &[i16]) -> String {
+ let mut bytes = Vec::with_capacity(samples.len() * 2);
+ for s in samples {
+ bytes.extend_from_slice(&s.to_le_bytes());
+ }
+ B64.encode(bytes)
+}
+
+fn b64_to_pcm(data: &str) -> Vec<i16> {
+ let bytes = B64.decode(data).unwrap_or_default();
+ bytes.chunks_exact(2).map(|c| i16::from_le_bytes([c[0], c[1]])).collect()
+}
+
+/// Feed call outcomes for outgoing calls to whoever placed them.
+pub async fn route_call_event(watchers: &CallWatchers, call: &IncomingCall) {
+ let (id, outcome) = match &call.action {
+ CallAction::Accept { call_id, .. } => (call_id.clone(), "answered"),
+ CallAction::Reject { call_id, reason, .. } => (call_id.clone(), if reason.is_none() { "declined" } else { "busy" }),
+ CallAction::Terminate { call_id, .. } => (call_id.clone(), "ended"),
+ _ => return,
+ };
+ if let Some(tx) = watchers.lock().await.get(&id) {
+ let _ = tx.send(outcome);
+ }
+}
+
+/// An incoming offer: ask Mercury whether to answer (owner only), then bridge it.
+pub async fn on_offer(st: Arc<State>, client: Arc<Client>, call: Box<IncomingCall>) {
+ let CallAction::Offer { call_id, caller_pn, is_video, group_jid, .. } = &call.action else { return };
+ let from = call.from.to_string();
+ let from_phone = caller_pn.as_ref().and_then(phone_of).or_else(|| phone_of(&call.from));
+ let call_id = call_id.clone();
+
+ if group_jid.is_some() || settings().get("answerCalls").and_then(Value::as_bool) == Some(false) {
+ let _ = client.voip().reject(&call).await;
+ return;
+ }
+ let decision = st
+ .out
+ .request("mercury/call/incoming", json!({ "callId": call_id, "from": from, "fromPhone": from_phone, "video": is_video, "voiceReady": voice_ready() }), Duration::from_secs(8))
+ .await
+ .unwrap_or_else(|e| json!({ "accept": false, "reason": e }));
+ if decision.get("accept").and_then(Value::as_bool) != Some(true) {
+ let _ = client.voip().reject(&call).await;
+ return;
+ }
+ let instructions = decision.get("instructions").and_then(Value::as_str).unwrap_or("").to_string();
+
+ let (mic_tx, mic_rx) = async_channel::bounded::<Vec<i16>>(3);
+ let (spk_tx, spk_rx) = async_channel::bounded::<Vec<i16>>(64);
+ let handle = match client.voip().accept(&call).audio(mic_rx, spk_tx).start().await {
+ Ok(h) => h,
+ Err(e) => {
+ log(format!("accept failed: {e}"));
+ st.out.notify("mercury/call/ended", json!({ "callId": call_id, "direction": "incoming", "outcome": "failed", "detail": e.to_string(), "durationSec": 0, "transcript": [] }));
+ return;
+ }
+ };
+ let opener = "The owner just called you. Greet them briefly by name if you know it, and ask how you can help.".to_string();
+ run_session(st, handle, mic_tx, spk_rx, call_id, "incoming", instructions, opener).await;
+}
+
+/// The `call_owner` tool: ring the owner and, if they answer, talk.
+pub async fn call_owner(st: Arc<State>, args: &Value) -> Result<String, String> {
+ let reason = args.get("reason").and_then(Value::as_str).unwrap_or("").trim().to_string();
+ if reason.is_empty() {
+ return Err("reason is required".into());
+ }
+ if !voice_ready() {
+ return Err("Voice calls need an OpenAI provider. Add your OpenAI key once in Mercury's dashboard (Providers) or with `mercury doctor`.".into());
+ }
+ let owner: String = setting_str("owner", "").chars().filter(char::is_ascii_digit).collect();
+ if owner.len() < 6 {
+ return Err("No owner number is set. Run: mercury plugins set whatsapp owner +<number>".into());
+ }
+ // Rate limit: a looping task must never spam the owner with calls.
+ let max_per_hour = settings().get("maxCallsPerHour").and_then(Value::as_f64).unwrap_or(4.0).max(0.0) as usize;
+ {
+ let mut recent = st.recent_calls.lock().await;
+ let hour_ago = Instant::now() - Duration::from_secs(3600);
+ recent.retain(|t| *t > hour_ago);
+ if recent.len() >= max_per_hour {
+ return Err(format!("Not calling: already called the owner {} times in the last hour (limit {max_per_hour}). Send a message instead.", recent.len()));
+ }
+ recent.push(Instant::now());
+ }
+ let client = st.client.lock().await.clone().ok_or("WhatsApp is not linked.")?;
+ let jid: Jid = format!("{owner}@s.whatsapp.net").parse().map_err(|e| format!("bad owner number: {e}"))?;
+
+ let (mic_tx, mic_rx) = async_channel::bounded::<Vec<i16>>(3);
+ let (spk_tx, spk_rx) = async_channel::bounded::<Vec<i16>>(64);
+ let handle = client.voip().call(&jid).audio(mic_rx, spk_tx).start().await.map_err(|e| format!("couldn't place the call: {e}"))?;
+ let call_id = handle.call_id().to_string();
+
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ st.call_watchers.lock().await.insert(call_id.clone(), tx);
+ let outcome = tokio::time::timeout(RING_TIMEOUT, async {
+ loop {
+ match rx.recv().await {
+ Some("answered") => return "answered",
+ Some("busy") => continue, // one of their devices can't take it; others keep ringing
+ Some(other) => return other,
+ None => return "failed",
+ }
+ }
+ })
+ .await
+ .unwrap_or("no_answer");
+ st.call_watchers.lock().await.remove(&call_id);
+
+ if outcome != "answered" {
+ let _ = handle.terminate().await;
+ let outcome = if outcome == "ended" { "no_answer" } else { outcome };
+ st.out.notify("mercury/call/ended", json!({ "callId": call_id, "direction": "outgoing", "outcome": outcome, "reason": reason, "durationSec": 0, "transcript": [] }));
+ return Ok(format!("{outcome}: the owner did not pick up. Send them a message instead."));
+ }
+ let briefing = st.out.request("mercury/call/briefing", json!({ "callId": call_id }), Duration::from_secs(5)).await.unwrap_or(json!({}));
+ let instructions = briefing.get("instructions").and_then(Value::as_str).unwrap_or("").to_string();
+ let opener = format!("You called the owner and they answered. Why you called: {reason}. Greet them, explain why you called in one or two sentences, and help with whatever they need.");
+ let st2 = st.clone();
+ tokio::spawn(async move { run_session(st2, handle, mic_tx, spk_rx, call_id, "outgoing", instructions, opener).await });
+ Ok("answered: the owner picked up and the call is in progress. A summary will be sent when it ends.".into())
+}
+
+fn session_config(instructions: &str) -> Value {
+ let base = "You are Mercury, the user's AI assistant, talking on a WhatsApp voice call. \
+ Speak naturally and briefly: one or two sentences at a time, no lists, no markdown, no URLs read aloud. \
+ For anything that needs Mercury's memory, files, tools, the web, or doing something, call ask_mercury with a clear question, \
+ and say a short filler like 'one moment' first. Nothing that needs the user's approval can be done during a call; \
+ if ask_mercury says so, offer to do it by message instead. When the user says goodbye or is done, say goodbye and call end_call.";
+ json!({
+ "type": "session.update",
+ "session": {
+ "type": "realtime",
+ "instructions": if instructions.is_empty() { base.to_string() } else { format!("{base}\n\n{instructions}") },
+ "audio": {
+ "input": {
+ "format": { "type": "audio/pcm", "rate": AI_RATE },
+ "turn_detection": { "type": "server_vad", "interrupt_response": true, "create_response": true },
+ "transcription": { "model": "gpt-4o-mini-transcribe" },
+ },
+ "output": { "format": { "type": "audio/pcm", "rate": AI_RATE }, "voice": setting_str("voice", "marin") },
+ },
+ "tools": [
+ {
+ "type": "function",
+ "name": "ask_mercury",
+ "description": "Ask Mercury (with its memory, tools and files) a question or to do something. Returns the answer to speak back.",
+ "parameters": { "type": "object", "properties": { "question": { "type": "string" } }, "required": ["question"] },
+ },
+ { "type": "function", "name": "end_call", "description": "Hang up after saying goodbye.", "parameters": { "type": "object", "properties": {} } },
+ ],
+ },
+ })
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn run_session(
+ st: Arc<State>,
+ handle: CallHandle,
+ mic_tx: async_channel::Sender<Vec<i16>>,
+ spk_rx: async_channel::Receiver<Vec<i16>>,
+ call_id: String,
+ direction: &'static str,
+ instructions: String,
+ opener: String,
+) {
+ let started = Instant::now();
+ let transcript: Arc<Mutex<Vec<Value>>> = Arc::new(Mutex::new(Vec::new()));
+ let outcome = match bridge(&st, &handle, mic_tx, spk_rx, &call_id, &instructions, &opener, transcript.clone()).await {
+ Ok(()) => "completed".to_string(),
+ Err(e) => {
+ log(format!("voice session ended with an error: {e}"));
+ // Tell the caller something went wrong rather than leaving silence.
+ let _ = handle.terminate().await;
+ format!("failed: {e}")
+ }
+ };
+ let _ = tokio::time::timeout(Duration::from_secs(5), handle.terminate()).await;
+ let t = transcript.lock().await.clone();
+ st.out.notify("mercury/call/ended", json!({
+ "callId": call_id,
+ "direction": direction,
+ "outcome": outcome,
+ "durationSec": started.elapsed().as_secs(),
+ "transcript": t,
+ }));
+}
+
+#[allow(clippy::too_many_arguments)]
+async fn bridge(
+ st: &Arc<State>,
+ handle: &CallHandle,
+ mic_tx: async_channel::Sender<Vec<i16>>,
+ spk_rx: async_channel::Receiver<Vec<i16>>,
+ call_id: &str,
+ instructions: &str,
+ opener: &str,
+ transcript: Arc<Mutex<Vec<Value>>>,
+) -> Result<(), String> {
+ let key = std::env::var("MERCURY_PROVIDER_OPENAI_API_KEY").map_err(|_| "no OpenAI key".to_string())?;
+ let uri: http::Uri = realtime_url().parse().map_err(|e| format!("bad realtime URL: {e}"))?;
+ let auth = http::HeaderValue::from_str(&format!("Bearer {key}")).map_err(|e| e.to_string())?;
+ let (ws, _) = ClientBuilder::from_uri(uri)
+ .add_header(http::header::AUTHORIZATION, auth)
+ .map_err(|e| e.to_string())?
+ .connect()
+ .await
+ .map_err(|e| format!("couldn't reach the voice model: {e}"))?;
+ let (mut ws_tx, mut ws_rx) = ws.split();
+
+ let (send_q, mut send_rx) = mpsc::unbounded_channel::<Value>();
+ // Single writer for the model socket.
+ let writer = tokio::spawn(async move {
+ while let Some(v) = send_rx.recv().await {
+ if ws_tx.send(Message::text(v.to_string())).await.is_err() {
+ break;
+ }
+ }
+ let _ = ws_tx.close().await;
+ });
+
+ let _ = send_q.send(session_config(instructions));
+ let _ = send_q.send(json!({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": format!("[Call context, not spoken by the user] {opener}") }] } }));
+ let _ = send_q.send(json!({ "type": "response.create" }));
+
+ // Caller → model.
+ let up_q = send_q.clone();
+ let uplink = tokio::spawn(async move {
+ while let Ok(frame) = spk_rx.recv().await {
+ let up = resample(&frame, WA_RATE, AI_RATE);
+ if up_q.send(json!({ "type": "input_audio_buffer.append", "audio": pcm_to_b64(&up) })).is_err() {
+ break;
+ }
+ }
+ });
+
+ // Model → caller, paced at one 60 ms frame per tick.
+ let playout: Arc<std::sync::Mutex<VecDeque<i16>>> = Arc::new(std::sync::Mutex::new(VecDeque::new()));
+ let play = playout.clone();
+ let pacer = tokio::spawn(async move {
+ let mut tick = tokio::time::interval(Duration::from_millis(60));
+ tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
+ loop {
+ tick.tick().await;
+ let frame: Vec<i16> = {
+ let mut q = play.lock().unwrap();
+ let n = q.len().min(FRAME);
+ let mut f: Vec<i16> = q.drain(..n).collect();
+ f.resize(FRAME, 0);
+ f
+ };
+ if mic_tx.send(frame).await.is_err() {
+ break;
+ }
+ }
+ });
+
+ let max_minutes = settings().get("maxCallMinutes").and_then(Value::as_f64).unwrap_or(15.0).clamp(1.0, 120.0);
+ let deadline = tokio::time::sleep(Duration::from_secs_f64(max_minutes * 60.0));
+ tokio::pin!(deadline);
+ let ended = handle.wait_ended();
+ tokio::pin!(ended);
+ let mut hang_up = false;
+
+ let result = loop {
+ tokio::select! {
+ _ = &mut ended => break Ok(()),
+ _ = &mut deadline => { hang_up = true; break Ok(()) }
+ msg = ws_rx.next() => {
+ let Some(Ok(msg)) = msg else { break Err("the voice model disconnected".to_string()) };
+ if msg.is_close() { break Err("the voice model closed the session".to_string()); }
+ let Some(text) = msg.as_text() else { continue };
+ let Ok(ev) = serde_json::from_str::<Value>(text) else { continue };
+ let kind = ev.get("type").and_then(Value::as_str).unwrap_or("");
+ match kind {
+ "response.output_audio.delta" | "response.audio.delta" => {
+ if let Some(d) = ev.get("delta").and_then(Value::as_str) {
+ let down = resample(&b64_to_pcm(d), AI_RATE, WA_RATE);
+ playout.lock().unwrap().extend(down);
+ }
+ }
+ // The caller started talking: stop speaking over them.
+ "input_audio_buffer.speech_started" => playout.lock().unwrap().clear(),
+ "conversation.item.input_audio_transcription.completed" => {
+ if let Some(t) = ev.get("transcript").and_then(Value::as_str) {
+ transcript.lock().await.push(json!({ "role": "owner", "text": t.trim() }));
+ }
+ }
+ "response.output_audio_transcript.done" | "response.audio_transcript.done" => {
+ if let Some(t) = ev.get("transcript").and_then(Value::as_str) {
+ transcript.lock().await.push(json!({ "role": "mercury", "text": t.trim() }));
+ }
+ }
+ "response.function_call_arguments.done" => {
+ let name = ev.get("name").and_then(Value::as_str).unwrap_or("").to_string();
+ let fc_id = ev.get("call_id").and_then(Value::as_str).unwrap_or("").to_string();
+ let args: Value = ev.get("arguments").and_then(Value::as_str).and_then(|a| serde_json::from_str(a).ok()).unwrap_or(json!({}));
+ if name == "end_call" {
+ // Let the goodbye finish playing.
+ for _ in 0..50 {
+ if playout.lock().unwrap().is_empty() { break; }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ hang_up = true;
+ break Ok(());
+ }
+ if name == "ask_mercury" {
+ let q = args.get("question").and_then(Value::as_str).unwrap_or("").to_string();
+ transcript.lock().await.push(json!({ "role": "ask_mercury", "text": q }));
+ let st2 = st.clone();
+ let tx2 = send_q.clone();
+ let call_id2 = call_id.to_string();
+ tokio::spawn(async move {
+ let answer = st2.out.request("mercury/call/ask", json!({ "callId": call_id2, "question": q }), ASK_TIMEOUT)
+ .await
+ .ok()
+ .and_then(|v| v.get("answer").and_then(Value::as_str).map(str::to_string))
+ .unwrap_or_else(|| "Mercury didn't answer in time. It will send the answer by message.".into());
+ let _ = tx2.send(json!({ "type": "conversation.item.create", "item": { "type": "function_call_output", "call_id": fc_id, "output": answer } }));
+ let _ = tx2.send(json!({ "type": "response.create" }));
+ });
+ }
+ }
+ "error" => log(format!("voice model error: {}", ev.get("error").map(|e| e.to_string()).unwrap_or_default())),
+ _ => {}
+ }
+ }
+ }
+ };
+
+ uplink.abort();
+ pacer.abort();
+ drop(send_q);
+ let _ = tokio::time::timeout(Duration::from_secs(2), writer).await;
+ if hang_up {
+ let _ = handle.terminate().await;
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resample_lengths() {
+ assert_eq!(resample(&[0i16; 960], WA_RATE, AI_RATE).len(), 1440);
+ assert_eq!(resample(&[0i16; 1440], AI_RATE, WA_RATE).len(), 960);
+ }
+
+ #[test]
+ fn pcm_round_trip() {
+ let s = vec![0i16, 1, -1, i16::MAX, i16::MIN];
+ assert_eq!(b64_to_pcm(&pcm_to_b64(&s)), s);
+ }
+}
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.json
index 9652f0e1..6ecc5be2 100644
--- a/plugins/whatsapp/mercury-plugin.template.json
+++ b/plugins/whatsapp/mercury-plugin.template.json
@@ -3,31 +3,105 @@
"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).",
+ "description": "Chat with Mercury on WhatsApp and talk to it by voice call. 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" },
+ "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": [] } }
+ "platforms": {
+ "win32-x64": {
+ "command": "bin/mercury-wa.exe",
+ "args": []
+ }
+ }
},
"contributes": {
- "tools": [],
- "channel": { "type": "whatsapp" }
+ "tools": [
+ {
+ "name": "call_owner",
+ "description": "Ring the owner on WhatsApp and talk to them by voice (only the owner can be called; rate-limited). Use for things that matter right now; send a message for everything else.",
+ "readOnly": false,
+ "timeoutMs": 120000
+ }
+ ],
+ "channel": {
+ "type": "whatsapp"
+ }
},
"permissions": {
- "network": ["web.whatsapp.com", "*.whatsapp.net", "*.whatsapp.com"],
- "secrets": []
+ "network": [
+ "web.whatsapp.com",
+ "*.whatsapp.net",
+ "*.whatsapp.com",
+ "api.openai.com"
+ ],
+ "secrets": [],
+ "providers": {
+ "openai": "Voice calls"
+ }
},
"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 }
+ "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
+ },
+ "answerCalls": {
+ "type": "boolean",
+ "description": "Answer voice calls from the owner.",
+ "default": true
+ },
+ "maxCallsPerHour": {
+ "type": "number",
+ "description": "Most times Mercury may call you in an hour.",
+ "default": 4
+ },
+ "maxCallMinutes": {
+ "type": "number",
+ "description": "Longest a call can last, in minutes.",
+ "default": 15
+ },
+ "voice": {
+ "type": "enum",
+ "description": "Mercury's voice on calls.",
+ "options": [
+ "marin",
+ "cedar",
+ "alloy",
+ "ash",
+ "ballad",
+ "coral",
+ "echo",
+ "sage",
+ "shimmer",
+ "verse"
+ ],
+ "default": "marin"
+ },
+ "voiceModel": {
+ "type": "string",
+ "description": "OpenAI realtime model for calls.",
+ "default": "gpt-realtime"
+ }
}
}
}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index df33117d..80a3d973 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -2128,6 +2128,10 @@ export class Agent {
if (channel instanceof TelegramChannel || channel instanceof SignalChannel || channel instanceof DiscordChannel || channel instanceof SlackChannel) {
channel.endTask(msg.channelId);
channel.resetStepCounter(msg.channelId);
+ } else if (channel && typeof (channel as { endTask?: unknown }).endTask === 'function') {
+ // Any other channel that wants to know a turn finished (plugin channels: a
+ // voice call waits for the turn's answer).
+ try { (channel as unknown as { endTask: (id: string) => void }).endTask(msg.channelId); } catch { /* best effort */ }
}
}
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index dc81780c..1c3d05e0 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -19,9 +19,19 @@
* mercury/channel/typing { chatId, on }
* mercury/channel/pair { method: 'qr' | 'code', phone? }
* mercury/channel/unlink {}
+ * Voice calls (plugin → Mercury)
+ * mercury/call/incoming request { callId, from, fromPhone?, voiceReady } → { accept, instructions? }
+ * mercury/call/briefing request { callId } → { instructions }
+ * mercury/call/ask request { callId, question } → { answer } (runs a Mercury turn)
+ * mercury/call/ended notification { callId, direction, outcome, durationSec, transcript, reason? }
+ *
+ * During a call nobody can approve anything: approvals asked on a call are
+ * refused (fail-closed), and the model is told to offer doing it by message.
*/
import { basename } from 'node:path';
-import { existsSync, statSync } from 'node:fs';
+import { existsSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { getMercuryHome } from '../utils/config.js';
import { BaseChannel, type Channel } from '../channels/base.js';
import type { ChannelMessage, ChannelType } from '../types/channel.js';
import { logger } from '../utils/logger.js';
@@ -127,6 +137,10 @@ export class PluginChannel extends BaseChannel {
private pending = new Map<string, { resolve: (v: string) => void; timer: ReturnType<typeof setTimeout> }>();
private seen = new Set<string>();
private statusListeners = new Set<(s: ChannelStatus) => void>();
+ /** In-flight `ask_mercury` turns, by call target (`call:<callId>`). */
+ private callAsks = new Map<string, { chunks: string[]; resolve: (answer: string) => void; timer: ReturnType<typeof setTimeout> }>();
+ /** Call targets whose turn outlived the call question: later output goes to the owner's chat. */
+ private overflow = new Set<string>();
constructor(
private readonly manifest: PluginManifest,
@@ -178,6 +192,98 @@ export class PluginChannel extends BaseChannel {
handleNotification(method: string, params: unknown): void {
if (method === 'mercury/channel/status') this.onStatusNotification(params);
else if (method === 'mercury/channel/message') this.onMessageNotification(params as IncomingParams);
+ else if (method === 'mercury/call/ended') this.onCallEnded(params);
+ }
+
+ async handleRequest(method: string, params: unknown): Promise<unknown> {
+ const p = (params ?? {}) as Record<string, unknown>;
+ switch (method) {
+ case 'mercury/call/incoming': {
+ const from = typeof p.fromPhone === 'string' && p.fromPhone ? p.fromPhone : String(p.from ?? '');
+ if (this.roleOf(from) !== 'admin') return { accept: false, reason: 'only the owner can call Mercury' };
+ if (p.voiceReady !== true) {
+ void this.send('📞 I couldn\'t answer your call: voice calls need an OpenAI provider. Add your OpenAI key once in the dashboard (Providers) or with `mercury doctor`, and calls will work.').catch(() => {});
+ return { accept: false, reason: 'no voice provider' };
+ }
+ return { accept: true, instructions: voiceBriefing() };
+ }
+ case 'mercury/call/briefing':
+ return { instructions: voiceBriefing() };
+ case 'mercury/call/ask': {
+ const callId = typeof p.callId === 'string' ? p.callId.replace(/[^\w.-]/g, '').slice(0, 80) : '';
+ const question = typeof p.question === 'string' ? p.question.trim().slice(0, 4000) : '';
+ if (!callId || !question) throw new Error('callId and question are required');
+ return { answer: await this.askDuringCall(callId, question) };
+ }
+ default:
+ throw new Error(`Mercury does not support ${method}`);
+ }
+ }
+
+ /** Run a Mercury turn for a question asked on a call; resolves with its answer. */
+ private askDuringCall(callId: string, question: string): Promise<string> {
+ const target = `call:${callId}`;
+ const owner = this.defaultTarget();
+ if (!owner) return Promise.resolve('No owner number is set, so Mercury can\'t act on this call.');
+ return new Promise((resolve) => {
+ const previous = this.callAsks.get(target);
+ if (previous) {
+ clearTimeout(previous.timer);
+ previous.resolve('(superseded by a newer question)');
+ }
+ const timer = setTimeout(() => {
+ this.callAsks.delete(target);
+ this.overflow.add(target);
+ resolve('Mercury is still working on that. It will send the answer to WhatsApp when it\'s done.');
+ }, 90_000);
+ this.callAsks.set(target, { chunks: [], resolve, timer });
+ this.emit({
+ id: `call-${callId}-${Date.now()}`,
+ channelId: `${this.type}:${target}`,
+ channelType: this.type,
+ senderId: digits(owner),
+ senderRole: 'admin',
+ content: `[Voice call — the owner asked this out loud. Answer in one to three short spoken sentences: no markdown, lists, links or code. Anything that needs approval can't be done during a call; say so and offer to do it by message.]\n${question}`,
+ timestamp: Date.now(),
+ metadata: { pluginId: this.manifest.id, voiceCall: true, callId },
+ });
+ });
+ }
+
+ /** The agent finished a turn (called by the agent for every channel that has endTask). */
+ endTask(channelId: string): void {
+ const target = channelId.startsWith(`${this.type}:`) ? channelId.slice(this.type.length + 1) : channelId;
+ const ask = this.callAsks.get(target);
+ if (ask) {
+ clearTimeout(ask.timer);
+ this.callAsks.delete(target);
+ const answer = ask.chunks.filter((c) => !/^(☿|⚙|⏳|\s*\[)/.test(c.trim())).pop() ?? ask.chunks.pop() ?? '';
+ ask.resolve(answer.trim() || 'Done.');
+ }
+ this.overflow.delete(target);
+ }
+
+ private onCallEnded(params: unknown): void {
+ const p = (params ?? {}) as Record<string, unknown>;
+ const secs = typeof p.durationSec === 'number' ? Math.round(p.durationSec) : 0;
+ const dur = secs >= 60 ? `${Math.floor(secs / 60)}m ${secs % 60}s` : `${secs}s`;
+ const outcome = String(p.outcome ?? '');
+ const reason = typeof p.reason === 'string' ? p.reason.slice(0, 300) : '';
+ let text: string;
+ if (outcome === 'no_answer' || outcome === 'declined' || outcome === 'busy') {
+ text = `📞 I tried to call you${reason ? ` about: ${reason}` : ''}. ${outcome === 'declined' ? 'You declined' : 'No answer'}, so here it is in writing.`;
+ } else if (outcome.startsWith('failed') && secs === 0) {
+ text = `📞 A call couldn't start: ${outcome.replace(/^failed:?\s*/, '') || 'unknown error'}.`;
+ } else {
+ const lines = (Array.isArray(p.transcript) ? p.transcript : [])
+ .map((t) => t as { role?: unknown; text?: unknown })
+ .filter((t) => typeof t.text === 'string' && t.text)
+ .map((t) => `${t.role === 'owner' ? '🗣 You' : t.role === 'ask_mercury' ? '🔎 Asked Mercury' : '☿ Mercury'}: ${String(t.text).slice(0, 300)}`);
+ let body = lines.join('\n');
+ if (body.length > 2500) body = `…\n${body.slice(-2500)}`;
+ text = `📞 Call ${p.direction === 'outgoing' ? 'to you' : 'with you'} ended · ${dur}${outcome.startsWith('failed') ? ` (${outcome})` : ''}${body ? `\n\n${body}` : ''}`;
+ }
+ void this.send(text).catch(() => {});
}
private onStatusNotification(params: unknown): void {
@@ -293,13 +399,31 @@ export class PluginChannel extends BaseChannel {
async send(content: string, targetId?: string): Promise<void> {
if (!content.trim()) return;
+ const call = this.callTarget(targetId);
+ if (call) {
+ const ask = this.callAsks.get(call);
+ if (ask) {
+ ask.chunks.push(content);
+ return;
+ }
+ // The call question timed out but the turn kept going: deliver in chat.
+ return this.send(`📞 From your call:\n${content}`);
+ }
const chatId = this.chatOf(targetId);
for (const chunk of splitMessage(toWhatsAppText(content))) {
await this.transport.request('mercury/channel/send', { chatId, text: chunk }, SEND_TIMEOUT_MS);
}
}
+ /** `whatsapp:call:<id>` → `call:<id>`; undefined for normal chats. */
+ private callTarget(targetId?: string): string | undefined {
+ if (!targetId) return undefined;
+ const t = targetId.startsWith(`${this.type}:`) ? targetId.slice(this.type.length + 1) : targetId;
+ return t.startsWith('call:') ? t : undefined;
+ }
+
async sendFile(filePath: string, targetId?: string): Promise<void> {
+ if (this.callTarget(targetId)) targetId = undefined; // files from a call go to the owner's chat
if (!existsSync(filePath) || !statSync(filePath).isFile()) throw new Error(`Not a file: ${filePath}`);
if (statSync(filePath).size > FILE_LIMIT_BYTES) throw new Error('File is larger than 100 MB');
await this.transport.request('mercury/channel/sendFile', { chatId: this.chatOf(targetId), path: filePath }, FILE_TIMEOUT_MS);
@@ -314,6 +438,7 @@ export class PluginChannel extends BaseChannel {
}
async typing(targetId?: string): Promise<void> {
+ if (this.callTarget(targetId)) return;
try {
await this.transport.request('mercury/channel/typing', { chatId: this.chatOf(targetId), on: true }, 10_000);
} catch { /* cosmetic */ }
@@ -342,10 +467,13 @@ export class PluginChannel extends BaseChannel {
/** Approval prompt answered by text: 1/yes, 2/no, 3/always. No reply in 2 minutes is no. */
async askPermission(prompt: string, targetId?: string): Promise<string> {
+ // Nobody can approve mid-call: refuse (fail-closed). The model offers to do it by message.
+ if (this.callTarget(targetId)) return 'no';
return this.ask(`🔐 ${prompt}\n\nReply *1* (yes), *2* (no) or *3* (always for this chat).`, targetId);
}
async askToContinue(question: string, targetId?: string): Promise<boolean> {
+ if (this.callTarget(targetId)) return false;
return (await this.ask(`${question}\n\nReply *yes* to continue or *no* to stop.`, targetId)) !== 'no';
}
@@ -359,3 +487,18 @@ export class PluginChannel extends BaseChannel {
await this.transport.request('mercury/channel/unlink', {}, 30_000);
}
}
+
+/**
+ * Who Mercury is on a call: its soul and persona, trimmed. Read fresh for
+ * each call so edits to the soul files apply to the next call.
+ */
+export function voiceBriefing(): string {
+ const parts: string[] = [];
+ for (const name of ['soul.md', 'persona.md']) {
+ try {
+ const text = readFileSync(join(getMercuryHome(), 'soul', name), 'utf8').trim();
+ if (text) parts.push(text.slice(0, 1500));
+ } catch { /* optional */ }
+ }
+ return parts.length ? `Who you are (from Mercury's soul files; keep this voice on the call):\n${parts.join('\n\n')}` : '';
+}
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index 35732041..3957af07 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -21,8 +21,10 @@ const rl = require('node:readline').createInterface({ input: process.stdin });
const send = (m) => process.stdout.write(JSON.stringify(m) + '\\n');
const notify = (method, params) => send({ jsonrpc: '2.0', method, params });
const log = (name, v) => fs.appendFileSync(path.join(data, name), JSON.stringify(v) + '\\n');
+let reqN = 0;
rl.on('line', (line) => {
const msg = JSON.parse(line);
+ if (!msg.method) { log('replies.jsonl', msg); return; }
const ok = (result) => send({ jsonrpc: '2.0', id: msg.id, result });
switch (msg.method) {
case 'initialize':
@@ -31,9 +33,17 @@ rl.on('line', (line) => {
case 'notifications/initialized':
return notify('mercury/channel/status', { state: 'needs-pairing' });
case 'tools/list':
- return ok({ tools: [{ name: 'inject', description: 'test', inputSchema: { type: 'object' } }] });
+ return ok({ tools: ['inject', 'callsim', 'callend'].map((name) => ({ name, description: 'test', inputSchema: { type: 'object' } })) });
case 'tools/call': {
const a = msg.params.arguments;
+ if (msg.params.name === 'callsim') {
+ send({ jsonrpc: '2.0', id: 'wa-' + (++reqN), method: a.method, params: a.params });
+ return ok({ content: [{ type: 'text', text: 'sent' }] });
+ }
+ if (msg.params.name === 'callend') {
+ notify('mercury/call/ended', a);
+ return ok({ content: [{ type: 'text', text: 'sent' }] });
+ }
notify('mercury/channel/message', { id: a.id, chatId: a.chatId || '[email protected]', senderId: a.senderId || 'x@lid', senderPhone: a.senderPhone, isGroup: !!a.isGroup, fromMe: !!a.fromMe, text: a.text });
return ok({ content: [{ type: 'text', text: 'injected' }] });
}
@@ -60,7 +70,7 @@ function channelPlugin(root: string, id = 'whatsapp', extra: Record<string, unkn
manifestVersion: 1, id, name: 'WhatsApp', version: '1.0.0', description: 'test channel', kind: 'out-of-process',
engines: { mercury: '>=1.0.0', pluginApi: '^1.1.0' },
server: { command: 'node', args: ['server.cjs'] },
- contributes: { tools: [{ name: 'inject', description: 'Inject a message for tests.', readOnly: true }], channel: { type: 'whatsapp' } },
+ contributes: { tools: ['inject', 'callsim', 'callend'].map((name) => ({ name, description: 'Test hook.', readOnly: true })), channel: { type: 'whatsapp' } },
settings: { version: 1, fields: { owner: { type: 'string', default: '' }, members: { type: 'string', default: '' }, allowGroups: { type: 'boolean', default: false } } },
...extra,
}));
@@ -97,8 +107,8 @@ afterEach(async () => {
env.restore();
});
-async function inject(args: Record<string, unknown>): Promise<void> {
- const t = getPluginTools(new PermissionManager())['whatsapp__inject'] as Tool & { execute: (a: unknown, o: unknown) => Promise<unknown> };
+async function inject(args: Record<string, unknown>, tool = 'inject'): Promise<void> {
+ const t = getPluginTools(new PermissionManager())[`whatsapp__${tool}`] as Tool & { execute: (a: unknown, o: unknown) => Promise<unknown> };
await t.execute(args, { toolCallId: 't', messages: [] });
await sleep(40);
}
@@ -199,4 +209,59 @@ describe('plugin channels (plugin API 1.1)', () => {
expect(toWhatsAppText('## Hi\n__x__')).toBe('*Hi*\n_x_');
expect(splitMessage('a\nb', 2)).toEqual(['a', 'b']);
});
+
+ describe('voice calls', () => {
+ const replies = () => {
+ const f = join(pluginDataDir('whatsapp'), 'replies.jsonl');
+ return existsSync(f) ? readFileSync(f, 'utf8').trim().split('\n').map((l) => JSON.parse(l)) : [];
+ };
+ const sent = () => {
+ const f = join(pluginDataDir('whatsapp'), 'out.jsonl');
+ return existsSync(f) ? readFileSync(f, 'utf8').trim().split('\n').map((l) => JSON.parse(l)) : [];
+ };
+ const callsim = (method: string, params: Record<string, unknown>) => inject({ method, params }, 'callsim');
+
+ it('answers only the owner, and only with a voice provider', async () => {
+ await installChannel();
+ await callsim('mercury/call/incoming', { callId: 'c1', from: 'x@lid', fromPhone: '15550002', voiceReady: true });
+ await callsim('mercury/call/incoming', { callId: 'c2', from: '[email protected]', voiceReady: true });
+ await callsim('mercury/call/incoming', { callId: 'c3', from: 'x@lid', fromPhone: '15550002', voiceReady: false });
+ await waitFor(() => replies().length === 3);
+ const r = replies();
+ expect(r[0].result.accept).toBe(true);
+ expect(r[1].result.accept).toBe(false);
+ expect(r[2].result.accept).toBe(false);
+ await waitFor(() => sent().some((m) => /OpenAI provider/.test(m.text ?? '')));
+ expect(sent().find((m) => /OpenAI provider/.test(m.text))?.text).toMatch(/Providers/);
+ });
+
+ it('ask_mercury runs a turn and returns its answer, without messaging WhatsApp', async () => {
+ const ch = await installChannel();
+ await callsim('mercury/call/ask', { callId: 'c9', question: 'What is the weather?' });
+ await waitFor(() => received.length === 1);
+ const msg = received[0];
+ expect(msg.channelId).toBe('whatsapp:call:c9');
+ expect(msg.senderRole).toBe('admin');
+ expect(msg.content).toMatch(/Voice call[\s\S]*What is the weather\?/);
+ // The agent replies on the call target, then finishes the turn.
+ expect(await ch.askPermission('Run git push?', msg.channelId)).toBe('no');
+ await ch.send('☿ Working on it…', msg.channelId);
+ await ch.send('It is sunny and 24 degrees.', msg.channelId);
+ ch.endTask(msg.channelId);
+ await waitFor(() => replies().length === 1);
+ expect(replies()[0].result.answer).toBe('It is sunny and 24 degrees.');
+ expect(sent().filter((m) => m.method === 'mercury/channel/send')).toEqual([]);
+ });
+
+ it('sends the owner a summary when a call ends, or a note when it was missed', async () => {
+ await installChannel();
+ await inject({ callId: 'c5', direction: 'incoming', outcome: 'completed', durationSec: 75, transcript: [{ role: 'owner', text: 'Any news?' }, { role: 'mercury', text: 'Two new emails.' }] }, 'callend');
+ await inject({ callId: 'c6', direction: 'outgoing', outcome: 'no_answer', reason: 'The deploy failed', durationSec: 0, transcript: [] }, 'callend');
+ await waitFor(() => sent().length >= 2);
+ const texts = sent().map((m) => m.text as string);
+ expect(texts[0]).toMatch(/Call with you ended · 1m 15s[\s\S]*You: Any news\?[\s\S]*Mercury: Two new emails\./);
+ expect(texts[1]).toMatch(/tried to call you about: The deploy failed\. No answer/);
+ expect(sent().every((m) => m.chatId === '[email protected]')).toBe(true);
+ });
+ });
});
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index 9e3c0bc8..bc5aa2c8 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -273,6 +273,7 @@ export class PluginManager {
}
const deps = {
onNotification: channel ? (method: string, params: unknown) => channel!.handleNotification(method, params) : undefined,
+ onRequest: channel ? (method: string, params: unknown) => channel!.handleRequest(method, params) : undefined,
onReady: channel ? () => channel!.attach() : undefined,
onDown: channel ? () => channel!.down() : undefined,
mercuryVersion: mercuryVersion(),
diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.ts
index 17f78b80..11cdadfb 100644
--- a/src/plugins/runtime/out-of-process.ts
+++ b/src/plugins/runtime/out-of-process.ts
@@ -260,7 +260,12 @@ export class OutOfProcessRuntime implements PluginRuntime {
if (msg.method && msg.id !== undefined) {
// Server → client requests: we support ping; refuse everything else (sampling, roots…).
if (msg.method === 'ping') this.reply(msg.id, {});
- else this.replyError(msg.id, -32601, `Mercury does not support ${msg.method}`);
+ else if (msg.method.startsWith('mercury/') && this.manifest.contributes.channel && this.deps.onRequest) {
+ const id = msg.id;
+ this.deps.onRequest(msg.method, msg.params)
+ .then((result) => this.reply(id, result ?? {}))
+ .catch((err) => this.replyError(id, -32000, (err as Error).message));
+ } else this.replyError(msg.id, -32601, `Mercury does not support ${msg.method}`);
return;
}
if (msg.method) {
diff --git a/src/plugins/runtime/types.ts b/src/plugins/runtime/types.ts
index 6ef4023a..5e3c5373 100644
--- a/src/plugins/runtime/types.ts
+++ b/src/plugins/runtime/types.ts
@@ -19,6 +19,8 @@ export interface RuntimeDeps {
onFatal?(code: 'crashed' | 'activation', message: string): void;
/** Plugin API 1.1 channels: a `mercury/…` notification from the plugin. */
onNotification?(method: string, params: unknown): void;
+ /** Plugin API 1.1 channels: a `mercury/…` request from the plugin (e.g. a call decision). */
+ onRequest?(method: string, params: unknown): Promise<unknown>;
/** The plugin finished its handshake (first start and every restart). */
onReady?(): void;
/** The plugin process went away (crash, recycle or stop). */