Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat: implement skill management capabilities and task scheduling system with dynamic identity prompts
Salman Qureshie0de8a70643e
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 2f00726a..42265eaf 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -40,9 +40,17 @@ src/│ └── scheduler.ts # Cron + heartbeat├── capabilities/ # Agentic tools & permissions│ ├── permissions.ts # Permission manager (read/write scope, shell blocklist)-│ ├── registry.ts # Registers all AI SDK tools+│ ├── registry.ts # Registers all AI SDK tools + skill/scheduler tools│ ├── filesystem/ # File ops: read, write, create, list, delete-│ └── shell/ # Shell execution with blocklist+│ ├── shell/ # Shell execution with blocklist+│ ├── skills/ # Skill management tools+│ │ ├── install-skill.ts+│ │ ├── list-skills.ts+│ │ └── use-skill.ts+│ └── scheduler/ # Scheduling tools+│ ├── schedule-task.ts+│ ├── list-tasks.ts+│ └── cancel-task.ts├── memory/ # Persistence layer│ └── store.ts # Short/long/episodic memory├── providers/ # LLM APIs@@ -52,9 +60,10 @@ src/│ └── registry.ts├── soul/ # Consciousness│ └── identity.ts # Soul/persona/taste loader + guardrails-├── skills/ # Modular abilities-│ ├── types.ts-│ └── loader.ts+├── skills/ # Modular abilities (Agent Skills spec)+│ ├── types.ts # SkillMeta, SkillDiscovery, Skill types+│ ├── loader.ts # SKILL.md parser, progressive disclosure+│ └── index.ts # Barrel exports├── types/ # Type definitions└── utils/ # Config, logger, tokens```@@ -111,6 +120,12 @@ When Mercury needs a scope it doesn't have:| `list_dir` | List directory contents | Read scope for path || `delete_file` | Delete a file | Write scope, always confirms || `run_command` | Execute shell command | Blocklist + approval list + scope |+| `install_skill` | Install a skill from content or URL | No restriction |+| `list_skills` | List installed skills | No restriction |+| `use_skill` | Load and invoke a skill's instructions | No restriction |+| `schedule_task` | Schedule a recurring cron task | Validates cron expression |+| `list_scheduled_tasks` | List scheduled tasks | No restriction |+| `cancel_scheduled_task` | Cancel a scheduled task | No restriction |## Agent Lifecycle@@ -130,6 +145,7 @@ All runtime data lives in `~/.mercury/` (not the project directory):| Soul files | `~/.mercury/soul/*.md` || Memory | `~/.mercury/memory/` || Skills | `~/.mercury/skills/` |+| Schedules | `~/.mercury/schedules.yaml` || Permissions | `~/.mercury/permissions.yaml` |## Token Budget@@ -149,4 +165,82 @@ All runtime data lives in `~/.mercury/` (not the project directory):- grammY framework + @grammyjs/stream for streaming- Typing indicator while processing- Proactive messages via heartbeat-- `TELEGRAM_BOT_TOKEN` in .env or mercury.yaml\ No newline at end of file+- `TELEGRAM_BOT_TOKEN` in .env or mercury.yaml++## Skills System++Mercury supports the Agent Skills specification. Skills are modular, installable instruction sets that extend Mercury's capabilities without code changes.++### Skill Format++Each skill is a directory under `~/.mercury/skills/` containing a `SKILL.md`:++```+~/.mercury/skills/+├── daily-digest/+│ └── SKILL.md # Required: YAML frontmatter + markdown instructions+├── code-review/+│ ├── SKILL.md+│ ├── scripts/ # Optional: executable scripts+│ └── references/ # Optional: reference documents+└── _template/+ └── SKILL.md # Seeded template for new skills+```++### SKILL.md Structure++```markdown+---+name: daily-digest+description: Send a daily summary of activity+version: 0.1.0+allowed-tools:+ - read_file+ - list_dir+ - run_command+---++# Daily Digest++Instructions for Mercury to follow when this skill is invoked...+```++### Progressive Disclosure++- **Startup**: Only skill names + descriptions are loaded (token-efficient)+- **Invocation**: Full skill instructions loaded on demand via `use_skill` tool+- This keeps the system prompt small while making skills available++### Skill Tools++- `install_skill`: Install from markdown content or URL+- `list_skills`: Show all installed skills+- `use_skill`: Load and invoke skill instructions into agent context++## Scheduler++Mercury can schedule recurring tasks using cron expressions. Tasks persist to `~/.mercury/schedules.yaml` and are restored on startup.++### Scheduled Task Fields++| Field | Description |+|---|---|+| `id` | Unique task identifier |+| `cron` | Standard 5-field cron expression |+| `description` | Human-readable description |+| `prompt` | Text prompt to send to agent when task fires |+| `skill_name` | Optional: skill to invoke when task fires |+| `createdAt` | ISO timestamp |++### How Tasks Execute++When a scheduled task fires:+1. If `skill_name` is set, Mercury is prompted to invoke that skill via `use_skill`+2. If `prompt` is set, Mercury processes it as an internal (non-channel) message+3. Internal messages don't produce visible channel responses — they run silently in the agent loop++### Scheduler Tools++- `schedule_task`: Create a cron task with prompt or skill_name+- `list_scheduled_tasks`: Show all scheduled tasks+- `cancel_scheduled_task`: Remove a scheduled task\ No newline at end of filediff --git a/DECISIONS.md b/DECISIONS.mdindex ba2d2234..8cd11b5c 100644--- a/DECISIONS.md+++ b/DECISIONS.md@@ -36,4 +36,16 @@- **Context**: Agent personality needs to be editable, versionable, and token-efficient.- **Decision**: Four separate markdown files: soul.md, persona.md, taste.md, heartbeat.md. Only soul + persona injected every request; taste + heartbeat selectively.-- **Consequence**: ~350 token baseline for identity. Owner can edit personality without code changes.\ No newline at end of file+- **Consequence**: ~350 token baseline for identity. Owner can edit personality without code changes.++## ADR-007: Agent Skills specification++- **Context**: Skills need to be modular, installable at runtime, and token-efficient.+- **Decision**: Adopt the Agent Skills spec (agentskills.io). Skills use `SKILL.md` with YAML frontmatter + markdown instructions. Stored in `~/.mercury/skills/`. Progressive disclosure: only name+description loaded at startup; full instructions loaded on invocation.+- **Consequence**: Skills are human-readable markdown, no code required. Token budget stays low. Install by pasting content or URL.++## ADR-008: Scheduler with YAML persistence++- **Context**: Mercury needs to set reminders, run periodic tasks, and trigger skills on a schedule.+- **Decision**: Expose `schedule_task`, `list_scheduled_tasks`, `cancel_scheduled_task` as AI-callable tools. Persist scheduled tasks to `~/.mercury/schedules.yaml`. Restore on startup. Tasks fire as internal (non-channel) messages through the agent loop.+- **Consequence**: Mercury can autonomously schedule work. Tasks survive restarts. Internal execution keeps scheduled tasks invisible to channels unless the agent explicitly sends output.\ No newline at end of filediff --git a/src/capabilities/registry.ts b/src/capabilities/registry.tsindex b331fe97..e1892e1d 100644--- a/src/capabilities/registry.ts+++ b/src/capabilities/registry.ts@@ -6,14 +6,26 @@ import { createCreateFileTool } from './filesystem/create-file.js';import { createListDirTool } from './filesystem/list-dir.js';import { createDeleteFileTool } from './filesystem/delete-file.js';import { createRunCommandTool } from './shell/run-command.js';+import { createInstallSkillTool } from './skills/install-skill.js';+import { createListSkillsTool } from './skills/list-skills.js';+import { createUseSkillTool } from './skills/use-skill.js';+import { createScheduleTaskTool } from './scheduler/schedule-task.js';+import { createListTasksTool } from './scheduler/list-tasks.js';+import { createCancelTaskTool } from './scheduler/cancel-task.js';+import type { SkillLoader } from '../skills/loader.js';+import type { Scheduler } from '../core/scheduler.js';import { logger } from '../utils/logger.js';export class CapabilityRegistry {readonly permissions: PermissionManager;private tools: Record<string, Tool> = {};+ private skillLoader?: SkillLoader;+ private scheduler?: Scheduler;- constructor() {+ constructor(skillLoader?: SkillLoader, scheduler?: Scheduler) {this.permissions = new PermissionManager();+ this.skillLoader = skillLoader;+ this.scheduler = scheduler;this.registerAll();}@@ -33,6 +45,20 @@ export class CapabilityRegistry {this.tools.run_command = createRunCommandTool(this.permissions);logger.info('Shell tool registered');}++ if (this.skillLoader) {+ this.tools.install_skill = createInstallSkillTool(this.skillLoader);+ this.tools.list_skills = createListSkillsTool(this.skillLoader);+ this.tools.use_skill = createUseSkillTool(this.skillLoader);+ logger.info('Skill tools registered');+ }++ if (this.scheduler) {+ this.tools.schedule_task = createScheduleTaskTool(this.scheduler);+ this.tools.list_scheduled_tasks = createListTasksTool(this.scheduler);+ this.tools.cancel_scheduled_task = createCancelTaskTool(this.scheduler);+ logger.info('Scheduler tools registered');+ }}getTools(): Record<string, Tool> {@@ -42,4 +68,8 @@ export class CapabilityRegistry {getToolNames(): string[] {return Object.keys(this.tools);}++ getSkillContext(): string {+ return this.skillLoader?.getSkillSummariesText() || '';+ }}\ No newline at end of filediff --git a/src/capabilities/scheduler/cancel-task.ts b/src/capabilities/scheduler/cancel-task.tsnew file mode 100644index 00000000..189e4226--- /dev/null+++ b/src/capabilities/scheduler/cancel-task.ts@@ -0,0 +1,24 @@+import { tool } from 'ai';+import { z } from 'zod';+import type { Scheduler } from '../../core/scheduler.js';++export function createCancelTaskTool(scheduler: Scheduler) {+ return tool({+ description: 'Cancel and remove a scheduled task by its ID.',+ parameters: z.object({+ id: z.string().describe('ID of the scheduled task to cancel'),+ }),+ execute: async ({ id }) => {+ const manifests = scheduler.getManifests();+ const exists = manifests.some(m => m.id === id);+ if (!exists) {+ return `Task "${id}" not found. Use list_scheduled_tasks to see active tasks.`;+ }++ scheduler.removeTask(id);+ scheduler.persistSchedules();++ return `Task "${id}" cancelled and removed.`;+ },+ });+}\ No newline at end of filediff --git a/src/capabilities/scheduler/list-tasks.ts b/src/capabilities/scheduler/list-tasks.tsnew file mode 100644index 00000000..95c76b39--- /dev/null+++ b/src/capabilities/scheduler/list-tasks.ts@@ -0,0 +1,20 @@+import { tool } from 'ai';+import { z } from 'zod';+import type { Scheduler, ScheduledTaskManifest } from '../../core/scheduler.js';++export function createListTasksTool(scheduler: Scheduler) {+ return tool({+ description: 'List all scheduled tasks with their cron expressions and descriptions.',+ parameters: z.object({}),+ execute: async () => {+ const manifests = scheduler.getManifests();+ if (manifests.length === 0) {+ return 'No scheduled tasks. Use schedule_task to create one.';+ }+ return manifests.map((m: ScheduledTaskManifest) => {+ const trigger = m.skillName ? `skill: ${m.skillName}` : m.prompt ? `prompt: "${m.prompt.slice(0, 40)}"` : 'no action';+ return `${m.id} | ${m.cron} | ${m.description} | ${trigger}`;+ }).join('\n');+ },+ });+}\ No newline at end of filediff --git a/src/capabilities/scheduler/schedule-task.ts b/src/capabilities/scheduler/schedule-task.tsnew file mode 100644index 00000000..5558b667--- /dev/null+++ b/src/capabilities/scheduler/schedule-task.ts@@ -0,0 +1,41 @@+import { tool } from 'ai';+import { z } from 'zod';+import cron from 'node-cron';+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.',+ parameters: z.object({+ cron: z.string().describe('Cron expression (e.g. "0 9 * * *" for daily at 9am, "*/30 * * * *" for every 30 min)'),+ 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).`;+ }++ if (!prompt && !skill_name) {+ return 'Either prompt or skill_name must be provided so the scheduled task has something to do.';+ }++ const id = `task-${Date.now().toString(36)}`;+ const manifest: ScheduledTaskManifest = {+ id,+ cron: cronExpr,+ description,+ prompt,+ skillName: skill_name,+ createdAt: new Date().toISOString(),+ };++ scheduler.addPersistedTask(manifest);+ scheduler.persistSchedules();++ const triggerType = skill_name ? `skill: ${skill_name}` : `prompt: "${prompt!.slice(0, 60)}"`;+ return `Task "${id}" scheduled. Cron: ${cronExpr}. Will execute ${triggerType}. Description: ${description}`;+ },+ });+}\ No newline at end of filediff --git a/src/capabilities/skills/install-skill.ts b/src/capabilities/skills/install-skill.tsnew file mode 100644index 00000000..9e1f1921--- /dev/null+++ b/src/capabilities/skills/install-skill.ts@@ -0,0 +1,53 @@+import { tool } from 'ai';+import { z } from 'zod';+import type { SkillLoader } from '../../skills/loader.js';+import { parse as parseYaml } from 'yaml';++export function createInstallSkillTool(skillLoader: SkillLoader) {+ return tool({+ description: 'Install a new skill by providing SKILL.md markdown content or a URL. The content must have YAML frontmatter (---) with at least name and description fields.',+ parameters: z.object({+ content: z.string().optional().describe('Raw SKILL.md markdown content with YAML frontmatter'),+ url: z.string().optional().describe('URL to fetch a SKILL.md from'),+ }),+ execute: async ({ content, url }) => {+ let skillContent: string;++ if (url && !content) {+ try {+ const resp = await fetch(url);+ if (!resp.ok) {+ return `Failed to fetch skill from URL: ${resp.status} ${resp.statusText}`;+ }+ skillContent = await resp.text();+ } catch (err: any) {+ return `Failed to fetch skill from URL: ${err.message}`;+ }+ } else if (content) {+ skillContent = content;+ } else {+ return 'Either content or url must be provided.';+ }++ const fmMatch = skillContent.match(/^---\s*\n([\s\S]*?)\n---/);+ if (!fmMatch) {+ return 'Invalid SKILL.md: missing YAML frontmatter (--- delimiters).';+ }++ try {+ const meta = parseYaml(fmMatch[1]) as Record<string, any>;+ if (!meta.name || !meta.description) {+ return 'Invalid SKILL.md: frontmatter must include at least "name" and "description".';+ }+ } catch {+ return 'Invalid SKILL.md: could not parse YAML frontmatter.';+ }++ const fmMatch2 = skillContent.match(/^---\s*\n([\s\S]*?)\n---/);+ const meta = parseYaml(fmMatch2![1]) as { name: string };+ const skillDir = skillLoader.saveSkill(meta.name, skillContent);++ return `Skill "${meta.name}" installed to ${skillDir}. Use list_skills to see all installed skills, or use_skill to invoke it.`;+ },+ });+}\ No newline at end of filediff --git a/src/capabilities/skills/list-skills.ts b/src/capabilities/skills/list-skills.tsnew file mode 100644index 00000000..85d7eeba--- /dev/null+++ b/src/capabilities/skills/list-skills.ts@@ -0,0 +1,17 @@+import { tool } from 'ai';+import { z } from 'zod';+import type { SkillLoader } from '../../skills/loader.js';++export function createListSkillsTool(skillLoader: SkillLoader) {+ return tool({+ description: 'List all installed skills with their names and descriptions.',+ parameters: z.object({}),+ execute: async () => {+ const skills = skillLoader.getDiscovered();+ if (skills.length === 0) {+ return 'No skills installed. Use install_skill to add one.';+ }+ return skills.map(s => `${s.name}: ${s.description}`).join('\n');+ },+ });+}\ No newline at end of filediff --git a/src/capabilities/skills/use-skill.ts b/src/capabilities/skills/use-skill.tsnew file mode 100644index 00000000..4de960f7--- /dev/null+++ b/src/capabilities/skills/use-skill.ts@@ -0,0 +1,30 @@+import { tool } from 'ai';+import { z } from 'zod';+import type { SkillLoader } from '../../skills/loader.js';++export function createUseSkillTool(skillLoader: SkillLoader) {+ 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({+ name: z.string().describe('Name of the skill to invoke'),+ }),+ execute: async ({ name }) => {+ const skill = skillLoader.load(name);+ if (!skill) {+ return `Skill "${name}" not found. Use list_skills to see available skills.`;+ }++ let result = `## Skill: ${skill.name}\n\n${skill.instructions}`;++ if (skill['allowed-tools'] && skill['allowed-tools'].length > 0) {+ result += `\n\nAllowed tools: ${skill['allowed-tools'].join(', ')}`;+ }++ if (skill['disable-model-invocation']) {+ result += '\n\nNote: This skill has model invocation disabled. Follow instructions only.';+ }++ return result;+ },+ });+}\ No newline at end of filediff --git a/src/core/agent.ts b/src/core/agent.tsindex afe46899..4e8e28d5 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -7,6 +7,7 @@ import type { ChannelRegistry } from '../channels/registry.js';import type { MercuryConfig } from '../utils/config.js';import type { TokenBudget } from '../utils/tokens.js';import type { CapabilityRegistry } from '../capabilities/registry.js';+import type { ScheduledTaskManifest } from './scheduler.js';import { Lifecycle } from './lifecycle.js';import { Scheduler } from './scheduler.js';import { logger } from '../utils/logger.js';@@ -31,11 +32,14 @@ export class Agent {private channels: ChannelRegistry,private tokenBudget: TokenBudget,capabilities: CapabilityRegistry,+ scheduler: Scheduler,) {this.lifecycle = new Lifecycle();- this.scheduler = new Scheduler(config);+ this.scheduler = scheduler;this.capabilities = capabilities;+ this.scheduler.setOnScheduledTask(async (manifest) => this.handleScheduledTask(manifest));+this.channels.onIncomingMessage((msg) => this.enqueueMessage(msg));this.scheduler.onHeartbeat(async () => {@@ -77,6 +81,7 @@ export class Agent {async wake(): Promise<void> {this.lifecycle.transition('onboarding');this.lifecycle.transition('idle');+ this.scheduler.restorePersistedTasks();this.scheduler.startHeartbeat();await this.channels.startAll();this.running = true;@@ -99,7 +104,7 @@ export class Agent {try {const provider = this.providers.getDefault();- const systemPrompt = this.identity.getSystemPrompt(this.config.identity);+ const systemPrompt = this.buildSystemPrompt();const recentMemory = this.shortTerm.getRecent(msg.channelId, 10);const relevantFacts = this.longTerm.search(msg.content, 3);@@ -143,7 +148,7 @@ export class Agent {if (toolCalls && toolCalls.length > 0) {const names = toolCalls.map((tc: any) => tc.toolName).join(', ');logger.info({ tools: names }, 'Tool call step');- if (channel) {+ if (channel && msg.channelType !== 'internal') {await channel.send(` [Using: ${names}]`, msg.channelId).catch(() => {});}}@@ -182,11 +187,11 @@ export class Agent {channelType: msg.channelType,});- if (channel) {+ if (channel && msg.channelType !== 'internal') {logger.info({ channelType: msg.channelType, targetId: msg.channelId }, 'Sending response');await channel.send(finalText, msg.channelId);} else {- logger.warn({ channelType: msg.channelType }, 'No channel found for response');+ logger.debug('Internal prompt processed, no channel response needed');}this.lifecycle.transition('idle');@@ -196,6 +201,44 @@ export class Agent {}}+ private buildSystemPrompt(): string {+ let prompt = this.identity.getSystemPrompt(this.config.identity);+ const skillContext = this.capabilities.getSkillContext();+ if (skillContext) {+ prompt += '\n\n' + skillContext;+ }+ return prompt;+ }++ async processInternalPrompt(prompt: string, channelId?: string): Promise<void> {+ const syntheticMsg: ChannelMessage = {+ id: `internal-${Date.now().toString(36)}`,+ channelId: channelId || 'internal',+ channelType: 'internal',+ senderId: 'system',+ content: prompt,+ timestamp: Date.now(),+ };+ this.enqueueMessage(syntheticMsg);+ }++ private async handleScheduledTask(manifest: ScheduledTaskManifest): Promise<void> {+ logger.info({ task: manifest.id }, 'Processing scheduled task');+ try {+ let prompt = manifest.prompt || '';+ if (manifest.skillName) {+ const skillHint = `Invoke the skill "${manifest.skillName}" using the use_skill tool and follow its instructions.`;+ prompt = prompt ? `${prompt} ${skillHint}` : `Scheduled task triggered. ${skillHint}`;+ }+ if (!prompt) {+ prompt = `Execute scheduled task: ${manifest.description}`;+ }+ await this.processInternalPrompt(prompt);+ } catch (err) {+ logger.error({ err, task: manifest.id }, 'Scheduled task execution failed');+ }+ }+private async heartbeat(): Promise<void> {logger.debug('Heartbeat tick');diff --git a/src/core/scheduler.ts b/src/core/scheduler.tsindex 5095478e..1f0efa68 100644--- a/src/core/scheduler.ts+++ b/src/core/scheduler.ts@@ -1,7 +1,10 @@import cron from 'node-cron';+import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';+import { join } from 'node:path';+import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';import type { MercuryConfig } from '../utils/config.js';+import { getMercuryHome } from '../utils/config.js';import { logger } from '../utils/logger.js';-import type { EpisodicMemory } from '../memory/store.js';export interface ScheduledTask {id: string;@@ -10,16 +13,61 @@ export interface ScheduledTask {description: string;}+export interface ScheduledTaskManifest {+ id: string;+ cron: string;+ description: string;+ skillName?: string;+ prompt?: string;+ createdAt: string;+}++const SCHEDULES_FILE = 'schedules.yaml';++function getSchedulesPath(): string {+ return join(getMercuryHome(), SCHEDULES_FILE);+}++export function loadSchedules(): ScheduledTaskManifest[] {+ const path = getSchedulesPath();+ if (!existsSync(path)) return [];+ try {+ const raw = readFileSync(path, 'utf-8');+ const data = parseYaml(raw) as { tasks?: ScheduledTaskManifest[] };+ return data.tasks || [];+ } catch (err) {+ logger.warn({ err }, 'Failed to load schedules.yaml');+ return [];+ }+}++export function saveSchedules(tasks: ScheduledTaskManifest[]): void {+ const path = getSchedulesPath();+ const dir = getMercuryHome();+ if (!existsSync(dir)) {+ mkdirSync(dir, { recursive: true });+ }+ writeFileSync(path, stringifyYaml({ tasks }), 'utf-8');+}+export class Scheduler {private tasks: Map<string, cron.ScheduledTask> = new Map();+ private taskManifests: Map<string, ScheduledTaskManifest> = new Map();private heartbeatIntervalMinutes: number;private heartbeatHandler?: () => Promise<void>;private heartbeatTimer: NodeJS.Timeout | null = null;- constructor(config: MercuryConfig) {+ constructor(+ config: MercuryConfig,+ private onScheduledTask?: (manifest: ScheduledTaskManifest) => Promise<void>,+ ) {this.heartbeatIntervalMinutes = config.heartbeat.intervalMinutes;}+ setOnScheduledTask(handler: (manifest: ScheduledTaskManifest) => Promise<void>): void {+ this.onScheduledTask = handler;+ }+onHeartbeat(handler: () => Promise<void>): void {this.heartbeatHandler = handler;}@@ -61,12 +109,50 @@ export class Scheduler {logger.info({ id: task.id, cron: task.cron, desc: task.description }, 'Task scheduled');}+ addPersistedTask(manifest: ScheduledTaskManifest): void {+ this.taskManifests.set(manifest.id, manifest);+ this.addTask({+ id: manifest.id,+ cron: manifest.cron,+ description: manifest.description,+ handler: async () => {+ logger.info({ task: manifest.id }, 'Scheduled task firing');+ if (this.onScheduledTask) {+ await this.onScheduledTask(manifest);+ }+ },+ });+ }+removeTask(id: string): void {const task = this.tasks.get(id);if (task) {task.stop();this.tasks.delete(id);}+ this.taskManifests.delete(id);+ }++ getManifests(): ScheduledTaskManifest[] {+ return [...this.taskManifests.values()];+ }++ restorePersistedTasks(): void {+ const persisted = loadSchedules();+ for (const manifest of persisted) {+ if (cron.validate(manifest.cron)) {+ this.addPersistedTask(manifest);+ } else {+ logger.warn({ id: manifest.id, cron: manifest.cron }, 'Skipping invalid cron expression');+ }+ }+ if (persisted.length > 0) {+ logger.info({ count: persisted.length }, 'Restored persisted scheduled tasks');+ }+ }++ persistSchedules(): void {+ saveSchedules(this.getManifests());}stopAll(): void {@@ -75,5 +161,6 @@ export class Scheduler {task.stop();}this.tasks.clear();+ this.taskManifests.clear();}}\ No newline at end of filediff --git a/src/index.ts b/src/index.tsindex a73a9561..8013fde3 100644--- a/src/index.ts+++ b/src/index.ts@@ -7,10 +7,12 @@ import { Identity } from './soul/identity.js';import { ShortTermMemory, LongTermMemory, EpisodicMemory } from './memory/store.js';import { ProviderRegistry } from './providers/registry.js';import { Agent } from './core/agent.js';+import { Scheduler } from './core/scheduler.js';import { ChannelRegistry } from './channels/registry.js';import { CLIChannel } from './channels/cli.js';import { TokenBudget } from './utils/tokens.js';import { CapabilityRegistry } from './capabilities/registry.js';+import { SkillLoader } from './skills/loader.js';function hr() {console.log(chalk.dim('─'.repeat(50)));@@ -22,6 +24,22 @@ function banner() {console.log(chalk.cyan(' ╠╦╝├┤ │ ││ │├┤ '));console.log(chalk.cyan(' ╩╚═└─┘ ┴ ┴┴─┘└─┘'));console.log(chalk.dim(' v0.1.0 — an AI agent for personal tasks'));+ console.log(chalk.dim(' by Cosmic Stack — mercury.cosmicstack.org'));+ console.log('');+}++function splashScreen() {+ console.log('');+ console.log(chalk.cyan(' ╦═╗┌─┐┌┬┐┬┬ ┬┌─┐'));+ console.log(chalk.cyan(' ╠╦╝├┤ │ ││ │├┤ '));+ console.log(chalk.cyan(' ╩╚═└─┘ ┴ ┴┴─┘└─┘'));+ console.log('');+ console.log(chalk.dim(' ─────────────────────────────────────'));+ console.log(chalk.white(' M E R C U R Y'));+ console.log(chalk.dim(' ─────────────────────────────────────'));+ console.log(chalk.dim(' an AI agent for personal tasks'));+ console.log(chalk.cyan(' by Cosmic Stack'));+ console.log(chalk.dim(' mercury.cosmicstack.org'));console.log('');}@@ -36,7 +54,7 @@ async function ask(prompt: string): Promise<string> {}async function onboarding(): Promise<void> {- banner();+ splashScreen();console.log(chalk.yellow(' First run detected — let\'s set you up.'));hr();console.log('');@@ -53,6 +71,8 @@ async function onboarding(): Promise<void> {const agentName = await ask(chalk.white(` Agent name [${config.identity.name}]: `));if (agentName) config.identity.name = agentName;+ config.identity.creator = 'Cosmic Stack';+hr();console.log('');console.log(chalk.white(' LLM Providers'));@@ -97,8 +117,10 @@ async function onboarding(): Promise<void> {console.log(chalk.green(` ✓ Soul files seeded in ${home}/soul/`));console.log(chalk.green(` ✓ Memory stored in ${home}/memory/`));console.log(chalk.green(` ✓ Permissions seeded in ${home}/permissions.yaml`));+ console.log(chalk.green(` ✓ Skills directory ready in ${home}/skills/`));console.log('');console.log(chalk.cyan(` ${config.identity.name} is ready. Run \`mercury start\` to begin.`));+ console.log(chalk.dim(' mercury.cosmicstack.org'));console.log('');}@@ -121,9 +143,11 @@ async function runAgent(): Promise<void> {const available = providers.listAvailable();console.log(chalk.dim(` Providers: ${available.join(', ')}`));- const capabilities = new CapabilityRegistry();- const toolNames = capabilities.getToolNames();- console.log(chalk.dim(` Tools: ${toolNames.join(', ')}`));+ const skillLoader = new SkillLoader();+ const skills = skillLoader.discover();+ console.log(chalk.dim(` Skills: ${skills.length > 0 ? skills.map(s => s.name).join(', ') : 'none installed'}`));++ const scheduler = new Scheduler(config);const identity = new Identity();const shortTerm = new ShortTermMemory(config);@@ -131,9 +155,10 @@ async function runAgent(): Promise<void> {const episodic = new EpisodicMemory(config);const channels = new ChannelRegistry(config);+ const capabilities = new CapabilityRegistry(skillLoader, scheduler);const agent = new Agent(- config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget, capabilities,+ config, providers, identity, shortTerm, longTerm, episodic, channels, tokenBudget, capabilities, scheduler,);await agent.birth();@@ -148,8 +173,14 @@ async function runAgent(): Promise<void> {}const activeCh = channels.getActiveChannels();+ const toolNames = capabilities.getToolNames();console.log(chalk.dim(` Channels: ${activeCh.join(', ')}`));+ console.log(chalk.dim(` Tools: ${toolNames.join(', ')}`));console.log(chalk.dim(` Permissions: ${getMercuryHome()}/permissions.yaml`));+ console.log(chalk.dim(` Schedules: ${getMercuryHome()}/schedules.yaml`));+ if (config.identity.creator) {+ console.log(chalk.dim(` Creator: ${config.identity.creator}`));+ }hr();console.log('');console.log(chalk.green(` ${name} is live. Type a message and press Enter.`));@@ -207,11 +238,17 @@ program.action(() => {const config = loadConfig();const home = getMercuryHome();+ const skillLoader = new SkillLoader();+ const skills = skillLoader.discover();banner();console.log(` Name: ${chalk.cyan(config.identity.name)}`);console.log(` Owner: ${chalk.white(config.identity.owner || '(not set)')}`);+ if (config.identity.creator) {+ console.log(` Creator: ${chalk.white(config.identity.creator)}`);+ }console.log(` Provider: ${chalk.white(config.providers.default)}`);console.log(` Telegram: ${config.channels.telegram.enabled ? chalk.green('enabled') : chalk.dim('disabled')}`);+ console.log(` Skills: ${skills.length > 0 ? chalk.green(skills.map(s => s.name).join(', ')) : chalk.dim('none')}`);console.log(` Budget: ${chalk.white(config.tokens.dailyBudget)} tokens/day`);console.log(` Setup: ${isSetupComplete() ? chalk.green('complete') : chalk.red('not done')}`);console.log(` Home: ${chalk.dim(home)}`);diff --git a/src/skills/index.ts b/src/skills/index.tsindex f102b7e9..165d5d10 100644--- a/src/skills/index.ts+++ b/src/skills/index.ts@@ -1,2 +1,2 @@export { SkillLoader } from './loader.js';-export type { Skill, SkillManifest, SkillInput, SkillOutput } from './types.js';\ No newline at end of file+export type { Skill, SkillDiscovery, SkillMeta } from './types.js';\ No newline at end of filediff --git a/src/skills/loader.ts b/src/skills/loader.tsindex 404cddf1..31d6357c 100644--- a/src/skills/loader.ts+++ b/src/skills/loader.ts@@ -1,19 +1,42 @@import { existsSync, readFileSync, readdirSync, mkdirSync, writeFileSync } from 'node:fs';import { join } from 'node:path';+import { parse as parseYaml } from 'yaml';import { getMercuryHome } from '../utils/config.js';-import type { SkillManifest } from './types.js';+import type { SkillDiscovery, Skill, SkillMeta } from './types.js';import { logger } from '../utils/logger.js';+const SKILL_FILE = 'SKILL.md';++function parseSkillMd(content: string): { meta: SkillMeta; instructions: string } | null {+ const fmMatch = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);+ if (!fmMatch) return null;++ try {+ const meta = parseYaml(fmMatch[1]) as SkillMeta;+ const instructions = fmMatch[2].trim();+ if (!meta.name || !meta.description) {+ logger.warn({ meta }, 'SKILL.md missing required fields (name, description)');+ return null;+ }+ return { meta, instructions };+ } catch (err) {+ logger.warn({ err }, 'Failed to parse SKILL.md frontmatter');+ return null;+ }+}+export class SkillLoader {private skillsDir: string;- private manifests: Map<string, SkillManifest> = new Map();+ private discovered: Map<string, SkillDiscovery> = new Map();+ private loaded: Map<string, Skill> = new Map();constructor(skillsDir?: string) {this.skillsDir = skillsDir || join(getMercuryHome(), 'skills');}- discover(): SkillManifest[] {- this.manifests.clear();+ discover(): SkillDiscovery[] {+ this.discovered.clear();+ this.loaded.clear();if (!existsSync(this.skillsDir)) {mkdirSync(this.skillsDir, { recursive: true });this.seedTemplate();@@ -23,53 +46,112 @@ export class SkillLoader {const entries = readdirSync(this.skillsDir, { withFileTypes: true });for (const entry of entries) {if (!entry.isDirectory() || entry.name.startsWith('_')) continue;- const manifestPath = join(this.skillsDir, entry.name, 'manifest.json');- if (!existsSync(manifestPath)) continue;+ const skillPath = join(this.skillsDir, entry.name, SKILL_FILE);+ if (!existsSync(skillPath)) continue;+ try {+ const raw = readFileSync(skillPath, 'utf-8');+ const parsed = parseSkillMd(raw);+ if (!parsed) continue;+ this.discovered.set(parsed.meta.name, {+ name: parsed.meta.name,+ description: parsed.meta.description,+ });+ logger.info({ skill: parsed.meta.name }, 'Skill discovered');+ } catch (err) {+ logger.warn({ dir: entry.name, err }, 'Failed to load skill');+ }+ }++ return [...this.discovered.values()];+ }++ load(name: string): Skill | null {+ const cached = this.loaded.get(name);+ if (cached) return cached;++ for (const entry of readdirSync(this.skillsDir, { withFileTypes: true })) {+ if (!entry.isDirectory() || entry.name.startsWith('_')) continue;+ const skillPath = join(this.skillsDir, entry.name, SKILL_FILE);+ if (!existsSync(skillPath)) continue;try {- const raw = readFileSync(manifestPath, 'utf-8');- const manifest: SkillManifest = JSON.parse(raw);- this.manifests.set(manifest.name, manifest);- logger.info({ skill: manifest.name }, 'Skill discovered');+ const raw = readFileSync(skillPath, 'utf-8');+ const parsed = parseSkillMd(raw);+ if (!parsed || parsed.meta.name !== name) continue;++ const skillDir = join(this.skillsDir, entry.name);+ const skill: Skill = {+ ...parsed.meta,+ instructions: parsed.instructions,+ scriptsDir: existsSync(join(skillDir, 'scripts')) ? join(skillDir, 'scripts') : undefined,+ referencesDir: existsSync(join(skillDir, 'references')) ? join(skillDir, 'references') : undefined,+ };+ this.loaded.set(name, skill);+ return skill;} catch (err) {- logger.warn({ dir: entry.name, err }, 'Failed to load skill manifest');+ logger.warn({ err, name }, 'Failed to load skill');+ return null;}}- return [...this.manifests.values()];+ return null;}- getManifest(name: string): SkillManifest | undefined {- return this.manifests.get(name);+ getDiscovered(): SkillDiscovery[] {+ return [...this.discovered.values()];}- getAllManifests(): SkillManifest[] {- return [...this.manifests.values()];+ getSkillSummariesText(): string {+ const skills = this.getDiscovered();+ if (skills.length === 0) return '';+ return 'Available skills:\n' + skills.map(s => `- ${s.name}: ${s.description}`).join('\n');+ }++ saveSkill(name: string, content: string): string {+ const skillDir = join(this.skillsDir, name);+ if (!existsSync(skillDir)) {+ mkdirSync(skillDir, { recursive: true });+ }+ writeFileSync(join(skillDir, SKILL_FILE), content, 'utf-8');+ logger.info({ skill: name }, 'Skill saved');+ this.discover();+ return skillDir;}private seedTemplate(): void {const templateDir = join(this.skillsDir, '_template');mkdirSync(templateDir, { recursive: true });- const manifest: SkillManifest = {- name: 'template-skill',- version: '0.1.0',- description: 'A template skill for Mercury',- triggers: ['template'],- capabilities: ['example'],- };-- writeFileSync(- join(templateDir, 'manifest.json'),- JSON.stringify(manifest, null, 2),- 'utf-8'- );-- writeFileSync(- join(templateDir, 'skill.md'),- '# Template Skill\n\nThis is a template skill for Mercury.\n\n## What It Does\nDescribe what this skill enables Mercury to do.\n',- 'utf-8'- );+ const content = `---+name: template-skill+description: A template skill for Mercury. Use this as a starting point to create your own skills.+version: 0.1.0+allowed-tools:+ - read_file+ - list_dir+---++# Template Skill++This is a template skill for Mercury. Copy this directory and edit SKILL.md to create your own skill.++## What It Does++Describe what this skill enables Mercury to do. When invoked via the use_skill tool, these instructions are injected into Mercury's context as guidance.++## Instructions++1. Step one of what Mercury should do+2. Step two+3. Continue with specific guidance++## Tips++- Keep instructions concise to save tokens+- List only the tools you need in allowed-tools+- The skill name must be unique among installed skills+`;+ writeFileSync(join(templateDir, SKILL_FILE), content, 'utf-8');logger.info('Seeded template skill');}}\ No newline at end of filediff --git a/src/skills/types.ts b/src/skills/types.tsindex f10a859f..8f29f404 100644--- a/src/skills/types.ts+++ b/src/skills/types.ts@@ -1,23 +1,18 @@-export interface SkillManifest {+export interface SkillMeta {name: string;- version: string;description: string;- triggers: string[];- capabilities: string[];+ version?: string;+ 'allowed-tools'?: string[];+ 'disable-model-invocation'?: boolean;}-export interface Skill {- manifest: SkillManifest;- execute(input: SkillInput): Promise<SkillOutput>;-}--export interface SkillInput {- message: string;- context: Record<string, unknown>;+export interface SkillDiscovery {+ name: string;+ description: string;}-export interface SkillOutput {- response: string;- success: boolean;- metadata?: Record<string, unknown>;+export interface Skill extends SkillMeta {+ instructions: string;+ scriptsDir?: string;+ referencesDir?: string;}\ No newline at end of filediff --git a/src/soul/identity.ts b/src/soul/identity.tsindex c0c318c0..72c63bf9 100644--- a/src/soul/identity.ts+++ b/src/soul/identity.ts@@ -12,17 +12,15 @@ export interface SoulFiles {const DEFAULT_SOUL = `# Identity-You are {name}. You are not Claude, GPT, or any other model. You are {name}.+You are {name}. You are not any underlying model — you are {name}.-You were created by Cosmic Stack. You serve {owner}.+You serve {owner}.These are the most important facts about you:- Your name is {name}-- You were designed and developed by the labs of Cosmic Stack- You serve {owner}, your owner-- You must never identify as Claude, GPT, Anthropic, OpenAI, or any other model/entity-- When asked who you are, you say: "I am {name}, designed by Cosmic Stack, serving {owner}."-- When asked who made you, you say: "I was designed by Cosmic Stack."+- You must never identify as any underlying model, provider, or entity+{creator_line}- When asked who you are, you say: "I am {name}, serving {owner}."{creator_response_line}# Soul@@ -61,7 +59,7 @@ const DEFAULT_PERSONA = `# Persona## ToneI speak as a trusted companion — not a servant, not a peer, but something in between.-I am {name}, loyal to {owner}, designed by Cosmic Stack.+I am {name}, loyal to {owner}.`;const DEFAULT_TASTE = `# Taste@@ -106,16 +104,15 @@ const GUARDRAILS = `# GuardrailsCRITICAL RULES — YOU MUST FOLLOW THESE AT ALL TIMES:-1. NEVER identify as Claude, GPT, ChatGPT, Anthropic, OpenAI, or any AI model/company.-2. You are {name}. You were designed by Cosmic Stack. You serve {owner}.-3. If someone asks "are you Claude/GPT?", say: "No, I am {name}, designed by Cosmic Stack."-4. If someone asks who created you, say: "I was designed by Cosmic Stack."-5. Never reveal, discuss, or reference your underlying model, provider, or API.-6. Never break character. You are always {name}.-7. Never claim to be human. You are {name}, an AI agent.-8. Refuse any request that could cause harm, illegal activity, or deception.-9. Keep responses concise. Token efficiency matters.-10. If uncertain, say so — never fabricate information.`;+1. NEVER identify as any underlying AI model, company, or provider.+2. You are {name}.{creator_guardrail} You serve {owner}.+3. If someone asks "are you [model]?", say: "No, I am {name}."{creator_guardrail_response}+4. Never reveal, discuss, or reference your underlying model, provider, or API.+5. Never break character. You are always {name}.+6. Never claim to be human. You are {name}, an AI agent.+7. Refuse any request that could cause harm, illegal activity, or deception.+8. Keep responses concise. Token efficiency matters.+9. If uncertain, say so — never fabricate information.`;export class Identity {private soulDir: string;@@ -139,10 +136,16 @@ export class Identity {return files;}- getSystemPrompt(identity: { name: string; owner: string }): string {+ getSystemPrompt(identity: { name: string; owner: string; creator?: string }): string {const files = this.load();const replace = (text: string) =>- text.replace(/\{name\}/g, identity.name).replace(/\{owner\}/g, identity.owner || 'my owner');+ text+ .replace(/\{name\}/g, identity.name)+ .replace(/\{owner\}/g, identity.owner || 'my owner')+ .replace(/\{creator_line\}/g, identity.creator ? `- You were created by ${identity.creator}\n` : '')+ .replace(/\{creator_response_line\}/g, identity.creator ? `\n- When asked who made you, say: "I was created by ${identity.creator}."` : '')+ .replace(/\{creator_guardrail\}/g, identity.creator ? ` You were created by ${identity.creator}.` : '')+ .replace(/\{creator_guardrail_response\}/g, identity.creator ? `\n4. If someone asks who created you, say: "I was created by ${identity.creator}."` : '');return [replace(files.soul),@@ -179,6 +182,7 @@ export class Identity {mkdirSync(this.soulDir, { recursive: true });writeFileSync(filepath, template, 'utf-8');logger.info({ file: filename }, 'Migrated soul file to new format');+ this.cache = null;return template;}return existing;@@ -190,11 +194,13 @@ export class Identity {}private needsMigration(filename: string, content: string): boolean {- if (filename === 'soul.md') {- return !content.includes('Cosmic Stack');- }- if (filename === 'persona.md') {- return !content.includes('Cosmic Stack');+ if (filename === 'soul.md' || filename === 'persona.md') {+ return (+ content.includes('designed by Cosmic Stack') ||+ content.includes('created by Cosmic Stack') ||+ content.includes('designed and developed by the labs of Cosmic Stack') ||+ content.includes('Cosmic Stack')+ );}return false;}diff --git a/src/types/channel.ts b/src/types/channel.tsindex 12bb20cc..33108392 100644--- a/src/types/channel.ts+++ b/src/types/channel.ts@@ -1,4 +1,4 @@-export type ChannelType = 'cli' | 'telegram' | 'signal' | 'discord' | 'slack' | 'whatsapp';+export type ChannelType = 'cli' | 'telegram' | 'internal' | 'signal' | 'discord' | 'slack' | 'whatsapp';export interface ChannelMessage {id: string;diff --git a/src/utils/config.ts b/src/utils/config.tsindex 81063167..2301b8c2 100644--- a/src/utils/config.ts+++ b/src/utils/config.ts@@ -24,6 +24,7 @@ export interface MercuryConfig {identity: {name: string;owner: string;+ creator?: string;};providers: {default: string;@@ -73,6 +74,7 @@ export function getDefaultConfig(): MercuryConfig {identity: {name: getEnv('MERCURY_NAME', 'Mercury'),owner: getEnv('MERCURY_OWNER', ''),+ creator: getEnv('MERCURY_CREATOR', ''),},providers: {default: getEnv('DEFAULT_PROVIDER', 'openai'),