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): Mercury can send links and details to the chat during a call

Salman Qureshia38351fe3126
diff --git a/plugins/whatsapp/companion/src/main.rs b/plugins/whatsapp/companion/src/main.rs
index 49ddf998..d4fb7acb 100644
--- a/plugins/whatsapp/companion/src/main.rs
+++ b/plugins/whatsapp/companion/src/main.rs
@@ -236,21 +236,32 @@ async fn handle(st: Arc<State>, msg: Value) {
"serverInfo": { "name": "mercury-wa", "version": env!("CARGO_PKG_VERSION") },
})),
"ping" => Ok(json!({})),
- "tools/list" => Ok(json!({ "tools": [{
- "name": "call_owner",
- "description": "Ring the owner on WhatsApp and talk to them by voice. Only the owner can be called.",
- "inputSchema": { "type": "object", "properties": { "reason": { "type": "string", "description": "Why you're calling, in one sentence" } }, "required": ["reason"] },
- }] })),
+ "tools/list" => Ok(json!({ "tools": [
+ {
+ "name": "call_owner",
+ "description": "Ring the owner on WhatsApp and talk to them by voice. Only the owner can be called.",
+ "inputSchema": { "type": "object", "properties": { "reason": { "type": "string", "description": "Why you're calling, in one sentence" } }, "required": ["reason"] },
+ },
+ {
+ "name": "send_to_chat",
+ "description": "Send the owner a WhatsApp message (links, lists, details). Only the owner receives it.",
+ "inputSchema": { "type": "object", "properties": { "text": { "type": "string", "description": "The message, with any links in full" } }, "required": ["text"] },
+ },
+ ] })),
"tools/call" => {
let name = params.get("name").and_then(Value::as_str).unwrap_or("");
let args = params.get("arguments").cloned().unwrap_or(json!({}));
- if name != "call_owner" {
- Err(format!("unknown tool {name}"))
- } else {
- Ok(match voice::call_owner(st.clone(), &args).await {
+ let result = match name {
+ "call_owner" => Some(voice::call_owner(st.clone(), &args).await),
+ "send_to_chat" => Some(send_to_owner(st.clone(), &args).await),
+ _ => None,
+ };
+ match result {
+ None => Err(format!("unknown tool {name}")),
+ Some(r) => Ok(match r {
Ok(text) => json!({ "content": [{ "type": "text", "text": text }] }),
Err(e) => json!({ "content": [{ "type": "text", "text": e }], "isError": true }),
- })
+ }),
}
}
"mercury/channel/pair" => pair(st.clone(), &params).await,
@@ -301,6 +312,19 @@ async fn pair(st: Arc<State>, params: &Value) -> Result<Value, String> {
Ok(json!({}))
}
+/// The send_to_chat tool: a WhatsApp message to the owner (and only the owner).
+async fn send_to_owner(st: Arc<State>, args: &Value) -> Result<String, String> {
+ let text = args.get("text").and_then(Value::as_str).unwrap_or("").trim().to_string();
+ if text.is_empty() { return Err("text is required".into()); }
+ let owner: String = voice::settings().get("owner").and_then(Value::as_str).unwrap_or("").chars().filter(char::is_ascii_digit).collect();
+ if owner.len() < 6 { return Err("No owner number is set. Run: mercury plugins set whatsapp owner +<number>".into()); }
+ let c = client(&st).await?;
+ let to: Jid = format!("{owner}@s.whatsapp.net").parse().map_err(|e| format!("bad owner number: {e}"))?;
+ let text: String = text.chars().take(4000).collect();
+ c.send_text(to, text).await.map_err(|e| e.to_string())?;
+ Ok("Sent to the owner's WhatsApp chat.".into())
+}
+
fn remove_session(dir: &Path) {
for suffix in ["", "-wal", "-shm", "-journal"] {
let _ = std::fs::remove_file(dir.join(format!("whatsapp.db{suffix}")));
diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rs
index e0245f2b..47552bb4 100644
--- a/plugins/whatsapp/companion/src/voice.rs
+++ b/plugins/whatsapp/companion/src/voice.rs
@@ -174,6 +174,8 @@ fn instructions_for(instructions: &str) -> String {
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. \
+ Mercury can send things to the user's WhatsApp chat during the call (links, lists, details): when they ask for something to be sent, \
+ or say yes to an offer to send it, call ask_mercury with a request like 'send the phone links to my chat'. Never say you can't send things. \
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}") }
}
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.json
index a57efed1..c6c4a933 100644
--- a/plugins/whatsapp/mercury-plugin.template.json
+++ b/plugins/whatsapp/mercury-plugin.template.json
@@ -29,6 +29,12 @@
"description": "Ring the owner on WhatsApp and talk to them by voice (only the owner can be called; rate-limited). Use for things that matter right now; send a message for everything else. To call later (\"call me in 10 minutes\", \"every day at 6pm\") or when something finishes or happens, use schedule_task with a prompt that ends by calling this tool, and put \"whatsapp__call_owner\" in allow_tools so it can call without asking again.",
"readOnly": false,
"timeoutMs": 120000
+ },
+ {
+ "name": "send_to_chat",
+ "readOnly": true,
+ "timeoutMs": 30000,
+ "description": "Send the owner a WhatsApp message: links, lists, prices, addresses, anything worth keeping. Only the owner receives it, so no approval is needed. On a voice call, use it instead of reading links or long details aloud, then say you've sent them to the chat."
}
],
"channel": {
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 0bec6a62..5137e5db 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -320,7 +320,7 @@ export class PluginChannel extends BaseChannel {
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. Go ahead and do what they ask, including saving files or running things: if an action needs approval, Mercury asks the owner on the call and in the chat, and continues once they say yes. Don't ask them to confirm by message yourself.]${sentNote}\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. Go ahead and do what they ask, including saving files or running things: if an action needs approval, Mercury asks the owner on the call and in the chat, and continues once they say yes. Don't ask them to confirm by message yourself. Links, lists, prices, addresses and other details worth keeping: never read them out. If they asked for them, send them with whatsapp__send_to_chat and say you've sent them to the chat. If you found something useful they didn't ask to receive, end your answer by offering to send it ("Want me to send the links to your chat?") and only send once they say yes. Whenever your answer involves links or details, add them after a final line "For the chat:" (that part isn't spoken, and lets you send them later without searching again).]${sentNote}\n${question}`,
timestamp: Date.now(),
metadata: { pluginId: this.manifest.id, voiceCall: true, callId, attachments: files.slice(-4), channelAccess: this.accessFor('admin'), channelGuidance: this.guidance('admin', false, true) },
});
@@ -335,7 +335,7 @@ export class PluginChannel extends BaseChannel {
clearTimeout(ask.timer);
this.callAsks.delete(target);
const answer = ask.chunks.filter((c) => !/^(☿|⚙|⏳|\s*\[)/.test(c.trim())).pop() ?? ask.chunks.pop() ?? '';
- ask.resolve(answer.trim() || 'Done.');
+ ask.resolve(spokenPart(answer) || 'Done.');
}
this.overflow.delete(target);
}
@@ -556,7 +556,7 @@ export class PluginChannel extends BaseChannel {
`## Channel: ${name}`,
`You're talking with ${who} on ${where}.`,
voiceCall
- ? 'Your answer is spoken aloud: one to three short sentences, no markdown, lists, links or code. Use your tools as usual during a call; approvals are asked on the call and answered by voice or in the chat.'
+ ? 'Your answer is spoken aloud: one to three short sentences, no markdown, lists, links or code. Use your tools as usual during a call; approvals are asked on the call and answered by voice or in the chat. Anything worth keeping (links, lists, details) goes to the chat with whatsapp__send_to_chat, sent when asked, or offered first when not.'
: `Write like a text message: short and conversational. ${name} formatting only (*bold*, _italic_, ~strike~). No code blocks, tables, headings or long lists. If they need code, a document or long output, write it to a file and send it with send_file, then summarise it in a sentence. Never paste raw file contents, logs or stack traces.`,
];
if (this.accessFor(role) === 'extended') {
@@ -734,3 +734,12 @@ export function voiceBriefing(): string {
}
return parts.length ? `Who you are (from Mercury's soul files; keep this voice on the call):\n${parts.join('\n\n')}` : '';
}
+
+/**
+ * The part of a call answer to speak: everything before a "For the chat:"
+ * section (links and details kept in the call's history for send_to_chat).
+ */
+export function spokenPart(answer: string): string {
+ const cut = answer.search(/(^|\n)\s*\**\s*for the chat\s*:?\**\s*:?/i);
+ return (cut >= 0 ? answer.slice(0, cut) : answer).trim();
+}
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index 4fb223bd..15882c23 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -7,7 +7,7 @@ import type { Channel } from '../channels/base.js';
import type { ChannelMessage } from '../types/channel.js';
import { PluginManager, setProviderLookup } from './manager.js';
import { PluginChannel } from './channel-bridge.js';
-import { getPluginChannel, setChannelHost, splitMessage, toWhatsAppText } from './channel-bridge.js';
+import { getPluginChannel, setChannelHost, splitMessage, spokenPart, toWhatsAppText } from './channel-bridge.js';
import { getPluginTools, resetToolBridge } from './tool-bridge.js';
import { pluginDataDir } from './store.js';
import { manifestSchema } from './types.js';
@@ -452,4 +452,11 @@ describe('plugin channels (plugin API 1.1)', () => {
expect(sent[0]).toMatch(/couldn't understand that voice note \(insufficient_quota\)/);
});
});
+
+ it('call answers: the "For the chat:" details are kept out of speech', () => {
+ expect(spokenPart('The Pixel 10 and iPhone 18 are the best picks. Want me to send the links to your chat?\n\nFor the chat:\n- Pixel 10: https://a.example\n- iPhone 18: https://b.example'))
+ .toBe('The Pixel 10 and iPhone 18 are the best picks. Want me to send the links to your chat?');
+ expect(spokenPart('Just a plain answer.')).toBe('Just a plain answer.');
+ expect(spokenPart('Answer.\n**For the chat:** links')).toBe('Answer.');
+ });
});