Skip to content

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

feat(whatsapp): show Mercury photos and documents during a voice call

Salman Qureshi101dd70929d4
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rs
index 2e3b19eb..fee44dad 100644
--- a/plugins/whatsapp/companion/src/main.rs
+++ b/plugins/whatsapp/companion/src/main.rs
@@ -92,6 +92,8 @@ pub struct State {
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>>,
+ /// Things that happened in the chat during a call (a photo arrived), to mention at the next pause.
+ pub call_context: std::sync::Mutex<HashMap<String, Vec<String>>>,
}
pub fn log(msg: impl AsRef<str>) {
@@ -138,6 +140,7 @@ async fn main() -> anyhow::Result<()> {
recent_calls: Mutex::new(Vec::new()),
call_watchers: Arc::new(Mutex::new(HashMap::new())),
call_activity: std::sync::Mutex::new(HashMap::new()),
+ call_context: std::sync::Mutex::new(HashMap::new()),
});
let mut lines = BufReader::new(tokio::io::stdin()).lines();
@@ -175,6 +178,12 @@ async fn handle(st: Arc<State>, msg: Value) {
}
return;
}
+ if method == "mercury/call/context" {
+ if let (Some(call), Some(text)) = (params.get("callId").and_then(Value::as_str), params.get("text").and_then(Value::as_str)) {
+ st.call_context.lock().unwrap().entry(call.to_string()).or_default().push(text.chars().take(400).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.rs
index ab782f55..433f5526 100644
--- a/plugins/whatsapp/companion/src/voice.rs
+++ b/plugins/whatsapp/companion/src/voice.rs
@@ -204,6 +204,7 @@ fn session_config(instructions: &str) -> Value {
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. \
+ 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. \
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",
@@ -362,9 +363,18 @@ async fn bridge(
deliver(&send_q, &mut ready_answers, &mut responding);
continue;
}
+ if responding || !playout.lock().unwrap().is_empty() { continue; }
+ // Something arrived in the chat (a photo, a document): let the voice mention it.
+ let context = st.call_context.lock().unwrap().remove(call_id);
+ if let Some(notes) = context.filter(|n| !n.is_empty()) {
+ 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" }));
+ 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.
- if responding || !playout.lock().unwrap().is_empty() { continue; }
let due = {
let mut p = pending.lock().unwrap();
let now = Instant::now();
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 928e58d7..2ce15b91 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -26,6 +26,7 @@
* 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)
+ * mercury/call/context notification { callId, text } (something happened in the chat, e.g. a photo arrived)
*
* 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.
@@ -161,6 +162,21 @@ export class PluginChannel extends BaseChannel {
private callAsks = new Map<string, { chunks: string[]; resolve: (answer: string) => void; timer: ReturnType<typeof setTimeout> }>();
/** Call targets whose turn outlived the call question: later output goes to the owner's chat. */
private overflow = new Set<string>();
+ /** Calls in progress, and the files the owner sent in the chat during each (for the voice to ask about). */
+ private activeCalls = new Map<string, { since: number; files: Array<{ path: string; kind: string; name: string; mime?: string }> }>();
+
+ private callStarted(callId: string): void {
+ if (!callId) return;
+ this.activeCalls.set(callId, { since: Date.now(), files: [] });
+ // A call that never reported its end is forgotten after 2 hours.
+ for (const [id, c] of this.activeCalls) if (Date.now() - c.since > 2 * 3600_000) this.activeCalls.delete(id);
+ }
+
+ private currentCall(): [string, { since: number; files: Array<{ path: string; kind: string; name: string; mime?: string }> }] | undefined {
+ let latest: [string, { since: number; files: Array<{ path: string; kind: string; name: string; mime?: string }> }] | undefined;
+ for (const e of this.activeCalls) if (!latest || e[1].since > latest[1].since) latest = e;
+ return latest;
+ }
constructor(
private readonly manifest: PluginManifest,
@@ -233,9 +249,11 @@ export class PluginChannel extends BaseChannel {
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' };
}
+ this.callStarted(String(p.callId ?? ''));
return { accept: true, instructions: voiceBriefing() };
}
case 'mercury/call/briefing':
+ this.callStarted(String(p.callId ?? ''));
return { instructions: voiceBriefing() };
case 'mercury/call/ask': {
const callId = typeof p.callId === 'string' ? p.callId.replace(/[^\w.-]/g, '').slice(0, 80) : '';
@@ -265,15 +283,19 @@ export class PluginChannel extends BaseChannel {
resolve('Mercury is still working on that. It will send the answer to WhatsApp when it\'s done.');
}, 90_000);
this.callAsks.set(target, { chunks: [], resolve, timer });
+ const files = this.activeCalls.get(callId)?.files ?? [];
+ const sentNote = files.length
+ ? `\n[During this call the owner sent ${files.map((f) => `a ${f.kind === 'image' ? 'photo' : f.kind} (${f.name})`).join(', ')} in the WhatsApp chat; ${files.length === 1 ? 'it is' : 'they are'} attached to this message. "It", "this" or "the photo" means ${files.length === 1 ? 'that file' : 'the latest one'}.]`
+ : '';
this.emit({
id: `call-${callId}-${Date.now()}`,
channelId: `${this.type}:${target}`,
channelType: this.type,
senderId: digits(owner),
senderRole: 'admin',
- content: `[Voice call: the owner asked this out loud. Use your tools to get the real answer: web_search for news and anything current, fetch_url, memory, skills. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Only actions that change something (files, commands, sending messages, purchases) need approval, and that can't be given on a call; for those, say you'll do it once they confirm by message.]\n${question}`,
+ content: `[Voice call: the owner asked this out loud. Use your tools to get the real answer: web_search for news and anything current, fetch_url, memory, skills. Then answer in one to three short spoken sentences, with no markdown, lists, links or code. Only actions that change something (files, commands, sending messages, purchases) need approval, and that can't be given on a call; for those, say you'll do it once they confirm by message.]${sentNote}\n${question}`,
timestamp: Date.now(),
- metadata: { pluginId: this.manifest.id, voiceCall: true, callId, channelAccess: this.accessFor('admin'), channelGuidance: this.guidance('admin', false, true) },
+ metadata: { pluginId: this.manifest.id, voiceCall: true, callId, attachments: files.slice(-4), channelAccess: this.accessFor('admin'), channelGuidance: this.guidance('admin', false, true) },
});
});
}
@@ -293,6 +315,7 @@ export class PluginChannel extends BaseChannel {
private onCallEnded(params: unknown): void {
const p = (params ?? {}) as Record<string, unknown>;
+ this.activeCalls.delete(String(p.callId ?? ''));
const secs = typeof p.durationSec === 'number' ? Math.round(p.durationSec) : 0;
const dur = secs >= 60 ? `${Math.floor(secs / 60)}m ${secs % 60}s` : `${secs}s`;
const outcome = String(p.outcome ?? '');
@@ -414,6 +437,19 @@ export class PluginChannel extends BaseChannel {
await this.send(`🎤 I couldn't understand that voice note (${(err as Error).message.slice(0, 160)}). Could you type it?`, `${this.type}:${chatId}`).catch(() => {});
}
}
+ // On a call: files sent in the chat belong to the conversation on the
+ // phone. Keep them for the voice to ask about, and tell it they arrived.
+ const call = role === 'admin' && others.length ? this.currentCall() : undefined;
+ if (call) {
+ call[1].files.push(...others);
+ if (call[1].files.length > 8) call[1].files.splice(0, call[1].files.length - 8);
+ const what = others.map((f) => (f.kind === 'image' ? 'a photo' : f.kind === 'document' ? `a document (${f.name})` : `a ${f.kind}`)).join(' and ');
+ this.transport.notify?.('mercury/call/context', {
+ callId: call[0],
+ text: `The owner just sent ${what} in the WhatsApp chat${content ? ` with the message "${content.slice(0, 200)}"` : ''}. Mercury can see it: if they ask about it (or to confirm you got it), use ask_mercury.`,
+ });
+ if (!content) return; // a bare photo during a call is for the call, not a separate chat reply
+ }
if (others.length) {
const list = others.map((f) => `${f.kind}: ${f.path}`).join('\n');
content = `${content}${content ? '\n' : ''}[Attachments: the files are attached to this message; these are their paths on this computer]\n${list}`;
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index 1b8c6cfa..e211f953 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -45,7 +45,7 @@ rl.on('line', (line) => {
notify('mercury/call/ended', a);
return ok({ content: [{ type: 'text', text: 'sent' }] });
}
- notify('mercury/channel/message', { id: a.id, chatId: a.chatId || '[email protected]', senderId: a.senderId || 'x@lid', senderPhone: a.senderPhone, isGroup: !!a.isGroup, fromMe: !!a.fromMe, text: a.text });
+ notify('mercury/channel/message', { id: a.id, chatId: a.chatId || '[email protected]', senderId: a.senderId || 'x@lid', senderPhone: a.senderPhone, isGroup: !!a.isGroup, fromMe: !!a.fromMe, text: a.text, attachments: a.attachments });
return ok({ content: [{ type: 'text', text: 'injected' }] });
}
case 'mercury/channel/pair':
@@ -59,6 +59,8 @@ rl.on('line', (line) => {
return ok({});
case 'mercury/call/progress':
return log('progress.jsonl', msg.params);
+ case 'mercury/call/context':
+ return log('context.jsonl', msg.params);
case 'mercury/channel/unlink':
ok({});
return notify('mercury/channel/status', { state: 'logged-out', detail: 'unlinked by owner' });
@@ -263,6 +265,30 @@ describe('plugin channels (plugin API 1.1)', () => {
expect(sent().filter((m) => m.method === 'mercury/channel/send')).toEqual([]);
});
+ it('a photo sent in the chat during a call goes to the call: the voice hears about it and Mercury sees it', async () => {
+ await installChannel();
+ await callsim('mercury/call/incoming', { callId: 'k1', from: 'x@lid', fromPhone: '15550002', voiceReady: true });
+ await waitFor(() => replies().length === 1);
+ const photo = join(src, 'photo.jpg');
+ writeFileSync(photo, Buffer.from([0xff, 0xd8, 0xff]));
+ await inject({ id: 'p1', senderPhone: '15550002', attachments: [{ kind: 'image', path: photo }] });
+ expect(received).toEqual([]); // a bare photo during a call isn't a separate chat turn
+ const ctx = join(pluginDataDir('whatsapp'), 'context.jsonl');
+ await waitFor(() => existsSync(ctx));
+ expect(JSON.parse(readFileSync(ctx, 'utf8').trim())).toMatchObject({ callId: 'k1', text: expect.stringMatching(/just sent a photo[\s\S]*ask_mercury/) });
+
+ await callsim('mercury/call/ask', { callId: 'k1', question: 'What is in the photo?' });
+ await waitFor(() => received.length === 1);
+ expect(received[0].content).toMatch(/During this call the owner sent a photo \(photo\.jpg\)[\s\S]*What is in the photo\?/);
+ expect(received[0].metadata?.attachments).toEqual([expect.objectContaining({ kind: 'image', path: photo })]);
+
+ await inject({ callId: 'k1', direction: 'incoming', outcome: 'completed', durationSec: 30, transcript: [] }, 'callend');
+ await sleep(50);
+ await inject({ id: 'p2', senderPhone: '15550002', attachments: [{ kind: 'image', path: photo }] });
+ await waitFor(() => received.length === 2); // after the call, photos are ordinary chat messages again
+ expect(received[1].channelId).toBe('whatsapp:[email protected]');
+ });
+
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');