Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: schedule WhatsApp calls ("call me in 10 minutes", "call me when it's done")
Salman Qureshib29d81165fa2
diff --git a/plugins/whatsapp/mercury-plugin.template.json b/plugins/whatsapp/mercury-plugin.template.jsonindex a86daa46..16f5fa2c 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.",+ "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}diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.tsindex a364ff1e..c4307342 100644--- a/src/capabilities/permissions.ts+++ b/src/capabilities/permissions.ts@@ -529,9 +529,17 @@ export class PermissionManager {* - "always" is remembered per channel for this plugin tool.* - otherwise the user sees the plugin, tool and arguments.*/+ /** Plugin tools pre-approved for the current turn only (a scheduled task's allowTools). */+ private turnPluginGrants = new Set<string>();++ setTurnPluginGrants(tools: string[]): void {+ this.turnPluginGrants = new Set(tools);+ }+async approvePluginTool(toolKey: string, prompt: string): Promise<boolean> {const ctx = this.ctx();if (this.failClosed) return true;+ if (this.turnPluginGrants.has(toolKey)) return true;if (ctx.channelType === 'internal') return ctx.autoApprove;if (this.isGlobalAutoApproveActive()) return true;if (this.approvedPluginToolsByContext.get(ctx.channelId)?.has(toolKey)) return true;diff --git a/src/capabilities/scheduler/schedule-task.test.ts b/src/capabilities/scheduler/schedule-task.test.tsnew file mode 100644index 00000000..e090b8c8--- /dev/null+++ b/src/capabilities/scheduler/schedule-task.test.ts@@ -0,0 +1,66 @@+import { describe, expect, it } from 'vitest';+import { createScheduleTaskTool } from './schedule-task.js';+import { PermissionManager } from '../permissions.js';+import type { ScheduledTaskManifest } from '../../core/scheduler.js';++function setup(role?: 'admin' | 'member') {+ const added: ScheduledTaskManifest[] = [];+ const asked: string[] = [];+ const scheduler = {+ addDelayedTask: (m: ScheduledTaskManifest) => added.push(m),+ addPersistedTask: (m: ScheduledTaskManifest) => added.push(m),+ persistSchedules: () => {},+ };+ const permissions = {+ requestApproval: async (prompt: string) => { asked.push(prompt); return true; },+ getCurrentSenderRole: () => role,+ } as unknown as PermissionManager;+ const tool = createScheduleTaskTool(scheduler as never, permissions, () => ({ channelId: 'whatsapp:o@lid', channelType: 'whatsapp' })) as unknown as {+ execute: (a: Record<string, unknown>) => Promise<string>;+ };+ return { tool, added, asked };+}++describe('schedule_task with allow_tools', () => {+ it('"call me in 10 minutes": the owner approves the call once, at creation', async () => {+ const { tool, added, asked } = setup('admin');+ const out = await tool.execute({ delay_seconds: 600, description: 'Call about the meeting', prompt: 'Call the owner about the meeting.', allow_tools: ['whatsapp__call_owner'] });+ expect(out).toMatch(/Will trigger in 600 seconds/);+ expect(asked[0]).toMatch(/may use whatsapp__call_owner without asking again/);+ expect(added[0]).toMatchObject({ allowTools: ['whatsapp__call_owner'], sourceChannelType: 'whatsapp', delaySeconds: 600 });+ });++ it('recurring tasks keep allow_tools too', async () => {+ const { tool, added } = setup();+ await tool.execute({ cron: '0 18 * * *', description: 'Evening briefing call', prompt: 'Call me with the briefing.', allow_tools: ['whatsapp__call_owner'] });+ expect(added[0]).toMatchObject({ cron: '0 18 * * *', allowTools: ['whatsapp__call_owner'] });+ });++ it('only plugin tools, and never from a member', async () => {+ const { tool, added } = setup();+ expect(await tool.execute({ delay_seconds: 60, description: 'x', prompt: 'x', allow_tools: ['run_command'] })).toMatch(/only takes plugin tools/);+ const member = setup('member');+ expect(await member.tool.execute({ delay_seconds: 60, description: 'x', prompt: 'x', allow_tools: ['whatsapp__call_owner'] })).toMatch(/Only the owner/);+ expect([...added, ...member.added]).toEqual([]);+ });++ it('without allow_tools nothing is pre-approved', async () => {+ const { tool, added, asked } = setup('admin');+ await tool.execute({ delay_seconds: 60, description: 'Remind me', prompt: 'Remind me to stretch' });+ expect(added[0].allowTools).toBeUndefined();+ expect(asked[0]).toBe('Create scheduled task: Remind me');+ });+});++describe('turn grants', () => {+ it('a granted plugin tool runs without asking for that turn only', async () => {+ const pm = new PermissionManager();+ pm.setCurrentContext('whatsapp', 'whatsapp:o@lid');+ pm.onAsk(async () => 'no');+ pm.setTurnPluginGrants(['whatsapp__call_owner']);+ expect(await pm.approvePluginTool('whatsapp__call_owner', 'x')).toBe(true);+ expect(await pm.approvePluginTool('other__tool', 'x')).toBe(false);+ pm.setTurnPluginGrants([]);+ expect(await pm.approvePluginTool('whatsapp__call_owner', 'x')).toBe(false);+ });+});diff --git a/src/capabilities/scheduler/schedule-task.ts b/src/capabilities/scheduler/schedule-task.tsindex 656f74c4..dff20073 100644--- a/src/capabilities/scheduler/schedule-task.ts+++ b/src/capabilities/scheduler/schedule-task.ts@@ -1,6 +1,7 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';import cron from 'node-cron';+import { isPluginToolName } from '../../plugins/tool-bridge.js';import type { Scheduler, ScheduledTaskManifest } from '../../core/scheduler.js';import type { PermissionManager } from '../permissions.js';@@ -13,8 +14,11 @@ export function createScheduleTaskTool(scheduler: Scheduler, permissions: Permisdescription: z.string().describe('Human-readable description of what this task does'),prompt: z.string().optional().describe('Prompt to send to the agent when the task fires'),skill_name: z.string().optional().describe('Name of a skill to invoke when the task fires'),+ allow_tools: z.array(z.string()).max(10).optional().describe(+ 'Plugin tools the task needs when it fires, approved now so it can run unattended, e.g. ["whatsapp__call_owner"] for "call me in 10 minutes" or "call me when the research is done". Only list tools the task actually needs.',+ ),})),- execute: async ({ cron: cronExpr, delay_seconds, description, prompt, skill_name }) => {+ execute: async ({ cron: cronExpr, delay_seconds, description, prompt, skill_name, allow_tools }) => {if (!cronExpr && !delay_seconds) {return 'Either cron or delay_seconds must be provided.';}@@ -26,7 +30,15 @@ export function createScheduleTaskTool(scheduler: Scheduler, permissions: Permisreturn 'Either prompt or skill_name must be provided so the task has something to do.';}- const approved = await permissions.requestApproval(`Create scheduled task: ${description}`);+ const allowTools = [...new Set((allow_tools ?? []).filter((t) => isPluginToolName(t)))];+ const rejected = (allow_tools ?? []).filter((t) => !isPluginToolName(t));+ if (rejected.length) return `allow_tools only takes plugin tools (like whatsapp__call_owner); not: ${rejected.join(', ')}.`;+ if (allowTools.length && permissions.getCurrentSenderRole() === 'member') {+ return 'Only the owner can schedule tasks that act without asking (allow_tools).';+ }+ const approved = await permissions.requestApproval(+ `Create scheduled task: ${description}${allowTools.length ? ` (when it runs, it may use ${allowTools.join(', ')} without asking again)` : ''}`,+ );if (!approved) return 'Permission denied: scheduled task creation was not approved.';const id = `task-${Date.now().toString(36)}`;@@ -43,6 +55,7 @@ export function createScheduleTaskTool(scheduler: Scheduler, permissions: PermiscreatedAt: new Date().toISOString(),sourceChannelId: ctx.channelId,sourceChannelType: ctx.channelType,+ ...(allowTools.length ? { allowTools } : {}),};scheduler.addDelayedTask(manifest);@@ -65,6 +78,7 @@ export function createScheduleTaskTool(scheduler: Scheduler, permissions: PermiscreatedAt: new Date().toISOString(),sourceChannelId: ctx.channelId,sourceChannelType: ctx.channelType,+ ...(allowTools.length ? { allowTools } : {}),};scheduler.addPersistedTask(manifest);diff --git a/src/core/agent.ts b/src/core/agent.tsindex af95de9f..fa5bef95 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -2641,6 +2641,10 @@ export class Agent {// e.g. WhatsApp): "general" means no tools, no personal memory and no// learning from the turn; the guidance tells the model where it is and// how to write for it.+ // A scheduled task the owner approved with specific plugin tools runs them unattended.+ this.capabilities.permissions.setTurnPluginGrants(+ msg.senderId === 'system' && Array.isArray(msg.metadata?.allowTools) ? (msg.metadata.allowTools as unknown[]).filter((t): t is string => typeof t === 'string') : [],+ );const generalAccess = msg.metadata?.channelAccess === 'general';this.capabilities.setToolsDisabled(generalAccess);const guidance = typeof msg.metadata?.channelGuidance === 'string' ? msg.metadata.channelGuidance.slice(0, 2000) : '';@@ -4194,6 +4198,7 @@ export class Agent {stopHeartbeat();this.finalizeChannelTask(msg);this.capabilities.setToolsDisabled(false);+ this.capabilities.permissions.setTurnPluginGrants([]);this.currentMessage = null;this.currentAbort = null;this.currentAbortReason = null;@@ -4254,7 +4259,7 @@ export class Agent {});}- async processInternalPrompt(prompt: string, channelId?: string, channelType?: string): Promise<void> {+ async processInternalPrompt(prompt: string, channelId?: string, channelType?: string, opts: { allowTools?: string[]; scheduledTaskId?: string } = {}): Promise<void> {const syntheticMsg: ChannelMessage = {id: `internal-${Date.now().toString(36)}`,channelId: channelId || 'internal',@@ -4262,6 +4267,9 @@ export class Agent {senderId: 'system',content: prompt,timestamp: Date.now(),+ ...(opts.allowTools?.length || opts.scheduledTaskId+ ? { metadata: { ...(opts.allowTools?.length ? { allowTools: opts.allowTools } : {}), ...(opts.scheduledTaskId ? { scheduledTaskId: opts.scheduledTaskId } : {}) } }+ : {}),};this.enqueueMessage(syntheticMsg);}@@ -4309,7 +4317,7 @@ export class Agent {if (!prompt) {prompt = `Execute scheduled task: ${manifest.description}`;}- await this.processInternalPrompt(prompt, manifest.sourceChannelId, manifest.sourceChannelType);+ await this.processInternalPrompt(prompt, manifest.sourceChannelId, manifest.sourceChannelType, { allowTools: manifest.allowTools, scheduledTaskId: manifest.id });} catch (err) {logger.error({ err, task: manifest.id }, 'Scheduled task execution failed');}diff --git a/src/core/scheduler.ts b/src/core/scheduler.tsindex 166dfbe4..b14720cc 100644--- a/src/core/scheduler.ts+++ b/src/core/scheduler.ts@@ -26,6 +26,12 @@ export interface ScheduledTaskManifest {sourceChannelType?: string;/** Set for Mercury Bot routines — the run routes to the bot, not the main agent. */botId?: string;+ /**+ * Plugin tools this task may run without asking when it fires (e.g.+ * "whatsapp__call_owner" for "call me in 10 minutes"). Approved by the owner+ * once, when the task was created; nothing else is pre-approved.+ */+ allowTools?: string[];}const SCHEDULES_FILE = 'schedules.yaml';