Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(whatsapp): choose the voice for calls (OpenAI default, Gemini, Grok, ElevenLabs, Azure, Qwen, or your own model)
Salman Qureshi9a5f4b0efbec
diff --git a/plugins/whatsapp/companion/Cargo.toml b/plugins/whatsapp/companion/Cargo.tomlindex 0ecc3273..5e0fb420 100644--- a/plugins/whatsapp/companion/Cargo.toml+++ b/plugins/whatsapp/companion/Cargo.toml@@ -15,6 +15,8 @@ whatsapp-rust = { git = "https://github.com/oxidezap/whatsapp-rust", rev = "c373tokio-websockets = { version = "0.13.3", features = ["client", "rustls-webpki-roots", "rand", "ring"] }http = "1"base64 = "0.22"+# Minting ElevenLabs Realtime session secrets (rustls, like everything else here).+ureq = "3"tokio = { version = "1.47", features = ["full"] }serde_json = "1"anyhow = "1"diff --git a/plugins/whatsapp/companion/src/links/gemini.rs b/plugins/whatsapp/companion/src/links/gemini.rsnew file mode 100644index 00000000..047cc665--- /dev/null+++ b/plugins/whatsapp/companion/src/links/gemini.rs@@ -0,0 +1,158 @@+//! Google Gemini Live: native 16 kHz input, 24 kHz output, its own protocol.+//! Connections last ~10 minutes, so the link resumes the session (handle from+//! sessionResumptionUpdate) on goAway or a drop, and the call carries on.++use std::collections::HashMap;+use std::time::Duration;++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use whatsapp_rust::futures::{SinkExt, StreamExt};++use super::{Brain, CALL_RATE, Link, LinkCmd, LinkConfig, LinkEvent, b64, env_key, pcm_from_bytes, resample, setting, unb64, ws};++const URL: &str = "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";++fn setup(cfg: &LinkConfig, handle: Option<&str>) -> Value {+ let s = &cfg.settings;+ let decls: Vec<Value> = cfg.tools.as_array().cloned().unwrap_or_default().iter().map(|t| json!({+ "name": t.get("name"), "description": t.get("description"), "parameters": t.get("parameters"),+ })).collect();+ let mut setup = json!({+ "model": format!("models/{}", setting(s, "geminiModel", "gemini-3.8-live")),+ "generationConfig": {+ "responseModalities": ["AUDIO"],+ "speechConfig": { "voiceConfig": { "prebuiltVoiceConfig": { "voiceName": setting(s, "geminiVoice", "Kore") } } },+ },+ "systemInstruction": { "parts": [{ "text": cfg.instructions }] },+ "tools": [{ "functionDeclarations": decls }],+ "inputAudioTranscription": {},+ "outputAudioTranscription": {},+ "realtimeInputConfig": {+ "automaticActivityDetection": { "disabled": false, "silenceDurationMs": 600 },+ "activityHandling": "START_OF_ACTIVITY_INTERRUPTS",+ },+ "contextWindowCompression": { "slidingWindow": {} },+ "sessionResumption": {},+ });+ if let Some(h) = handle { setup["sessionResumption"] = json!({ "handle": h }); }+ json!({ "setup": setup })+}++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ let key = env_key("GEMINI_API_KEY").ok_or("no Gemini API key")?;+ let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<LinkCmd>();+ let (ev_tx, ev_rx) = mpsc::unbounded_channel::<LinkEvent>();+ // Fail fast on a bad key or model: the first connection is made here.+ let mut sock = connect(&key, &cfg, None).await?;++ tokio::spawn(async move {+ let mut handle: Option<String> = None;+ let mut names: HashMap<String, String> = HashMap::new();+ let (mut user_text, mut model_text) = (String::new(), String::new());+ let mut responding = false;+ 'conn: loop {+ let (mut tx, mut rx) = sock.split();+ loop {+ tokio::select! {+ c = cmd_rx.recv() => {+ let Some(c) = c else { let _ = tx.close().await; return };+ let msg = match c {+ LinkCmd::Audio(frame) => json!({ "realtimeInput": { "audio": { "data": b64(&frame), "mimeType": "audio/pcm;rate=16000" } } }),+ LinkCmd::Instruct(text) => json!({ "clientContent": { "turns": [{ "role": "user", "parts": [{ "text": text }] }], "turnComplete": true } }),+ LinkCmd::Say(text) => json!({ "clientContent": { "turns": [{ "role": "user", "parts": [{ "text": format!("[Say this to the caller, naturally] {text}") }] }], "turnComplete": true } }),+ LinkCmd::ToolResult { id, output } => {+ let name = names.remove(&id).unwrap_or_default();+ json!({ "toolResponse": { "functionResponses": [{ "id": id, "name": name, "response": { "result": output } }] } })+ }+ LinkCmd::Cancel => continue,+ };+ if tx.send(Message::text(msg.to_string())).await.is_err() { break; }+ }+ m = rx.next() => {+ let Some(Ok(m)) = m else { break };+ if m.is_close() {+ let reason = m.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ if handle.is_none() {+ let _ = ev_tx.send(LinkEvent::Closed(format!("Gemini closed the session{}", if reason.is_empty() { String::new() } else { format!(": {reason}") })));+ return;+ }+ break;+ }+ let text = if let Some(t) = m.as_text() { t.to_string() } else { String::from_utf8_lossy(&m.as_payload().to_vec()).to_string() };+ let Ok(v) = serde_json::from_str::<Value>(&text) else { continue };+ if let Some(h) = v.pointer("/sessionResumptionUpdate/newHandle").and_then(Value::as_str) {+ if v.pointer("/sessionResumptionUpdate/resumable").and_then(Value::as_bool) != Some(false) { handle = Some(h.to_string()); }+ }+ if v.get("goAway").is_some() { break; } // resume on a fresh connection+ if let Some(calls) = v.pointer("/toolCall/functionCalls").and_then(Value::as_array) {+ for c in calls {+ let id = c.get("id").and_then(Value::as_str).unwrap_or("").to_string();+ let name = c.get("name").and_then(Value::as_str).unwrap_or("").to_string();+ names.insert(id.clone(), name.clone());+ let _ = ev_tx.send(LinkEvent::ToolCall { id, name, args: c.get("args").cloned().unwrap_or(json!({})) });+ }+ }+ let Some(sc) = v.get("serverContent") else { continue };+ if sc.get("interrupted").and_then(Value::as_bool) == Some(true) {+ let _ = ev_tx.send(LinkEvent::SpeechStarted);+ }+ if let Some(t) = sc.pointer("/inputTranscription/text").and_then(Value::as_str) { user_text.push_str(t); }+ if let Some(t) = sc.pointer("/outputTranscription/text").and_then(Value::as_str) { model_text.push_str(t); }+ if let Some(parts) = sc.pointer("/modelTurn/parts").and_then(Value::as_array) {+ for part in parts {+ if let Some(d) = part.pointer("/inlineData/data").and_then(Value::as_str) {+ if !responding {+ responding = true;+ let _ = ev_tx.send(LinkEvent::ResponseStarted);+ if !user_text.trim().is_empty() { let _ = ev_tx.send(LinkEvent::UserText(std::mem::take(&mut user_text).trim().to_string())); }+ }+ let _ = ev_tx.send(LinkEvent::Audio(resample(&pcm_from_bytes(&unb64(d)), 24_000, CALL_RATE)));+ }+ }+ }+ if sc.get("turnComplete").and_then(Value::as_bool) == Some(true) {+ if !user_text.trim().is_empty() { let _ = ev_tx.send(LinkEvent::UserText(std::mem::take(&mut user_text).trim().to_string())); }+ if !model_text.trim().is_empty() { let _ = ev_tx.send(LinkEvent::AssistantText(std::mem::take(&mut model_text).trim().to_string())); }+ responding = false;+ let _ = ev_tx.send(LinkEvent::ResponseDone);+ }+ }+ }+ }+ // Connection ended without the call ending: resume where we left off.+ for attempt in 0..3u64 {+ tokio::time::sleep(Duration::from_millis(300 * (attempt + 1))).await;+ match connect(&key, &cfg, handle.as_deref()).await {+ Ok(s) => { sock = s; continue 'conn; }+ Err(e) => crate::log(format!("gemini resume failed: {e}")),+ }+ }+ let _ = ev_tx.send(LinkEvent::Closed("lost the connection to Gemini".into()));+ return;+ }+ });++ Ok(Link { brain: Brain::Voice, cmd: cmd_tx, events: ev_rx })+}++async fn connect(key: &str, cfg: &LinkConfig, handle: Option<&str>) -> Result<ws::Socket, String> {+ let mut sock = ws::connect(&format!("{URL}?key={key}"), &[]).await.map_err(|e| format!("couldn't reach Gemini: {e}"))?;+ sock.send(Message::text(setup(cfg, handle).to_string())).await.map_err(|e| e.to_string())?;+ // Wait for setupComplete before streaming audio.+ let wait = async {+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| e.to_string())?;+ if m.is_close() {+ let reason = m.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ return Err(format!("Gemini refused the session: {reason}"));+ }+ let text = if let Some(t) = m.as_text() { t.to_string() } else { String::from_utf8_lossy(&m.as_payload().to_vec()).to_string() };+ if text.contains("setupComplete") { return Ok(()); }+ }+ Err("Gemini closed during setup".to_string())+ };+ tokio::time::timeout(Duration::from_secs(15), wait).await.map_err(|_| "Gemini setup timed out".to_string())??;+ Ok(sock)+}diff --git a/plugins/whatsapp/companion/src/links/mod.rs b/plugins/whatsapp/companion/src/links/mod.rsnew file mode 100644index 00000000..0e33e186--- /dev/null+++ b/plugins/whatsapp/companion/src/links/mod.rs@@ -0,0 +1,231 @@+//! Voice links: one per kind of voice provider, all speaking the same small+//! language to the call bridge (voice.rs). The bridge owns everything about+//! the call itself (Mercury questions, approvals, progress updates, photos,+//! summaries); a link only moves audio and events.+//!+//! - realtime: speech-to-speech models on OpenAI's Realtime protocol+//! (OpenAI, Azure OpenAI, xAI Grok, ElevenLabs Realtime, Qwen-Omni)+//! - gemini: Google Gemini Live+//! - pipeline: speech-to-text → the user's own Mercury model → text-to-speech+//! (Deepgram / AssemblyAI / ElevenLabs Scribe / Sarvam, then Cartesia /+//! ElevenLabs / MiniMax / Sarvam / Deepgram voices)++pub mod gemini;+pub mod pipeline;+pub mod realtime;+pub mod stt;+pub mod tts;+pub mod ws;++use serde_json::Value;+use tokio::sync::mpsc;++/// Phone-call audio rate: 16 kHz mono PCM16.+pub const CALL_RATE: u32 = 16_000;++#[derive(Debug)]+pub enum LinkEvent {+ /// Audio for the caller, 16 kHz mono PCM16.+ Audio(Vec<i16>),+ /// The caller started talking: stop playing and cancel speech (barge-in).+ SpeechStarted,+ /// A finished utterance from the caller.+ UserText(String),+ /// What the voice said (for the transcript).+ AssistantText(String),+ /// The voice model wants a tool (ask_mercury, answer_approval, end_call).+ ToolCall { id: String, name: String, args: Value },+ ResponseStarted,+ ResponseDone,+ /// The provider closed the session; the reason is already in plain words.+ Closed(String),+}++#[derive(Debug)]+pub enum LinkCmd {+ /// Caller audio, 16 kHz mono PCM16, 60 ms frames.+ Audio(Vec<i16>),+ /// An instruction for a model that reasons (status update, approval question).+ Instruct(String),+ /// Speak exactly this (pipeline voices; realtime models are asked to say it).+ Say(String),+ /// The result of a ToolCall.+ ToolResult { id: String, output: String },+ /// Stop speaking now (barge-in).+ Cancel,+}++/// Does this link's own model reason and call tools, or does Mercury think for every turn?+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Brain {+ /// A speech-to-speech model: it chats and calls ask_mercury when it needs to.+ Voice,+ /// Every caller utterance is a Mercury turn; the link only listens and speaks.+ Mercury,+}++pub struct Link {+ pub brain: Brain,+ pub cmd: mpsc::UnboundedSender<LinkCmd>,+ pub events: mpsc::UnboundedReceiver<LinkEvent>,+}++impl Link {+ pub fn send(&self, c: LinkCmd) {+ let _ = self.cmd.send(c);+ }+}++/// Everything a link needs to start: provider choice and keys come from the+/// plugin settings and environment (keys are passed by Mercury, never typed here).+pub struct LinkConfig {+ pub instructions: String,+ pub tools: Value,+ pub settings: Value,+}++pub fn setting<'a>(settings: &'a Value, key: &str, default: &'a str) -> String {+ settings.get(key).and_then(Value::as_str).filter(|s| !s.trim().is_empty()).unwrap_or(default).trim().to_string()+}++pub fn env_key(name: &str) -> Option<String> {+ std::env::var(name).ok().filter(|k| !k.trim().is_empty())+}++/// Which voice engine the owner picked, and whether its keys are present.+pub fn engine(settings: &Value) -> String {+ setting(settings, "voiceEngine", "openai")+}++/// Human-readable reason calls can't start with the current settings, if any.+pub fn not_ready(settings: &Value) -> Option<String> {+ let need = |name: &str, what: &str| if env_key(name).is_none() { Some(format!("voice calls with {what} need its API key: add it in /plugins whatsapp")) } else { None };+ match engine(settings).as_str() {+ "openai" => if env_key("MERCURY_PROVIDER_OPENAI_API_KEY").is_none() { Some("voice calls need an OpenAI provider: add your OpenAI key once in the dashboard (Providers) or with `mercury doctor`".into()) } else { None },+ "grok" => if env_key("MERCURY_PROVIDER_GROK_API_KEY").is_none() { Some("voice calls with Grok need a Grok provider: add your xAI key in the dashboard (Providers)".into()) } else { None },+ "azure" => need("AZURE_OPENAI_API_KEY", "Azure OpenAI").or_else(|| if setting(settings, "azureEndpoint", "").is_empty() { Some("set the Azure endpoint in /plugins whatsapp".into()) } else { None }),+ "elevenlabs" => need("ELEVENLABS_API_KEY", "ElevenLabs"),+ "qwen" => need("DASHSCOPE_API_KEY", "Qwen (Alibaba Model Studio)"),+ "gemini" => need("GEMINI_API_KEY", "Gemini"),+ "mercury" => {+ let stt = setting(settings, "sttProvider", "deepgram");+ let tts = setting(settings, "ttsProvider", "cartesia");+ stt::key_name(&stt).and_then(|k| need(k, &stt::label(&stt))).or_else(|| tts::key_name(&tts).and_then(|k| need(k, &tts::label(&tts))))+ }+ other => Some(format!("unknown voice engine \"{other}\"")),+ }+}++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ match engine(&cfg.settings).as_str() {+ "gemini" => gemini::open(cfg).await,+ "mercury" => pipeline::open(cfg).await,+ _ => realtime::open(cfg).await,+ }+}++// ── shared helpers ────────────────────────────────────────────────────────++/// 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()+}++pub fn pcm_bytes(samples: &[i16]) -> Vec<u8> {+ let mut bytes = Vec::with_capacity(samples.len() * 2);+ for s in samples {+ bytes.extend_from_slice(&s.to_le_bytes());+ }+ bytes+}++pub fn pcm_from_bytes(bytes: &[u8]) -> Vec<i16> {+ bytes.chunks_exact(2).map(|c| i16::from_le_bytes([c[0], c[1]])).collect()+}++pub fn b64(samples: &[i16]) -> String {+ use base64::Engine as _;+ base64::engine::general_purpose::STANDARD.encode(pcm_bytes(samples))+}++pub fn unb64(data: &str) -> Vec<u8> {+ use base64::Engine as _;+ base64::engine::general_purpose::STANDARD.decode(data).unwrap_or_default()+}++/// Drop a RIFF/WAV header if a provider sends one in front of raw PCM.+pub fn strip_wav(bytes: &[u8]) -> &[u8] {+ if bytes.len() > 12 && &bytes[0..4] == b"RIFF" && &bytes[8..12] == b"WAVE" {+ let mut i = 12;+ while i + 8 <= bytes.len() {+ let len = u32::from_le_bytes([bytes[i + 4], bytes[i + 5], bytes[i + 6], bytes[i + 7]]) as usize;+ if &bytes[i..i + 4] == b"data" {+ return &bytes[(i + 8).min(bytes.len())..];+ }+ i += 8 + len;+ }+ }+ bytes+}++/// The language of a reply, by script: Devanagari → Hindi, Arabic script → Urdu, else English.+pub fn script_language(text: &str) -> &'static str {+ let (mut deva, mut arabic, mut latin) = (0, 0, 0);+ for c in text.chars() {+ match c as u32 {+ 0x0900..=0x097F => deva += 1,+ 0x0600..=0x06FF | 0x0750..=0x077F | 0xFB50..=0xFDFF | 0xFE70..=0xFEFF => arabic += 1,+ 0x41..=0x5A | 0x61..=0x7A => latin += 1,+ _ => {}+ }+ }+ if deva > latin && deva >= arabic { "hi" } else if arabic > latin { "ur" } else { "en" }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn resample_lengths() {+ assert_eq!(resample(&[0i16; 960], 16_000, 24_000).len(), 1440);+ assert_eq!(resample(&[0i16; 1440], 24_000, 16_000).len(), 960);+ }++ #[test]+ fn pcm_round_trip() {+ let s = vec![0i16, 1, -1, i16::MAX, i16::MIN];+ assert_eq!(pcm_from_bytes(&unb64(&b64(&s))), s);+ }++ #[test]+ fn wav_header_is_stripped() {+ let mut wav = b"RIFF\0\0\0\0WAVEfmt \x10\0\0\0".to_vec();+ wav.extend_from_slice(&[0u8; 16]);+ wav.extend_from_slice(b"data\x04\0\0\0");+ wav.extend_from_slice(&[1, 0, 2, 0]);+ assert_eq!(strip_wav(&wav), &[1, 0, 2, 0]);+ assert_eq!(strip_wav(&[5, 6]), &[5, 6]);+ }++ #[test]+ fn languages_by_script() {+ assert_eq!(script_language("Hello there"), "en");+ assert_eq!(script_language("नमस्ते, आप कैसे हैं"), "hi");+ assert_eq!(script_language("آپ کیسے ہیں"), "ur");+ }+}diff --git a/plugins/whatsapp/companion/src/links/pipeline.rs b/plugins/whatsapp/companion/src/links/pipeline.rsnew file mode 100644index 00000000..f3c2b297--- /dev/null+++ b/plugins/whatsapp/companion/src/links/pipeline.rs@@ -0,0 +1,94 @@+//! "My own model" calls: streaming speech-to-text → the bridge (which asks the+//! owner's Mercury model, any provider) → streaming text-to-speech.+//!+//! This link never reasons: every finished utterance goes up as UserText, and+//! the bridge answers with Say. Speech is queued in order; Cancel (barge-in)+//! stops the current utterance and drops anything queued.++use std::collections::VecDeque;++use tokio::sync::mpsc;++use super::{Brain, Link, LinkCmd, LinkConfig, LinkEvent, stt, tts};++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<LinkCmd>();+ let (ev_tx, ev_rx) = mpsc::unbounded_channel::<LinkEvent>();+ let (stt_tx, mut stt_rx) = mpsc::unbounded_channel::<stt::SttEvent>();+ let audio_in = stt::start(&cfg.settings, stt_tx).await?;++ // Speech-to-text events → bridge.+ let ev = ev_tx.clone();+ tokio::spawn(async move {+ while let Some(e) = stt_rx.recv().await {+ let out = match e {+ stt::SttEvent::SpeechStarted => LinkEvent::SpeechStarted,+ stt::SttEvent::Final(t) => LinkEvent::UserText(t),+ stt::SttEvent::Closed(r) => LinkEvent::Closed(r),+ };+ if ev.send(out).is_err() { break; }+ }+ });++ let settings = cfg.settings.clone();+ tokio::spawn(async move {+ let mut queue: VecDeque<String> = VecDeque::new();+ let mut speaking: Option<tokio::task::JoinHandle<()>> = None;+ let (done_tx, mut done_rx) = mpsc::unbounded_channel::<()>();+ loop {+ // Start the next utterance when idle.+ if speaking.as_ref().map(|h| h.is_finished()).unwrap_or(true) {+ if let Some(text) = queue.pop_front() {+ let _ = ev_tx.send(LinkEvent::ResponseStarted);+ let _ = ev_tx.send(LinkEvent::AssistantText(text.clone()));+ let (pcm_tx, mut pcm_rx) = mpsc::unbounded_channel::<Vec<i16>>();+ let ev2 = ev_tx.clone();+ let fwd = tokio::spawn(async move {+ while let Some(p) = pcm_rx.recv().await {+ if ev2.send(LinkEvent::Audio(p)).is_err() { break; }+ }+ });+ let s = settings.clone();+ let done = done_tx.clone();+ let ev3 = ev_tx.clone();+ speaking = Some(tokio::spawn(async move {+ if let Err(e) = tts::speak(&s, &text, &pcm_tx).await {+ crate::log(format!("voice: {e}"));+ // A broken voice provider shouldn't leave the caller in silence forever.+ let _ = ev3.send(LinkEvent::Closed(e));+ }+ drop(pcm_tx);+ let _ = fwd.await;+ let _ = done.send(());+ }));+ }+ }+ tokio::select! {+ c = cmd_rx.recv() => {+ let Some(c) = c else { break };+ match c {+ LinkCmd::Audio(frame) => { let _ = audio_in.send(frame); }+ LinkCmd::Say(text) => { if !text.trim().is_empty() { queue.push_back(text); } }+ LinkCmd::ToolResult { output, .. } => { if !output.trim().is_empty() { queue.push_back(output); } }+ // Only reasoning models act on instructions; the bridge sends Say for us.+ LinkCmd::Instruct(_) => {}+ LinkCmd::Cancel => {+ queue.clear();+ if let Some(h) = speaking.take() {+ h.abort();+ let _ = ev_tx.send(LinkEvent::ResponseDone);+ }+ }+ }+ }+ Some(()) = done_rx.recv() => {+ speaking = None;+ if queue.is_empty() { let _ = ev_tx.send(LinkEvent::ResponseDone); }+ }+ }+ }+ if let Some(h) = speaking { h.abort(); }+ });++ Ok(Link { brain: Brain::Mercury, cmd: cmd_tx, events: ev_rx })+}diff --git a/plugins/whatsapp/companion/src/links/realtime.rs b/plugins/whatsapp/companion/src/links/realtime.rsnew file mode 100644index 00000000..93d18503--- /dev/null+++ b/plugins/whatsapp/companion/src/links/realtime.rs@@ -0,0 +1,244 @@+//! Speech-to-speech models on OpenAI's Realtime protocol. One client, small+//! per-provider profiles: OpenAI (default), Azure OpenAI, xAI Grok, Alibaba+//! Qwen-Omni (older event names), ElevenLabs Realtime (session minted via a+//! client secret; experimental until ElevenLabs documents server use).++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use whatsapp_rust::futures::{SinkExt, StreamExt};++use super::{Brain, CALL_RATE, Link, LinkCmd, LinkConfig, LinkEvent, b64, env_key, pcm_from_bytes, resample, setting, unb64, ws};++#[derive(Clone, Copy, PartialEq, Eq)]+enum Dialect {+ /// OpenAI GA session shape (OpenAI, Azure, ElevenLabs).+ Ga,+ /// GA events, but voice and turn detection at the top of the session (xAI).+ Grok,+ /// Older Realtime shape and event names, tools nested in "function" (Qwen).+ Beta,+}++struct Profile {+ url: String,+ headers: Vec<(&'static str, String)>,+ model: String,+ dialect: Dialect,+ in_rate: u32,+ out_rate: u32,+ voice: String,+ transcribe: Option<String>,+}++fn base_ws(http_base: &str) -> String {+ let b = http_base.trim_end_matches('/');+ if let Some(r) = b.strip_prefix("https://") { format!("wss://{r}") } else if let Some(r) = b.strip_prefix("http://") { format!("ws://{r}") } else { b.to_string() }+}++async fn profile(s: &Value) -> Result<Profile, String> {+ let engine = super::engine(s);+ Ok(match engine.as_str() {+ "openai" => {+ let key = env_key("MERCURY_PROVIDER_OPENAI_API_KEY").ok_or("no OpenAI provider key")?;+ let base = env_key("MERCURY_PROVIDER_OPENAI_BASE_URL").unwrap_or_else(|| "https://api.openai.com/v1".into());+ let model = setting(s, "voiceModel", "gpt-realtime-2.1");+ Profile {+ url: format!("{}/realtime?model={model}", base_ws(&base)),+ headers: vec![("authorization", format!("Bearer {key}"))],+ model, dialect: Dialect::Ga, in_rate: 24_000, out_rate: 24_000,+ voice: setting(s, "voice", "marin"), transcribe: Some("gpt-4o-mini-transcribe".into()),+ }+ }+ "azure" => {+ let key = env_key("AZURE_OPENAI_API_KEY").ok_or("no Azure OpenAI key")?;+ let endpoint = setting(s, "azureEndpoint", "");+ let host = endpoint.trim_start_matches("https://").trim_start_matches("wss://").trim_end_matches('/').to_string();+ if host.is_empty() { return Err("set the Azure endpoint (e.g. myresource.openai.azure.com)".into()); }+ let model = setting(s, "azureDeployment", "gpt-realtime-2.1");+ Profile {+ url: format!("wss://{host}/openai/v1/realtime?model={model}"),+ headers: vec![("api-key", key)],+ model, dialect: Dialect::Ga, in_rate: 24_000, out_rate: 24_000,+ voice: setting(s, "voice", "marin"), transcribe: Some(setting(s, "azureTranscribeModel", "whisper-1")),+ }+ }+ "grok" => {+ let key = env_key("MERCURY_PROVIDER_GROK_API_KEY").ok_or("no Grok provider key")?;+ let model = setting(s, "grokModel", "grok-voice-latest");+ Profile {+ url: format!("wss://api.x.ai/v1/realtime?model={model}"),+ headers: vec![("authorization", format!("Bearer {key}"))],+ // xAI takes phone-rate audio directly: no resampling either way.+ model, dialect: Dialect::Grok, in_rate: CALL_RATE, out_rate: CALL_RATE,+ voice: setting(s, "grokVoice", "eve"), transcribe: Some("grok-transcribe".into()),+ }+ }+ "qwen" => {+ let key = env_key("DASHSCOPE_API_KEY").ok_or("no Qwen (DashScope) key")?;+ let endpoint = setting(s, "qwenEndpoint", "dashscope-intl.aliyuncs.com");+ let host = endpoint.trim_start_matches("https://").trim_start_matches("wss://").trim_end_matches('/').to_string();+ let model = setting(s, "qwenModel", "qwen3.8-omni-flash-realtime");+ Profile {+ url: format!("wss://{host}/api-ws/v1/realtime?model={model}"),+ headers: vec![("authorization", format!("Bearer {key}"))],+ model, dialect: Dialect::Beta, in_rate: CALL_RATE, out_rate: 24_000,+ voice: setting(s, "qwenVoice", "Tina"), transcribe: Some("qwen3-asr-flash-realtime".into()),+ }+ }+ "elevenlabs" => {+ let key = env_key("ELEVENLABS_API_KEY").ok_or("no ElevenLabs key")?;+ let model = setting(s, "elevenlabsModel", "eleven_realtime_v1_mini");+ let voice = setting(s, "elevenlabsVoice", "brian");+ let secret = eleven_client_secret(&key, &model, &voice).await?;+ Profile {+ url: "wss://api.elevenlabs.io/v1/convai/realtime".into(),+ headers: vec![("authorization", format!("Bearer {secret}"))],+ model, dialect: Dialect::Ga, in_rate: 24_000, out_rate: 24_000, voice, transcribe: None,+ }+ }+ other => return Err(format!("{other} isn't a realtime voice engine")),+ })+}++/// ElevenLabs Realtime is reached with a short-lived client secret minted with the API key.+async fn eleven_client_secret(key: &str, model: &str, voice: &str) -> Result<String, String> {+ let body = json!({+ "session": { "type": "realtime", "model": model, "audio": { "output": { "voice": voice } } },+ "expires_after": { "anchor": "created_at", "seconds": 600 },+ });+ let key = key.to_string();+ tokio::task::spawn_blocking(move || -> Result<String, String> {+ let mut res = ureq::post("https://api.elevenlabs.io/v1/convai/realtime/client_secrets")+ .header("xi-api-key", &key)+ .header("content-type", "application/json")+ .send(body.to_string().as_bytes())+ .map_err(|e| format!("ElevenLabs: {e}"))?;+ let v: Value = serde_json::from_str(&res.body_mut().read_to_string().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;+ v.get("value").and_then(Value::as_str).map(str::to_string).ok_or_else(|| "ElevenLabs didn't return a session secret".into())+ })+ .await+ .map_err(|e| e.to_string())?+}++fn session(p: &Profile, cfg: &LinkConfig) -> Value {+ let tools: Vec<Value> = cfg.tools.as_array().cloned().unwrap_or_default();+ match p.dialect {+ Dialect::Ga => {+ let mut input = json!({+ "format": { "type": "audio/pcm", "rate": p.in_rate },+ "turn_detection": { "type": "server_vad", "interrupt_response": true, "create_response": true },+ });+ if let Some(t) = &p.transcribe { input["transcription"] = json!({ "model": t }); }+ json!({ "type": "session.update", "session": {+ "type": "realtime", "model": p.model, "instructions": cfg.instructions,+ "audio": { "input": input, "output": { "format": { "type": "audio/pcm", "rate": p.out_rate }, "voice": p.voice } },+ "tools": tools,+ } })+ }+ Dialect::Grok => json!({ "type": "session.update", "session": {+ "instructions": cfg.instructions, "voice": p.voice,+ "turn_detection": { "type": "server_vad" },+ "audio": {+ "input": { "format": { "type": "audio/pcm", "rate": p.in_rate }, "transcription": { "model": p.transcribe } },+ "output": { "format": { "type": "audio/pcm", "rate": p.out_rate } },+ },+ "tools": tools,+ } }),+ Dialect::Beta => json!({ "type": "session.update", "session": {+ "modalities": ["text", "audio"], "voice": p.voice, "instructions": cfg.instructions,+ "input_audio_format": "pcm", "output_audio_format": "pcm",+ "turn_detection": { "type": "server_vad", "silence_duration_ms": 700 },+ "input_audio_transcription": { "model": p.transcribe },+ "tools": tools.iter().map(|t| json!({ "type": "function", "function": {+ "name": t.get("name"), "description": t.get("description"), "parameters": t.get("parameters") } })).collect::<Vec<_>>(),+ } }),+ }+}++/// An instruction the model should respond to now (status update, approval, greeting).+fn instruct(p: &Profile, text: &str) -> Vec<Value> {+ match p.dialect {+ // Qwen has no user text items: steer the next response directly.+ Dialect::Beta => vec![json!({ "type": "response.create", "response": { "instructions": text } })],+ _ => vec![+ json!({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] } }),+ json!({ "type": "response.create" }),+ ],+ }+}++pub async fn open(cfg: LinkConfig) -> Result<Link, String> {+ let p = profile(&cfg.settings).await?;+ let sock = ws::connect(&p.url, &p.headers).await.map_err(|e| format!("couldn't reach the voice model: {e}"))?;+ let (mut tx, mut rx) = sock.split();+ let (cmd_tx, mut cmd_rx) = mpsc::unbounded_channel::<LinkCmd>();+ let (ev_tx, ev_rx) = mpsc::unbounded_channel::<LinkEvent>();++ tx.send(Message::text(session(&p, &cfg).to_string())).await.map_err(|e| e.to_string())?;++ let (in_rate, dialect) = (p.in_rate, p.dialect);+ let p2 = Profile { url: String::new(), headers: vec![], model: p.model.clone(), dialect: p.dialect, in_rate: p.in_rate, out_rate: p.out_rate, voice: p.voice.clone(), transcribe: None };+ tokio::spawn(async move {+ while let Some(c) = cmd_rx.recv().await {+ let msgs: Vec<Value> = match c {+ LinkCmd::Audio(frame) => vec![json!({ "type": "input_audio_buffer.append", "audio": b64(&resample(&frame, CALL_RATE, in_rate)) })],+ LinkCmd::Instruct(text) => instruct(&p2, &text),+ LinkCmd::Say(text) => instruct(&p2, &format!("[Say this to the caller, in your own natural voice] {text}")),+ LinkCmd::ToolResult { id, output } => vec![+ json!({ "type": "conversation.item.create", "item": { "type": "function_call_output", "call_id": id, "output": output } }),+ json!({ "type": "response.create" }),+ ],+ // Server VAD already interrupts the response; nothing to send.+ LinkCmd::Cancel => vec![],+ };+ for m in msgs {+ if tx.send(Message::text(m.to_string())).await.is_err() { return; }+ }+ }+ let _ = tx.close().await;+ });++ let out_rate = p.out_rate;+ tokio::spawn(async move {+ while let Some(m) = rx.next().await {+ let Ok(m) = m else { break };+ if m.is_close() {+ let reason = m.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ let _ = ev_tx.send(LinkEvent::Closed(crate::voice::explain_close(&reason)));+ return;+ }+ let Some(t) = m.as_text() else { continue };+ let Ok(v) = serde_json::from_str::<Value>(t) else { continue };+ let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();+ let e = match s("type").as_str() {+ "response.created" => Some(LinkEvent::ResponseStarted),+ "response.done" | "response.cancelled" => Some(LinkEvent::ResponseDone),+ "response.output_audio.delta" | "response.audio.delta" => {+ let pcm = pcm_from_bytes(&unb64(&s("delta")));+ Some(LinkEvent::Audio(resample(&pcm, out_rate, CALL_RATE)))+ }+ "input_audio_buffer.speech_started" => Some(LinkEvent::SpeechStarted),+ "conversation.item.input_audio_transcription.completed" => Some(LinkEvent::UserText(s("transcript").trim().to_string())),+ "response.output_audio_transcript.done" | "response.audio_transcript.done" => Some(LinkEvent::AssistantText(s("transcript").trim().to_string())),+ "response.function_call_arguments.done" => Some(LinkEvent::ToolCall {+ id: s("call_id"),+ name: s("name"),+ args: serde_json::from_str(&s("arguments")).unwrap_or(json!({})),+ }),+ "error" => {+ crate::log(format!("voice model error: {}", v.get("error").map(|e| e.to_string()).unwrap_or_default()));+ None+ }+ _ => None,+ };+ if let Some(e) = e {+ if ev_tx.send(e).is_err() { break; }+ }+ }+ let _ = dialect;+ let _ = ev_tx.send(LinkEvent::Closed("the voice model disconnected".into()));+ });++ Ok(Link { brain: Brain::Voice, cmd: cmd_tx, events: ev_rx })+}diff --git a/plugins/whatsapp/companion/src/links/stt.rs b/plugins/whatsapp/companion/src/links/stt.rsnew file mode 100644index 00000000..db0db7cf--- /dev/null+++ b/plugins/whatsapp/companion/src/links/stt.rs@@ -0,0 +1,191 @@+//! Streaming speech-to-text for the pipeline: Deepgram, AssemblyAI,+//! ElevenLabs Scribe, Sarvam. Each turns caller audio (16 kHz PCM16) into+//! "speech started" and "finished utterance" events.++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use whatsapp_rust::futures::{SinkExt, StreamExt};++use super::{b64, pcm_bytes, setting, env_key, ws};++pub enum SttEvent {+ SpeechStarted,+ Final(String),+ Closed(String),+}++pub fn key_name(provider: &str) -> Option<&'static str> {+ match provider {+ "deepgram" => Some("DEEPGRAM_API_KEY"),+ "assemblyai" => Some("ASSEMBLYAI_API_KEY"),+ "elevenlabs" => Some("ELEVENLABS_API_KEY"),+ "sarvam" => Some("SARVAM_API_KEY"),+ _ => None,+ }+}++pub fn label(provider: &str) -> String {+ match provider {+ "deepgram" => "Deepgram",+ "assemblyai" => "AssemblyAI",+ "elevenlabs" => "ElevenLabs",+ "sarvam" => "Sarvam",+ other => other,+ }+ .to_string()+}++/// Start listening. Audio goes in on the returned sender; events come out on `events`.+pub async fn start(settings: &Value, events: mpsc::UnboundedSender<SttEvent>) -> Result<mpsc::UnboundedSender<Vec<i16>>, String> {+ let provider = setting(settings, "sttProvider", "deepgram");+ let lang = setting(settings, "sttLanguage", "auto");+ let key = env_key(key_name(&provider).ok_or_else(|| format!("unknown speech-to-text provider {provider}"))?)+ .ok_or_else(|| format!("{} needs its API key", label(&provider)))?;++ let (url, headers): (String, Vec<(&str, String)>) = match provider.as_str() {+ "deepgram" => {+ // Nova-3: "multi" covers en/hi and others; Urdu needs language=ur on its own.+ let language = if lang == "auto" { "multi".to_string() } else { lang.clone() };+ (+ format!("wss://api.deepgram.com/v1/listen?model={}&encoding=linear16&sample_rate=16000&channels=1&language={language}&interim_results=true&endpointing=400&utterance_end_ms=1000&vad_events=true&smart_format=true", setting(settings, "sttModel", "nova-3")),+ vec![("authorization", format!("Token {key}"))],+ )+ }+ "assemblyai" => {+ let detect = if lang == "auto" { "&language_detection=true".to_string() } else { format!("&language_codes={lang}") };+ (+ format!("wss://streaming.assemblyai.com/v3/ws?speech_model={}&sample_rate=16000&encoding=pcm_s16le&min_turn_silence=500{detect}", setting(settings, "sttModel", "universal-3-6-pro")),+ vec![("authorization", key)],+ )+ }+ "elevenlabs" => {+ let language = if lang == "auto" { String::new() } else { format!("&language_code={lang}") };+ (+ format!("wss://api.elevenlabs.io/v1/speech-to-text/realtime?model_id={}&audio_format=pcm_16000&commit_strategy=vad&vad_silence_threshold_secs=0.6{language}", setting(settings, "sttModel", "scribe_v2_realtime")),+ vec![("xi-api-key", key)],+ )+ }+ "sarvam" => {+ let language = match lang.as_str() { "auto" => "unknown".to_string(), l if l.contains('-') => l.to_string(), l => format!("{l}-IN") };+ (+ format!("wss://api.sarvam.ai/speech-to-text/ws?model={}&language-code={language}&sample_rate=16000&input_audio_codec=pcm_s16le&vad_signals=true&high_vad_sensitivity=true&mode=transcribe", setting(settings, "sttModel", "saaras:v4")),+ vec![("api-subscription-key", key)],+ )+ }+ other => return Err(format!("unknown speech-to-text provider {other}")),+ };++ let sock = ws::connect(&url, &headers).await.map_err(|e| format!("couldn't reach {}: {e}", label(&provider)))?;+ let (mut tx, mut rx) = sock.split();+ let (audio_tx, mut audio_rx) = mpsc::unbounded_channel::<Vec<i16>>();++ let p = provider.clone();+ tokio::spawn(async move {+ let mut keepalive = tokio::time::interval(std::time::Duration::from_secs(5));+ loop {+ tokio::select! {+ frame = audio_rx.recv() => {+ let Some(frame) = frame else { break };+ let msg = match p.as_str() {+ "elevenlabs" => Message::text(json!({ "message_type": "input_audio_chunk", "audio_base_64": b64(&frame), "commit": false, "sample_rate": 16000 }).to_string()),+ "sarvam" => Message::text(json!({ "audio": { "data": b64(&frame), "sample_rate": "16000", "encoding": "audio/wav" } }).to_string()),+ _ => Message::binary(pcm_bytes(&frame)),+ };+ if tx.send(msg).await.is_err() { break; }+ }+ _ = keepalive.tick() => {+ if p == "deepgram" && tx.send(Message::text(json!({ "type": "KeepAlive" }).to_string())).await.is_err() { break; }+ }+ }+ }+ let close = match p.as_str() {+ "deepgram" => Some(json!({ "type": "CloseStream" })),+ "assemblyai" => Some(json!({ "type": "Terminate" })),+ _ => None,+ };+ if let Some(c) = close { let _ = tx.send(Message::text(c.to_string())).await; }+ let _ = tx.close().await;+ });++ tokio::spawn(async move {+ // Deepgram sends final segments; an utterance ends at speech_final / UtteranceEnd.+ let mut pending = String::new();+ let mut speaking = false;+ while let Some(msg) = rx.next().await {+ let Ok(msg) = msg else { break };+ if msg.is_close() {+ let reason = msg.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();+ let _ = events.send(SttEvent::Closed(if reason.is_empty() { format!("{} closed the connection", label(&provider)) } else { format!("{}: {reason}", label(&provider)) }));+ return;+ }+ let Some(text) = msg.as_text() else { continue };+ let Ok(v) = serde_json::from_str::<Value>(text) else { continue };+ let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();+ match provider.as_str() {+ "deepgram" => match s("type").as_str() {+ "SpeechStarted" => { let _ = events.send(SttEvent::SpeechStarted); }+ "Results" => {+ let t = v.pointer("/channel/alternatives/0/transcript").and_then(Value::as_str).unwrap_or("").trim().to_string();+ if !t.is_empty() && !speaking { speaking = true; let _ = events.send(SttEvent::SpeechStarted); }+ if v.get("is_final").and_then(Value::as_bool) == Some(true) && !t.is_empty() {+ if !pending.is_empty() { pending.push(' '); }+ pending.push_str(&t);+ }+ if v.get("speech_final").and_then(Value::as_bool) == Some(true) && !pending.is_empty() {+ let _ = events.send(SttEvent::Final(std::mem::take(&mut pending)));+ speaking = false;+ }+ }+ "UtteranceEnd" => {+ if !pending.is_empty() { let _ = events.send(SttEvent::Final(std::mem::take(&mut pending))); }+ speaking = false;+ }+ "Error" => crate::log(format!("deepgram: {}", s("description"))),+ _ => {}+ },+ "assemblyai" => match s("type").as_str() {+ "SpeechStarted" => { let _ = events.send(SttEvent::SpeechStarted); }+ "Turn" => {+ let t = s("transcript");+ if !t.trim().is_empty() && !speaking { speaking = true; let _ = events.send(SttEvent::SpeechStarted); }+ if v.get("end_of_turn").and_then(Value::as_bool) == Some(true) {+ let u = if s("utterance").trim().is_empty() { t } else { s("utterance") };+ if !u.trim().is_empty() { let _ = events.send(SttEvent::Final(u.trim().to_string())); }+ speaking = false;+ }+ }+ "Termination" => break,+ _ => {}+ },+ "elevenlabs" => match s("message_type").as_str() {+ "partial_transcript" => {+ if !s("text").trim().is_empty() && !speaking { speaking = true; let _ = events.send(SttEvent::SpeechStarted); }+ }+ "committed_transcript" | "committed_transcript_with_timestamps" => {+ let t = s("text");+ if !t.trim().is_empty() { let _ = events.send(SttEvent::Final(t.trim().to_string())); }+ speaking = false;+ }+ "session_started" => {}+ kind => if v.get("error").is_some() { crate::log(format!("elevenlabs stt {kind}: {}", s("error"))); },+ },+ "sarvam" => match s("type").as_str() {+ "events" => {+ if v.pointer("/data/signal_type").and_then(Value::as_str) == Some("START_SPEECH") { let _ = events.send(SttEvent::SpeechStarted); }+ }+ "data" => {+ let t = v.pointer("/data/transcript").and_then(Value::as_str).unwrap_or("").trim().to_string();+ if !t.is_empty() { let _ = events.send(SttEvent::Final(t)); }+ }+ "error" => crate::log(format!("sarvam stt: {}", v.pointer("/data/error").and_then(Value::as_str).unwrap_or(""))),+ _ => {}+ },+ _ => {}+ }+ }+ let _ = events.send(SttEvent::Closed(format!("{} disconnected", label(&provider))));+ });++ Ok(audio_tx)+}diff --git a/plugins/whatsapp/companion/src/links/tts.rs b/plugins/whatsapp/companion/src/links/tts.rsnew file mode 100644index 00000000..a9a61baf--- /dev/null+++ b/plugins/whatsapp/companion/src/links/tts.rs@@ -0,0 +1,198 @@+//! Streaming text-to-speech for the pipeline: Cartesia, ElevenLabs, MiniMax,+//! Sarvam, Deepgram. One connection per utterance, so cancelling (barge-in)+//! is just dropping the task: nothing half-spoken can leak into the next reply.++use serde_json::{Value, json};+use tokio::sync::mpsc;+use tokio_websockets::Message;+use whatsapp_rust::futures::{SinkExt, StreamExt};++use super::{env_key, pcm_from_bytes, script_language, setting, strip_wav, unb64, ws};++pub fn key_name(provider: &str) -> Option<&'static str> {+ match provider {+ "cartesia" => Some("CARTESIA_API_KEY"),+ "elevenlabs" => Some("ELEVENLABS_API_KEY"),+ "minimax" => Some("MINIMAX_API_KEY"),+ "sarvam" => Some("SARVAM_API_KEY"),+ "deepgram" => Some("DEEPGRAM_API_KEY"),+ _ => None,+ }+}++pub fn label(provider: &str) -> String {+ match provider {+ "cartesia" => "Cartesia",+ "elevenlabs" => "ElevenLabs",+ "minimax" => "MiniMax",+ "sarvam" => "Sarvam",+ "deepgram" => "Deepgram",+ other => other,+ }+ .to_string()+}++fn default_voice(provider: &str) -> &'static str {+ match provider {+ "cartesia" => "a0e99841-438c-4a64-b679-ae501e7d6091",+ "elevenlabs" => "JBFqnCBsd6RMkjVDRZzb",+ "minimax" => "English_expressive_narrator",+ "sarvam" => "shubh",+ "deepgram" => "aura-2-thalia-en",+ _ => "",+ }+}++/// Speak `text`: 16 kHz PCM16 chunks go to `out` as they arrive. Returns when done.+pub async fn speak(settings: &Value, text: &str, out: &mpsc::UnboundedSender<Vec<i16>>) -> Result<(), String> {+ let provider = setting(settings, "ttsProvider", "cartesia");+ let key = env_key(key_name(&provider).ok_or_else(|| format!("unknown voice provider {provider}"))?)+ .ok_or_else(|| format!("{} needs its API key", label(&provider)))?;+ let voice = setting(settings, "ttsVoice", default_voice(&provider));+ let lang = script_language(text);+ let fail = |e: String| format!("{}: {e}", label(&provider));++ match provider.as_str() {+ "cartesia" => {+ let mut sock = ws::connect("wss://api.cartesia.ai/tts/websocket", &[("x-api-key", key), ("cartesia-version", "2026-08-14".into())]).await.map_err(fail)?;+ let req = json!({+ "model_id": setting(settings, "ttsModel", "sonic-3.6"),+ "transcript": text,+ "voice": { "id": voice },+ "language": lang,+ "context_id": format!("u{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)),+ "output_format": { "container": "raw", "encoding": "pcm_s16le", "sample_rate": 16000 },+ "continue": false,+ });+ sock.send(Message::text(req.to_string())).await.map_err(|e| fail(e.to_string()))?;+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ match v.get("type").and_then(Value::as_str) {+ Some("chunk") => if let Some(d) = v.get("data").and_then(Value::as_str) { let _ = out.send(pcm_from_bytes(&unb64(d))); },+ Some("done") => break,+ Some("error") => return Err(fail(v.get("message").and_then(Value::as_str).unwrap_or("error").to_string())),+ _ => {}+ }+ }+ let _ = sock.close().await;+ }+ "elevenlabs" => {+ let url = format!(+ "wss://api.elevenlabs.io/v1/text-to-speech/{voice}/stream-input?model_id={}&output_format=pcm_16000&inactivity_timeout=30",+ setting(settings, "ttsModel", "eleven_flash_v2_5")+ );+ let mut sock = ws::connect(&url, &[("xi-api-key", key)]).await.map_err(fail)?;+ for msg in [json!({ "text": " " }), json!({ "text": format!("{text} "), "flush": true }), json!({ "text": "" })] {+ sock.send(Message::text(msg.to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ if let Some(a) = v.get("audio").and_then(Value::as_str) { let _ = out.send(pcm_from_bytes(&unb64(a))); }+ if v.get("isFinal").and_then(Value::as_bool) == Some(true) { break; }+ if let Some(e) = v.get("error").and_then(Value::as_str) { return Err(fail(e.to_string())); }+ }+ }+ "minimax" => {+ let mut sock = ws::connect("wss://api.minimax.io/ws/v1/t2a_v2", &[("authorization", format!("Bearer {key}"))]).await.map_err(fail)?;+ let boost = match lang { "hi" => "Hindi", _ => "auto" };+ let mut started = false;+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ match v.get("event").and_then(Value::as_str) {+ Some("connected_success") => {+ let start = json!({+ "event": "task_start",+ "model": setting(settings, "ttsModel", "speech-2.8-turbo"),+ "language_boost": boost,+ "voice_setting": { "voice_id": voice, "speed": 1, "vol": 1, "pitch": 0 },+ "audio_setting": { "sample_rate": 16000, "format": "pcm", "channel": 1 },+ });+ sock.send(Message::text(start.to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ Some("task_started") if !started => {+ started = true;+ sock.send(Message::text(json!({ "event": "task_continue", "text": text }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ sock.send(Message::text(json!({ "event": "task_finish" }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ Some("task_failed") => return Err(fail(v.pointer("/base_resp/status_msg").and_then(Value::as_str).unwrap_or("failed").to_string())),+ Some("task_finished") => break,+ _ => {+ if let Some(h) = v.pointer("/data/audio").and_then(Value::as_str) {+ let _ = out.send(pcm_from_bytes(&hex_decode(h)));+ }+ if v.get("is_final").and_then(Value::as_bool) == Some(true) { break; }+ }+ }+ }+ }+ "sarvam" => {+ let url = format!("wss://api.sarvam.ai/text-to-speech/ws?model={}&send_completion_event=true", setting(settings, "ttsModel", "bulbul:v3"));+ let mut sock = ws::connect(&url, &[("api-subscription-key", key)]).await.map_err(fail)?;+ let language_code = match lang { "hi" => "hi-IN", _ => "en-IN" };+ let msgs = [+ json!({ "type": "config", "data": { "model": setting(settings, "ttsModel", "bulbul:v3"), "language_code": language_code, "speaker": voice, "pace": 1.0, "speech_sample_rate": 16000, "output_audio_codec": "linear16" } }),+ json!({ "type": "text", "data": { "text": text } }),+ json!({ "type": "flush" }),+ ];+ for msg in msgs {+ sock.send(Message::text(msg.to_string())).await.map_err(|e| fail(e.to_string()))?;+ }+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ match v.get("type").and_then(Value::as_str) {+ Some("audio") => if let Some(a) = v.pointer("/data/audio").and_then(Value::as_str) { let bytes = unb64(a); let _ = out.send(pcm_from_bytes(strip_wav(&bytes))); },+ Some("event") if v.pointer("/data/event_type").and_then(Value::as_str) == Some("final") => break,+ Some("error") => return Err(fail(v.pointer("/data/message").and_then(Value::as_str).unwrap_or("error").to_string())),+ _ => {}+ }+ }+ let _ = sock.close().await;+ }+ "deepgram" => {+ let url = format!("wss://api.deepgram.com/v1/speak?model={voice}&encoding=linear16&sample_rate=16000");+ let mut sock = ws::connect(&url, &[("authorization", format!("Token {key}"))]).await.map_err(fail)?;+ sock.send(Message::text(json!({ "type": "Speak", "text": text }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ sock.send(Message::text(json!({ "type": "Flush" }).to_string())).await.map_err(|e| fail(e.to_string()))?;+ while let Some(m) = sock.next().await {+ let m = m.map_err(|e| fail(e.to_string()))?;+ if m.is_close() { break; }+ if m.is_binary() {+ let _ = out.send(pcm_from_bytes(&m.as_payload().to_vec()));+ continue;+ }+ let Some(t) = m.as_text() else { continue };+ let v: Value = serde_json::from_str(t).unwrap_or_default();+ if v.get("type").and_then(Value::as_str) == Some("Flushed") { break; }+ }+ let _ = sock.send(Message::text(json!({ "type": "Close" }).to_string())).await;+ }+ other => return Err(format!("unknown voice provider {other}")),+ }+ Ok(())+}++fn hex_decode(h: &str) -> Vec<u8> {+ let b = h.as_bytes();+ (0..b.len() / 2)+ .filter_map(|i| u8::from_str_radix(std::str::from_utf8(&b[i * 2..i * 2 + 2]).ok()?, 16).ok())+ .collect()+}++#[cfg(test)]+mod tests {+ #[test]+ fn hex() {+ assert_eq!(super::hex_decode("00ff10"), vec![0, 255, 16]);+ }+}diff --git a/plugins/whatsapp/companion/src/links/ws.rs b/plugins/whatsapp/companion/src/links/ws.rsnew file mode 100644index 00000000..6514c66b--- /dev/null+++ b/plugins/whatsapp/companion/src/links/ws.rs@@ -0,0 +1,18 @@+//! WebSocket connect with custom headers (rustls + ring, like whatsapp-rust).++use tokio_websockets::{ClientBuilder, MaybeTlsStream, WebSocketStream};+use tokio::net::TcpStream;++pub type Socket = WebSocketStream<MaybeTlsStream<TcpStream>>;++pub async fn connect(url: &str, headers: &[(&str, String)]) -> Result<Socket, String> {+ let uri: http::Uri = url.parse().map_err(|e| format!("bad URL: {e}"))?;+ let mut b = ClientBuilder::from_uri(uri);+ for (name, value) in headers {+ let n = http::HeaderName::from_bytes(name.as_bytes()).map_err(|e| e.to_string())?;+ let v = http::HeaderValue::from_str(value).map_err(|e| e.to_string())?;+ b = b.add_header(n, v).map_err(|e| e.to_string())?;+ }+ let (ws, _) = b.connect().await.map_err(|e| e.to_string())?;+ Ok(ws)+}diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rsindex f863b950..49ddf998 100644--- a/plugins/whatsapp/companion/src/main.rs+++ b/plugins/whatsapp/companion/src/main.rs@@ -10,6 +10,7 @@//!//! stdout is the protocol channel: logs go to stderr only.+mod links;mod voice;use std::collections::HashMap;diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rsindex aac64d45..e0245f2b 100644--- a/plugins/whatsapp/companion/src/voice.rs+++ b/plugins/whatsapp/companion/src/voice.rs@@ -12,21 +12,16 @@ 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::links::{self, Brain, Link, LinkCmd, LinkConfig, LinkEvent};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);// Long enough for a turn that waits on the owner's approval; Mercury itself replies@@ -44,48 +39,18 @@ 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)+/// Why calls can't run with the current voice settings (missing key), if anything.+pub fn voice_problem() -> Option<String> {+ links::not_ready(&settings())}-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"))+pub fn voice_ready() -> bool {+ voice_problem().is_none()}-/// 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) {@@ -113,7 +78,7 @@ pub async fn on_offer(st: Arc<State>, client: Arc<Client>, call: Box<IncomingCal}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))+ .request("mercury/call/incoming", json!({ "callId": call_id, "from": from, "fromPhone": from_phone, "video": is_video, "voiceReady": voice_ready(), "voiceProblem": voice_problem() }), 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) {@@ -142,8 +107,8 @@ pub async fn call_owner(st: Arc<State>, args: &Value) -> Result<String, 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());+ if let Some(problem) = voice_problem() {+ return Err(format!("Can't call: {problem}."));}let owner: String = setting_str("owner", "").chars().filter(char::is_ascii_digit).collect();if owner.len() < 6 {@@ -198,7 +163,7 @@ pub async fn call_owner(st: Arc<State>, args: &Value) -> Result<String, String>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 {+fn instructions_for(instructions: &str) -> String {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. \You don't know today's news or anything current yourself: for news, facts that may have changed, the user's own things \@@ -209,37 +174,26 @@ fn session_config(instructions: &str) -> Value {The user can send photos and documents in the WhatsApp chat during the call: Mercury can see them, so for 'what's in this photo?' call ask_mercury. \Some actions need the user's approval. When you get an approval request, ask the user plainly whether to go ahead, wait for their answer, \then call answer_approval. Never answer an approval yourself: only the user's own words count. \- Only actions that change something need the user's approval, which can't be given on a call; if ask_mercury says so, offer to do it by message. 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": {} } },- {- "type": "function",- "name": "answer_approval",- "description": "Report the user's answer to the approval you just asked them about. Only call it after they answered out loud.",- "parameters": { "type": "object", "properties": { "approved": { "type": "boolean", "description": "true only if the user clearly said yes" } }, "required": ["approved"] },- },- ],+ When the user says goodbye or is done, say goodbye and call end_call.";+ if instructions.is_empty() { base.to_string() } else { format!("{base}\n\n{instructions}") }+}++fn tools() -> Value {+ json!([+ {+ "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": {} } },+ {+ "type": "function",+ "name": "answer_approval",+ "description": "Report the user's answer to the approval you just asked them about. Only call it after they answered out loud.",+ "parameters": { "type": "object", "properties": { "approved": { "type": "boolean", "description": "true only if the user clearly said yes" } }, "required": ["approved"] },+ },+ ])}#[allow(clippy::too_many_arguments)]@@ -255,11 +209,10 @@ async fn run_session() {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 {+ let outcome = match bridge(&st, &handle, mic_tx, spk_rx, &call_id, direction, &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}")}@@ -275,6 +228,11 @@ async fn run_session(}));}+/// Words for a pipeline voice to say where a reasoning model would get an instruction.+fn spoken_status(n: u32, doing: &str) -> String {+ if n == 1 { format!("This one takes a few seconds, I'm {doing}. Stay on the line.") } else { format!("Still {doing}, almost there.") }+}+#[allow(clippy::too_many_arguments)]async fn bridge(st: &Arc<State>,@@ -282,48 +240,30 @@ async fn bridge(mic_tx: async_channel::Sender<Vec<i16>>,spk_rx: async_channel::Receiver<Vec<i16>>,call_id: &str,+ direction: &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" }));+ let cfg = LinkConfig { instructions: instructions_for(instructions), tools: tools(), settings: settings() };+ let mut link = links::open(cfg).await?;+ let brain = link.brain;++ // Greeting: a reasoning model is told the situation; a pipeline voice just says hello.+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(format!("[Call context, not spoken by the user] {opener}"))),+ Brain::Mercury => link.send(LinkCmd::Say(if direction == "outgoing" { format!("Hi, it's Mercury. {}", opener_reason(opener)) } else { "Hi, it's Mercury. How can I help?".into() })),+ }- // Caller → model.- let up_q = send_q.clone();+ // Caller → voice.+ let up = link.cmd.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;- }+ if up.send(LinkCmd::Audio(frame)).is_err() { break; }}});- // Model → caller, paced at one 60 ms frame per tick.+ // Voice → 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 {@@ -338,25 +278,20 @@ async fn bridge(f.resize(FRAME, 0);f};- if mic_tx.send(frame).await.is_err() {- break;- }+ if mic_tx.send(frame).await.is_err() { break; }}});- // Questions Mercury is still working on: (asked at, last spoken update, updates so far).let pending: Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>> = Arc::new(std::sync::Mutex::new(HashMap::new()));let mut responding = false;- // Answers from Mercury, spoken as soon as the voice is free (only one response may be active).let (answer_tx, mut answer_rx) = mpsc::unbounded_channel::<(String, String)>();let mut ready_answers: VecDeque<(String, String)> = VecDeque::new();- // The approval being asked out loud right now, and what the user has said since (transcripts).let mut awaiting: Option<(String, Instant)> = None;let mut user_said: Vec<(Instant, String)> = Vec::new();- // A spoken "yes" waiting for its transcript: (function call id, approval id, asked at, deadline).let mut verifying: Option<(String, String, Instant, Instant)> = None;let mut status_tick = tokio::time::interval(Duration::from_secs(1));status_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+ let mut ask_seq = 0u32;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));@@ -365,13 +300,35 @@ async fn bridge(tokio::pin!(ended);let mut hang_up = false;+ // Ask Mercury a question; the answer comes back on answer_tx.+ let ask = |q: String, id: String, pending: &Arc<std::sync::Mutex<HashMap<String, (Instant, Instant, u32)>>>| {+ let st2 = st.clone();+ let tx2 = answer_tx.clone();+ let call_id2 = call_id.to_string();+ let now = Instant::now();+ pending.lock().unwrap().insert(id.clone(), (now, now, 0));+ st.call_activity.lock().unwrap().remove(call_id);+ let pending2 = pending.clone();+ 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());+ pending2.lock().unwrap().remove(&id);+ let _ = tx2.send((id, answer));+ });+ };+let result = loop {tokio::select! {_ = &mut ended => break Ok(()),_ = &mut deadline => { hang_up = true; break Ok(()) }Some(a) = answer_rx.recv() => {+ // A newer question replaced this one: don't speak the stale answer.+ if a.1.starts_with("(superseded") { continue; }ready_answers.push_back(a);- if !responding { deliver(&send_q, &mut ready_answers, &mut responding); }+ if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }}_ = status_tick.tick() => {if let Some((fc, _id, _asked, deadline)) = verifying.clone() {@@ -381,23 +338,22 @@ async fn bridge(}}if !responding && !ready_answers.is_empty() {- deliver(&send_q, &mut ready_answers, &mut responding);+ deliver(&link, brain, &mut ready_answers, &mut responding);continue;}if responding || !playout.lock().unwrap().is_empty() { continue; }- // Mercury needs the user's go-ahead: ask out loud.if awaiting.is_none() {let next = st.call_approvals.lock().unwrap().get_mut(call_id).and_then(|l| if l.is_empty() { None } else { Some(l.remove(0)) });if let Some((id, prompt)) = next {awaiting = Some((id, Instant::now()));- let text = format!("[Approval needed, not said by the user] Mercury wants to: {prompt}. Ask the user plainly, in one or two sentences, whether to go ahead. Then wait for their answer and call answer_approval. (They can also reply 1 in the WhatsApp chat.)");- let _ = send_q.send(json!({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] } }));- let _ = send_q.send(json!({ "type": "response.create" }));+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(format!("[Approval needed, not said by the user] Mercury wants to: {prompt}. Ask the user plainly, in one or two sentences, whether to go ahead. Then wait for their answer and call answer_approval. (They can also reply 1 in the WhatsApp chat.)"))),+ Brain::Mercury => link.send(LinkCmd::Say(format!("I need your go-ahead to {prompt}. Should I do it? Say yes or no, or reply 1 in the chat."))),+ }responding = true;continue;}}- // Something arrived in the chat (a photo, a document, an approval given there): let the voice mention it.let context = st.call_context.lock().unwrap().remove(call_id);if let Some(mut notes) = context.filter(|n| !n.is_empty()) {for n in notes.iter_mut() {@@ -407,14 +363,13 @@ async fn bridge(*n = text.to_string();}}- let text = format!("[Status update, not said by the user] {} Acknowledge it in one short sentence (for example 'Got your photo, want me to take a look?'), unless they're mid-sentence.", notes.join(" "));- let _ = send_q.send(json!({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] } }));- let _ = send_q.send(json!({ "type": "response.create" }));+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(format!("[Status update, not said by the user] {} Acknowledge it in one short sentence (for example 'Got your photo, want me to take a look?'), unless they're mid-sentence.", notes.join(" ")))),+ Brain::Mercury => link.send(LinkCmd::Say(if notes.iter().any(|n| n.contains("sent")) { "Got it, I can see what you sent. Ask me about it whenever you like.".into() } else { "Okay, noted.".into() })),+ }responding = true;continue;}- // Keep the caller company while a lookup runs: a short spoken update- // after ~8s, then every ~14s, never over the model or the caller.let due = {let mut p = pending.lock().unwrap();let now = Instant::now();@@ -429,66 +384,72 @@ async fn bridge(};if let Some((n, secs)) = due {let doing = st.call_activity.lock().unwrap().get(call_id).cloned().unwrap_or_else(|| "working on it".into());- let text = if n == 1 {- format!("[Status update, not said by the user] Mercury is still {doing}. Tell the user in one short sentence that it's taking a few seconds and they can stay on the line.")- } else {- format!("[Status update, not said by the user] After {secs} seconds Mercury is still {doing}. Give the user one short, natural update (don't repeat yourself) so they know you're still there.")- };- let _ = send_q.send(json!({ "type": "conversation.item.create", "item": { "type": "message", "role": "user", "content": [{ "type": "input_text", "text": text }] } }));- let _ = send_q.send(json!({ "type": "response.create" }));+ match brain {+ Brain::Voice => link.send(LinkCmd::Instruct(if n == 1 {+ format!("[Status update, not said by the user] Mercury is still {doing}. Tell the user in one short sentence that it's taking a few seconds and they can stay on the line.")+ } else {+ format!("[Status update, not said by the user] After {secs} seconds Mercury is still {doing}. Give the user one short, natural update (don't repeat yourself) so they know you're still there.")+ })),+ Brain::Mercury => link.send(LinkCmd::Say(spoken_status(n, &doing))),+ }responding = true;}}- msg = ws_rx.next() => {- let Some(Ok(msg)) = msg else { break Err("the voice model disconnected".to_string()) };- if msg.is_close() {- let reason = msg.as_close().map(|(_, r)| r.to_string()).unwrap_or_default();- break Err(explain_close(&reason));- }- 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.created" => responding = true,- "response.done" | "response.cancelled" => {+ ev = link.events.recv() => {+ let Some(ev) = ev else { break Err("the voice connection ended".to_string()) };+ match ev {+ LinkEvent::Closed(reason) => break Err(reason),+ LinkEvent::ResponseStarted => responding = true,+ LinkEvent::ResponseDone => {responding = false;- if !ready_answers.is_empty() { deliver(&send_q, &mut ready_answers, &mut responding); }+ if !ready_answers.is_empty() { deliver(&link, brain, &mut ready_answers, &mut responding); }}- "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);- }+ LinkEvent::Audio(pcm) => playout.lock().unwrap().extend(pcm),+ LinkEvent::SpeechStarted => {+ playout.lock().unwrap().clear();+ link.send(LinkCmd::Cancel);+ }+ LinkEvent::AssistantText(t) => {+ if !t.is_empty() { transcript.lock().await.push(json!({ "role": "mercury", "text": t })); }}- // 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() }));- user_said.push((Instant::now(), t.trim().to_string()));- if user_said.len() > 20 { user_said.remove(0); }- if let Some((fc, id, asked_at, _)) = verifying.clone() {+ LinkEvent::UserText(t) => {+ if t.is_empty() { continue; }+ transcript.lock().await.push(json!({ "role": "owner", "text": t.clone() }));+ user_said.push((Instant::now(), t.clone()));+ if user_said.len() > 20 { user_said.remove(0); }+ if let Some((fc, id, asked_at, _)) = verifying.clone() {+ if let Some(v) = spoken_verdict(&user_said, asked_at) {+ verifying = None;+ awaiting = None;+ let out = finalize_approval(st, call_id, &id, v).await;+ ready_answers.push_back((fc, out));+ if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }+ }+ continue;+ }+ if brain == Brain::Mercury {+ // No model of its own: the caller's words decide approvals, everything else is a Mercury turn.+ if let Some((id, asked_at)) = awaiting.clone() {if let Some(v) = spoken_verdict(&user_said, asked_at) {- verifying = None;awaiting = None;- let out = finalize_approval(st, call_id, &id, v).await;- ready_answers.push_back((fc, out));- if !responding { deliver(&send_q, &mut ready_answers, &mut responding); }+ finalize_approval(st, call_id, &id, v).await;+ link.send(LinkCmd::Say(if v { "Okay, going ahead.".into() } else { "Okay, I won't.".into() }));+ continue;}}+ if is_goodbye(&t) {+ link.send(LinkCmd::Say("Okay, bye for now!".into()));+ tokio::time::sleep(Duration::from_millis(2500)).await;+ hang_up = true;+ break Ok(());+ }+ ask_seq += 1;+ transcript.lock().await.push(json!({ "role": "ask_mercury", "text": t.clone() }));+ ask(t, format!("turn-{ask_seq}"), &pending);}}- "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!({}));+ LinkEvent::ToolCall { id, name, args } => {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;@@ -499,55 +460,30 @@ async fn bridge(if name == "answer_approval" {let approved = args.get("approved").and_then(Value::as_bool).unwrap_or(false);match awaiting.clone() {- None => {- ready_answers.push_back((fc_id, "No approval is waiting right now.".to_string()));- }- Some((id, asked_at)) => {- // The user's own words decide, not the model. Transcription can lag the- // model a little, so an undecided "yes" waits up to 3s for the transcript.- match (approved, spoken_verdict(&user_said, asked_at)) {- (false, _) | (true, Some(false)) => {- awaiting = None;- let out = finalize_approval(st, call_id, &id, false).await;- ready_answers.push_back((fc_id, out));- }- (true, Some(true)) => {- awaiting = None;- let out = finalize_approval(st, call_id, &id, true).await;- ready_answers.push_back((fc_id, out));- }- (true, None) => {- verifying = Some((fc_id, id, asked_at, Instant::now() + Duration::from_secs(3)));- }+ None => ready_answers.push_back((id, "No approval is waiting right now.".to_string())),+ Some((aid, asked_at)) => match (approved, spoken_verdict(&user_said, asked_at)) {+ (false, _) | (true, Some(false)) => {+ awaiting = None;+ let out = finalize_approval(st, call_id, &aid, false).await;+ ready_answers.push_back((id, out));}- }+ (true, Some(true)) => {+ awaiting = None;+ let out = finalize_approval(st, call_id, &aid, true).await;+ ready_answers.push_back((id, out));+ }+ (true, None) => verifying = Some((id, aid, asked_at, Instant::now() + Duration::from_secs(3))),+ },}- if !responding { deliver(&send_q, &mut ready_answers, &mut responding); }+ if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }continue;}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 = answer_tx.clone();- let call_id2 = call_id.to_string();- let now = Instant::now();- pending.lock().unwrap().insert(fc_id.clone(), (now, now, 0));- st.call_activity.lock().unwrap().remove(call_id);- let pending2 = pending.clone();- 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());- pending2.lock().unwrap().remove(&fc_id);- let _ = tx2.send((fc_id, answer));- });+ transcript.lock().await.push(json!({ "role": "ask_mercury", "text": q.clone() }));+ ask(q, id, &pending);}}- "error" => log(format!("voice model error: {}", ev.get("error").map(|e| e.to_string()).unwrap_or_default())),- _ => {}}}}@@ -555,14 +491,25 @@ async fn bridge(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}+/// An outgoing call's opener carries "Why you called: …"; a pipeline voice says just the reason.+fn opener_reason(opener: &str) -> String {+ opener.split("Why you called:").nth(1).map(|r| r.split(". Greet").next().unwrap_or(r).trim().to_string()).filter(|r| !r.is_empty())+ .map(|r| format!("I'm calling because {r}"))+ .unwrap_or_else(|| "How can I help?".into())+}++fn is_goodbye(t: &str) -> bool {+ let t = format!(" {} ", t.to_lowercase().trim_matches(|c: char| !c.is_alphanumeric() && !c.is_whitespace()));+ let short = t.split_whitespace().count() <= 4;+ short && [" bye ", " goodbye ", " bye bye ", " that's all ", " thats all ", " khuda hafiz ", " allah hafiz ", " alvida ", "अलविदा", "خدا حافظ", "اللہ حافظ"].iter().any(|w| t.contains(w))+}+async fn finalize_approval(st: &Arc<State>, call_id: &str, approval_id: &str, yes: bool) -> String {match st.out.request("mercury/call/approve", json!({ "callId": call_id, "approvalId": approval_id, "approved": yes }), Duration::from_secs(10)).await {Ok(v) if v.get("ok").and_then(Value::as_bool) == Some(true) => {@@ -587,17 +534,26 @@ pub fn spoken_verdict(said: &[(Instant, String)], since: Instant) -> Option<boolNone}-/// Hand Mercury's answer to the voice model and have it speak.-fn deliver(send_q: &mpsc::UnboundedSender<Value>, ready: &mut VecDeque<(String, String)>, responding: &mut bool) {- if let Some((fc_id, answer)) = ready.pop_front() {- let _ = send_q.send(json!({ "type": "conversation.item.create", "item": { "type": "function_call_output", "call_id": fc_id, "output": answer } }));- let _ = send_q.send(json!({ "type": "response.create" }));+/// Hand Mercury's answer to the voice: a reasoning model gets it as the tool result;+/// a pipeline voice speaks it (approval bookkeeping strings become short words).+fn deliver(link: &Link, brain: Brain, ready: &mut VecDeque<(String, String)>, responding: &mut bool) {+ if let Some((id, answer)) = ready.pop_front() {+ match brain {+ Brain::Voice => link.send(LinkCmd::ToolResult { id, output: answer }),+ Brain::Mercury => {+ let spoken = if answer.starts_with("Approved.") { "Okay, going ahead.".to_string() }+ else if answer.starts_with("Declined.") { "Okay, I won't.".to_string() }+ else if answer.starts_with("Not approved:") { "Sorry, I didn't catch a yes. Should I go ahead?".to_string() }+ else { answer };+ link.send(LinkCmd::Say(spoken));+ }+ }*responding = true;}}/// Turn the voice provider's close reason into something the owner can act on.-fn explain_close(reason: &str) -> String {+pub fn explain_close(reason: &str) -> String {let r = reason.to_ascii_lowercase();if r.contains("insufficient_quota") || r.contains("credit_balance") || r.contains("billing") {"your OpenAI account is out of credit. Add credit at platform.openai.com → Settings → Billing, then call again".into()@@ -618,11 +574,6 @@ fn explain_close(reason: &str) -> String {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 only_the_users_own_yes_counts() {@@ -642,9 +593,4 @@ mod tests {assert!(explain_close("").contains("closed"));}- #[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.jsonindex 16f5fa2c..799555ae 100644--- a/plugins/whatsapp/mercury-plugin.template.json+++ b/plugins/whatsapp/mercury-plugin.template.json@@ -3,7 +3,7 @@"id": "whatsapp","name": "WhatsApp","version": "0.1.0",- "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).",+ "description": "Chat with Mercury on WhatsApp and talk to it by voice call: OpenAI by default, or Gemini, Grok, ElevenLabs, Azure, Qwen, or your own Mercury model with Deepgram/Cartesia/MiniMax/Sarvam voices. 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",@@ -37,14 +37,45 @@},"permissions": {"network": [- "web.whatsapp.com",- "*.whatsapp.net",+ "*.aliyuncs.com",+ "*.openai.azure.com","*.whatsapp.com",- "api.openai.com"+ "*.whatsapp.net",+ "api.cartesia.ai",+ "api.deepgram.com",+ "api.elevenlabs.io",+ "api.minimax.io",+ "api.openai.com",+ "api.sarvam.ai",+ "api.x.ai",+ "generativelanguage.googleapis.com",+ "streaming.assemblyai.com",+ "web.whatsapp.com"+ ],+ "secrets": [+ "GEMINI_API_KEY",+ "ELEVENLABS_API_KEY",+ "AZURE_OPENAI_API_KEY",+ "DASHSCOPE_API_KEY",+ "DEEPGRAM_API_KEY",+ "ASSEMBLYAI_API_KEY",+ "SARVAM_API_KEY",+ "CARTESIA_API_KEY",+ "MINIMAX_API_KEY"],- "secrets": [],"providers": {- "openai": "Voice calls"+ "openai": {+ "unlocks": "Voice calls",+ "when": {+ "voiceEngine": "openai"+ }+ },+ "grok": {+ "unlocks": "Voice calls with Grok",+ "when": {+ "voiceEngine": "grok"+ }+ }}},"settings": {@@ -108,17 +139,41 @@"label": "Answer your voice calls","setup": true},- "maxCallsPerHour": {- "type": "number",- "description": "Most times Mercury may call you in an hour.",- "default": 4,- "label": "Most calls from Mercury per hour"+ "voiceEngine": {+ "type": "enum",+ "label": "Voice for calls",+ "setup": true,+ "default": "openai",+ "description": "Who listens and speaks on calls. Change anytime in /plugins whatsapp.",+ "options": [+ "openai",+ "gemini",+ "grok",+ "elevenlabs",+ "azure",+ "qwen",+ "mercury"+ ],+ "optionLabels": {+ "openai": "OpenAI Realtime (default): natural, uses your OpenAI provider",+ "gemini": "Google Gemini Live: cheapest, free tier, Hindi and Urdu",+ "grok": "xAI Grok Voice: uses your Grok provider",+ "elevenlabs": "ElevenLabs Realtime (experimental)",+ "azure": "Azure OpenAI Realtime",+ "qwen": "Alibaba Qwen-Omni Realtime",+ "mercury": "My own model: your Mercury model thinks; pick who listens and speaks"+ }},- "maxCallMinutes": {- "type": "number",- "description": "Longest a call can last, in minutes.",- "default": 15,- "label": "Longest call, in minutes"+ "voiceModel": {+ "type": "string",+ "label": "OpenAI voice model",+ "default": "gpt-realtime-2.1",+ "description": "gpt-realtime-2.1, or gpt-realtime-2.1-mini (about 3x cheaper).",+ "when": {+ "voiceEngine": [+ "openai"+ ]+ }},"voice": {"type": "enum",@@ -136,13 +191,364 @@"verse"],"default": "marin",- "label": "Mercury's voice on calls"+ "label": "OpenAI voice",+ "when": {+ "voiceEngine": [+ "openai",+ "azure"+ ]+ }},- "voiceModel": {+ "geminiKey": {+ "type": "secret",+ "secret": "GEMINI_API_KEY",+ "label": "Gemini API key",+ "setup": true,+ "required": true,+ "description": "From aistudio.google.com/apikey.",+ "when": {+ "voiceEngine": [+ "gemini"+ ]+ }+ },+ "geminiModel": {+ "type": "string",+ "label": "Gemini Live model",+ "default": "gemini-3.8-live",+ "when": {+ "voiceEngine": [+ "gemini"+ ]+ }+ },+ "geminiVoice": {+ "type": "string",+ "label": "Gemini voice",+ "default": "Kore",+ "description": "e.g. Kore, Puck, Charon, Aoede.",+ "when": {+ "voiceEngine": [+ "gemini"+ ]+ }+ },+ "grokModel": {+ "type": "string",+ "label": "Grok voice model",+ "default": "grok-voice-latest",+ "when": {+ "voiceEngine": [+ "grok"+ ]+ }+ },+ "grokVoice": {+ "type": "enum",+ "label": "Grok voice",+ "default": "eve",+ "options": [+ "eve",+ "ara",+ "leo",+ "rex",+ "sal",+ "atlas",+ "naksh",+ "celeste",+ "ursa",+ "sirius",+ "lumen"+ ],+ "when": {+ "voiceEngine": [+ "grok"+ ]+ }+ },+ "elevenlabsKey": {+ "type": "secret",+ "secret": "ELEVENLABS_API_KEY",+ "label": "ElevenLabs API key",+ "setup": true,+ "required": true,+ "when": [+ {+ "voiceEngine": [+ "elevenlabs"+ ]+ },+ {+ "voiceEngine": "mercury",+ "sttProvider": "elevenlabs"+ },+ {+ "voiceEngine": "mercury",+ "ttsProvider": "elevenlabs"+ }+ ]+ },+ "elevenlabsModel": {+ "type": "enum",+ "label": "ElevenLabs Realtime model",+ "default": "eleven_realtime_v1_mini",+ "options": [+ "eleven_realtime_v1_mini",+ "eleven_realtime_v1_max"+ ],+ "when": {+ "voiceEngine": [+ "elevenlabs"+ ]+ }+ },+ "elevenlabsVoice": {"type": "string",- "description": "OpenAI realtime model for calls.",- "default": "gpt-realtime",- "label": "Voice model (OpenAI)"+ "label": "ElevenLabs voice",+ "default": "brian",+ "when": {+ "voiceEngine": [+ "elevenlabs"+ ]+ }+ },+ "azureKey": {+ "type": "secret",+ "secret": "AZURE_OPENAI_API_KEY",+ "label": "Azure OpenAI API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": [+ "azure"+ ]+ }+ },+ "azureEndpoint": {+ "type": "string",+ "label": "Azure endpoint",+ "setup": true,+ "required": true,+ "description": "e.g. myresource.openai.azure.com",+ "when": {+ "voiceEngine": [+ "azure"+ ]+ }+ },+ "azureDeployment": {+ "type": "string",+ "label": "Azure realtime deployment name",+ "setup": true,+ "default": "gpt-realtime-2.1",+ "when": {+ "voiceEngine": [+ "azure"+ ]+ }+ },+ "qwenKey": {+ "type": "secret",+ "secret": "DASHSCOPE_API_KEY",+ "label": "Alibaba Model Studio (DashScope) API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": [+ "qwen"+ ]+ }+ },+ "qwenEndpoint": {+ "type": "string",+ "label": "Qwen endpoint host",+ "default": "dashscope-intl.aliyuncs.com",+ "description": "Your workspace host, e.g. {workspace}.ap-southeast-1.maas.aliyuncs.com",+ "when": {+ "voiceEngine": [+ "qwen"+ ]+ }+ },+ "qwenModel": {+ "type": "string",+ "label": "Qwen model",+ "default": "qwen3.8-omni-flash-realtime",+ "when": {+ "voiceEngine": [+ "qwen"+ ]+ }+ },+ "qwenVoice": {+ "type": "string",+ "label": "Qwen voice",+ "default": "Tina",+ "when": {+ "voiceEngine": [+ "qwen"+ ]+ }+ },+ "sttProvider": {+ "type": "enum",+ "label": "Who listens (speech to text)",+ "setup": true,+ "default": "deepgram",+ "options": [+ "deepgram",+ "assemblyai",+ "elevenlabs",+ "sarvam"+ ],+ "optionLabels": {+ "deepgram": "Deepgram Nova-3: fast, cheap, Hindi and Urdu",+ "assemblyai": "AssemblyAI Universal-3.6 Pro: Hindi and Urdu",+ "elevenlabs": "ElevenLabs Scribe v2",+ "sarvam": "Sarvam Saaras: Indian languages, incl. Urdu"+ },+ "when": {+ "voiceEngine": [+ "mercury"+ ]+ }+ },+ "sttLanguage": {+ "type": "enum",+ "label": "Language you'll speak",+ "default": "auto",+ "options": [+ "auto",+ "en",+ "hi",+ "ur"+ ],+ "optionLabels": {+ "auto": "Detect automatically",+ "en": "English",+ "hi": "Hindi",+ "ur": "Urdu"+ },+ "when": {+ "voiceEngine": [+ "mercury"+ ]+ }+ },+ "deepgramKey": {+ "type": "secret",+ "secret": "DEEPGRAM_API_KEY",+ "label": "Deepgram API key",+ "setup": true,+ "required": true,+ "when": [+ {+ "voiceEngine": "mercury",+ "sttProvider": "deepgram"+ },+ {+ "voiceEngine": "mercury",+ "ttsProvider": "deepgram"+ }+ ]+ },+ "assemblyaiKey": {+ "type": "secret",+ "secret": "ASSEMBLYAI_API_KEY",+ "label": "AssemblyAI API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": "mercury",+ "sttProvider": "assemblyai"+ }+ },+ "sarvamKey": {+ "type": "secret",+ "secret": "SARVAM_API_KEY",+ "label": "Sarvam API key",+ "setup": true,+ "required": true,+ "when": [+ {+ "voiceEngine": "mercury",+ "sttProvider": "sarvam"+ },+ {+ "voiceEngine": "mercury",+ "ttsProvider": "sarvam"+ }+ ]+ },+ "ttsProvider": {+ "type": "enum",+ "label": "Who speaks (voice)",+ "setup": true,+ "default": "cartesia",+ "options": [+ "cartesia",+ "elevenlabs",+ "minimax",+ "sarvam",+ "deepgram"+ ],+ "optionLabels": {+ "cartesia": "Cartesia Sonic-3.6: very fast, Hindi, Hinglish and Urdu",+ "elevenlabs": "ElevenLabs Flash: 17k+ voices (Hindi, no Urdu)",+ "minimax": "MiniMax speech-2.8 (Hindi, no Urdu)",+ "sarvam": "Sarvam Bulbul: Indian voices (no Urdu)",+ "deepgram": "Deepgram Aura-2 (English and a few others)"+ },+ "when": {+ "voiceEngine": [+ "mercury"+ ]+ }+ },+ "cartesiaKey": {+ "type": "secret",+ "secret": "CARTESIA_API_KEY",+ "label": "Cartesia API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": "mercury",+ "ttsProvider": "cartesia"+ }+ },+ "minimaxKey": {+ "type": "secret",+ "secret": "MINIMAX_API_KEY",+ "label": "MiniMax API key",+ "setup": true,+ "required": true,+ "when": {+ "voiceEngine": "mercury",+ "ttsProvider": "minimax"+ }+ },+ "ttsVoice": {+ "type": "string",+ "label": "Voice ID",+ "description": "Leave empty for the provider's default voice.",+ "default": "",+ "when": {+ "voiceEngine": [+ "mercury"+ ]+ }+ },+ "maxCallsPerHour": {+ "type": "number",+ "description": "Most times Mercury may call you in an hour.",+ "default": 4,+ "label": "Most calls from Mercury per hour"+ },+ "maxCallMinutes": {+ "type": "number",+ "description": "Longest a call can last, in minutes.",+ "default": 15,+ "label": "Longest call, in minutes"}}}diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsindex 3ccad0fc..0bec6a62 100644--- a/src/plugins/channel-bridge.ts+++ b/src/plugins/channel-bridge.ts@@ -259,8 +259,9 @@ export class PluginChannel extends BaseChannel {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' };+ const why = typeof p.voiceProblem === 'string' && p.voiceProblem ? p.voiceProblem : 'voice calls need an OpenAI provider: add your OpenAI key once in the dashboard (Providers) or with `mercury doctor`';+ void this.send(`📞 I couldn't answer your call: ${why}.`).catch(() => {});+ return { accept: false, reason: 'voice engine not ready' };}this.callStarted(String(p.callId ?? ''));return { accept: true, instructions: voiceBriefing() };