Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(whatsapp): keep the caller informed while Mercury works on a call
Salman Qureshi6f33a3d66511
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rsindex 78412e3a..2e3b19eb 100644--- a/plugins/whatsapp/companion/src/main.rs+++ b/plugins/whatsapp/companion/src/main.rs@@ -90,6 +90,8 @@ pub struct State {pub recent_calls: Mutex<Vec<std::time::Instant>>,/// Outcomes of outgoing calls being placed.pub call_watchers: voice::CallWatchers,+ /// What Mercury is doing right now for each call's pending question (from mercury/call/progress).+ pub call_activity: std::sync::Mutex<HashMap<String, String>>,}pub fn log(msg: impl AsRef<str>) {@@ -135,6 +137,7 @@ async fn main() -> anyhow::Result<()> {client: Mutex::new(None),recent_calls: Mutex::new(Vec::new()),call_watchers: Arc::new(Mutex::new(HashMap::new())),+ call_activity: std::sync::Mutex::new(HashMap::new()),});let mut lines = BufReader::new(tokio::io::stdin()).lines();@@ -166,6 +169,12 @@ async fn handle(st: Arc<State>, msg: Value) {let params = msg.get("params").cloned().unwrap_or(Value::Null);let Some(id) = msg.get("id").cloned() else {// Notifications from Mercury.+ if method == "mercury/call/progress" {+ if let (Some(call), Some(activity)) = (params.get("callId").and_then(Value::as_str), params.get("activity").and_then(Value::as_str)) {+ st.call_activity.lock().unwrap().insert(call.to_string(), activity.chars().take(80).collect());+ }+ return;+ }if method == "notifications/initialized" {if db_path(&st.data_dir).exists() {// Linked before: reconnect with the saved session.diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rsindex eb6a90e3..ab782f55 100644--- a/plugins/whatsapp/companion/src/voice.rs+++ b/plugins/whatsapp/companion/src/voice.rs@@ -201,7 +201,9 @@ fn session_config(instructions: &str) -> Value {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 \(memory, files, calendar) or doing something, call ask_mercury with a clear, complete question; Mercury searches the web and uses its tools. \- Say a short filler like 'one moment, let me check' first, then speak its answer in your own words. \+ Before calling it for anything that searches the web or reads pages, tell the user it can take a few seconds and they can stay on the line \+ (for example: 'Let me look that up, it'll take a few seconds, stay with me'). Then speak its answer in your own words. \+ If you get a status update while Mercury is still working, give the user one short, natural sentence about it so they know you're still there. \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",@@ -331,6 +333,15 @@ async fn bridge(}});+ // 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();+ let mut status_tick = tokio::time::interval(Duration::from_secs(1));+ status_tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);+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);@@ -342,6 +353,42 @@ async fn bridge(tokio::select! {_ = &mut ended => break Ok(()),_ = &mut deadline => { hang_up = true; break Ok(()) }+ Some(a) = answer_rx.recv() => {+ ready_answers.push_back(a);+ if !responding { deliver(&send_q, &mut ready_answers, &mut responding); }+ }+ _ = status_tick.tick() => {+ if !responding && !ready_answers.is_empty() {+ deliver(&send_q, &mut ready_answers, &mut responding);+ 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.+ if responding || !playout.lock().unwrap().is_empty() { continue; }+ let due = {+ let mut p = pending.lock().unwrap();+ let now = Instant::now();+ p.iter_mut().find_map(|(_, (asked, last, n))| {+ let wait = if *n == 0 { Duration::from_secs(8) } else { Duration::from_secs(14) };+ if *n < 8 && now.duration_since(if *n == 0 { *asked } else { *last }) >= wait {+ *last = now;+ *n += 1;+ Some((*n, now.duration_since(*asked).as_secs()))+ } else { None }+ })+ };+ 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" }));+ responding = true;+ }+ }msg = ws_rx.next() => {let Some(Ok(msg)) = msg else { break Err("the voice model disconnected".to_string()) };if msg.is_close() {@@ -352,6 +399,11 @@ async fn bridge(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" => {+ responding = false;+ if !ready_answers.is_empty() { deliver(&send_q, &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);@@ -387,16 +439,20 @@ async fn bridge(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 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());- 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" }));+ pending2.lock().unwrap().remove(&fc_id);+ let _ = tx2.send((fc_id, answer));});}}@@ -417,6 +473,15 @@ async fn bridge(result}+/// 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" }));+ *responding = true;+ }+}+/// Turn the voice provider's close reason into something the owner can act on.fn explain_close(reason: &str) -> String {let r = reason.to_ascii_lowercase();diff --git a/src/core/agent.ts b/src/core/agent.tsindex e44a0472..564d3cc4 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -1549,6 +1549,14 @@ export class Agent {status: 'running' | 'done' | 'error',durationMs?: number,): void {+ // Channels that narrate progress themselves (plugin channels: a voice call+ // speaks "still searching the web…") hear about every tool start.+ if (status === 'running' && this.currentMessage) {+ const current = this.channels.getChannelForMessage(this.currentMessage) as { toolStarted?: (channelId: string, toolName: string) => void } | undefined;+ if (typeof current?.toolStarted === 'function') {+ try { current.toolStarted(this.currentMessage.channelId, toolName); } catch { /* best effort */ }+ }+ }const ch = this.channels.get('cli');if (!(ch instanceof CLIChannel)) return;if (status === 'running') {@@ -1623,8 +1631,13 @@ export class Agent {} else if (channel instanceof WebChannel) {(channel as WebChannel).sendHeartbeat(heartbeatText, msg.channelId);} else if (channel && (channel as { quietProgress?: boolean }).quietProgress) {- // Phone chats (plugin channels like WhatsApp): keep "typing…" alive instead of messages.+ // Phone chats (plugin channels like WhatsApp): keep "typing…" alive, and+ // say once, early, that this one is taking a while and what it's doing.void channel.typing(msg.channelId).catch(() => {});+ if (heartbeatCount === 1) {+ const doing = this.currentActivity ? this.currentActivity.replace(/[.…]+$/, '') : 'working on it';+ void channel.send(`⏳ This one takes a moment. Still on it: ${doing.charAt(0).toLowerCase()}${doing.slice(1)}…`, msg.channelId).catch(() => {});+ }} else if (channel) {void channel.send(heartbeatText, msg.channelId).catch((e) => logger.warn({ e }, 'channel send failed'));}diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.tsindex c9b74944..4c8713a5 100644--- a/src/plugins/channel-bridge.ts+++ b/src/plugins/channel-bridge.ts@@ -24,6 +24,8 @@* 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? }+ * Mercury → plugin during a call+ * mercury/call/progress notification { callId, activity } (what an ask_mercury turn is doing now)** 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.@@ -52,6 +54,24 @@ export interface ChannelStatus {export interface ChannelTransport {request(method: string, params: unknown, timeoutMs: number): Promise<unknown>;+ /** One-way message to the plugin (e.g. call progress). */+ notify?(method: string, params: unknown): void;+}++/** What a tool is doing, in words a voice can say. */+export function describeTool(name: string): string {+ if (name === 'web_search') return 'searching the web';+ if (name === 'fetch_url') return 'reading a web page';+ if (name === 'search_memory') return 'checking what I know about you';+ if (name === 'save_memory') return 'making a note';+ if (name === 'use_skill' || name === 'list_skills') return 'using a skill';+ if (name === 'read_file' || name === 'list_dir') return 'looking through your files';+ if (name === 'run_command') return 'running a command';+ if (/^git_|github|_pr$|issue/.test(name)) return 'checking GitHub';+ if (name.startsWith('spotify_')) return 'talking to Spotify';+ if (name === 'dispatch_bot' || name === 'delegate_task') return 'asking one of my helpers';+ if (name.includes('__')) return 'using a plugin';+ return 'working on it';}/** Where plugin channels are registered (the runtime's ChannelRegistry). */@@ -470,6 +490,17 @@ export class PluginChannel extends BaseChannel {}}+ /**+ * A tool started in a turn for this channel. On a call, the plugin is told+ * what Mercury is doing so the voice can say "still searching the web…"+ * instead of leaving the caller in silence.+ */+ toolStarted(channelId: string, toolName: string): void {+ const call = this.callTarget(channelId);+ if (!call) return;+ this.transport.notify?.('mercury/call/progress', { callId: call.slice('call:'.length), activity: describeTool(toolName) });+ }+/** `whatsapp:call:<id>` → `call:<id>`; undefined for normal chats. */private callTarget(targetId?: string): string | undefined {if (!targetId) return undefined;diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.tsindex 89b32eb5..13c621ea 100644--- a/src/plugins/channel.test.ts+++ b/src/plugins/channel.test.ts@@ -56,6 +56,8 @@ rl.on('line', (line) => {case 'mercury/channel/typing':log('out.jsonl', { method: msg.method, ...msg.params });return ok({});+ case 'mercury/call/progress':+ return log('progress.jsonl', msg.params);case 'mercury/channel/unlink':ok({});return notify('mercury/channel/status', { state: 'logged-out', detail: 'unlinked by owner' });@@ -259,6 +261,19 @@ describe('plugin channels (plugin API 1.1)', () => {expect(sent().filter((m) => m.method === 'mercury/channel/send')).toEqual([]);});+ it('tells the plugin what Mercury is doing during a call, in words a voice can say', async () => {+ const ch = await installChannel();+ ch.toolStarted('whatsapp:call:c7', 'web_search');+ ch.toolStarted('whatsapp:call:c7', 'fetch_url');+ ch.toolStarted('whatsapp:[email protected]', 'web_search'); // a normal chat: nothing sent+ const f = join(pluginDataDir('whatsapp'), 'progress.jsonl');+ await waitFor(() => existsSync(f) && readFileSync(f, 'utf8').trim().split('\n').length === 2);+ expect(readFileSync(f, 'utf8').trim().split('\n').map((l) => JSON.parse(l))).toEqual([+ { callId: 'c7', activity: 'searching the web' },+ { callId: 'c7', activity: 'reading a web page' },+ ]);+ });+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');diff --git a/src/plugins/manager.ts b/src/plugins/manager.tsindex 4732be62..27b9829c 100644--- a/src/plugins/manager.ts+++ b/src/plugins/manager.ts@@ -268,7 +268,10 @@ export class PluginManager {}channel = new PluginChannel(manifest,- { request: (method, params, timeoutMs) => runtimeRef ? runtimeRef.channelRequest(method, params, timeoutMs) : Promise.reject(new Error('not running')) },+ {+ request: (method, params, timeoutMs) => runtimeRef ? runtimeRef.channelRequest(method, params, timeoutMs) : Promise.reject(new Error('not running')),+ notify: (method, params) => runtimeRef?.channelNotify(method, params),+ },() => resolvedSettings(manifest),(m) => { void this.notifyFn(m); },(key, value) => this.setSetting(id, key, value),diff --git a/src/plugins/runtime/out-of-process.ts b/src/plugins/runtime/out-of-process.tsindex 11cdadfb..1f62c7fc 100644--- a/src/plugins/runtime/out-of-process.ts+++ b/src/plugins/runtime/out-of-process.ts@@ -235,6 +235,11 @@ export class OutOfProcessRuntime implements PluginRuntime {});}+ /** Plugin API 1.1 channel notifications to the plugin (`mercury/call/*`). */+ channelNotify(method: string, params: unknown): void {+ if (method.startsWith('mercury/') && this.ready) this.notify(method, params);+ }+private notify(method: string, params: unknown): void {const child = this.child;if (!child?.stdin?.writable) return;