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.

v0.1.0 — fix scheduled task routing, add npm publishing setup

Salman Qureshi0b14788d5ce2
diff --git a/.npmignore b/.npmignore
index 28f58223..4bb93202 100644
--- a/.npmignore
+++ b/.npmignore
@@ -1,3 +1,17 @@
+src/
site/
-*.tsbuildinfo
-.DS_Store
\ No newline at end of file
+scripts/
+*.ts
+!dist/*.ts
+tsconfig.json
+tsup.config.ts
+vitest.config.*
+.github/
+ARCHITECTURE.md
+DECISIONS.md
+RESEARCH.md
+.env
+.env.example
+*.log
+.DS_Store
+*.tsbuildinfo
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 00000000..e34e03fd
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,9 @@
+MIT License
+
+Copyright © 2026 Cosmic Stack
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
diff --git a/README.md b/README.md
new file mode 100644
index 00000000..f4902769
--- /dev/null
+++ b/README.md
@@ -0,0 +1,110 @@
+<h1 align="center">
+ <pre>
+ __ _____________ ________ ________ __
+ / |/ / ____/ __ \/ ____/ / / / __ \ \/ /
+ / /|_/ / __/ / /_/ / / / / / / /_/ /\ /
+/ / / / /___/ _, _/ /___/ /_/ / _, _/ / /
+/_/ /_/_____/_/ |_|\____/\____/_/ |_| /_/
+ </pre>
+</h1>
+
+<p align="center">
+ <strong>Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access.</strong>
+</p>
+
+<p align="center">
+ Runs 24/7 from CLI or Telegram. 21 built-in tools. Extensible skills. Asks before it acts.
+</p>
+
+<p align="center">
+ <a href="https://www.npmjs.com/package/@cosmicstack/mercury-agent"><img src="https://img.shields.io/npm/v/@cosmicstack/mercury-agent" alt="npm"></a>
+ <a href="https://github.com/cosmicstack-labs/mercury-agent"><img src="https://img.shields.io/github/license/cosmicstack-labs/mercury-agent" alt="license"></a>
+ <a href="https://nodejs.org/"><img src="https://img.shields.io/node/v/@cosmicstack/mercury-agent" alt="node"></a>
+</p>
+
+---
+
+## Quick Start
+
+```bash
+npx @cosmicstack/mercury-agent
+```
+
+Or install globally:
+
+```bash
+npm i -g @cosmicstack/mercury-agent
+mercury
+```
+
+First run triggers the setup wizard — enter your name, an API key, and optionally a Telegram bot token. Takes 30 seconds.
+
+## Why Mercury?
+
+Every AI agent can read files, run commands, and fetch URLs. Most do it silently. **Mercury asks first.**
+
+- **Permission-hardened** — Shell blocklist (`sudo`, `rm -rf /`, etc. never execute). Folder-level read/write scoping. Pending approval flow. Skill elevation with granular `allowed-tools`. No surprises.
+- **Soul-driven** — Personality defined by markdown files you own (`soul.md`, `persona.md`, `taste.md`, `heartbeat.md`). No corporate wrapper.
+- **Token-aware** — Daily budget enforcement. Auto-concise when over 70%. `/budget` command to check, reset, or override.
+- **Multi-channel** — CLI with real-time streaming. Telegram with HTML formatting, file uploads, and typing indicators.
+- **Always on** — Cron scheduling, delayed reminders, heartbeat monitoring, and proactive notifications.
+- **Extensible** — Install community skills with a single command. Schedule skills as recurring tasks. Based on the [Agent Skills](https://agentskills.io) specification.
+
+## Built-in Tools
+
+| Category | Tools |
+|----------|-------|
+| **Filesystem** | `read_file`, `write_file`, `create_file`, `edit_file`, `list_dir`, `delete_file`, `send_file` |
+| **Shell** | `run_command`, `approve_command` |
+| **Git** | `git_status`, `git_diff`, `git_log`, `git_add`, `git_commit`, `git_push` |
+| **Web** | `fetch_url` |
+| **Skills** | `install_skill`, `list_skills`, `use_skill` |
+| **Scheduler** | `schedule_task`, `list_scheduled_tasks`, `cancel_scheduled_task` |
+| **System** | `budget_status` |
+
+## Channels
+
+| Channel | Features |
+|---------|----------|
+| **CLI** | Readline prompt, real-time text streaming, markdown rendering, file display |
+| **Telegram** | HTML formatting, file uploads (photos, audio, video, documents), typing indicators, `/budget` commands |
+
+## Scheduler
+
+- **Recurring**: `schedule_task` with cron expressions (`0 9 * * *` for daily at 9am)
+- **One-shot**: `schedule_task` with `delay_seconds` (e.g. 15 seconds)
+- Tasks persist to `~/.mercury/schedules.yaml` and restore on restart
+- Responses route back to the channel where the task was created
+
+## Configuration
+
+All runtime data lives in `~/.mercury/` — not in your project directory.
+
+| Path | Purpose |
+|------|---------|
+| `~/.mercury/mercury.yaml` | Main config (providers, channels, budget) |
+| `~/.mercury/soul/*.md` | Agent personality (soul, persona, taste, heartbeat) |
+| `~/.mercury/permissions.yaml` | Capabilities and approval rules |
+| `~/.mercury/skills/` | Installed skills |
+| `~/.mercury/schedules.yaml` | Scheduled tasks |
+| `~/.mercury/token-usage.json` | Daily token usage tracking |
+| `~/.mercury/memory/` | Short-term, long-term, episodic memory |
+
+## Provider Fallback
+
+Configure multiple LLM providers. Mercury tries them in order and falls back automatically:
+
+- **DeepSeek** — default, cost-effective
+- **OpenAI** — GPT-4o-mini and others
+- **Anthropic** — Claude and others
+
+## Architecture
+
+- **TypeScript + Node.js 20+** — ESM, tsup build, zero native dependencies
+- **Vercel AI SDK v4** — `generateText` + `streamText`, 10-step agentic loop, provider fallback
+- **grammY** — Telegram bot with typing indicators and file uploads
+- **Flat-file persistence** — No database. YAML + JSON in `~/.mercury/`
+
+## License
+
+MIT © [Cosmic Stack](https://github.com/cosmicstack-labs)
\ No newline at end of file
diff --git a/package.json b/package.json
index 164460ab..2e87aa55 100644
--- a/package.json
+++ b/package.json
@@ -1,7 +1,7 @@
{
- "name": "mercury",
+ "name": "@cosmicstack/mercury-agent",
"version": "0.1.0",
- "description": "Mercury — an AI agent for personal tasks. Soul-driven, token-efficient, always on.",
+ "description": "Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",
"type": "module",
"main": "dist/index.js",
"bin": {
@@ -14,16 +14,45 @@
"lint": "tsc --noEmit",
"typecheck": "tsc --noEmit",
"test": "vitest run",
- "test:watch": "vitest"
+ "test:watch": "vitest",
+ "prepublishOnly": "npm run build"
},
"keywords": [
"ai",
"agent",
+ "ai-agent",
"cli",
"telegram",
- "personal-assistant"
+ "telegram-bot",
+ "personal-assistant",
+ "soul-driven",
+ "token-budget",
+ "permissions",
+ "scheduler",
+ "cron",
+ "skill-system",
+ "deepseek",
+ "openai",
+ "anthropic",
+ "llm"
],
+ "author": "Cosmic Stack",
"license": "MIT",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/cosmicstack-labs/mercury-agent.git"
+ },
+ "homepage": "https://mercury.cosmicstack.org",
+ "bugs": {
+ "url": "https://github.com/cosmicstack-labs/mercury-agent/issues"
+ },
+ "publishConfig": {
+ "access": "public",
+ "registry": "https://registry.npmjs.org/"
+ },
+ "files": [
+ "dist"
+ ],
"dependencies": {
"@ai-sdk/anthropic": "^1.2.0",
"@ai-sdk/openai": "^1.3.0",
@@ -55,4 +84,4 @@
"engines": {
"node": ">=20.0.0"
}
-}
+}
\ No newline at end of file
diff --git a/scripts/publish.sh b/scripts/publish.sh
new file mode 100755
index 00000000..497653b4
--- /dev/null
+++ b/scripts/publish.sh
@@ -0,0 +1,36 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+echo "☿ Mercury Agent — Publish"
+echo "────────────────────────────"
+
+PKG_NAME=$(node -p "require('./package.json').name")
+PKG_VERSION=$(node -p "require('./package.json').version")
+
+echo "Package: ${PKG_NAME}"
+echo "Version: ${PKG_VERSION}"
+echo ""
+
+echo "1/5 Type checking..."
+npm run typecheck
+
+echo "2/5 Building..."
+npm run build
+
+echo "3/5 Verifying package contents..."
+npm pack --dry-run 2>&1 | head -20
+
+echo ""
+echo "4/5 Verifying shebang..."
+head -1 dist/index.js
+
+echo ""
+echo "5/5 Publishing to npm..."
+npm publish --access public
+
+echo ""
+echo "✓ Published ${PKG_NAME}@${PKG_VERSION}"
+
+echo "Tagging git..."
+git tag -a "v${PKG_VERSION}" -m "v${PKG_VERSION}"
+echo "Done. Push with: git push origin main --tags"
\ No newline at end of file
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index cd55d355..11b0d4d2 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -35,6 +35,8 @@ export class CapabilityRegistry {
private scheduler?: Scheduler;
private tokenBudget?: TokenBudget;
private sendFileHandler?: (filePath: string) => Promise<void>;
+ private currentChannelId = 'cli';
+ private currentChannelType = 'cli';
constructor(skillLoader?: SkillLoader, scheduler?: Scheduler, tokenBudget?: TokenBudget) {
this.permissions = new PermissionManager();
@@ -43,6 +45,15 @@ export class CapabilityRegistry {
this.tokenBudget = tokenBudget;
}
+ setChannelContext(channelId: string, channelType: string): void {
+ this.currentChannelId = channelId;
+ this.currentChannelType = channelType;
+ }
+
+ getChannelContext(): { channelId: string; channelType: string } {
+ return { channelId: this.currentChannelId, channelType: this.currentChannelType };
+ }
+
setSendFileHandler(handler: (filePath: string) => Promise<void>): void {
this.sendFileHandler = handler;
}
@@ -79,7 +90,7 @@ export class CapabilityRegistry {
}
if (this.scheduler) {
- this.tools.schedule_task = createScheduleTaskTool(this.scheduler);
+ this.tools.schedule_task = createScheduleTaskTool(this.scheduler, () => this.getChannelContext());
this.tools.list_scheduled_tasks = createListTasksTool(this.scheduler);
this.tools.cancel_scheduled_task = createCancelTaskTool(this.scheduler);
logger.info('Scheduler tools registered');
diff --git a/src/capabilities/scheduler/schedule-task.ts b/src/capabilities/scheduler/schedule-task.ts
index e65be566..f16add3f 100644
--- a/src/capabilities/scheduler/schedule-task.ts
+++ b/src/capabilities/scheduler/schedule-task.ts
@@ -3,7 +3,7 @@ import { z } from 'zod';
import cron from 'node-cron';
import type { Scheduler, ScheduledTaskManifest } from '../../core/scheduler.js';
-export function createScheduleTaskTool(scheduler: Scheduler) {
+export function createScheduleTaskTool(scheduler: Scheduler, getContext: () => { channelId: string; channelType: string }) {
return tool({
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({
@@ -26,6 +26,7 @@ export function createScheduleTaskTool(scheduler: Scheduler) {
}
const id = `task-${Date.now().toString(36)}`;
+ const ctx = getContext();
if (delay_seconds) {
const manifest: ScheduledTaskManifest = {
@@ -36,6 +37,8 @@ export function createScheduleTaskTool(scheduler: Scheduler) {
delaySeconds: delay_seconds,
executeAt: new Date(Date.now() + delay_seconds * 1000).toISOString(),
createdAt: new Date().toISOString(),
+ sourceChannelId: ctx.channelId,
+ sourceChannelType: ctx.channelType,
};
scheduler.addDelayedTask(manifest);
@@ -56,6 +59,8 @@ export function createScheduleTaskTool(scheduler: Scheduler) {
prompt,
skillName: skill_name,
createdAt: new Date().toISOString(),
+ sourceChannelId: ctx.channelId,
+ sourceChannelType: ctx.channelType,
};
scheduler.addPersistedTask(manifest);
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 6fc11503..dc4603e0 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -1,5 +1,5 @@
import { generateText, streamText } from 'ai';
-import type { ChannelMessage } from '../types/channel.js';
+import type { ChannelMessage, ChannelType } from '../types/channel.js';
import type { ProviderRegistry } from '../providers/registry.js';
import type { Identity } from '../soul/identity.js';
import type { ShortTermMemory, LongTermMemory, EpisodicMemory } from '../memory/store.js';
@@ -103,10 +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);
- }
+ const isInternal = msg.channelType === 'internal';
+ const isScheduled = msg.senderId === 'system' && msg.channelType !== 'internal';
+ if (isInternal || isScheduled) {
+ this.capabilities.permissions.setAutoApproveAll(true);
+ }
try {
const trimmed = msg.content.trim();
@@ -170,6 +171,8 @@ export class Agent {
await channel.typing(msg.channelId).catch(() => {});
}
+ this.capabilities.setChannelContext(msg.channelId, msg.channelType);
+
const fallbackIterator = this.providers.getFallbackIterator();
let result: any = null;
let usedProvider: { name: string; model: string } | null = null;
@@ -302,7 +305,7 @@ export class Agent {
logger.error({ err }, 'Error handling message');
this.lifecycle.transition('idle');
} finally {
- if (isInternal) {
+ if (isInternal || isScheduled) {
this.capabilities.permissions.setAutoApproveAll(false);
}
this.capabilities.permissions.clearElevation();
@@ -323,11 +326,11 @@ export class Agent {
return prompt;
}
- async processInternalPrompt(prompt: string, channelId?: string): Promise<void> {
+ async processInternalPrompt(prompt: string, channelId?: string, channelType?: string): Promise<void> {
const syntheticMsg: ChannelMessage = {
id: `internal-${Date.now().toString(36)}`,
channelId: channelId || 'internal',
- channelType: 'internal',
+ channelType: (channelType || 'internal') as ChannelType,
senderId: 'system',
content: prompt,
timestamp: Date.now(),
@@ -336,7 +339,7 @@ export class Agent {
}
private async handleScheduledTask(manifest: ScheduledTaskManifest): Promise<void> {
- logger.info({ task: manifest.id }, 'Processing scheduled task');
+ logger.info({ task: manifest.id, channel: manifest.sourceChannelType }, 'Processing scheduled task');
try {
let prompt = manifest.prompt || '';
if (manifest.skillName) {
@@ -346,7 +349,7 @@ export class Agent {
if (!prompt) {
prompt = `Execute scheduled task: ${manifest.description}`;
}
- await this.processInternalPrompt(prompt);
+ await this.processInternalPrompt(prompt, manifest.sourceChannelId, manifest.sourceChannelType);
} catch (err) {
logger.error({ err, task: manifest.id }, 'Scheduled task execution failed');
}
diff --git a/src/core/scheduler.ts b/src/core/scheduler.ts
index 9d1519b9..1dc3f7cb 100644
--- a/src/core/scheduler.ts
+++ b/src/core/scheduler.ts
@@ -22,6 +22,8 @@ export interface ScheduledTaskManifest {
delaySeconds?: number;
executeAt?: string;
createdAt: string;
+ sourceChannelId?: string;
+ sourceChannelType?: string;
}
const SCHEDULES_FILE = 'schedules.yaml';
diff --git a/tsup.config.ts b/tsup.config.ts
index 76762a64..ea2c5d7e 100644
--- a/tsup.config.ts
+++ b/tsup.config.ts
@@ -9,7 +9,7 @@ export default defineConfig({
splitting: false,
sourcemap: true,
minify: false,
- banner: {},
+ banner: { js: "#!/usr/bin/env node" },
external: [
"react",
"ink",