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: add support for one-shot delayed tasks, persistent command approval, and automatic permission elevation for internal agent operations.

Salman Qureshib98b979c7dcf
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 77dbb9d0..7e24c6fe 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -125,6 +125,8 @@ export class PermissionManager {
private manifest: PermissionsManifest;
private readonly cwd: string;
private askHandler?: (prompt: string) => Promise<string>;
+ private autoApproveAll = false;
+ private elevatedCommands: Set<string> = new Set();
constructor() {
this.cwd = process.cwd();
@@ -135,6 +137,35 @@ export class PermissionManager {
this.askHandler = handler;
}
+ setAutoApproveAll(value: boolean): void {
+ this.autoApproveAll = value;
+ }
+
+ elevateForSkill(allowedTools: string[]): void {
+ if (allowedTools.includes('run_command')) {
+ this.elevatedCommands.add('run_command');
+ }
+ if (allowedTools.includes('read_file') || allowedTools.includes('list_dir')) {
+ this.elevatedCommands.add('fs_read');
+ }
+ if (allowedTools.includes('write_file') || allowedTools.includes('create_file') || allowedTools.includes('delete_file')) {
+ this.elevatedCommands.add('fs_write');
+ }
+ }
+
+ clearElevation(): void {
+ this.elevatedCommands.clear();
+ }
+
+ isElevated(tool: string): boolean {
+ if (this.elevatedCommands.has(tool)) return true;
+ return false;
+ }
+
+ isShellElevated(): boolean {
+ return this.elevatedCommands.has('run_command');
+ }
+
private load(): PermissionsManifest {
if (existsSync(PERMISSIONS_FILE)) {
try {
@@ -162,7 +193,25 @@ export class PermissionManager {
return this.manifest;
}
+ addApprovedCommand(baseCommand: string): void {
+ const cmdName = baseCommand.trim().split(/\s+/)[0];
+ const pattern = `${cmdName} *`;
+ const shell = this.manifest.capabilities.shell;
+ if (!shell.autoApproved.includes(pattern) && !shell.autoApproved.includes(cmdName)) {
+ shell.autoApproved.push(pattern);
+ this.save();
+ logger.info({ pattern }, 'Shell command pattern auto-approved and saved');
+ }
+ }
+
async checkFsAccess(path: string, mode: 'read' | 'write'): Promise<{ allowed: boolean; reason?: string }> {
+ if (mode === 'read' && this.elevatedCommands.has('fs_read')) {
+ return { allowed: true };
+ }
+ if (mode === 'write' && this.elevatedCommands.has('fs_write')) {
+ return { allowed: true };
+ }
+
const fs = this.manifest.capabilities.filesystem;
if (!fs.enabled) {
return { allowed: false, reason: 'Filesystem capability is disabled' };
@@ -181,6 +230,16 @@ export class PermissionManager {
}
async checkShellCommand(command: string): Promise<{ allowed: boolean; reason?: string; needsApproval: boolean }> {
+ if (this.autoApproveAll) {
+ logger.info({ cmd: command.trim() }, 'Shell command auto-approved (auto-approve-all mode)');
+ return { allowed: true, needsApproval: false };
+ }
+
+ if (this.isShellElevated()) {
+ logger.info({ cmd: command.trim() }, 'Shell command auto-approved (skill elevation)');
+ return { allowed: true, needsApproval: false };
+ }
+
const shell = this.manifest.capabilities.shell;
if (!shell.enabled) {
return { allowed: false, reason: 'Shell capability is disabled', needsApproval: false };
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index e1892e1d..5c8e0047 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -49,7 +49,7 @@ export class CapabilityRegistry {
if (this.skillLoader) {
this.tools.install_skill = createInstallSkillTool(this.skillLoader);
this.tools.list_skills = createListSkillsTool(this.skillLoader);
- this.tools.use_skill = createUseSkillTool(this.skillLoader);
+ this.tools.use_skill = createUseSkillTool(this.skillLoader, this.permissions);
logger.info('Skill tools registered');
}
diff --git a/src/capabilities/scheduler/schedule-task.ts b/src/capabilities/scheduler/schedule-task.ts
index 5558b667..e65be566 100644
--- a/src/capabilities/scheduler/schedule-task.ts
+++ b/src/capabilities/scheduler/schedule-task.ts
@@ -5,23 +5,50 @@ import type { Scheduler, ScheduledTaskManifest } from '../../core/scheduler.js';
export function createScheduleTaskTool(scheduler: Scheduler) {
return tool({
- description: 'Schedule a recurring task using a cron expression. You can optionally specify a skill name to invoke or a prompt to process.',
+ description: 'Schedule a task. Use "cron" for recurring tasks (e.g. "0 9 * * *" for daily at 9am) or "delay_seconds" for one-shot delayed tasks (e.g. 15 for "remind me in 15 seconds"). Provide exactly one of cron or delay_seconds.',
parameters: z.object({
- cron: z.string().describe('Cron expression (e.g. "0 9 * * *" for daily at 9am, "*/30 * * * *" for every 30 min)'),
+ cron: z.string().optional().describe('Cron expression for recurring tasks (e.g. "0 9 * * *" for daily at 9am)'),
+ delay_seconds: z.number().optional().describe('Delay in seconds for one-shot tasks (e.g. 15 for "remind me in 15 seconds")'),
description: 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'),
}),
- execute: async ({ cron: cronExpr, description, prompt, skill_name }) => {
- if (!cron.validate(cronExpr)) {
- return `Invalid cron expression: "${cronExpr}". Use standard 5-field cron format (min hour day month weekday).`;
+ execute: async ({ cron: cronExpr, delay_seconds, description, prompt, skill_name }) => {
+ if (!cronExpr && !delay_seconds) {
+ return 'Either cron or delay_seconds must be provided.';
+ }
+ if (cronExpr && delay_seconds) {
+ return 'Provide either cron or delay_seconds, not both.';
}
if (!prompt && !skill_name) {
- return 'Either prompt or skill_name must be provided so the scheduled task has something to do.';
+ return 'Either prompt or skill_name must be provided so the task has something to do.';
}
const id = `task-${Date.now().toString(36)}`;
+
+ if (delay_seconds) {
+ const manifest: ScheduledTaskManifest = {
+ id,
+ description,
+ prompt,
+ skillName: skill_name,
+ delaySeconds: delay_seconds,
+ executeAt: new Date(Date.now() + delay_seconds * 1000).toISOString(),
+ createdAt: new Date().toISOString(),
+ };
+
+ scheduler.addDelayedTask(manifest);
+ scheduler.persistSchedules();
+
+ const triggerType = skill_name ? `skill: ${skill_name}` : `prompt: "${prompt!.slice(0, 60)}"`;
+ return `Reminder "${id}" set. Will trigger in ${delay_seconds} second${delay_seconds !== 1 ? 's' : ''}. ${triggerType}. Description: ${description}`;
+ }
+
+ if (!cron.validate(cronExpr!)) {
+ return `Invalid cron expression: "${cronExpr}". Use standard 5-field cron format (min hour day month weekday).`;
+ }
+
const manifest: ScheduledTaskManifest = {
id,
cron: cronExpr,
diff --git a/src/capabilities/shell/run-command.ts b/src/capabilities/shell/run-command.ts
index be5e328e..56178fed 100644
--- a/src/capabilities/shell/run-command.ts
+++ b/src/capabilities/shell/run-command.ts
@@ -10,7 +10,7 @@ export function createRunCommandTool(permissions: PermissionManager) {
description: `Run a shell command. Commands run in the current working directory unless an absolute path is given.
Blocked commands (sudo, rm -rf /, etc.) are never executed.
Auto-approved commands (ls, cat, git status, etc.) run without asking.
-Other commands require user approval.`,
+Other commands require user approval (y/n/always). "always" saves the approval for future use.`,
parameters: z.object({
command: z.string().describe('The shell command to execute'),
}),
@@ -57,8 +57,19 @@ async function askApproval(command: string, permissions: PermissionManager): Pro
}
const response = await handler(
- `Mercury wants to run: ${command}\nAllow? (y/n): `
+ `Mercury wants to run: ${command}\nAllow? (y/n/always): `
);
- return response.toLowerCase() === 'y' || response.toLowerCase() === 'yes';
+ const normalized = response.toLowerCase().trim();
+
+ if (normalized === 'always') {
+ permissions.addApprovedCommand(command);
+ return true;
+ }
+
+ if (normalized === 'y' || normalized === 'yes') {
+ return true;
+ }
+
+ return false;
}
\ No newline at end of file
diff --git a/src/capabilities/skills/use-skill.ts b/src/capabilities/skills/use-skill.ts
index 4de960f7..ed56ce7f 100644
--- a/src/capabilities/skills/use-skill.ts
+++ b/src/capabilities/skills/use-skill.ts
@@ -1,8 +1,9 @@
import { tool } from 'ai';
import { z } from 'zod';
import type { SkillLoader } from '../../skills/loader.js';
+import type { PermissionManager } from '../permissions.js';
-export function createUseSkillTool(skillLoader: SkillLoader) {
+export function createUseSkillTool(skillLoader: SkillLoader, permissions: PermissionManager) {
return tool({
description: 'Load and invoke a skill by name. Returns the skill\'s full instructions which should be followed as guidance for the current task.',
parameters: z.object({
@@ -14,6 +15,10 @@ export function createUseSkillTool(skillLoader: SkillLoader) {
return `Skill "${name}" not found. Use list_skills to see available skills.`;
}
+ if (skill['allowed-tools'] && skill['allowed-tools'].length > 0) {
+ permissions.elevateForSkill(skill['allowed-tools']);
+ }
+
let result = `## Skill: ${skill.name}\n\n${skill.instructions}`;
if (skill['allowed-tools'] && skill['allowed-tools'].length > 0) {
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 7ec7c036..bac1c0c7 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -103,6 +103,11 @@ export class Agent {
this.lifecycle.transition('thinking');
const startTime = Date.now();
+ const isInternal = msg.channelType === 'internal';
+ if (isInternal) {
+ this.capabilities.permissions.setAutoApproveAll(true);
+ }
+
try {
const provider = this.providers.getDefault();
const systemPrompt = this.buildSystemPrompt();
@@ -200,6 +205,11 @@ export class Agent {
} catch (err) {
logger.error({ err }, 'Error handling message');
this.lifecycle.transition('idle');
+ } finally {
+ if (isInternal) {
+ this.capabilities.permissions.setAutoApproveAll(false);
+ }
+ this.capabilities.permissions.clearElevation();
}
}
diff --git a/src/core/scheduler.ts b/src/core/scheduler.ts
index 1f0efa68..9d1519b9 100644
--- a/src/core/scheduler.ts
+++ b/src/core/scheduler.ts
@@ -15,10 +15,12 @@ export interface ScheduledTask {
export interface ScheduledTaskManifest {
id: string;
- cron: string;
+ cron?: string;
description: string;
skillName?: string;
prompt?: string;
+ delaySeconds?: number;
+ executeAt?: string;
createdAt: string;
}
@@ -52,6 +54,7 @@ export function saveSchedules(tasks: ScheduledTaskManifest[]): void {
export class Scheduler {
private tasks: Map<string, cron.ScheduledTask> = new Map();
+ private delayedTasks: Map<string, NodeJS.Timeout> = new Map();
private taskManifests: Map<string, ScheduledTaskManifest> = new Map();
private heartbeatIntervalMinutes: number;
private heartbeatHandler?: () => Promise<void>;
@@ -113,7 +116,7 @@ export class Scheduler {
this.taskManifests.set(manifest.id, manifest);
this.addTask({
id: manifest.id,
- cron: manifest.cron,
+ cron: manifest.cron!,
description: manifest.description,
handler: async () => {
logger.info({ task: manifest.id }, 'Scheduled task firing');
@@ -124,12 +127,40 @@ export class Scheduler {
});
}
+ addDelayedTask(manifest: ScheduledTaskManifest): void {
+ this.taskManifests.set(manifest.id, manifest);
+ const delayMs = (manifest.delaySeconds || 60) * 1000;
+
+ const timer = setTimeout(async () => {
+ try {
+ logger.info({ task: manifest.id }, 'Delayed task firing');
+ if (this.onScheduledTask) {
+ await this.onScheduledTask(manifest);
+ }
+ } catch (err) {
+ logger.error({ task: manifest.id, err }, 'Delayed task error');
+ } finally {
+ this.delayedTasks.delete(manifest.id);
+ this.taskManifests.delete(manifest.id);
+ this.persistSchedules();
+ }
+ }, delayMs);
+
+ this.delayedTasks.set(manifest.id, timer);
+ logger.info({ id: manifest.id, delaySeconds: manifest.delaySeconds }, 'Delayed task scheduled');
+ }
+
removeTask(id: string): void {
const task = this.tasks.get(id);
if (task) {
task.stop();
this.tasks.delete(id);
}
+ const timer = this.delayedTasks.get(id);
+ if (timer) {
+ clearTimeout(timer);
+ this.delayedTasks.delete(id);
+ }
this.taskManifests.delete(id);
}
@@ -140,10 +171,20 @@ export class Scheduler {
restorePersistedTasks(): void {
const persisted = loadSchedules();
for (const manifest of persisted) {
- if (cron.validate(manifest.cron)) {
+ if (manifest.delaySeconds) {
+ const executeAt = manifest.executeAt ? new Date(manifest.executeAt) : null;
+ const now = Date.now();
+ if (executeAt && executeAt.getTime() > now) {
+ const remainingMs = executeAt.getTime() - now;
+ manifest.delaySeconds = Math.ceil(remainingMs / 1000);
+ this.addDelayedTask(manifest);
+ } else {
+ logger.info({ id: manifest.id }, 'Delayed task already expired, skipping');
+ }
+ } else if (manifest.cron && cron.validate(manifest.cron)) {
this.addPersistedTask(manifest);
} else {
- logger.warn({ id: manifest.id, cron: manifest.cron }, 'Skipping invalid cron expression');
+ logger.warn({ id: manifest.id, cron: manifest.cron }, 'Skipping invalid task');
}
}
if (persisted.length > 0) {
@@ -160,7 +201,11 @@ export class Scheduler {
for (const [, task] of this.tasks) {
task.stop();
}
+ for (const [, timer] of this.delayedTasks) {
+ clearTimeout(timer);
+ }
this.tasks.clear();
+ this.delayedTasks.clear();
this.taskManifests.clear();
}
}
\ No newline at end of file