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): reliable scheduled calls ("call me at 9pm", from chat, terminal or a call)

Salman Qureshi8d57fd71319b
diff --git a/plugins/whatsapp/companion/src/voice.rs b/plugins/whatsapp/companion/src/voice.rs
index 47552bb4..f1d1885a 100644
--- a/plugins/whatsapp/companion/src/voice.rs
+++ b/plugins/whatsapp/companion/src/voice.rs
@@ -176,6 +176,7 @@ fn instructions_for(instructions: &str) -> String {
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. \
+ If the user asks you to call them back later ('call me at 9', 'call me back in an hour'), use schedule_callback right away and read back its confirmation. \
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}") }
}
@@ -189,6 +190,15 @@ fn tools() -> Value {
"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": "schedule_callback",
+ "description": "Schedule Mercury to call the user back later. Pass the time exactly as they said it ('9pm', 'in 20 minutes', 'tomorrow 8am'); it's worked out for you. Read back the confirmation it returns.",
+ "parameters": { "type": "object", "properties": {
+ "when": { "type": "string", "description": "The time as the user said it" },
+ "topic": { "type": "string", "description": "What to call about, in a few words" }
+ }, "required": ["when"] },
+ },
{
"type": "function",
"name": "answer_approval",
@@ -480,6 +490,20 @@ async fn bridge(
if !responding { deliver(&link, brain, &mut ready_answers, &mut responding); }
continue;
}
+ if name == "schedule_callback" {
+ let r = st.out.request("mercury/call/schedule", json!({
+ "when": args.get("when").and_then(Value::as_str).unwrap_or(""),
+ "topic": args.get("topic").and_then(Value::as_str).unwrap_or(""),
+ }), Duration::from_secs(10)).await;
+ let text = match r {
+ Ok(v) => v.get("text").and_then(Value::as_str).unwrap_or("Done.").to_string(),
+ Err(e) => format!("Couldn't schedule it: {e}"),
+ };
+ transcript.lock().await.push(json!({ "role": "ask_mercury", "text": format!("schedule a call back: {}", args.get("when").and_then(Value::as_str).unwrap_or("")) }));
+ ready_answers.push_back((id, text));
+ 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.clone() }));
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.json
index c6c4a933..a9ae065e 100644
--- a/plugins/whatsapp/mercury-plugin.template.json
+++ b/plugins/whatsapp/mercury-plugin.template.json
@@ -26,7 +26,7 @@
"tools": [
{
"name": "call_owner",
- "description": "Ring the owner on WhatsApp and talk to them by voice (only the owner can be called; rate-limited). Use for things that matter right now; send a message for everything else. 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.",
+ "description": "Ring the owner on WhatsApp right now and talk to them by voice (only the owner can be called; rate-limited). Use for things that matter now; send a message for everything else. To call LATER (\"call me at 9pm\", \"in 20 minutes\"), use schedule_call instead. For \"call me when X is done\", do X, then call this.",
"readOnly": false,
"timeoutMs": 120000
},
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 1dd7145c..de5e0540 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -35,6 +35,9 @@ import { createCreateIssueTool } from './github/create-issue.js';
import { createGithubApiTool } from './github/github-api.js';
import { createFetchUrlTool } from './web/fetch-url.js';
import { createWebSearchTool } from './web/web-search.js';
+import { activeCallScheduler, describeTime } from '../plugins/call-schedule.js';
+import { tool, zodSchema } from 'ai';
+import { z } from 'zod';
import {
createSpotifySearchTool,
createSpotifyPlayTool,
@@ -299,6 +302,14 @@ export class CapabilityRegistry {
getTools(): Record<string, Tool> {
if (this.toolsDisabled) return {};
+ // Scheduled calls (when a calling channel plugin is running): owner only.
+ if (this.permissions.getCurrentSenderRole() !== 'member' && activeCallScheduler()) {
+ return { ...this.getToolsInner(), ...callTools() };
+ }
+ return this.getToolsInner();
+ }
+
+ private getToolsInner(): Record<string, Tool> {
// Members on a channel that distinguishes roles (e.g. Telegram) must not be
// able to install skills: `install_skill` is the escalation path from chat
// access to arbitrary local execution and is documented as admin-only.
@@ -355,3 +366,44 @@ export class CapabilityRegistry {
return this.skillLoader?.getSkillSummariesText() || '';
}
}
+
+/** Tools for scheduled calls (the time is worked out in code, not by the model). */
+function callTools(): Record<string, Tool> {
+ return {
+ schedule_call: tool({
+ description:
+ 'Schedule Mercury to call the owner on WhatsApp later, e.g. "call me at 9pm about the deploy", "call me back in 20 minutes", "call me tomorrow 8:30am". ' +
+ 'Pass the time exactly as the owner said it (e.g. "9pm", "after 9 PM", "in 20 minutes", "tomorrow 8:30am"); it is converted in code. ' +
+ 'Tell the owner the confirmation it returns (it has the exact time). For "call me when X is done", do X first, then call call_owner.',
+ inputSchema: zodSchema(z.object({
+ when: z.string().min(1).max(80).describe('The time as the owner said it'),
+ topic: z.string().max(300).optional().describe('What the call is about, in a few words'),
+ })),
+ execute: async ({ when, topic }) => {
+ const s = activeCallScheduler();
+ if (!s) return 'Calls need the WhatsApp plugin, linked and running.';
+ try {
+ return s.schedule(when, topic ?? '').confirmation;
+ } catch (err) {
+ return `Couldn't schedule: ${(err as Error).message}`;
+ }
+ },
+ }),
+ list_scheduled_calls: tool({
+ description: 'List the calls Mercury has scheduled to the owner.',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => {
+ const list = activeCallScheduler()?.list() ?? [];
+ return list.length ? list.map((c, i) => `${i + 1}. ${describeTime(new Date(c.at))}: ${c.topic} (id ${c.id})`).join('\n') : 'No calls scheduled.';
+ },
+ }),
+ cancel_scheduled_call: tool({
+ description: 'Cancel a scheduled call by its number in list_scheduled_calls, its id, or "all".',
+ inputSchema: zodSchema(z.object({ which: z.string().min(1).max(40) })),
+ execute: async ({ which }) => {
+ const n = activeCallScheduler()?.cancel(which.toLowerCase()) ?? 0;
+ return n ? `Cancelled ${n} call${n === 1 ? '' : 's'}.` : 'No scheduled call matches that.';
+ },
+ }),
+ };
+}
diff --git a/src/core/agent.ts b/src/core/agent.ts
index d5de4cdf..4aadac52 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -97,6 +97,7 @@ import { buildFileChangePreview } from '../utils/file-preview.js';
import { whatsNewText } from '../utils/whats-new.js';
import { handleBotsCommand as handleBotsCommandImpl } from './commands/bots-command.js';
import { withAttachments } from './attachments.js';
+import { handleCallCommand } from '../plugins/call-schedule.js';
import { handlePluginsCommand, tryPluginCommand, pluginCommandHelp, hasPluginDialog, answerPluginDialog } from '../plugins/commands.js';
import { handleChatCommand as handleChatCommandImpl } from './commands/chat-command.js';
import { handleBgCommand as handleBgCommandImpl } from './commands/bg-command.js';
@@ -762,6 +763,15 @@ export class Agent {
}
}
+ // /call and /calls: scheduled calls, worked out in code (no model turn).
+ if (/^\/calls?(\s|$)/.test(trimmed)) {
+ const channel = this.channels.getChannelForMessage(msg);
+ if (channel) {
+ void channel.send(handleCallCommand(trimmed, msg.senderRole === 'member'), msg.channelId).catch(() => {});
+ }
+ return;
+ }
+
// /plugins is fast-path like /bots: installing or toggling a plugin must
// work while a turn is running (that's often when you notice you need it).
if (/^\/plugins?(\s|$)/.test(trimmed)) {
diff --git a/src/plugins/call-schedule.test.ts b/src/plugins/call-schedule.test.ts
new file mode 100644
index 00000000..e60bd07a
--- /dev/null
+++ b/src/plugins/call-schedule.test.ts
@@ -0,0 +1,106 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { CallScheduler, handleCallCommand, parseWhen, registerCallScheduler } from './call-schedule.js';
+import { publishTool, resetToolBridge } from './tool-bridge.js';
+import { tempHome } from './test-fixtures.js';
+
+// Tue 21 Oct 2026, 14:00 local time.
+const NOW = new Date(2026, 9, 21, 14, 0, 0);
+const hm = (d: Date | null) => d && `${d.getDate()} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
+
+describe('parseWhen', () => {
+ it.each([
+ ['9pm', '21 21:00'],
+ ['after 9 PM', '21 21:00'],
+ ['at 9', '21 21:00'], // a bare 9 at 14:00 means 9 tonight
+ ['9', '21 21:00'],
+ ['1pm', '22 13:00'], // already past today → tomorrow
+ ['21:30', '21 21:30'],
+ ['9:15 am', '22 09:15'],
+ ['tonight at 8', '21 20:00'],
+ ['tomorrow 8:30am', '22 08:30'],
+ ['tomorrow 8', '22 08:00'],
+ ['tomorrow at 3', '22 15:00'],
+ ['in 20 minutes', '21 14:20'],
+ ['20m', '21 14:20'],
+ ['in 2 hours', '21 16:00'],
+ ['in an hour', '21 15:00'],
+ ['in half an hour', '21 14:30'],
+ ])('%s → %s', (input, want) => {
+ expect(hm(parseWhen(input, NOW))).toBe(want);
+ });
+
+ it('rejects what it can\'t understand', () => {
+ for (const bad of ['whenever', '25:00', '13pm', 'next week sometime', '']) expect(parseWhen(bad, NOW)).toBeNull();
+ });
+});
+
+describe('CallScheduler', () => {
+ let env: ReturnType<typeof tempHome>;
+ beforeEach(() => { env = tempHome(); resetToolBridge(); });
+ afterEach(() => { registerCallScheduler('whatsapp', null); resetToolBridge(); vi.useRealTimers(); env.restore(); });
+
+ it('confirms with the exact time, lists, cancels, and survives a restart', () => {
+ const notes: string[] = [];
+ const s = new CallScheduler('whatsapp', async (t) => { notes.push(t); });
+ s.start();
+ expect(s.schedule('9pm', 'the deploy', NOW).confirmation).toMatch(/^✅ I'll call you at 9:00\s?PM.* tonight \(in 7 h\) about the deploy\.$/i);
+ s.cancel('all');
+ s.schedule('in 3 hours', 'the deploy');
+ s.schedule('tomorrow 8am', 'standup');
+ expect(s.list().map((c) => c.topic).sort()).toEqual(['standup', 'the deploy']);
+ s.stop();
+
+ const again = new CallScheduler('whatsapp', async (t) => { notes.push(t); });
+ again.start(); // reloaded from disk
+ expect(again.list()).toHaveLength(2);
+ const first = again.list()[0].topic;
+ expect(again.cancel('1')).toBe(1);
+ expect(again.list().map((c) => c.topic)).toEqual([first === 'standup' ? 'the deploy' : 'standup']);
+ expect(again.cancel('all')).toBe(1);
+ again.stop();
+ });
+
+ it('rings the owner at the time; no answer → one retry, then a message', async () => {
+ vi.useFakeTimers({ now: NOW });
+ const rings: string[] = [];
+ let answer = 'no_answer: the owner did not pick up.';
+ publishTool({
+ pluginId: 'whatsapp', pluginName: 'WhatsApp', name: 'call_owner', description: '', inputSchema: {}, readOnly: false, timeoutMs: 1000,
+ invoke: async (args) => { rings.push(String((args as { reason: string }).reason)); return answer; },
+ });
+ const notes: string[] = [];
+ const s = new CallScheduler('whatsapp', async (t) => { notes.push(t); });
+ registerCallScheduler('whatsapp', s);
+ s.start();
+ s.schedule('in 10 minutes', 'the deploy', new Date());
+ await vi.advanceTimersByTimeAsync(10 * 60_000 + 50);
+ expect(rings).toEqual(['you asked me to call about the deploy']);
+ await vi.advanceTimersByTimeAsync(5 * 60_000 + 50);
+ expect(rings).toHaveLength(2);
+ expect(notes[0]).toMatch(/tried to call you about the deploy, but you didn't pick up/);
+ expect(s.list()).toEqual([]);
+
+ // Answered first time: no retry, no message.
+ answer = 'answered: the owner picked up.';
+ s.schedule('in 1 minute', 'lunch', new Date());
+ await vi.advanceTimersByTimeAsync(60_000 + 50);
+ expect(rings).toHaveLength(3);
+ expect(notes).toHaveLength(1);
+ s.stop();
+ });
+
+ it('/call and /calls work without any model', () => {
+ const s = new CallScheduler('whatsapp', async () => {});
+ registerCallScheduler('whatsapp', s);
+ s.start();
+ expect(handleCallCommand('/call 9pm about the deploy', false)).toMatch(/I'll call you at .*about the deploy/);
+ expect(handleCallCommand('/call in 20 minutes', false)).toMatch(/I'll call you at/);
+ expect(handleCallCommand('/calls', false)).toMatch(/Scheduled calls:\n1\. [\s\S]*\n2\. /);
+ expect(handleCallCommand('/call whenever', false)).toMatch(/couldn't work out when "whenever"/);
+ expect(handleCallCommand('/calls cancel all', false)).toBe('🗑 Cancelled 2 calls.');
+ expect(handleCallCommand('/call 9pm', true)).toBe('Only the owner can schedule calls.');
+ registerCallScheduler('whatsapp', null);
+ expect(handleCallCommand('/call 9pm', false)).toMatch(/need the WhatsApp plugin/);
+ s.stop();
+ });
+});
diff --git a/src/plugins/call-schedule.ts b/src/plugins/call-schedule.ts
new file mode 100644
index 00000000..86916276
--- /dev/null
+++ b/src/plugins/call-schedule.ts
@@ -0,0 +1,298 @@
+/**
+ * Scheduled calls: "call me at 9pm about the deploy", reliably.
+ *
+ * A call is a precise action, not something an AI turn has to remember to do:
+ * at the time, Mercury rings the owner (the channel plugin's call_owner tool)
+ * with the topic as the opener. No answer → one retry after 5 minutes → a
+ * chat message. Times are worked out here, in the host's timezone, and every
+ * schedule is confirmed with the exact time, so a misunderstanding shows up
+ * immediately rather than at 9pm.
+ *
+ * Saved to <plugin dir>/scheduled-calls.json, so calls survive restarts; one
+ * that came due while Mercury was down is placed when it's back (up to 2h
+ * late), otherwise the owner gets a "missed" note.
+ */
+import { existsSync, mkdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { logger } from '../utils/logger.js';
+import { pluginDir, writeJsonAtomic } from './store.js';
+import { listLiveTools } from './tool-bridge.js';
+
+export interface ScheduledCall {
+ id: string;
+ at: string;
+ topic: string;
+ createdAt: string;
+ attempts: number;
+}
+
+const RETRY_MS = 5 * 60_000;
+const MAX_LATE_MS = 2 * 3600_000;
+const MAX_AHEAD_MS = 30 * 24 * 3600_000;
+
+// ── time parsing ──────────────────────────────────────────────────────────
+
+/**
+ * When to call, from what people actually say: "in 10 minutes", "10m",
+ * "9pm", "9:30 pm", "21:00", "at 9", "after 9 PM", "tonight at 8",
+ * "tomorrow 8:30am", "now", or an ISO date-time. A bare hour means the next
+ * time that hour comes round (9 at 14:00 → 21:00 today).
+ */
+export function parseWhen(input: string, now = new Date()): Date | null {
+ const t = input.trim().toLowerCase().replace(/\s+/g, ' ').replace(/[.,!]+$/g, '');
+ if (!t) return null;
+ if (/^(now|right now|immediately|asap)$/.test(t)) return new Date(now.getTime() + 5_000);
+
+ const rel = /^(?:in |after )?(\d+(?:\.\d+)?) ?(s|sec|secs|seconds?|m|min|mins|minutes?|h|hr|hrs|hours?)(?: from now)?$/.exec(t)
+ ?? /^(?:in|after) (an?|half an?) (minute|hour)$/.exec(t);
+ if (rel) {
+ const n = rel[1] === 'a' || rel[1] === 'an' ? 1 : rel[1].startsWith('half') ? 0.5 : Number(rel[1]);
+ const unit = rel[2][0];
+ const ms = unit === 's' ? 1000 : unit === 'm' ? 60_000 : 3600_000;
+ return new Date(now.getTime() + n * ms);
+ }
+
+ if (/^\d{4}-\d{2}-\d{2}t/.test(t)) {
+ const d = new Date(input.trim());
+ return Number.isNaN(d.getTime()) ? null : d;
+ }
+
+ const m = /^(?:(today|tonight|this evening|this morning|tomorrow)(?: at)? )?(?:(?:at|after|around|by) )?(\d{1,2})(?:[:.](\d{2}))? ?(am|pm|a\.m|p\.m)?(?: (today|tonight|tomorrow))?$/.exec(t);
+ if (!m) return null;
+ const day = m[1] ?? m[5];
+ let hour = Number(m[2]);
+ const minute = m[3] ? Number(m[3]) : 0;
+ const ampm = m[4]?.startsWith('p') ? 'pm' : m[4]?.startsWith('a') ? 'am' : undefined;
+ if (hour > 23 || minute > 59 || (ampm && (hour < 1 || hour > 12))) return null;
+ if (ampm === 'pm' && hour < 12) hour += 12;
+ if (ampm === 'am' && hour === 12) hour = 0;
+ const evening = day === 'tonight' || day === 'this evening';
+
+ const at = (base: Date, h: number) => {
+ const d = new Date(base);
+ d.setHours(h, minute, 0, 0);
+ return d;
+ };
+ const tomorrow = new Date(now);
+ tomorrow.setDate(now.getDate() + 1);
+
+ if (day === 'tomorrow') {
+ if (ampm || hour > 12 || hour === 0) return at(tomorrow, hour);
+ return at(tomorrow, hour < 7 ? hour + 12 : hour); // "tomorrow 8" means 8am, "tomorrow 3" 3pm
+ }
+ // Explicit 24h time or am/pm: today if still ahead, otherwise tomorrow.
+ if (ampm || hour > 12 || hour === 0 || evening) {
+ const h = evening && hour < 12 ? hour + 12 : hour;
+ const d = at(now, h);
+ return d.getTime() > now.getTime() ? d : at(tomorrow, h);
+ }
+ // A bare 1–12: whichever of h:00 / (h+12):00 comes next.
+ const options = [at(now, hour), at(now, hour === 12 ? 12 : hour + 12), at(tomorrow, hour), at(tomorrow, hour === 12 ? 12 : hour + 12)];
+ return options.filter((d) => d.getTime() > now.getTime()).sort((a, b) => a.getTime() - b.getTime())[0] ?? null;
+}
+
+/** "9:00 PM tonight (in 2 h 14 m)", "8:30 AM tomorrow (Thu 23 Oct)". */
+export function describeTime(at: Date, now = new Date()): string {
+ const time = at.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
+ const sameDay = at.toDateString() === now.toDateString();
+ const tmr = new Date(now);
+ tmr.setDate(now.getDate() + 1);
+ const day = sameDay ? (at.getHours() >= 17 ? 'tonight' : 'today') : at.toDateString() === tmr.toDateString() ? 'tomorrow' : at.toLocaleDateString(undefined, { weekday: 'short', day: 'numeric', month: 'short' });
+ const mins = Math.max(0, Math.round((at.getTime() - now.getTime()) / 60_000));
+ const rel = mins < 1 ? 'in a moment' : mins < 60 ? `in ${mins} min` : mins < 24 * 60 ? `in ${Math.floor(mins / 60)} h${mins % 60 ? ` ${mins % 60} m` : ''}` : '';
+ const tz = Intl.DateTimeFormat(undefined, { timeZoneName: 'short' }).formatToParts(at).find((p) => p.type === 'timeZoneName')?.value;
+ return `${time}${tz ? ` ${tz}` : ''} ${day}${rel ? ` (${rel})` : ''}`;
+}
+
+// ── scheduler ─────────────────────────────────────────────────────────────
+
+export class CallScheduler {
+ private calls: ScheduledCall[] = [];
+ private timers = new Map<string, ReturnType<typeof setTimeout>>();
+ private seq = 0;
+
+ constructor(
+ private readonly pluginId: string,
+ /** Send the owner a chat message (missed call notes). */
+ private readonly message: (text: string) => Promise<void>,
+ ) {}
+
+ private file(): string {
+ return join(pluginDir(this.pluginId), 'scheduled-calls.json');
+ }
+
+ start(): void {
+ try {
+ const raw = existsSync(this.file()) ? (JSON.parse(readFileSync(this.file(), 'utf8')) as ScheduledCall[]) : [];
+ this.calls = Array.isArray(raw) ? raw.filter((c) => c && typeof c.at === 'string' && typeof c.id === 'string') : [];
+ } catch {
+ this.calls = [];
+ }
+ const now = Date.now();
+ for (const c of [...this.calls]) {
+ const due = Date.parse(c.at);
+ if (due < now - MAX_LATE_MS) {
+ this.remove(c.id);
+ void this.message(`📞 I missed the call I'd scheduled for ${describeTime(new Date(due))} about "${c.topic}" (Mercury wasn't running). Say /call now to ring you now.`).catch(() => {});
+ } else {
+ this.arm(c);
+ }
+ }
+ this.save();
+ }
+
+ stop(): void {
+ for (const t of this.timers.values()) clearTimeout(t);
+ this.timers.clear();
+ }
+
+ list(): ScheduledCall[] {
+ return [...this.calls].sort((a, b) => Date.parse(a.at) - Date.parse(b.at));
+ }
+
+ /** Schedule a call; returns the confirmation to show (or throws with a plain reason). */
+ schedule(when: string, topic: string, now = new Date()): { call: ScheduledCall; confirmation: string } {
+ const at = parseWhen(when, now);
+ if (!at) throw new Error(`I couldn't work out when "${when}" is. Try "9pm", "in 20 minutes" or "tomorrow 8:30am".`);
+ if (at.getTime() - now.getTime() > MAX_AHEAD_MS) throw new Error('That\'s more than 30 days away; pick a closer time.');
+ const call: ScheduledCall = {
+ id: `c${Date.now().toString(36)}${(++this.seq).toString(36)}`,
+ at: at.toISOString(),
+ topic: topic.trim().slice(0, 300) || 'checking in',
+ createdAt: now.toISOString(),
+ attempts: 0,
+ };
+ this.calls.push(call);
+ this.arm(call);
+ this.save();
+ return { call, confirmation: `✅ I'll call you at ${describeTime(at, now)}${call.topic !== 'checking in' ? ` about ${call.topic}` : ''}.` };
+ }
+
+ /** Cancel by id, by list number (1-based), or "all". Returns how many were cancelled. */
+ cancel(which: string): number {
+ const list = this.list();
+ const targets = which === 'all' ? list : list.filter((c, i) => c.id === which || String(i + 1) === which);
+ for (const c of targets) this.remove(c.id);
+ this.save();
+ return targets.length;
+ }
+
+ private remove(id: string): void {
+ const t = this.timers.get(id);
+ if (t) clearTimeout(t);
+ this.timers.delete(id);
+ this.calls = this.calls.filter((c) => c.id !== id);
+ }
+
+ private save(): void {
+ try {
+ mkdirSync(pluginDir(this.pluginId), { recursive: true });
+ writeJsonAtomic(this.file(), this.calls);
+ } catch (err) {
+ logger.warn({ err }, 'Could not save scheduled calls');
+ }
+ }
+
+ private arm(c: ScheduledCall): void {
+ const existing = this.timers.get(c.id);
+ if (existing) clearTimeout(existing);
+ // Long waits are re-armed in steps (timers drift over days; Node caps at ~24.8 days).
+ const wait = Math.max(0, Date.parse(c.at) - Date.now());
+ const step = Math.min(wait, 6 * 3600_000);
+ const t = setTimeout(() => {
+ if (Date.parse(c.at) - Date.now() > 1000) { this.arm(c); return; }
+ void this.place(c);
+ }, step);
+ t.unref?.();
+ this.timers.set(c.id, t);
+ }
+
+ /** Ring the owner. One retry after 5 minutes if they don't pick up, then a message. */
+ private async place(c: ScheduledCall): Promise<void> {
+ this.timers.delete(c.id);
+ const tool = listLiveTools().find((t) => t.pluginId === this.pluginId && t.name === 'call_owner');
+ let outcome = '';
+ if (!tool) {
+ outcome = 'the WhatsApp plugin isn\'t running';
+ } else {
+ try {
+ // Pre-approved: the owner scheduled this call themselves, and it can only ring them.
+ const ac = new AbortController();
+ const reason = `you asked me to call${c.topic !== 'checking in' ? ` about ${c.topic}` : ' you now'}`;
+ outcome = String(await tool.invoke({ reason }, ac.signal));
+ } catch (err) {
+ outcome = `failed: ${(err as Error).message}`;
+ }
+ }
+ if (outcome.startsWith('answered')) {
+ this.remove(c.id);
+ this.save();
+ return;
+ }
+ c.attempts += 1;
+ if (c.attempts < 2 && !/isn't running|Voice calls|need/.test(outcome)) {
+ c.at = new Date(Date.now() + RETRY_MS).toISOString();
+ this.arm(c);
+ this.save();
+ return;
+ }
+ this.remove(c.id);
+ this.save();
+ const why = /no_answer|declined|busy/.test(outcome) ? 'you didn\'t pick up' : outcome.replace(/^failed:\s*/, '').slice(0, 200);
+ await this.message(`📞 I tried to call you${c.topic !== 'checking in' ? ` about ${c.topic}` : ''}, but ${why}. Say /call now when you're free, or just reply here.`).catch(() => {});
+ }
+}
+
+// ── the active scheduler (one per running channel plugin with calls) ──────
+
+const schedulers = new Map<string, CallScheduler>();
+
+export function registerCallScheduler(pluginId: string, s: CallScheduler | null): void {
+ const old = schedulers.get(pluginId);
+ if (old && old !== s) old.stop();
+ if (s) schedulers.set(pluginId, s);
+ else schedulers.delete(pluginId);
+}
+
+export function activeCallScheduler(): CallScheduler | undefined {
+ return schedulers.values().next().value;
+}
+
+// ── /call and /calls ──────────────────────────────────────────────────────
+
+export const CALL_HELP = [
+ 'Usage:',
+ ' /call 9pm about the deploy call you then (also: in 20m, tomorrow 8:30am, tonight 8, now)',
+ ' /calls list scheduled calls',
+ ' /calls cancel 2 | all cancel one (by number) or all',
+].join('\n');
+
+/** Handle "/call …" and "/calls …". Returns the reply text. */
+export function handleCallCommand(trimmed: string, isMember: boolean): string {
+ const s = activeCallScheduler();
+ if (!s) return '📞 Calls need the WhatsApp plugin, linked and running. Set it up with /plugins install whatsapp.';
+ if (isMember) return 'Only the owner can schedule calls.';
+ const [cmd, ...rest] = trimmed.slice(1).split(/\s+/);
+ const args = rest.join(' ').trim();
+ if (cmd === 'calls') {
+ if (/^cancel\b/i.test(args)) {
+ const which = args.replace(/^cancel\s*/i, '').trim() || '';
+ if (!which) return 'Which one? /calls cancel 1, or /calls cancel all.';
+ const n = s.cancel(which.toLowerCase());
+ return n ? `🗑 Cancelled ${n} call${n === 1 ? '' : 's'}.` : 'No scheduled call matches that. See /calls.';
+ }
+ const list = s.list();
+ if (!list.length) return '📞 No calls scheduled. Try: /call 9pm about the deploy';
+ return ['📞 Scheduled calls:', ...list.map((c, i) => `${i + 1}. ${describeTime(new Date(c.at))}: ${c.topic}`), '', 'Cancel with /calls cancel <number> or all.'].join('\n');
+ }
+ if (!args || args === 'help') return CALL_HELP;
+ // "/call 9pm about the deploy", "/call in 20 minutes to review the PR", "/call now"
+ const m = /^(.*?)(?:\s+(?:about|to|for|re|regarding|with)\s+(.+))?$/i.exec(args);
+ const when = (m?.[1] ?? args).trim();
+ const topic = (m?.[2] ?? '').trim();
+ try {
+ return s.schedule(when, topic).confirmation;
+ } catch (err) {
+ return `✗ ${(err as Error).message}`;
+ }
+}
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 7779d1db..a61d1571 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -31,6 +31,7 @@
* mercury/call/approval-resolved notification { callId, approvalId, decision, via }
* plugin → Mercury
* mercury/call/approve request { callId, approvalId, approved } (after checking the owner said yes)
+ * mercury/call/schedule request { when, topic } → { ok, text } ("call me back at 9")
*
* Approvals during a call are asked by voice and in the chat at once; the
* first answer wins. The plugin accepts a spoken yes only when the owner's own
@@ -40,6 +41,7 @@ import { basename } from 'node:path';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { getMercuryHome } from '../utils/config.js';
+import { activeCallScheduler } from './call-schedule.js';
import { BaseChannel, type Channel } from '../channels/base.js';
import type { ChannelMessage, ChannelType } from '../types/channel.js';
import { logger } from '../utils/logger.js';
@@ -269,6 +271,17 @@ export class PluginChannel extends BaseChannel {
case 'mercury/call/briefing':
this.callStarted(String(p.callId ?? ''));
return { instructions: voiceBriefing() };
+ case 'mercury/call/schedule': {
+ // "Call me back at 9" said on a call: the time is worked out here, not by a model.
+ const sched = activeCallScheduler();
+ if (!sched) return { ok: false, text: 'Scheduled calls aren\'t available right now.' };
+ try {
+ const r = sched.schedule(String(p.when ?? ''), typeof p.topic === 'string' ? p.topic : '');
+ return { ok: true, text: r.confirmation.replace(/^✅\s*/, '') };
+ } catch (err) {
+ return { ok: false, text: (err as Error).message };
+ }
+ }
case 'mercury/call/approve': {
// The plugin only sends this after checking the owner's own words on the call.
const approvalId = String(p.approvalId ?? '');
diff --git a/src/plugins/manager.ts b/src/plugins/manager.ts
index 12e18876..a2f28d5c 100644
--- a/src/plugins/manager.ts
+++ b/src/plugins/manager.ts
@@ -34,6 +34,7 @@ import { InProcessRuntime, inProcessLogger } from './runtime/in-process.js';
import { OutOfProcessRuntime } from './runtime/out-of-process.js';
import { PluginChannel, type ChannelStatus } from './channel-bridge.js';
import { transcribeAudio } from './transcribe.js';
+import { CallScheduler, registerCallScheduler } from './call-schedule.js';
import type { PluginRuntime } from './runtime/types.js';
import { providerSecretNames, whenMatches, type WhenCondition, type CatalogEntry, type DisabledCode, type PluginListItem, type PluginManifest, type PluginProviderId, type PluginsState } from './types.js';
import { loadConfig } from '../utils/config.js';
@@ -310,6 +311,12 @@ export class PluginManager {
return;
}
this.running.set(id, { runtime, manifest, version, startedAt: Date.now(), consecutiveFailures: 0, channel });
+ // A channel plugin that can call the owner gets scheduled calls ("call me at 9pm").
+ if (channel && manifest.contributes.tools.some((t) => t.name === 'call_owner')) {
+ const sched = new CallScheduler(id, (text) => channel!.send(text));
+ registerCallScheduler(id, sched);
+ sched.start();
+ }
this.lastErrors.delete(id);
logger.info({ plugin: id, version, kind: manifest.kind }, 'Plugin started');
this.noticeMissingSecrets(id, manifest);
@@ -332,6 +339,7 @@ export class PluginManager {
} finally {
unpublishPlugin(id);
run.channel?.detach();
+ registerCallScheduler(id, null);
}
}
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index 52e5e996..07afe5e8 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -34,7 +34,7 @@ export const PLUGIN_TOOL_NAME_RE = /^[a-z][a-z0-9_]{0,29}$/;
* TUI's SLASH_COMMANDS by src/plugins/commands.test.ts.
*/
export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([
- 'agents', 'bg', 'bot', 'bots', 'budget', 'chat', 'cloud', 'code', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',
+ 'agents', 'bg', 'bot', 'bots', 'budget', 'call', 'calls', 'chat', 'cloud', 'code', 'halt', 'help', 'log', 'memory', 'menu', 'models', 'model',
'permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'saver', 'session', 'sessions', 'skills', 'spotify',
'status', 'stop', 'stream', 'tools', 'update', 'view', 'whatsnew', 'ws', 'start', 'skip', 'new', 'compact', 'clear',
'approve', 'deny', 'yes', 'no', 'cancel', 'pair', 'unpair', 'telegram', 'discord', 'slack', 'signal', 'web', 'exit', 'quit',
diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsx
index 15b9a35d..93c18938 100644
--- a/src/ui/input-composer.tsx
+++ b/src/ui/input-composer.tsx
@@ -125,6 +125,9 @@ export const SLASH_COMMANDS: readonly string[] = [
'/skills install ',
'/skills remove ',
'/skills help',
+ '/call ',
+ '/calls',
+ '/calls cancel ',
'/plugins',
'/plugins search ',
'/plugins info ',
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 7b705267..63aa9418 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -151,6 +151,8 @@ export function getManual(): string {
['/skills view <id>', 'Show details + registry URL for a skill'],
['/skills install <id|url>', 'Install from the registry or a raw SKILL.md URL'],
['/skills remove <id>', 'Uninstall a skill'],
+ ['/call <when> [about …]', 'Schedule Mercury to call you on WhatsApp (9pm, in 20m, tomorrow 8:30am)'],
+ ['/calls', 'List or cancel scheduled calls'],
['/plugins', 'Installed and available plugins, with status'],
['/plugins install <id|path|url>', 'Install a plugin (shows what it needs first)'],
['/plugins enable|disable <id>', 'Turn a plugin on or off'],